259 lines
7.9 KiB
Rust
259 lines
7.9 KiB
Rust
use uuid::Uuid;
|
|
|
|
use super::{
|
|
DecodeError, QueryConversionError, ReferenceRelation, ReferenceViolationKind, RepositoryError,
|
|
dtos::Upsert,
|
|
encoding::{
|
|
decode_direction, decode_recurrence_unit, decode_weekend_adjustment, encode_direction,
|
|
encode_recurrence_unit, encode_weekend_adjustment,
|
|
},
|
|
};
|
|
use crate::{
|
|
database::{self, Constraint, DatabaseError, dtos::RecurringTransactionRow},
|
|
domain::{Cents, Recurrence, RecurrenceInterval, RecurringTransaction, Schedule},
|
|
};
|
|
|
|
pub struct Query {
|
|
pub limit: Option<u64>,
|
|
pub offset: Option<u64>,
|
|
}
|
|
|
|
pub async fn list<'e, E>(
|
|
executor: E,
|
|
user_id: Uuid,
|
|
query: Query,
|
|
) -> Result<Vec<RecurringTransaction>, RepositoryError>
|
|
where
|
|
E: sqlx::Executor<'e, Database = sqlx::Postgres>,
|
|
{
|
|
let query = database::recurring_transactions::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()?,
|
|
};
|
|
|
|
let transactions = database::recurring_transactions::list(executor, user_id, query)
|
|
.await?
|
|
.into_iter()
|
|
.map(decode)
|
|
.collect::<Result<_, _>>()?;
|
|
|
|
Ok(transactions)
|
|
}
|
|
|
|
pub async fn get_by_id<'e, E>(
|
|
executor: E,
|
|
user_id: Uuid,
|
|
id: Uuid,
|
|
) -> Result<Option<RecurringTransaction>, RepositoryError>
|
|
where
|
|
E: sqlx::Executor<'e, Database = sqlx::Postgres>,
|
|
{
|
|
let transaction = database::recurring_transactions::get_by_id(executor, user_id, id)
|
|
.await?
|
|
.map(decode)
|
|
.transpose()?;
|
|
|
|
Ok(transaction)
|
|
}
|
|
|
|
pub async fn upsert<'e, E>(
|
|
executor: E,
|
|
user_id: Uuid,
|
|
transaction: RecurringTransaction,
|
|
) -> Result<Option<Upsert<RecurringTransaction>>, RepositoryError>
|
|
where
|
|
E: sqlx::Executor<'e, Database = sqlx::Postgres>,
|
|
{
|
|
let upserted = database::recurring_transactions::upsert(executor, user_id, encode(transaction))
|
|
.await
|
|
.map_err(classify_upsert_error)?
|
|
.map(|upserted| upserted.try_map(decode))
|
|
.transpose()?
|
|
.map(Into::into);
|
|
|
|
Ok(upserted)
|
|
}
|
|
|
|
pub async fn delete_by_id<'e, E>(
|
|
executor: E,
|
|
user_id: Uuid,
|
|
id: Uuid,
|
|
) -> Result<Option<RecurringTransaction>, RepositoryError>
|
|
where
|
|
E: sqlx::Executor<'e, Database = sqlx::Postgres>,
|
|
{
|
|
let transaction = database::recurring_transactions::delete_by_id(executor, user_id, id)
|
|
.await?
|
|
.map(decode)
|
|
.transpose()?;
|
|
|
|
Ok(transaction)
|
|
}
|
|
|
|
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),
|
|
}
|
|
}
|
|
|
|
fn decode(row: RecurringTransactionRow) -> Result<RecurringTransaction, DecodeError> {
|
|
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();
|
|
let round_trip = decode(encode(transaction.clone())).unwrap();
|
|
assert_eq!(round_trip, transaction);
|
|
}
|
|
}
|