Implemented a domain layer, because the API DTO's where getting bloated.
This commit is contained in:
@@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user