Create/update scheduled transactions.
This commit is contained in:
+21
-8
@@ -3,16 +3,20 @@ use axum::{
|
||||
response::{IntoResponse, Response},
|
||||
};
|
||||
|
||||
use crate::routes::dtos::{
|
||||
scheduled_transaction::RecurringTransactionConversionError,
|
||||
transaction_direction::TransactionDirectionConversionError,
|
||||
use crate::routes::{
|
||||
dtos::{
|
||||
direction::DirectionConversionError,
|
||||
scheduled_transaction::RecurringTransactionConversionError,
|
||||
},
|
||||
validation::scheduled_transaction::ScheduledTransactionValidationError,
|
||||
};
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum AppError {
|
||||
Database(sqlx::Error),
|
||||
TransactionDirection(TransactionDirectionConversionError),
|
||||
Direction(DirectionConversionError),
|
||||
RecurringTransaction(RecurringTransactionConversionError),
|
||||
ScheduledTransactionValidation(ScheduledTransactionValidationError),
|
||||
}
|
||||
|
||||
impl From<sqlx::Error> for AppError {
|
||||
@@ -21,9 +25,9 @@ impl From<sqlx::Error> for AppError {
|
||||
}
|
||||
}
|
||||
|
||||
impl From<TransactionDirectionConversionError> for AppError {
|
||||
fn from(error: TransactionDirectionConversionError) -> Self {
|
||||
Self::TransactionDirection(error)
|
||||
impl From<DirectionConversionError> for AppError {
|
||||
fn from(error: DirectionConversionError) -> Self {
|
||||
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 {
|
||||
fn into_response(self) -> Response {
|
||||
match self {
|
||||
Self::ScheduledTransactionValidation(error) => {
|
||||
return (StatusCode::UNPROCESSABLE_ENTITY, error.to_string()).into_response();
|
||||
}
|
||||
Self::Database(error) => tracing::error!(%error, "Database query failed"),
|
||||
Self::TransactionDirection(error) => {
|
||||
Self::Direction(error) => {
|
||||
tracing::error!(%error, "Invalid transaction direction")
|
||||
}
|
||||
Self::RecurringTransaction(error) => {
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
pub mod dtos;
|
||||
mod scheduled_transactions;
|
||||
mod transactions;
|
||||
pub mod validation;
|
||||
|
||||
pub fn create_router(pool: sqlx::PgPool) -> axum::Router {
|
||||
axum::Router::new()
|
||||
|
||||
@@ -1,3 +1,3 @@
|
||||
pub mod direction;
|
||||
pub mod scheduled_transaction;
|
||||
pub mod transaction;
|
||||
pub mod transaction_direction;
|
||||
|
||||
+21
-12
@@ -2,30 +2,39 @@ use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum TransactionDirection {
|
||||
pub enum Direction {
|
||||
In,
|
||||
Out,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct TransactionDirectionConversionError(pub String);
|
||||
|
||||
impl std::fmt::Display for TransactionDirectionConversionError {
|
||||
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
write!(formatter, "invalid direction value: {}", self.0)
|
||||
impl Direction {
|
||||
pub fn as_str(&self) -> &'static str {
|
||||
match self {
|
||||
Self::In => "in",
|
||||
Self::Out => "out",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for TransactionDirectionConversionError {}
|
||||
|
||||
impl TryFrom<String> for TransactionDirection {
|
||||
type Error = TransactionDirectionConversionError;
|
||||
impl TryFrom<String> for Direction {
|
||||
type Error = DirectionConversionError;
|
||||
|
||||
fn try_from(value: String) -> Result<Self, Self::Error> {
|
||||
match value.as_str() {
|
||||
"in" => Ok(Self::In),
|
||||
"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::{
|
||||
database::dtos::scheduled_transaction::RecurringTransactionRow,
|
||||
routes::dtos::transaction_direction::{
|
||||
TransactionDirection, TransactionDirectionConversionError,
|
||||
},
|
||||
routes::dtos::direction::{Direction, DirectionConversionError},
|
||||
};
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
@@ -16,12 +14,60 @@ pub enum ScheduledTransaction {
|
||||
Recurring(RecurringTransaction),
|
||||
}
|
||||
|
||||
impl From<RecurringTransaction> for ScheduledTransaction {
|
||||
fn from(transaction: RecurringTransaction) -> Self {
|
||||
Self::Recurring(transaction)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct RecurringTransaction {
|
||||
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 amount: f64,
|
||||
pub direction: TransactionDirection,
|
||||
pub direction: Direction,
|
||||
pub start: DateTime<Utc>,
|
||||
pub end: Option<DateTime<Utc>>,
|
||||
pub recurrence: Recurrence,
|
||||
@@ -43,6 +89,31 @@ pub enum RecurrenceUnit {
|
||||
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)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum WeekendAdjustment {
|
||||
@@ -50,19 +121,38 @@ pub enum WeekendAdjustment {
|
||||
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)]
|
||||
pub enum RecurringTransactionConversionError {
|
||||
Direction(TransactionDirectionConversionError),
|
||||
Direction(DirectionConversionError),
|
||||
RecurrenceEvery(i32),
|
||||
RecurrenceUnit(String),
|
||||
WeekendAdjustment(String),
|
||||
}
|
||||
|
||||
impl From<RecurringTransaction> for ScheduledTransaction {
|
||||
fn from(transaction: RecurringTransaction) -> Self {
|
||||
Self::Recurring(transaction)
|
||||
}
|
||||
}
|
||||
impl std::error::Error for RecurringTransactionConversionError {}
|
||||
|
||||
impl std::fmt::Display for RecurringTransactionConversionError {
|
||||
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 {
|
||||
type Error = RecurringTransactionConversionError;
|
||||
use super::{
|
||||
Recurrence, RecurrenceUnit, RecurringTransaction, RecurringTransactionData,
|
||||
ScheduledTransaction, ScheduledTransactionData, WeekendAdjustment,
|
||||
};
|
||||
use crate::routes::dtos::direction::Direction;
|
||||
|
||||
fn try_from(row: RecurringTransactionRow) -> Result<Self, Self::Error> {
|
||||
Ok(Self {
|
||||
id: row.id,
|
||||
name: row.name,
|
||||
amount: row.amount_cents as f64 / 100.0,
|
||||
direction: TransactionDirection::try_from(row.direction)
|
||||
.map_err(RecurringTransactionConversionError::Direction)?,
|
||||
start: row.starts_at,
|
||||
end: row.ends_at,
|
||||
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: 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,
|
||||
},
|
||||
every: 2,
|
||||
unit: RecurrenceUnit::Month,
|
||||
weekend_adjustment: Some(WeekendAdjustment::NextBusinessDay),
|
||||
},
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
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)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl TryFrom<String> for WeekendAdjustment {
|
||||
type Error = RecurringTransactionConversionError;
|
||||
#[test]
|
||||
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> {
|
||||
match value.as_str() {
|
||||
"previous_business_day" => Ok(Self::PreviousBusinessDay),
|
||||
"next_business_day" => Ok(Self::NextBusinessDay),
|
||||
_ => Err(RecurringTransactionConversionError::WeekendAdjustment(
|
||||
value,
|
||||
)),
|
||||
}
|
||||
let request: ScheduledTransactionData = serde_json::from_value(response).unwrap();
|
||||
let ScheduledTransactionData::Recurring(data) = request;
|
||||
assert_eq!(data.amount, 12.34);
|
||||
assert_eq!(data.recurrence.every, 2);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,28 +3,26 @@ use serde::Serialize;
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::database::dtos::transaction::TransactionRow;
|
||||
use crate::routes::dtos::transaction_direction::{
|
||||
TransactionDirection, TransactionDirectionConversionError,
|
||||
};
|
||||
use crate::routes::dtos::direction::{Direction, DirectionConversionError};
|
||||
|
||||
#[derive(Serialize)]
|
||||
pub struct TransactionResponse {
|
||||
pub id: Uuid,
|
||||
pub description: String,
|
||||
pub amount: f64,
|
||||
pub direction: TransactionDirection,
|
||||
pub direction: Direction,
|
||||
pub date: DateTime<Utc>,
|
||||
}
|
||||
|
||||
impl TryFrom<TransactionRow> for TransactionResponse {
|
||||
type Error = TransactionDirectionConversionError;
|
||||
type Error = DirectionConversionError;
|
||||
|
||||
fn try_from(row: TransactionRow) -> Result<Self, Self::Error> {
|
||||
Ok(Self {
|
||||
id: row.id,
|
||||
description: row.description,
|
||||
amount: row.amount_cents as f64 / 100.0,
|
||||
direction: TransactionDirection::try_from(row.direction)?,
|
||||
direction: Direction::try_from(row.direction)?,
|
||||
date: row.date,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1,14 +1,24 @@
|
||||
use axum::{Json, extract::State};
|
||||
use axum::{
|
||||
Json,
|
||||
extract::{Path, State},
|
||||
http::StatusCode,
|
||||
};
|
||||
use sqlx::PgPool;
|
||||
use uuid::Uuid;
|
||||
|
||||
use super::validation::scheduled_transaction::ValidatedRecurringTransaction;
|
||||
use crate::{
|
||||
database::dtos::scheduled_transaction::RecurringTransactionRow,
|
||||
error::AppError,
|
||||
routes::dtos::scheduled_transaction::{RecurringTransaction, ScheduledTransaction},
|
||||
routes::dtos::scheduled_transaction::{
|
||||
RecurringTransaction, ScheduledTransaction, ScheduledTransactionData, WeekendAdjustment,
|
||||
},
|
||||
};
|
||||
|
||||
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))]
|
||||
@@ -43,3 +53,83 @@ async fn get_scheduled_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