Made scheduled transactions more generic.
This commit is contained in:
@@ -1,2 +1,2 @@
|
||||
pub mod expense;
|
||||
pub mod scheduled_transaction;
|
||||
pub mod transaction;
|
||||
|
||||
+2
-1
@@ -1,10 +1,11 @@
|
||||
use chrono::{DateTime, Utc};
|
||||
use uuid::Uuid;
|
||||
|
||||
pub struct RecurringExpenseRow {
|
||||
pub struct RecurringTransactionRow {
|
||||
pub id: Uuid,
|
||||
pub name: String,
|
||||
pub amount_cents: i64,
|
||||
pub direction: String,
|
||||
pub starts_at: DateTime<Utc>,
|
||||
pub ends_at: Option<DateTime<Utc>>,
|
||||
pub recurrence_every: i32,
|
||||
@@ -5,5 +5,6 @@ pub struct TransactionRow {
|
||||
pub id: Uuid,
|
||||
pub description: String,
|
||||
pub amount_cents: i64,
|
||||
pub direction: String,
|
||||
pub date: DateTime<Utc>,
|
||||
}
|
||||
|
||||
+18
-7
@@ -3,12 +3,16 @@ use axum::{
|
||||
response::{IntoResponse, Response},
|
||||
};
|
||||
|
||||
use crate::routes::dtos::expense::RecurringExpenseConversionError;
|
||||
use crate::routes::dtos::{
|
||||
direction::TransactionDirectionConversionError,
|
||||
scheduled_transaction::RecurringTransactionConversionError,
|
||||
};
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum AppError {
|
||||
Database(sqlx::Error),
|
||||
RecurringExpense(RecurringExpenseConversionError),
|
||||
Direction(TransactionDirectionConversionError),
|
||||
RecurringTransaction(RecurringTransactionConversionError),
|
||||
}
|
||||
|
||||
impl From<sqlx::Error> for AppError {
|
||||
@@ -17,9 +21,15 @@ impl From<sqlx::Error> for AppError {
|
||||
}
|
||||
}
|
||||
|
||||
impl From<RecurringExpenseConversionError> for AppError {
|
||||
fn from(error: RecurringExpenseConversionError) -> Self {
|
||||
Self::RecurringExpense(error)
|
||||
impl From<TransactionDirectionConversionError> for AppError {
|
||||
fn from(error: TransactionDirectionConversionError) -> Self {
|
||||
Self::Direction(error)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<RecurringTransactionConversionError> for AppError {
|
||||
fn from(error: RecurringTransactionConversionError) -> Self {
|
||||
Self::RecurringTransaction(error)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -27,8 +37,9 @@ impl IntoResponse for AppError {
|
||||
fn into_response(self) -> Response {
|
||||
match self {
|
||||
Self::Database(error) => tracing::error!(%error, "Database query failed"),
|
||||
Self::RecurringExpense(error) => {
|
||||
tracing::error!(%error, "Invalid recurring expense data")
|
||||
Self::Direction(error) => tracing::error!(%error, "Invalid transaction direction"),
|
||||
Self::RecurringTransaction(error) => {
|
||||
tracing::error!(%error, "Invalid recurring transaction data")
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
pub mod dtos;
|
||||
mod expenses;
|
||||
mod scheduled_transactions;
|
||||
mod transactions;
|
||||
|
||||
pub fn create_router(pool: sqlx::PgPool) -> axum::Router {
|
||||
@@ -7,7 +7,10 @@ pub fn create_router(pool: sqlx::PgPool) -> axum::Router {
|
||||
.nest(
|
||||
"/api",
|
||||
axum::Router::new()
|
||||
.nest("/expenses", expenses::create_router())
|
||||
.nest(
|
||||
"/scheduled-transactions",
|
||||
scheduled_transactions::create_router(),
|
||||
)
|
||||
.nest("/transactions", transactions::create_router()),
|
||||
)
|
||||
.with_state(pool)
|
||||
|
||||
@@ -1,2 +1,3 @@
|
||||
pub mod expense;
|
||||
pub mod direction;
|
||||
pub mod scheduled_transaction;
|
||||
pub mod transaction;
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum TransactionDirection {
|
||||
In,
|
||||
Out,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct TransactionDirectionConversionError(pub String);
|
||||
|
||||
impl std::fmt::Display for TransactionDirectionConversionError {
|
||||
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
write!(formatter, "invalid direction value: {}", self.0)
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for TransactionDirectionConversionError {}
|
||||
|
||||
impl TryFrom<String> for TransactionDirection {
|
||||
type Error = TransactionDirectionConversionError;
|
||||
|
||||
fn try_from(value: String) -> Result<Self, Self::Error> {
|
||||
match value.as_str() {
|
||||
"in" => Ok(Self::In),
|
||||
"out" => Ok(Self::Out),
|
||||
_ => Err(TransactionDirectionConversionError(value)),
|
||||
}
|
||||
}
|
||||
}
|
||||
+28
-18
@@ -2,20 +2,24 @@ use chrono::{DateTime, Utc};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::database::dtos::expense::RecurringExpenseRow;
|
||||
use crate::{
|
||||
database::dtos::scheduled_transaction::RecurringTransactionRow,
|
||||
routes::dtos::direction::{TransactionDirection, TransactionDirectionConversionError},
|
||||
};
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
#[serde(tag = "type")]
|
||||
pub enum Expense {
|
||||
Recurring(RecurringExpense),
|
||||
pub enum ScheduledTransaction {
|
||||
Recurring(RecurringTransaction),
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct RecurringExpense {
|
||||
pub struct RecurringTransaction {
|
||||
pub id: Uuid,
|
||||
pub name: String,
|
||||
pub amount: f64,
|
||||
pub direction: TransactionDirection,
|
||||
pub start: DateTime<Utc>,
|
||||
pub end: Option<DateTime<Utc>>,
|
||||
pub recurrence: Recurrence,
|
||||
@@ -45,21 +49,23 @@ pub enum WeekendAdjustment {
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum RecurringExpenseConversionError {
|
||||
pub enum RecurringTransactionConversionError {
|
||||
Direction(TransactionDirectionConversionError),
|
||||
RecurrenceEvery(i32),
|
||||
RecurrenceUnit(String),
|
||||
WeekendAdjustment(String),
|
||||
}
|
||||
|
||||
impl From<RecurringExpense> for Expense {
|
||||
fn from(expense: RecurringExpense) -> Self {
|
||||
Self::Recurring(expense)
|
||||
impl From<RecurringTransaction> for ScheduledTransaction {
|
||||
fn from(transaction: RecurringTransaction) -> Self {
|
||||
Self::Recurring(transaction)
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Display for RecurringExpenseConversionError {
|
||||
impl std::fmt::Display for RecurringTransactionConversionError {
|
||||
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match self {
|
||||
Self::Direction(error) => error.fmt(formatter),
|
||||
Self::RecurrenceEvery(value) => {
|
||||
write!(formatter, "invalid recurrence_every value: {value}")
|
||||
}
|
||||
@@ -73,21 +79,23 @@ impl std::fmt::Display for RecurringExpenseConversionError {
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for RecurringExpenseConversionError {}
|
||||
impl std::error::Error for RecurringTransactionConversionError {}
|
||||
|
||||
impl TryFrom<RecurringExpenseRow> for RecurringExpense {
|
||||
type Error = RecurringExpenseConversionError;
|
||||
impl TryFrom<RecurringTransactionRow> for RecurringTransaction {
|
||||
type Error = RecurringTransactionConversionError;
|
||||
|
||||
fn try_from(row: RecurringExpenseRow) -> Result<Self, Self::Error> {
|
||||
fn try_from(row: RecurringTransactionRow) -> Result<Self, Self::Error> {
|
||||
Ok(Self {
|
||||
id: row.id,
|
||||
name: row.name,
|
||||
amount: row.amount_cents as f64 / 100.0,
|
||||
direction: TransactionDirection::try_from(row.direction)
|
||||
.map_err(RecurringTransactionConversionError::Direction)?,
|
||||
start: row.starts_at,
|
||||
end: row.ends_at,
|
||||
recurrence: Recurrence {
|
||||
every: row.recurrence_every.try_into().map_err(|_| {
|
||||
RecurringExpenseConversionError::RecurrenceEvery(row.recurrence_every)
|
||||
RecurringTransactionConversionError::RecurrenceEvery(row.recurrence_every)
|
||||
})?,
|
||||
unit: RecurrenceUnit::try_from(row.recurrence_unit)?,
|
||||
weekend_adjustment: match row.weekend_adjustment {
|
||||
@@ -100,7 +108,7 @@ impl TryFrom<RecurringExpenseRow> for RecurringExpense {
|
||||
}
|
||||
|
||||
impl TryFrom<String> for RecurrenceUnit {
|
||||
type Error = RecurringExpenseConversionError;
|
||||
type Error = RecurringTransactionConversionError;
|
||||
|
||||
fn try_from(value: String) -> Result<Self, Self::Error> {
|
||||
match value.as_str() {
|
||||
@@ -108,19 +116,21 @@ impl TryFrom<String> for RecurrenceUnit {
|
||||
"week" => Ok(Self::Week),
|
||||
"month" => Ok(Self::Month),
|
||||
"year" => Ok(Self::Year),
|
||||
_ => Err(RecurringExpenseConversionError::RecurrenceUnit(value)),
|
||||
_ => Err(RecurringTransactionConversionError::RecurrenceUnit(value)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl TryFrom<String> for WeekendAdjustment {
|
||||
type Error = RecurringExpenseConversionError;
|
||||
type Error = RecurringTransactionConversionError;
|
||||
|
||||
fn try_from(value: String) -> Result<Self, Self::Error> {
|
||||
match value.as_str() {
|
||||
"previous_business_day" => Ok(Self::PreviousBusinessDay),
|
||||
"next_business_day" => Ok(Self::NextBusinessDay),
|
||||
_ => Err(RecurringExpenseConversionError::WeekendAdjustment(value)),
|
||||
_ => Err(RecurringTransactionConversionError::WeekendAdjustment(
|
||||
value,
|
||||
)),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -3,23 +3,28 @@ use serde::Serialize;
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::database::dtos::transaction::TransactionRow;
|
||||
use crate::routes::dtos::direction::{TransactionDirection, TransactionDirectionConversionError};
|
||||
|
||||
#[derive(Serialize)]
|
||||
pub struct TransactionResponse {
|
||||
pub id: Uuid,
|
||||
pub description: String,
|
||||
pub amount: f64,
|
||||
pub direction: TransactionDirection,
|
||||
pub date: DateTime<Utc>,
|
||||
}
|
||||
|
||||
impl From<TransactionRow> for TransactionResponse {
|
||||
fn from(row: TransactionRow) -> Self {
|
||||
Self {
|
||||
impl TryFrom<TransactionRow> for TransactionResponse {
|
||||
type Error = TransactionDirectionConversionError;
|
||||
|
||||
fn try_from(row: TransactionRow) -> Result<Self, Self::Error> {
|
||||
Ok(Self {
|
||||
id: row.id,
|
||||
description: row.description,
|
||||
amount: row.amount_cents as f64 / 100.0,
|
||||
direction: TransactionDirection::try_from(row.direction)?,
|
||||
date: row.date,
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -31,13 +36,16 @@ mod tests {
|
||||
fn converts_cents_to_major_currency_units() {
|
||||
let id = Uuid::new_v4();
|
||||
let date = Utc::now();
|
||||
let response = TransactionResponse::from(TransactionRow {
|
||||
let response = TransactionResponse::try_from(TransactionRow {
|
||||
id,
|
||||
description: "Groceries".to_string(),
|
||||
amount_cents: 4250,
|
||||
direction: "out".to_string(),
|
||||
date,
|
||||
});
|
||||
|
||||
let response = response.expect("valid direction");
|
||||
|
||||
assert_eq!(response.id, id);
|
||||
assert_eq!(response.description, "Groceries");
|
||||
assert_eq!(response.amount, 42.5);
|
||||
|
||||
@@ -1,42 +0,0 @@
|
||||
use axum::{Json, extract::State};
|
||||
use sqlx::PgPool;
|
||||
|
||||
use crate::{
|
||||
database::dtos::expense::RecurringExpenseRow,
|
||||
error::AppError,
|
||||
routes::dtos::expense::{Expense, RecurringExpense},
|
||||
};
|
||||
|
||||
pub fn create_router() -> axum::Router<PgPool> {
|
||||
axum::Router::new().route("/", axum::routing::get(get_expenses))
|
||||
}
|
||||
|
||||
#[tracing::instrument(skip(pool))]
|
||||
async fn get_expenses(State(pool): State<PgPool>) -> Result<Json<Vec<Expense>>, AppError> {
|
||||
let rows = sqlx::query_as!(
|
||||
RecurringExpenseRow,
|
||||
r#"
|
||||
SELECT
|
||||
id,
|
||||
name,
|
||||
amount_cents,
|
||||
starts_at,
|
||||
ends_at,
|
||||
recurrence_every,
|
||||
recurrence_unit,
|
||||
weekend_adjustment
|
||||
FROM recurring_expenses
|
||||
ORDER BY starts_at DESC, id DESC
|
||||
"#,
|
||||
)
|
||||
.fetch_all(&pool)
|
||||
.await?;
|
||||
|
||||
let expenses = rows
|
||||
.into_iter()
|
||||
.map(RecurringExpense::try_from)
|
||||
.map(|result| result.map(Expense::from))
|
||||
.collect::<Result<Vec<_>, _>>()?;
|
||||
|
||||
Ok(Json(expenses))
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
use axum::{Json, extract::State};
|
||||
use sqlx::PgPool;
|
||||
|
||||
use crate::{
|
||||
database::dtos::scheduled_transaction::RecurringTransactionRow,
|
||||
error::AppError,
|
||||
routes::dtos::scheduled_transaction::{RecurringTransaction, ScheduledTransaction},
|
||||
};
|
||||
|
||||
pub fn create_router() -> axum::Router<PgPool> {
|
||||
axum::Router::new().route("/", axum::routing::get(get_scheduled_transactions))
|
||||
}
|
||||
|
||||
#[tracing::instrument(skip(pool))]
|
||||
async fn get_scheduled_transactions(
|
||||
State(pool): State<PgPool>,
|
||||
) -> Result<Json<Vec<ScheduledTransaction>>, AppError> {
|
||||
let rows = sqlx::query_as!(
|
||||
RecurringTransactionRow,
|
||||
r#"
|
||||
SELECT
|
||||
id,
|
||||
name,
|
||||
amount_cents,
|
||||
direction,
|
||||
starts_at,
|
||||
ends_at,
|
||||
recurrence_every,
|
||||
recurrence_unit,
|
||||
weekend_adjustment
|
||||
FROM recurring_transactions
|
||||
ORDER BY starts_at DESC, id DESC
|
||||
"#,
|
||||
)
|
||||
.fetch_all(&pool)
|
||||
.await?;
|
||||
|
||||
let transactions = rows
|
||||
.into_iter()
|
||||
.map(RecurringTransaction::try_from)
|
||||
.map(|result| result.map(ScheduledTransaction::from))
|
||||
.collect::<Result<Vec<_>, _>>()?;
|
||||
|
||||
Ok(Json(transactions))
|
||||
}
|
||||
@@ -17,7 +17,7 @@ async fn get_transactions(
|
||||
let rows = sqlx::query_as!(
|
||||
TransactionRow,
|
||||
r#"
|
||||
SELECT id, description, amount_cents, date
|
||||
SELECT id, description, amount_cents, direction, date
|
||||
FROM transactions
|
||||
ORDER BY date DESC, id DESC
|
||||
"#
|
||||
@@ -25,7 +25,10 @@ async fn get_transactions(
|
||||
.fetch_all(&pool)
|
||||
.await?;
|
||||
|
||||
Ok(Json(
|
||||
rows.into_iter().map(TransactionResponse::from).collect(),
|
||||
))
|
||||
let transactions = rows
|
||||
.into_iter()
|
||||
.map(TransactionResponse::try_from)
|
||||
.collect::<Result<Vec<_>, _>>()?;
|
||||
|
||||
Ok(Json(transactions))
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user