Implemented a domain layer, because the API DTO's where getting bloated.
This commit is contained in:
@@ -3,6 +3,15 @@ pub enum Upsert<T> {
|
||||
Updated(T),
|
||||
}
|
||||
|
||||
impl<T> Upsert<T> {
|
||||
pub fn try_map<U, E>(self, f: impl FnOnce(T) -> Result<U, E>) -> Result<Upsert<U>, E> {
|
||||
Ok(match self {
|
||||
Self::Created(value) => Upsert::Created(f(value)?),
|
||||
Self::Updated(value) => Upsert::Updated(f(value)?),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub enum Delete {
|
||||
Deleted,
|
||||
NotFound,
|
||||
|
||||
@@ -5,7 +5,7 @@ use crate::database::{
|
||||
dtos::recurring_transaction::RecurringTransactionRow,
|
||||
};
|
||||
|
||||
pub async fn query_scheduled_transactions<'e, E>(
|
||||
pub async fn query_recurring_transactions<'e, E>(
|
||||
executor: E,
|
||||
) -> Result<Vec<RecurringTransactionRow>, sqlx::Error>
|
||||
where
|
||||
@@ -32,7 +32,7 @@ where
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn get_scheduled_transaction_by_id<'e, E>(
|
||||
pub async fn get_recurring_transaction_by_id<'e, E>(
|
||||
executor: E,
|
||||
id: Uuid,
|
||||
) -> Result<Option<RecurringTransactionRow>, sqlx::Error>
|
||||
@@ -61,7 +61,7 @@ where
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn upsert_scheduled_transaction<'e, E>(
|
||||
pub async fn upsert_recurring_transaction<'e, E>(
|
||||
executor: E,
|
||||
transaction: RecurringTransactionRow,
|
||||
) -> Result<Upsert<RecurringTransactionRow>, sqlx::Error>
|
||||
@@ -135,7 +135,7 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn delete_scheduled_transaction_by_id<'e, E>(
|
||||
pub async fn delete_recurring_transaction_by_id<'e, E>(
|
||||
executor: E,
|
||||
id: Uuid,
|
||||
) -> Result<Delete, sqlx::Error>
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
mod cents;
|
||||
mod direction;
|
||||
mod recurring_transaction;
|
||||
mod schedule;
|
||||
mod transaction;
|
||||
|
||||
pub use cents::{Cents, CentsConversionError};
|
||||
pub use direction::Direction;
|
||||
pub use recurring_transaction::RecurringTransaction;
|
||||
pub use schedule::{
|
||||
Recurrence, RecurrenceInterval, RecurrenceIntervalError, RecurrenceUnit, Schedule,
|
||||
WeekendAdjustment,
|
||||
};
|
||||
pub use transaction::Transaction;
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum ValidationError {
|
||||
#[error(transparent)]
|
||||
Amount(#[from] CentsConversionError),
|
||||
|
||||
#[error(transparent)]
|
||||
RecurrenceInterval(#[from] RecurrenceIntervalError),
|
||||
|
||||
#[error("end must not be before start")]
|
||||
EndBeforeStart,
|
||||
}
|
||||
@@ -1,18 +1,20 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
|
||||
#[serde(transparent)]
|
||||
/// Non-negative amount in cents, bounded by `i64::MAX`.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct Cents(u64);
|
||||
|
||||
impl Cents {
|
||||
pub fn get(&self) -> u64 {
|
||||
pub fn get(self) -> u64 {
|
||||
self.0
|
||||
}
|
||||
}
|
||||
|
||||
impl From<u64> for Cents {
|
||||
fn from(value: u64) -> Self {
|
||||
Self(value)
|
||||
impl TryFrom<u64> for Cents {
|
||||
type Error = CentsConversionError;
|
||||
|
||||
fn try_from(value: u64) -> Result<Self, Self::Error> {
|
||||
i64::try_from(value)
|
||||
.map(|_| Self(value))
|
||||
.map_err(|_| CentsConversionError(value.into()))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -26,11 +28,9 @@ impl TryFrom<i64> for Cents {
|
||||
}
|
||||
}
|
||||
|
||||
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()))
|
||||
impl From<Cents> for i64 {
|
||||
fn from(value: Cents) -> Self {
|
||||
value.0 as i64
|
||||
}
|
||||
}
|
||||
|
||||
@@ -42,6 +42,23 @@ pub struct CentsConversionError(pub i128);
|
||||
mod tests {
|
||||
use super::{Cents, CentsConversionError};
|
||||
|
||||
#[test]
|
||||
fn accepts_amounts_up_to_i64_max() {
|
||||
assert_eq!(Cents::try_from(4250_u64).unwrap().get(), 4250);
|
||||
assert_eq!(
|
||||
i64::from(Cents::try_from(i64::MAX as u64).unwrap()),
|
||||
i64::MAX
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_amounts_above_i64_max() {
|
||||
assert!(matches!(
|
||||
Cents::try_from(i64::MAX as u64 + 1),
|
||||
Err(CentsConversionError(value)) if value == i64::MAX as i128 + 1
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn converts_non_negative_database_values() {
|
||||
assert_eq!(Cents::try_from(4250_i64).unwrap().get(), 4250);
|
||||
@@ -54,12 +71,4 @@ mod tests {
|
||||
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
|
||||
));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum Direction {
|
||||
In,
|
||||
Out,
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
use uuid::Uuid;
|
||||
|
||||
use super::{Cents, Direction, Schedule};
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct RecurringTransaction {
|
||||
pub id: Uuid,
|
||||
pub name: String,
|
||||
pub amount: Cents,
|
||||
pub direction: Direction,
|
||||
pub schedule: Schedule,
|
||||
}
|
||||
@@ -0,0 +1,332 @@
|
||||
use chrono::{DateTime, Datelike, Months, TimeDelta, Utc, Weekday};
|
||||
|
||||
use crate::domain::ValidationError;
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct Schedule {
|
||||
start: DateTime<Utc>,
|
||||
end: Option<DateTime<Utc>>,
|
||||
recurrence: Recurrence,
|
||||
}
|
||||
|
||||
impl Schedule {
|
||||
pub fn new(
|
||||
start: DateTime<Utc>,
|
||||
end: Option<DateTime<Utc>>,
|
||||
recurrence: Recurrence,
|
||||
) -> Result<Self, ValidationError> {
|
||||
if end.is_some_and(|end| end < start) {
|
||||
return Err(ValidationError::EndBeforeStart);
|
||||
}
|
||||
|
||||
Ok(Self {
|
||||
start,
|
||||
end,
|
||||
recurrence,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn start(&self) -> DateTime<Utc> {
|
||||
self.start
|
||||
}
|
||||
|
||||
pub fn end(&self) -> Option<DateTime<Utc>> {
|
||||
self.end
|
||||
}
|
||||
|
||||
pub fn recurrence(&self) -> Recurrence {
|
||||
self.recurrence
|
||||
}
|
||||
|
||||
/// First occurrence at or after `from`, or `None` once the schedule has ended.
|
||||
pub fn next_occurrence(&self, from: DateTime<Utc>) -> Option<DateTime<Utc>> {
|
||||
// Weekend adjustment can push a slightly earlier occurrence past `from`.
|
||||
let mut index = self.index_at(from).saturating_sub(3);
|
||||
|
||||
loop {
|
||||
let occurrence = self.occurrence(index)?;
|
||||
if self.end.is_some_and(|end| occurrence > end) {
|
||||
return None;
|
||||
}
|
||||
if occurrence >= from {
|
||||
return Some(occurrence);
|
||||
}
|
||||
index = index.checked_add(1)?;
|
||||
}
|
||||
}
|
||||
|
||||
fn occurrence(&self, index: u32) -> Option<DateTime<Utc>> {
|
||||
let Recurrence {
|
||||
every,
|
||||
unit,
|
||||
weekend_adjustment,
|
||||
} = self.recurrence;
|
||||
let steps = index.checked_mul(every.get())?;
|
||||
|
||||
let date = match unit {
|
||||
RecurrenceUnit::Day => TimeDelta::try_days(i64::from(steps))
|
||||
.and_then(|duration| self.start.checked_add_signed(duration)),
|
||||
RecurrenceUnit::Week => i64::from(steps)
|
||||
.checked_mul(7)
|
||||
.and_then(TimeDelta::try_days)
|
||||
.and_then(|duration| self.start.checked_add_signed(duration)),
|
||||
RecurrenceUnit::Month => self.start.checked_add_months(Months::new(steps)),
|
||||
RecurrenceUnit::Year => steps
|
||||
.checked_mul(12)
|
||||
.and_then(|months| self.start.checked_add_months(Months::new(months))),
|
||||
}?;
|
||||
|
||||
let day_delta = match (date.weekday(), weekend_adjustment) {
|
||||
(Weekday::Sat, Some(WeekendAdjustment::PreviousBusinessDay)) => -1,
|
||||
(Weekday::Sun, Some(WeekendAdjustment::PreviousBusinessDay)) => -2,
|
||||
(Weekday::Sat, Some(WeekendAdjustment::NextBusinessDay)) => 2,
|
||||
(Weekday::Sun, Some(WeekendAdjustment::NextBusinessDay)) => 1,
|
||||
_ => 0,
|
||||
};
|
||||
date.checked_add_signed(TimeDelta::days(day_delta))
|
||||
}
|
||||
|
||||
/// Estimated index of the last unadjusted occurrence at or before `at`.
|
||||
fn index_at(&self, at: DateTime<Utc>) -> u32 {
|
||||
let months = i64::from(at.year() - self.start.year()) * 12 + i64::from(at.month())
|
||||
- i64::from(self.start.month());
|
||||
let elapsed = match self.recurrence.unit {
|
||||
RecurrenceUnit::Day => (at - self.start).num_days(),
|
||||
RecurrenceUnit::Week => (at - self.start).num_weeks(),
|
||||
RecurrenceUnit::Month => months,
|
||||
RecurrenceUnit::Year => months / 12,
|
||||
};
|
||||
|
||||
u32::try_from(elapsed.max(0) / i64::from(self.recurrence.every.get())).unwrap_or(u32::MAX)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct Recurrence {
|
||||
pub every: RecurrenceInterval,
|
||||
pub unit: RecurrenceUnit,
|
||||
pub weekend_adjustment: Option<WeekendAdjustment>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct RecurrenceInterval(u32);
|
||||
|
||||
impl RecurrenceInterval {
|
||||
pub fn get(self) -> u32 {
|
||||
self.0
|
||||
}
|
||||
}
|
||||
|
||||
impl TryFrom<u32> for RecurrenceInterval {
|
||||
type Error = RecurrenceIntervalError;
|
||||
|
||||
fn try_from(value: u32) -> Result<Self, Self::Error> {
|
||||
if (1..=i32::MAX as u32).contains(&value) {
|
||||
Ok(Self(value))
|
||||
} else {
|
||||
Err(RecurrenceIntervalError(value.into()))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl TryFrom<i32> for RecurrenceInterval {
|
||||
type Error = RecurrenceIntervalError;
|
||||
|
||||
fn try_from(value: i32) -> Result<Self, Self::Error> {
|
||||
u32::try_from(value)
|
||||
.ok()
|
||||
.and_then(|value| Self::try_from(value).ok())
|
||||
.ok_or(RecurrenceIntervalError(value.into()))
|
||||
}
|
||||
}
|
||||
|
||||
impl From<RecurrenceInterval> for i32 {
|
||||
fn from(value: RecurrenceInterval) -> Self {
|
||||
value.0 as i32
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
#[error("recurrence every must be between 1 and {}: {}", i32::MAX, .0)]
|
||||
pub struct RecurrenceIntervalError(pub i64);
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum RecurrenceUnit {
|
||||
Day,
|
||||
Week,
|
||||
Month,
|
||||
Year,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum WeekendAdjustment {
|
||||
PreviousBusinessDay,
|
||||
NextBusinessDay,
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use chrono::{DateTime, TimeDelta, TimeZone, Utc};
|
||||
|
||||
use super::{
|
||||
Recurrence, RecurrenceInterval, RecurrenceIntervalError, RecurrenceUnit, Schedule,
|
||||
WeekendAdjustment,
|
||||
};
|
||||
use crate::domain::ValidationError;
|
||||
|
||||
fn recurrence(
|
||||
every: u32,
|
||||
unit: RecurrenceUnit,
|
||||
weekend_adjustment: Option<WeekendAdjustment>,
|
||||
) -> Recurrence {
|
||||
Recurrence {
|
||||
every: RecurrenceInterval::try_from(every).unwrap(),
|
||||
unit,
|
||||
weekend_adjustment,
|
||||
}
|
||||
}
|
||||
|
||||
fn at(year: i32, month: u32, day: u32, hour: u32) -> DateTime<Utc> {
|
||||
Utc.with_ymd_and_hms(year, month, day, hour, 0, 0).unwrap()
|
||||
}
|
||||
|
||||
fn next(
|
||||
start: DateTime<Utc>,
|
||||
end: Option<DateTime<Utc>>,
|
||||
recurrence: Recurrence,
|
||||
from: DateTime<Utc>,
|
||||
) -> Option<DateTime<Utc>> {
|
||||
Schedule::new(start, end, recurrence)
|
||||
.unwrap()
|
||||
.next_occurrence(from)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn starts_at_start_and_includes_exact_matches() {
|
||||
let start = at(2026, 9, 24, 12);
|
||||
let weekly = recurrence(1, RecurrenceUnit::Week, None);
|
||||
assert_eq!(next(start, None, weekly, at(2026, 1, 1, 0)), Some(start));
|
||||
assert_eq!(next(start, None, weekly, start), Some(start));
|
||||
assert_eq!(
|
||||
next(start, None, weekly, at(2026, 9, 25, 0)),
|
||||
Some(at(2026, 10, 1, 12))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn calculates_calendar_recurrences_without_drift() {
|
||||
let monthly = recurrence(1, RecurrenceUnit::Month, None);
|
||||
let start = at(2026, 1, 31, 12);
|
||||
assert_eq!(
|
||||
next(start, None, monthly, at(2026, 2, 1, 0)),
|
||||
Some(at(2026, 2, 28, 12))
|
||||
);
|
||||
assert_eq!(
|
||||
next(start, None, monthly, at(2026, 3, 1, 0)),
|
||||
Some(at(2026, 3, 31, 12))
|
||||
);
|
||||
|
||||
let yearly = recurrence(1, RecurrenceUnit::Year, None);
|
||||
let start = at(2024, 2, 29, 12);
|
||||
assert_eq!(
|
||||
next(start, None, yearly, at(2024, 3, 1, 0)),
|
||||
Some(at(2025, 2, 28, 12))
|
||||
);
|
||||
assert_eq!(
|
||||
next(start, None, yearly, at(2027, 3, 1, 0)),
|
||||
Some(at(2028, 2, 29, 12))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn adjusts_weekends_and_respects_end_date() {
|
||||
let start = at(2026, 9, 24, 12);
|
||||
let from = at(2026, 9, 25, 0);
|
||||
|
||||
let next_business_day = recurrence(
|
||||
2,
|
||||
RecurrenceUnit::Day,
|
||||
Some(WeekendAdjustment::NextBusinessDay),
|
||||
);
|
||||
assert_eq!(
|
||||
next(start, None, next_business_day, from),
|
||||
Some(at(2026, 9, 28, 12))
|
||||
);
|
||||
assert_eq!(
|
||||
next(start, Some(at(2026, 9, 27, 12)), next_business_day, from),
|
||||
None
|
||||
);
|
||||
|
||||
let previous_business_day = recurrence(
|
||||
2,
|
||||
RecurrenceUnit::Day,
|
||||
Some(WeekendAdjustment::PreviousBusinessDay),
|
||||
);
|
||||
assert_eq!(
|
||||
next(start, None, previous_business_day, from),
|
||||
Some(at(2026, 9, 25, 12))
|
||||
);
|
||||
|
||||
// Saturday Feb 28 shifts to Mar 2 without moving March's occurrence.
|
||||
let monthly = recurrence(
|
||||
1,
|
||||
RecurrenceUnit::Month,
|
||||
Some(WeekendAdjustment::NextBusinessDay),
|
||||
);
|
||||
let start = at(2026, 1, 30, 12);
|
||||
assert_eq!(
|
||||
next(start, None, monthly, at(2026, 3, 1, 0)),
|
||||
Some(at(2026, 3, 2, 12))
|
||||
);
|
||||
assert_eq!(
|
||||
next(start, None, monthly, at(2026, 3, 3, 0)),
|
||||
Some(at(2026, 3, 30, 12))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn finds_adjusted_occurrences_that_land_after_from() {
|
||||
let daily = recurrence(
|
||||
1,
|
||||
RecurrenceUnit::Day,
|
||||
Some(WeekendAdjustment::NextBusinessDay),
|
||||
);
|
||||
assert_eq!(
|
||||
next(at(2026, 9, 21, 12), None, daily, at(2026, 9, 27, 13)),
|
||||
Some(at(2026, 9, 28, 12))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn validates_date_ordering() {
|
||||
let start = Utc.with_ymd_and_hms(2026, 9, 24, 12, 0, 0).unwrap();
|
||||
let recurrence = recurrence(1, RecurrenceUnit::Month, None);
|
||||
|
||||
assert!(matches!(
|
||||
Schedule::new(start, Some(start - TimeDelta::seconds(1)), recurrence),
|
||||
Err(ValidationError::EndBeforeStart)
|
||||
));
|
||||
assert!(Schedule::new(start, Some(start), recurrence).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_invalid_recurrence_ranges() {
|
||||
assert_eq!(RecurrenceInterval::try_from(1_u32).unwrap().get(), 1);
|
||||
assert_eq!(
|
||||
i32::from(RecurrenceInterval::try_from(i32::MAX as u32).unwrap()),
|
||||
i32::MAX
|
||||
);
|
||||
for every in [0, i32::MAX as u32 + 1] {
|
||||
assert!(matches!(
|
||||
RecurrenceInterval::try_from(every),
|
||||
Err(RecurrenceIntervalError(value)) if value == i64::from(every)
|
||||
));
|
||||
}
|
||||
for every in [0_i32, -1] {
|
||||
assert!(matches!(
|
||||
RecurrenceInterval::try_from(every),
|
||||
Err(RecurrenceIntervalError(value)) if value == i64::from(every)
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
use chrono::{DateTime, Utc};
|
||||
use uuid::Uuid;
|
||||
|
||||
use super::{Cents, Direction};
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct Transaction {
|
||||
pub id: Uuid,
|
||||
pub description: String,
|
||||
pub amount: Cents,
|
||||
pub direction: Direction,
|
||||
pub date: DateTime<Utc>,
|
||||
}
|
||||
+9
-40
@@ -3,17 +3,7 @@ use axum::{
|
||||
response::{IntoResponse, Response},
|
||||
};
|
||||
|
||||
use crate::routes::{
|
||||
dtos::{
|
||||
direction::DirectionConversionError,
|
||||
scheduled_transaction::RecurringTransactionConversionError,
|
||||
transaction::TransactionConversionError,
|
||||
},
|
||||
validation::{
|
||||
recurring_transaction::ScheduledTransactionValidationError,
|
||||
transaction::TransactionValidationError,
|
||||
},
|
||||
};
|
||||
use crate::{domain::ValidationError, repository::RepositoryError};
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum AppError {
|
||||
@@ -23,23 +13,11 @@ pub enum AppError {
|
||||
#[error("not found")]
|
||||
NotFound,
|
||||
|
||||
#[error("database error")]
|
||||
Database(#[from] sqlx::Error),
|
||||
#[error("repository error")]
|
||||
Repository(#[from] RepositoryError),
|
||||
|
||||
#[error("direction conversion error")]
|
||||
Direction(#[from] DirectionConversionError),
|
||||
|
||||
#[error("recurring transaction conversion error")]
|
||||
RecurringTransaction(#[from] RecurringTransactionConversionError),
|
||||
|
||||
#[error("transaction conversion error")]
|
||||
Transaction(#[from] TransactionConversionError),
|
||||
|
||||
#[error("scheduled transaction validation error")]
|
||||
ScheduledTransactionValidation(#[from] ScheduledTransactionValidationError),
|
||||
|
||||
#[error("transaction validation error")]
|
||||
TransactionValidation(#[from] TransactionValidationError),
|
||||
#[error("validation error")]
|
||||
Validation(#[from] ValidationError),
|
||||
}
|
||||
|
||||
impl IntoResponse for AppError {
|
||||
@@ -51,23 +29,14 @@ impl IntoResponse for AppError {
|
||||
Self::NotFound => {
|
||||
return error_response(StatusCode::NOT_FOUND, "Not found");
|
||||
}
|
||||
Self::ScheduledTransactionValidation(error) => {
|
||||
Self::Validation(error) => {
|
||||
return error_response(StatusCode::UNPROCESSABLE_ENTITY, error.to_string());
|
||||
}
|
||||
Self::TransactionValidation(error) => {
|
||||
return error_response(StatusCode::UNPROCESSABLE_ENTITY, error.to_string());
|
||||
}
|
||||
Self::Database(error) => {
|
||||
Self::Repository(RepositoryError::Database(error)) => {
|
||||
tracing::error!(%error, "Database query failed");
|
||||
}
|
||||
Self::Direction(error) => {
|
||||
tracing::error!(%error, "Invalid transaction direction")
|
||||
}
|
||||
Self::RecurringTransaction(error) => {
|
||||
tracing::error!(%error, "Invalid recurring transaction data")
|
||||
}
|
||||
Self::Transaction(error) => {
|
||||
tracing::error!(%error, "Invalid transaction data");
|
||||
Self::Repository(RepositoryError::Decode(error)) => {
|
||||
tracing::error!(%error, "Invalid stored data");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -5,7 +5,9 @@ use sqlx::postgres::PgPoolOptions;
|
||||
use tokio::net::TcpListener;
|
||||
|
||||
mod database;
|
||||
mod domain;
|
||||
mod error;
|
||||
mod repository;
|
||||
mod routes;
|
||||
|
||||
#[tokio::main]
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
mod encoding;
|
||||
pub mod recurring_transactions;
|
||||
pub mod transactions;
|
||||
|
||||
pub use crate::database::common::{Delete, Upsert};
|
||||
use crate::domain::{CentsConversionError, RecurrenceIntervalError, ValidationError};
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum RepositoryError {
|
||||
#[error(transparent)]
|
||||
Database(#[from] sqlx::Error),
|
||||
|
||||
#[error(transparent)]
|
||||
Decode(#[from] DecodeError),
|
||||
}
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum DecodeError {
|
||||
#[error(transparent)]
|
||||
Amount(#[from] CentsConversionError),
|
||||
|
||||
#[error(transparent)]
|
||||
RecurrenceInterval(#[from] RecurrenceIntervalError),
|
||||
|
||||
#[error(transparent)]
|
||||
Invalid(#[from] ValidationError),
|
||||
|
||||
#[error("invalid direction value: {0}")]
|
||||
Direction(String),
|
||||
|
||||
#[error("invalid recurrence_unit value: {0}")]
|
||||
RecurrenceUnit(String),
|
||||
|
||||
#[error("invalid weekend_adjustment value: {0}")]
|
||||
WeekendAdjustment(String),
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -4,7 +4,6 @@ pub mod dtos;
|
||||
pub mod extractors;
|
||||
pub mod scheduled_transactions;
|
||||
pub mod transactions;
|
||||
pub mod validation;
|
||||
|
||||
pub fn create_router(pool: sqlx::PgPool) -> axum::Router {
|
||||
axum::Router::new()
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
pub mod cents;
|
||||
pub mod direction;
|
||||
pub mod scheduled_transaction;
|
||||
pub mod transaction;
|
||||
|
||||
@@ -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,
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum TransactionConversionError {
|
||||
#[error(transparent)]
|
||||
Cents(#[from] CentsConversionError),
|
||||
|
||||
#[error(transparent)]
|
||||
Direction(#[from] DirectionConversionError),
|
||||
}
|
||||
|
||||
#[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