Implemented a domain layer, because the API DTO's where getting bloated.
This commit is contained in:
@@ -0,0 +1,96 @@
|
||||
use super::DecodeError;
|
||||
use crate::domain::{Direction, RecurrenceUnit, WeekendAdjustment};
|
||||
|
||||
pub fn encode_direction(direction: Direction) -> &'static str {
|
||||
match direction {
|
||||
Direction::In => "in",
|
||||
Direction::Out => "out",
|
||||
}
|
||||
}
|
||||
|
||||
pub fn decode_direction(value: String) -> Result<Direction, DecodeError> {
|
||||
match value.as_str() {
|
||||
"in" => Ok(Direction::In),
|
||||
"out" => Ok(Direction::Out),
|
||||
_ => Err(DecodeError::Direction(value)),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn encode_recurrence_unit(unit: RecurrenceUnit) -> &'static str {
|
||||
match unit {
|
||||
RecurrenceUnit::Day => "day",
|
||||
RecurrenceUnit::Week => "week",
|
||||
RecurrenceUnit::Month => "month",
|
||||
RecurrenceUnit::Year => "year",
|
||||
}
|
||||
}
|
||||
|
||||
pub fn decode_recurrence_unit(value: String) -> Result<RecurrenceUnit, DecodeError> {
|
||||
match value.as_str() {
|
||||
"day" => Ok(RecurrenceUnit::Day),
|
||||
"week" => Ok(RecurrenceUnit::Week),
|
||||
"month" => Ok(RecurrenceUnit::Month),
|
||||
"year" => Ok(RecurrenceUnit::Year),
|
||||
_ => Err(DecodeError::RecurrenceUnit(value)),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn encode_weekend_adjustment(adjustment: WeekendAdjustment) -> &'static str {
|
||||
match adjustment {
|
||||
WeekendAdjustment::PreviousBusinessDay => "previous_business_day",
|
||||
WeekendAdjustment::NextBusinessDay => "next_business_day",
|
||||
}
|
||||
}
|
||||
|
||||
pub fn decode_weekend_adjustment(value: String) -> Result<WeekendAdjustment, DecodeError> {
|
||||
match value.as_str() {
|
||||
"previous_business_day" => Ok(WeekendAdjustment::PreviousBusinessDay),
|
||||
"next_business_day" => Ok(WeekendAdjustment::NextBusinessDay),
|
||||
_ => Err(DecodeError::WeekendAdjustment(value)),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn round_trips_all_variants() {
|
||||
for direction in [Direction::In, Direction::Out] {
|
||||
let encoded = encode_direction(direction).to_owned();
|
||||
assert_eq!(decode_direction(encoded).unwrap(), direction);
|
||||
}
|
||||
for unit in [
|
||||
RecurrenceUnit::Day,
|
||||
RecurrenceUnit::Week,
|
||||
RecurrenceUnit::Month,
|
||||
RecurrenceUnit::Year,
|
||||
] {
|
||||
let encoded = encode_recurrence_unit(unit).to_owned();
|
||||
assert_eq!(decode_recurrence_unit(encoded).unwrap(), unit);
|
||||
}
|
||||
for adjustment in [
|
||||
WeekendAdjustment::PreviousBusinessDay,
|
||||
WeekendAdjustment::NextBusinessDay,
|
||||
] {
|
||||
let encoded = encode_weekend_adjustment(adjustment).to_owned();
|
||||
assert_eq!(decode_weekend_adjustment(encoded).unwrap(), adjustment);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_unknown_values() {
|
||||
assert!(matches!(
|
||||
decode_direction("sideways".to_owned()),
|
||||
Err(DecodeError::Direction(value)) if value == "sideways"
|
||||
));
|
||||
assert!(matches!(
|
||||
decode_recurrence_unit("hour".to_owned()),
|
||||
Err(DecodeError::RecurrenceUnit(value)) if value == "hour"
|
||||
));
|
||||
assert!(matches!(
|
||||
decode_weekend_adjustment("never".to_owned()),
|
||||
Err(DecodeError::WeekendAdjustment(value)) if value == "never"
|
||||
));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,172 @@
|
||||
use uuid::Uuid;
|
||||
|
||||
use super::{
|
||||
DecodeError, Delete, RepositoryError, Upsert,
|
||||
encoding::{
|
||||
decode_direction, decode_recurrence_unit, decode_weekend_adjustment, encode_direction,
|
||||
encode_recurrence_unit, encode_weekend_adjustment,
|
||||
},
|
||||
};
|
||||
use crate::{
|
||||
database::{
|
||||
dtos::recurring_transaction::RecurringTransactionRow, recurring_transactions as db,
|
||||
},
|
||||
domain::{Cents, Recurrence, RecurrenceInterval, RecurringTransaction, Schedule},
|
||||
};
|
||||
|
||||
pub async fn list<'e, E>(executor: E) -> Result<Vec<RecurringTransaction>, RepositoryError>
|
||||
where
|
||||
E: sqlx::Executor<'e, Database = sqlx::Postgres>,
|
||||
{
|
||||
let transactions = db::query_recurring_transactions(executor)
|
||||
.await?
|
||||
.into_iter()
|
||||
.map(decode)
|
||||
.collect::<Result<_, DecodeError>>()?;
|
||||
|
||||
Ok(transactions)
|
||||
}
|
||||
|
||||
pub async fn get<'e, E>(
|
||||
executor: E,
|
||||
id: Uuid,
|
||||
) -> Result<Option<RecurringTransaction>, RepositoryError>
|
||||
where
|
||||
E: sqlx::Executor<'e, Database = sqlx::Postgres>,
|
||||
{
|
||||
let transaction = db::get_recurring_transaction_by_id(executor, id)
|
||||
.await?
|
||||
.map(decode)
|
||||
.transpose()?;
|
||||
|
||||
Ok(transaction)
|
||||
}
|
||||
|
||||
pub async fn upsert<'e, E>(
|
||||
executor: E,
|
||||
transaction: RecurringTransaction,
|
||||
) -> Result<Upsert<RecurringTransaction>, RepositoryError>
|
||||
where
|
||||
E: sqlx::Executor<'e, Database = sqlx::Postgres>,
|
||||
{
|
||||
let transaction = db::upsert_recurring_transaction(executor, encode(transaction))
|
||||
.await?
|
||||
.try_map(decode)?;
|
||||
|
||||
Ok(transaction)
|
||||
}
|
||||
|
||||
pub async fn delete<'e, E>(executor: E, id: Uuid) -> Result<Delete, RepositoryError>
|
||||
where
|
||||
E: sqlx::Executor<'e, Database = sqlx::Postgres>,
|
||||
{
|
||||
Ok(db::delete_recurring_transaction_by_id(executor, id).await?)
|
||||
}
|
||||
|
||||
fn decode(row: RecurringTransactionRow) -> Result<RecurringTransaction, DecodeError> {
|
||||
let recurrence = Recurrence {
|
||||
every: RecurrenceInterval::try_from(row.recurrence_every)?,
|
||||
unit: decode_recurrence_unit(row.recurrence_unit)?,
|
||||
weekend_adjustment: row
|
||||
.weekend_adjustment
|
||||
.map(decode_weekend_adjustment)
|
||||
.transpose()?,
|
||||
};
|
||||
|
||||
Ok(RecurringTransaction {
|
||||
id: row.id,
|
||||
name: row.name,
|
||||
amount: Cents::try_from(row.amount_cents)?,
|
||||
direction: decode_direction(row.direction)?,
|
||||
schedule: Schedule::new(row.starts_at, row.ends_at, recurrence)?,
|
||||
})
|
||||
}
|
||||
|
||||
fn encode(transaction: RecurringTransaction) -> RecurringTransactionRow {
|
||||
let recurrence = transaction.schedule.recurrence();
|
||||
|
||||
RecurringTransactionRow {
|
||||
id: transaction.id,
|
||||
name: transaction.name,
|
||||
amount_cents: transaction.amount.into(),
|
||||
direction: encode_direction(transaction.direction).to_owned(),
|
||||
starts_at: transaction.schedule.start(),
|
||||
ends_at: transaction.schedule.end(),
|
||||
recurrence_every: recurrence.every.into(),
|
||||
recurrence_unit: encode_recurrence_unit(recurrence.unit).to_owned(),
|
||||
weekend_adjustment: recurrence
|
||||
.weekend_adjustment
|
||||
.map(|adjustment| encode_weekend_adjustment(adjustment).to_owned()),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use chrono::{TimeDelta, TimeZone, Utc};
|
||||
use uuid::Uuid;
|
||||
|
||||
use super::*;
|
||||
use crate::domain::{Direction, RecurrenceUnit, ValidationError, WeekendAdjustment};
|
||||
|
||||
fn row() -> RecurringTransactionRow {
|
||||
RecurringTransactionRow {
|
||||
id: Uuid::new_v4(),
|
||||
name: "Rent".to_owned(),
|
||||
amount_cents: 120_000,
|
||||
direction: "out".to_owned(),
|
||||
starts_at: Utc.with_ymd_and_hms(2026, 9, 24, 12, 0, 0).unwrap(),
|
||||
ends_at: None,
|
||||
recurrence_every: 1,
|
||||
recurrence_unit: "month".to_owned(),
|
||||
weekend_adjustment: Some("next_business_day".to_owned()),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decodes_valid_rows() {
|
||||
let row = row();
|
||||
let (id, start) = (row.id, row.starts_at);
|
||||
let transaction = decode(row).unwrap();
|
||||
let recurrence = transaction.schedule.recurrence();
|
||||
|
||||
assert_eq!(transaction.id, id);
|
||||
assert_eq!(transaction.name, "Rent");
|
||||
assert_eq!(transaction.amount.get(), 120_000);
|
||||
assert_eq!(transaction.direction, Direction::Out);
|
||||
assert_eq!(transaction.schedule.start(), start);
|
||||
assert_eq!(transaction.schedule.end(), None);
|
||||
assert_eq!(recurrence.every.get(), 1);
|
||||
assert_eq!(recurrence.unit, RecurrenceUnit::Month);
|
||||
assert_eq!(
|
||||
recurrence.weekend_adjustment,
|
||||
Some(WeekendAdjustment::NextBusinessDay)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_corrupt_rows() {
|
||||
let mut every = row();
|
||||
every.recurrence_every = 0;
|
||||
assert!(matches!(
|
||||
decode(every),
|
||||
Err(DecodeError::RecurrenceInterval(_))
|
||||
));
|
||||
|
||||
let mut unit = row();
|
||||
unit.recurrence_unit = "hour".to_owned();
|
||||
assert!(matches!(decode(unit), Err(DecodeError::RecurrenceUnit(_))));
|
||||
|
||||
let mut end = row();
|
||||
end.ends_at = Some(end.starts_at - TimeDelta::seconds(1));
|
||||
assert!(matches!(
|
||||
decode(end),
|
||||
Err(DecodeError::Invalid(ValidationError::EndBeforeStart))
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn round_trips_through_rows() {
|
||||
let transaction = decode(row()).unwrap();
|
||||
assert_eq!(decode(encode(transaction.clone())).unwrap(), transaction);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
use uuid::Uuid;
|
||||
|
||||
use super::{
|
||||
DecodeError, Delete, RepositoryError, Upsert,
|
||||
encoding::{decode_direction, encode_direction},
|
||||
};
|
||||
use crate::{
|
||||
database::{dtos::transaction::TransactionRow, transactions as db},
|
||||
domain::{Cents, Transaction},
|
||||
};
|
||||
|
||||
pub async fn list<'e, E>(executor: E) -> Result<Vec<Transaction>, RepositoryError>
|
||||
where
|
||||
E: sqlx::Executor<'e, Database = sqlx::Postgres>,
|
||||
{
|
||||
let transactions = db::query_transactions(executor)
|
||||
.await?
|
||||
.into_iter()
|
||||
.map(decode)
|
||||
.collect::<Result<_, DecodeError>>()?;
|
||||
|
||||
Ok(transactions)
|
||||
}
|
||||
|
||||
pub async fn get<'e, E>(executor: E, id: Uuid) -> Result<Option<Transaction>, RepositoryError>
|
||||
where
|
||||
E: sqlx::Executor<'e, Database = sqlx::Postgres>,
|
||||
{
|
||||
let transaction = db::get_transaction_by_id(executor, id)
|
||||
.await?
|
||||
.map(decode)
|
||||
.transpose()?;
|
||||
|
||||
Ok(transaction)
|
||||
}
|
||||
|
||||
pub async fn upsert<'e, E>(
|
||||
executor: E,
|
||||
transaction: Transaction,
|
||||
) -> Result<Upsert<Transaction>, RepositoryError>
|
||||
where
|
||||
E: sqlx::Executor<'e, Database = sqlx::Postgres>,
|
||||
{
|
||||
let transaction = db::upsert_transaction(executor, encode(transaction))
|
||||
.await?
|
||||
.try_map(decode)?;
|
||||
|
||||
Ok(transaction)
|
||||
}
|
||||
|
||||
pub async fn delete<'e, E>(executor: E, id: Uuid) -> Result<Delete, RepositoryError>
|
||||
where
|
||||
E: sqlx::Executor<'e, Database = sqlx::Postgres>,
|
||||
{
|
||||
Ok(db::delete_transaction_by_id(executor, id).await?)
|
||||
}
|
||||
|
||||
fn decode(row: TransactionRow) -> Result<Transaction, DecodeError> {
|
||||
Ok(Transaction {
|
||||
id: row.id,
|
||||
description: row.description,
|
||||
amount: Cents::try_from(row.amount_cents)?,
|
||||
direction: decode_direction(row.direction)?,
|
||||
date: row.date,
|
||||
})
|
||||
}
|
||||
|
||||
fn encode(transaction: Transaction) -> TransactionRow {
|
||||
TransactionRow {
|
||||
id: transaction.id,
|
||||
description: transaction.description,
|
||||
amount_cents: transaction.amount.into(),
|
||||
direction: encode_direction(transaction.direction).to_owned(),
|
||||
date: transaction.date,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use chrono::Utc;
|
||||
use uuid::Uuid;
|
||||
|
||||
use super::*;
|
||||
use crate::domain::Direction;
|
||||
|
||||
fn row() -> TransactionRow {
|
||||
TransactionRow {
|
||||
id: Uuid::new_v4(),
|
||||
description: "Groceries".to_owned(),
|
||||
amount_cents: 4250,
|
||||
direction: "out".to_owned(),
|
||||
date: Utc::now(),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decodes_valid_rows() {
|
||||
let row = row();
|
||||
let (id, date) = (row.id, row.date);
|
||||
let transaction = decode(row).unwrap();
|
||||
|
||||
assert_eq!(transaction.id, id);
|
||||
assert_eq!(transaction.description, "Groceries");
|
||||
assert_eq!(transaction.amount.get(), 4250);
|
||||
assert_eq!(transaction.direction, Direction::Out);
|
||||
assert_eq!(transaction.date, date);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_corrupt_rows() {
|
||||
let mut negative = row();
|
||||
negative.amount_cents = -1;
|
||||
assert!(matches!(decode(negative), Err(DecodeError::Amount(_))));
|
||||
|
||||
let mut direction = row();
|
||||
direction.direction = "sideways".to_owned();
|
||||
assert!(matches!(decode(direction), Err(DecodeError::Direction(_))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn round_trips_through_rows() {
|
||||
let transaction = decode(row()).unwrap();
|
||||
assert_eq!(decode(encode(transaction.clone())).unwrap(), transaction);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user