Implemented amount_cents for transactions.
This commit is contained in:
@@ -9,31 +9,54 @@ use crate::routes::dtos::direction::{Direction, DirectionConversionError};
|
||||
pub struct TransactionResponse {
|
||||
pub id: Uuid,
|
||||
pub description: String,
|
||||
pub amount: f64,
|
||||
pub amount_cents: u64,
|
||||
pub direction: Direction,
|
||||
pub date: DateTime<Utc>,
|
||||
}
|
||||
|
||||
impl TryFrom<TransactionRow> for TransactionResponse {
|
||||
type Error = DirectionConversionError;
|
||||
type Error = TransactionConversionError;
|
||||
|
||||
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)?,
|
||||
amount_cents: row
|
||||
.amount_cents
|
||||
.try_into()
|
||||
.map_err(|_| TransactionConversionError::AmountCents(row.amount_cents))?,
|
||||
direction: Direction::try_from(row.direction)
|
||||
.map_err(TransactionConversionError::Direction)?,
|
||||
date: row.date,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum TransactionConversionError {
|
||||
AmountCents(i64),
|
||||
Direction(DirectionConversionError),
|
||||
}
|
||||
|
||||
impl std::error::Error for TransactionConversionError {}
|
||||
|
||||
impl std::fmt::Display for TransactionConversionError {
|
||||
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match self {
|
||||
Self::AmountCents(value) => {
|
||||
write!(formatter, "invalid amount_cents value: {value}")
|
||||
}
|
||||
Self::Direction(error) => error.fmt(formatter),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn converts_cents_to_major_currency_units() {
|
||||
fn preserves_cents_in_response() {
|
||||
let id = Uuid::new_v4();
|
||||
let date = Utc::now();
|
||||
let response = TransactionResponse::try_from(TransactionRow {
|
||||
@@ -48,7 +71,7 @@ mod tests {
|
||||
|
||||
assert_eq!(response.id, id);
|
||||
assert_eq!(response.description, "Groceries");
|
||||
assert_eq!(response.amount, 42.5);
|
||||
assert_eq!(response.amount_cents, 4250);
|
||||
assert_eq!(response.date, date);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user