Refactored src and dst account to just account in preparation for a "counter party", instead of a full account.
This commit is contained in:
@@ -28,10 +28,9 @@ impl From<RecurringTransactionResponse> for ScheduledTransactionResponse {
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
pub struct RecurringTransactionRequest {
|
||||
pub name: String,
|
||||
pub account: AccountRequest,
|
||||
pub amount_cents: u64,
|
||||
pub direction: Direction,
|
||||
pub source_account: Option<AccountRequest>,
|
||||
pub destination_account: Option<AccountRequest>,
|
||||
pub schedule: ScheduleRequest,
|
||||
}
|
||||
|
||||
@@ -48,10 +47,9 @@ impl RecurringTransactionRequest {
|
||||
Ok(domain::RecurringTransaction {
|
||||
id,
|
||||
name: self.name,
|
||||
account_id: self.account.id,
|
||||
amount: self.amount_cents.try_into()?,
|
||||
direction: self.direction.into(),
|
||||
source_account_id: self.source_account.as_ref().map(|account| account.id),
|
||||
destination_account_id: self.destination_account.as_ref().map(|account| account.id),
|
||||
schedule: domain::Schedule::new(
|
||||
self.schedule.start,
|
||||
self.schedule.end,
|
||||
@@ -66,33 +64,27 @@ impl RecurringTransactionRequest {
|
||||
pub struct RecurringTransactionResponse {
|
||||
pub id: Uuid,
|
||||
pub name: String,
|
||||
pub account: AccountResponse,
|
||||
pub amount_cents: u64,
|
||||
pub direction: Direction,
|
||||
pub source_account: Option<AccountResponse>,
|
||||
pub destination_account: Option<AccountResponse>,
|
||||
pub schedule: ScheduleResponse,
|
||||
}
|
||||
|
||||
impl RecurringTransactionResponse {
|
||||
pub fn new(
|
||||
transaction: domain::RecurringTransaction,
|
||||
source_account: Option<domain::Account>,
|
||||
destination_account: Option<domain::Account>,
|
||||
account: domain::Account,
|
||||
schedule_next: Option<DateTime<Utc>>,
|
||||
) -> Self {
|
||||
Self {
|
||||
id: transaction.id,
|
||||
name: transaction.name,
|
||||
account: AccountResponse {
|
||||
id: account.id,
|
||||
name: account.name,
|
||||
},
|
||||
amount_cents: transaction.amount.get(),
|
||||
direction: transaction.direction.into(),
|
||||
source_account: source_account.map(|account| AccountResponse {
|
||||
id: account.id,
|
||||
name: account.name,
|
||||
}),
|
||||
destination_account: destination_account.map(|account| AccountResponse {
|
||||
id: account.id,
|
||||
name: account.name,
|
||||
}),
|
||||
schedule: ScheduleResponse::new(transaction.schedule, schedule_next),
|
||||
}
|
||||
}
|
||||
@@ -225,8 +217,10 @@ mod tests {
|
||||
let transaction = request().into_domain(Uuid::nil()).unwrap();
|
||||
ScheduledTransactionResponse::from(RecurringTransactionResponse::new(
|
||||
transaction,
|
||||
None,
|
||||
None,
|
||||
domain::Account {
|
||||
id: Uuid::nil(),
|
||||
name: "Checking".to_owned(),
|
||||
},
|
||||
None,
|
||||
))
|
||||
}
|
||||
@@ -234,10 +228,9 @@ mod tests {
|
||||
fn request() -> RecurringTransactionRequest {
|
||||
RecurringTransactionRequest {
|
||||
name: "Rent".to_owned(),
|
||||
account: super::AccountRequest { id: Uuid::nil() },
|
||||
amount_cents: 1234,
|
||||
direction: Direction::Out,
|
||||
source_account: None,
|
||||
destination_account: None,
|
||||
schedule: ScheduleRequest {
|
||||
start: Utc.with_ymd_and_hms(2026, 9, 24, 12, 0, 0).unwrap(),
|
||||
end: None,
|
||||
@@ -258,8 +251,10 @@ mod tests {
|
||||
assert_eq!(response["name"], "Rent");
|
||||
assert_eq!(response["amount_cents"], 1234);
|
||||
assert_eq!(response["direction"], "out");
|
||||
assert!(response["source_account"].is_null());
|
||||
assert!(response["destination_account"].is_null());
|
||||
assert_eq!(response["account"]["id"], Uuid::nil().to_string());
|
||||
assert_eq!(response["account"]["name"], "Checking");
|
||||
assert!(response.get("source_account").is_none());
|
||||
assert!(response.get("destination_account").is_none());
|
||||
assert!(response["schedule"]["start"].is_string());
|
||||
assert!(response["schedule"]["end"].is_null());
|
||||
assert_eq!(response["schedule"]["recurrence"]["every"], 2);
|
||||
@@ -274,39 +269,21 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn serializes_recurring_transaction_response_with_source_and_destination_accounts() {
|
||||
let source_id = Uuid::new_v4();
|
||||
let destination_id = Uuid::new_v4();
|
||||
|
||||
fn serializes_recurring_transaction_response_with_account() {
|
||||
let account_id = Uuid::new_v4();
|
||||
let mut transaction = request();
|
||||
transaction.source_account = Some(super::AccountRequest { id: source_id });
|
||||
transaction.destination_account = Some(super::AccountRequest { id: destination_id });
|
||||
|
||||
transaction.account = super::AccountRequest { id: account_id };
|
||||
let transaction = transaction.into_domain(Uuid::nil()).unwrap();
|
||||
let source_account = Some(domain::Account {
|
||||
id: source_id,
|
||||
let account = domain::Account {
|
||||
id: account_id,
|
||||
name: "Checking".to_owned(),
|
||||
});
|
||||
let destination_account = Some(domain::Account {
|
||||
id: destination_id,
|
||||
name: "Savings".to_owned(),
|
||||
});
|
||||
};
|
||||
|
||||
let response = RecurringTransactionResponse::new(
|
||||
transaction,
|
||||
source_account,
|
||||
destination_account,
|
||||
None,
|
||||
);
|
||||
let response = RecurringTransactionResponse::new(transaction, account, None);
|
||||
let response = serde_json::to_value(response).unwrap();
|
||||
|
||||
assert_eq!(response["source_account"]["id"], source_id.to_string());
|
||||
assert_eq!(response["source_account"]["name"], "Checking");
|
||||
assert_eq!(
|
||||
response["destination_account"]["id"],
|
||||
destination_id.to_string()
|
||||
);
|
||||
assert_eq!(response["destination_account"]["name"], "Savings");
|
||||
assert_eq!(response["account"]["id"], account_id.to_string());
|
||||
assert_eq!(response["account"]["name"], "Checking");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -315,6 +292,7 @@ mod tests {
|
||||
let request: ScheduledTransactionRequest = serde_json::from_value(response).unwrap();
|
||||
let ScheduledTransactionRequest::Recurring(request) = request;
|
||||
assert_eq!(request.name, "Rent");
|
||||
assert_eq!(request.account.id, Uuid::nil());
|
||||
assert_eq!(request.amount_cents, 1234);
|
||||
assert!(matches!(request.direction, Direction::Out));
|
||||
assert_eq!(
|
||||
@@ -342,6 +320,7 @@ mod tests {
|
||||
assert_eq!(transaction.id, id);
|
||||
assert_eq!(transaction.amount.get(), 1234);
|
||||
assert_eq!(transaction.direction, domain::Direction::Out);
|
||||
assert_eq!(transaction.account_id, Uuid::nil());
|
||||
assert_eq!(recurrence.every.get(), 2);
|
||||
assert_eq!(recurrence.unit, domain::RecurrenceUnit::Month);
|
||||
assert_eq!(
|
||||
@@ -349,4 +328,15 @@ mod tests {
|
||||
Some(domain::WeekendAdjustment::NextBusinessDay)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn requires_account_in_recurring_transaction_request() {
|
||||
let mut missing_account = serde_json::to_value(scheduled_response()).unwrap();
|
||||
missing_account.as_object_mut().unwrap().remove("account");
|
||||
assert!(serde_json::from_value::<ScheduledTransactionRequest>(missing_account).is_err());
|
||||
|
||||
let mut null_account = serde_json::to_value(scheduled_response()).unwrap();
|
||||
null_account["account"] = serde_json::Value::Null;
|
||||
assert!(serde_json::from_value::<ScheduledTransactionRequest>(null_account).is_err());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,20 +7,22 @@ use crate::domain;
|
||||
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
pub struct TransactionRequest {
|
||||
pub description: String,
|
||||
pub account: AccountRequest,
|
||||
pub amount_cents: u64,
|
||||
pub direction: Direction,
|
||||
pub date: DateTime<Utc>,
|
||||
pub description: String,
|
||||
}
|
||||
|
||||
impl TransactionRequest {
|
||||
pub fn into_domain(self, id: Uuid) -> Result<domain::Transaction, domain::DomainError> {
|
||||
Ok(domain::Transaction {
|
||||
id,
|
||||
description: self.description,
|
||||
account_id: self.account.id,
|
||||
amount: self.amount_cents.try_into()?,
|
||||
direction: self.direction.into(),
|
||||
date: self.date,
|
||||
description: self.description,
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -28,24 +30,40 @@ impl TransactionRequest {
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct TransactionResponse {
|
||||
pub id: Uuid,
|
||||
pub description: String,
|
||||
pub account: AccountResponse,
|
||||
pub amount_cents: u64,
|
||||
pub direction: Direction,
|
||||
pub date: DateTime<Utc>,
|
||||
pub description: String,
|
||||
}
|
||||
|
||||
impl From<domain::Transaction> for TransactionResponse {
|
||||
fn from(transaction: domain::Transaction) -> Self {
|
||||
impl TransactionResponse {
|
||||
pub fn new(transaction: domain::Transaction, account: domain::Account) -> Self {
|
||||
Self {
|
||||
id: transaction.id,
|
||||
description: transaction.description,
|
||||
account: AccountResponse {
|
||||
id: account.id,
|
||||
name: account.name,
|
||||
},
|
||||
amount_cents: transaction.amount.get(),
|
||||
direction: transaction.direction.into(),
|
||||
date: transaction.date,
|
||||
description: transaction.description,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
pub struct AccountRequest {
|
||||
pub id: Uuid,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct AccountResponse {
|
||||
pub id: Uuid,
|
||||
pub name: String,
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use chrono::TimeZone;
|
||||
@@ -54,10 +72,11 @@ mod tests {
|
||||
|
||||
fn request() -> TransactionRequest {
|
||||
TransactionRequest {
|
||||
description: "Groceries".to_string(),
|
||||
account: AccountRequest { id: Uuid::nil() },
|
||||
amount_cents: 4250,
|
||||
direction: Direction::Out,
|
||||
date: Utc.with_ymd_and_hms(2026, 9, 29, 12, 0, 0).unwrap(),
|
||||
description: "Groceries".to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -66,26 +85,53 @@ mod tests {
|
||||
let id = Uuid::nil();
|
||||
let date = request().date;
|
||||
let transaction = request().into_domain(id).unwrap();
|
||||
let response = serde_json::to_value(TransactionResponse::from(transaction)).unwrap();
|
||||
let account = domain::Account {
|
||||
id: Uuid::nil(),
|
||||
name: "Checking".to_owned(),
|
||||
};
|
||||
let response =
|
||||
serde_json::to_value(TransactionResponse::new(transaction, account)).unwrap();
|
||||
|
||||
assert_eq!(response["id"], id.to_string());
|
||||
assert_eq!(response["description"], "Groceries");
|
||||
assert_eq!(response["account"]["id"], Uuid::nil().to_string());
|
||||
assert_eq!(response["account"]["name"], "Checking");
|
||||
assert_eq!(response["amount_cents"], 4250);
|
||||
assert_eq!(response["direction"], "out");
|
||||
assert_eq!(response["date"], serde_json::to_value(date).unwrap());
|
||||
assert_eq!(response["description"], "Groceries");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deserializes_transaction_response_as_request() {
|
||||
let date = request().date;
|
||||
let transaction = request().into_domain(Uuid::nil()).unwrap();
|
||||
let response = serde_json::to_value(TransactionResponse::from(transaction)).unwrap();
|
||||
let account = domain::Account {
|
||||
id: Uuid::nil(),
|
||||
name: "Checking".to_owned(),
|
||||
};
|
||||
let response =
|
||||
serde_json::to_value(TransactionResponse::new(transaction, account)).unwrap();
|
||||
let request: TransactionRequest = serde_json::from_value(response).unwrap();
|
||||
|
||||
assert_eq!(request.description, "Groceries");
|
||||
assert_eq!(request.amount_cents, 4250);
|
||||
assert_eq!(request.account.id, Uuid::nil());
|
||||
assert!(matches!(request.direction, Direction::Out));
|
||||
assert_eq!(request.date, date);
|
||||
assert_eq!(request.description, "Groceries");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn requires_account_in_transaction_request() {
|
||||
let transaction = request().into_domain(Uuid::nil()).unwrap();
|
||||
let account = domain::Account {
|
||||
id: Uuid::nil(),
|
||||
name: "Checking".to_owned(),
|
||||
};
|
||||
let mut response =
|
||||
serde_json::to_value(TransactionResponse::new(transaction, account)).unwrap();
|
||||
response.as_object_mut().unwrap().remove("account");
|
||||
|
||||
assert!(serde_json::from_value::<TransactionRequest>(response).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -93,18 +139,28 @@ mod tests {
|
||||
let id = Uuid::new_v4();
|
||||
let request = request();
|
||||
let date = request.date;
|
||||
let account_id = request.account.id;
|
||||
|
||||
let transaction = request.into_domain(id).unwrap();
|
||||
assert_eq!(transaction.id, id);
|
||||
assert_eq!(transaction.account_id, account_id);
|
||||
assert_eq!(transaction.amount.get(), 4250);
|
||||
assert_eq!(transaction.direction, domain::Direction::Out);
|
||||
assert_eq!(transaction.date, date);
|
||||
|
||||
let response = TransactionResponse::from(transaction);
|
||||
let response = TransactionResponse::new(
|
||||
transaction,
|
||||
domain::Account {
|
||||
id: account_id,
|
||||
name: "Checking".to_owned(),
|
||||
},
|
||||
);
|
||||
assert_eq!(response.id, id);
|
||||
assert_eq!(response.description, "Groceries");
|
||||
assert_eq!(response.account.id, account_id);
|
||||
assert_eq!(response.account.name, "Checking");
|
||||
assert_eq!(response.amount_cents, 4250);
|
||||
assert!(matches!(response.direction, Direction::Out));
|
||||
assert_eq!(response.date, date);
|
||||
assert_eq!(response.description, "Groceries");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -68,7 +68,7 @@ async fn list_scheduled_transactions(
|
||||
let responses = transactions
|
||||
.into_iter()
|
||||
.map(|transaction| create_response(transaction, &accounts, now))
|
||||
.collect();
|
||||
.collect::<Result<Vec<_>, _>>()?;
|
||||
|
||||
Ok(Json(responses))
|
||||
}
|
||||
@@ -87,7 +87,7 @@ async fn get_scheduled_transaction(
|
||||
get_accounts_for_transactions(&mut tx, std::slice::from_ref(&transaction)).await?;
|
||||
tx.commit().await.map_err(RepositoryError::from)?;
|
||||
|
||||
Ok(Json(create_response(transaction, &accounts, Utc::now())))
|
||||
Ok(Json(create_response(transaction, &accounts, Utc::now())?))
|
||||
}
|
||||
|
||||
#[axum::debug_handler]
|
||||
@@ -111,7 +111,7 @@ async fn upsert_scheduled_transaction(
|
||||
|
||||
Ok((
|
||||
status,
|
||||
Json(create_response(transaction, &accounts, Utc::now())),
|
||||
Json(create_response(transaction, &accounts, Utc::now())?),
|
||||
))
|
||||
}
|
||||
|
||||
@@ -133,13 +133,7 @@ async fn get_accounts_for_transactions(
|
||||
) -> Result<HashMap<Uuid, domain::Account>, AppError> {
|
||||
let account_ids = transactions
|
||||
.iter()
|
||||
.flat_map(|transaction| {
|
||||
[
|
||||
transaction.source_account_id,
|
||||
transaction.destination_account_id,
|
||||
]
|
||||
})
|
||||
.flatten()
|
||||
.map(|transaction| transaction.account_id)
|
||||
.collect::<HashSet<_>>()
|
||||
.into_iter()
|
||||
.collect::<Vec<_>>();
|
||||
@@ -151,15 +145,13 @@ fn create_response(
|
||||
transaction: domain::RecurringTransaction,
|
||||
accounts: &HashMap<Uuid, domain::Account>,
|
||||
now: DateTime<Utc>,
|
||||
) -> ScheduledTransactionResponse {
|
||||
let source_account = transaction
|
||||
.source_account_id
|
||||
.and_then(|id| accounts.get(&id).cloned());
|
||||
let destination_account = transaction
|
||||
.destination_account_id
|
||||
.and_then(|id| accounts.get(&id).cloned());
|
||||
) -> Result<ScheduledTransactionResponse, AppError> {
|
||||
let account = accounts
|
||||
.get(&transaction.account_id)
|
||||
.cloned()
|
||||
.ok_or(AppError::Internal)?;
|
||||
|
||||
let next = transaction.schedule.next_occurrence(now);
|
||||
|
||||
RecurringTransactionResponse::new(transaction, source_account, destination_account, next).into()
|
||||
Ok(RecurringTransactionResponse::new(transaction, account, next).into())
|
||||
}
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
use std::collections::{HashMap, HashSet};
|
||||
|
||||
use axum::{extract::State, http::StatusCode};
|
||||
use serde::Deserialize;
|
||||
use sqlx::PgPool;
|
||||
@@ -8,8 +10,10 @@ use super::{
|
||||
extractors::{json::Json, path::Path, query::Query},
|
||||
};
|
||||
use crate::{
|
||||
domain,
|
||||
error::AppError,
|
||||
repository::{
|
||||
RepositoryError, accounts as account_repository,
|
||||
dtos::{Delete, Upsert},
|
||||
transactions as repository,
|
||||
},
|
||||
@@ -50,13 +54,17 @@ async fn list_transactions(
|
||||
State(pool): State<PgPool>,
|
||||
Query(query): Query<QueryParams>,
|
||||
) -> Result<Json<Vec<TransactionResponse>>, AppError> {
|
||||
let transactions = repository::list(&pool, query.try_into()?)
|
||||
.await?
|
||||
.into_iter()
|
||||
.map(TransactionResponse::from)
|
||||
.collect();
|
||||
let mut tx = pool.begin().await.map_err(RepositoryError::from)?;
|
||||
let transactions = repository::list(&mut *tx, query.try_into()?).await?;
|
||||
let accounts = get_accounts_for_transactions(&mut tx, &transactions).await?;
|
||||
tx.commit().await.map_err(RepositoryError::from)?;
|
||||
|
||||
Ok(Json(transactions))
|
||||
let responses = transactions
|
||||
.into_iter()
|
||||
.map(|transaction| create_response(transaction, &accounts))
|
||||
.collect::<Result<Vec<_>, _>>()?;
|
||||
|
||||
Ok(Json(responses))
|
||||
}
|
||||
|
||||
#[axum::debug_handler]
|
||||
@@ -65,11 +73,15 @@ async fn get_transaction(
|
||||
State(pool): State<PgPool>,
|
||||
Path(id): Path<Uuid>,
|
||||
) -> Result<Json<TransactionResponse>, AppError> {
|
||||
let transaction = repository::get(&pool, id)
|
||||
let mut tx = pool.begin().await.map_err(RepositoryError::from)?;
|
||||
let transaction = repository::get(&mut *tx, id)
|
||||
.await?
|
||||
.ok_or(AppError::NotFound)?;
|
||||
let accounts =
|
||||
get_accounts_for_transactions(&mut tx, std::slice::from_ref(&transaction)).await?;
|
||||
tx.commit().await.map_err(RepositoryError::from)?;
|
||||
|
||||
Ok(Json(transaction.into()))
|
||||
Ok(Json(create_response(transaction, &accounts)?))
|
||||
}
|
||||
|
||||
#[axum::debug_handler]
|
||||
@@ -81,12 +93,16 @@ async fn upsert_transaction(
|
||||
) -> Result<(StatusCode, Json<TransactionResponse>), AppError> {
|
||||
let transaction = transaction.into_domain(id)?;
|
||||
|
||||
let (status, transaction) = match repository::upsert(&pool, transaction).await? {
|
||||
let mut tx = pool.begin().await.map_err(RepositoryError::from)?;
|
||||
let (status, transaction) = match repository::upsert(&mut *tx, transaction).await? {
|
||||
Upsert::Created(transaction) => (StatusCode::CREATED, transaction),
|
||||
Upsert::Updated(transaction) => (StatusCode::OK, transaction),
|
||||
};
|
||||
let accounts =
|
||||
get_accounts_for_transactions(&mut tx, std::slice::from_ref(&transaction)).await?;
|
||||
tx.commit().await.map_err(RepositoryError::from)?;
|
||||
|
||||
Ok((status, Json(transaction.into())))
|
||||
Ok((status, Json(create_response(transaction, &accounts)?)))
|
||||
}
|
||||
|
||||
#[axum::debug_handler]
|
||||
@@ -100,3 +116,29 @@ async fn delete_transaction(
|
||||
Delete::NotFound => Err(AppError::NotFound),
|
||||
}
|
||||
}
|
||||
|
||||
async fn get_accounts_for_transactions(
|
||||
connection: &mut sqlx::PgConnection,
|
||||
transactions: &[domain::Transaction],
|
||||
) -> Result<HashMap<Uuid, domain::Account>, AppError> {
|
||||
let account_ids = transactions
|
||||
.iter()
|
||||
.map(|transaction| transaction.account_id)
|
||||
.collect::<HashSet<_>>()
|
||||
.into_iter()
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
Ok(account_repository::get_by_ids(connection, &account_ids).await?)
|
||||
}
|
||||
|
||||
fn create_response(
|
||||
transaction: domain::Transaction,
|
||||
accounts: &HashMap<Uuid, domain::Account>,
|
||||
) -> Result<TransactionResponse, AppError> {
|
||||
let account = accounts
|
||||
.get(&transaction.account_id)
|
||||
.cloned()
|
||||
.ok_or(AppError::Internal)?;
|
||||
|
||||
Ok(TransactionResponse::new(transaction, account))
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user