Compare commits

...

2 commits

Author SHA1 Message Date
272e8f68c6 Merge pull request 'feat: billing: aggregate IDs are provided by caller & test View impl' (#113) from billing-fix-aggregate-id into master
All checks were successful
ci/woodpecker/push/woodpecker Pipeline was successful
Reviewed-on: #113
2024-09-21 20:04:39 +05:30
4a51a3d629
feat: billing: aggregate IDs are provided by caller & test View impl
All checks were successful
ci/woodpecker/push/woodpecker Pipeline was successful
ci/woodpecker/pr/woodpecker Pipeline was successful
ci/woodpecker/pull_request_closed/woodpecker Pipeline was successful
2024-09-21 19:55:11 +05:30
19 changed files with 812 additions and 441 deletions

View file

@ -1,27 +0,0 @@
{
"db_name": "PostgreSQL",
"query": "UPDATE\n cqrs_billing_line_item_query\n SET\n version = $1,\n product_name = $2,\n product_id = $3,\n line_item_id = $4,\n quantity_minor_unit = $5,\n quantity_minor_number = $6,\n quantity_major_unit = $7,\n quantity_major_number = $8,\n created_time = $9,\n bill_id = $10,\n price_per_unit_minor = $11 ,\n price_per_unit_major = $12,\n price_per_unit_currency = $13,\n deleted = $14;",
"describe": {
"columns": [],
"parameters": {
"Left": [
"Int8",
"Text",
"Uuid",
"Uuid",
"Text",
"Int4",
"Text",
"Int4",
"Timestamptz",
"Uuid",
"Int4",
"Int4",
"Text",
"Bool"
]
},
"nullable": []
},
"hash": "0268f0c43abe34a3147f0a43f0e11bf302a3750ecadf28b1d6af62da62934f87"
}

View file

@ -0,0 +1,26 @@
{
"db_name": "PostgreSQL",
"query": "UPDATE\n cqrs_billing_line_item_query\n SET\n version = $1,\n product_name = $2,\n product_id = $3,\n quantity_minor_unit = $4,\n quantity_minor_number = $5,\n quantity_major_unit = $6,\n quantity_major_number = $7,\n created_time = $8,\n bill_id = $9,\n price_per_unit_minor = $10 ,\n price_per_unit_major = $11,\n price_per_unit_currency = $12,\n deleted = $13;",
"describe": {
"columns": [],
"parameters": {
"Left": [
"Int8",
"Text",
"Uuid",
"Text",
"Int4",
"Text",
"Int4",
"Timestamptz",
"Uuid",
"Int4",
"Int4",
"Text",
"Bool"
]
},
"nullable": []
},
"hash": "995cca627c711a87b30723c6ceefd3fcdd1fc63bdcd95f8a974823089652aa51"
}

View file

@ -1,6 +1,6 @@
{ {
"db_name": "PostgreSQL", "db_name": "PostgreSQL",
"query": "UPDATE\n cqrs_billing_bill_query\n SET\n version = $1,\n\n created_time = $2,\n store_id = $3,\n bill_id = $4,\n token_number = $5,\n total_price_major = $6,\n total_price_minor = $7,\n total_price_currency = $8,\n\n deleted = $9;", "query": "UPDATE\n cqrs_billing_bill_query\n SET\n version = $1,\n\n created_time = $2,\n store_id = $3,\n token_number = $4,\n total_price_major = $5,\n total_price_minor = $6,\n total_price_currency = $7,\n deleted = $8;",
"describe": { "describe": {
"columns": [], "columns": [],
"parameters": { "parameters": {
@ -8,7 +8,6 @@
"Int8", "Int8",
"Timestamptz", "Timestamptz",
"Uuid", "Uuid",
"Uuid",
"Int4", "Int4",
"Int4", "Int4",
"Int4", "Int4",
@ -18,5 +17,5 @@
}, },
"nullable": [] "nullable": []
}, },
"hash": "b335fc519289a42c707855b620a35433d3f8bd1e798772c05fc156494c036ef5" "hash": "c30f49bb293ca6e184c5110bdfe1108b23bdf71dd904bdd5287155161138565d"
} }

View file

@ -1,6 +1,6 @@
{ {
"db_name": "PostgreSQL", "db_name": "PostgreSQL",
"query": "UPDATE\n cqrs_billing_store_query\n SET\n version = $1,\n name = $2,\n address = $3,\n store_id = $4,\n owner = $5,\n deleted = $6;", "query": "UPDATE\n cqrs_billing_store_query\n SET\n version = $1,\n name = $2,\n address = $3,\n owner = $4,\n deleted = $5;",
"describe": { "describe": {
"columns": [], "columns": [],
"parameters": { "parameters": {
@ -9,11 +9,10 @@
"Text", "Text",
"Text", "Text",
"Uuid", "Uuid",
"Uuid",
"Bool" "Bool"
] ]
}, },
"nullable": [] "nullable": []
}, },
"hash": "3811531518316435c32223582f9de6bdfefc19839129577407a1e4071f5c49f6" "hash": "d7decc8f70fc4f12d7a1db5009d2190bb9746000067d53990eb7cd646ff5d252"
} }

View file

@ -36,7 +36,7 @@ pub mod tests {
// use crate::billing::domain::add_product_command::tests::get_customizations; // use crate::billing::domain::add_product_command::tests::get_customizations;
use crate::billing::domain::bill_aggregate::*; use crate::billing::domain::bill_aggregate::*;
async fn create_dummy_bill(bill: &Bill, db: &BillingDBPostgresAdapter) { pub async fn create_dummy_bill(bill: &Bill, db: &BillingDBPostgresAdapter) {
sqlx::query!( sqlx::query!(
"INSERT INTO cqrs_billing_bill_query ( "INSERT INTO cqrs_billing_bill_query (
version, version,

View file

@ -2,6 +2,8 @@
// //
// SPDX-License-Identifier: AGPL-3.0-or-later // SPDX-License-Identifier: AGPL-3.0-or-later
use std::str::FromStr;
use async_trait::async_trait; use async_trait::async_trait;
use cqrs_es::persist::{PersistenceError, ViewContext, ViewRepository}; use cqrs_es::persist::{PersistenceError, ViewContext, ViewRepository};
use cqrs_es::{EventEnvelope, Query, View}; use cqrs_es::{EventEnvelope, Query, View};
@ -11,8 +13,9 @@ use uuid::Uuid;
use super::errors::*; use super::errors::*;
use super::BillingDBPostgresAdapter; use super::BillingDBPostgresAdapter;
use crate::billing::domain::bill_aggregate::Bill; use crate::billing::domain::bill_aggregate::{Bill, BillBuilder};
use crate::billing::domain::events::BillingEvent; use crate::billing::domain::events::BillingEvent;
use crate::types::currency::{self, Currency, PriceBuilder};
use crate::utils::parse_aggregate_id::parse_aggregate_id; use crate::utils::parse_aggregate_id::parse_aggregate_id;
pub const NEW_BILL_NON_UUID: &str = "billing_new_bill_non_uuid-asdfa"; pub const NEW_BILL_NON_UUID: &str = "billing_new_bill_non_uuid-asdfa";
@ -34,6 +37,36 @@ pub struct BillView {
deleted: bool, deleted: bool,
} }
impl From<BillView> for Bill {
fn from(v: BillView) -> Self {
let price = match (
v.total_price_minor,
v.total_price_major,
v.total_price_currency,
) {
(Some(minor), Some(major), Some(currency)) => Some(
PriceBuilder::default()
.major(major as usize)
.minor(minor as usize)
.currency(Currency::from_str(&currency).unwrap())
.build()
.unwrap(),
),
_ => None,
};
BillBuilder::default()
.created_time(v.created_time)
.store_id(v.store_id)
.bill_id(v.bill_id)
.token_number(v.token_number as usize)
.total_price(price)
.deleted(v.deleted)
.build()
.unwrap()
}
}
impl Default for BillView { impl Default for BillView {
fn default() -> Self { fn default() -> Self {
Self { Self {
@ -225,17 +258,14 @@ impl ViewRepository<BillView, Bill> for BillingDBPostgresAdapter {
created_time = $2, created_time = $2,
store_id = $3, store_id = $3,
bill_id = $4, token_number = $4,
token_number = $5, total_price_major = $5,
total_price_major = $6, total_price_minor = $6,
total_price_minor = $7, total_price_currency = $7,
total_price_currency = $8, deleted = $8;",
deleted = $9;",
version, version,
view.created_time, view.created_time,
view.store_id, view.store_id,
view.bill_id,
view.token_number, view.token_number,
view.total_price_major, view.total_price_major,
view.total_price_minor, view.total_price_minor,
@ -281,108 +311,136 @@ impl Query<Bill> for BillingDBPostgresAdapter {
} }
} }
// Our second query, this one will be handled with Postgres `GenericQuery` #[cfg(test)]
// which will serialize and persist our view after it is updated. It also mod tests {
// provides a `load` method to deserialize the view on request. use super::*;
//pub type BillQuery = GenericQuery<BillingDBPostgresAdapter, BillView, Bill>;
//pub type BillQuery = Query<dyn BillingDBPostgresAdapter, BillView, Bill>;
//#[cfg(test)] use postgres_es::PostgresCqrs;
//mod tests {
// use super::*; use crate::{
// billing::{
// use postgres_es::PostgresCqrs; application::services::{
// add_bill_service::AddBillServiceBuilder, update_bill_service::*,
// use crate::{ MockBillingServicesInterface,
// db::migrate::*, },
// billing::{ domain::{
// application::services::{ add_bill_command::*, commands::BillingCommand, store_aggregate::Store,
// add_category_service::tests::mock_add_category_service, add_customization_service::tests::mock_add_customization_service, add_line_item_service::tests::mock_add_line_item_service, add_product_service::tests::mock_add_product_service, add_bill_service::AddBillServiceBuilder, update_category_service::tests::mock_update_category_service, update_customization_service::tests::mock_update_customization_service, update_product_service::tests::mock_update_product_service, update_bill_service::tests::mock_update_bill_service, BillingServicesBuilder update_bill_command::*,
// }, },
// domain::{ },
// add_category_command::AddCategoryCommand, add_customization_command, db::migrate::*,
// add_product_command::tests::get_command, add_bill_command::AddBillCommand, tests::bdd::*,
// commands::BillingCommand, utils::uuid::tests::*,
// update_category_command::tests::get_update_category_command, };
// update_customization_command::tests::get_update_customization_command, use std::sync::Arc;
// update_product_command, update_bill_command::tests::get_update_bill_cmd,
// }, #[actix_rt::test]
// }, async fn pg_query_billing_bill_view() {
// tests::bdd::IS_NEVER_CALLED, let settings = crate::settings::tests::get_settings().await;
// utils::{random_string::GenerateRandomStringInterface, uuid::tests::UUID}, //let settings = crate::settings::Settings::new().unwrap();
// }; settings.create_db().await;
// use std::sync::Arc;
// let db = crate::db::sqlx_postgres::Postgres::init(&settings.database.url).await;
// #[actix_rt::test] db.migrate().await;
// async fn pg_query() { let db = BillingDBPostgresAdapter::new(db.pool.clone());
// let settings = crate::settings::tests::get_settings().await;
// //let settings = crate::settings::Settings::new().unwrap(); let simple_query = SimpleLoggingQuery {};
// settings.create_db().await;
// let queries: Vec<Box<dyn Query<Bill>>> = vec![Box::new(simple_query), Box::new(db.clone())];
// let db = crate::db::sqlx_postgres::Postgres::init(&settings.database.url).await;
// db.migrate().await; let mut mock_services = MockBillingServicesInterface::new();
// let db = BillingDBPostgresAdapter::new(db.pool.clone());
// let store = Store::default();
// let simple_query = SimpleLoggingQuery {}; crate::billing::adapters::output::db::postgres::store_id_exists::tests::create_dummy_store_record(&store, &db).await;
//
// let queries: Vec<Box<dyn Query<Bill>>> = let db2 = db.clone();
// vec![Box::new(simple_query), Box::new(db.clone())]; mock_services
// .expect_add_bill()
// let services = BillingServicesBuilder::default() .times(IS_CALLED_ONLY_ONCE.unwrap())
// .add_bill(Arc::new( .returning(move || {
// AddBillServiceBuilder::default() Arc::new(
// .db_bill_id_exists(Arc::new(db.clone())) AddBillServiceBuilder::default()
// .db_bill_name_exists(Arc::new(db.clone())) .db_bill_id_exists(Arc::new(db2.clone()))
// .get_uuid(Arc::new(crate::utils::uuid::GenerateUUID {})) .db_next_token_id(Arc::new(db2.clone()))
// .build() .build()
// .unwrap(), .unwrap(),
// )) )
// .add_category(mock_add_category_service( });
// IS_NEVER_CALLED,
// AddCategoryCommand::new("foo".into(), None, UUID, UUID).unwrap(), let db2 = db.clone();
// )) mock_services
// .add_product(mock_add_product_service(IS_NEVER_CALLED, get_command())) .expect_update_bill()
// .add_customization(mock_add_customization_service( .times(IS_CALLED_ONLY_ONCE.unwrap())
// IS_NEVER_CALLED, .returning(move || {
// add_customization_command::tests::get_command(), Arc::new(
// )) UpdateBillServiceBuilder::default()
// .update_product(mock_update_product_service( .db_bill_id_exists(Arc::new(db2.clone()))
// IS_NEVER_CALLED, .build()
// update_product_command::tests::get_command(), .unwrap(),
// )) )
// .update_customization(mock_update_customization_service( });
// IS_NEVER_CALLED,
// get_update_customization_command(), let (cqrs, bill_query): (
// )) Arc<PostgresCqrs<Bill>>,
// .update_category(mock_update_category_service( Arc<dyn ViewRepository<BillView, Bill>>,
// IS_NEVER_CALLED, ) = (
// get_update_category_command(), Arc::new(postgres_es::postgres_cqrs(
// )) db.pool.clone(),
// .update_bill(mock_update_bill_service( queries,
// IS_NEVER_CALLED, Arc::new(mock_services),
// get_update_bill_cmd(), )),
// )) Arc::new(db.clone()),
// .build() );
// .unwrap();
// let cmd = AddBillCommandBuilder::default()
// let (cqrs, _bill_query): ( .adding_by(UUID)
// Arc<PostgresCqrs<Bill>>, .bill_id(UUID)
// Arc<dyn ViewRepository<BillView, Bill>>, .store_id(*store.store_id())
// ) = ( .build()
// Arc::new(postgres_es::postgres_cqrs( .unwrap();
// db.pool.clone(),
// queries, cqrs.execute(
// Arc::new(services), &cmd.bill_id().to_string(),
// )), BillingCommand::AddBill(cmd.clone()),
// Arc::new(db.clone()), )
// ); .await
// .unwrap();
// let rand = crate::utils::random_string::GenerateRandomString {};
// let cmd = AddBillCommand::new(rand.get_random(10), None, UUID).unwrap(); let bill = bill_query
// cqrs.execute("", BillingCommand::AddBill(cmd.clone())) .load(&(*cmd.bill_id()).to_string())
// .await .await
// .unwrap(); .unwrap()
// .unwrap();
// settings.drop_db().await; let bill: Bill = bill.into();
// } assert_eq!(bill.store_id(), cmd.store_id());
//} assert_eq!(bill.bill_id(), cmd.bill_id());
assert!(!bill.deleted());
let update_bill_cmd = UpdateBillCommandBuilder::default()
.adding_by(UUID)
.store_id(*store.store_id())
.total_price(None)
.old_bill(bill.clone())
.build()
.unwrap();
cqrs.execute(
&cmd.bill_id().to_string(),
BillingCommand::UpdateBill(update_bill_cmd.clone()),
)
.await
.unwrap();
let bill = bill_query
.load(&(*cmd.bill_id()).to_string())
.await
.unwrap()
.unwrap();
let bill: Bill = bill.into();
assert_eq!(bill.store_id(), cmd.store_id());
assert_eq!(bill.bill_id(), update_bill_cmd.old_bill().bill_id());
assert_eq!(bill.total_price(), update_bill_cmd.total_price());
assert!(!bill.deleted());
settings.drop_db().await;
}
}

View file

@ -309,21 +309,19 @@ impl ViewRepository<LineItemView, LineItem> for BillingDBPostgresAdapter {
version = $1, version = $1,
product_name = $2, product_name = $2,
product_id = $3, product_id = $3,
line_item_id = $4, quantity_minor_unit = $4,
quantity_minor_unit = $5, quantity_minor_number = $5,
quantity_minor_number = $6, quantity_major_unit = $6,
quantity_major_unit = $7, quantity_major_number = $7,
quantity_major_number = $8, created_time = $8,
created_time = $9, bill_id = $9,
bill_id = $10, price_per_unit_minor = $10 ,
price_per_unit_minor = $11 , price_per_unit_major = $11,
price_per_unit_major = $12, price_per_unit_currency = $12,
price_per_unit_currency = $13, deleted = $13;",
deleted = $14;",
version, version,
view.product_name, view.product_name,
view.product_id, view.product_id,
view.line_item_id,
view.quantity_minor_unit, view.quantity_minor_unit,
view.quantity_minor_number, view.quantity_minor_number,
view.quantity_major_unit, view.quantity_major_unit,
@ -364,3 +362,215 @@ impl Query<LineItem> for BillingDBPostgresAdapter {
self.update_view(view, view_context).await.unwrap(); self.update_view(view, view_context).await.unwrap();
} }
} }
#[cfg(test)]
mod tests {
use super::*;
use postgres_es::PostgresCqrs;
use crate::{
billing::{
application::services::{
add_line_item_service::AddLineItemServiceBuilder, delete_line_item_service::*,
update_line_item_service::*, MockBillingServicesInterface,
},
domain::{
add_line_item_command::*, bill_aggregate::Bill, commands::BillingCommand,
delete_line_item_command::DeleteLineItemCommandBuilder,
update_line_item_command::*,
},
},
db::migrate::*,
tests::bdd::*,
types::quantity::*,
utils::{
random_string::GenerateRandomStringInterface,
uuid::{tests::UUID, *},
},
};
use std::sync::Arc;
#[actix_rt::test]
async fn pg_query_billing_line_item_view() {
let settings = crate::settings::tests::get_settings().await;
//let settings = crate::settings::Settings::new().unwrap();
settings.create_db().await;
let db = crate::db::sqlx_postgres::Postgres::init(&settings.database.url).await;
db.migrate().await;
let db = BillingDBPostgresAdapter::new(db.pool.clone());
let queries: Vec<Box<dyn Query<LineItem>>> = vec![Box::new(db.clone())];
let mut mock_services = MockBillingServicesInterface::new();
let bill = Bill::default();
crate::billing::adapters::output::db::postgres::bill_id_exists::tests::create_dummy_bill(
&bill, &db,
)
.await;
let db2 = db.clone();
mock_services
.expect_add_line_item()
.times(IS_CALLED_ONLY_ONCE.unwrap())
.returning(move || {
Arc::new(
AddLineItemServiceBuilder::default()
.db_line_item_id_exists(Arc::new(db2.clone()))
.db_bill_id_exists(Arc::new(db2.clone()))
.build()
.unwrap(),
)
});
let db2 = db.clone();
mock_services
.expect_update_line_item()
.times(IS_CALLED_ONLY_ONCE.unwrap())
.returning(move || {
Arc::new(
UpdateLineItemServiceBuilder::default()
.db_line_item_id_exists(Arc::new(db2.clone()))
.db_bill_id_exists(Arc::new(db2.clone()))
.build()
.unwrap(),
)
});
let db2 = db.clone();
mock_services
.expect_delete_line_item()
.times(IS_CALLED_ONLY_ONCE.unwrap())
.returning(move || {
Arc::new(
DeleteLineItemServiceBuilder::default()
.db_line_item_id_exists(Arc::new(db2.clone()))
.build()
.unwrap(),
)
});
let (cqrs, line_item_query): (
Arc<PostgresCqrs<LineItem>>,
Arc<dyn ViewRepository<LineItemView, LineItem>>,
) = (
Arc::new(postgres_es::postgres_cqrs(
db.pool.clone(),
queries,
Arc::new(mock_services),
)),
Arc::new(db.clone()),
);
let rand = crate::utils::random_string::GenerateRandomString {};
let uuid = GenerateUUID {};
let line_item_id = uuid.get_uuid();
let cmd = AddLineItemCommandBuilder::default()
.product_name(rand.get_random(10))
.adding_by(UUID)
.price_per_unit(Price::default())
.quantity(Quantity::get_quantity())
.product_id(UUID)
.bill_id(*bill.bill_id())
.line_item_id(line_item_id)
.build()
.unwrap();
cqrs.execute(
&cmd.line_item_id().to_string(),
BillingCommand::AddLineItem(cmd.clone()),
)
.await
.unwrap();
let line_item = line_item_query
.load(&(*cmd.line_item_id()).to_string())
.await
.unwrap()
.unwrap();
let line_item: LineItem = line_item.into();
assert_eq!(line_item.line_item_id(), cmd.line_item_id());
assert_eq!(line_item.product_name(), cmd.product_name());
assert_eq!(line_item.product_id(), cmd.product_id());
assert_eq!(line_item.quantity(), cmd.quantity());
assert!(!line_item.deleted());
let update_line_item_cmd = UnvalidatedUpdateLineItemCommandBuilder::default()
.product_name(rand.get_random(10))
.adding_by(UUID)
.quantity(Quantity::get_quantity())
.product_id(UUID)
.bill_id(*bill.bill_id())
.old_line_item(line_item.clone())
.price_per_unit(Price::default())
.build()
.unwrap()
.validate()
.unwrap();
cqrs.execute(
&cmd.line_item_id().to_string(),
BillingCommand::UpdateLineItem(update_line_item_cmd.clone()),
)
.await
.unwrap();
let line_item = line_item_query
.load(&(*cmd.line_item_id()).to_string())
.await
.unwrap()
.unwrap();
let line_item: LineItem = line_item.into();
assert_eq!(
line_item.line_item_id(),
update_line_item_cmd.old_line_item().line_item_id()
);
assert_eq!(
line_item.product_name(),
update_line_item_cmd.product_name()
);
assert_eq!(line_item.product_id(), update_line_item_cmd.product_id());
assert_eq!(line_item.quantity(), update_line_item_cmd.quantity());
assert!(!line_item.deleted());
// delete
let delete_line_item_cmd = DeleteLineItemCommandBuilder::default()
.line_item(line_item.clone())
.adding_by(UUID)
.build()
.unwrap();
cqrs.execute(
&cmd.line_item_id().to_string(),
BillingCommand::DeleteLineItem(delete_line_item_cmd.clone()),
)
.await
.unwrap();
let deleted_line_item = line_item_query
.load(&(*cmd.line_item_id()).to_string())
.await
.unwrap()
.unwrap();
let deleted_line_item: LineItem = deleted_line_item.into();
assert_eq!(
deleted_line_item.line_item_id(),
delete_line_item_cmd.line_item().line_item_id()
);
assert_eq!(
deleted_line_item.product_name(),
delete_line_item_cmd.line_item().product_name()
);
assert_eq!(
deleted_line_item.product_id(),
delete_line_item_cmd.line_item().product_id()
);
assert_eq!(
deleted_line_item.quantity(),
delete_line_item_cmd.line_item().quantity()
);
assert!(deleted_line_item.deleted());
settings.drop_db().await;
}
}

View file

@ -45,7 +45,7 @@ pub mod tests {
VALUES ($1, $2, $3, $4, $5 ,$6);", VALUES ($1, $2, $3, $4, $5 ,$6);",
1, 1,
s.name(), s.name(),
s.address().as_ref().unwrap(), s.address().as_ref().map(|s| s.as_str()),
s.store_id(), s.store_id(),
s.owner(), s.owner(),
false false

View file

@ -11,7 +11,7 @@ use uuid::Uuid;
use super::errors::*; use super::errors::*;
use super::BillingDBPostgresAdapter; use super::BillingDBPostgresAdapter;
use crate::billing::domain::events::BillingEvent; use crate::billing::domain::events::BillingEvent;
use crate::billing::domain::store_aggregate::Store; use crate::billing::domain::store_aggregate::*;
use crate::utils::parse_aggregate_id::parse_aggregate_id; use crate::utils::parse_aggregate_id::parse_aggregate_id;
pub const NEW_STORE_NON_UUID: &str = "billing_new_store_non_uuid-asdfa"; pub const NEW_STORE_NON_UUID: &str = "billing_new_store_non_uuid-asdfa";
@ -27,6 +27,19 @@ pub struct StoreView {
deleted: bool, deleted: bool,
} }
impl From<StoreView> for Store {
fn from(value: StoreView) -> Self {
StoreBuilder::default()
.name(value.name)
.address(value.address)
.store_id(value.store_id)
.owner(value.owner)
.deleted(value.deleted)
.build()
.unwrap()
}
}
// This updates the view with events as they are committed. // This updates the view with events as they are committed.
// The logic should be minimal here, e.g., don't calculate the account balance, // The logic should be minimal here, e.g., don't calculate the account balance,
// design the events to carry the balance information instead. // design the events to carry the balance information instead.
@ -156,13 +169,11 @@ impl ViewRepository<StoreView, Store> for BillingDBPostgresAdapter {
version = $1, version = $1,
name = $2, name = $2,
address = $3, address = $3,
store_id = $4, owner = $4,
owner = $5, deleted = $5;",
deleted = $6;",
version, version,
view.name, view.name,
view.address, view.address,
view.store_id,
view.owner, view.owner,
view.deleted, view.deleted,
) )
@ -205,108 +216,138 @@ impl Query<Store> for BillingDBPostgresAdapter {
} }
} }
// Our second query, this one will be handled with Postgres `GenericQuery` #[cfg(test)]
// which will serialize and persist our view after it is updated. It also mod tests {
// provides a `load` method to deserialize the view on request. use super::*;
//pub type StoreQuery = GenericQuery<BillingDBPostgresAdapter, StoreView, Store>;
//pub type StoreQuery = Query<dyn BillingDBPostgresAdapter, StoreView, Store>;
//#[cfg(test)] use postgres_es::PostgresCqrs;
//mod tests {
// use super::*; use crate::{
// billing::{
// use postgres_es::PostgresCqrs; application::services::{
// add_store_service::AddStoreServiceBuilder, update_store_service::*,
// use crate::{ MockBillingServicesInterface,
// db::migrate::*, },
// billing::{ domain::add_store_command::*,
// application::services::{ domain::commands::BillingCommand,
// add_category_service::tests::mock_add_category_service, add_customization_service::tests::mock_add_customization_service, add_line_item_service::tests::mock_add_line_item_service, add_product_service::tests::mock_add_product_service, add_store_service::AddStoreServiceBuilder, update_category_service::tests::mock_update_category_service, update_customization_service::tests::mock_update_customization_service, update_product_service::tests::mock_update_product_service, update_store_service::tests::mock_update_store_service, BillingServicesBuilder domain::update_store_command::*,
// }, },
// domain::{ db::migrate::*,
// add_category_command::AddCategoryCommand, add_customization_command, tests::bdd::*,
// add_product_command::tests::get_command, add_store_command::AddStoreCommand, utils::{random_string::GenerateRandomStringInterface, uuid::tests::UUID},
// commands::BillingCommand, };
// update_category_command::tests::get_update_category_command, use std::sync::Arc;
// update_customization_command::tests::get_update_customization_command,
// update_product_command, update_store_command::tests::get_update_store_cmd, #[actix_rt::test]
// }, async fn pg_query_billing_store_view() {
// }, let settings = crate::settings::tests::get_settings().await;
// tests::bdd::IS_NEVER_CALLED, //let settings = crate::settings::Settings::new().unwrap();
// utils::{random_string::GenerateRandomStringInterface, uuid::tests::UUID}, settings.create_db().await;
// };
// use std::sync::Arc; let db = crate::db::sqlx_postgres::Postgres::init(&settings.database.url).await;
// db.migrate().await;
// #[actix_rt::test] let db = BillingDBPostgresAdapter::new(db.pool.clone());
// async fn pg_query() {
// let settings = crate::settings::tests::get_settings().await; let simple_query = SimpleLoggingQuery {};
// //let settings = crate::settings::Settings::new().unwrap();
// settings.create_db().await; let queries: Vec<Box<dyn Query<Store>>> =
// vec![Box::new(simple_query), Box::new(db.clone())];
// let db = crate::db::sqlx_postgres::Postgres::init(&settings.database.url).await;
// db.migrate().await; let mut mock_services = MockBillingServicesInterface::new();
// let db = BillingDBPostgresAdapter::new(db.pool.clone());
// let db2 = db.clone();
// let simple_query = SimpleLoggingQuery {}; mock_services
// .expect_add_store()
// let queries: Vec<Box<dyn Query<Store>>> = .times(IS_CALLED_ONLY_ONCE.unwrap())
// vec![Box::new(simple_query), Box::new(db.clone())]; .returning(move || {
// Arc::new(
// let services = BillingServicesBuilder::default() AddStoreServiceBuilder::default()
// .add_store(Arc::new( .db_store_id_exists(Arc::new(db2.clone()))
// AddStoreServiceBuilder::default() .db_store_name_exists(Arc::new(db2.clone()))
// .db_store_id_exists(Arc::new(db.clone())) .build()
// .db_store_name_exists(Arc::new(db.clone())) .unwrap(),
// .get_uuid(Arc::new(crate::utils::uuid::GenerateUUID {})) )
// .build() });
// .unwrap(),
// )) let db2 = db.clone();
// .add_category(mock_add_category_service( mock_services
// IS_NEVER_CALLED, .expect_update_store()
// AddCategoryCommand::new("foo".into(), None, UUID, UUID).unwrap(), .times(IS_CALLED_ONLY_ONCE.unwrap())
// )) .returning(move || {
// .add_product(mock_add_product_service(IS_NEVER_CALLED, get_command())) Arc::new(
// .add_customization(mock_add_customization_service( UpdateStoreServiceBuilder::default()
// IS_NEVER_CALLED, .db_store_id_exists(Arc::new(db2.clone()))
// add_customization_command::tests::get_command(), .db_store_name_exists(Arc::new(db2.clone()))
// )) .build()
// .update_product(mock_update_product_service( .unwrap(),
// IS_NEVER_CALLED, )
// update_product_command::tests::get_command(), });
// ))
// .update_customization(mock_update_customization_service( let (cqrs, store_query): (
// IS_NEVER_CALLED, Arc<PostgresCqrs<Store>>,
// get_update_customization_command(), Arc<dyn ViewRepository<StoreView, Store>>,
// )) ) = (
// .update_category(mock_update_category_service( Arc::new(postgres_es::postgres_cqrs(
// IS_NEVER_CALLED, db.pool.clone(),
// get_update_category_command(), queries,
// )) Arc::new(mock_services),
// .update_store(mock_update_store_service( )),
// IS_NEVER_CALLED, Arc::new(db.clone()),
// get_update_store_cmd(), );
// ))
// .build() let rand = crate::utils::random_string::GenerateRandomString {};
// .unwrap(); let cmd = AddStoreCommandBuilder::default()
// .name(rand.get_random(10))
// let (cqrs, _store_query): ( .address(None)
// Arc<PostgresCqrs<Store>>, .owner(UUID)
// Arc<dyn ViewRepository<StoreView, Store>>, .store_id(UUID)
// ) = ( .build()
// Arc::new(postgres_es::postgres_cqrs( .unwrap();
// db.pool.clone(), cqrs.execute(
// queries, &cmd.store_id().to_string(),
// Arc::new(services), BillingCommand::AddStore(cmd.clone()),
// )), )
// Arc::new(db.clone()), .await
// ); .unwrap();
//
// let rand = crate::utils::random_string::GenerateRandomString {}; let store = store_query
// let cmd = AddStoreCommand::new(rand.get_random(10), None, UUID).unwrap(); .load(&(*cmd.store_id()).to_string())
// cqrs.execute("", BillingCommand::AddStore(cmd.clone())) .await
// .await .unwrap()
// .unwrap(); .unwrap();
// let store: Store = store.into();
// settings.drop_db().await; assert_eq!(store.name(), cmd.name());
// } assert_eq!(store.address(), cmd.address());
//} assert_eq!(store.owner(), cmd.owner());
assert_eq!(store.store_id(), cmd.store_id());
assert!(!store.deleted());
let update_store_cmd = UpdateStoreCommand::new(
rand.get_random(10),
Some(rand.get_random(10)),
UUID,
store,
UUID,
)
.unwrap();
cqrs.execute(
&cmd.store_id().to_string(),
BillingCommand::UpdateStore(update_store_cmd.clone()),
)
.await
.unwrap();
let store = store_query
.load(&(*cmd.store_id()).to_string())
.await
.unwrap()
.unwrap();
let store: Store = store.into();
assert_eq!(store.name(), update_store_cmd.name());
assert_eq!(store.address(), update_store_cmd.address());
assert_eq!(store.owner(), update_store_cmd.owner());
assert_eq!(store.store_id(), update_store_cmd.old_store().store_id());
assert!(!store.deleted());
settings.drop_db().await;
}
}

View file

@ -17,7 +17,6 @@ use crate::billing::{
bill_aggregate::*, bill_aggregate::*,
}, },
}; };
use crate::utils::uuid::*;
#[automock] #[automock]
#[async_trait::async_trait] #[async_trait::async_trait]
@ -31,27 +30,19 @@ pub type AddBillServiceObj = Arc<dyn AddBillUseCase>;
pub struct AddBillService { pub struct AddBillService {
db_bill_id_exists: BillIDExistsDBPortObj, db_bill_id_exists: BillIDExistsDBPortObj,
db_next_token_id: NextTokenIDDBPortObj, db_next_token_id: NextTokenIDDBPortObj,
get_uuid: GetUUIDInterfaceObj,
} }
#[async_trait::async_trait] #[async_trait::async_trait]
impl AddBillUseCase for AddBillService { impl AddBillUseCase for AddBillService {
async fn add_bill(&self, cmd: AddBillCommand) -> BillingResult<BillAddedEvent> { async fn add_bill(&self, cmd: AddBillCommand) -> BillingResult<BillAddedEvent> {
let mut bill_id = self.get_uuid.get_uuid(); if self.db_bill_id_exists.bill_id_exists(cmd.bill_id()).await? {
return Err(BillingError::DuplicateBillID);
loop {
if self.db_bill_id_exists.bill_id_exists(&bill_id).await? {
bill_id = self.get_uuid.get_uuid();
continue;
} else {
break;
}
} }
let token_number = self.db_next_token_id.next_token_id(cmd.store_id()).await?; let token_number = self.db_next_token_id.next_token_id(cmd.store_id()).await?;
let bill = BillBuilder::default() let bill = BillBuilder::default()
.bill_id(bill_id) .bill_id(*cmd.bill_id())
.token_number(token_number) .token_number(token_number)
.created_time(cmd.created_time().clone()) .created_time(cmd.created_time().clone())
.store_id(*cmd.store_id()) .store_id(*cmd.store_id())
@ -80,7 +71,7 @@ pub mod tests {
let mut m = MockAddBillUseCase::new(); let mut m = MockAddBillUseCase::new();
let bill = BillBuilder::default() let bill = BillBuilder::default()
.bill_id(UUID) .bill_id(*cmd.bill_id())
.token_number(1) .token_number(1)
.total_price(None) .total_price(None)
.created_time(cmd.created_time().clone()) .created_time(cmd.created_time().clone())
@ -113,7 +104,6 @@ pub mod tests {
let s = AddBillServiceBuilder::default() let s = AddBillServiceBuilder::default()
.db_bill_id_exists(mock_bill_id_exists_db_port_false(IS_CALLED_ONLY_ONCE)) .db_bill_id_exists(mock_bill_id_exists_db_port_false(IS_CALLED_ONLY_ONCE))
.db_next_token_id(mock_next_token_id_db_port(IS_CALLED_ONLY_ONCE)) .db_next_token_id(mock_next_token_id_db_port(IS_CALLED_ONLY_ONCE))
.get_uuid(mock_get_uuid(IS_CALLED_ONLY_ONCE))
.build() .build()
.unwrap(); .unwrap();

View file

@ -15,7 +15,6 @@ use crate::billing::{
application::port::output::db::line_item_id_exists::*, application::port::output::db::line_item_id_exists::*,
domain::{add_line_item_command::*, line_item_added_event::*, line_item_aggregate::*}, domain::{add_line_item_command::*, line_item_added_event::*, line_item_aggregate::*},
}; };
use crate::utils::uuid::*;
#[automock] #[automock]
#[async_trait::async_trait] #[async_trait::async_trait]
@ -29,7 +28,6 @@ pub type AddLineItemServiceObj = Arc<dyn AddLineItemUseCase>;
pub struct AddLineItemService { pub struct AddLineItemService {
db_line_item_id_exists: LineItemIDExistsDBPortObj, db_line_item_id_exists: LineItemIDExistsDBPortObj,
db_bill_id_exists: BillIDExistsDBPortObj, db_bill_id_exists: BillIDExistsDBPortObj,
get_uuid: GetUUIDInterfaceObj,
} }
#[async_trait::async_trait] #[async_trait::async_trait]
@ -39,19 +37,12 @@ impl AddLineItemUseCase for AddLineItemService {
return Err(BillingError::BillIDNotFound); return Err(BillingError::BillIDNotFound);
} }
let mut line_item_id = self.get_uuid.get_uuid(); if self
.db_line_item_id_exists
loop { .line_item_id_exists(cmd.line_item_id())
if self .await?
.db_line_item_id_exists {
.line_item_id_exists(&line_item_id) return Err(BillingError::DuplicateLineItemID);
.await?
{
line_item_id = self.get_uuid.get_uuid();
continue;
} else {
break;
}
} }
let line_item = LineItemBuilder::default() let line_item = LineItemBuilder::default()
@ -59,7 +50,7 @@ impl AddLineItemUseCase for AddLineItemService {
.product_name(cmd.product_name().into()) .product_name(cmd.product_name().into())
.product_id(*cmd.product_id()) .product_id(*cmd.product_id())
.bill_id(*cmd.bill_id()) .bill_id(*cmd.bill_id())
.line_item_id(line_item_id) .line_item_id(*cmd.line_item_id())
.quantity(cmd.quantity().clone()) .quantity(cmd.quantity().clone())
.price_per_unit(cmd.price_per_unit().clone()) .price_per_unit(cmd.price_per_unit().clone())
.deleted(false) .deleted(false)
@ -79,8 +70,7 @@ pub mod tests {
use super::*; use super::*;
use crate::billing::domain::line_item_added_event::tests::get_added_line_item_event_from_command; use crate::billing::domain::line_item_added_event::tests::get_added_line_item_event_from_command;
use crate::utils::uuid::tests::UUID; use crate::tests::bdd::*;
use crate::{tests::bdd::*, utils::uuid::tests::mock_get_uuid};
pub fn mock_add_line_item_service( pub fn mock_add_line_item_service(
times: Option<usize>, times: Option<usize>,
@ -107,7 +97,6 @@ pub mod tests {
let s = AddLineItemServiceBuilder::default() let s = AddLineItemServiceBuilder::default()
.db_line_item_id_exists(mock_line_item_id_exists_db_port_false(IS_CALLED_ONLY_ONCE)) .db_line_item_id_exists(mock_line_item_id_exists_db_port_false(IS_CALLED_ONLY_ONCE))
.db_bill_id_exists(mock_bill_id_exists_db_port_true(IS_CALLED_ONLY_ONCE)) .db_bill_id_exists(mock_bill_id_exists_db_port_true(IS_CALLED_ONLY_ONCE))
.get_uuid(mock_get_uuid(IS_CALLED_ONLY_ONCE))
.build() .build()
.unwrap(); .unwrap();
@ -129,7 +118,6 @@ pub mod tests {
let s = AddLineItemServiceBuilder::default() let s = AddLineItemServiceBuilder::default()
.db_line_item_id_exists(mock_line_item_id_exists_db_port_false(IS_NEVER_CALLED)) .db_line_item_id_exists(mock_line_item_id_exists_db_port_false(IS_NEVER_CALLED))
.db_bill_id_exists(mock_bill_id_exists_db_port_false(IS_CALLED_ONLY_ONCE)) .db_bill_id_exists(mock_bill_id_exists_db_port_false(IS_CALLED_ONLY_ONCE))
.get_uuid(mock_get_uuid(IS_NEVER_CALLED))
.build() .build()
.unwrap(); .unwrap();

View file

@ -12,12 +12,11 @@ use super::errors::*;
use crate::billing::{ use crate::billing::{
application::port::output::db::{store_id_exists::*, store_name_exists::*}, application::port::output::db::{store_id_exists::*, store_name_exists::*},
domain::{ domain::{
add_store_command::AddStoreCommand, add_store_command::*,
store_added_event::{StoreAddedEvent, StoreAddedEventBuilder}, store_added_event::{StoreAddedEvent, StoreAddedEventBuilder},
store_aggregate::*, store_aggregate::*,
}, },
}; };
use crate::utils::uuid::*;
#[automock] #[automock]
#[async_trait::async_trait] #[async_trait::async_trait]
@ -31,28 +30,24 @@ pub type AddStoreServiceObj = Arc<dyn AddStoreUseCase>;
pub struct AddStoreService { pub struct AddStoreService {
db_store_id_exists: StoreIDExistsDBPortObj, db_store_id_exists: StoreIDExistsDBPortObj,
db_store_name_exists: StoreNameExistsDBPortObj, db_store_name_exists: StoreNameExistsDBPortObj,
get_uuid: GetUUIDInterfaceObj,
} }
#[async_trait::async_trait] #[async_trait::async_trait]
impl AddStoreUseCase for AddStoreService { impl AddStoreUseCase for AddStoreService {
async fn add_store(&self, cmd: AddStoreCommand) -> BillingResult<StoreAddedEvent> { async fn add_store(&self, cmd: AddStoreCommand) -> BillingResult<StoreAddedEvent> {
let mut store_id = self.get_uuid.get_uuid(); if self
.db_store_id_exists
loop { .store_id_exists(cmd.store_id())
if self.db_store_id_exists.store_id_exists(&store_id).await? { .await?
store_id = self.get_uuid.get_uuid(); {
continue; return Err(BillingError::DuplicateStoreID);
} else {
break;
}
} }
let store = StoreBuilder::default() let store = StoreBuilder::default()
.name(cmd.name().into()) .name(cmd.name().into())
.address(cmd.address().as_ref().map(|s| s.to_string())) .address(cmd.address().as_ref().map(|s| s.to_string()))
.owner(*cmd.owner()) .owner(*cmd.owner())
.store_id(store_id) .store_id(*cmd.store_id())
.build() .build()
.unwrap(); .unwrap();
@ -64,7 +59,7 @@ impl AddStoreUseCase for AddStoreService {
.name(store.name().into()) .name(store.name().into())
.address(store.address().as_ref().map(|s| s.to_string())) .address(store.address().as_ref().map(|s| s.to_string()))
.owner(*cmd.owner()) .owner(*cmd.owner())
.store_id(store_id) .store_id(*cmd.store_id())
.build() .build()
.unwrap()) .unwrap())
} }
@ -87,7 +82,7 @@ pub mod tests {
.name(cmd.name().into()) .name(cmd.name().into())
.address(cmd.address().as_ref().map(|s| s.to_string())) .address(cmd.address().as_ref().map(|s| s.to_string()))
.owner(*cmd.owner()) .owner(*cmd.owner())
.store_id(UUID) .store_id(*cmd.store_id())
.build() .build()
.unwrap(); .unwrap();
@ -108,13 +103,17 @@ pub mod tests {
let address = "bar"; let address = "bar";
let owner = UUID; let owner = UUID;
// address = None let cmd = AddStoreCommandBuilder::default()
let cmd = AddStoreCommand::new(name.into(), Some(address.into()), owner).unwrap(); .name(name.into())
.address(Some(address.into()))
.owner(owner)
.store_id(UUID)
.build()
.unwrap();
let s = AddStoreServiceBuilder::default() let s = AddStoreServiceBuilder::default()
.db_store_id_exists(mock_store_id_exists_db_port_false(IS_CALLED_ONLY_ONCE)) .db_store_id_exists(mock_store_id_exists_db_port_false(IS_CALLED_ONLY_ONCE))
.db_store_name_exists(mock_store_name_exists_db_port_false(IS_CALLED_ONLY_ONCE)) .db_store_name_exists(mock_store_name_exists_db_port_false(IS_CALLED_ONLY_ONCE))
.get_uuid(mock_get_uuid(IS_CALLED_ONLY_ONCE))
.build() .build()
.unwrap(); .unwrap();
@ -122,7 +121,7 @@ pub mod tests {
assert_eq!(res.name(), cmd.name()); assert_eq!(res.name(), cmd.name());
assert_eq!(res.address(), cmd.address()); assert_eq!(res.address(), cmd.address());
assert_eq!(res.owner(), cmd.owner()); assert_eq!(res.owner(), cmd.owner());
assert_eq!(res.store_id(), &UUID); assert_eq!(res.store_id(), cmd.store_id());
} }
#[actix_rt::test] #[actix_rt::test]
@ -131,13 +130,17 @@ pub mod tests {
let address = "bar"; let address = "bar";
let owner = UUID; let owner = UUID;
// address = None let cmd = AddStoreCommandBuilder::default()
let cmd = AddStoreCommand::new(name.into(), Some(address.into()), owner).unwrap(); .name(name.into())
.address(Some(address.into()))
.owner(owner)
.store_id(UUID)
.build()
.unwrap();
let s = AddStoreServiceBuilder::default() let s = AddStoreServiceBuilder::default()
.db_store_id_exists(mock_store_id_exists_db_port_false(IS_CALLED_ONLY_ONCE)) .db_store_id_exists(mock_store_id_exists_db_port_false(IS_CALLED_ONLY_ONCE))
.db_store_name_exists(mock_store_name_exists_db_port_true(IS_CALLED_ONLY_ONCE)) .db_store_name_exists(mock_store_name_exists_db_port_true(IS_CALLED_ONLY_ONCE))
.get_uuid(mock_get_uuid(IS_CALLED_ONLY_ONCE))
.build() .build()
.unwrap(); .unwrap();

View file

@ -15,6 +15,9 @@ pub enum BillingError {
BillIDNotFound, BillIDNotFound,
InternalError, InternalError,
DuplicateStoreName, DuplicateStoreName,
DuplicateBillID,
DuplicateLineItemID,
DuplicateStoreID,
StoreIDNotFound, StoreIDNotFound,
LineItemIDNotFound, LineItemIDNotFound,
} }
@ -22,21 +25,12 @@ pub enum BillingError {
impl From<BillingDBError> for BillingError { impl From<BillingDBError> for BillingError {
fn from(value: BillingDBError) -> Self { fn from(value: BillingDBError) -> Self {
match value { match value {
BillingDBError::DuplicateBillID => { BillingDBError::DuplicateBillID => Self::DuplicateBillID,
error!("DuplicateBillID");
Self::InternalError
}
BillingDBError::DuplicateStoreName => Self::DuplicateStoreName, BillingDBError::DuplicateStoreName => Self::DuplicateStoreName,
BillingDBError::DuplicateStoreID => { BillingDBError::DuplicateStoreID => Self::DuplicateStoreID,
error!("DuplicateStoreID");
Self::InternalError
}
BillingDBError::StoreIDNotFound => BillingError::StoreIDNotFound, BillingDBError::StoreIDNotFound => BillingError::StoreIDNotFound,
BillingDBError::InternalError => BillingError::InternalError, BillingDBError::InternalError => BillingError::InternalError,
BillingDBError::DuplicateLineItemID => { BillingDBError::DuplicateLineItemID => Self::DuplicateLineItemID,
error!("DuplicateLineItemID");
Self::InternalError
}
BillingDBError::LineItemIDNotFound => BillingError::LineItemIDNotFound, BillingDBError::LineItemIDNotFound => BillingError::LineItemIDNotFound,
} }
} }

View file

@ -4,14 +4,10 @@
use derive_builder::Builder; use derive_builder::Builder;
use derive_getters::Getters; use derive_getters::Getters;
use derive_more::{Display, Error};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use time::OffsetDateTime; use time::OffsetDateTime;
use uuid::Uuid; use uuid::Uuid;
use crate::types::{currency::*, quantity::*};
use crate::utils::string::empty_string_err;
#[derive( #[derive(
Clone, Debug, Serialize, Deserialize, Eq, PartialEq, Ord, PartialOrd, Getters, Builder, Clone, Debug, Serialize, Deserialize, Eq, PartialEq, Ord, PartialOrd, Getters, Builder,
)] )]
@ -21,6 +17,7 @@ pub struct AddBillCommand {
#[builder(default = "OffsetDateTime::now_utc()")] #[builder(default = "OffsetDateTime::now_utc()")]
created_time: OffsetDateTime, created_time: OffsetDateTime,
bill_id: Uuid,
store_id: Uuid, store_id: Uuid,
} }
@ -41,6 +38,7 @@ mod tests {
.adding_by(adding_by) .adding_by(adding_by)
.created_time(datetime!(1970-01-01 0:00 UTC)) .created_time(datetime!(1970-01-01 0:00 UTC))
.store_id(store_id) .store_id(store_id)
.bill_id(UUID)
.build() .build()
.unwrap() .unwrap()
} }
@ -54,6 +52,7 @@ mod tests {
let cmd = AddBillCommandBuilder::default() let cmd = AddBillCommandBuilder::default()
.adding_by(adding_by) .adding_by(adding_by)
.store_id(store_id) .store_id(store_id)
.bill_id(UUID)
.build() .build()
.unwrap(); .unwrap();

View file

@ -19,55 +19,42 @@ pub enum AddLineItemCommandError {
} }
#[derive( #[derive(
Clone, Debug, Serialize, Deserialize, Eq, PartialEq, Ord, PartialOrd, Getters, Builder, Clone, Debug, Builder, Serialize, Deserialize, Eq, PartialEq, Ord, PartialOrd, Getters,
)] )]
pub struct UnvalidatedAddLineItemCommand { #[builder(build_fn(validate = "Self::validate"))]
adding_by: Uuid, pub struct AddLineItemCommand {
#[builder(default = "OffsetDateTime::now_utc()")] #[builder(default = "OffsetDateTime::now_utc()")]
created_time: OffsetDateTime, created_time: OffsetDateTime,
#[builder(setter(custom))]
product_name: String, product_name: String,
product_id: Uuid, product_id: Uuid,
bill_id: Uuid, bill_id: Uuid,
quantity: Quantity, line_item_id: Uuid,
price_per_unit: Price,
}
impl UnvalidatedAddLineItemCommand {
pub fn validate(self) -> Result<AddLineItemCommand, AddLineItemCommandError> {
let product_name = empty_string_err(
self.product_name,
AddLineItemCommandError::ProductNameIsEmpty,
)?;
if self.quantity.is_empty() {
return Err(AddLineItemCommandError::QuantityIsEmpty);
}
Ok(AddLineItemCommand {
created_time: self.created_time,
product_name,
product_id: self.product_id,
bill_id: self.bill_id,
quantity: self.quantity,
adding_by: self.adding_by,
price_per_unit: self.price_per_unit,
})
}
}
#[derive(Clone, Debug, Serialize, Deserialize, Eq, PartialEq, Ord, PartialOrd, Getters)]
pub struct AddLineItemCommand {
created_time: OffsetDateTime,
product_name: String,
product_id: Uuid,
bill_id: Uuid,
quantity: Quantity, quantity: Quantity,
price_per_unit: Price, price_per_unit: Price,
adding_by: Uuid, adding_by: Uuid,
} }
impl AddLineItemCommandBuilder {
pub fn product_name(&mut self, product_name: String) -> &mut Self {
self.product_name = Some(product_name.trim().to_owned());
self
}
fn validate(&self) -> Result<(), String> {
let product_name = self.product_name.as_ref().unwrap().trim().to_owned();
if product_name.is_empty() {
return Err(AddLineItemCommandError::ProductNameIsEmpty.to_string());
}
if self.quantity.as_ref().unwrap().is_empty() {
return Err(AddLineItemCommandError::QuantityIsEmpty.to_string());
}
Ok(())
}
}
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use time::macros::datetime; use time::macros::datetime;
@ -84,7 +71,7 @@ mod tests {
let adding_by = UUID; let adding_by = UUID;
let quantity = Quantity::get_quantity(); let quantity = Quantity::get_quantity();
UnvalidatedAddLineItemCommandBuilder::default() AddLineItemCommandBuilder::default()
.product_name(product_name.into()) .product_name(product_name.into())
.adding_by(adding_by) .adding_by(adding_by)
.created_time(datetime!(1970-01-01 0:00 UTC)) .created_time(datetime!(1970-01-01 0:00 UTC))
@ -92,10 +79,9 @@ mod tests {
.price_per_unit(Price::default()) .price_per_unit(Price::default())
.product_id(product_id) .product_id(product_id)
.bill_id(bill_id) .bill_id(bill_id)
.line_item_id(UUID)
.build() .build()
.unwrap() .unwrap()
.validate()
.unwrap()
} }
} }
@ -107,16 +93,15 @@ mod tests {
let adding_by = UUID; let adding_by = UUID;
let quantity = Quantity::get_quantity(); let quantity = Quantity::get_quantity();
let cmd = UnvalidatedAddLineItemCommandBuilder::default() let cmd = AddLineItemCommandBuilder::default()
.product_name(product_name.into()) .product_name(product_name.into())
.adding_by(adding_by) .adding_by(adding_by)
.price_per_unit(Price::default()) .price_per_unit(Price::default())
.quantity(quantity.clone()) .quantity(quantity.clone())
.product_id(product_id) .product_id(product_id)
.bill_id(bill_id) .bill_id(bill_id)
.line_item_id(UUID)
.build() .build()
.unwrap()
.validate()
.unwrap(); .unwrap();
assert_eq!(cmd.quantity(), &quantity); assert_eq!(cmd.quantity(), &quantity);
@ -133,19 +118,16 @@ mod tests {
let adding_by = UUID; let adding_by = UUID;
let quantity = Quantity::get_quantity(); let quantity = Quantity::get_quantity();
assert_eq!( assert!(AddLineItemCommandBuilder::default()
UnvalidatedAddLineItemCommandBuilder::default() .product_name(product_name.into())
.product_name(product_name.into()) .adding_by(adding_by)
.adding_by(adding_by) .quantity(quantity.clone())
.quantity(quantity.clone()) .price_per_unit(Price::default())
.price_per_unit(Price::default()) .product_id(product_id)
.product_id(product_id) .line_item_id(UUID)
.bill_id(bill_id) .bill_id(bill_id)
.build() .build()
.unwrap() .is_err());
.validate(),
Err(AddLineItemCommandError::ProductNameIsEmpty)
);
} }
#[test] #[test]
@ -157,18 +139,14 @@ mod tests {
// minor = 0; major = 0; // minor = 0; major = 0;
let quantity = Quantity::default(); let quantity = Quantity::default();
assert_eq!( assert!(AddLineItemCommandBuilder::default()
UnvalidatedAddLineItemCommandBuilder::default() .product_name(product_name.into())
.product_name(product_name.into()) .adding_by(adding_by)
.adding_by(adding_by) .quantity(quantity.clone())
.quantity(quantity.clone()) .product_id(product_id)
.product_id(product_id) .bill_id(bill_id)
.bill_id(bill_id) .price_per_unit(Price::default())
.price_per_unit(Price::default()) .build()
.build() .is_err());
.unwrap()
.validate(),
Err(AddLineItemCommandError::QuantityIsEmpty)
);
} }
} }

View file

@ -1,7 +1,91 @@
//// SPDX-FileCopyrightText: 2024 Aravinth Manivannan <realaravinth@batsense.net>
////
//// SPDX-License-Identifier: AGPL-3.0-or-later
//
//use derive_getters::Getters;
//use derive_more::{Display, Error};
//use serde::{Deserialize, Serialize};
//use uuid::Uuid;
//
//#[derive(Debug, Error, Display, Clone, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)]
//pub enum AddStoreCommandError {
// NameIsEmpty,
//}
//
//#[derive(Clone, Debug, Serialize, Deserialize, Eq, PartialEq, Ord, PartialOrd, Getters)]
//pub struct AddStoreCommand {
// name: String,
// address: Option<String>,
// owner: Uuid,
//}
//
//impl AddStoreCommand {
// pub fn new(
// name: String,
// address: Option<String>,
// owner: Uuid,
// ) -> Result<Self, AddStoreCommandError> {
// let address: Option<String> = if let Some(address) = address {
// let address = address.trim();
// if address.is_empty() {
// None
// } else {
// Some(address.to_owned())
// }
// } else {
// None
// };
//
// let name = name.trim().to_owned();
// if name.is_empty() {
// return Err(AddStoreCommandError::NameIsEmpty);
// }
//
// Ok(Self {
// name,
// address,
// owner,
// })
// }
//}
//
//#[cfg(test)]
//mod tests {
// use crate::utils::uuid::tests::UUID;
//
// use super::*;
//
// #[test]
// fn test_cmd() {
// let name = "foo";
// let address = "bar";
// let owner = UUID;
//
// // address = None
// let cmd = AddStoreCommand::new(name.into(), None, owner).unwrap();
// assert_eq!(cmd.name(), name);
// assert_eq!(cmd.address(), &None);
// assert_eq!(cmd.owner(), &owner);
//
// // address = Some
// let cmd = AddStoreCommand::new(name.into(), Some(address.into()), owner).unwrap();
// assert_eq!(cmd.name(), name);
// assert_eq!(cmd.address(), &Some(address.to_owned()));
// assert_eq!(cmd.owner(), &owner);
//
// // AddStoreCommandError::NameIsEmpty
// assert_eq!(
// AddStoreCommand::new("".into(), Some(address.into()), owner),
// Err(AddStoreCommandError::NameIsEmpty)
// )
// }
//}
// SPDX-FileCopyrightText: 2024 Aravinth Manivannan <realaravinth@batsense.net> // SPDX-FileCopyrightText: 2024 Aravinth Manivannan <realaravinth@batsense.net>
// //
// SPDX-License-Identifier: AGPL-3.0-or-later // SPDX-License-Identifier: AGPL-3.0-or-later
use derive_builder::Builder;
use derive_getters::Getters; use derive_getters::Getters;
use derive_more::{Display, Error}; use derive_more::{Display, Error};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
@ -12,46 +96,52 @@ pub enum AddStoreCommandError {
NameIsEmpty, NameIsEmpty,
} }
#[derive(Clone, Debug, Serialize, Deserialize, Eq, PartialEq, Ord, PartialOrd, Getters)] #[derive(
Clone, Builder, Debug, Serialize, Deserialize, Eq, PartialEq, Ord, PartialOrd, Getters,
)]
#[builder(build_fn(validate = "Self::validate"))]
pub struct AddStoreCommand { pub struct AddStoreCommand {
#[builder(setter(custom))]
name: String, name: String,
#[builder(setter(custom))]
address: Option<String>, address: Option<String>,
store_id: Uuid,
owner: Uuid, owner: Uuid,
} }
impl AddStoreCommand { impl AddStoreCommandBuilder {
pub fn new( pub fn address(&mut self, address: Option<String>) -> &mut Self {
name: String, self.address = if let Some(address) = address {
address: Option<String>,
owner: Uuid,
) -> Result<Self, AddStoreCommandError> {
let address: Option<String> = if let Some(address) = address {
let address = address.trim(); let address = address.trim();
if address.is_empty() { if address.is_empty() {
None Some(None)
} else { } else {
Some(address.to_owned()) Some(Some(address.to_owned()))
} }
} else { } else {
None Some(None)
}; };
self
}
let name = name.trim().to_owned(); pub fn name(&mut self, name: String) -> &mut Self {
self.name = Some(name.trim().to_owned());
self
}
fn validate(&self) -> Result<(), String> {
let name = self.name.as_ref().unwrap().trim().to_owned();
if name.is_empty() { if name.is_empty() {
return Err(AddStoreCommandError::NameIsEmpty); return Err(AddStoreCommandError::NameIsEmpty.to_string());
} }
Ok(())
Ok(Self {
name,
address,
owner,
})
} }
} }
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use crate::utils::uuid::tests::UUID; use crate::tests::bdd::*;
use crate::utils::uuid::tests::*;
use super::*; use super::*;
@ -62,21 +152,41 @@ mod tests {
let owner = UUID; let owner = UUID;
// address = None // address = None
let cmd = AddStoreCommand::new(name.into(), None, owner).unwrap(); let cmd = AddStoreCommandBuilder::default()
.name(name.into())
.address(None)
.owner(owner)
.store_id(UUID)
.build()
.unwrap();
// let cmd = AddStoreCommand::new(name.into(), None, owner, UUID).unwrap();
assert_eq!(cmd.name(), name); assert_eq!(cmd.name(), name);
assert_eq!(cmd.address(), &None); assert_eq!(cmd.address(), &None);
assert_eq!(cmd.owner(), &owner); assert_eq!(cmd.owner(), &owner);
assert_eq!(*cmd.store_id(), UUID);
// address = Some // address = Some
let cmd = AddStoreCommand::new(name.into(), Some(address.into()), owner).unwrap(); let cmd = AddStoreCommandBuilder::default()
.name(name.into())
.address(Some(address.into()))
.owner(owner)
.store_id(UUID)
.build()
.unwrap();
// let cmd = AddStoreCommand::new(name.into(), Some(address.into()), owner, UUID).unwrap();
assert_eq!(cmd.name(), name); assert_eq!(cmd.name(), name);
assert_eq!(cmd.address(), &Some(address.to_owned())); assert_eq!(cmd.address(), &Some(address.to_owned()));
assert_eq!(cmd.owner(), &owner); assert_eq!(cmd.owner(), &owner);
assert_eq!(*cmd.store_id(), UUID);
// AddStoreCommandError::NameIsEmpty // AddStoreCommandError::NameIsEmpty
assert_eq!(
AddStoreCommand::new("".into(), Some(address.into()), owner), assert!(AddStoreCommandBuilder::default()
Err(AddStoreCommandError::NameIsEmpty) .name("".into())
) .address(Some(address.into()))
.owner(owner)
.store_id(UUID)
.build()
.is_err())
} }
} }

View file

@ -85,7 +85,7 @@ pub mod tests {
.quantity(cmd.quantity().clone()) .quantity(cmd.quantity().clone())
.bill_id(*cmd.bill_id()) .bill_id(*cmd.bill_id())
.price_per_unit(cmd.price_per_unit().clone()) .price_per_unit(cmd.price_per_unit().clone())
.line_item_id(UUID) .line_item_id(*cmd.line_item_id())
.build() .build()
.unwrap() .unwrap()
} }

View file

@ -113,7 +113,13 @@ mod tests {
.unwrap(); .unwrap();
let expected = BillingEvent::StoreAdded(expected); let expected = BillingEvent::StoreAdded(expected);
let cmd = AddStoreCommand::new(name.into(), address.clone(), owner).unwrap(); let cmd = AddStoreCommandBuilder::default()
.name(name.into())
.address(address.clone())
.owner(owner)
.store_id(UUID)
.build()
.unwrap();
let mut services = MockBillingServicesInterface::new(); let mut services = MockBillingServicesInterface::new();
services services

View file

@ -21,7 +21,6 @@ pub struct UpdateBillCommand {
created_time: OffsetDateTime, created_time: OffsetDateTime,
store_id: Uuid, store_id: Uuid,
token_number: usize,
total_price: Option<Price>, total_price: Option<Price>,
old_bill: Bill, old_bill: Bill,
@ -45,7 +44,6 @@ mod tests {
.adding_by(adding_by) .adding_by(adding_by)
.store_id(store_id) .store_id(store_id)
.total_price(None) .total_price(None)
.token_number(1)
.old_bill(Bill::get_bill()) .old_bill(Bill::get_bill())
.build() .build()
.unwrap() .unwrap()
@ -62,7 +60,6 @@ mod tests {
.adding_by(adding_by) .adding_by(adding_by)
.store_id(store_id) .store_id(store_id)
.total_price(None) .total_price(None)
.token_number(1)
.old_bill(old_bill.clone()) .old_bill(old_bill.clone())
.build() .build()
.unwrap(); .unwrap();