Added expenses.
This commit is contained in:
@@ -0,0 +1,23 @@
|
|||||||
|
CREATE TABLE recurring_expenses (
|
||||||
|
id UUID PRIMARY KEY DEFAULT gen_random_uuid (),
|
||||||
|
name TEXT NOT NULL,
|
||||||
|
amount_cents BIGINT NOT NULL,
|
||||||
|
starts_at TIMESTAMPTZ NOT NULL,
|
||||||
|
ends_at TIMESTAMPTZ,
|
||||||
|
recurrence_every INTEGER NOT NULL CHECK (recurrence_every > 0),
|
||||||
|
recurrence_unit TEXT NOT NULL CHECK (
|
||||||
|
recurrence_unit IN (
|
||||||
|
'day',
|
||||||
|
'week',
|
||||||
|
'month',
|
||||||
|
'year'
|
||||||
|
)
|
||||||
|
),
|
||||||
|
weekend_adjustment TEXT CHECK (
|
||||||
|
weekend_adjustment IS NULL
|
||||||
|
OR weekend_adjustment IN (
|
||||||
|
'previous_business_day',
|
||||||
|
'next_business_day'
|
||||||
|
)
|
||||||
|
)
|
||||||
|
);
|
||||||
@@ -1 +1,2 @@
|
|||||||
|
pub mod expense;
|
||||||
pub mod transaction;
|
pub mod transaction;
|
||||||
|
|||||||
@@ -0,0 +1,14 @@
|
|||||||
|
use chrono::{DateTime, Utc};
|
||||||
|
use uuid::Uuid;
|
||||||
|
|
||||||
|
#[derive(sqlx::FromRow)]
|
||||||
|
pub struct RecurringExpenseRow {
|
||||||
|
pub id: Uuid,
|
||||||
|
pub name: String,
|
||||||
|
pub amount_cents: i64,
|
||||||
|
pub starts_at: DateTime<Utc>,
|
||||||
|
pub ends_at: Option<DateTime<Utc>>,
|
||||||
|
pub recurrence_every: i32,
|
||||||
|
pub recurrence_unit: String,
|
||||||
|
pub weekend_adjustment: Option<String>,
|
||||||
|
}
|
||||||
@@ -3,9 +3,12 @@ use axum::{
|
|||||||
response::{IntoResponse, Response},
|
response::{IntoResponse, Response},
|
||||||
};
|
};
|
||||||
|
|
||||||
|
use crate::routes::dtos::expense::RecurringExpenseConversionError;
|
||||||
|
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
pub enum AppError {
|
pub enum AppError {
|
||||||
Database(sqlx::Error),
|
Database(sqlx::Error),
|
||||||
|
InvalidRecurringExpense(RecurringExpenseConversionError),
|
||||||
}
|
}
|
||||||
|
|
||||||
impl From<sqlx::Error> for AppError {
|
impl From<sqlx::Error> for AppError {
|
||||||
@@ -14,10 +17,19 @@ impl From<sqlx::Error> for AppError {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl From<RecurringExpenseConversionError> for AppError {
|
||||||
|
fn from(error: RecurringExpenseConversionError) -> Self {
|
||||||
|
Self::InvalidRecurringExpense(error)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
impl IntoResponse for AppError {
|
impl IntoResponse for AppError {
|
||||||
fn into_response(self) -> Response {
|
fn into_response(self) -> Response {
|
||||||
match self {
|
match self {
|
||||||
Self::Database(error) => tracing::error!(%error, "Database query failed"),
|
Self::Database(error) => tracing::error!(%error, "Database query failed"),
|
||||||
|
Self::InvalidRecurringExpense(error) => {
|
||||||
|
tracing::error!(%error, "Invalid recurring expense data")
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
(StatusCode::INTERNAL_SERVER_ERROR, "Internal server error").into_response()
|
(StatusCode::INTERNAL_SERVER_ERROR, "Internal server error").into_response()
|
||||||
|
|||||||
@@ -1,11 +1,14 @@
|
|||||||
pub mod dtos;
|
pub mod dtos;
|
||||||
|
mod expenses;
|
||||||
mod transactions;
|
mod transactions;
|
||||||
|
|
||||||
pub fn create_router(pool: sqlx::PgPool) -> axum::Router {
|
pub fn create_router(pool: sqlx::PgPool) -> axum::Router {
|
||||||
axum::Router::new()
|
axum::Router::new()
|
||||||
.nest(
|
.nest(
|
||||||
"/api",
|
"/api",
|
||||||
axum::Router::new().nest("/transactions", transactions::create_router()),
|
axum::Router::new()
|
||||||
|
.nest("/expenses", expenses::create_router())
|
||||||
|
.nest("/transactions", transactions::create_router()),
|
||||||
)
|
)
|
||||||
.with_state(pool)
|
.with_state(pool)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1 +1,2 @@
|
|||||||
|
pub mod expense;
|
||||||
pub mod transaction;
|
pub mod transaction;
|
||||||
|
|||||||
@@ -0,0 +1,130 @@
|
|||||||
|
use chrono::{DateTime, Utc};
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
use uuid::Uuid;
|
||||||
|
|
||||||
|
use crate::database::dtos::expense::RecurringExpenseRow;
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
|
#[serde(rename_all = "snake_case")]
|
||||||
|
#[serde(tag = "type")]
|
||||||
|
pub enum Expense {
|
||||||
|
Recurring(RecurringExpense),
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
|
pub struct RecurringExpense {
|
||||||
|
pub id: Uuid,
|
||||||
|
pub name: String,
|
||||||
|
pub amount: f64,
|
||||||
|
pub start: DateTime<Utc>,
|
||||||
|
pub end: Option<DateTime<Utc>>,
|
||||||
|
pub recurrence: Recurrence,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
|
pub struct Recurrence {
|
||||||
|
pub every: u32,
|
||||||
|
pub unit: RecurrenceUnit,
|
||||||
|
pub weekend_adjustment: Option<WeekendAdjustment>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
|
#[serde(rename_all = "snake_case")]
|
||||||
|
pub enum RecurrenceUnit {
|
||||||
|
Day,
|
||||||
|
Week,
|
||||||
|
Month,
|
||||||
|
Year,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
|
#[serde(rename_all = "snake_case")]
|
||||||
|
pub enum WeekendAdjustment {
|
||||||
|
PreviousBusinessDay,
|
||||||
|
NextBusinessDay,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub enum RecurringExpenseConversionError {
|
||||||
|
InvalidRecurrenceEvery(i32),
|
||||||
|
InvalidRecurrenceUnit(String),
|
||||||
|
InvalidWeekendAdjustment(String),
|
||||||
|
}
|
||||||
|
|
||||||
|
impl From<RecurringExpense> for Expense {
|
||||||
|
fn from(expense: RecurringExpense) -> Self {
|
||||||
|
Self::Recurring(expense)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl std::fmt::Display for RecurringExpenseConversionError {
|
||||||
|
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||||
|
match self {
|
||||||
|
Self::InvalidRecurrenceEvery(value) => {
|
||||||
|
write!(formatter, "invalid recurrence_every value: {value}")
|
||||||
|
}
|
||||||
|
Self::InvalidRecurrenceUnit(value) => {
|
||||||
|
write!(formatter, "invalid recurrence_unit value: {value}")
|
||||||
|
}
|
||||||
|
Self::InvalidWeekendAdjustment(value) => {
|
||||||
|
write!(formatter, "invalid weekend_adjustment value: {value}")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl std::error::Error for RecurringExpenseConversionError {}
|
||||||
|
|
||||||
|
impl TryFrom<RecurringExpenseRow> for RecurringExpense {
|
||||||
|
type Error = RecurringExpenseConversionError;
|
||||||
|
|
||||||
|
fn try_from(row: RecurringExpenseRow) -> Result<Self, Self::Error> {
|
||||||
|
Ok(Self {
|
||||||
|
id: row.id,
|
||||||
|
name: row.name,
|
||||||
|
amount: row.amount_cents as f64 / 100.0,
|
||||||
|
start: row.starts_at,
|
||||||
|
end: row.ends_at,
|
||||||
|
recurrence: Recurrence {
|
||||||
|
every: row.recurrence_every.try_into().map_err(|_| {
|
||||||
|
RecurringExpenseConversionError::InvalidRecurrenceEvery(row.recurrence_every)
|
||||||
|
})?,
|
||||||
|
unit: RecurrenceUnit::try_from(row.recurrence_unit)?,
|
||||||
|
weekend_adjustment: match row.weekend_adjustment {
|
||||||
|
Some(value) => Some(WeekendAdjustment::try_from(value)?),
|
||||||
|
None => None,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl TryFrom<String> for RecurrenceUnit {
|
||||||
|
type Error = RecurringExpenseConversionError;
|
||||||
|
|
||||||
|
fn try_from(value: String) -> Result<Self, Self::Error> {
|
||||||
|
match value.as_str() {
|
||||||
|
"day" => Ok(Self::Day),
|
||||||
|
"week" => Ok(Self::Week),
|
||||||
|
"month" => Ok(Self::Month),
|
||||||
|
"year" => Ok(Self::Year),
|
||||||
|
_ => Err(RecurringExpenseConversionError::InvalidRecurrenceUnit(
|
||||||
|
value,
|
||||||
|
)),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl TryFrom<String> for WeekendAdjustment {
|
||||||
|
type Error = RecurringExpenseConversionError;
|
||||||
|
|
||||||
|
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::InvalidWeekendAdjustment(
|
||||||
|
value,
|
||||||
|
)),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,41 @@
|
|||||||
|
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))
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user