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),
|
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 {
|
pub enum Delete {
|
||||||
Deleted,
|
Deleted,
|
||||||
NotFound,
|
NotFound,
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ use crate::database::{
|
|||||||
dtos::recurring_transaction::RecurringTransactionRow,
|
dtos::recurring_transaction::RecurringTransactionRow,
|
||||||
};
|
};
|
||||||
|
|
||||||
pub async fn query_scheduled_transactions<'e, E>(
|
pub async fn query_recurring_transactions<'e, E>(
|
||||||
executor: E,
|
executor: E,
|
||||||
) -> Result<Vec<RecurringTransactionRow>, sqlx::Error>
|
) -> Result<Vec<RecurringTransactionRow>, sqlx::Error>
|
||||||
where
|
where
|
||||||
@@ -32,7 +32,7 @@ where
|
|||||||
.await
|
.await
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn get_scheduled_transaction_by_id<'e, E>(
|
pub async fn get_recurring_transaction_by_id<'e, E>(
|
||||||
executor: E,
|
executor: E,
|
||||||
id: Uuid,
|
id: Uuid,
|
||||||
) -> Result<Option<RecurringTransactionRow>, sqlx::Error>
|
) -> Result<Option<RecurringTransactionRow>, sqlx::Error>
|
||||||
@@ -61,7 +61,7 @@ where
|
|||||||
.await
|
.await
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn upsert_scheduled_transaction<'e, E>(
|
pub async fn upsert_recurring_transaction<'e, E>(
|
||||||
executor: E,
|
executor: E,
|
||||||
transaction: RecurringTransactionRow,
|
transaction: RecurringTransactionRow,
|
||||||
) -> Result<Upsert<RecurringTransactionRow>, sqlx::Error>
|
) -> 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,
|
executor: E,
|
||||||
id: Uuid,
|
id: Uuid,
|
||||||
) -> Result<Delete, sqlx::Error>
|
) -> 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};
|
/// Non-negative amount in cents, bounded by `i64::MAX`.
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
|
|
||||||
#[serde(transparent)]
|
|
||||||
pub struct Cents(u64);
|
pub struct Cents(u64);
|
||||||
|
|
||||||
impl Cents {
|
impl Cents {
|
||||||
pub fn get(&self) -> u64 {
|
pub fn get(self) -> u64 {
|
||||||
self.0
|
self.0
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl From<u64> for Cents {
|
impl TryFrom<u64> for Cents {
|
||||||
fn from(value: u64) -> Self {
|
type Error = CentsConversionError;
|
||||||
Self(value)
|
|
||||||
|
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 {
|
impl From<Cents> for i64 {
|
||||||
type Error = CentsConversionError;
|
fn from(value: Cents) -> Self {
|
||||||
|
value.0 as i64
|
||||||
fn try_from(value: Cents) -> Result<Self, Self::Error> {
|
|
||||||
i64::try_from(value.get()).map_err(|_| CentsConversionError(value.get().into()))
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -42,6 +42,23 @@ pub struct CentsConversionError(pub i128);
|
|||||||
mod tests {
|
mod tests {
|
||||||
use super::{Cents, CentsConversionError};
|
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]
|
#[test]
|
||||||
fn converts_non_negative_database_values() {
|
fn converts_non_negative_database_values() {
|
||||||
assert_eq!(Cents::try_from(4250_i64).unwrap().get(), 4250);
|
assert_eq!(Cents::try_from(4250_i64).unwrap().get(), 4250);
|
||||||
@@ -54,12 +71,4 @@ mod tests {
|
|||||||
Err(CentsConversionError(-1_i128))
|
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},
|
response::{IntoResponse, Response},
|
||||||
};
|
};
|
||||||
|
|
||||||
use crate::routes::{
|
use crate::{domain::ValidationError, repository::RepositoryError};
|
||||||
dtos::{
|
|
||||||
direction::DirectionConversionError,
|
|
||||||
scheduled_transaction::RecurringTransactionConversionError,
|
|
||||||
transaction::TransactionConversionError,
|
|
||||||
},
|
|
||||||
validation::{
|
|
||||||
recurring_transaction::ScheduledTransactionValidationError,
|
|
||||||
transaction::TransactionValidationError,
|
|
||||||
},
|
|
||||||
};
|
|
||||||
|
|
||||||
#[derive(Debug, thiserror::Error)]
|
#[derive(Debug, thiserror::Error)]
|
||||||
pub enum AppError {
|
pub enum AppError {
|
||||||
@@ -23,23 +13,11 @@ pub enum AppError {
|
|||||||
#[error("not found")]
|
#[error("not found")]
|
||||||
NotFound,
|
NotFound,
|
||||||
|
|
||||||
#[error("database error")]
|
#[error("repository error")]
|
||||||
Database(#[from] sqlx::Error),
|
Repository(#[from] RepositoryError),
|
||||||
|
|
||||||
#[error("direction conversion error")]
|
#[error("validation error")]
|
||||||
Direction(#[from] DirectionConversionError),
|
Validation(#[from] ValidationError),
|
||||||
|
|
||||||
#[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),
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl IntoResponse for AppError {
|
impl IntoResponse for AppError {
|
||||||
@@ -51,23 +29,14 @@ impl IntoResponse for AppError {
|
|||||||
Self::NotFound => {
|
Self::NotFound => {
|
||||||
return error_response(StatusCode::NOT_FOUND, "Not found");
|
return error_response(StatusCode::NOT_FOUND, "Not found");
|
||||||
}
|
}
|
||||||
Self::ScheduledTransactionValidation(error) => {
|
Self::Validation(error) => {
|
||||||
return error_response(StatusCode::UNPROCESSABLE_ENTITY, error.to_string());
|
return error_response(StatusCode::UNPROCESSABLE_ENTITY, error.to_string());
|
||||||
}
|
}
|
||||||
Self::TransactionValidation(error) => {
|
Self::Repository(RepositoryError::Database(error)) => {
|
||||||
return error_response(StatusCode::UNPROCESSABLE_ENTITY, error.to_string());
|
|
||||||
}
|
|
||||||
Self::Database(error) => {
|
|
||||||
tracing::error!(%error, "Database query failed");
|
tracing::error!(%error, "Database query failed");
|
||||||
}
|
}
|
||||||
Self::Direction(error) => {
|
Self::Repository(RepositoryError::Decode(error)) => {
|
||||||
tracing::error!(%error, "Invalid transaction direction")
|
tracing::error!(%error, "Invalid stored data");
|
||||||
}
|
|
||||||
Self::RecurringTransaction(error) => {
|
|
||||||
tracing::error!(%error, "Invalid recurring transaction data")
|
|
||||||
}
|
|
||||||
Self::Transaction(error) => {
|
|
||||||
tracing::error!(%error, "Invalid transaction data");
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -5,7 +5,9 @@ use sqlx::postgres::PgPoolOptions;
|
|||||||
use tokio::net::TcpListener;
|
use tokio::net::TcpListener;
|
||||||
|
|
||||||
mod database;
|
mod database;
|
||||||
|
mod domain;
|
||||||
mod error;
|
mod error;
|
||||||
|
mod repository;
|
||||||
mod routes;
|
mod routes;
|
||||||
|
|
||||||
#[tokio::main]
|
#[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 extractors;
|
||||||
pub mod scheduled_transactions;
|
pub mod scheduled_transactions;
|
||||||
pub mod transactions;
|
pub mod transactions;
|
||||||
pub mod validation;
|
|
||||||
|
|
||||||
pub fn create_router(pool: sqlx::PgPool) -> axum::Router {
|
pub fn create_router(pool: sqlx::PgPool) -> axum::Router {
|
||||||
axum::Router::new()
|
axum::Router::new()
|
||||||
|
|||||||
@@ -1,4 +1,3 @@
|
|||||||
pub mod cents;
|
|
||||||
pub mod direction;
|
pub mod direction;
|
||||||
pub mod scheduled_transaction;
|
pub mod scheduled_transaction;
|
||||||
pub mod transaction;
|
pub mod transaction;
|
||||||
|
|||||||
@@ -1,33 +1,28 @@
|
|||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
use crate::domain;
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
|
||||||
#[serde(rename_all = "snake_case")]
|
#[serde(rename_all = "snake_case")]
|
||||||
pub enum Direction {
|
pub enum Direction {
|
||||||
In,
|
In,
|
||||||
Out,
|
Out,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Direction {
|
impl From<Direction> for domain::Direction {
|
||||||
pub fn as_str(&self) -> &'static str {
|
fn from(direction: Direction) -> Self {
|
||||||
match self {
|
match direction {
|
||||||
Self::In => "in",
|
Direction::In => Self::In,
|
||||||
Self::Out => "out",
|
Direction::Out => Self::Out,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl TryFrom<String> for Direction {
|
impl From<domain::Direction> for Direction {
|
||||||
type Error = DirectionConversionError;
|
fn from(direction: domain::Direction) -> Self {
|
||||||
|
match direction {
|
||||||
fn try_from(value: String) -> Result<Self, Self::Error> {
|
domain::Direction::In => Self::In,
|
||||||
match value.as_str() {
|
domain::Direction::Out => Self::Out,
|
||||||
"in" => Ok(Self::In),
|
|
||||||
"out" => Ok(Self::Out),
|
|
||||||
_ => Err(DirectionConversionError(value)),
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[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 serde::{Deserialize, Serialize};
|
||||||
use uuid::Uuid;
|
use uuid::Uuid;
|
||||||
|
|
||||||
use crate::{
|
use crate::{domain, routes::dtos::direction::Direction};
|
||||||
database::dtos::recurring_transaction::RecurringTransactionRow,
|
|
||||||
routes::dtos::{
|
|
||||||
cents::{Cents, CentsConversionError},
|
|
||||||
direction::{Direction, DirectionConversionError},
|
|
||||||
},
|
|
||||||
};
|
|
||||||
|
|
||||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
#[derive(Debug, Clone, Serialize)]
|
||||||
#[serde(rename_all = "snake_case")]
|
#[serde(rename_all = "snake_case")]
|
||||||
#[serde(tag = "type")]
|
#[serde(tag = "type")]
|
||||||
pub enum ScheduledTransaction {
|
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 struct RecurringTransaction {
|
||||||
pub id: Uuid,
|
pub id: Uuid,
|
||||||
|
|
||||||
#[serde(flatten)]
|
#[serde(flatten)]
|
||||||
pub data: RecurringTransactionData,
|
pub data: RecurringTransactionData,
|
||||||
|
|
||||||
|
/// The next scheduled occurrence of the transaction.
|
||||||
|
pub next: Option<DateTime<Utc>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl TryFrom<RecurringTransactionRow> for RecurringTransaction {
|
impl RecurringTransaction {
|
||||||
type Error = RecurringTransactionConversionError;
|
pub fn new(transaction: domain::RecurringTransaction, next: Option<DateTime<Utc>>) -> Self {
|
||||||
|
Self {
|
||||||
fn try_from(row: RecurringTransactionRow) -> Result<Self, Self::Error> {
|
id: transaction.id,
|
||||||
Ok(Self {
|
next,
|
||||||
id: row.id,
|
|
||||||
data: RecurringTransactionData {
|
data: RecurringTransactionData {
|
||||||
name: row.name,
|
name: transaction.name,
|
||||||
amount_cents: Cents::try_from(row.amount_cents)?,
|
amount_cents: transaction.amount.get(),
|
||||||
direction: Direction::try_from(row.direction)
|
direction: transaction.direction.into(),
|
||||||
.map_err(RecurringTransactionConversionError::Direction)?,
|
start: transaction.schedule.start(),
|
||||||
start: row.starts_at,
|
end: transaction.schedule.end(),
|
||||||
end: row.ends_at,
|
recurrence: transaction.schedule.recurrence().into(),
|
||||||
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,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
},
|
||||||
})
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -69,13 +55,34 @@ pub enum ScheduledTransactionData {
|
|||||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
pub struct RecurringTransactionData {
|
pub struct RecurringTransactionData {
|
||||||
pub name: String,
|
pub name: String,
|
||||||
pub amount_cents: Cents,
|
pub amount_cents: u64,
|
||||||
pub direction: Direction,
|
pub direction: Direction,
|
||||||
pub start: DateTime<Utc>,
|
pub start: DateTime<Utc>,
|
||||||
pub end: Option<DateTime<Utc>>,
|
pub end: Option<DateTime<Utc>>,
|
||||||
pub recurrence: Recurrence,
|
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)]
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
pub struct Recurrence {
|
pub struct Recurrence {
|
||||||
pub every: u32,
|
pub every: u32,
|
||||||
@@ -83,7 +90,17 @@ pub struct Recurrence {
|
|||||||
pub weekend_adjustment: Option<WeekendAdjustment>,
|
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")]
|
#[serde(rename_all = "snake_case")]
|
||||||
pub enum RecurrenceUnit {
|
pub enum RecurrenceUnit {
|
||||||
Day,
|
Day,
|
||||||
@@ -92,94 +109,68 @@ pub enum RecurrenceUnit {
|
|||||||
Year,
|
Year,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl RecurrenceUnit {
|
impl From<RecurrenceUnit> for domain::RecurrenceUnit {
|
||||||
pub fn as_str(&self) -> &'static str {
|
fn from(unit: RecurrenceUnit) -> Self {
|
||||||
match self {
|
match unit {
|
||||||
Self::Day => "day",
|
RecurrenceUnit::Day => Self::Day,
|
||||||
Self::Week => "week",
|
RecurrenceUnit::Week => Self::Week,
|
||||||
Self::Month => "month",
|
RecurrenceUnit::Month => Self::Month,
|
||||||
Self::Year => "year",
|
RecurrenceUnit::Year => Self::Year,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl TryFrom<String> for RecurrenceUnit {
|
impl From<domain::RecurrenceUnit> for RecurrenceUnit {
|
||||||
type Error = RecurringTransactionConversionError;
|
fn from(unit: domain::RecurrenceUnit) -> Self {
|
||||||
|
match unit {
|
||||||
fn try_from(value: String) -> Result<Self, Self::Error> {
|
domain::RecurrenceUnit::Day => Self::Day,
|
||||||
match value.as_str() {
|
domain::RecurrenceUnit::Week => Self::Week,
|
||||||
"day" => Ok(Self::Day),
|
domain::RecurrenceUnit::Month => Self::Month,
|
||||||
"week" => Ok(Self::Week),
|
domain::RecurrenceUnit::Year => Self::Year,
|
||||||
"month" => Ok(Self::Month),
|
|
||||||
"year" => Ok(Self::Year),
|
|
||||||
_ => Err(RecurringTransactionConversionError::RecurrenceUnit(value)),
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
|
||||||
#[serde(rename_all = "snake_case")]
|
#[serde(rename_all = "snake_case")]
|
||||||
pub enum WeekendAdjustment {
|
pub enum WeekendAdjustment {
|
||||||
PreviousBusinessDay,
|
PreviousBusinessDay,
|
||||||
NextBusinessDay,
|
NextBusinessDay,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl WeekendAdjustment {
|
impl From<WeekendAdjustment> for domain::WeekendAdjustment {
|
||||||
pub fn as_str(&self) -> &'static str {
|
fn from(adjustment: WeekendAdjustment) -> Self {
|
||||||
match self {
|
match adjustment {
|
||||||
Self::PreviousBusinessDay => "previous_business_day",
|
WeekendAdjustment::PreviousBusinessDay => Self::PreviousBusinessDay,
|
||||||
Self::NextBusinessDay => "next_business_day",
|
WeekendAdjustment::NextBusinessDay => Self::NextBusinessDay,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl TryFrom<String> for WeekendAdjustment {
|
impl From<domain::WeekendAdjustment> for WeekendAdjustment {
|
||||||
type Error = RecurringTransactionConversionError;
|
fn from(adjustment: domain::WeekendAdjustment) -> Self {
|
||||||
|
match adjustment {
|
||||||
fn try_from(value: String) -> Result<Self, Self::Error> {
|
domain::WeekendAdjustment::PreviousBusinessDay => Self::PreviousBusinessDay,
|
||||||
match value.as_str() {
|
domain::WeekendAdjustment::NextBusinessDay => Self::NextBusinessDay,
|
||||||
"previous_business_day" => Ok(Self::PreviousBusinessDay),
|
|
||||||
"next_business_day" => Ok(Self::NextBusinessDay),
|
|
||||||
_ => Err(RecurringTransactionConversionError::WeekendAdjustment(
|
|
||||||
value,
|
|
||||||
)),
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[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)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use chrono::{TimeZone, Utc};
|
use chrono::{TimeDelta, TimeZone, Utc};
|
||||||
use uuid::Uuid;
|
use uuid::Uuid;
|
||||||
|
|
||||||
use super::{
|
use super::{
|
||||||
Recurrence, RecurrenceUnit, RecurringTransaction, RecurringTransactionData,
|
Recurrence, RecurrenceUnit, RecurringTransaction, RecurringTransactionData,
|
||||||
ScheduledTransaction, ScheduledTransactionData, WeekendAdjustment,
|
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 {
|
RecurringTransactionData {
|
||||||
name: String::new(),
|
name: String::new(),
|
||||||
amount_cents: amount_cents.into(),
|
amount_cents,
|
||||||
direction: Direction::Out,
|
direction: Direction::Out,
|
||||||
start: Utc.with_ymd_and_hms(2026, 9, 24, 12, 0, 0).unwrap(),
|
start: Utc.with_ymd_and_hms(2026, 9, 24, 12, 0, 0).unwrap(),
|
||||||
end: None,
|
end: None,
|
||||||
@@ -193,19 +184,63 @@ mod tests {
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn keeps_scheduled_transaction_json_flat() {
|
fn keeps_scheduled_transaction_json_flat() {
|
||||||
let response = ScheduledTransaction::Recurring(RecurringTransaction {
|
let transaction = data(1234).into_domain(Uuid::nil()).unwrap();
|
||||||
id: Uuid::nil(),
|
let response = ScheduledTransaction::from(RecurringTransaction::new(transaction, None));
|
||||||
data: transaction(1234),
|
|
||||||
});
|
|
||||||
let response = serde_json::to_value(response).unwrap();
|
let response = serde_json::to_value(response).unwrap();
|
||||||
assert_eq!(response["type"], "recurring");
|
assert_eq!(response["type"], "recurring");
|
||||||
assert_eq!(response["id"], Uuid::nil().to_string());
|
assert_eq!(response["id"], Uuid::nil().to_string());
|
||||||
|
assert!(response["next"].is_null());
|
||||||
assert_eq!(response["amount_cents"], 1234);
|
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());
|
assert!(response.get("data").is_none());
|
||||||
|
|
||||||
let request: ScheduledTransactionData = serde_json::from_value(response).unwrap();
|
let request: ScheduledTransactionData = serde_json::from_value(response).unwrap();
|
||||||
let ScheduledTransactionData::Recurring(data) = request;
|
let ScheduledTransactionData::Recurring(data) = request;
|
||||||
assert_eq!(data.amount_cents.get(), 1234);
|
assert_eq!(data.amount_cents, 1234);
|
||||||
assert_eq!(data.recurrence.every, 2);
|
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 serde::{Deserialize, Serialize};
|
||||||
use uuid::Uuid;
|
use uuid::Uuid;
|
||||||
|
|
||||||
use crate::database::dtos::transaction::TransactionRow;
|
use crate::{domain, routes::dtos::direction::Direction};
|
||||||
use crate::routes::dtos::{
|
|
||||||
cents::{Cents, CentsConversionError},
|
|
||||||
direction::{Direction, DirectionConversionError},
|
|
||||||
};
|
|
||||||
|
|
||||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
pub struct Transaction {
|
pub struct Transaction {
|
||||||
@@ -19,80 +15,91 @@ pub struct Transaction {
|
|||||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
pub struct TransactionData {
|
pub struct TransactionData {
|
||||||
pub description: String,
|
pub description: String,
|
||||||
pub amount_cents: Cents,
|
pub amount_cents: u64,
|
||||||
pub direction: Direction,
|
pub direction: Direction,
|
||||||
pub date: DateTime<Utc>,
|
pub date: DateTime<Utc>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl TryFrom<TransactionRow> for Transaction {
|
impl From<domain::Transaction> for Transaction {
|
||||||
type Error = TransactionConversionError;
|
fn from(transaction: domain::Transaction) -> Self {
|
||||||
|
Self {
|
||||||
fn try_from(row: TransactionRow) -> Result<Self, Self::Error> {
|
id: transaction.id,
|
||||||
Ok(Self {
|
|
||||||
id: row.id,
|
|
||||||
data: TransactionData {
|
data: TransactionData {
|
||||||
description: row.description,
|
description: transaction.description,
|
||||||
amount_cents: Cents::try_from(row.amount_cents)?,
|
amount_cents: transaction.amount.get(),
|
||||||
direction: Direction::try_from(row.direction)
|
direction: transaction.direction.into(),
|
||||||
.map_err(TransactionConversionError::Direction)?,
|
date: transaction.date,
|
||||||
date: row.date,
|
|
||||||
},
|
},
|
||||||
})
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, thiserror::Error)]
|
impl TransactionData {
|
||||||
pub enum TransactionConversionError {
|
pub fn into_domain(self, id: Uuid) -> Result<domain::Transaction, domain::ValidationError> {
|
||||||
#[error(transparent)]
|
Ok(domain::Transaction {
|
||||||
Cents(#[from] CentsConversionError),
|
id,
|
||||||
|
description: self.description,
|
||||||
#[error(transparent)]
|
amount: domain::Cents::try_from(self.amount_cents)?,
|
||||||
Direction(#[from] DirectionConversionError),
|
direction: self.direction.into(),
|
||||||
|
date: self.date,
|
||||||
|
})
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
|
|
||||||
#[test]
|
fn data(amount_cents: u64) -> TransactionData {
|
||||||
fn preserves_cents_in_response() {
|
TransactionData {
|
||||||
let id = Uuid::new_v4();
|
|
||||||
let date = Utc::now();
|
|
||||||
let response = Transaction::try_from(TransactionRow {
|
|
||||||
id,
|
|
||||||
description: "Groceries".to_string(),
|
description: "Groceries".to_string(),
|
||||||
amount_cents: 4250,
|
amount_cents,
|
||||||
direction: "out".to_string(),
|
direction: Direction::Out,
|
||||||
date,
|
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.id, id);
|
||||||
assert_eq!(response.data.description, "Groceries");
|
assert_eq!(response.data.description, "Groceries");
|
||||||
assert_eq!(response.data.amount_cents.get(), 4250);
|
assert_eq!(response.data.amount_cents, 4250);
|
||||||
assert_eq!(response.data.date, date);
|
}
|
||||||
|
|
||||||
|
#[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]
|
#[test]
|
||||||
fn keeps_transaction_json_flat() {
|
fn keeps_transaction_json_flat() {
|
||||||
let response = Transaction {
|
let response = Transaction {
|
||||||
id: Uuid::nil(),
|
id: Uuid::nil(),
|
||||||
data: TransactionData {
|
data: data(4250),
|
||||||
description: "Groceries".to_string(),
|
|
||||||
amount_cents: 4250.into(),
|
|
||||||
direction: Direction::Out,
|
|
||||||
date: Utc::now(),
|
|
||||||
},
|
|
||||||
};
|
};
|
||||||
|
|
||||||
let response = serde_json::to_value(response).unwrap();
|
let response = serde_json::to_value(response).unwrap();
|
||||||
assert_eq!(response["id"], Uuid::nil().to_string());
|
assert_eq!(response["id"], Uuid::nil().to_string());
|
||||||
assert_eq!(response["amount_cents"], 4250);
|
assert_eq!(response["amount_cents"], 4250);
|
||||||
|
assert_eq!(response["direction"], "out");
|
||||||
assert!(response.get("data").is_none());
|
assert!(response.get("data").is_none());
|
||||||
|
|
||||||
let request: TransactionData = serde_json::from_value(response).unwrap();
|
let request: TransactionData = serde_json::from_value(response).unwrap();
|
||||||
assert_eq!(request.description, "Groceries");
|
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 axum::{extract::State, http::StatusCode};
|
||||||
|
use chrono::{DateTime, Utc};
|
||||||
use sqlx::PgPool;
|
use sqlx::PgPool;
|
||||||
use uuid::Uuid;
|
use uuid::Uuid;
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
database::{
|
domain,
|
||||||
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,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
error::AppError,
|
error::AppError,
|
||||||
|
repository::{Delete, Upsert, recurring_transactions as repository},
|
||||||
routes::{
|
routes::{
|
||||||
dtos::scheduled_transaction::{
|
dtos::scheduled_transaction::{
|
||||||
RecurringTransaction, ScheduledTransaction, ScheduledTransactionData,
|
RecurringTransaction, ScheduledTransaction, ScheduledTransactionData,
|
||||||
},
|
},
|
||||||
extractors::{json::Json, path::Path},
|
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(
|
async fn get_scheduled_transactions(
|
||||||
State(pool): State<PgPool>,
|
State(pool): State<PgPool>,
|
||||||
) -> Result<Json<Vec<ScheduledTransaction>>, AppError> {
|
) -> Result<Json<Vec<ScheduledTransaction>>, AppError> {
|
||||||
let rows = query_scheduled_transactions(&pool).await?;
|
let now = Utc::now();
|
||||||
|
let transactions = repository::list(&pool)
|
||||||
let transactions = rows
|
.await?
|
||||||
.into_iter()
|
.into_iter()
|
||||||
.map(RecurringTransaction::try_from)
|
.map(|transaction| respond(transaction, now))
|
||||||
.map(|result| result.map(ScheduledTransaction::from))
|
.collect();
|
||||||
.collect::<Result<Vec<_>, _>>()?;
|
|
||||||
|
|
||||||
Ok(Json(transactions))
|
Ok(Json(transactions))
|
||||||
}
|
}
|
||||||
@@ -54,15 +47,11 @@ async fn get_scheduled_transaction(
|
|||||||
State(pool): State<PgPool>,
|
State(pool): State<PgPool>,
|
||||||
Path(id): Path<Uuid>,
|
Path(id): Path<Uuid>,
|
||||||
) -> Result<Json<ScheduledTransaction>, AppError> {
|
) -> Result<Json<ScheduledTransaction>, AppError> {
|
||||||
let row = get_scheduled_transaction_by_id(&pool, id)
|
let transaction = repository::get(&pool, id)
|
||||||
.await?
|
.await?
|
||||||
.map(RecurringTransaction::try_from)
|
.ok_or(AppError::NotFound)?;
|
||||||
.transpose()?;
|
|
||||||
|
|
||||||
match row {
|
Ok(Json(respond(transaction, Utc::now())))
|
||||||
Some(transaction) => Ok(Json(ScheduledTransaction::from(transaction))),
|
|
||||||
None => Err(AppError::NotFound),
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[axum::debug_handler]
|
#[axum::debug_handler]
|
||||||
@@ -73,29 +62,14 @@ async fn put_scheduled_transaction(
|
|||||||
Json(transaction): Json<ScheduledTransactionData>,
|
Json(transaction): Json<ScheduledTransactionData>,
|
||||||
) -> Result<(StatusCode, Json<ScheduledTransaction>), AppError> {
|
) -> Result<(StatusCode, Json<ScheduledTransaction>), AppError> {
|
||||||
let ScheduledTransactionData::Recurring(transaction) = transaction;
|
let ScheduledTransactionData::Recurring(transaction) = transaction;
|
||||||
|
let transaction = transaction.into_domain(id)?;
|
||||||
|
|
||||||
let transaction = ValidatedRecurringTransaction::try_from(transaction)?;
|
let (status, transaction) = match repository::upsert(&pool, transaction).await? {
|
||||||
let transaction = RecurringTransactionRow {
|
Upsert::Created(transaction) => (StatusCode::CREATED, transaction),
|
||||||
id,
|
Upsert::Updated(transaction) => (StatusCode::OK, transaction),
|
||||||
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, row) = match upsert_scheduled_transaction(&pool, transaction).await? {
|
Ok((status, Json(respond(transaction, Utc::now()))))
|
||||||
Upsert::Created(row) => (StatusCode::CREATED, row),
|
|
||||||
Upsert::Updated(row) => (StatusCode::OK, row),
|
|
||||||
};
|
|
||||||
let transaction = RecurringTransaction::try_from(row)?;
|
|
||||||
|
|
||||||
Ok((status, Json(transaction.into())))
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[axum::debug_handler]
|
#[axum::debug_handler]
|
||||||
@@ -104,8 +78,14 @@ async fn delete_scheduled_transaction(
|
|||||||
State(pool): State<PgPool>,
|
State(pool): State<PgPool>,
|
||||||
Path(id): Path<Uuid>,
|
Path(id): Path<Uuid>,
|
||||||
) -> Result<StatusCode, AppError> {
|
) -> 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::Deleted => Ok(StatusCode::NO_CONTENT),
|
||||||
Delete::NotFound => Err(AppError::NotFound),
|
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 uuid::Uuid;
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
database::{
|
|
||||||
common::{Delete, Upsert},
|
|
||||||
dtos::transaction::TransactionRow,
|
|
||||||
transactions::{
|
|
||||||
delete_transaction_by_id, get_transaction_by_id, query_transactions, upsert_transaction,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
error::AppError,
|
error::AppError,
|
||||||
|
repository::{Delete, Upsert, transactions as repository},
|
||||||
routes::{
|
routes::{
|
||||||
dtos::transaction::{Transaction, TransactionData},
|
dtos::transaction::{Transaction, TransactionData},
|
||||||
extractors::{json::Json, path::Path},
|
extractors::{json::Json, path::Path},
|
||||||
validation::transaction::ValidatedTransaction,
|
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -32,12 +25,11 @@ pub fn create_router() -> axum::Router<PgPool> {
|
|||||||
#[axum::debug_handler]
|
#[axum::debug_handler]
|
||||||
#[tracing::instrument(skip(pool))]
|
#[tracing::instrument(skip(pool))]
|
||||||
async fn get_transactions(State(pool): State<PgPool>) -> Result<Json<Vec<Transaction>>, AppError> {
|
async fn get_transactions(State(pool): State<PgPool>) -> Result<Json<Vec<Transaction>>, AppError> {
|
||||||
let rows = query_transactions(&pool).await?;
|
let transactions = repository::list(&pool)
|
||||||
|
.await?
|
||||||
let transactions = rows
|
|
||||||
.into_iter()
|
.into_iter()
|
||||||
.map(Transaction::try_from)
|
.map(Transaction::from)
|
||||||
.collect::<Result<Vec<_>, _>>()?;
|
.collect();
|
||||||
|
|
||||||
Ok(Json(transactions))
|
Ok(Json(transactions))
|
||||||
}
|
}
|
||||||
@@ -48,15 +40,11 @@ async fn get_transaction(
|
|||||||
State(pool): State<PgPool>,
|
State(pool): State<PgPool>,
|
||||||
Path(id): Path<Uuid>,
|
Path(id): Path<Uuid>,
|
||||||
) -> Result<Json<Transaction>, AppError> {
|
) -> Result<Json<Transaction>, AppError> {
|
||||||
let transaction = get_transaction_by_id(&pool, id)
|
let transaction = repository::get(&pool, id)
|
||||||
.await?
|
.await?
|
||||||
.map(Transaction::try_from)
|
.ok_or(AppError::NotFound)?;
|
||||||
.transpose()?;
|
|
||||||
|
|
||||||
match transaction {
|
Ok(Json(transaction.into()))
|
||||||
Some(transaction) => Ok(Json(transaction)),
|
|
||||||
None => Err(AppError::NotFound),
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[axum::debug_handler]
|
#[axum::debug_handler]
|
||||||
@@ -66,22 +54,14 @@ async fn put_transaction(
|
|||||||
Path(id): Path<Uuid>,
|
Path(id): Path<Uuid>,
|
||||||
Json(transaction): Json<TransactionData>,
|
Json(transaction): Json<TransactionData>,
|
||||||
) -> Result<(StatusCode, Json<Transaction>), AppError> {
|
) -> Result<(StatusCode, Json<Transaction>), AppError> {
|
||||||
let transaction = ValidatedTransaction::try_from(transaction)?;
|
let transaction = transaction.into_domain(id)?;
|
||||||
let transaction = TransactionRow {
|
|
||||||
id,
|
let (status, transaction) = match repository::upsert(&pool, transaction).await? {
|
||||||
description: transaction.description,
|
Upsert::Created(transaction) => (StatusCode::CREATED, transaction),
|
||||||
amount_cents: transaction.amount_cents,
|
Upsert::Updated(transaction) => (StatusCode::OK, transaction),
|
||||||
direction: transaction.direction.as_str().to_owned(),
|
|
||||||
date: transaction.date,
|
|
||||||
};
|
};
|
||||||
|
|
||||||
let (status, row) = match upsert_transaction(&pool, transaction).await? {
|
Ok((status, Json(transaction.into())))
|
||||||
Upsert::Created(row) => (StatusCode::CREATED, row),
|
|
||||||
Upsert::Updated(row) => (StatusCode::OK, row),
|
|
||||||
};
|
|
||||||
let transaction = Transaction::try_from(row)?;
|
|
||||||
|
|
||||||
Ok((status, Json(transaction)))
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[axum::debug_handler]
|
#[axum::debug_handler]
|
||||||
@@ -90,7 +70,7 @@ async fn delete_transaction(
|
|||||||
Path(id): Path<Uuid>,
|
Path(id): Path<Uuid>,
|
||||||
State(pool): State<PgPool>,
|
State(pool): State<PgPool>,
|
||||||
) -> Result<StatusCode, AppError> {
|
) -> Result<StatusCode, AppError> {
|
||||||
match delete_transaction_by_id(&pool, id).await? {
|
match repository::delete(&pool, id).await? {
|
||||||
Delete::Deleted => Ok(StatusCode::NO_CONTENT),
|
Delete::Deleted => Ok(StatusCode::NO_CONTENT),
|
||||||
Delete::NotFound => Err(AppError::NotFound),
|
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