55 lines
1.4 KiB
Rust
55 lines
1.4 KiB
Rust
use chrono::{DateTime, Utc};
|
|
use serde::Serialize;
|
|
use uuid::Uuid;
|
|
|
|
use crate::database::dtos::transaction::TransactionRow;
|
|
use crate::routes::dtos::direction::{Direction, DirectionConversionError};
|
|
|
|
#[derive(Serialize)]
|
|
pub struct TransactionResponse {
|
|
pub id: Uuid,
|
|
pub description: String,
|
|
pub amount: f64,
|
|
pub direction: Direction,
|
|
pub date: DateTime<Utc>,
|
|
}
|
|
|
|
impl TryFrom<TransactionRow> for TransactionResponse {
|
|
type Error = DirectionConversionError;
|
|
|
|
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: Direction::try_from(row.direction)?,
|
|
date: row.date,
|
|
})
|
|
}
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
|
|
#[test]
|
|
fn converts_cents_to_major_currency_units() {
|
|
let id = Uuid::new_v4();
|
|
let date = Utc::now();
|
|
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);
|
|
assert_eq!(response.date, date);
|
|
}
|
|
}
|