162 lines
4.8 KiB
Rust
162 lines
4.8 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::{Auth, Json, Path, Query},
|
|
};
|
|
use crate::{domain, error::AppError, repository};
|
|
|
|
pub fn create_router() -> axum::Router<crate::state::AppState> {
|
|
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>,
|
|
}
|
|
|
|
#[axum::debug_handler]
|
|
#[tracing::instrument(skip(pool))]
|
|
async fn list_scheduled_transactions(
|
|
Auth(auth): Auth,
|
|
State(pool): State<PgPool>,
|
|
Query(query): Query<QueryParams>,
|
|
) -> Result<Json<Vec<ScheduledTransactionResponse>>, AppError> {
|
|
let user_id = auth.user_id();
|
|
|
|
let query = repository::recurring_transactions::Query {
|
|
limit: Some(query.limit.unwrap_or(20)),
|
|
offset: query.offset,
|
|
};
|
|
|
|
let transactions = repository::recurring_transactions::list(&pool, user_id, query).await?;
|
|
let accounts = get_accounts_for_transactions(&pool, user_id, &transactions).await?;
|
|
|
|
let responses = transactions
|
|
.into_iter()
|
|
.map(|transaction| create_response(transaction, &accounts, Utc::now()))
|
|
.collect::<Result<Vec<_>, _>>()?;
|
|
|
|
Ok(Json(responses))
|
|
}
|
|
|
|
#[axum::debug_handler]
|
|
#[tracing::instrument(skip(pool))]
|
|
async fn get_scheduled_transaction(
|
|
Auth(auth): Auth,
|
|
State(pool): State<PgPool>,
|
|
Path(id): Path<Uuid>,
|
|
) -> Result<Json<ScheduledTransactionResponse>, AppError> {
|
|
let user_id = auth.user_id();
|
|
|
|
let transaction = repository::recurring_transactions::get_by_id(&pool, user_id, id)
|
|
.await?
|
|
.ok_or(AppError::NotFound)?;
|
|
let account = repository::accounts::get_by_id(&pool, user_id, transaction.account_id)
|
|
.await?
|
|
.ok_or(AppError::RaceCondition)?; // Account should be accessible!
|
|
|
|
Ok(Json(create_response(
|
|
transaction,
|
|
&HashMap::from([(account.id, account)]),
|
|
Utc::now(),
|
|
)?))
|
|
}
|
|
|
|
#[axum::debug_handler]
|
|
#[tracing::instrument(skip(pool, transaction))]
|
|
async fn upsert_scheduled_transaction(
|
|
Auth(auth): Auth,
|
|
State(pool): State<PgPool>,
|
|
Path(id): Path<Uuid>,
|
|
Json(transaction): Json<ScheduledTransactionRequest>,
|
|
) -> Result<(StatusCode, Json<ScheduledTransactionResponse>), AppError> {
|
|
let user_id = auth.user_id();
|
|
|
|
let ScheduledTransactionRequest::Recurring(transaction) = transaction;
|
|
|
|
let transaction = transaction.into_domain(id)?;
|
|
let account = repository::accounts::get_by_id(&pool, user_id, transaction.account_id)
|
|
.await?
|
|
.ok_or(AppError::AccountIdNotFound)?;
|
|
let upserted = repository::recurring_transactions::upsert(&pool, user_id, transaction)
|
|
.await?
|
|
.ok_or(AppError::ScheduledTransactionIdAlreadyExists)?;
|
|
|
|
let status = if upserted.previous.is_some() {
|
|
StatusCode::OK
|
|
} else {
|
|
StatusCode::CREATED
|
|
};
|
|
|
|
let accounts = HashMap::from([(account.id, account)]);
|
|
|
|
Ok((
|
|
status,
|
|
Json(create_response(upserted.current, &accounts, Utc::now())?),
|
|
))
|
|
}
|
|
|
|
#[axum::debug_handler]
|
|
#[tracing::instrument(skip(pool))]
|
|
async fn delete_scheduled_transaction(
|
|
Auth(auth): Auth,
|
|
State(pool): State<PgPool>,
|
|
Path(id): Path<Uuid>,
|
|
) -> Result<StatusCode, AppError> {
|
|
repository::recurring_transactions::delete_by_id(&pool, auth.user_id(), id)
|
|
.await?
|
|
.ok_or(AppError::NotFound)?;
|
|
|
|
Ok(StatusCode::NO_CONTENT)
|
|
}
|
|
|
|
async fn get_accounts_for_transactions<'e, E>(
|
|
executor: E,
|
|
user_id: Uuid,
|
|
transactions: &[domain::RecurringTransaction],
|
|
) -> Result<HashMap<Uuid, domain::Account>, AppError>
|
|
where
|
|
E: sqlx::Executor<'e, Database = sqlx::Postgres>,
|
|
{
|
|
let account_ids = transactions
|
|
.iter()
|
|
.map(|transaction| transaction.account_id)
|
|
.collect::<HashSet<_>>()
|
|
.into_iter()
|
|
.collect::<Vec<_>>();
|
|
|
|
Ok(repository::accounts::get_by_ids(executor, user_id, &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::Unknown)?;
|
|
|
|
let next = transaction.schedule.next_occurrence(now);
|
|
|
|
Ok(RecurringTransactionResponse::new(transaction, account, next).into())
|
|
}
|