149 lines
4.5 KiB
Rust
149 lines
4.5 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::{self, RepositoryError},
|
|
};
|
|
|
|
pub fn create_router() -> axum::Router<PgPool> {
|
|
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 query = repository::transactions::Query {
|
|
limit: Some(query.limit.unwrap_or(20)),
|
|
offset: query.offset,
|
|
};
|
|
|
|
let mut tx = pool.begin().await.map_err(RepositoryError::from)?;
|
|
let transactions = repository::transactions::list(&mut *tx, auth.user_id(), query).await?;
|
|
let accounts = get_accounts_for_transactions(&mut tx, auth.user_id(), &transactions).await?;
|
|
tx.commit().await.map_err(RepositoryError::from)?;
|
|
|
|
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 mut tx = pool.begin().await.map_err(RepositoryError::from)?;
|
|
let transaction = repository::transactions::get_by_id(&mut *tx, auth.user_id(), id)
|
|
.await?
|
|
.ok_or(AppError::NotFound)?;
|
|
let accounts =
|
|
get_accounts_for_transactions(&mut tx, auth.user_id(), std::slice::from_ref(&transaction))
|
|
.await?;
|
|
tx.commit().await.map_err(RepositoryError::from)?;
|
|
|
|
Ok(Json(create_response(transaction, &accounts)?))
|
|
}
|
|
|
|
#[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 transaction = transaction.into_domain(id)?;
|
|
|
|
let mut tx = pool.begin().await.map_err(RepositoryError::from)?;
|
|
let account = repository::accounts::get_by_id(&mut *tx, auth.user_id(), transaction.account_id)
|
|
.await?
|
|
.ok_or(AppError::AccountIdNotFound)?;
|
|
let upserted = repository::transactions::upsert(&mut *tx, auth.user_id(), transaction)
|
|
.await?
|
|
.ok_or(AppError::TransactionIdAlreadyExists)?;
|
|
tx.commit().await.map_err(RepositoryError::from)?;
|
|
|
|
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)?)))
|
|
}
|
|
|
|
#[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(
|
|
connection: &mut sqlx::PgConnection,
|
|
user_id: Uuid,
|
|
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(repository::accounts::get_by_ids(connection, 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))
|
|
}
|