99 lines
2.8 KiB
Rust
99 lines
2.8 KiB
Rust
use chrono::{DateTime, Utc};
|
|
use serde::{Deserialize, Serialize};
|
|
use uuid::Uuid;
|
|
|
|
use crate::database::dtos::transaction::TransactionRow;
|
|
use crate::routes::dtos::{
|
|
amount_cents::{AmountCents, AmountCentsConversionError},
|
|
direction::{Direction, DirectionConversionError},
|
|
};
|
|
|
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
|
pub struct Transaction {
|
|
pub id: Uuid,
|
|
|
|
#[serde(flatten)]
|
|
pub data: TransactionData,
|
|
}
|
|
|
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
|
pub struct TransactionData {
|
|
pub description: String,
|
|
pub amount_cents: AmountCents,
|
|
pub direction: Direction,
|
|
pub date: DateTime<Utc>,
|
|
}
|
|
|
|
impl TryFrom<TransactionRow> for Transaction {
|
|
type Error = TransactionConversionError;
|
|
|
|
fn try_from(row: TransactionRow) -> Result<Self, Self::Error> {
|
|
Ok(Self {
|
|
id: row.id,
|
|
data: TransactionData {
|
|
description: row.description,
|
|
amount_cents: AmountCents::try_from(row.amount_cents)?,
|
|
direction: Direction::try_from(row.direction)
|
|
.map_err(TransactionConversionError::Direction)?,
|
|
date: row.date,
|
|
},
|
|
})
|
|
}
|
|
}
|
|
|
|
#[derive(Debug, thiserror::Error)]
|
|
pub enum TransactionConversionError {
|
|
#[error(transparent)]
|
|
AmountCents(#[from] AmountCentsConversionError),
|
|
|
|
#[error(transparent)]
|
|
Direction(#[from] DirectionConversionError),
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
|
|
#[test]
|
|
fn preserves_cents_in_response() {
|
|
let id = Uuid::new_v4();
|
|
let date = Utc::now();
|
|
let response = Transaction::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.data.description, "Groceries");
|
|
assert_eq!(response.data.amount_cents.get(), 4250);
|
|
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);
|
|
}
|
|
}
|