Made scheduled transactions more generic.
This commit is contained in:
+8
-2
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"db_name": "PostgreSQL",
|
||||
"query": "\n SELECT id, description, amount_cents, date\n FROM transactions\n ORDER BY date DESC, id DESC\n ",
|
||||
"query": "\n SELECT id, description, amount_cents, direction, date\n FROM transactions\n ORDER BY date DESC, id DESC\n ",
|
||||
"describe": {
|
||||
"columns": [
|
||||
{
|
||||
@@ -20,6 +20,11 @@
|
||||
},
|
||||
{
|
||||
"ordinal": 3,
|
||||
"name": "direction",
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"ordinal": 4,
|
||||
"name": "date",
|
||||
"type_info": "Timestamptz"
|
||||
}
|
||||
@@ -31,8 +36,9 @@
|
||||
false,
|
||||
false,
|
||||
false,
|
||||
false,
|
||||
false
|
||||
]
|
||||
},
|
||||
"hash": "9b91722c2119022fa62421e2d1eaca7557b0f5a31e99485548bdd5a37b0c56fb"
|
||||
"hash": "9046c905a83167f865e902a3bd66e0e53647938e0f5af0ff00058726f25c761e"
|
||||
}
|
||||
+12
-6
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"db_name": "PostgreSQL",
|
||||
"query": "\n SELECT\n id,\n name,\n amount_cents,\n starts_at,\n ends_at,\n recurrence_every,\n recurrence_unit,\n weekend_adjustment\n FROM recurring_expenses\n ORDER BY starts_at DESC, id DESC\n ",
|
||||
"query": "\n SELECT\n id,\n name,\n amount_cents,\n direction,\n starts_at,\n ends_at,\n recurrence_every,\n recurrence_unit,\n weekend_adjustment\n FROM recurring_transactions\n ORDER BY starts_at DESC, id DESC\n ",
|
||||
"describe": {
|
||||
"columns": [
|
||||
{
|
||||
@@ -20,26 +20,31 @@
|
||||
},
|
||||
{
|
||||
"ordinal": 3,
|
||||
"name": "direction",
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"ordinal": 4,
|
||||
"name": "starts_at",
|
||||
"type_info": "Timestamptz"
|
||||
},
|
||||
{
|
||||
"ordinal": 4,
|
||||
"ordinal": 5,
|
||||
"name": "ends_at",
|
||||
"type_info": "Timestamptz"
|
||||
},
|
||||
{
|
||||
"ordinal": 5,
|
||||
"ordinal": 6,
|
||||
"name": "recurrence_every",
|
||||
"type_info": "Int4"
|
||||
},
|
||||
{
|
||||
"ordinal": 6,
|
||||
"ordinal": 7,
|
||||
"name": "recurrence_unit",
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"ordinal": 7,
|
||||
"ordinal": 8,
|
||||
"name": "weekend_adjustment",
|
||||
"type_info": "Text"
|
||||
}
|
||||
@@ -52,11 +57,12 @@
|
||||
false,
|
||||
false,
|
||||
false,
|
||||
false,
|
||||
true,
|
||||
false,
|
||||
false,
|
||||
true
|
||||
]
|
||||
},
|
||||
"hash": "546ab0f8a84d179bfc93ba646a64dd7772530e84f1adf31231c8614218c21ec4"
|
||||
"hash": "adfd3f5ee43fd9877d4411cb20b2d147ec204db6783a570668b4843c1c57ea4e"
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
CREATE TABLE transactions (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid (),
|
||||
description TEXT NOT NULL,
|
||||
amount_cents BIGINT NOT NULL,
|
||||
amount_cents BIGINT NOT NULL CHECK (amount_cents >= 0),
|
||||
direction TEXT NOT NULL CHECK (direction IN ('in', 'out')),
|
||||
date TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
);
|
||||
+3
-2
@@ -1,7 +1,8 @@
|
||||
CREATE TABLE recurring_expenses (
|
||||
CREATE TABLE recurring_transactions (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid (),
|
||||
name TEXT NOT NULL,
|
||||
amount_cents BIGINT NOT NULL,
|
||||
amount_cents BIGINT NOT NULL CHECK (amount_cents >= 0),
|
||||
direction TEXT NOT NULL CHECK (direction IN ('in', 'out')),
|
||||
starts_at TIMESTAMPTZ NOT NULL,
|
||||
ends_at TIMESTAMPTZ,
|
||||
recurrence_every INTEGER NOT NULL CHECK (recurrence_every > 0),
|
||||
@@ -0,0 +1,57 @@
|
||||
INSERT INTO
|
||||
transactions (
|
||||
id,
|
||||
description,
|
||||
amount_cents,
|
||||
direction,
|
||||
date
|
||||
)
|
||||
VALUES (
|
||||
'00000000-0000-0000-0000-000000000001',
|
||||
'Salary',
|
||||
320000,
|
||||
'in',
|
||||
'2026-09-01T09:00:00Z'
|
||||
),
|
||||
(
|
||||
'00000000-0000-0000-0000-000000000002',
|
||||
'Groceries',
|
||||
8450,
|
||||
'out',
|
||||
'2026-09-18T17:30:00Z'
|
||||
);
|
||||
|
||||
INSERT INTO
|
||||
recurring_transactions (
|
||||
id,
|
||||
name,
|
||||
amount_cents,
|
||||
direction,
|
||||
starts_at,
|
||||
ends_at,
|
||||
recurrence_every,
|
||||
recurrence_unit,
|
||||
weekend_adjustment
|
||||
)
|
||||
VALUES (
|
||||
'00000000-0000-0000-0000-000000000101',
|
||||
'Salary',
|
||||
320000,
|
||||
'in',
|
||||
'2026-10-01T09:00:00Z',
|
||||
NULL,
|
||||
1,
|
||||
'month',
|
||||
NULL
|
||||
),
|
||||
(
|
||||
'00000000-0000-0000-0000-000000000102',
|
||||
'Rent',
|
||||
125000,
|
||||
'out',
|
||||
'2026-10-01T09:00:00Z',
|
||||
NULL,
|
||||
1,
|
||||
'month',
|
||||
'previous_business_day'
|
||||
);
|
||||
@@ -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