Added additional transaction operations.
This commit is contained in:
+46
@@ -0,0 +1,46 @@
|
|||||||
|
{
|
||||||
|
"db_name": "PostgreSQL",
|
||||||
|
"query": "\n\t\tSELECT id, description, amount_cents, direction, date\n\t\tFROM transactions\n\t\tWHERE id = $1\n\t\t",
|
||||||
|
"describe": {
|
||||||
|
"columns": [
|
||||||
|
{
|
||||||
|
"ordinal": 0,
|
||||||
|
"name": "id",
|
||||||
|
"type_info": "Uuid"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"ordinal": 1,
|
||||||
|
"name": "description",
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"ordinal": 2,
|
||||||
|
"name": "amount_cents",
|
||||||
|
"type_info": "Int8"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"ordinal": 3,
|
||||||
|
"name": "direction",
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"ordinal": 4,
|
||||||
|
"name": "date",
|
||||||
|
"type_info": "Timestamptz"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"parameters": {
|
||||||
|
"Left": [
|
||||||
|
"Uuid"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"nullable": [
|
||||||
|
false,
|
||||||
|
false,
|
||||||
|
false,
|
||||||
|
false,
|
||||||
|
false
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"hash": "04e8934ac1d987fc859ed21a3fdc41f62165efb6248575e78d577ca333d025c2"
|
||||||
|
}
|
||||||
+56
@@ -0,0 +1,56 @@
|
|||||||
|
{
|
||||||
|
"db_name": "PostgreSQL",
|
||||||
|
"query": "\n\t\tINSERT INTO transactions (id, description, amount_cents, direction, date)\n\t\tVALUES ($1, $2, $3, $4, $5)\n\t\tON CONFLICT (id) DO UPDATE SET\n\t\t\tdescription = EXCLUDED.description,\n\t\t\tamount_cents = EXCLUDED.amount_cents,\n\t\t\tdirection = EXCLUDED.direction,\n\t\t\tdate = EXCLUDED.date\n\t\tRETURNING WITH (OLD AS old_row, NEW AS new_row)\n\t\t\told_row.id AS \"old_id?\",\n\t\t\tnew_row.id AS \"id!\",\n\t\t\tnew_row.description AS \"description!\",\n\t\t\tnew_row.amount_cents AS \"amount_cents!\",\n\t\t\tnew_row.direction AS \"direction!\",\n\t\t\tnew_row.date AS \"date!\"\n\t\t",
|
||||||
|
"describe": {
|
||||||
|
"columns": [
|
||||||
|
{
|
||||||
|
"ordinal": 0,
|
||||||
|
"name": "old_id?",
|
||||||
|
"type_info": "Uuid"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"ordinal": 1,
|
||||||
|
"name": "id!",
|
||||||
|
"type_info": "Uuid"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"ordinal": 2,
|
||||||
|
"name": "description!",
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"ordinal": 3,
|
||||||
|
"name": "amount_cents!",
|
||||||
|
"type_info": "Int8"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"ordinal": 4,
|
||||||
|
"name": "direction!",
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"ordinal": 5,
|
||||||
|
"name": "date!",
|
||||||
|
"type_info": "Timestamptz"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"parameters": {
|
||||||
|
"Left": [
|
||||||
|
"Uuid",
|
||||||
|
"Text",
|
||||||
|
"Int8",
|
||||||
|
"Text",
|
||||||
|
"Timestamptz"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"nullable": [
|
||||||
|
false,
|
||||||
|
false,
|
||||||
|
false,
|
||||||
|
false,
|
||||||
|
false,
|
||||||
|
false
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"hash": "2c91d06bd5687a10c8b54386586b1c5be73ae4cc1a72351a78f26c136c429e1d"
|
||||||
|
}
|
||||||
+2
-2
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"db_name": "PostgreSQL",
|
"db_name": "PostgreSQL",
|
||||||
"query": "\n SELECT id, description, amount_cents, direction, date\n FROM transactions\n ORDER BY date DESC, id DESC\n ",
|
"query": "\n\t\tSELECT id, description, amount_cents, direction, date\n\t\tFROM transactions\n\t\tORDER BY date DESC, id DESC\n\t\t",
|
||||||
"describe": {
|
"describe": {
|
||||||
"columns": [
|
"columns": [
|
||||||
{
|
{
|
||||||
@@ -40,5 +40,5 @@
|
|||||||
false
|
false
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
"hash": "9046c905a83167f865e902a3bd66e0e53647938e0f5af0ff00058726f25c761e"
|
"hash": "7e9c0f4b0502b63b823233a826c9388703e9568f769cfc50c40ac0929750b744"
|
||||||
}
|
}
|
||||||
@@ -1,3 +1,4 @@
|
|||||||
pub mod common;
|
pub mod common;
|
||||||
pub mod dtos;
|
pub mod dtos;
|
||||||
pub mod recurring_transactions;
|
pub mod recurring_transactions;
|
||||||
|
pub mod transactions;
|
||||||
|
|||||||
@@ -0,0 +1,105 @@
|
|||||||
|
use uuid::Uuid;
|
||||||
|
|
||||||
|
use crate::database::{
|
||||||
|
common::{Delete, Upsert},
|
||||||
|
dtos::transaction::TransactionRow,
|
||||||
|
};
|
||||||
|
|
||||||
|
pub async fn query_transactions<'e, E>(executor: E) -> Result<Vec<TransactionRow>, sqlx::Error>
|
||||||
|
where
|
||||||
|
E: sqlx::Executor<'e, Database = sqlx::Postgres>,
|
||||||
|
{
|
||||||
|
sqlx::query_as!(
|
||||||
|
TransactionRow,
|
||||||
|
r#"
|
||||||
|
SELECT id, description, amount_cents, direction, date
|
||||||
|
FROM transactions
|
||||||
|
ORDER BY date DESC, id DESC
|
||||||
|
"#,
|
||||||
|
)
|
||||||
|
.fetch_all(executor)
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn get_transaction_by_id<'e, E>(
|
||||||
|
executor: E,
|
||||||
|
id: Uuid,
|
||||||
|
) -> Result<Option<TransactionRow>, sqlx::Error>
|
||||||
|
where
|
||||||
|
E: sqlx::Executor<'e, Database = sqlx::Postgres>,
|
||||||
|
{
|
||||||
|
sqlx::query_as!(
|
||||||
|
TransactionRow,
|
||||||
|
r#"
|
||||||
|
SELECT id, description, amount_cents, direction, date
|
||||||
|
FROM transactions
|
||||||
|
WHERE id = $1
|
||||||
|
"#,
|
||||||
|
id,
|
||||||
|
)
|
||||||
|
.fetch_optional(executor)
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn upsert_transaction<'e, E>(
|
||||||
|
executor: E,
|
||||||
|
transaction: TransactionRow,
|
||||||
|
) -> Result<Upsert<TransactionRow>, sqlx::Error>
|
||||||
|
where
|
||||||
|
E: sqlx::Executor<'e, Database = sqlx::Postgres>,
|
||||||
|
{
|
||||||
|
let row = sqlx::query!(
|
||||||
|
r#"
|
||||||
|
INSERT INTO transactions (id, description, amount_cents, direction, date)
|
||||||
|
VALUES ($1, $2, $3, $4, $5)
|
||||||
|
ON CONFLICT (id) DO UPDATE SET
|
||||||
|
description = EXCLUDED.description,
|
||||||
|
amount_cents = EXCLUDED.amount_cents,
|
||||||
|
direction = EXCLUDED.direction,
|
||||||
|
date = EXCLUDED.date
|
||||||
|
RETURNING WITH (OLD AS old_row, NEW AS new_row)
|
||||||
|
old_row.id AS "old_id?",
|
||||||
|
new_row.id AS "id!",
|
||||||
|
new_row.description AS "description!",
|
||||||
|
new_row.amount_cents AS "amount_cents!",
|
||||||
|
new_row.direction AS "direction!",
|
||||||
|
new_row.date AS "date!"
|
||||||
|
"#,
|
||||||
|
transaction.id,
|
||||||
|
transaction.description,
|
||||||
|
transaction.amount_cents,
|
||||||
|
transaction.direction,
|
||||||
|
transaction.date,
|
||||||
|
)
|
||||||
|
.fetch_one(executor)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
let transaction = TransactionRow {
|
||||||
|
id: row.id,
|
||||||
|
description: row.description,
|
||||||
|
amount_cents: row.amount_cents,
|
||||||
|
direction: row.direction,
|
||||||
|
date: row.date,
|
||||||
|
};
|
||||||
|
|
||||||
|
if row.old_id.is_some() {
|
||||||
|
Ok(Upsert::Updated(transaction))
|
||||||
|
} else {
|
||||||
|
Ok(Upsert::Created(transaction))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn delete_transaction_by_id<'e, E>(executor: E, id: Uuid) -> Result<Delete, sqlx::Error>
|
||||||
|
where
|
||||||
|
E: sqlx::Executor<'e, Database = sqlx::Postgres>,
|
||||||
|
{
|
||||||
|
let deleted = sqlx::query!("DELETE FROM transactions WHERE id = $1 RETURNING id", id)
|
||||||
|
.fetch_optional(executor)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
Ok(if deleted.is_some() {
|
||||||
|
Delete::Deleted
|
||||||
|
} else {
|
||||||
|
Delete::NotFound
|
||||||
|
})
|
||||||
|
}
|
||||||
+10
-1
@@ -9,7 +9,10 @@ use crate::routes::{
|
|||||||
scheduled_transaction::RecurringTransactionConversionError,
|
scheduled_transaction::RecurringTransactionConversionError,
|
||||||
transaction::TransactionConversionError,
|
transaction::TransactionConversionError,
|
||||||
},
|
},
|
||||||
validation::scheduled_transaction::ScheduledTransactionValidationError,
|
validation::{
|
||||||
|
scheduled_transaction::ScheduledTransactionValidationError,
|
||||||
|
transaction::TransactionValidationError,
|
||||||
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
#[derive(Debug, thiserror::Error)]
|
#[derive(Debug, thiserror::Error)]
|
||||||
@@ -31,6 +34,9 @@ pub enum AppError {
|
|||||||
|
|
||||||
#[error("scheduled transaction validation error")]
|
#[error("scheduled transaction validation error")]
|
||||||
ScheduledTransactionValidation(#[from] ScheduledTransactionValidationError),
|
ScheduledTransactionValidation(#[from] ScheduledTransactionValidationError),
|
||||||
|
|
||||||
|
#[error("transaction validation error")]
|
||||||
|
TransactionValidation(#[from] TransactionValidationError),
|
||||||
}
|
}
|
||||||
|
|
||||||
impl IntoResponse for AppError {
|
impl IntoResponse for AppError {
|
||||||
@@ -42,6 +48,9 @@ impl IntoResponse for AppError {
|
|||||||
Self::ScheduledTransactionValidation(error) => {
|
Self::ScheduledTransactionValidation(error) => {
|
||||||
return (StatusCode::UNPROCESSABLE_ENTITY, error.to_string()).into_response();
|
return (StatusCode::UNPROCESSABLE_ENTITY, error.to_string()).into_response();
|
||||||
}
|
}
|
||||||
|
Self::TransactionValidation(error) => {
|
||||||
|
return (StatusCode::UNPROCESSABLE_ENTITY, error.to_string()).into_response();
|
||||||
|
}
|
||||||
Self::Database(error) => {
|
Self::Database(error) => {
|
||||||
tracing::error!(%error, "Database query failed");
|
tracing::error!(%error, "Database query failed");
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
pub mod amount_cents;
|
||||||
pub mod direction;
|
pub mod direction;
|
||||||
pub mod scheduled_transaction;
|
pub mod scheduled_transaction;
|
||||||
pub mod transaction;
|
pub mod transaction;
|
||||||
|
|||||||
@@ -0,0 +1,65 @@
|
|||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
|
||||||
|
#[serde(transparent)]
|
||||||
|
pub struct AmountCents(u64);
|
||||||
|
|
||||||
|
impl AmountCents {
|
||||||
|
pub fn get(&self) -> u64 {
|
||||||
|
self.0
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl From<u64> for AmountCents {
|
||||||
|
fn from(value: u64) -> Self {
|
||||||
|
Self(value)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl TryFrom<i64> for AmountCents {
|
||||||
|
type Error = AmountCentsConversionError;
|
||||||
|
|
||||||
|
fn try_from(value: i64) -> Result<Self, Self::Error> {
|
||||||
|
u64::try_from(value)
|
||||||
|
.map(Self)
|
||||||
|
.map_err(|_| AmountCentsConversionError(value.into()))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl TryFrom<AmountCents> for i64 {
|
||||||
|
type Error = AmountCentsConversionError;
|
||||||
|
|
||||||
|
fn try_from(value: AmountCents) -> Result<Self, Self::Error> {
|
||||||
|
i64::try_from(value.get()).map_err(|_| AmountCentsConversionError(value.get().into()))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, thiserror::Error)]
|
||||||
|
#[error("invalid amount_cents value: {0}")]
|
||||||
|
pub struct AmountCentsConversionError(pub i128);
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::{AmountCents, AmountCentsConversionError};
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn converts_non_negative_database_values() {
|
||||||
|
assert_eq!(AmountCents::try_from(4250_i64).unwrap().get(), 4250);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rejects_negative_database_values() {
|
||||||
|
assert!(matches!(
|
||||||
|
AmountCents::try_from(-1_i64),
|
||||||
|
Err(AmountCentsConversionError(-1_i128))
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rejects_values_too_large_for_the_database() {
|
||||||
|
assert!(matches!(
|
||||||
|
i64::try_from(AmountCents::from(i64::MAX as u64 + 1)),
|
||||||
|
Err(AmountCentsConversionError(value)) if value == i64::MAX as i128 + 1
|
||||||
|
));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -4,7 +4,10 @@ use uuid::Uuid;
|
|||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
database::dtos::recurring_transaction::RecurringTransactionRow,
|
database::dtos::recurring_transaction::RecurringTransactionRow,
|
||||||
routes::dtos::direction::{Direction, DirectionConversionError},
|
routes::dtos::{
|
||||||
|
amount_cents::{AmountCents, AmountCentsConversionError},
|
||||||
|
direction::{Direction, DirectionConversionError},
|
||||||
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
@@ -36,9 +39,7 @@ impl TryFrom<RecurringTransactionRow> for RecurringTransaction {
|
|||||||
id: row.id,
|
id: row.id,
|
||||||
data: RecurringTransactionData {
|
data: RecurringTransactionData {
|
||||||
name: row.name,
|
name: row.name,
|
||||||
amount_cents: row.amount_cents.try_into().map_err(|_| {
|
amount_cents: AmountCents::try_from(row.amount_cents)?,
|
||||||
RecurringTransactionConversionError::AmountCents(row.amount_cents)
|
|
||||||
})?,
|
|
||||||
direction: Direction::try_from(row.direction)
|
direction: Direction::try_from(row.direction)
|
||||||
.map_err(RecurringTransactionConversionError::Direction)?,
|
.map_err(RecurringTransactionConversionError::Direction)?,
|
||||||
start: row.starts_at,
|
start: row.starts_at,
|
||||||
@@ -68,7 +69,7 @@ pub enum ScheduledTransactionData {
|
|||||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
pub struct RecurringTransactionData {
|
pub struct RecurringTransactionData {
|
||||||
pub name: String,
|
pub name: String,
|
||||||
pub amount_cents: u64,
|
pub amount_cents: AmountCents,
|
||||||
pub direction: Direction,
|
pub direction: Direction,
|
||||||
pub start: DateTime<Utc>,
|
pub start: DateTime<Utc>,
|
||||||
pub end: Option<DateTime<Utc>>,
|
pub end: Option<DateTime<Utc>>,
|
||||||
@@ -148,8 +149,8 @@ impl TryFrom<String> for WeekendAdjustment {
|
|||||||
|
|
||||||
#[derive(Debug, thiserror::Error)]
|
#[derive(Debug, thiserror::Error)]
|
||||||
pub enum RecurringTransactionConversionError {
|
pub enum RecurringTransactionConversionError {
|
||||||
#[error("invalid amount_cents value: {0}")]
|
#[error(transparent)]
|
||||||
AmountCents(i64),
|
AmountCents(#[from] AmountCentsConversionError),
|
||||||
|
|
||||||
#[error(transparent)]
|
#[error(transparent)]
|
||||||
Direction(#[from] DirectionConversionError),
|
Direction(#[from] DirectionConversionError),
|
||||||
@@ -178,7 +179,7 @@ mod tests {
|
|||||||
fn transaction(amount_cents: u64) -> RecurringTransactionData {
|
fn transaction(amount_cents: u64) -> RecurringTransactionData {
|
||||||
RecurringTransactionData {
|
RecurringTransactionData {
|
||||||
name: String::new(),
|
name: String::new(),
|
||||||
amount_cents,
|
amount_cents: amount_cents.into(),
|
||||||
direction: Direction::Out,
|
direction: Direction::Out,
|
||||||
start: Utc.with_ymd_and_hms(2026, 9, 24, 12, 0, 0).unwrap(),
|
start: Utc.with_ymd_and_hms(2026, 9, 24, 12, 0, 0).unwrap(),
|
||||||
end: None,
|
end: None,
|
||||||
@@ -204,7 +205,7 @@ mod tests {
|
|||||||
|
|
||||||
let request: ScheduledTransactionData = serde_json::from_value(response).unwrap();
|
let request: ScheduledTransactionData = serde_json::from_value(response).unwrap();
|
||||||
let ScheduledTransactionData::Recurring(data) = request;
|
let ScheduledTransactionData::Recurring(data) = request;
|
||||||
assert_eq!(data.amount_cents, 1234);
|
assert_eq!(data.amount_cents.get(), 1234);
|
||||||
assert_eq!(data.recurrence.every, 2);
|
assert_eq!(data.recurrence.every, 2);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,41 +1,50 @@
|
|||||||
use chrono::{DateTime, Utc};
|
use chrono::{DateTime, Utc};
|
||||||
use serde::Serialize;
|
use serde::{Deserialize, Serialize};
|
||||||
use uuid::Uuid;
|
use uuid::Uuid;
|
||||||
|
|
||||||
use crate::database::dtos::transaction::TransactionRow;
|
use crate::database::dtos::transaction::TransactionRow;
|
||||||
use crate::routes::dtos::direction::{Direction, DirectionConversionError};
|
use crate::routes::dtos::{
|
||||||
|
amount_cents::{AmountCents, AmountCentsConversionError},
|
||||||
|
direction::{Direction, DirectionConversionError},
|
||||||
|
};
|
||||||
|
|
||||||
#[derive(Serialize)]
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
pub struct TransactionResponse {
|
pub struct Transaction {
|
||||||
pub id: Uuid,
|
pub id: Uuid,
|
||||||
|
|
||||||
|
#[serde(flatten)]
|
||||||
|
pub data: TransactionData,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
|
pub struct TransactionData {
|
||||||
pub description: String,
|
pub description: String,
|
||||||
pub amount_cents: u64,
|
pub amount_cents: AmountCents,
|
||||||
pub direction: Direction,
|
pub direction: Direction,
|
||||||
pub date: DateTime<Utc>,
|
pub date: DateTime<Utc>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl TryFrom<TransactionRow> for TransactionResponse {
|
impl TryFrom<TransactionRow> for Transaction {
|
||||||
type Error = TransactionConversionError;
|
type Error = TransactionConversionError;
|
||||||
|
|
||||||
fn try_from(row: TransactionRow) -> Result<Self, Self::Error> {
|
fn try_from(row: TransactionRow) -> Result<Self, Self::Error> {
|
||||||
Ok(Self {
|
Ok(Self {
|
||||||
id: row.id,
|
id: row.id,
|
||||||
description: row.description,
|
data: TransactionData {
|
||||||
amount_cents: row
|
description: row.description,
|
||||||
.amount_cents
|
amount_cents: AmountCents::try_from(row.amount_cents)?,
|
||||||
.try_into()
|
direction: Direction::try_from(row.direction)
|
||||||
.map_err(|_| TransactionConversionError::AmountCents(row.amount_cents))?,
|
.map_err(TransactionConversionError::Direction)?,
|
||||||
direction: Direction::try_from(row.direction)
|
date: row.date,
|
||||||
.map_err(TransactionConversionError::Direction)?,
|
},
|
||||||
date: row.date,
|
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, thiserror::Error)]
|
#[derive(Debug, thiserror::Error)]
|
||||||
pub enum TransactionConversionError {
|
pub enum TransactionConversionError {
|
||||||
#[error("invalid amount_cents value: {0}")]
|
#[error(transparent)]
|
||||||
AmountCents(i64),
|
AmountCents(#[from] AmountCentsConversionError),
|
||||||
|
|
||||||
#[error(transparent)]
|
#[error(transparent)]
|
||||||
Direction(#[from] DirectionConversionError),
|
Direction(#[from] DirectionConversionError),
|
||||||
@@ -49,7 +58,7 @@ mod tests {
|
|||||||
fn preserves_cents_in_response() {
|
fn preserves_cents_in_response() {
|
||||||
let id = Uuid::new_v4();
|
let id = Uuid::new_v4();
|
||||||
let date = Utc::now();
|
let date = Utc::now();
|
||||||
let response = TransactionResponse::try_from(TransactionRow {
|
let response = Transaction::try_from(TransactionRow {
|
||||||
id,
|
id,
|
||||||
description: "Groceries".to_string(),
|
description: "Groceries".to_string(),
|
||||||
amount_cents: 4250,
|
amount_cents: 4250,
|
||||||
@@ -60,8 +69,30 @@ mod tests {
|
|||||||
let response = response.expect("valid direction");
|
let response = response.expect("valid direction");
|
||||||
|
|
||||||
assert_eq!(response.id, id);
|
assert_eq!(response.id, id);
|
||||||
assert_eq!(response.description, "Groceries");
|
assert_eq!(response.data.description, "Groceries");
|
||||||
assert_eq!(response.amount_cents, 4250);
|
assert_eq!(response.data.amount_cents.get(), 4250);
|
||||||
assert_eq!(response.date, date);
|
assert_eq!(response.data.date, date);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn keeps_transaction_json_flat() {
|
||||||
|
let response = Transaction {
|
||||||
|
id: Uuid::nil(),
|
||||||
|
data: TransactionData {
|
||||||
|
description: "Groceries".to_string(),
|
||||||
|
amount_cents: 4250.into(),
|
||||||
|
direction: Direction::Out,
|
||||||
|
date: Utc::now(),
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
let response = serde_json::to_value(response).unwrap();
|
||||||
|
assert_eq!(response["id"], Uuid::nil().to_string());
|
||||||
|
assert_eq!(response["amount_cents"], 4250);
|
||||||
|
assert!(response.get("data").is_none());
|
||||||
|
|
||||||
|
let request: TransactionData = serde_json::from_value(response).unwrap();
|
||||||
|
assert_eq!(request.description, "Groceries");
|
||||||
|
assert_eq!(request.amount_cents.get(), 4250);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,7 +6,6 @@ use axum::{
|
|||||||
use sqlx::PgPool;
|
use sqlx::PgPool;
|
||||||
use uuid::Uuid;
|
use uuid::Uuid;
|
||||||
|
|
||||||
use super::validation::scheduled_transaction::ValidatedRecurringTransaction;
|
|
||||||
use crate::{
|
use crate::{
|
||||||
database::{
|
database::{
|
||||||
common::{Delete, Upsert},
|
common::{Delete, Upsert},
|
||||||
@@ -17,17 +16,23 @@ use crate::{
|
|||||||
},
|
},
|
||||||
},
|
},
|
||||||
error::AppError,
|
error::AppError,
|
||||||
routes::dtos::scheduled_transaction::{
|
routes::{
|
||||||
RecurringTransaction, ScheduledTransaction, ScheduledTransactionData,
|
dtos::scheduled_transaction::{
|
||||||
|
RecurringTransaction, ScheduledTransaction, ScheduledTransactionData,
|
||||||
|
},
|
||||||
|
validation::scheduled_transaction::ValidatedRecurringTransaction,
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
pub fn create_router() -> axum::Router<PgPool> {
|
pub fn create_router() -> axum::Router<PgPool> {
|
||||||
axum::Router::new()
|
axum::Router::new()
|
||||||
.route("/", axum::routing::get(get_scheduled_transactions))
|
.route("/", axum::routing::get(get_scheduled_transactions))
|
||||||
.route("/{id}", axum::routing::get(get_scheduled_transaction))
|
.route(
|
||||||
.route("/{id}", axum::routing::put(put_scheduled_transaction))
|
"/{id}",
|
||||||
.route("/{id}", axum::routing::delete(delete_scheduled_transaction))
|
axum::routing::get(get_scheduled_transaction)
|
||||||
|
.put(put_scheduled_transaction)
|
||||||
|
.delete(delete_scheduled_transaction),
|
||||||
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
#[axum::debug_handler]
|
#[axum::debug_handler]
|
||||||
@@ -54,7 +59,7 @@ async fn get_scheduled_transaction(
|
|||||||
) -> Result<Json<ScheduledTransaction>, AppError> {
|
) -> Result<Json<ScheduledTransaction>, AppError> {
|
||||||
let row = get_scheduled_transaction_by_id(&pool, id)
|
let row = get_scheduled_transaction_by_id(&pool, id)
|
||||||
.await?
|
.await?
|
||||||
.map(|t| RecurringTransaction::try_from(t))
|
.map(RecurringTransaction::try_from)
|
||||||
.transpose()?;
|
.transpose()?;
|
||||||
|
|
||||||
match row {
|
match row {
|
||||||
@@ -76,7 +81,7 @@ async fn put_scheduled_transaction(
|
|||||||
let transaction = RecurringTransactionRow {
|
let transaction = RecurringTransactionRow {
|
||||||
id,
|
id,
|
||||||
name: transaction.name,
|
name: transaction.name,
|
||||||
amount_cents: transaction.amount_cents.get(),
|
amount_cents: transaction.amount_cents,
|
||||||
direction: transaction.direction.as_str().to_owned(),
|
direction: transaction.direction.as_str().to_owned(),
|
||||||
starts_at: transaction.starts_at,
|
starts_at: transaction.starts_at,
|
||||||
ends_at: transaction.ends_at,
|
ends_at: transaction.ends_at,
|
||||||
|
|||||||
@@ -7,53 +7,94 @@ use sqlx::PgPool;
|
|||||||
use uuid::Uuid;
|
use uuid::Uuid;
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
database::dtos::transaction::TransactionRow, error::AppError,
|
database::{
|
||||||
routes::dtos::transaction::TransactionResponse,
|
common::{Delete, Upsert},
|
||||||
|
dtos::transaction::TransactionRow,
|
||||||
|
transactions::{
|
||||||
|
delete_transaction_by_id, get_transaction_by_id, query_transactions, upsert_transaction,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
error::AppError,
|
||||||
|
routes::{
|
||||||
|
dtos::transaction::{Transaction, TransactionData},
|
||||||
|
validation::transaction::ValidatedTransaction,
|
||||||
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
pub fn create_router() -> axum::Router<PgPool> {
|
pub fn create_router() -> axum::Router<PgPool> {
|
||||||
axum::Router::new()
|
axum::Router::new()
|
||||||
.route("/", axum::routing::get(get_transactions))
|
.route("/", axum::routing::get(get_transactions))
|
||||||
.route("/{id}", axum::routing::delete(delete_transaction))
|
.route(
|
||||||
|
"/{id}",
|
||||||
|
axum::routing::get(get_transaction)
|
||||||
|
.put(put_transaction)
|
||||||
|
.delete(delete_transaction),
|
||||||
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
#[axum::debug_handler]
|
#[axum::debug_handler]
|
||||||
#[tracing::instrument(skip(pool))]
|
#[tracing::instrument(skip(pool))]
|
||||||
async fn get_transactions(
|
async fn get_transactions(State(pool): State<PgPool>) -> Result<Json<Vec<Transaction>>, AppError> {
|
||||||
State(pool): State<PgPool>,
|
let rows = query_transactions(&pool).await?;
|
||||||
) -> Result<Json<Vec<TransactionResponse>>, AppError> {
|
|
||||||
let rows = sqlx::query_as!(
|
|
||||||
TransactionRow,
|
|
||||||
r#"
|
|
||||||
SELECT id, description, amount_cents, direction, date
|
|
||||||
FROM transactions
|
|
||||||
ORDER BY date DESC, id DESC
|
|
||||||
"#
|
|
||||||
)
|
|
||||||
.fetch_all(&pool)
|
|
||||||
.await?;
|
|
||||||
|
|
||||||
let transactions = rows
|
let transactions = rows
|
||||||
.into_iter()
|
.into_iter()
|
||||||
.map(TransactionResponse::try_from)
|
.map(Transaction::try_from)
|
||||||
.collect::<Result<Vec<_>, _>>()?;
|
.collect::<Result<Vec<_>, _>>()?;
|
||||||
|
|
||||||
Ok(Json(transactions))
|
Ok(Json(transactions))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[axum::debug_handler]
|
||||||
|
#[tracing::instrument(skip(pool))]
|
||||||
|
async fn get_transaction(
|
||||||
|
State(pool): State<PgPool>,
|
||||||
|
Path(id): Path<Uuid>,
|
||||||
|
) -> Result<Json<Transaction>, AppError> {
|
||||||
|
let transaction = get_transaction_by_id(&pool, id)
|
||||||
|
.await?
|
||||||
|
.map(Transaction::try_from)
|
||||||
|
.transpose()?;
|
||||||
|
|
||||||
|
match transaction {
|
||||||
|
Some(transaction) => Ok(Json(transaction)),
|
||||||
|
None => Err(AppError::NotFound),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[axum::debug_handler]
|
||||||
|
#[tracing::instrument(skip(pool, transaction))]
|
||||||
|
async fn put_transaction(
|
||||||
|
State(pool): State<PgPool>,
|
||||||
|
Path(id): Path<Uuid>,
|
||||||
|
Json(transaction): Json<TransactionData>,
|
||||||
|
) -> Result<(StatusCode, Json<Transaction>), AppError> {
|
||||||
|
let transaction = ValidatedTransaction::try_from(transaction)?;
|
||||||
|
let transaction = TransactionRow {
|
||||||
|
id,
|
||||||
|
description: transaction.description,
|
||||||
|
amount_cents: transaction.amount_cents,
|
||||||
|
direction: transaction.direction.as_str().to_owned(),
|
||||||
|
date: transaction.date,
|
||||||
|
};
|
||||||
|
|
||||||
|
let (status, row) = match upsert_transaction(&pool, transaction).await? {
|
||||||
|
Upsert::Created(row) => (StatusCode::CREATED, row),
|
||||||
|
Upsert::Updated(row) => (StatusCode::OK, row),
|
||||||
|
};
|
||||||
|
let transaction = Transaction::try_from(row)?;
|
||||||
|
|
||||||
|
Ok((status, Json(transaction)))
|
||||||
|
}
|
||||||
|
|
||||||
#[axum::debug_handler]
|
#[axum::debug_handler]
|
||||||
#[tracing::instrument(skip(pool))]
|
#[tracing::instrument(skip(pool))]
|
||||||
async fn delete_transaction(
|
async fn delete_transaction(
|
||||||
Path(id): Path<Uuid>,
|
Path(id): Path<Uuid>,
|
||||||
State(pool): State<PgPool>,
|
State(pool): State<PgPool>,
|
||||||
) -> Result<StatusCode, AppError> {
|
) -> Result<StatusCode, AppError> {
|
||||||
let deleted = sqlx::query!("DELETE FROM transactions WHERE id = $1 RETURNING id", id)
|
match delete_transaction_by_id(&pool, id).await? {
|
||||||
.fetch_optional(&pool)
|
Delete::Deleted => Ok(StatusCode::NO_CONTENT),
|
||||||
.await?;
|
Delete::NotFound => Err(AppError::NotFound),
|
||||||
|
|
||||||
if deleted.is_none() {
|
|
||||||
return Ok(StatusCode::NOT_FOUND);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
Ok(StatusCode::NO_CONTENT)
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1 +1,2 @@
|
|||||||
pub mod scheduled_transaction;
|
pub mod scheduled_transaction;
|
||||||
|
pub mod transaction;
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
use chrono::{DateTime, Utc};
|
use chrono::{DateTime, Utc};
|
||||||
|
|
||||||
use crate::routes::dtos::{
|
use crate::routes::dtos::{
|
||||||
|
amount_cents::AmountCentsConversionError,
|
||||||
direction::Direction,
|
direction::Direction,
|
||||||
scheduled_transaction::{RecurrenceUnit, RecurringTransactionData, WeekendAdjustment},
|
scheduled_transaction::{RecurrenceUnit, RecurringTransactionData, WeekendAdjustment},
|
||||||
};
|
};
|
||||||
@@ -8,7 +9,7 @@ use crate::routes::dtos::{
|
|||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
pub struct ValidatedRecurringTransaction {
|
pub struct ValidatedRecurringTransaction {
|
||||||
pub name: String,
|
pub name: String,
|
||||||
pub amount_cents: Cents,
|
pub amount_cents: i64,
|
||||||
pub direction: Direction,
|
pub direction: Direction,
|
||||||
pub starts_at: DateTime<Utc>,
|
pub starts_at: DateTime<Utc>,
|
||||||
pub ends_at: Option<DateTime<Utc>>,
|
pub ends_at: Option<DateTime<Utc>>,
|
||||||
@@ -42,25 +43,6 @@ impl TryFrom<RecurringTransactionData> for ValidatedRecurringTransaction {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug)]
|
|
||||||
pub struct Cents(i64);
|
|
||||||
|
|
||||||
impl Cents {
|
|
||||||
pub fn get(&self) -> i64 {
|
|
||||||
self.0
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl TryFrom<u64> for Cents {
|
|
||||||
type Error = ScheduledTransactionValidationError;
|
|
||||||
|
|
||||||
fn try_from(amount_cents: u64) -> Result<Self, Self::Error> {
|
|
||||||
i64::try_from(amount_cents)
|
|
||||||
.map(Self)
|
|
||||||
.map_err(|_| ScheduledTransactionValidationError::AmountOutOfRange)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
pub struct PositiveRecurrenceInterval(i32);
|
pub struct PositiveRecurrenceInterval(i32);
|
||||||
|
|
||||||
@@ -84,8 +66,8 @@ impl TryFrom<u32> for PositiveRecurrenceInterval {
|
|||||||
|
|
||||||
#[derive(Debug, thiserror::Error)]
|
#[derive(Debug, thiserror::Error)]
|
||||||
pub enum ScheduledTransactionValidationError {
|
pub enum ScheduledTransactionValidationError {
|
||||||
#[error("amount is too large")]
|
#[error(transparent)]
|
||||||
AmountOutOfRange,
|
AmountCents(#[from] AmountCentsConversionError),
|
||||||
|
|
||||||
#[error("recurrence every must be between 1 and {}: {}", i32::MAX, .0)]
|
#[error("recurrence every must be between 1 and {}: {}", i32::MAX, .0)]
|
||||||
RecurrenceEvery(u32),
|
RecurrenceEvery(u32),
|
||||||
@@ -99,10 +81,11 @@ mod tests {
|
|||||||
use chrono::{TimeZone, Utc};
|
use chrono::{TimeZone, Utc};
|
||||||
|
|
||||||
use super::{
|
use super::{
|
||||||
Cents, PositiveRecurrenceInterval, ScheduledTransactionValidationError,
|
PositiveRecurrenceInterval, ScheduledTransactionValidationError,
|
||||||
ValidatedRecurringTransaction,
|
ValidatedRecurringTransaction,
|
||||||
};
|
};
|
||||||
use crate::routes::dtos::{
|
use crate::routes::dtos::{
|
||||||
|
amount_cents::AmountCentsConversionError,
|
||||||
direction::Direction,
|
direction::Direction,
|
||||||
scheduled_transaction::{
|
scheduled_transaction::{
|
||||||
Recurrence, RecurrenceUnit, RecurringTransactionData, WeekendAdjustment,
|
Recurrence, RecurrenceUnit, RecurringTransactionData, WeekendAdjustment,
|
||||||
@@ -112,7 +95,7 @@ mod tests {
|
|||||||
fn transaction(amount_cents: u64) -> RecurringTransactionData {
|
fn transaction(amount_cents: u64) -> RecurringTransactionData {
|
||||||
RecurringTransactionData {
|
RecurringTransactionData {
|
||||||
name: String::new(),
|
name: String::new(),
|
||||||
amount_cents,
|
amount_cents: amount_cents.into(),
|
||||||
direction: Direction::Out,
|
direction: Direction::Out,
|
||||||
start: Utc.with_ymd_and_hms(2026, 9, 24, 12, 0, 0).unwrap(),
|
start: Utc.with_ymd_and_hms(2026, 9, 24, 12, 0, 0).unwrap(),
|
||||||
end: None,
|
end: None,
|
||||||
@@ -128,7 +111,7 @@ mod tests {
|
|||||||
fn validates_and_preserves_typed_values() {
|
fn validates_and_preserves_typed_values() {
|
||||||
let transaction = ValidatedRecurringTransaction::try_from(transaction(1234)).unwrap();
|
let transaction = ValidatedRecurringTransaction::try_from(transaction(1234)).unwrap();
|
||||||
assert_eq!(transaction.name, "");
|
assert_eq!(transaction.name, "");
|
||||||
assert_eq!(transaction.amount_cents.get(), 1234);
|
assert_eq!(transaction.amount_cents, 1234);
|
||||||
assert!(matches!(transaction.direction, Direction::Out));
|
assert!(matches!(transaction.direction, Direction::Out));
|
||||||
assert_eq!(transaction.recurrence_every.get(), 2);
|
assert_eq!(transaction.recurrence_every.get(), 2);
|
||||||
assert!(matches!(transaction.recurrence_unit, RecurrenceUnit::Month));
|
assert!(matches!(transaction.recurrence_unit, RecurrenceUnit::Month));
|
||||||
@@ -140,8 +123,13 @@ mod tests {
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn rejects_amounts_that_do_not_fit_in_database() {
|
fn rejects_amounts_that_do_not_fit_in_database() {
|
||||||
let error = Cents::try_from(i64::MAX as u64 + 1).unwrap_err();
|
let error =
|
||||||
assert_eq!(error.to_string(), "amount is too large");
|
ValidatedRecurringTransaction::try_from(transaction(i64::MAX as u64 + 1)).unwrap_err();
|
||||||
|
assert!(matches!(
|
||||||
|
error,
|
||||||
|
ScheduledTransactionValidationError::AmountCents(AmountCentsConversionError(value))
|
||||||
|
if value == i64::MAX as i128 + 1
|
||||||
|
));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
|
|||||||
@@ -0,0 +1,74 @@
|
|||||||
|
use chrono::{DateTime, Utc};
|
||||||
|
|
||||||
|
use crate::routes::dtos::{
|
||||||
|
amount_cents::AmountCentsConversionError, direction::Direction, transaction::TransactionData,
|
||||||
|
};
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub struct ValidatedTransaction {
|
||||||
|
pub description: String,
|
||||||
|
pub amount_cents: i64,
|
||||||
|
pub direction: Direction,
|
||||||
|
pub date: DateTime<Utc>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl TryFrom<TransactionData> for ValidatedTransaction {
|
||||||
|
type Error = TransactionValidationError;
|
||||||
|
|
||||||
|
fn try_from(transaction: TransactionData) -> Result<Self, Self::Error> {
|
||||||
|
Ok(Self {
|
||||||
|
description: transaction.description,
|
||||||
|
amount_cents: transaction.amount_cents.try_into()?,
|
||||||
|
direction: transaction.direction,
|
||||||
|
date: transaction.date,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, thiserror::Error)]
|
||||||
|
pub enum TransactionValidationError {
|
||||||
|
#[error(transparent)]
|
||||||
|
AmountCents(#[from] AmountCentsConversionError),
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use chrono::Utc;
|
||||||
|
|
||||||
|
use super::{TransactionValidationError, ValidatedTransaction};
|
||||||
|
use crate::routes::dtos::{
|
||||||
|
amount_cents::AmountCentsConversionError, direction::Direction,
|
||||||
|
transaction::TransactionData,
|
||||||
|
};
|
||||||
|
|
||||||
|
fn transaction(amount_cents: u64) -> TransactionData {
|
||||||
|
TransactionData {
|
||||||
|
description: "Groceries".to_string(),
|
||||||
|
amount_cents: amount_cents.into(),
|
||||||
|
direction: Direction::Out,
|
||||||
|
date: Utc::now(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn validates_and_preserves_typed_values() {
|
||||||
|
let transaction = ValidatedTransaction::try_from(transaction(1234)).unwrap();
|
||||||
|
assert_eq!(transaction.description, "Groceries");
|
||||||
|
assert_eq!(transaction.amount_cents, 1234);
|
||||||
|
assert!(matches!(transaction.direction, Direction::Out));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rejects_amounts_that_do_not_fit_in_database() {
|
||||||
|
let error = ValidatedTransaction::try_from(transaction(i64::MAX as u64 + 1)).unwrap_err();
|
||||||
|
assert_eq!(
|
||||||
|
error.to_string(),
|
||||||
|
format!("invalid amount_cents value: {}", i64::MAX as u64 + 1)
|
||||||
|
);
|
||||||
|
assert!(matches!(
|
||||||
|
error,
|
||||||
|
TransactionValidationError::AmountCents(AmountCentsConversionError(value))
|
||||||
|
if value == i64::MAX as i128 + 1
|
||||||
|
));
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user