Return account details.
This commit is contained in:
+28
@@ -0,0 +1,28 @@
|
||||
{
|
||||
"db_name": "PostgreSQL",
|
||||
"query": "\n\t\tSELECT id, name\n\t\tFROM accounts\n\t\tWHERE id = ANY($1)\n\t\t",
|
||||
"describe": {
|
||||
"columns": [
|
||||
{
|
||||
"ordinal": 0,
|
||||
"name": "id",
|
||||
"type_info": "Uuid"
|
||||
},
|
||||
{
|
||||
"ordinal": 1,
|
||||
"name": "name",
|
||||
"type_info": "Text"
|
||||
}
|
||||
],
|
||||
"parameters": {
|
||||
"Left": [
|
||||
"UuidArray"
|
||||
]
|
||||
},
|
||||
"nullable": [
|
||||
false,
|
||||
false
|
||||
]
|
||||
},
|
||||
"hash": "016dcd0136e2284546f7ad4db96cadba51847776866997f0e978cff9c869c635"
|
||||
}
|
||||
@@ -1,3 +1,14 @@
|
||||
INSERT INTO
|
||||
accounts (id, name)
|
||||
VALUES (
|
||||
'00000000-0000-0000-0000-000000000001',
|
||||
'Checking Account'
|
||||
),
|
||||
(
|
||||
'00000000-0000-0000-0000-000000000002',
|
||||
'Savings Account'
|
||||
);
|
||||
|
||||
INSERT INTO
|
||||
transactions (
|
||||
id,
|
||||
@@ -27,6 +38,8 @@ INSERT INTO
|
||||
name,
|
||||
amount_cents,
|
||||
direction,
|
||||
source_account_id,
|
||||
destination_account_id,
|
||||
starts_at,
|
||||
ends_at,
|
||||
recurrence_every,
|
||||
@@ -38,6 +51,8 @@ VALUES (
|
||||
'Salary',
|
||||
320000,
|
||||
'in',
|
||||
'00000000-0000-0000-0000-000000000001',
|
||||
NULL,
|
||||
'2026-10-01T09:00:00Z',
|
||||
NULL,
|
||||
1,
|
||||
@@ -49,20 +64,11 @@ VALUES (
|
||||
'Rent',
|
||||
125000,
|
||||
'out',
|
||||
NULL,
|
||||
'00000000-0000-0000-0000-000000000001',
|
||||
'2026-10-01T09:00:00Z',
|
||||
NULL,
|
||||
1,
|
||||
'month',
|
||||
'previous_business_day'
|
||||
);
|
||||
|
||||
INSERT INTO
|
||||
accounts (id, name)
|
||||
VALUES (
|
||||
'00000000-0000-0000-0000-000000000001',
|
||||
'Checking Account'
|
||||
),
|
||||
(
|
||||
'00000000-0000-0000-0000-000000000002',
|
||||
'Savings Account'
|
||||
);
|
||||
@@ -62,6 +62,24 @@ where
|
||||
.map_err(DatabaseError::from)
|
||||
}
|
||||
|
||||
pub async fn get_by_ids<'e, E>(executor: E, ids: &[Uuid]) -> Result<Vec<AccountRow>, DatabaseError>
|
||||
where
|
||||
E: sqlx::Executor<'e, Database = sqlx::Postgres>,
|
||||
{
|
||||
sqlx::query_as!(
|
||||
AccountRow,
|
||||
r#"
|
||||
SELECT id, name
|
||||
FROM accounts
|
||||
WHERE id = ANY($1)
|
||||
"#,
|
||||
ids,
|
||||
)
|
||||
.fetch_all(executor)
|
||||
.await
|
||||
.map_err(DatabaseError::from)
|
||||
}
|
||||
|
||||
pub async fn upsert<'e, E>(
|
||||
executor: E,
|
||||
account: AccountRow,
|
||||
|
||||
@@ -21,6 +21,12 @@ pub enum RepositoryError {
|
||||
QueryConversion(#[from] QueryConversionError),
|
||||
}
|
||||
|
||||
impl From<sqlx::Error> for RepositoryError {
|
||||
fn from(error: sqlx::Error) -> Self {
|
||||
Self::Database(DatabaseError::from(error))
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum DecodeError {
|
||||
#[error(transparent)]
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
use std::collections::HashMap;
|
||||
|
||||
use uuid::Uuid;
|
||||
|
||||
use super::{
|
||||
@@ -66,6 +68,29 @@ where
|
||||
Ok(account)
|
||||
}
|
||||
|
||||
pub async fn get_by_ids<'e, E>(
|
||||
executor: E,
|
||||
ids: &[Uuid],
|
||||
) -> Result<HashMap<Uuid, Account>, RepositoryError>
|
||||
where
|
||||
E: sqlx::Executor<'e, Database = sqlx::Postgres>,
|
||||
{
|
||||
if ids.is_empty() {
|
||||
return Ok(HashMap::new());
|
||||
}
|
||||
|
||||
let accounts = db::get_by_ids(executor, ids)
|
||||
.await?
|
||||
.into_iter()
|
||||
.map(decode)
|
||||
.collect::<Result<Vec<_>, DecodeError>>()?;
|
||||
|
||||
Ok(accounts
|
||||
.into_iter()
|
||||
.map(|account| (account.id, account))
|
||||
.collect())
|
||||
}
|
||||
|
||||
pub async fn upsert<'e, E>(
|
||||
executor: E,
|
||||
account: Account,
|
||||
|
||||
@@ -30,8 +30,8 @@ pub struct RecurringTransactionRequest {
|
||||
pub name: String,
|
||||
pub amount_cents: u64,
|
||||
pub direction: Direction,
|
||||
pub source_account_id: Option<Uuid>,
|
||||
pub destination_account_id: Option<Uuid>,
|
||||
pub source_account: Option<SourceAccountRequest>,
|
||||
pub destination_account: Option<DestinationAccountRequest>,
|
||||
pub schedule: ScheduleRequest,
|
||||
}
|
||||
|
||||
@@ -50,8 +50,8 @@ impl RecurringTransactionRequest {
|
||||
name: self.name,
|
||||
amount: domain::Cents::try_from(self.amount_cents)?,
|
||||
direction: self.direction.into(),
|
||||
source_account_id: self.source_account_id,
|
||||
destination_account_id: self.destination_account_id,
|
||||
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,
|
||||
@@ -68,25 +68,58 @@ pub struct RecurringTransactionResponse {
|
||||
pub name: String,
|
||||
pub amount_cents: u64,
|
||||
pub direction: Direction,
|
||||
pub source_account_id: Option<Uuid>,
|
||||
pub destination_account_id: Option<Uuid>,
|
||||
pub source_account: Option<SourceAccountResponse>,
|
||||
pub destination_account: Option<DestinationAccountResponse>,
|
||||
pub schedule: ScheduleResponse,
|
||||
}
|
||||
|
||||
impl RecurringTransactionResponse {
|
||||
pub fn new(transaction: domain::RecurringTransaction, next: Option<DateTime<Utc>>) -> Self {
|
||||
pub fn new(
|
||||
transaction: domain::RecurringTransaction,
|
||||
source_account: Option<domain::Account>,
|
||||
destination_account: Option<domain::Account>,
|
||||
schedule_next: Option<DateTime<Utc>>,
|
||||
) -> Self {
|
||||
Self {
|
||||
id: transaction.id,
|
||||
name: transaction.name,
|
||||
amount_cents: transaction.amount.get(),
|
||||
direction: transaction.direction.into(),
|
||||
source_account_id: transaction.source_account_id,
|
||||
destination_account_id: transaction.destination_account_id,
|
||||
schedule: ScheduleResponse::new(transaction.schedule, next),
|
||||
source_account: source_account.map(|account| SourceAccountResponse {
|
||||
id: account.id,
|
||||
name: account.name,
|
||||
}),
|
||||
destination_account: destination_account.map(|account| DestinationAccountResponse {
|
||||
id: account.id,
|
||||
name: account.name,
|
||||
}),
|
||||
schedule: ScheduleResponse::new(transaction.schedule, schedule_next),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
pub struct SourceAccountRequest {
|
||||
pub id: Uuid,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct SourceAccountResponse {
|
||||
pub id: Uuid,
|
||||
pub name: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
pub struct DestinationAccountRequest {
|
||||
pub id: Uuid,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct DestinationAccountResponse {
|
||||
pub id: Uuid,
|
||||
pub name: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
pub struct ScheduleRequest {
|
||||
pub start: DateTime<Utc>,
|
||||
@@ -207,8 +240,8 @@ mod tests {
|
||||
name: String::new(),
|
||||
amount_cents,
|
||||
direction: Direction::Out,
|
||||
source_account_id: None,
|
||||
destination_account_id: None,
|
||||
source_account: None,
|
||||
destination_account: None,
|
||||
schedule: ScheduleRequest {
|
||||
start: Utc.with_ymd_and_hms(2026, 9, 24, 12, 0, 0).unwrap(),
|
||||
end: None,
|
||||
@@ -224,15 +257,22 @@ mod tests {
|
||||
#[test]
|
||||
fn serializes_scheduled_transaction_with_nested_schedule() {
|
||||
let transaction = request(1234).into_domain(Uuid::nil()).unwrap();
|
||||
let source_account = None;
|
||||
let destination_account = None;
|
||||
let schedule_next = None;
|
||||
let response = ScheduledTransactionResponse::from(RecurringTransactionResponse::new(
|
||||
transaction,
|
||||
None,
|
||||
source_account,
|
||||
destination_account,
|
||||
schedule_next,
|
||||
));
|
||||
|
||||
let response = serde_json::to_value(response).unwrap();
|
||||
assert_eq!(response["type"], "recurring");
|
||||
assert_eq!(response["id"], Uuid::nil().to_string());
|
||||
assert_eq!(response["amount_cents"], 1234);
|
||||
assert!(response["source_account"].is_null());
|
||||
assert!(response["destination_account"].is_null());
|
||||
assert_eq!(response["schedule"]["recurrence"]["unit"], "month");
|
||||
assert_eq!(
|
||||
response["schedule"]["weekend_adjustment"],
|
||||
@@ -248,6 +288,41 @@ mod tests {
|
||||
assert_eq!(request.schedule.recurrence.every, 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn serializes_source_and_destination_accounts() {
|
||||
let source_id = Uuid::new_v4();
|
||||
let destination_id = Uuid::new_v4();
|
||||
let mut transaction = request(1234);
|
||||
transaction.source_account = Some(super::SourceAccountRequest { id: source_id });
|
||||
transaction.destination_account =
|
||||
Some(super::DestinationAccountRequest { id: destination_id });
|
||||
let transaction = transaction.into_domain(Uuid::nil()).unwrap();
|
||||
let source_account = Some(domain::Account {
|
||||
id: source_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 = 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");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn converts_to_domain() {
|
||||
let id = Uuid::new_v4();
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
use std::collections::{HashMap, HashSet};
|
||||
|
||||
use axum::{extract::State, http::StatusCode};
|
||||
use chrono::{DateTime, Utc};
|
||||
use serde::Deserialize;
|
||||
@@ -14,6 +16,7 @@ use crate::{
|
||||
domain,
|
||||
error::AppError,
|
||||
repository::{
|
||||
RepositoryError, accounts as account_repository,
|
||||
dtos::{Delete, Upsert},
|
||||
recurring_transactions as repository,
|
||||
},
|
||||
@@ -55,13 +58,19 @@ async fn list_scheduled_transactions(
|
||||
Query(query): Query<QueryParams>,
|
||||
) -> Result<Json<Vec<ScheduledTransactionResponse>>, AppError> {
|
||||
let now = Utc::now();
|
||||
let transactions = repository::query(&pool, query.try_into()?)
|
||||
.await?
|
||||
let query = query.try_into()?;
|
||||
|
||||
let mut tx = pool.begin().await.map_err(RepositoryError::from)?;
|
||||
let transactions = repository::query(&mut *tx, query).await?;
|
||||
let accounts = get_accounts_for_transactions(&mut tx, &transactions).await?;
|
||||
tx.commit().await.map_err(RepositoryError::from)?;
|
||||
|
||||
let responses = transactions
|
||||
.into_iter()
|
||||
.map(|transaction| create_response(transaction, now))
|
||||
.map(|transaction| create_response(transaction, &accounts, now))
|
||||
.collect();
|
||||
|
||||
Ok(Json(transactions))
|
||||
Ok(Json(responses))
|
||||
}
|
||||
|
||||
#[axum::debug_handler]
|
||||
@@ -70,11 +79,15 @@ async fn get_scheduled_transaction(
|
||||
State(pool): State<PgPool>,
|
||||
Path(id): Path<Uuid>,
|
||||
) -> Result<Json<ScheduledTransactionResponse>, 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(create_response(transaction, Utc::now())))
|
||||
Ok(Json(create_response(transaction, &accounts, Utc::now())))
|
||||
}
|
||||
|
||||
#[axum::debug_handler]
|
||||
@@ -87,12 +100,19 @@ async fn upsert_scheduled_transaction(
|
||||
let ScheduledTransactionRequest::Recurring(transaction) = transaction;
|
||||
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(create_response(transaction, Utc::now()))))
|
||||
Ok((
|
||||
status,
|
||||
Json(create_response(transaction, &accounts, Utc::now())),
|
||||
))
|
||||
}
|
||||
|
||||
#[axum::debug_handler]
|
||||
@@ -107,11 +127,39 @@ async fn delete_scheduled_transaction(
|
||||
}
|
||||
}
|
||||
|
||||
async fn get_accounts_for_transactions(
|
||||
connection: &mut sqlx::PgConnection,
|
||||
transactions: &[domain::RecurringTransaction],
|
||||
) -> Result<HashMap<Uuid, domain::Account>, AppError> {
|
||||
let account_ids = transactions
|
||||
.iter()
|
||||
.flat_map(|transaction| {
|
||||
[
|
||||
transaction.source_account_id,
|
||||
transaction.destination_account_id,
|
||||
]
|
||||
})
|
||||
.flatten()
|
||||
.collect::<HashSet<_>>()
|
||||
.into_iter()
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
Ok(account_repository::get_by_ids(connection, &account_ids).await?)
|
||||
}
|
||||
|
||||
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());
|
||||
|
||||
let next = transaction.schedule.next_occurrence(now);
|
||||
|
||||
RecurringTransactionResponse::new(transaction, next).into()
|
||||
RecurringTransactionResponse::new(transaction, source_account, destination_account, next).into()
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user