diff --git a/server/.sqlx/query-9b91722c2119022fa62421e2d1eaca7557b0f5a31e99485548bdd5a37b0c56fb.json b/server/.sqlx/query-9046c905a83167f865e902a3bd66e0e53647938e0f5af0ff00058726f25c761e.json similarity index 63% rename from server/.sqlx/query-9b91722c2119022fa62421e2d1eaca7557b0f5a31e99485548bdd5a37b0c56fb.json rename to server/.sqlx/query-9046c905a83167f865e902a3bd66e0e53647938e0f5af0ff00058726f25c761e.json index b2811b4..823012f 100644 --- a/server/.sqlx/query-9b91722c2119022fa62421e2d1eaca7557b0f5a31e99485548bdd5a37b0c56fb.json +++ b/server/.sqlx/query-9046c905a83167f865e902a3bd66e0e53647938e0f5af0ff00058726f25c761e.json @@ -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" } diff --git a/server/.sqlx/query-546ab0f8a84d179bfc93ba646a64dd7772530e84f1adf31231c8614218c21ec4.json b/server/.sqlx/query-adfd3f5ee43fd9877d4411cb20b2d147ec204db6783a570668b4843c1c57ea4e.json similarity index 70% rename from server/.sqlx/query-546ab0f8a84d179bfc93ba646a64dd7772530e84f1adf31231c8614218c21ec4.json rename to server/.sqlx/query-adfd3f5ee43fd9877d4411cb20b2d147ec204db6783a570668b4843c1c57ea4e.json index 5864a6f..85cf5db 100644 --- a/server/.sqlx/query-546ab0f8a84d179bfc93ba646a64dd7772530e84f1adf31231c8614218c21ec4.json +++ b/server/.sqlx/query-adfd3f5ee43fd9877d4411cb20b2d147ec204db6783a570668b4843c1c57ea4e.json @@ -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" } diff --git a/server/migrations/20260919000000_create_transactions.sql b/server/migrations/20260919000000_create_transactions.sql index 0a67fdc..5127411 100644 --- a/server/migrations/20260919000000_create_transactions.sql +++ b/server/migrations/20260919000000_create_transactions.sql @@ -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() ); \ No newline at end of file diff --git a/server/migrations/20260920000000_create_recurring_expenses.sql b/server/migrations/20260920000000_create_recurring_transactions.sql similarity index 77% rename from server/migrations/20260920000000_create_recurring_expenses.sql rename to server/migrations/20260920000000_create_recurring_transactions.sql index c192615..533e12a 100644 --- a/server/migrations/20260920000000_create_recurring_expenses.sql +++ b/server/migrations/20260920000000_create_recurring_transactions.sql @@ -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), diff --git a/server/migrations/20260921000000_seed_demo_data.sql b/server/migrations/20260921000000_seed_demo_data.sql new file mode 100644 index 0000000..af8ebfb --- /dev/null +++ b/server/migrations/20260921000000_seed_demo_data.sql @@ -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' + ); \ No newline at end of file diff --git a/server/src/database/dtos.rs b/server/src/database/dtos.rs index 31ab374..81e8ccf 100644 --- a/server/src/database/dtos.rs +++ b/server/src/database/dtos.rs @@ -1,2 +1,2 @@ -pub mod expense; +pub mod scheduled_transaction; pub mod transaction; diff --git a/server/src/database/dtos/expense.rs b/server/src/database/dtos/scheduled_transaction.rs similarity index 82% rename from server/src/database/dtos/expense.rs rename to server/src/database/dtos/scheduled_transaction.rs index 4b954fc..ad0aeb0 100644 --- a/server/src/database/dtos/expense.rs +++ b/server/src/database/dtos/scheduled_transaction.rs @@ -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, pub ends_at: Option>, pub recurrence_every: i32, diff --git a/server/src/database/dtos/transaction.rs b/server/src/database/dtos/transaction.rs index c44752a..a18cfdf 100644 --- a/server/src/database/dtos/transaction.rs +++ b/server/src/database/dtos/transaction.rs @@ -5,5 +5,6 @@ pub struct TransactionRow { pub id: Uuid, pub description: String, pub amount_cents: i64, + pub direction: String, pub date: DateTime, } diff --git a/server/src/error.rs b/server/src/error.rs index b79de4a..bc07629 100644 --- a/server/src/error.rs +++ b/server/src/error.rs @@ -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 for AppError { @@ -17,9 +21,15 @@ impl From for AppError { } } -impl From for AppError { - fn from(error: RecurringExpenseConversionError) -> Self { - Self::RecurringExpense(error) +impl From for AppError { + fn from(error: TransactionDirectionConversionError) -> Self { + Self::Direction(error) + } +} + +impl From 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") } } diff --git a/server/src/routes.rs b/server/src/routes.rs index 6029256..c77e0b2 100644 --- a/server/src/routes.rs +++ b/server/src/routes.rs @@ -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) diff --git a/server/src/routes/dtos.rs b/server/src/routes/dtos.rs index 31ab374..c8509ae 100644 --- a/server/src/routes/dtos.rs +++ b/server/src/routes/dtos.rs @@ -1,2 +1,3 @@ -pub mod expense; +pub mod direction; +pub mod scheduled_transaction; pub mod transaction; diff --git a/server/src/routes/dtos/direction.rs b/server/src/routes/dtos/direction.rs new file mode 100644 index 0000000..6fa3346 --- /dev/null +++ b/server/src/routes/dtos/direction.rs @@ -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 for TransactionDirection { + type Error = TransactionDirectionConversionError; + + fn try_from(value: String) -> Result { + match value.as_str() { + "in" => Ok(Self::In), + "out" => Ok(Self::Out), + _ => Err(TransactionDirectionConversionError(value)), + } + } +} diff --git a/server/src/routes/dtos/expense.rs b/server/src/routes/dtos/scheduled_transaction.rs similarity index 64% rename from server/src/routes/dtos/expense.rs rename to server/src/routes/dtos/scheduled_transaction.rs index 29d93ba..bfd436b 100644 --- a/server/src/routes/dtos/expense.rs +++ b/server/src/routes/dtos/scheduled_transaction.rs @@ -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, pub end: Option>, 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 for Expense { - fn from(expense: RecurringExpense) -> Self { - Self::Recurring(expense) +impl From 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 for RecurringExpense { - type Error = RecurringExpenseConversionError; +impl TryFrom for RecurringTransaction { + type Error = RecurringTransactionConversionError; - fn try_from(row: RecurringExpenseRow) -> Result { + fn try_from(row: RecurringTransactionRow) -> Result { 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 for RecurringExpense { } impl TryFrom for RecurrenceUnit { - type Error = RecurringExpenseConversionError; + type Error = RecurringTransactionConversionError; fn try_from(value: String) -> Result { match value.as_str() { @@ -108,19 +116,21 @@ impl TryFrom for RecurrenceUnit { "week" => Ok(Self::Week), "month" => Ok(Self::Month), "year" => Ok(Self::Year), - _ => Err(RecurringExpenseConversionError::RecurrenceUnit(value)), + _ => Err(RecurringTransactionConversionError::RecurrenceUnit(value)), } } } impl TryFrom for WeekendAdjustment { - type Error = RecurringExpenseConversionError; + type Error = RecurringTransactionConversionError; fn try_from(value: String) -> Result { match value.as_str() { "previous_business_day" => Ok(Self::PreviousBusinessDay), "next_business_day" => Ok(Self::NextBusinessDay), - _ => Err(RecurringExpenseConversionError::WeekendAdjustment(value)), + _ => Err(RecurringTransactionConversionError::WeekendAdjustment( + value, + )), } } } diff --git a/server/src/routes/dtos/transaction.rs b/server/src/routes/dtos/transaction.rs index e070164..3767626 100644 --- a/server/src/routes/dtos/transaction.rs +++ b/server/src/routes/dtos/transaction.rs @@ -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, } -impl From for TransactionResponse { - fn from(row: TransactionRow) -> Self { - Self { +impl TryFrom for TransactionResponse { + type Error = TransactionDirectionConversionError; + + fn try_from(row: TransactionRow) -> Result { + 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); diff --git a/server/src/routes/expenses.rs b/server/src/routes/expenses.rs deleted file mode 100644 index 3a4ed29..0000000 --- a/server/src/routes/expenses.rs +++ /dev/null @@ -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 { - axum::Router::new().route("/", axum::routing::get(get_expenses)) -} - -#[tracing::instrument(skip(pool))] -async fn get_expenses(State(pool): State) -> Result>, 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::, _>>()?; - - Ok(Json(expenses)) -} diff --git a/server/src/routes/scheduled_transactions.rs b/server/src/routes/scheduled_transactions.rs new file mode 100644 index 0000000..2bfea76 --- /dev/null +++ b/server/src/routes/scheduled_transactions.rs @@ -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 { + axum::Router::new().route("/", axum::routing::get(get_scheduled_transactions)) +} + +#[tracing::instrument(skip(pool))] +async fn get_scheduled_transactions( + State(pool): State, +) -> Result>, 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::, _>>()?; + + Ok(Json(transactions)) +} diff --git a/server/src/routes/transactions.rs b/server/src/routes/transactions.rs index df38b5a..f4aad3b 100644 --- a/server/src/routes/transactions.rs +++ b/server/src/routes/transactions.rs @@ -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::, _>>()?; + + Ok(Json(transactions)) }