154 lines
4.3 KiB
Rust
154 lines
4.3 KiB
Rust
use std::collections::{HashMap, HashSet};
|
|
|
|
use axum::{extract::State, http::StatusCode};
|
|
use serde::Deserialize;
|
|
use sqlx::PgPool;
|
|
use uuid::Uuid;
|
|
|
|
use super::{
|
|
dtos::transaction::{TransactionRequest, TransactionResponse},
|
|
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_transactions))
|
|
.route(
|
|
"/{id}",
|
|
axum::routing::get(get_transaction)
|
|
.put(upsert_transaction)
|
|
.delete(delete_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_transactions(
|
|
Auth(auth): Auth,
|
|
State(pool): State<PgPool>,
|
|
Query(query): Query<QueryParams>,
|
|
) -> Result<Json<Vec<TransactionResponse>>, AppError> {
|
|
let user_id = auth.user_id();
|
|
|
|
let query = repository::transactions::Query {
|
|
limit: Some(query.limit.unwrap_or(20)),
|
|
offset: query.offset,
|
|
};
|
|
|
|
let transactions = repository::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))
|
|
.collect::<Result<Vec<_>, _>>()?;
|
|
|
|
Ok(Json(responses))
|
|
}
|
|
|
|
#[axum::debug_handler]
|
|
#[tracing::instrument(skip(pool))]
|
|
async fn get_transaction(
|
|
Auth(auth): Auth,
|
|
State(pool): State<PgPool>,
|
|
Path(id): Path<Uuid>,
|
|
) -> Result<Json<TransactionResponse>, AppError> {
|
|
let user_id = auth.user_id();
|
|
|
|
let transaction = repository::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 exist!
|
|
|
|
Ok(Json(create_response(
|
|
transaction,
|
|
&HashMap::from([(account.id, account)]),
|
|
)?))
|
|
}
|
|
|
|
#[axum::debug_handler]
|
|
#[tracing::instrument(skip(pool, transaction))]
|
|
async fn upsert_transaction(
|
|
Auth(auth): Auth,
|
|
State(pool): State<PgPool>,
|
|
Path(id): Path<Uuid>,
|
|
Json(transaction): Json<TransactionRequest>,
|
|
) -> Result<(StatusCode, Json<TransactionResponse>), AppError> {
|
|
let user_id = auth.user_id();
|
|
|
|
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::transactions::upsert(&pool, user_id, transaction)
|
|
.await?
|
|
.ok_or(AppError::TransactionIdAlreadyExists)?;
|
|
|
|
let status = if upserted.previous.is_some() {
|
|
StatusCode::OK
|
|
} else {
|
|
StatusCode::CREATED
|
|
};
|
|
|
|
Ok((
|
|
status,
|
|
Json(create_response(
|
|
upserted.current,
|
|
&HashMap::from([(account.id, account)]),
|
|
)?),
|
|
))
|
|
}
|
|
|
|
#[axum::debug_handler]
|
|
#[tracing::instrument(skip(pool))]
|
|
async fn delete_transaction(
|
|
Auth(auth): Auth,
|
|
Path(id): Path<Uuid>,
|
|
State(pool): State<PgPool>,
|
|
) -> Result<StatusCode, AppError> {
|
|
repository::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::Transaction],
|
|
) -> 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::Transaction,
|
|
accounts: &HashMap<Uuid, domain::Account>,
|
|
) -> Result<TransactionResponse, AppError> {
|
|
let account = accounts
|
|
.get(&transaction.account_id)
|
|
.cloned()
|
|
.ok_or(AppError::Unknown)?;
|
|
|
|
Ok(TransactionResponse::new(transaction, account))
|
|
}
|