Refactored API DTOs to be more straight forward.
This commit is contained in:
@@ -7,6 +7,7 @@ pub struct Schedule {
|
||||
start: DateTime<Utc>,
|
||||
end: Option<DateTime<Utc>>,
|
||||
recurrence: Recurrence,
|
||||
weekend_adjustment: Option<WeekendAdjustment>,
|
||||
}
|
||||
|
||||
impl Schedule {
|
||||
@@ -14,6 +15,7 @@ impl Schedule {
|
||||
start: DateTime<Utc>,
|
||||
end: Option<DateTime<Utc>>,
|
||||
recurrence: Recurrence,
|
||||
weekend_adjustment: Option<WeekendAdjustment>,
|
||||
) -> Result<Self, ValidationError> {
|
||||
if end.is_some_and(|end| end < start) {
|
||||
return Err(ValidationError::EndBeforeStart);
|
||||
@@ -23,6 +25,7 @@ impl Schedule {
|
||||
start,
|
||||
end,
|
||||
recurrence,
|
||||
weekend_adjustment,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -38,7 +41,11 @@ impl Schedule {
|
||||
self.recurrence
|
||||
}
|
||||
|
||||
/// First occurrence at or after `from`, or `None` once the schedule has ended.
|
||||
pub fn weekend_adjustment(&self) -> Option<WeekendAdjustment> {
|
||||
self.weekend_adjustment
|
||||
}
|
||||
|
||||
/// Find the 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);
|
||||
@@ -56,11 +63,7 @@ impl Schedule {
|
||||
}
|
||||
|
||||
fn occurrence(&self, index: u32) -> Option<DateTime<Utc>> {
|
||||
let Recurrence {
|
||||
every,
|
||||
unit,
|
||||
weekend_adjustment,
|
||||
} = self.recurrence;
|
||||
let Recurrence { every, unit } = self.recurrence;
|
||||
let steps = index.checked_mul(every.get())?;
|
||||
|
||||
let date = match unit {
|
||||
@@ -76,7 +79,7 @@ impl Schedule {
|
||||
.and_then(|months| self.start.checked_add_months(Months::new(months))),
|
||||
}?;
|
||||
|
||||
let day_delta = match (date.weekday(), weekend_adjustment) {
|
||||
let day_delta = match (date.weekday(), self.weekend_adjustment) {
|
||||
(Weekday::Sat, Some(WeekendAdjustment::PreviousBusinessDay)) => -1,
|
||||
(Weekday::Sun, Some(WeekendAdjustment::PreviousBusinessDay)) => -2,
|
||||
(Weekday::Sat, Some(WeekendAdjustment::NextBusinessDay)) => 2,
|
||||
@@ -86,7 +89,7 @@ impl Schedule {
|
||||
date.checked_add_signed(TimeDelta::days(day_delta))
|
||||
}
|
||||
|
||||
/// Estimated index of the last unadjusted occurrence at or before `at`.
|
||||
/// Estimate the 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());
|
||||
@@ -105,7 +108,6 @@ impl Schedule {
|
||||
pub struct Recurrence {
|
||||
pub every: RecurrenceInterval,
|
||||
pub unit: RecurrenceUnit,
|
||||
pub weekend_adjustment: Option<WeekendAdjustment>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
@@ -174,15 +176,10 @@ mod tests {
|
||||
};
|
||||
use crate::domain::ValidationError;
|
||||
|
||||
fn recurrence(
|
||||
every: u32,
|
||||
unit: RecurrenceUnit,
|
||||
weekend_adjustment: Option<WeekendAdjustment>,
|
||||
) -> Recurrence {
|
||||
fn recurrence(every: u32, unit: RecurrenceUnit) -> Recurrence {
|
||||
Recurrence {
|
||||
every: RecurrenceInterval::try_from(every).unwrap(),
|
||||
unit,
|
||||
weekend_adjustment,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -194,9 +191,10 @@ mod tests {
|
||||
start: DateTime<Utc>,
|
||||
end: Option<DateTime<Utc>>,
|
||||
recurrence: Recurrence,
|
||||
weekend_adjustment: Option<WeekendAdjustment>,
|
||||
from: DateTime<Utc>,
|
||||
) -> Option<DateTime<Utc>> {
|
||||
Schedule::new(start, end, recurrence)
|
||||
Schedule::new(start, end, recurrence, weekend_adjustment)
|
||||
.unwrap()
|
||||
.next_occurrence(from)
|
||||
}
|
||||
@@ -204,36 +202,39 @@ mod tests {
|
||||
#[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));
|
||||
let weekly = recurrence(1, RecurrenceUnit::Week);
|
||||
assert_eq!(
|
||||
next(start, None, weekly, at(2026, 9, 25, 0)),
|
||||
next(start, None, weekly, None, at(2026, 1, 1, 0)),
|
||||
Some(start)
|
||||
);
|
||||
assert_eq!(next(start, None, weekly, None, start), Some(start));
|
||||
assert_eq!(
|
||||
next(start, None, weekly, None, 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 monthly = recurrence(1, RecurrenceUnit::Month);
|
||||
let start = at(2026, 1, 31, 12);
|
||||
assert_eq!(
|
||||
next(start, None, monthly, at(2026, 2, 1, 0)),
|
||||
next(start, None, monthly, None, at(2026, 2, 1, 0)),
|
||||
Some(at(2026, 2, 28, 12))
|
||||
);
|
||||
assert_eq!(
|
||||
next(start, None, monthly, at(2026, 3, 1, 0)),
|
||||
next(start, None, monthly, None, at(2026, 3, 1, 0)),
|
||||
Some(at(2026, 3, 31, 12))
|
||||
);
|
||||
|
||||
let yearly = recurrence(1, RecurrenceUnit::Year, None);
|
||||
let yearly = recurrence(1, RecurrenceUnit::Year);
|
||||
let start = at(2024, 2, 29, 12);
|
||||
assert_eq!(
|
||||
next(start, None, yearly, at(2024, 3, 1, 0)),
|
||||
next(start, None, yearly, None, at(2024, 3, 1, 0)),
|
||||
Some(at(2025, 2, 28, 12))
|
||||
);
|
||||
assert_eq!(
|
||||
next(start, None, yearly, at(2027, 3, 1, 0)),
|
||||
next(start, None, yearly, None, at(2027, 3, 1, 0)),
|
||||
Some(at(2028, 2, 29, 12))
|
||||
);
|
||||
}
|
||||
@@ -243,56 +244,76 @@ mod tests {
|
||||
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),
|
||||
);
|
||||
let next_business_day = recurrence(2, RecurrenceUnit::Day);
|
||||
assert_eq!(
|
||||
next(start, None, next_business_day, from),
|
||||
next(
|
||||
start,
|
||||
None,
|
||||
next_business_day,
|
||||
Some(WeekendAdjustment::NextBusinessDay),
|
||||
from
|
||||
),
|
||||
Some(at(2026, 9, 28, 12))
|
||||
);
|
||||
assert_eq!(
|
||||
next(start, Some(at(2026, 9, 27, 12)), next_business_day, from),
|
||||
next(
|
||||
start,
|
||||
Some(at(2026, 9, 27, 12)),
|
||||
next_business_day,
|
||||
Some(WeekendAdjustment::NextBusinessDay),
|
||||
from,
|
||||
),
|
||||
None
|
||||
);
|
||||
|
||||
let previous_business_day = recurrence(
|
||||
2,
|
||||
RecurrenceUnit::Day,
|
||||
Some(WeekendAdjustment::PreviousBusinessDay),
|
||||
);
|
||||
let previous_business_day = recurrence(2, RecurrenceUnit::Day);
|
||||
assert_eq!(
|
||||
next(start, None, previous_business_day, from),
|
||||
next(
|
||||
start,
|
||||
None,
|
||||
previous_business_day,
|
||||
Some(WeekendAdjustment::PreviousBusinessDay),
|
||||
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 monthly = recurrence(1, RecurrenceUnit::Month);
|
||||
let start = at(2026, 1, 30, 12);
|
||||
assert_eq!(
|
||||
next(start, None, monthly, at(2026, 3, 1, 0)),
|
||||
next(
|
||||
start,
|
||||
None,
|
||||
monthly,
|
||||
Some(WeekendAdjustment::NextBusinessDay),
|
||||
at(2026, 3, 1, 0),
|
||||
),
|
||||
Some(at(2026, 3, 2, 12))
|
||||
);
|
||||
assert_eq!(
|
||||
next(start, None, monthly, at(2026, 3, 3, 0)),
|
||||
next(
|
||||
start,
|
||||
None,
|
||||
monthly,
|
||||
Some(WeekendAdjustment::NextBusinessDay),
|
||||
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),
|
||||
);
|
||||
let daily = recurrence(1, RecurrenceUnit::Day);
|
||||
assert_eq!(
|
||||
next(at(2026, 9, 21, 12), None, daily, at(2026, 9, 27, 13)),
|
||||
next(
|
||||
at(2026, 9, 21, 12),
|
||||
None,
|
||||
daily,
|
||||
Some(WeekendAdjustment::NextBusinessDay),
|
||||
at(2026, 9, 27, 13),
|
||||
),
|
||||
Some(at(2026, 9, 28, 12))
|
||||
);
|
||||
}
|
||||
@@ -300,13 +321,13 @@ mod tests {
|
||||
#[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);
|
||||
let recurrence = recurrence(1, RecurrenceUnit::Month);
|
||||
|
||||
assert!(matches!(
|
||||
Schedule::new(start, Some(start - TimeDelta::seconds(1)), recurrence),
|
||||
Schedule::new(start, Some(start - TimeDelta::seconds(1)), recurrence, None,),
|
||||
Err(ValidationError::EndBeforeStart)
|
||||
));
|
||||
assert!(Schedule::new(start, Some(start), recurrence).is_ok());
|
||||
assert!(Schedule::new(start, Some(start), recurrence, None).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -67,18 +67,18 @@ fn decode(row: RecurringTransactionRow) -> Result<RecurringTransaction, DecodeEr
|
||||
let recurrence = Recurrence {
|
||||
every: RecurrenceInterval::try_from(row.recurrence_every)?,
|
||||
unit: decode_recurrence_unit(row.recurrence_unit)?,
|
||||
weekend_adjustment: row
|
||||
};
|
||||
let weekend_adjustment = row
|
||||
.weekend_adjustment
|
||||
.map(decode_weekend_adjustment)
|
||||
.transpose()?,
|
||||
};
|
||||
.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)?,
|
||||
schedule: Schedule::new(row.starts_at, row.ends_at, recurrence, weekend_adjustment)?,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -94,8 +94,9 @@ fn encode(transaction: RecurringTransaction) -> RecurringTransactionRow {
|
||||
ends_at: transaction.schedule.end(),
|
||||
recurrence_every: recurrence.every.into(),
|
||||
recurrence_unit: encode_recurrence_unit(recurrence.unit).to_owned(),
|
||||
weekend_adjustment: recurrence
|
||||
.weekend_adjustment
|
||||
weekend_adjustment: transaction
|
||||
.schedule
|
||||
.weekend_adjustment()
|
||||
.map(|adjustment| encode_weekend_adjustment(adjustment).to_owned()),
|
||||
}
|
||||
}
|
||||
@@ -138,7 +139,7 @@ mod tests {
|
||||
assert_eq!(recurrence.every.get(), 1);
|
||||
assert_eq!(recurrence.unit, RecurrenceUnit::Month);
|
||||
assert_eq!(
|
||||
recurrence.weekend_adjustment,
|
||||
transaction.schedule.weekend_adjustment(),
|
||||
Some(WeekendAdjustment::NextBusinessDay)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -4,90 +4,111 @@ use uuid::Uuid;
|
||||
|
||||
use crate::{domain, routes::dtos::direction::Direction};
|
||||
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
#[serde(tag = "type")]
|
||||
pub enum ScheduledTransactionRequest {
|
||||
Recurring(RecurringTransactionRequest),
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
#[serde(tag = "type")]
|
||||
pub enum ScheduledTransaction {
|
||||
Recurring(RecurringTransaction),
|
||||
pub enum ScheduledTransactionResponse {
|
||||
Recurring(RecurringTransactionResponse),
|
||||
}
|
||||
|
||||
impl From<RecurringTransaction> for ScheduledTransaction {
|
||||
fn from(transaction: RecurringTransaction) -> Self {
|
||||
impl From<RecurringTransactionResponse> for ScheduledTransactionResponse {
|
||||
fn from(transaction: RecurringTransactionResponse) -> Self {
|
||||
Self::Recurring(transaction)
|
||||
}
|
||||
}
|
||||
|
||||
#[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 RecurringTransaction {
|
||||
pub fn new(transaction: domain::RecurringTransaction, next: Option<DateTime<Utc>>) -> Self {
|
||||
Self {
|
||||
id: transaction.id,
|
||||
next,
|
||||
data: RecurringTransactionData {
|
||||
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(),
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
#[serde(tag = "type")]
|
||||
pub enum ScheduledTransactionData {
|
||||
Recurring(RecurringTransactionData),
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct RecurringTransactionData {
|
||||
pub struct RecurringTransactionRequest {
|
||||
pub name: String,
|
||||
pub amount_cents: u64,
|
||||
pub direction: Direction,
|
||||
pub start: DateTime<Utc>,
|
||||
pub end: Option<DateTime<Utc>>,
|
||||
pub recurrence: Recurrence,
|
||||
pub schedule: ScheduleRequest,
|
||||
}
|
||||
|
||||
impl RecurringTransactionData {
|
||||
impl RecurringTransactionRequest {
|
||||
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)?,
|
||||
schedule: domain::Schedule::new(
|
||||
self.schedule.start,
|
||||
self.schedule.end,
|
||||
domain::Recurrence {
|
||||
every: domain::RecurrenceInterval::try_from(self.schedule.recurrence.every)?,
|
||||
unit: self.schedule.recurrence.unit.into(),
|
||||
},
|
||||
self.schedule.weekend_adjustment.map(Into::into),
|
||||
)?,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct RecurringTransactionResponse {
|
||||
pub id: Uuid,
|
||||
pub name: String,
|
||||
pub amount_cents: u64,
|
||||
pub direction: Direction,
|
||||
pub schedule: ScheduleResponse,
|
||||
}
|
||||
|
||||
impl RecurringTransactionResponse {
|
||||
pub fn new(transaction: domain::RecurringTransaction, next: Option<DateTime<Utc>>) -> Self {
|
||||
Self {
|
||||
id: transaction.id,
|
||||
name: transaction.name,
|
||||
amount_cents: transaction.amount.get(),
|
||||
direction: transaction.direction.into(),
|
||||
schedule: ScheduleResponse::new(transaction.schedule, next),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
pub struct ScheduleRequest {
|
||||
pub start: DateTime<Utc>,
|
||||
pub end: Option<DateTime<Utc>>,
|
||||
pub recurrence: Recurrence,
|
||||
pub weekend_adjustment: Option<WeekendAdjustment>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct ScheduleResponse {
|
||||
pub start: DateTime<Utc>,
|
||||
pub end: Option<DateTime<Utc>>,
|
||||
pub recurrence: Recurrence,
|
||||
pub weekend_adjustment: Option<WeekendAdjustment>,
|
||||
pub next: Option<DateTime<Utc>>,
|
||||
}
|
||||
|
||||
impl ScheduleResponse {
|
||||
fn new(schedule: domain::Schedule, next: Option<DateTime<Utc>>) -> Self {
|
||||
Self {
|
||||
start: schedule.start(),
|
||||
end: schedule.end(),
|
||||
recurrence: schedule.recurrence().into(),
|
||||
weekend_adjustment: schedule.weekend_adjustment().map(Into::into),
|
||||
next,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct Recurrence {
|
||||
pub every: u32,
|
||||
pub unit: RecurrenceUnit,
|
||||
pub weekend_adjustment: Option<WeekendAdjustment>,
|
||||
}
|
||||
|
||||
impl From<domain::Recurrence> for Recurrence {
|
||||
@@ -95,7 +116,6 @@ impl From<domain::Recurrence> for Recurrence {
|
||||
Self {
|
||||
every: recurrence.every.get(),
|
||||
unit: recurrence.unit.into(),
|
||||
weekend_adjustment: recurrence.weekend_adjustment.map(Into::into),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -162,53 +182,60 @@ mod tests {
|
||||
use uuid::Uuid;
|
||||
|
||||
use super::{
|
||||
Recurrence, RecurrenceUnit, RecurringTransaction, RecurringTransactionData,
|
||||
ScheduledTransaction, ScheduledTransactionData, WeekendAdjustment,
|
||||
Recurrence, RecurrenceUnit, RecurringTransactionRequest, RecurringTransactionResponse,
|
||||
ScheduleRequest, ScheduledTransactionRequest, ScheduledTransactionResponse,
|
||||
WeekendAdjustment,
|
||||
};
|
||||
use crate::{domain, routes::dtos::direction::Direction};
|
||||
|
||||
fn data(amount_cents: u64) -> RecurringTransactionData {
|
||||
RecurringTransactionData {
|
||||
fn request(amount_cents: u64) -> RecurringTransactionRequest {
|
||||
RecurringTransactionRequest {
|
||||
name: String::new(),
|
||||
amount_cents,
|
||||
direction: Direction::Out,
|
||||
schedule: ScheduleRequest {
|
||||
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 keeps_scheduled_transaction_json_flat() {
|
||||
let transaction = data(1234).into_domain(Uuid::nil()).unwrap();
|
||||
let response = ScheduledTransaction::from(RecurringTransaction::new(transaction, None));
|
||||
fn serializes_scheduled_transaction_with_nested_schedule() {
|
||||
let transaction = request(1234).into_domain(Uuid::nil()).unwrap();
|
||||
let response = ScheduledTransactionResponse::from(RecurringTransactionResponse::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["schedule"]["recurrence"]["unit"], "month");
|
||||
assert_eq!(
|
||||
response["recurrence"]["weekend_adjustment"],
|
||||
response["schedule"]["weekend_adjustment"],
|
||||
"next_business_day"
|
||||
);
|
||||
assert!(response["schedule"]["next"].is_null());
|
||||
assert!(response.get("next").is_none());
|
||||
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, 1234);
|
||||
assert_eq!(data.recurrence.every, 2);
|
||||
let request: ScheduledTransactionRequest = serde_json::from_value(response).unwrap();
|
||||
let ScheduledTransactionRequest::Recurring(request) = request;
|
||||
assert_eq!(request.amount_cents, 1234);
|
||||
assert_eq!(request.schedule.recurrence.every, 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn converts_to_domain() {
|
||||
let id = Uuid::new_v4();
|
||||
let transaction = data(1234).into_domain(id).unwrap();
|
||||
let transaction = request(1234).into_domain(id).unwrap();
|
||||
let recurrence = transaction.schedule.recurrence();
|
||||
|
||||
assert_eq!(transaction.id, id);
|
||||
@@ -217,7 +244,7 @@ mod tests {
|
||||
assert_eq!(recurrence.every.get(), 2);
|
||||
assert_eq!(recurrence.unit, domain::RecurrenceUnit::Month);
|
||||
assert_eq!(
|
||||
recurrence.weekend_adjustment,
|
||||
transaction.schedule.weekend_adjustment(),
|
||||
Some(domain::WeekendAdjustment::NextBusinessDay)
|
||||
);
|
||||
}
|
||||
@@ -225,19 +252,19 @@ mod tests {
|
||||
#[test]
|
||||
fn rejects_invalid_requests() {
|
||||
assert!(matches!(
|
||||
data(i64::MAX as u64 + 1).into_domain(Uuid::nil()),
|
||||
request(i64::MAX as u64 + 1).into_domain(Uuid::nil()),
|
||||
Err(domain::ValidationError::Amount(_))
|
||||
));
|
||||
|
||||
let mut every = data(100);
|
||||
every.recurrence.every = 0;
|
||||
let mut every = request(100);
|
||||
every.schedule.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));
|
||||
let mut end = request(100);
|
||||
end.schedule.end = Some(end.schedule.start - TimeDelta::seconds(1));
|
||||
assert!(matches!(
|
||||
end.into_domain(Uuid::nil()),
|
||||
Err(domain::ValidationError::EndBeforeStart)
|
||||
|
||||
@@ -4,37 +4,15 @@ use uuid::Uuid;
|
||||
|
||||
use crate::{domain, routes::dtos::direction::Direction};
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct Transaction {
|
||||
pub id: Uuid,
|
||||
|
||||
#[serde(flatten)]
|
||||
pub data: TransactionData,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct TransactionData {
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
pub struct TransactionRequest {
|
||||
pub description: String,
|
||||
pub amount_cents: u64,
|
||||
pub direction: Direction,
|
||||
pub date: DateTime<Utc>,
|
||||
}
|
||||
|
||||
impl From<domain::Transaction> for Transaction {
|
||||
fn from(transaction: domain::Transaction) -> Self {
|
||||
Self {
|
||||
id: transaction.id,
|
||||
data: TransactionData {
|
||||
description: transaction.description,
|
||||
amount_cents: transaction.amount.get(),
|
||||
direction: transaction.direction.into(),
|
||||
date: transaction.date,
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl TransactionData {
|
||||
impl TransactionRequest {
|
||||
pub fn into_domain(self, id: Uuid) -> Result<domain::Transaction, domain::ValidationError> {
|
||||
Ok(domain::Transaction {
|
||||
id,
|
||||
@@ -46,12 +24,33 @@ impl TransactionData {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct TransactionResponse {
|
||||
pub id: Uuid,
|
||||
pub description: String,
|
||||
pub amount_cents: u64,
|
||||
pub direction: Direction,
|
||||
pub date: DateTime<Utc>,
|
||||
}
|
||||
|
||||
impl From<domain::Transaction> for TransactionResponse {
|
||||
fn from(transaction: domain::Transaction) -> Self {
|
||||
Self {
|
||||
id: transaction.id,
|
||||
description: transaction.description,
|
||||
amount_cents: transaction.amount.get(),
|
||||
direction: transaction.direction.into(),
|
||||
date: transaction.date,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn data(amount_cents: u64) -> TransactionData {
|
||||
TransactionData {
|
||||
fn request(amount_cents: u64) -> TransactionRequest {
|
||||
TransactionRequest {
|
||||
description: "Groceries".to_string(),
|
||||
amount_cents,
|
||||
direction: Direction::Out,
|
||||
@@ -62,20 +61,20 @@ mod tests {
|
||||
#[test]
|
||||
fn converts_between_dto_and_domain() {
|
||||
let id = Uuid::new_v4();
|
||||
let transaction = data(4250).into_domain(id).unwrap();
|
||||
let transaction = request(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);
|
||||
let response = TransactionResponse::from(transaction);
|
||||
assert_eq!(response.id, id);
|
||||
assert_eq!(response.data.description, "Groceries");
|
||||
assert_eq!(response.data.amount_cents, 4250);
|
||||
assert_eq!(response.description, "Groceries");
|
||||
assert_eq!(response.amount_cents, 4250);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_amounts_that_do_not_fit_in_database() {
|
||||
let error = data(i64::MAX as u64 + 1)
|
||||
let error = request(i64::MAX as u64 + 1)
|
||||
.into_domain(Uuid::nil())
|
||||
.unwrap_err();
|
||||
assert!(matches!(
|
||||
@@ -87,18 +86,21 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn keeps_transaction_json_flat() {
|
||||
let response = Transaction {
|
||||
let response = TransactionResponse {
|
||||
id: Uuid::nil(),
|
||||
data: data(4250),
|
||||
description: "Groceries".to_owned(),
|
||||
amount_cents: 4250,
|
||||
direction: Direction::Out,
|
||||
date: Utc::now(),
|
||||
};
|
||||
|
||||
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());
|
||||
assert_eq!(response["description"], "Groceries");
|
||||
|
||||
let request: TransactionData = serde_json::from_value(response).unwrap();
|
||||
let request: TransactionRequest = serde_json::from_value(response).unwrap();
|
||||
assert_eq!(request.description, "Groceries");
|
||||
assert_eq!(request.amount_cents, 4250);
|
||||
}
|
||||
|
||||
@@ -9,7 +9,7 @@ use crate::{
|
||||
repository::{Delete, Upsert, recurring_transactions as repository},
|
||||
routes::{
|
||||
dtos::scheduled_transaction::{
|
||||
RecurringTransaction, ScheduledTransaction, ScheduledTransactionData,
|
||||
RecurringTransactionResponse, ScheduledTransactionRequest, ScheduledTransactionResponse,
|
||||
},
|
||||
extractors::{json::Json, path::Path},
|
||||
},
|
||||
@@ -30,12 +30,12 @@ pub fn create_router() -> axum::Router<PgPool> {
|
||||
#[tracing::instrument(skip(pool))]
|
||||
async fn get_scheduled_transactions(
|
||||
State(pool): State<PgPool>,
|
||||
) -> Result<Json<Vec<ScheduledTransaction>>, AppError> {
|
||||
) -> Result<Json<Vec<ScheduledTransactionResponse>>, AppError> {
|
||||
let now = Utc::now();
|
||||
let transactions = repository::list(&pool)
|
||||
.await?
|
||||
.into_iter()
|
||||
.map(|transaction| respond(transaction, now))
|
||||
.map(|transaction| create_response(transaction, now))
|
||||
.collect();
|
||||
|
||||
Ok(Json(transactions))
|
||||
@@ -46,12 +46,12 @@ async fn get_scheduled_transactions(
|
||||
async fn get_scheduled_transaction(
|
||||
State(pool): State<PgPool>,
|
||||
Path(id): Path<Uuid>,
|
||||
) -> Result<Json<ScheduledTransaction>, AppError> {
|
||||
) -> Result<Json<ScheduledTransactionResponse>, AppError> {
|
||||
let transaction = repository::get(&pool, id)
|
||||
.await?
|
||||
.ok_or(AppError::NotFound)?;
|
||||
|
||||
Ok(Json(respond(transaction, Utc::now())))
|
||||
Ok(Json(create_response(transaction, Utc::now())))
|
||||
}
|
||||
|
||||
#[axum::debug_handler]
|
||||
@@ -59,9 +59,9 @@ async fn get_scheduled_transaction(
|
||||
async fn put_scheduled_transaction(
|
||||
State(pool): State<PgPool>,
|
||||
Path(id): Path<Uuid>,
|
||||
Json(transaction): Json<ScheduledTransactionData>,
|
||||
) -> Result<(StatusCode, Json<ScheduledTransaction>), AppError> {
|
||||
let ScheduledTransactionData::Recurring(transaction) = transaction;
|
||||
Json(transaction): Json<ScheduledTransactionRequest>,
|
||||
) -> Result<(StatusCode, Json<ScheduledTransactionResponse>), AppError> {
|
||||
let ScheduledTransactionRequest::Recurring(transaction) = transaction;
|
||||
let transaction = transaction.into_domain(id)?;
|
||||
|
||||
let (status, transaction) = match repository::upsert(&pool, transaction).await? {
|
||||
@@ -69,7 +69,7 @@ async fn put_scheduled_transaction(
|
||||
Upsert::Updated(transaction) => (StatusCode::OK, transaction),
|
||||
};
|
||||
|
||||
Ok((status, Json(respond(transaction, Utc::now()))))
|
||||
Ok((status, Json(create_response(transaction, Utc::now()))))
|
||||
}
|
||||
|
||||
#[axum::debug_handler]
|
||||
@@ -84,8 +84,11 @@ async fn delete_scheduled_transaction(
|
||||
}
|
||||
}
|
||||
|
||||
fn respond(transaction: domain::RecurringTransaction, now: DateTime<Utc>) -> ScheduledTransaction {
|
||||
fn create_response(
|
||||
transaction: domain::RecurringTransaction,
|
||||
now: DateTime<Utc>,
|
||||
) -> ScheduledTransactionResponse {
|
||||
let next = transaction.schedule.next_occurrence(now);
|
||||
|
||||
RecurringTransaction::new(transaction, next).into()
|
||||
RecurringTransactionResponse::new(transaction, next).into()
|
||||
}
|
||||
|
||||
@@ -6,7 +6,7 @@ use crate::{
|
||||
error::AppError,
|
||||
repository::{Delete, Upsert, transactions as repository},
|
||||
routes::{
|
||||
dtos::transaction::{Transaction, TransactionData},
|
||||
dtos::transaction::{TransactionRequest, TransactionResponse},
|
||||
extractors::{json::Json, path::Path},
|
||||
},
|
||||
};
|
||||
@@ -24,11 +24,13 @@ 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> {
|
||||
async fn get_transactions(
|
||||
State(pool): State<PgPool>,
|
||||
) -> Result<Json<Vec<TransactionResponse>>, AppError> {
|
||||
let transactions = repository::list(&pool)
|
||||
.await?
|
||||
.into_iter()
|
||||
.map(Transaction::from)
|
||||
.map(TransactionResponse::from)
|
||||
.collect();
|
||||
|
||||
Ok(Json(transactions))
|
||||
@@ -39,7 +41,7 @@ async fn get_transactions(State(pool): State<PgPool>) -> Result<Json<Vec<Transac
|
||||
async fn get_transaction(
|
||||
State(pool): State<PgPool>,
|
||||
Path(id): Path<Uuid>,
|
||||
) -> Result<Json<Transaction>, AppError> {
|
||||
) -> Result<Json<TransactionResponse>, AppError> {
|
||||
let transaction = repository::get(&pool, id)
|
||||
.await?
|
||||
.ok_or(AppError::NotFound)?;
|
||||
@@ -52,8 +54,8 @@ async fn get_transaction(
|
||||
async fn put_transaction(
|
||||
State(pool): State<PgPool>,
|
||||
Path(id): Path<Uuid>,
|
||||
Json(transaction): Json<TransactionData>,
|
||||
) -> Result<(StatusCode, Json<Transaction>), AppError> {
|
||||
Json(transaction): Json<TransactionRequest>,
|
||||
) -> Result<(StatusCode, Json<TransactionResponse>), AppError> {
|
||||
let transaction = transaction.into_domain(id)?;
|
||||
|
||||
let (status, transaction) = match repository::upsert(&pool, transaction).await? {
|
||||
|
||||
Reference in New Issue
Block a user