use uuid::Uuid; use super::{ DecodeError, Delete, QueryConversionError, 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 struct Query { pub limit: Option, pub offset: Option, } impl TryFrom for db::Query { type Error = QueryConversionError; fn try_from(query: Query) -> Result { Ok(db::Query { limit: query .limit .map(|l| i64::try_from(l).map_err(|_| QueryConversionError::Limit(l))) .transpose()?, offset: query .offset .map(|o| i64::try_from(o).map_err(|_| QueryConversionError::Offset(o))) .transpose()?, }) } } pub async fn query<'e, E>( executor: E, query: Query, ) -> Result, RepositoryError> where E: sqlx::Executor<'e, Database = sqlx::Postgres>, { let transactions = db::query_recurring_transactions(executor, query.try_into()?) .await? .into_iter() .map(decode) .collect::>()?; Ok(transactions) } pub async fn get<'e, E>( executor: E, id: Uuid, ) -> Result, 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, 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 where E: sqlx::Executor<'e, Database = sqlx::Postgres>, { Ok(db::delete_recurring_transaction_by_id(executor, id).await?) } fn decode(row: RecurringTransactionRow) -> Result { let recurrence = Recurrence { every: RecurrenceInterval::try_from(row.recurrence_every)?, unit: decode_recurrence_unit(row.recurrence_unit)?, }; let 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, weekend_adjustment)?, }) } 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: transaction .schedule .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!( transaction.schedule.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); } }