use uuid::Uuid; use super::{ DecodeError, QueryConversionError, ReferenceRelation, ReferenceViolationKind, RepositoryError, dtos::{Delete, Upsert}, encoding::{ decode_direction, decode_recurrence_unit, decode_weekend_adjustment, encode_direction, encode_recurrence_unit, encode_weekend_adjustment, }, }; use crate::{ database::{ Constraint, DatabaseError, dtos::RecurringTransactionRow, recurring_transactions as db, }, domain::{Cents, Recurrence, RecurrenceInterval, RecurringTransaction, Schedule}, }; pub struct Query { pub limit: Option, pub offset: Option, } impl Default for Query { fn default() -> Self { Self { limit: None, offset: None, } } } 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()?, ..Default::default() }) } } pub async fn query<'e, E>( executor: E, query: Query, ) -> Result, RepositoryError> where E: sqlx::Executor<'e, Database = sqlx::Postgres>, { let transactions = db::query(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_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(executor, encode(transaction)) .await .map_err(classify_upsert_error)? .try_map(decode)?; Ok(transaction.into()) } fn classify_upsert_error(error: DatabaseError) -> RepositoryError { let relation = match &error { DatabaseError::ForeignKeyViolation { constraint: Constraint::RecurringTransactionAccount, .. } => Some(ReferenceRelation::Account), _ => None, }; match relation { Some(relation) => RepositoryError::ReferenceViolation { relation, kind: ReferenceViolationKind::Missing, source: error, }, None => RepositoryError::Database(error), } } pub async fn delete<'e, E>(executor: E, id: Uuid) -> Result where E: sqlx::Executor<'e, Database = sqlx::Postgres>, { Ok(db::delete_by_id(executor, id).await?.into()) } 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, account_id: row.account_id, 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, account_id: transaction.account_id, 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, ScheduleError, WeekendAdjustment}; fn foreign_key_violation(constraint: Constraint) -> DatabaseError { DatabaseError::ForeignKeyViolation { constraint, source: sqlx::Error::Protocol("test database cause".to_owned()), } } #[test] fn classifies_upsert_foreign_key_constraints() { let account = classify_upsert_error(foreign_key_violation( Constraint::RecurringTransactionAccount, )); assert!(matches!( &account, RepositoryError::ReferenceViolation { relation: ReferenceRelation::Account, kind: ReferenceViolationKind::Missing, .. } )); } #[test] fn keeps_unknown_upsert_foreign_keys_generic() { let error = classify_upsert_error(foreign_key_violation(Constraint::Unnamed)); assert!(matches!(error, RepositoryError::Database(_))); } fn row() -> RecurringTransactionRow { RecurringTransactionRow { id: Uuid::new_v4(), name: "Rent".to_owned(), account_id: Uuid::new_v4(), 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, account_id) = (row.id, row.starts_at, row.account_id); let transaction = decode(row).unwrap(); 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.account_id, account_id); assert_eq!(transaction.schedule.start(), start); assert_eq!(transaction.schedule.end(), None); assert_eq!( transaction.schedule.weekend_adjustment(), Some(WeekendAdjustment::NextBusinessDay) ); let recurrence = transaction.schedule.recurrence(); assert_eq!(recurrence.every.get(), 1); assert_eq!(recurrence.unit, RecurrenceUnit::Month); } #[test] fn rejects_corrupt_rows() { let mut every = row(); every.recurrence_every = 0; assert!(matches!( decode(every), Err(DecodeError::Schedule(ScheduleError::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::Schedule(ScheduleError::EndBeforeStart)) )); } #[test] fn round_trips_through_rows() { let transaction = decode(row()).unwrap(); assert_eq!(decode(encode(transaction.clone())).unwrap(), transaction); } }