158 lines
4.9 KiB
Rust
158 lines
4.9 KiB
Rust
use std::collections::{HashMap, HashSet};
|
|
|
|
use axum::{extract::State, http::StatusCode};
|
|
use chrono::{DateTime, Utc};
|
|
use serde::Deserialize;
|
|
use sqlx::PgPool;
|
|
use uuid::Uuid;
|
|
|
|
use super::{
|
|
dtos::scheduled_transaction::{
|
|
RecurringTransactionResponse, ScheduledTransactionRequest, ScheduledTransactionResponse,
|
|
},
|
|
extractors::{json::Json, path::Path, query::Query},
|
|
};
|
|
use crate::{
|
|
domain,
|
|
error::AppError,
|
|
repository::{
|
|
RepositoryError, accounts as account_repository,
|
|
dtos::{Delete, Upsert},
|
|
recurring_transactions as repository,
|
|
},
|
|
};
|
|
|
|
pub fn create_router() -> axum::Router<PgPool> {
|
|
axum::Router::new()
|
|
.route("/", axum::routing::get(list_scheduled_transactions))
|
|
.route(
|
|
"/{id}",
|
|
axum::routing::get(get_scheduled_transaction)
|
|
.put(upsert_scheduled_transaction)
|
|
.delete(delete_scheduled_transaction),
|
|
)
|
|
}
|
|
|
|
#[derive(Debug, Deserialize)]
|
|
pub struct QueryParams {
|
|
pub limit: Option<u64>,
|
|
pub offset: Option<u64>,
|
|
}
|
|
|
|
impl TryFrom<QueryParams> for repository::Query {
|
|
type Error = AppError;
|
|
|
|
fn try_from(query: QueryParams) -> Result<Self, Self::Error> {
|
|
Ok(repository::Query {
|
|
limit: Some(query.limit.unwrap_or(20)),
|
|
offset: query.offset,
|
|
..Default::default()
|
|
})
|
|
}
|
|
}
|
|
|
|
#[axum::debug_handler]
|
|
#[tracing::instrument(skip(pool))]
|
|
async fn list_scheduled_transactions(
|
|
State(pool): State<PgPool>,
|
|
Query(query): Query<QueryParams>,
|
|
) -> Result<Json<Vec<ScheduledTransactionResponse>>, AppError> {
|
|
let now = Utc::now();
|
|
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, &accounts, now))
|
|
.collect::<Result<Vec<_>, _>>()?;
|
|
|
|
Ok(Json(responses))
|
|
}
|
|
|
|
#[axum::debug_handler]
|
|
#[tracing::instrument(skip(pool))]
|
|
async fn get_scheduled_transaction(
|
|
State(pool): State<PgPool>,
|
|
Path(id): Path<Uuid>,
|
|
) -> Result<Json<ScheduledTransactionResponse>, AppError> {
|
|
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, &accounts, Utc::now())?))
|
|
}
|
|
|
|
#[axum::debug_handler]
|
|
#[tracing::instrument(skip(pool, transaction))]
|
|
async fn upsert_scheduled_transaction(
|
|
State(pool): State<PgPool>,
|
|
Path(id): Path<Uuid>,
|
|
Json(transaction): Json<ScheduledTransactionRequest>,
|
|
) -> Result<(StatusCode, Json<ScheduledTransactionResponse>), AppError> {
|
|
let ScheduledTransactionRequest::Recurring(transaction) = transaction;
|
|
let transaction = transaction.into_domain(id)?;
|
|
|
|
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, &accounts, Utc::now())?),
|
|
))
|
|
}
|
|
|
|
#[axum::debug_handler]
|
|
#[tracing::instrument(skip(pool))]
|
|
async fn delete_scheduled_transaction(
|
|
State(pool): State<PgPool>,
|
|
Path(id): Path<Uuid>,
|
|
) -> Result<StatusCode, AppError> {
|
|
match repository::delete(&pool, id).await? {
|
|
Delete::Deleted => Ok(StatusCode::NO_CONTENT),
|
|
Delete::NotFound => Err(AppError::NotFound),
|
|
}
|
|
}
|
|
|
|
async fn get_accounts_for_transactions(
|
|
connection: &mut sqlx::PgConnection,
|
|
transactions: &[domain::RecurringTransaction],
|
|
) -> 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::RecurringTransaction,
|
|
accounts: &HashMap<Uuid, domain::Account>,
|
|
now: DateTime<Utc>,
|
|
) -> Result<ScheduledTransactionResponse, AppError> {
|
|
let account = accounts
|
|
.get(&transaction.account_id)
|
|
.cloned()
|
|
.ok_or(AppError::Internal)?;
|
|
|
|
let next = transaction.schedule.next_occurrence(now);
|
|
|
|
Ok(RecurringTransactionResponse::new(transaction, account, next).into())
|
|
}
|