Implemented a domain layer, because the API DTO's where getting bloated.
This commit is contained in:
@@ -1,4 +1,3 @@
|
||||
pub mod cents;
|
||||
pub mod direction;
|
||||
pub mod scheduled_transaction;
|
||||
pub mod transaction;
|
||||
|
||||
@@ -1,65 +0,0 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
|
||||
#[serde(transparent)]
|
||||
pub struct Cents(u64);
|
||||
|
||||
impl Cents {
|
||||
pub fn get(&self) -> u64 {
|
||||
self.0
|
||||
}
|
||||
}
|
||||
|
||||
impl From<u64> for Cents {
|
||||
fn from(value: u64) -> Self {
|
||||
Self(value)
|
||||
}
|
||||
}
|
||||
|
||||
impl TryFrom<i64> for Cents {
|
||||
type Error = CentsConversionError;
|
||||
|
||||
fn try_from(value: i64) -> Result<Self, Self::Error> {
|
||||
u64::try_from(value)
|
||||
.map(Self)
|
||||
.map_err(|_| CentsConversionError(value.into()))
|
||||
}
|
||||
}
|
||||
|
||||
impl TryFrom<Cents> for i64 {
|
||||
type Error = CentsConversionError;
|
||||
|
||||
fn try_from(value: Cents) -> Result<Self, Self::Error> {
|
||||
i64::try_from(value.get()).map_err(|_| CentsConversionError(value.get().into()))
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
#[error("invalid cents value: {0}")]
|
||||
pub struct CentsConversionError(pub i128);
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{Cents, CentsConversionError};
|
||||
|
||||
#[test]
|
||||
fn converts_non_negative_database_values() {
|
||||
assert_eq!(Cents::try_from(4250_i64).unwrap().get(), 4250);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_negative_database_values() {
|
||||
assert!(matches!(
|
||||
Cents::try_from(-1_i64),
|
||||
Err(CentsConversionError(-1_i128))
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_values_too_large_for_the_database() {
|
||||
assert!(matches!(
|
||||
i64::try_from(Cents::from(i64::MAX as u64 + 1)),
|
||||
Err(CentsConversionError(value)) if value == i64::MAX as i128 + 1
|
||||
));
|
||||
}
|
||||
}
|
||||
@@ -1,33 +1,28 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
use crate::domain;
|
||||
|
||||
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum Direction {
|
||||
In,
|
||||
Out,
|
||||
}
|
||||
|
||||
impl Direction {
|
||||
pub fn as_str(&self) -> &'static str {
|
||||
match self {
|
||||
Self::In => "in",
|
||||
Self::Out => "out",
|
||||
impl From<Direction> for domain::Direction {
|
||||
fn from(direction: Direction) -> Self {
|
||||
match direction {
|
||||
Direction::In => Self::In,
|
||||
Direction::Out => Self::Out,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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(DirectionConversionError(value)),
|
||||
impl From<domain::Direction> for Direction {
|
||||
fn from(direction: domain::Direction) -> Self {
|
||||
match direction {
|
||||
domain::Direction::In => Self::In,
|
||||
domain::Direction::Out => Self::Out,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
#[error("invalid direction value: {0}")]
|
||||
pub struct DirectionConversionError(pub String);
|
||||
|
||||
@@ -2,15 +2,9 @@ use chrono::{DateTime, Utc};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::{
|
||||
database::dtos::recurring_transaction::RecurringTransactionRow,
|
||||
routes::dtos::{
|
||||
cents::{Cents, CentsConversionError},
|
||||
direction::{Direction, DirectionConversionError},
|
||||
},
|
||||
};
|
||||
use crate::{domain, routes::dtos::direction::Direction};
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
#[serde(tag = "type")]
|
||||
pub enum ScheduledTransaction {
|
||||
@@ -23,39 +17,31 @@ impl From<RecurringTransaction> for ScheduledTransaction {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct RecurringTransaction {
|
||||
pub id: Uuid,
|
||||
|
||||
#[serde(flatten)]
|
||||
pub data: RecurringTransactionData,
|
||||
|
||||
/// The next scheduled occurrence of the transaction.
|
||||
pub next: Option<DateTime<Utc>>,
|
||||
}
|
||||
|
||||
impl TryFrom<RecurringTransactionRow> for RecurringTransaction {
|
||||
type Error = RecurringTransactionConversionError;
|
||||
|
||||
fn try_from(row: RecurringTransactionRow) -> Result<Self, Self::Error> {
|
||||
Ok(Self {
|
||||
id: row.id,
|
||||
impl RecurringTransaction {
|
||||
pub fn new(transaction: domain::RecurringTransaction, next: Option<DateTime<Utc>>) -> Self {
|
||||
Self {
|
||||
id: transaction.id,
|
||||
next,
|
||||
data: RecurringTransactionData {
|
||||
name: row.name,
|
||||
amount_cents: Cents::try_from(row.amount_cents)?,
|
||||
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,
|
||||
},
|
||||
},
|
||||
name: transaction.name,
|
||||
amount_cents: transaction.amount.get(),
|
||||
direction: transaction.direction.into(),
|
||||
start: transaction.schedule.start(),
|
||||
end: transaction.schedule.end(),
|
||||
recurrence: transaction.schedule.recurrence().into(),
|
||||
},
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -69,13 +55,34 @@ pub enum ScheduledTransactionData {
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct RecurringTransactionData {
|
||||
pub name: String,
|
||||
pub amount_cents: Cents,
|
||||
pub amount_cents: u64,
|
||||
pub direction: Direction,
|
||||
pub start: DateTime<Utc>,
|
||||
pub end: Option<DateTime<Utc>>,
|
||||
pub recurrence: Recurrence,
|
||||
}
|
||||
|
||||
impl RecurringTransactionData {
|
||||
pub fn into_domain(
|
||||
self,
|
||||
id: Uuid,
|
||||
) -> Result<domain::RecurringTransaction, domain::ValidationError> {
|
||||
let recurrence = domain::Recurrence {
|
||||
every: domain::RecurrenceInterval::try_from(self.recurrence.every)?,
|
||||
unit: self.recurrence.unit.into(),
|
||||
weekend_adjustment: self.recurrence.weekend_adjustment.map(Into::into),
|
||||
};
|
||||
|
||||
Ok(domain::RecurringTransaction {
|
||||
id,
|
||||
name: self.name,
|
||||
amount: domain::Cents::try_from(self.amount_cents)?,
|
||||
direction: self.direction.into(),
|
||||
schedule: domain::Schedule::new(self.start, self.end, recurrence)?,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct Recurrence {
|
||||
pub every: u32,
|
||||
@@ -83,7 +90,17 @@ pub struct Recurrence {
|
||||
pub weekend_adjustment: Option<WeekendAdjustment>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
impl From<domain::Recurrence> for Recurrence {
|
||||
fn from(recurrence: domain::Recurrence) -> Self {
|
||||
Self {
|
||||
every: recurrence.every.get(),
|
||||
unit: recurrence.unit.into(),
|
||||
weekend_adjustment: recurrence.weekend_adjustment.map(Into::into),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum RecurrenceUnit {
|
||||
Day,
|
||||
@@ -92,94 +109,68 @@ 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 From<RecurrenceUnit> for domain::RecurrenceUnit {
|
||||
fn from(unit: RecurrenceUnit) -> Self {
|
||||
match unit {
|
||||
RecurrenceUnit::Day => Self::Day,
|
||||
RecurrenceUnit::Week => Self::Week,
|
||||
RecurrenceUnit::Month => Self::Month,
|
||||
RecurrenceUnit::Year => Self::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)),
|
||||
impl From<domain::RecurrenceUnit> for RecurrenceUnit {
|
||||
fn from(unit: domain::RecurrenceUnit) -> Self {
|
||||
match unit {
|
||||
domain::RecurrenceUnit::Day => Self::Day,
|
||||
domain::RecurrenceUnit::Week => Self::Week,
|
||||
domain::RecurrenceUnit::Month => Self::Month,
|
||||
domain::RecurrenceUnit::Year => Self::Year,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum WeekendAdjustment {
|
||||
PreviousBusinessDay,
|
||||
NextBusinessDay,
|
||||
}
|
||||
|
||||
impl WeekendAdjustment {
|
||||
pub fn as_str(&self) -> &'static str {
|
||||
match self {
|
||||
Self::PreviousBusinessDay => "previous_business_day",
|
||||
Self::NextBusinessDay => "next_business_day",
|
||||
impl From<WeekendAdjustment> for domain::WeekendAdjustment {
|
||||
fn from(adjustment: WeekendAdjustment) -> Self {
|
||||
match adjustment {
|
||||
WeekendAdjustment::PreviousBusinessDay => Self::PreviousBusinessDay,
|
||||
WeekendAdjustment::NextBusinessDay => Self::NextBusinessDay,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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,
|
||||
)),
|
||||
impl From<domain::WeekendAdjustment> for WeekendAdjustment {
|
||||
fn from(adjustment: domain::WeekendAdjustment) -> Self {
|
||||
match adjustment {
|
||||
domain::WeekendAdjustment::PreviousBusinessDay => Self::PreviousBusinessDay,
|
||||
domain::WeekendAdjustment::NextBusinessDay => Self::NextBusinessDay,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum RecurringTransactionConversionError {
|
||||
#[error(transparent)]
|
||||
Cents(#[from] CentsConversionError),
|
||||
|
||||
#[error(transparent)]
|
||||
Direction(#[from] DirectionConversionError),
|
||||
|
||||
#[error("invalid recurrence_every value: {0}")]
|
||||
RecurrenceEvery(i32),
|
||||
|
||||
#[error("invalid recurrence_unit value: {0}")]
|
||||
RecurrenceUnit(String),
|
||||
|
||||
#[error("invalid weekend_adjustment value: {0}")]
|
||||
WeekendAdjustment(String),
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use chrono::{TimeZone, Utc};
|
||||
use chrono::{TimeDelta, TimeZone, Utc};
|
||||
use uuid::Uuid;
|
||||
|
||||
use super::{
|
||||
Recurrence, RecurrenceUnit, RecurringTransaction, RecurringTransactionData,
|
||||
ScheduledTransaction, ScheduledTransactionData, WeekendAdjustment,
|
||||
};
|
||||
use crate::routes::dtos::direction::Direction;
|
||||
use crate::{domain, routes::dtos::direction::Direction};
|
||||
|
||||
fn transaction(amount_cents: u64) -> RecurringTransactionData {
|
||||
fn data(amount_cents: u64) -> RecurringTransactionData {
|
||||
RecurringTransactionData {
|
||||
name: String::new(),
|
||||
amount_cents: amount_cents.into(),
|
||||
amount_cents,
|
||||
direction: Direction::Out,
|
||||
start: Utc.with_ymd_and_hms(2026, 9, 24, 12, 0, 0).unwrap(),
|
||||
end: None,
|
||||
@@ -193,19 +184,63 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn keeps_scheduled_transaction_json_flat() {
|
||||
let response = ScheduledTransaction::Recurring(RecurringTransaction {
|
||||
id: Uuid::nil(),
|
||||
data: transaction(1234),
|
||||
});
|
||||
let transaction = data(1234).into_domain(Uuid::nil()).unwrap();
|
||||
let response = ScheduledTransaction::from(RecurringTransaction::new(transaction, None));
|
||||
|
||||
let response = serde_json::to_value(response).unwrap();
|
||||
assert_eq!(response["type"], "recurring");
|
||||
assert_eq!(response["id"], Uuid::nil().to_string());
|
||||
assert!(response["next"].is_null());
|
||||
assert_eq!(response["amount_cents"], 1234);
|
||||
assert_eq!(response["recurrence"]["unit"], "month");
|
||||
assert_eq!(
|
||||
response["recurrence"]["weekend_adjustment"],
|
||||
"next_business_day"
|
||||
);
|
||||
assert!(response.get("data").is_none());
|
||||
|
||||
let request: ScheduledTransactionData = serde_json::from_value(response).unwrap();
|
||||
let ScheduledTransactionData::Recurring(data) = request;
|
||||
assert_eq!(data.amount_cents.get(), 1234);
|
||||
assert_eq!(data.amount_cents, 1234);
|
||||
assert_eq!(data.recurrence.every, 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn converts_to_domain() {
|
||||
let id = Uuid::new_v4();
|
||||
let transaction = data(1234).into_domain(id).unwrap();
|
||||
let recurrence = transaction.schedule.recurrence();
|
||||
|
||||
assert_eq!(transaction.id, id);
|
||||
assert_eq!(transaction.amount.get(), 1234);
|
||||
assert_eq!(transaction.direction, domain::Direction::Out);
|
||||
assert_eq!(recurrence.every.get(), 2);
|
||||
assert_eq!(recurrence.unit, domain::RecurrenceUnit::Month);
|
||||
assert_eq!(
|
||||
recurrence.weekend_adjustment,
|
||||
Some(domain::WeekendAdjustment::NextBusinessDay)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_invalid_requests() {
|
||||
assert!(matches!(
|
||||
data(i64::MAX as u64 + 1).into_domain(Uuid::nil()),
|
||||
Err(domain::ValidationError::Amount(_))
|
||||
));
|
||||
|
||||
let mut every = data(100);
|
||||
every.recurrence.every = 0;
|
||||
assert!(matches!(
|
||||
every.into_domain(Uuid::nil()),
|
||||
Err(domain::ValidationError::RecurrenceInterval(_))
|
||||
));
|
||||
|
||||
let mut end = data(100);
|
||||
end.end = Some(end.start - TimeDelta::seconds(1));
|
||||
assert!(matches!(
|
||||
end.into_domain(Uuid::nil()),
|
||||
Err(domain::ValidationError::EndBeforeStart)
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,11 +2,7 @@ use chrono::{DateTime, Utc};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::database::dtos::transaction::TransactionRow;
|
||||
use crate::routes::dtos::{
|
||||
cents::{Cents, CentsConversionError},
|
||||
direction::{Direction, DirectionConversionError},
|
||||
};
|
||||
use crate::{domain, routes::dtos::direction::Direction};
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct Transaction {
|
||||
@@ -19,80 +15,91 @@ pub struct Transaction {
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct TransactionData {
|
||||
pub description: String,
|
||||
pub amount_cents: Cents,
|
||||
pub amount_cents: u64,
|
||||
pub direction: Direction,
|
||||
pub date: DateTime<Utc>,
|
||||
}
|
||||
|
||||
impl TryFrom<TransactionRow> for Transaction {
|
||||
type Error = TransactionConversionError;
|
||||
|
||||
fn try_from(row: TransactionRow) -> Result<Self, Self::Error> {
|
||||
Ok(Self {
|
||||
id: row.id,
|
||||
impl From<domain::Transaction> for Transaction {
|
||||
fn from(transaction: domain::Transaction) -> Self {
|
||||
Self {
|
||||
id: transaction.id,
|
||||
data: TransactionData {
|
||||
description: row.description,
|
||||
amount_cents: Cents::try_from(row.amount_cents)?,
|
||||
direction: Direction::try_from(row.direction)
|
||||
.map_err(TransactionConversionError::Direction)?,
|
||||
date: row.date,
|
||||
description: transaction.description,
|
||||
amount_cents: transaction.amount.get(),
|
||||
direction: transaction.direction.into(),
|
||||
date: transaction.date,
|
||||
},
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum TransactionConversionError {
|
||||
#[error(transparent)]
|
||||
Cents(#[from] CentsConversionError),
|
||||
|
||||
#[error(transparent)]
|
||||
Direction(#[from] DirectionConversionError),
|
||||
impl TransactionData {
|
||||
pub fn into_domain(self, id: Uuid) -> Result<domain::Transaction, domain::ValidationError> {
|
||||
Ok(domain::Transaction {
|
||||
id,
|
||||
description: self.description,
|
||||
amount: domain::Cents::try_from(self.amount_cents)?,
|
||||
direction: self.direction.into(),
|
||||
date: self.date,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn preserves_cents_in_response() {
|
||||
let id = Uuid::new_v4();
|
||||
let date = Utc::now();
|
||||
let response = Transaction::try_from(TransactionRow {
|
||||
id,
|
||||
fn data(amount_cents: u64) -> TransactionData {
|
||||
TransactionData {
|
||||
description: "Groceries".to_string(),
|
||||
amount_cents: 4250,
|
||||
direction: "out".to_string(),
|
||||
date,
|
||||
});
|
||||
amount_cents,
|
||||
direction: Direction::Out,
|
||||
date: Utc::now(),
|
||||
}
|
||||
}
|
||||
|
||||
let response = response.expect("valid direction");
|
||||
#[test]
|
||||
fn converts_between_dto_and_domain() {
|
||||
let id = Uuid::new_v4();
|
||||
let transaction = data(4250).into_domain(id).unwrap();
|
||||
assert_eq!(transaction.id, id);
|
||||
assert_eq!(transaction.amount.get(), 4250);
|
||||
assert_eq!(transaction.direction, domain::Direction::Out);
|
||||
|
||||
let response = Transaction::from(transaction);
|
||||
assert_eq!(response.id, id);
|
||||
assert_eq!(response.data.description, "Groceries");
|
||||
assert_eq!(response.data.amount_cents.get(), 4250);
|
||||
assert_eq!(response.data.date, date);
|
||||
assert_eq!(response.data.amount_cents, 4250);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_amounts_that_do_not_fit_in_database() {
|
||||
let error = data(i64::MAX as u64 + 1)
|
||||
.into_domain(Uuid::nil())
|
||||
.unwrap_err();
|
||||
assert!(matches!(
|
||||
error,
|
||||
domain::ValidationError::Amount(domain::CentsConversionError(value))
|
||||
if value == i64::MAX as i128 + 1
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keeps_transaction_json_flat() {
|
||||
let response = Transaction {
|
||||
id: Uuid::nil(),
|
||||
data: TransactionData {
|
||||
description: "Groceries".to_string(),
|
||||
amount_cents: 4250.into(),
|
||||
direction: Direction::Out,
|
||||
date: Utc::now(),
|
||||
},
|
||||
data: data(4250),
|
||||
};
|
||||
|
||||
let response = serde_json::to_value(response).unwrap();
|
||||
assert_eq!(response["id"], Uuid::nil().to_string());
|
||||
assert_eq!(response["amount_cents"], 4250);
|
||||
assert_eq!(response["direction"], "out");
|
||||
assert!(response.get("data").is_none());
|
||||
|
||||
let request: TransactionData = serde_json::from_value(response).unwrap();
|
||||
assert_eq!(request.description, "Groceries");
|
||||
assert_eq!(request.amount_cents.get(), 4250);
|
||||
assert_eq!(request.amount_cents, 4250);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,23 +1,17 @@
|
||||
use axum::{extract::State, http::StatusCode};
|
||||
use chrono::{DateTime, Utc};
|
||||
use sqlx::PgPool;
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::{
|
||||
database::{
|
||||
common::{Delete, Upsert},
|
||||
dtos::recurring_transaction::RecurringTransactionRow,
|
||||
recurring_transactions::{
|
||||
delete_scheduled_transaction_by_id, get_scheduled_transaction_by_id,
|
||||
query_scheduled_transactions, upsert_scheduled_transaction,
|
||||
},
|
||||
},
|
||||
domain,
|
||||
error::AppError,
|
||||
repository::{Delete, Upsert, recurring_transactions as repository},
|
||||
routes::{
|
||||
dtos::scheduled_transaction::{
|
||||
RecurringTransaction, ScheduledTransaction, ScheduledTransactionData,
|
||||
},
|
||||
extractors::{json::Json, path::Path},
|
||||
validation::recurring_transaction::ValidatedRecurringTransaction,
|
||||
},
|
||||
};
|
||||
|
||||
@@ -37,13 +31,12 @@ pub fn create_router() -> axum::Router<PgPool> {
|
||||
async fn get_scheduled_transactions(
|
||||
State(pool): State<PgPool>,
|
||||
) -> Result<Json<Vec<ScheduledTransaction>>, AppError> {
|
||||
let rows = query_scheduled_transactions(&pool).await?;
|
||||
|
||||
let transactions = rows
|
||||
let now = Utc::now();
|
||||
let transactions = repository::list(&pool)
|
||||
.await?
|
||||
.into_iter()
|
||||
.map(RecurringTransaction::try_from)
|
||||
.map(|result| result.map(ScheduledTransaction::from))
|
||||
.collect::<Result<Vec<_>, _>>()?;
|
||||
.map(|transaction| respond(transaction, now))
|
||||
.collect();
|
||||
|
||||
Ok(Json(transactions))
|
||||
}
|
||||
@@ -54,15 +47,11 @@ async fn get_scheduled_transaction(
|
||||
State(pool): State<PgPool>,
|
||||
Path(id): Path<Uuid>,
|
||||
) -> Result<Json<ScheduledTransaction>, AppError> {
|
||||
let row = get_scheduled_transaction_by_id(&pool, id)
|
||||
let transaction = repository::get(&pool, id)
|
||||
.await?
|
||||
.map(RecurringTransaction::try_from)
|
||||
.transpose()?;
|
||||
.ok_or(AppError::NotFound)?;
|
||||
|
||||
match row {
|
||||
Some(transaction) => Ok(Json(ScheduledTransaction::from(transaction))),
|
||||
None => Err(AppError::NotFound),
|
||||
}
|
||||
Ok(Json(respond(transaction, Utc::now())))
|
||||
}
|
||||
|
||||
#[axum::debug_handler]
|
||||
@@ -73,29 +62,14 @@ async fn put_scheduled_transaction(
|
||||
Json(transaction): Json<ScheduledTransactionData>,
|
||||
) -> Result<(StatusCode, Json<ScheduledTransaction>), AppError> {
|
||||
let ScheduledTransactionData::Recurring(transaction) = transaction;
|
||||
let transaction = transaction.into_domain(id)?;
|
||||
|
||||
let transaction = ValidatedRecurringTransaction::try_from(transaction)?;
|
||||
let transaction = RecurringTransactionRow {
|
||||
id,
|
||||
name: transaction.name,
|
||||
amount_cents: transaction.amount_cents,
|
||||
direction: transaction.direction.as_str().to_owned(),
|
||||
starts_at: transaction.starts_at,
|
||||
ends_at: transaction.ends_at,
|
||||
recurrence_every: transaction.recurrence_every.get(),
|
||||
recurrence_unit: transaction.recurrence_unit.as_str().to_owned(),
|
||||
weekend_adjustment: transaction
|
||||
.weekend_adjustment
|
||||
.map(|adjustment| adjustment.as_str().to_owned()),
|
||||
let (status, transaction) = match repository::upsert(&pool, transaction).await? {
|
||||
Upsert::Created(transaction) => (StatusCode::CREATED, transaction),
|
||||
Upsert::Updated(transaction) => (StatusCode::OK, transaction),
|
||||
};
|
||||
|
||||
let (status, row) = match upsert_scheduled_transaction(&pool, transaction).await? {
|
||||
Upsert::Created(row) => (StatusCode::CREATED, row),
|
||||
Upsert::Updated(row) => (StatusCode::OK, row),
|
||||
};
|
||||
let transaction = RecurringTransaction::try_from(row)?;
|
||||
|
||||
Ok((status, Json(transaction.into())))
|
||||
Ok((status, Json(respond(transaction, Utc::now()))))
|
||||
}
|
||||
|
||||
#[axum::debug_handler]
|
||||
@@ -104,8 +78,14 @@ async fn delete_scheduled_transaction(
|
||||
State(pool): State<PgPool>,
|
||||
Path(id): Path<Uuid>,
|
||||
) -> Result<StatusCode, AppError> {
|
||||
match delete_scheduled_transaction_by_id(&pool, id).await? {
|
||||
match repository::delete(&pool, id).await? {
|
||||
Delete::Deleted => Ok(StatusCode::NO_CONTENT),
|
||||
Delete::NotFound => Err(AppError::NotFound),
|
||||
}
|
||||
}
|
||||
|
||||
fn respond(transaction: domain::RecurringTransaction, now: DateTime<Utc>) -> ScheduledTransaction {
|
||||
let next = transaction.schedule.next_occurrence(now);
|
||||
|
||||
RecurringTransaction::new(transaction, next).into()
|
||||
}
|
||||
|
||||
@@ -3,18 +3,11 @@ use sqlx::PgPool;
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::{
|
||||
database::{
|
||||
common::{Delete, Upsert},
|
||||
dtos::transaction::TransactionRow,
|
||||
transactions::{
|
||||
delete_transaction_by_id, get_transaction_by_id, query_transactions, upsert_transaction,
|
||||
},
|
||||
},
|
||||
error::AppError,
|
||||
repository::{Delete, Upsert, transactions as repository},
|
||||
routes::{
|
||||
dtos::transaction::{Transaction, TransactionData},
|
||||
extractors::{json::Json, path::Path},
|
||||
validation::transaction::ValidatedTransaction,
|
||||
},
|
||||
};
|
||||
|
||||
@@ -32,12 +25,11 @@ pub fn create_router() -> axum::Router<PgPool> {
|
||||
#[axum::debug_handler]
|
||||
#[tracing::instrument(skip(pool))]
|
||||
async fn get_transactions(State(pool): State<PgPool>) -> Result<Json<Vec<Transaction>>, AppError> {
|
||||
let rows = query_transactions(&pool).await?;
|
||||
|
||||
let transactions = rows
|
||||
let transactions = repository::list(&pool)
|
||||
.await?
|
||||
.into_iter()
|
||||
.map(Transaction::try_from)
|
||||
.collect::<Result<Vec<_>, _>>()?;
|
||||
.map(Transaction::from)
|
||||
.collect();
|
||||
|
||||
Ok(Json(transactions))
|
||||
}
|
||||
@@ -48,15 +40,11 @@ async fn get_transaction(
|
||||
State(pool): State<PgPool>,
|
||||
Path(id): Path<Uuid>,
|
||||
) -> Result<Json<Transaction>, AppError> {
|
||||
let transaction = get_transaction_by_id(&pool, id)
|
||||
let transaction = repository::get(&pool, id)
|
||||
.await?
|
||||
.map(Transaction::try_from)
|
||||
.transpose()?;
|
||||
.ok_or(AppError::NotFound)?;
|
||||
|
||||
match transaction {
|
||||
Some(transaction) => Ok(Json(transaction)),
|
||||
None => Err(AppError::NotFound),
|
||||
}
|
||||
Ok(Json(transaction.into()))
|
||||
}
|
||||
|
||||
#[axum::debug_handler]
|
||||
@@ -66,22 +54,14 @@ async fn put_transaction(
|
||||
Path(id): Path<Uuid>,
|
||||
Json(transaction): Json<TransactionData>,
|
||||
) -> Result<(StatusCode, Json<Transaction>), AppError> {
|
||||
let transaction = ValidatedTransaction::try_from(transaction)?;
|
||||
let transaction = TransactionRow {
|
||||
id,
|
||||
description: transaction.description,
|
||||
amount_cents: transaction.amount_cents,
|
||||
direction: transaction.direction.as_str().to_owned(),
|
||||
date: transaction.date,
|
||||
let transaction = transaction.into_domain(id)?;
|
||||
|
||||
let (status, transaction) = match repository::upsert(&pool, transaction).await? {
|
||||
Upsert::Created(transaction) => (StatusCode::CREATED, transaction),
|
||||
Upsert::Updated(transaction) => (StatusCode::OK, transaction),
|
||||
};
|
||||
|
||||
let (status, row) = match upsert_transaction(&pool, transaction).await? {
|
||||
Upsert::Created(row) => (StatusCode::CREATED, row),
|
||||
Upsert::Updated(row) => (StatusCode::OK, row),
|
||||
};
|
||||
let transaction = Transaction::try_from(row)?;
|
||||
|
||||
Ok((status, Json(transaction)))
|
||||
Ok((status, Json(transaction.into())))
|
||||
}
|
||||
|
||||
#[axum::debug_handler]
|
||||
@@ -90,7 +70,7 @@ async fn delete_transaction(
|
||||
Path(id): Path<Uuid>,
|
||||
State(pool): State<PgPool>,
|
||||
) -> Result<StatusCode, AppError> {
|
||||
match delete_transaction_by_id(&pool, id).await? {
|
||||
match repository::delete(&pool, id).await? {
|
||||
Delete::Deleted => Ok(StatusCode::NO_CONTENT),
|
||||
Delete::NotFound => Err(AppError::NotFound),
|
||||
}
|
||||
|
||||
@@ -1,2 +0,0 @@
|
||||
pub mod recurring_transaction;
|
||||
pub mod transaction;
|
||||
@@ -1,165 +0,0 @@
|
||||
use chrono::{DateTime, Utc};
|
||||
|
||||
use crate::routes::dtos::{
|
||||
cents::CentsConversionError,
|
||||
direction::Direction,
|
||||
scheduled_transaction::{RecurrenceUnit, RecurringTransactionData, WeekendAdjustment},
|
||||
};
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct ValidatedRecurringTransaction {
|
||||
pub name: String,
|
||||
pub amount_cents: i64,
|
||||
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_cents.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 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, thiserror::Error)]
|
||||
pub enum ScheduledTransactionValidationError {
|
||||
#[error(transparent)]
|
||||
Cents(#[from] CentsConversionError),
|
||||
|
||||
#[error("recurrence every must be between 1 and {}: {}", i32::MAX, .0)]
|
||||
RecurrenceEvery(u32),
|
||||
|
||||
#[error("end must not be before start")]
|
||||
EndBeforeStart,
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use chrono::{TimeZone, Utc};
|
||||
|
||||
use super::{
|
||||
PositiveRecurrenceInterval, ScheduledTransactionValidationError,
|
||||
ValidatedRecurringTransaction,
|
||||
};
|
||||
use crate::routes::dtos::{
|
||||
cents::CentsConversionError,
|
||||
direction::Direction,
|
||||
scheduled_transaction::{
|
||||
Recurrence, RecurrenceUnit, RecurringTransactionData, WeekendAdjustment,
|
||||
},
|
||||
};
|
||||
|
||||
fn transaction(amount_cents: u64) -> RecurringTransactionData {
|
||||
RecurringTransactionData {
|
||||
name: String::new(),
|
||||
amount_cents: amount_cents.into(),
|
||||
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(1234)).unwrap();
|
||||
assert_eq!(transaction.name, "");
|
||||
assert_eq!(transaction.amount_cents, 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_amounts_that_do_not_fit_in_database() {
|
||||
let error =
|
||||
ValidatedRecurringTransaction::try_from(transaction(i64::MAX as u64 + 1)).unwrap_err();
|
||||
assert!(matches!(
|
||||
error,
|
||||
ScheduledTransactionValidationError::Cents(CentsConversionError(value))
|
||||
if value == i64::MAX as i128 + 1
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn validates_date_ordering() {
|
||||
let mut invalid = transaction(100);
|
||||
invalid.end = Some(invalid.start - chrono::TimeDelta::seconds(1));
|
||||
assert!(matches!(
|
||||
ValidatedRecurringTransaction::try_from(invalid),
|
||||
Err(ScheduledTransactionValidationError::EndBeforeStart)
|
||||
));
|
||||
|
||||
let mut valid = transaction(100);
|
||||
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
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,69 +0,0 @@
|
||||
use chrono::{DateTime, Utc};
|
||||
|
||||
use crate::routes::dtos::{
|
||||
cents::CentsConversionError, direction::Direction, transaction::TransactionData,
|
||||
};
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct ValidatedTransaction {
|
||||
pub description: String,
|
||||
pub amount_cents: i64,
|
||||
pub direction: Direction,
|
||||
pub date: DateTime<Utc>,
|
||||
}
|
||||
|
||||
impl TryFrom<TransactionData> for ValidatedTransaction {
|
||||
type Error = TransactionValidationError;
|
||||
|
||||
fn try_from(transaction: TransactionData) -> Result<Self, Self::Error> {
|
||||
Ok(Self {
|
||||
description: transaction.description,
|
||||
amount_cents: transaction.amount_cents.try_into()?,
|
||||
direction: transaction.direction,
|
||||
date: transaction.date,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum TransactionValidationError {
|
||||
#[error(transparent)]
|
||||
Cents(#[from] CentsConversionError),
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use chrono::Utc;
|
||||
|
||||
use super::{TransactionValidationError, ValidatedTransaction};
|
||||
use crate::routes::dtos::{
|
||||
cents::CentsConversionError, direction::Direction, transaction::TransactionData,
|
||||
};
|
||||
|
||||
fn transaction(amount_cents: u64) -> TransactionData {
|
||||
TransactionData {
|
||||
description: "Groceries".to_string(),
|
||||
amount_cents: amount_cents.into(),
|
||||
direction: Direction::Out,
|
||||
date: Utc::now(),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn validates_and_preserves_typed_values() {
|
||||
let transaction = ValidatedTransaction::try_from(transaction(1234)).unwrap();
|
||||
assert_eq!(transaction.description, "Groceries");
|
||||
assert_eq!(transaction.amount_cents, 1234);
|
||||
assert!(matches!(transaction.direction, Direction::Out));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_amounts_that_do_not_fit_in_database() {
|
||||
let error = ValidatedTransaction::try_from(transaction(i64::MAX as u64 + 1)).unwrap_err();
|
||||
assert!(matches!(
|
||||
error,
|
||||
TransactionValidationError::Cents(CentsConversionError(value))
|
||||
if value == i64::MAX as i128 + 1
|
||||
));
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user