Create/update scheduled transactions.
This commit is contained in:
+2
-2
@@ -1,6 +1,6 @@
|
|||||||
services:
|
services:
|
||||||
postgres:
|
postgres:
|
||||||
image: postgres:17-alpine
|
image: postgres:18-alpine
|
||||||
environment:
|
environment:
|
||||||
POSTGRES_DB: expenses
|
POSTGRES_DB: expenses
|
||||||
POSTGRES_USER: expenses
|
POSTGRES_USER: expenses
|
||||||
@@ -13,7 +13,7 @@ services:
|
|||||||
timeout: 5s
|
timeout: 5s
|
||||||
retries: 5
|
retries: 5
|
||||||
volumes:
|
volumes:
|
||||||
- postgres-data:/var/lib/postgresql/data
|
- postgres-data:/var/lib/postgresql
|
||||||
|
|
||||||
volumes:
|
volumes:
|
||||||
postgres-data:
|
postgres-data:
|
||||||
+84
@@ -0,0 +1,84 @@
|
|||||||
|
{
|
||||||
|
"db_name": "PostgreSQL",
|
||||||
|
"query": "\n INSERT INTO recurring_transactions (\n id,\n name,\n amount_cents,\n direction,\n starts_at,\n ends_at,\n recurrence_every,\n recurrence_unit,\n weekend_adjustment\n )\n VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)\n ON CONFLICT (id) DO UPDATE SET\n name = EXCLUDED.name,\n amount_cents = EXCLUDED.amount_cents,\n direction = EXCLUDED.direction,\n starts_at = EXCLUDED.starts_at,\n ends_at = EXCLUDED.ends_at,\n recurrence_every = EXCLUDED.recurrence_every,\n recurrence_unit = EXCLUDED.recurrence_unit,\n weekend_adjustment = EXCLUDED.weekend_adjustment\n RETURNING WITH (OLD AS old_row, NEW AS new_row)\n old_row.id AS \"old_id?\",\n new_row.id AS \"id!\",\n new_row.name AS \"name!\",\n new_row.amount_cents AS \"amount_cents!\",\n new_row.direction AS \"direction!\",\n new_row.starts_at AS \"starts_at!\",\n new_row.ends_at AS \"ends_at?\",\n new_row.recurrence_every AS \"recurrence_every!\",\n new_row.recurrence_unit AS \"recurrence_unit!\",\n new_row.weekend_adjustment AS \"weekend_adjustment?\"\n ",
|
||||||
|
"describe": {
|
||||||
|
"columns": [
|
||||||
|
{
|
||||||
|
"ordinal": 0,
|
||||||
|
"name": "old_id?",
|
||||||
|
"type_info": "Uuid"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"ordinal": 1,
|
||||||
|
"name": "id!",
|
||||||
|
"type_info": "Uuid"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"ordinal": 2,
|
||||||
|
"name": "name!",
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"ordinal": 3,
|
||||||
|
"name": "amount_cents!",
|
||||||
|
"type_info": "Int8"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"ordinal": 4,
|
||||||
|
"name": "direction!",
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"ordinal": 5,
|
||||||
|
"name": "starts_at!",
|
||||||
|
"type_info": "Timestamptz"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"ordinal": 6,
|
||||||
|
"name": "ends_at?",
|
||||||
|
"type_info": "Timestamptz"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"ordinal": 7,
|
||||||
|
"name": "recurrence_every!",
|
||||||
|
"type_info": "Int4"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"ordinal": 8,
|
||||||
|
"name": "recurrence_unit!",
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"ordinal": 9,
|
||||||
|
"name": "weekend_adjustment?",
|
||||||
|
"type_info": "Text"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"parameters": {
|
||||||
|
"Left": [
|
||||||
|
"Uuid",
|
||||||
|
"Text",
|
||||||
|
"Int8",
|
||||||
|
"Text",
|
||||||
|
"Timestamptz",
|
||||||
|
"Timestamptz",
|
||||||
|
"Int4",
|
||||||
|
"Text",
|
||||||
|
"Text"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"nullable": [
|
||||||
|
false,
|
||||||
|
false,
|
||||||
|
false,
|
||||||
|
false,
|
||||||
|
false,
|
||||||
|
false,
|
||||||
|
true,
|
||||||
|
false,
|
||||||
|
false,
|
||||||
|
true
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"hash": "0670f762b989960690b3975bf3f9b03ecc2c407701f1952f4b4e40fc9d6e12d1"
|
||||||
|
}
|
||||||
+20
-7
@@ -3,16 +3,20 @@ use axum::{
|
|||||||
response::{IntoResponse, Response},
|
response::{IntoResponse, Response},
|
||||||
};
|
};
|
||||||
|
|
||||||
use crate::routes::dtos::{
|
use crate::routes::{
|
||||||
|
dtos::{
|
||||||
|
direction::DirectionConversionError,
|
||||||
scheduled_transaction::RecurringTransactionConversionError,
|
scheduled_transaction::RecurringTransactionConversionError,
|
||||||
transaction_direction::TransactionDirectionConversionError,
|
},
|
||||||
|
validation::scheduled_transaction::ScheduledTransactionValidationError,
|
||||||
};
|
};
|
||||||
|
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
pub enum AppError {
|
pub enum AppError {
|
||||||
Database(sqlx::Error),
|
Database(sqlx::Error),
|
||||||
TransactionDirection(TransactionDirectionConversionError),
|
Direction(DirectionConversionError),
|
||||||
RecurringTransaction(RecurringTransactionConversionError),
|
RecurringTransaction(RecurringTransactionConversionError),
|
||||||
|
ScheduledTransactionValidation(ScheduledTransactionValidationError),
|
||||||
}
|
}
|
||||||
|
|
||||||
impl From<sqlx::Error> for AppError {
|
impl From<sqlx::Error> for AppError {
|
||||||
@@ -21,9 +25,9 @@ impl From<sqlx::Error> for AppError {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl From<TransactionDirectionConversionError> for AppError {
|
impl From<DirectionConversionError> for AppError {
|
||||||
fn from(error: TransactionDirectionConversionError) -> Self {
|
fn from(error: DirectionConversionError) -> Self {
|
||||||
Self::TransactionDirection(error)
|
Self::Direction(error)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -33,11 +37,20 @@ impl From<RecurringTransactionConversionError> for AppError {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl From<ScheduledTransactionValidationError> for AppError {
|
||||||
|
fn from(error: ScheduledTransactionValidationError) -> Self {
|
||||||
|
Self::ScheduledTransactionValidation(error)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
impl IntoResponse for AppError {
|
impl IntoResponse for AppError {
|
||||||
fn into_response(self) -> Response {
|
fn into_response(self) -> Response {
|
||||||
match self {
|
match self {
|
||||||
|
Self::ScheduledTransactionValidation(error) => {
|
||||||
|
return (StatusCode::UNPROCESSABLE_ENTITY, error.to_string()).into_response();
|
||||||
|
}
|
||||||
Self::Database(error) => tracing::error!(%error, "Database query failed"),
|
Self::Database(error) => tracing::error!(%error, "Database query failed"),
|
||||||
Self::TransactionDirection(error) => {
|
Self::Direction(error) => {
|
||||||
tracing::error!(%error, "Invalid transaction direction")
|
tracing::error!(%error, "Invalid transaction direction")
|
||||||
}
|
}
|
||||||
Self::RecurringTransaction(error) => {
|
Self::RecurringTransaction(error) => {
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
pub mod dtos;
|
pub mod dtos;
|
||||||
mod scheduled_transactions;
|
mod scheduled_transactions;
|
||||||
mod transactions;
|
mod transactions;
|
||||||
|
pub mod validation;
|
||||||
|
|
||||||
pub fn create_router(pool: sqlx::PgPool) -> axum::Router {
|
pub fn create_router(pool: sqlx::PgPool) -> axum::Router {
|
||||||
axum::Router::new()
|
axum::Router::new()
|
||||||
|
|||||||
@@ -1,3 +1,3 @@
|
|||||||
|
pub mod direction;
|
||||||
pub mod scheduled_transaction;
|
pub mod scheduled_transaction;
|
||||||
pub mod transaction;
|
pub mod transaction;
|
||||||
pub mod transaction_direction;
|
|
||||||
|
|||||||
+21
-12
@@ -2,30 +2,39 @@ use serde::{Deserialize, Serialize};
|
|||||||
|
|
||||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
#[serde(rename_all = "snake_case")]
|
#[serde(rename_all = "snake_case")]
|
||||||
pub enum TransactionDirection {
|
pub enum Direction {
|
||||||
In,
|
In,
|
||||||
Out,
|
Out,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug)]
|
impl Direction {
|
||||||
pub struct TransactionDirectionConversionError(pub String);
|
pub fn as_str(&self) -> &'static str {
|
||||||
|
match self {
|
||||||
impl std::fmt::Display for TransactionDirectionConversionError {
|
Self::In => "in",
|
||||||
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
Self::Out => "out",
|
||||||
write!(formatter, "invalid direction value: {}", self.0)
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl std::error::Error for TransactionDirectionConversionError {}
|
impl TryFrom<String> for Direction {
|
||||||
|
type Error = DirectionConversionError;
|
||||||
impl TryFrom<String> for TransactionDirection {
|
|
||||||
type Error = TransactionDirectionConversionError;
|
|
||||||
|
|
||||||
fn try_from(value: String) -> Result<Self, Self::Error> {
|
fn try_from(value: String) -> Result<Self, Self::Error> {
|
||||||
match value.as_str() {
|
match value.as_str() {
|
||||||
"in" => Ok(Self::In),
|
"in" => Ok(Self::In),
|
||||||
"out" => Ok(Self::Out),
|
"out" => Ok(Self::Out),
|
||||||
_ => Err(TransactionDirectionConversionError(value)),
|
_ => Err(DirectionConversionError(value)),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub struct DirectionConversionError(pub String);
|
||||||
|
|
||||||
|
impl std::error::Error for DirectionConversionError {}
|
||||||
|
|
||||||
|
impl std::fmt::Display for DirectionConversionError {
|
||||||
|
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||||
|
write!(formatter, "invalid direction value: {}", self.0)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -4,9 +4,7 @@ use uuid::Uuid;
|
|||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
database::dtos::scheduled_transaction::RecurringTransactionRow,
|
database::dtos::scheduled_transaction::RecurringTransactionRow,
|
||||||
routes::dtos::transaction_direction::{
|
routes::dtos::direction::{Direction, DirectionConversionError},
|
||||||
TransactionDirection, TransactionDirectionConversionError,
|
|
||||||
},
|
|
||||||
};
|
};
|
||||||
|
|
||||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
@@ -16,12 +14,60 @@ pub enum ScheduledTransaction {
|
|||||||
Recurring(RecurringTransaction),
|
Recurring(RecurringTransaction),
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl From<RecurringTransaction> for ScheduledTransaction {
|
||||||
|
fn from(transaction: RecurringTransaction) -> Self {
|
||||||
|
Self::Recurring(transaction)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
pub struct RecurringTransaction {
|
pub struct RecurringTransaction {
|
||||||
pub id: Uuid,
|
pub id: Uuid,
|
||||||
|
|
||||||
|
#[serde(flatten)]
|
||||||
|
pub data: RecurringTransactionData,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl TryFrom<RecurringTransactionRow> for RecurringTransaction {
|
||||||
|
type Error = RecurringTransactionConversionError;
|
||||||
|
|
||||||
|
fn try_from(row: RecurringTransactionRow) -> Result<Self, Self::Error> {
|
||||||
|
Ok(Self {
|
||||||
|
id: row.id,
|
||||||
|
data: RecurringTransactionData {
|
||||||
|
name: row.name,
|
||||||
|
amount: row.amount_cents as f64 / 100.0,
|
||||||
|
direction: Direction::try_from(row.direction)
|
||||||
|
.map_err(RecurringTransactionConversionError::Direction)?,
|
||||||
|
start: row.starts_at,
|
||||||
|
end: row.ends_at,
|
||||||
|
recurrence: Recurrence {
|
||||||
|
every: row.recurrence_every.try_into().map_err(|_| {
|
||||||
|
RecurringTransactionConversionError::RecurrenceEvery(row.recurrence_every)
|
||||||
|
})?,
|
||||||
|
unit: RecurrenceUnit::try_from(row.recurrence_unit)?,
|
||||||
|
weekend_adjustment: match row.weekend_adjustment {
|
||||||
|
Some(value) => Some(WeekendAdjustment::try_from(value)?),
|
||||||
|
None => None,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Deserialize)]
|
||||||
|
#[serde(rename_all = "snake_case")]
|
||||||
|
#[serde(tag = "type")]
|
||||||
|
pub enum ScheduledTransactionData {
|
||||||
|
Recurring(RecurringTransactionData),
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
|
pub struct RecurringTransactionData {
|
||||||
pub name: String,
|
pub name: String,
|
||||||
pub amount: f64,
|
pub amount: f64,
|
||||||
pub direction: TransactionDirection,
|
pub direction: Direction,
|
||||||
pub start: DateTime<Utc>,
|
pub start: DateTime<Utc>,
|
||||||
pub end: Option<DateTime<Utc>>,
|
pub end: Option<DateTime<Utc>>,
|
||||||
pub recurrence: Recurrence,
|
pub recurrence: Recurrence,
|
||||||
@@ -43,6 +89,31 @@ pub enum RecurrenceUnit {
|
|||||||
Year,
|
Year,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl RecurrenceUnit {
|
||||||
|
pub fn as_str(&self) -> &'static str {
|
||||||
|
match self {
|
||||||
|
Self::Day => "day",
|
||||||
|
Self::Week => "week",
|
||||||
|
Self::Month => "month",
|
||||||
|
Self::Year => "year",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl TryFrom<String> for RecurrenceUnit {
|
||||||
|
type Error = RecurringTransactionConversionError;
|
||||||
|
|
||||||
|
fn try_from(value: String) -> Result<Self, Self::Error> {
|
||||||
|
match value.as_str() {
|
||||||
|
"day" => Ok(Self::Day),
|
||||||
|
"week" => Ok(Self::Week),
|
||||||
|
"month" => Ok(Self::Month),
|
||||||
|
"year" => Ok(Self::Year),
|
||||||
|
_ => Err(RecurringTransactionConversionError::RecurrenceUnit(value)),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
#[serde(rename_all = "snake_case")]
|
#[serde(rename_all = "snake_case")]
|
||||||
pub enum WeekendAdjustment {
|
pub enum WeekendAdjustment {
|
||||||
@@ -50,19 +121,38 @@ pub enum WeekendAdjustment {
|
|||||||
NextBusinessDay,
|
NextBusinessDay,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl WeekendAdjustment {
|
||||||
|
pub fn as_str(&self) -> &'static str {
|
||||||
|
match self {
|
||||||
|
Self::PreviousBusinessDay => "previous_business_day",
|
||||||
|
Self::NextBusinessDay => "next_business_day",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl TryFrom<String> for WeekendAdjustment {
|
||||||
|
type Error = RecurringTransactionConversionError;
|
||||||
|
|
||||||
|
fn try_from(value: String) -> Result<Self, Self::Error> {
|
||||||
|
match value.as_str() {
|
||||||
|
"previous_business_day" => Ok(Self::PreviousBusinessDay),
|
||||||
|
"next_business_day" => Ok(Self::NextBusinessDay),
|
||||||
|
_ => Err(RecurringTransactionConversionError::WeekendAdjustment(
|
||||||
|
value,
|
||||||
|
)),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
pub enum RecurringTransactionConversionError {
|
pub enum RecurringTransactionConversionError {
|
||||||
Direction(TransactionDirectionConversionError),
|
Direction(DirectionConversionError),
|
||||||
RecurrenceEvery(i32),
|
RecurrenceEvery(i32),
|
||||||
RecurrenceUnit(String),
|
RecurrenceUnit(String),
|
||||||
WeekendAdjustment(String),
|
WeekendAdjustment(String),
|
||||||
}
|
}
|
||||||
|
|
||||||
impl From<RecurringTransaction> for ScheduledTransaction {
|
impl std::error::Error for RecurringTransactionConversionError {}
|
||||||
fn from(transaction: RecurringTransaction) -> Self {
|
|
||||||
Self::Recurring(transaction)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl std::fmt::Display for RecurringTransactionConversionError {
|
impl std::fmt::Display for RecurringTransactionConversionError {
|
||||||
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||||
@@ -81,58 +171,47 @@ impl std::fmt::Display for RecurringTransactionConversionError {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl std::error::Error for RecurringTransactionConversionError {}
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use chrono::{TimeZone, Utc};
|
||||||
|
use uuid::Uuid;
|
||||||
|
|
||||||
impl TryFrom<RecurringTransactionRow> for RecurringTransaction {
|
use super::{
|
||||||
type Error = RecurringTransactionConversionError;
|
Recurrence, RecurrenceUnit, RecurringTransaction, RecurringTransactionData,
|
||||||
|
ScheduledTransaction, ScheduledTransactionData, WeekendAdjustment,
|
||||||
|
};
|
||||||
|
use crate::routes::dtos::direction::Direction;
|
||||||
|
|
||||||
fn try_from(row: RecurringTransactionRow) -> Result<Self, Self::Error> {
|
fn transaction(amount: f64) -> RecurringTransactionData {
|
||||||
Ok(Self {
|
RecurringTransactionData {
|
||||||
id: row.id,
|
name: String::new(),
|
||||||
name: row.name,
|
amount,
|
||||||
amount: row.amount_cents as f64 / 100.0,
|
direction: Direction::Out,
|
||||||
direction: TransactionDirection::try_from(row.direction)
|
start: Utc.with_ymd_and_hms(2026, 9, 24, 12, 0, 0).unwrap(),
|
||||||
.map_err(RecurringTransactionConversionError::Direction)?,
|
end: None,
|
||||||
start: row.starts_at,
|
|
||||||
end: row.ends_at,
|
|
||||||
recurrence: Recurrence {
|
recurrence: Recurrence {
|
||||||
every: row.recurrence_every.try_into().map_err(|_| {
|
every: 2,
|
||||||
RecurringTransactionConversionError::RecurrenceEvery(row.recurrence_every)
|
unit: RecurrenceUnit::Month,
|
||||||
})?,
|
weekend_adjustment: Some(WeekendAdjustment::NextBusinessDay),
|
||||||
unit: RecurrenceUnit::try_from(row.recurrence_unit)?,
|
|
||||||
weekend_adjustment: match row.weekend_adjustment {
|
|
||||||
Some(value) => Some(WeekendAdjustment::try_from(value)?),
|
|
||||||
None => None,
|
|
||||||
},
|
},
|
||||||
},
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl TryFrom<String> for RecurrenceUnit {
|
#[test]
|
||||||
type Error = RecurringTransactionConversionError;
|
fn keeps_scheduled_transaction_json_flat() {
|
||||||
|
let response = ScheduledTransaction::Recurring(RecurringTransaction {
|
||||||
|
id: Uuid::nil(),
|
||||||
|
data: transaction(12.34),
|
||||||
|
});
|
||||||
|
let response = serde_json::to_value(response).unwrap();
|
||||||
|
assert_eq!(response["type"], "recurring");
|
||||||
|
assert_eq!(response["id"], Uuid::nil().to_string());
|
||||||
|
assert_eq!(response["amount"], 12.34);
|
||||||
|
assert!(response.get("data").is_none());
|
||||||
|
|
||||||
fn try_from(value: String) -> Result<Self, Self::Error> {
|
let request: ScheduledTransactionData = serde_json::from_value(response).unwrap();
|
||||||
match value.as_str() {
|
let ScheduledTransactionData::Recurring(data) = request;
|
||||||
"day" => Ok(Self::Day),
|
assert_eq!(data.amount, 12.34);
|
||||||
"week" => Ok(Self::Week),
|
assert_eq!(data.recurrence.every, 2);
|
||||||
"month" => Ok(Self::Month),
|
|
||||||
"year" => Ok(Self::Year),
|
|
||||||
_ => Err(RecurringTransactionConversionError::RecurrenceUnit(value)),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl TryFrom<String> for WeekendAdjustment {
|
|
||||||
type Error = RecurringTransactionConversionError;
|
|
||||||
|
|
||||||
fn try_from(value: String) -> Result<Self, Self::Error> {
|
|
||||||
match value.as_str() {
|
|
||||||
"previous_business_day" => Ok(Self::PreviousBusinessDay),
|
|
||||||
"next_business_day" => Ok(Self::NextBusinessDay),
|
|
||||||
_ => Err(RecurringTransactionConversionError::WeekendAdjustment(
|
|
||||||
value,
|
|
||||||
)),
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,28 +3,26 @@ use serde::Serialize;
|
|||||||
use uuid::Uuid;
|
use uuid::Uuid;
|
||||||
|
|
||||||
use crate::database::dtos::transaction::TransactionRow;
|
use crate::database::dtos::transaction::TransactionRow;
|
||||||
use crate::routes::dtos::transaction_direction::{
|
use crate::routes::dtos::direction::{Direction, DirectionConversionError};
|
||||||
TransactionDirection, TransactionDirectionConversionError,
|
|
||||||
};
|
|
||||||
|
|
||||||
#[derive(Serialize)]
|
#[derive(Serialize)]
|
||||||
pub struct TransactionResponse {
|
pub struct TransactionResponse {
|
||||||
pub id: Uuid,
|
pub id: Uuid,
|
||||||
pub description: String,
|
pub description: String,
|
||||||
pub amount: f64,
|
pub amount: f64,
|
||||||
pub direction: TransactionDirection,
|
pub direction: Direction,
|
||||||
pub date: DateTime<Utc>,
|
pub date: DateTime<Utc>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl TryFrom<TransactionRow> for TransactionResponse {
|
impl TryFrom<TransactionRow> for TransactionResponse {
|
||||||
type Error = TransactionDirectionConversionError;
|
type Error = DirectionConversionError;
|
||||||
|
|
||||||
fn try_from(row: TransactionRow) -> Result<Self, Self::Error> {
|
fn try_from(row: TransactionRow) -> Result<Self, Self::Error> {
|
||||||
Ok(Self {
|
Ok(Self {
|
||||||
id: row.id,
|
id: row.id,
|
||||||
description: row.description,
|
description: row.description,
|
||||||
amount: row.amount_cents as f64 / 100.0,
|
amount: row.amount_cents as f64 / 100.0,
|
||||||
direction: TransactionDirection::try_from(row.direction)?,
|
direction: Direction::try_from(row.direction)?,
|
||||||
date: row.date,
|
date: row.date,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,14 +1,24 @@
|
|||||||
use axum::{Json, extract::State};
|
use axum::{
|
||||||
|
Json,
|
||||||
|
extract::{Path, State},
|
||||||
|
http::StatusCode,
|
||||||
|
};
|
||||||
use sqlx::PgPool;
|
use sqlx::PgPool;
|
||||||
|
use uuid::Uuid;
|
||||||
|
|
||||||
|
use super::validation::scheduled_transaction::ValidatedRecurringTransaction;
|
||||||
use crate::{
|
use crate::{
|
||||||
database::dtos::scheduled_transaction::RecurringTransactionRow,
|
database::dtos::scheduled_transaction::RecurringTransactionRow,
|
||||||
error::AppError,
|
error::AppError,
|
||||||
routes::dtos::scheduled_transaction::{RecurringTransaction, ScheduledTransaction},
|
routes::dtos::scheduled_transaction::{
|
||||||
|
RecurringTransaction, ScheduledTransaction, ScheduledTransactionData, WeekendAdjustment,
|
||||||
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
pub fn create_router() -> axum::Router<PgPool> {
|
pub fn create_router() -> axum::Router<PgPool> {
|
||||||
axum::Router::new().route("/", axum::routing::get(get_scheduled_transactions))
|
axum::Router::new()
|
||||||
|
.route("/", axum::routing::get(get_scheduled_transactions))
|
||||||
|
.route("/{id}", axum::routing::put(put_scheduled_transaction))
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tracing::instrument(skip(pool))]
|
#[tracing::instrument(skip(pool))]
|
||||||
@@ -43,3 +53,83 @@ async fn get_scheduled_transactions(
|
|||||||
|
|
||||||
Ok(Json(transactions))
|
Ok(Json(transactions))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[tracing::instrument(skip(pool, transaction))]
|
||||||
|
async fn put_scheduled_transaction(
|
||||||
|
Path(id): Path<Uuid>,
|
||||||
|
State(pool): State<PgPool>,
|
||||||
|
Json(transaction): Json<ScheduledTransactionData>,
|
||||||
|
) -> Result<(StatusCode, Json<ScheduledTransaction>), AppError> {
|
||||||
|
let ScheduledTransactionData::Recurring(transaction) = transaction;
|
||||||
|
let transaction = ValidatedRecurringTransaction::try_from(transaction)?;
|
||||||
|
|
||||||
|
let row = sqlx::query!(
|
||||||
|
r#"
|
||||||
|
INSERT INTO recurring_transactions (
|
||||||
|
id,
|
||||||
|
name,
|
||||||
|
amount_cents,
|
||||||
|
direction,
|
||||||
|
starts_at,
|
||||||
|
ends_at,
|
||||||
|
recurrence_every,
|
||||||
|
recurrence_unit,
|
||||||
|
weekend_adjustment
|
||||||
|
)
|
||||||
|
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)
|
||||||
|
ON CONFLICT (id) DO UPDATE SET
|
||||||
|
name = EXCLUDED.name,
|
||||||
|
amount_cents = EXCLUDED.amount_cents,
|
||||||
|
direction = EXCLUDED.direction,
|
||||||
|
starts_at = EXCLUDED.starts_at,
|
||||||
|
ends_at = EXCLUDED.ends_at,
|
||||||
|
recurrence_every = EXCLUDED.recurrence_every,
|
||||||
|
recurrence_unit = EXCLUDED.recurrence_unit,
|
||||||
|
weekend_adjustment = EXCLUDED.weekend_adjustment
|
||||||
|
RETURNING WITH (OLD AS old_row, NEW AS new_row)
|
||||||
|
old_row.id AS "old_id?",
|
||||||
|
new_row.id AS "id!",
|
||||||
|
new_row.name AS "name!",
|
||||||
|
new_row.amount_cents AS "amount_cents!",
|
||||||
|
new_row.direction AS "direction!",
|
||||||
|
new_row.starts_at AS "starts_at!",
|
||||||
|
new_row.ends_at AS "ends_at?",
|
||||||
|
new_row.recurrence_every AS "recurrence_every!",
|
||||||
|
new_row.recurrence_unit AS "recurrence_unit!",
|
||||||
|
new_row.weekend_adjustment AS "weekend_adjustment?"
|
||||||
|
"#,
|
||||||
|
id,
|
||||||
|
transaction.name,
|
||||||
|
transaction.amount_cents.get(),
|
||||||
|
transaction.direction.as_str(),
|
||||||
|
transaction.starts_at,
|
||||||
|
transaction.ends_at,
|
||||||
|
transaction.recurrence_every.get(),
|
||||||
|
transaction.recurrence_unit.as_str(),
|
||||||
|
transaction
|
||||||
|
.weekend_adjustment
|
||||||
|
.as_ref()
|
||||||
|
.map(WeekendAdjustment::as_str),
|
||||||
|
)
|
||||||
|
.fetch_one(&pool)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
let status = if row.old_id.is_none() {
|
||||||
|
StatusCode::CREATED
|
||||||
|
} else {
|
||||||
|
StatusCode::OK
|
||||||
|
};
|
||||||
|
let transaction = RecurringTransaction::try_from(RecurringTransactionRow {
|
||||||
|
id: row.id,
|
||||||
|
name: row.name,
|
||||||
|
amount_cents: row.amount_cents,
|
||||||
|
direction: row.direction,
|
||||||
|
starts_at: row.starts_at,
|
||||||
|
ends_at: row.ends_at,
|
||||||
|
recurrence_every: row.recurrence_every,
|
||||||
|
recurrence_unit: row.recurrence_unit,
|
||||||
|
weekend_adjustment: row.weekend_adjustment,
|
||||||
|
})?;
|
||||||
|
|
||||||
|
Ok((status, Json(transaction.into())))
|
||||||
|
}
|
||||||
|
|||||||
@@ -0,0 +1 @@
|
|||||||
|
pub mod scheduled_transaction;
|
||||||
@@ -0,0 +1,222 @@
|
|||||||
|
use chrono::{DateTime, Utc};
|
||||||
|
|
||||||
|
use crate::routes::dtos::{
|
||||||
|
direction::Direction,
|
||||||
|
scheduled_transaction::{RecurrenceUnit, RecurringTransactionData, WeekendAdjustment},
|
||||||
|
};
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub struct ValidatedRecurringTransaction {
|
||||||
|
pub name: String,
|
||||||
|
pub amount_cents: Cents,
|
||||||
|
pub direction: Direction,
|
||||||
|
pub starts_at: DateTime<Utc>,
|
||||||
|
pub ends_at: Option<DateTime<Utc>>,
|
||||||
|
pub recurrence_every: PositiveRecurrenceInterval,
|
||||||
|
pub recurrence_unit: RecurrenceUnit,
|
||||||
|
pub weekend_adjustment: Option<WeekendAdjustment>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl TryFrom<RecurringTransactionData> for ValidatedRecurringTransaction {
|
||||||
|
type Error = ScheduledTransactionValidationError;
|
||||||
|
|
||||||
|
fn try_from(transaction: RecurringTransactionData) -> Result<Self, Self::Error> {
|
||||||
|
if transaction
|
||||||
|
.end
|
||||||
|
.as_ref()
|
||||||
|
.is_some_and(|end| end < &transaction.start)
|
||||||
|
{
|
||||||
|
return Err(ScheduledTransactionValidationError::EndBeforeStart);
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(Self {
|
||||||
|
name: transaction.name,
|
||||||
|
amount_cents: transaction.amount.try_into()?,
|
||||||
|
direction: transaction.direction,
|
||||||
|
starts_at: transaction.start,
|
||||||
|
ends_at: transaction.end,
|
||||||
|
recurrence_every: transaction.recurrence.every.try_into()?,
|
||||||
|
recurrence_unit: transaction.recurrence.unit,
|
||||||
|
weekend_adjustment: transaction.recurrence.weekend_adjustment,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub struct Cents(i64);
|
||||||
|
|
||||||
|
impl Cents {
|
||||||
|
pub fn get(&self) -> i64 {
|
||||||
|
self.0
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl TryFrom<f64> for Cents {
|
||||||
|
type Error = ScheduledTransactionValidationError;
|
||||||
|
|
||||||
|
fn try_from(amount: f64) -> Result<Self, Self::Error> {
|
||||||
|
if !amount.is_finite() {
|
||||||
|
return Err(ScheduledTransactionValidationError::AmountNotFinite);
|
||||||
|
}
|
||||||
|
if amount < 0.0 {
|
||||||
|
return Err(ScheduledTransactionValidationError::AmountNegative);
|
||||||
|
}
|
||||||
|
|
||||||
|
let amount_cents = amount * 100.0;
|
||||||
|
if amount_cents >= 9_223_372_036_854_775_808.0 {
|
||||||
|
return Err(ScheduledTransactionValidationError::AmountOutOfRange);
|
||||||
|
}
|
||||||
|
|
||||||
|
let rounded_amount_cents = amount_cents.round();
|
||||||
|
let rounding_tolerance = f64::EPSILON * amount_cents.abs().max(1.0) * 2.0;
|
||||||
|
if (amount_cents - rounded_amount_cents).abs() > rounding_tolerance {
|
||||||
|
return Err(ScheduledTransactionValidationError::AmountHasFractionalCents);
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(Self(rounded_amount_cents as i64))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub struct PositiveRecurrenceInterval(i32);
|
||||||
|
|
||||||
|
impl PositiveRecurrenceInterval {
|
||||||
|
pub fn get(&self) -> i32 {
|
||||||
|
self.0
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl TryFrom<u32> for PositiveRecurrenceInterval {
|
||||||
|
type Error = ScheduledTransactionValidationError;
|
||||||
|
|
||||||
|
fn try_from(every: u32) -> Result<Self, Self::Error> {
|
||||||
|
i32::try_from(every)
|
||||||
|
.ok()
|
||||||
|
.filter(|value| *value > 0)
|
||||||
|
.map(Self)
|
||||||
|
.ok_or(ScheduledTransactionValidationError::RecurrenceEvery(every))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub enum ScheduledTransactionValidationError {
|
||||||
|
AmountNotFinite,
|
||||||
|
AmountNegative,
|
||||||
|
AmountHasFractionalCents,
|
||||||
|
AmountOutOfRange,
|
||||||
|
RecurrenceEvery(u32),
|
||||||
|
EndBeforeStart,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl std::error::Error for ScheduledTransactionValidationError {}
|
||||||
|
|
||||||
|
impl std::fmt::Display for ScheduledTransactionValidationError {
|
||||||
|
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||||
|
match self {
|
||||||
|
Self::AmountNotFinite => write!(formatter, "amount must be finite"),
|
||||||
|
Self::AmountNegative => write!(formatter, "amount must not be negative"),
|
||||||
|
Self::AmountHasFractionalCents => {
|
||||||
|
write!(formatter, "amount must have at most two decimal places")
|
||||||
|
}
|
||||||
|
Self::AmountOutOfRange => write!(formatter, "amount is too large"),
|
||||||
|
Self::RecurrenceEvery(value) => {
|
||||||
|
write!(
|
||||||
|
formatter,
|
||||||
|
"recurrence every must be between 1 and {}: {value}",
|
||||||
|
i32::MAX
|
||||||
|
)
|
||||||
|
}
|
||||||
|
Self::EndBeforeStart => write!(formatter, "end must not be before start"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use chrono::{TimeZone, Utc};
|
||||||
|
|
||||||
|
use super::{
|
||||||
|
Cents, PositiveRecurrenceInterval, ScheduledTransactionValidationError,
|
||||||
|
ValidatedRecurringTransaction,
|
||||||
|
};
|
||||||
|
use crate::routes::dtos::{
|
||||||
|
direction::Direction,
|
||||||
|
scheduled_transaction::{
|
||||||
|
Recurrence, RecurrenceUnit, RecurringTransactionData, WeekendAdjustment,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
fn transaction(amount: f64) -> RecurringTransactionData {
|
||||||
|
RecurringTransactionData {
|
||||||
|
name: String::new(),
|
||||||
|
amount,
|
||||||
|
direction: Direction::Out,
|
||||||
|
start: Utc.with_ymd_and_hms(2026, 9, 24, 12, 0, 0).unwrap(),
|
||||||
|
end: None,
|
||||||
|
recurrence: Recurrence {
|
||||||
|
every: 2,
|
||||||
|
unit: RecurrenceUnit::Month,
|
||||||
|
weekend_adjustment: Some(WeekendAdjustment::NextBusinessDay),
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn validates_and_preserves_typed_values() {
|
||||||
|
let transaction = ValidatedRecurringTransaction::try_from(transaction(12.34)).unwrap();
|
||||||
|
assert_eq!(transaction.name, "");
|
||||||
|
assert_eq!(transaction.amount_cents.get(), 1234);
|
||||||
|
assert!(matches!(transaction.direction, Direction::Out));
|
||||||
|
assert_eq!(transaction.recurrence_every.get(), 2);
|
||||||
|
assert!(matches!(transaction.recurrence_unit, RecurrenceUnit::Month));
|
||||||
|
assert!(matches!(
|
||||||
|
transaction.weekend_adjustment,
|
||||||
|
Some(WeekendAdjustment::NextBusinessDay)
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rejects_invalid_amounts() {
|
||||||
|
for (amount, expected) in [
|
||||||
|
(f64::NAN, "amount must be finite"),
|
||||||
|
(f64::INFINITY, "amount must be finite"),
|
||||||
|
(-0.01, "amount must not be negative"),
|
||||||
|
(1.001, "amount must have at most two decimal places"),
|
||||||
|
(f64::MAX, "amount is too large"),
|
||||||
|
] {
|
||||||
|
let error = Cents::try_from(amount).unwrap_err();
|
||||||
|
assert_eq!(error.to_string(), expected);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn validates_date_ordering() {
|
||||||
|
let mut invalid = transaction(1.0);
|
||||||
|
invalid.end = Some(invalid.start - chrono::TimeDelta::seconds(1));
|
||||||
|
assert!(matches!(
|
||||||
|
ValidatedRecurringTransaction::try_from(invalid),
|
||||||
|
Err(ScheduledTransactionValidationError::EndBeforeStart)
|
||||||
|
));
|
||||||
|
|
||||||
|
let mut valid = transaction(1.0);
|
||||||
|
valid.end = Some(valid.start);
|
||||||
|
assert!(ValidatedRecurringTransaction::try_from(valid).is_ok());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rejects_invalid_recurrence_ranges() {
|
||||||
|
assert_eq!(PositiveRecurrenceInterval::try_from(1).unwrap().get(), 1);
|
||||||
|
assert_eq!(
|
||||||
|
PositiveRecurrenceInterval::try_from(i32::MAX as u32)
|
||||||
|
.unwrap()
|
||||||
|
.get(),
|
||||||
|
i32::MAX
|
||||||
|
);
|
||||||
|
for every in [0, i32::MAX as u32 + 1] {
|
||||||
|
assert!(matches!(
|
||||||
|
PositiveRecurrenceInterval::try_from(every),
|
||||||
|
Err(ScheduledTransactionValidationError::RecurrenceEvery(value)) if value == every
|
||||||
|
));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user