Compare commits

..

No commits in common. "503920fc5fd60988aec01ac24dc92971042f618e" and "7d66d9d5b81bf729279a2ebb92491586c9490a1e" have entirely different histories.

25 changed files with 352 additions and 907 deletions

View file

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

View file

@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
"query": "UPDATE\n cqrs_inventory_category_query\n SET\n version = $1,\n name = $2,\n description = $3,\n store_id = $4,\n deleted = $5;",
"query": "UPDATE\n cqrs_inventory_category_query\n SET\n version = $1,\n name = $2,\n description = $3,\n category_id = $4,\n store_id = $5,\n deleted = $6;",
"describe": {
"columns": [],
"parameters": {
@ -9,10 +9,11 @@
"Text",
"Text",
"Uuid",
"Uuid",
"Bool"
]
},
"nullable": []
},
"hash": "c9bee14e15dae80b7af9b0fdca43a97b964024252bed2d0caeebee175acd55d9"
"hash": "14d111d7453b89f2346966a9fdd725d269ef36288ed5e7fe1f7ad452deaab0e6"
}

View file

@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
"query": "UPDATE\n cqrs_inventory_product_query\n SET\n version = $1,\n name = $2,\n description = $3,\n image = $4,\n category_id = $5,\n price_major = $6,\n price_minor = $7,\n price_currency = $8,\n sku_able = $9,\n quantity_minor_unit = $10,\n quantity_minor_number = $11,\n quantity_major_unit = $12,\n quantity_major_number = $13,\n deleted = $14;",
"query": "UPDATE\n cqrs_inventory_product_query\n SET\n version = $1,\n name = $2,\n description = $3,\n image = $4,\n product_id = $5,\n category_id = $6,\n price_major = $7,\n price_minor = $8,\n price_currency = $9,\n sku_able = $10,\n quantity_minor_unit = $11,\n quantity_minor_number = $12,\n quantity_major_unit = $13,\n quantity_major_number = $14,\n deleted = $15;",
"describe": {
"columns": [],
"parameters": {
@ -10,6 +10,7 @@
"Text",
"Text",
"Uuid",
"Uuid",
"Int4",
"Int4",
"Text",
@ -23,5 +24,5 @@
},
"nullable": []
},
"hash": "c358d3b79d35668b3475f29f5bf6767f7209a2443fd944420baf1e1cf5c51ccb"
"hash": "e2f9f291a20aac77851774ba8cd37325143a4d98e0980632f097c5885cc71094"
}

View file

@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
"query": "UPDATE\n cqrs_inventory_product_customizations_query\n SET\n version = $1,\n name = $2,\n product_id = $3,\n deleted = $4;",
"query": "UPDATE\n cqrs_inventory_product_customizations_query\n SET\n version = $1,\n name = $2,\n customization_id = $3,\n product_id = $4,\n deleted = $5;",
"describe": {
"columns": [],
"parameters": {
@ -8,10 +8,11 @@
"Int8",
"Text",
"Uuid",
"Uuid",
"Bool"
]
},
"nullable": []
},
"hash": "d46bb69f4e2afbae01ab08beb48a67b2cade64d9ebd47f3fc6143b057671cc1b"
"hash": "e88a5dae732c3f8180664f306b4bb1d21f97a2f1391860eb8714a52ef4439d81"
}

View file

@ -49,7 +49,7 @@ pub mod tests {
VALUES ($1, $2, $3, $4, $5, $6);",
1,
c.name(),
c.description().as_ref().map(|s| s.as_str()),
c.description().as_ref().unwrap(),
c.category_id(),
c.store_id(),
c.deleted().clone(),

View file

@ -10,7 +10,7 @@ use uuid::Uuid;
use super::errors::*;
use super::InventoryDBPostgresAdapter;
use crate::inventory::domain::category_aggregate::{Category, CategoryBuilder};
use crate::inventory::domain::category_aggregate::Category;
use crate::inventory::domain::events::InventoryEvent;
use crate::utils::parse_aggregate_id::parse_aggregate_id;
@ -27,19 +27,6 @@ pub struct CategoryView {
deleted: bool,
}
impl From<CategoryView> for Category {
fn from(v: CategoryView) -> Self {
CategoryBuilder::default()
.name(v.name)
.description(v.description)
.category_id(v.category_id)
.store_id(v.store_id)
.deleted(v.deleted)
.build()
.unwrap()
}
}
// This updates the view with events as they are committed.
// The logic should be minimal here, e.g., don't calculate the account balance,
// design the events to carry the balance information instead.
@ -177,11 +164,13 @@ impl ViewRepository<CategoryView, Category> for InventoryDBPostgresAdapter {
version = $1,
name = $2,
description = $3,
store_id = $4,
deleted = $5;",
category_id = $4,
store_id = $5,
deleted = $6;",
version,
view.name,
view.description,
view.category_id,
view.store_id,
view.deleted
)
@ -228,143 +217,3 @@ impl Query<Category> for InventoryDBPostgresAdapter {
self.update_view(view, view_context).await.unwrap();
}
}
#[cfg(test)]
mod tests {
use super::*;
use postgres_es::PostgresCqrs;
use crate::{
db::migrate::*,
inventory::{
application::services::{
add_category_service::*, update_category_service::*, MockInventoryServicesInterface,
},
domain::{
add_category_command::*, category_aggregate::*, commands::*, events::*,
store_aggregate::*, update_category_command::*,
},
},
tests::bdd::*,
utils::{random_string::GenerateRandomStringInterface, uuid::tests::UUID},
};
use std::sync::Arc;
#[actix_rt::test]
async fn pg_query_inventory_category_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 = InventoryDBPostgresAdapter::new(db.pool.clone());
let store = Store::default();
crate::inventory::adapters::output::db::postgres::store_id_exists::tests::create_dummy_store_record(&store, &db).await;
let queries: Vec<Box<dyn Query<Category>>> = vec![Box::new(db.clone())];
let mut mock_services = MockInventoryServicesInterface::new();
let db2 = Arc::new(db.clone());
mock_services
.expect_add_category()
.times(IS_CALLED_ONLY_ONCE.unwrap())
.returning(move || {
Arc::new(
AddCategoryServiceBuilder::default()
.db_store_id_exists(db2.clone())
.db_category_name_exists_for_store(db2.clone())
.db_category_id_exists(db2.clone())
.build()
.unwrap(),
)
});
let db2 = Arc::new(db.clone());
mock_services
.expect_update_category()
.times(IS_CALLED_ONLY_ONCE.unwrap())
.returning(move || {
Arc::new(
UpdateCategoryServiceBuilder::default()
.db_store_id_exists(db2.clone())
.db_category_name_exists_for_store(db2.clone())
.db_category_id_exists(db2.clone())
.build()
.unwrap(),
)
});
let (cqrs, category_query): (
Arc<PostgresCqrs<Category>>,
Arc<dyn ViewRepository<CategoryView, Category>>,
) = (
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 cmd = AddCategoryCommandBuilder::default()
.name(rand.get_random(10))
.description(None)
.store_id(*store.store_id())
.adding_by(UUID)
.category_id(UUID)
.build()
.unwrap();
cqrs.execute(
&cmd.category_id().to_string(),
InventoryCommand::AddCategory(cmd.clone()),
)
.await
.unwrap();
let category = category_query
.load(&(*cmd.category_id()).to_string())
.await
.unwrap()
.unwrap();
let category: Category = category.into();
assert_eq!(category.name(), cmd.name());
assert_eq!(category.description(), cmd.description());
assert_eq!(category.category_id(), cmd.category_id());
assert_eq!(category.store_id(), cmd.store_id());
assert!(!store.deleted());
let update_category_cmd = UpdateCategoryCommand::new(
rand.get_random(10),
Some(rand.get_random(10)),
category,
UUID,
)
.unwrap();
cqrs.execute(
&cmd.category_id().to_string(),
InventoryCommand::UpdateCategory(update_category_cmd.clone()),
)
.await
.unwrap();
let category = category_query
.load(&(*cmd.category_id()).to_string())
.await
.unwrap()
.unwrap();
let category: Category = category.into();
assert_eq!(category.name(), update_category_cmd.name());
assert_eq!(category.description(), update_category_cmd.description());
assert_eq!(category.category_id(), cmd.category_id());
assert_eq!(category.store_id(), cmd.store_id());
assert!(!category.deleted());
settings.drop_db().await;
}
}

View file

@ -187,10 +187,12 @@ impl ViewRepository<CustomizationView, Customization> for InventoryDBPostgresAda
SET
version = $1,
name = $2,
product_id = $3,
deleted = $4;",
customization_id = $3,
product_id = $4,
deleted = $5;",
version,
view.name,
view.customization_id,
view.product_id,
view.deleted,
)
@ -223,145 +225,3 @@ impl Query<Customization> for InventoryDBPostgresAdapter {
self.update_view(view, view_context).await.unwrap();
}
}
#[cfg(test)]
mod tests {
use super::*;
use postgres_es::PostgresCqrs;
use crate::{
db::migrate::*,
inventory::{
adapters::output::db::postgres::product_id_exists::tests::create_dummy_product_record,
application::services::{
add_customization_service::*, update_customization_service::*,
MockInventoryServicesInterface,
},
domain::{
add_customization_command::*,
commands::InventoryCommand,
product_aggregate::Product,
update_customization_command::{tests::get_update_customization_command, *},
},
},
tests::bdd::*,
utils::{random_string::GenerateRandomStringInterface, uuid::tests::UUID},
};
use std::sync::Arc;
#[actix_rt::test]
async fn pg_query_inventory_customization_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 = InventoryDBPostgresAdapter::new(db.pool.clone());
let product = Product::default();
create_dummy_product_record(&product, &db).await;
// let simple_query = super::store_view::SimpleLoggingQuery {};
let queries: Vec<Box<dyn Query<Customization>>> = vec![Box::new(db.clone())];
let mut mock_services = MockInventoryServicesInterface::new();
let db2 = db.clone();
mock_services
.expect_add_customization()
.times(IS_CALLED_ONLY_ONCE.unwrap())
.returning(move || {
Arc::new(
AddCustomizationServiceBuilder::default()
.db_product_id_exists(Arc::new(db2.clone()))
.db_customization_id_exists(Arc::new(db2.clone()))
.db_customization_name_exists_for_product(Arc::new(db2.clone()))
.build()
.unwrap(),
)
});
let db2 = Arc::new(db.clone());
mock_services
.expect_update_customization()
.times(IS_CALLED_ONLY_ONCE.unwrap())
.returning(move || {
Arc::new(
UpdateCustomizationServiceBuilder::default()
.db_product_id_exists(db2.clone())
.db_customization_name_exists_for_product(db2.clone())
.db_customization_id_exists(db2.clone())
.build()
.unwrap(),
)
});
let (cqrs, custmoization_query): (
Arc<PostgresCqrs<Customization>>,
Arc<dyn ViewRepository<CustomizationView, Customization>>,
) = (
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 cmd = AddCustomizationCommandBuilder::default()
.name(rand.get_random(10))
.product_id(product.product_id().clone())
.customization_id(UUID.clone())
.build()
.unwrap();
cqrs.execute(
&cmd.customization_id().to_string(),
InventoryCommand::AddCustomization(cmd.clone()),
)
.await
.unwrap();
let customization = custmoization_query
.load(&(*cmd.customization_id()).to_string())
.await
.unwrap()
.unwrap();
let customization: Customization = customization.into();
assert_eq!(customization.name(), cmd.name());
assert_eq!(customization.customization_id(), cmd.customization_id());
assert_eq!(customization.product_id(), cmd.product_id());
assert!(!customization.deleted());
let update_customization_command = UnvalidatedUpdateCustomizationCommandBuilder::default()
.name(rand.get_random(10))
.old_customization(customization.clone())
.adding_by(UUID.clone())
.build()
.unwrap()
.validate()
.unwrap();
cqrs.execute(
&cmd.customization_id().to_string(),
InventoryCommand::UpdateCustomization(update_customization_command.clone()),
)
.await
.unwrap();
let c = custmoization_query
.load(&(*cmd.customization_id()).to_string())
.await
.unwrap()
.unwrap();
let c: Customization = c.into();
assert_eq!(c.name(), update_customization_command.name());
assert_eq!(
update_customization_command.old_customization(),
&customization
);
assert!(!c.deleted());
settings.drop_db().await;
}
}

View file

@ -95,8 +95,8 @@ pub mod tests {
);",
1,
p.name(),
p.description().as_ref().map(|s| s.as_str()),
p.image().as_ref().map(|s| s.as_str()),
p.description().as_ref().unwrap(),
p.image().as_ref().unwrap(),
p.product_id(),
p.category_id(),
p.price().major().clone() as i32,

View file

@ -293,20 +293,22 @@ impl ViewRepository<ProductView, Product> for InventoryDBPostgresAdapter {
name = $2,
description = $3,
image = $4,
category_id = $5,
price_major = $6,
price_minor = $7,
price_currency = $8,
sku_able = $9,
quantity_minor_unit = $10,
quantity_minor_number = $11,
quantity_major_unit = $12,
quantity_major_number = $13,
deleted = $14;",
product_id = $5,
category_id = $6,
price_major = $7,
price_minor = $8,
price_currency = $9,
sku_able = $10,
quantity_minor_unit = $11,
quantity_minor_number = $12,
quantity_major_unit = $13,
quantity_major_number = $14,
deleted = $15;",
version,
view.name,
view.description,
view.image,
view.product_id,
view.category_id,
view.price_major,
view.price_minor,
@ -347,157 +349,3 @@ impl Query<Product> for InventoryDBPostgresAdapter {
self.update_view(view, view_context).await.unwrap();
}
}
#[cfg(test)]
mod tests {
use super::*;
use postgres_es::PostgresCqrs;
use crate::{
db::migrate::*,
inventory::{
application::{
port::output::full_text_search::add_product_to_store::*,
services::{
add_product_service::*, update_product_service::*,
MockInventoryServicesInterface,
},
},
domain::{
add_product_command::{tests::get_command, *},
category_aggregate::{Category, CategoryBuilder},
commands::*,
events::*,
product_aggregate::*,
store_aggregate::*,
update_product_command::{tests::get_command_with_product, *},
},
},
tests::bdd::*,
utils::{random_string::GenerateRandomStringInterface, uuid::tests::UUID},
};
use std::sync::Arc;
#[actix_rt::test]
async fn pg_query_inventory_product_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 = InventoryDBPostgresAdapter::new(db.pool.clone());
let store = Store::default();
crate::inventory::adapters::output::db::postgres::store_id_exists::tests::create_dummy_store_record(&store, &db).await;
let category = CategoryBuilder::default()
.name("fooooo_cat".into())
.description(None)
.store_id(*store.store_id())
.category_id(UUID)
.build()
.unwrap();
crate::inventory::adapters::output::db::postgres::category_name_exists_for_store::tests::create_dummy_category_record(&category, &db).await;
let queries: Vec<Box<dyn Query<Product>>> = vec![Box::new(db.clone())];
let mut mock_services = MockInventoryServicesInterface::new();
let db2 = Arc::new(db.clone());
mock_services
.expect_add_product()
.times(IS_CALLED_ONLY_ONCE.unwrap())
.returning(move || {
Arc::new(
AddProductServiceBuilder::default()
.db_product_name_exists_for_category(db2.clone())
.db_product_id_exists(db2.clone())
.db_get_category(db2.clone())
.db_category_id_exists(db2.clone())
.fts_add_product(mock_add_product_to_store_fts_port(IGNORE_CALL_COUNT))
.build()
.unwrap(),
)
});
let db2 = Arc::new(db.clone());
mock_services
.expect_update_product()
.times(IS_CALLED_ONLY_ONCE.unwrap())
.returning(move || {
Arc::new(
UpdateProductServiceBuilder::default()
.db_category_id_exists(db2.clone())
.db_product_name_exists_for_category(db2.clone())
.db_product_id_exists(db2.clone())
.build()
.unwrap(),
)
});
let (cqrs, product_query): (
Arc<PostgresCqrs<Product>>,
Arc<dyn ViewRepository<ProductView, Product>>,
) = (
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 cmd = get_command();
cqrs.execute(
&cmd.product_id().to_string(),
InventoryCommand::AddProduct(cmd.clone()),
)
.await
.unwrap();
let product = product_query
.load(&(*cmd.product_id()).to_string())
.await
.unwrap()
.unwrap();
let product: Product = product.into();
assert_eq!(product.name(), cmd.name());
assert_eq!(product.description(), cmd.description());
assert_eq!(product.image(), cmd.image());
assert_eq!(product.product_id(), cmd.product_id());
assert_eq!(product.quantity(), cmd.quantity());
assert_eq!(product.sku_able(), cmd.sku_able());
assert_eq!(product.price(), cmd.price());
assert!(!store.deleted());
let update_product_cmd = get_command_with_product(product.clone());
cqrs.execute(
&cmd.product_id().to_string(),
InventoryCommand::UpdateProduct(update_product_cmd.clone()),
)
.await
.unwrap();
let product = product_query
.load(&(*cmd.product_id()).to_string())
.await
.unwrap()
.unwrap();
let product: Product = product.into();
assert_eq!(product.name(), update_product_cmd.name());
assert_eq!(product.description(), update_product_cmd.description());
assert_eq!(product.image(), update_product_cmd.image());
assert_eq!(
product.product_id(),
update_product_cmd.old_product().product_id()
);
assert_eq!(product.quantity(), update_product_cmd.quantity());
assert_eq!(product.sku_able(), update_product_cmd.sku_able());
assert_eq!(product.price(), update_product_cmd.price());
assert!(!store.deleted());
settings.drop_db().await;
}
}

View file

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

View file

@ -11,7 +11,7 @@ use uuid::Uuid;
use super::errors::*;
use super::InventoryDBPostgresAdapter;
use crate::inventory::domain::events::InventoryEvent;
use crate::inventory::domain::store_aggregate::{Store, StoreBuilder};
use crate::inventory::domain::store_aggregate::Store;
use crate::utils::parse_aggregate_id::parse_aggregate_id;
pub const NEW_STORE_NON_UUID: &str = "new_store_non_uuid-asdfa";
@ -27,19 +27,6 @@ pub struct StoreView {
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.
// The logic should be minimal here, e.g., don't calculate the account balance,
// design the events to carry the balance information instead.
@ -169,11 +156,13 @@ impl ViewRepository<StoreView, Store> for InventoryDBPostgresAdapter {
version = $1,
name = $2,
address = $3,
owner = $4,
deleted = $5;",
store_id = $4,
owner = $5,
deleted = $6;",
version,
view.name,
view.address,
view.store_id,
view.owner,
view.deleted,
)
@ -203,21 +192,12 @@ impl Query<Store> for SimpleLoggingQuery {
#[async_trait]
impl Query<Store> for InventoryDBPostgresAdapter {
async fn dispatch(&self, aggregate_id: &str, events: &[EventEnvelope<Store>]) {
println!("Got store ID: {}", aggregate_id);
async fn dispatch(&self, store_id: &str, events: &[EventEnvelope<Store>]) {
let res = self
.load_with_context(&aggregate_id)
.load_with_context(store_id)
.await
.unwrap_or_else(|_| {
println!("generating default");
Some((
StoreView::default(),
ViewContext::new(aggregate_id.into(), 0),
))
});
.unwrap_or_else(|_| Some((StoreView::default(), ViewContext::new(store_id.into(), 0))));
let (mut view, view_context): (StoreView, ViewContext) = res.unwrap();
for event in events {
view.update(event);
}
@ -225,6 +205,12 @@ impl Query<Store> for InventoryDBPostgresAdapter {
}
}
// Our second query, this one will be handled with Postgres `GenericQuery`
// which will serialize and persist our view after it is updated. It also
// provides a `load` method to deserialize the view on request.
//pub type StoreQuery = GenericQuery<InventoryDBPostgresAdapter, StoreView, Store>;
//pub type StoreQuery = Query<dyn InventoryDBPostgresAdapter, StoreView, Store>;
#[cfg(test)]
mod tests {
use super::*;
@ -235,20 +221,31 @@ mod tests {
db::migrate::*,
inventory::{
application::services::{
add_store_service::AddStoreServiceBuilder, update_store_service::*,
MockInventoryServicesInterface,
add_category_service::tests::mock_add_category_service,
add_customization_service::tests::mock_add_customization_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, InventoryServicesBuilder,
},
domain::add_store_command::*,
domain::commands::InventoryCommand,
domain::update_store_command::*,
domain::{
add_category_command::AddCategoryCommand, add_customization_command,
add_product_command::tests::get_command, add_store_command::AddStoreCommand,
commands::InventoryCommand,
update_category_command::tests::get_update_category_command,
update_customization_command::tests::get_update_customization_command,
update_product_command, update_store_command::tests::get_update_store_cmd,
},
tests::bdd::*,
},
tests::bdd::IS_NEVER_CALLED,
utils::{random_string::GenerateRandomStringInterface, uuid::tests::UUID},
};
use std::sync::Arc;
#[actix_rt::test]
async fn pg_query_inventory_store_view() {
async fn pg_query() {
let settings = crate::settings::tests::get_settings().await;
//let settings = crate::settings::Settings::new().unwrap();
settings.create_db().await;
@ -262,101 +259,61 @@ mod tests {
let queries: Vec<Box<dyn Query<Store>>> =
vec![Box::new(simple_query), Box::new(db.clone())];
let mut mock_services = MockInventoryServicesInterface::new();
let db2 = db.clone();
mock_services
.expect_add_store()
.times(IS_CALLED_ONLY_ONCE.unwrap())
.returning(move || {
Arc::new(
let services = InventoryServicesBuilder::default()
.add_store(Arc::new(
AddStoreServiceBuilder::default()
.db_store_id_exists(Arc::new(db2.clone()))
.db_store_name_exists(Arc::new(db2.clone()))
.db_store_id_exists(Arc::new(db.clone()))
.db_store_name_exists(Arc::new(db.clone()))
.get_uuid(Arc::new(crate::utils::uuid::GenerateUUID {}))
.build()
.unwrap(),
)
});
let db2 = db.clone();
mock_services
.expect_update_store()
.times(IS_CALLED_ONLY_ONCE.unwrap())
.returning(move || {
Arc::new(
UpdateStoreServiceBuilder::default()
.db_store_id_exists(Arc::new(db2.clone()))
.db_store_name_exists(Arc::new(db2.clone()))
))
.add_category(mock_add_category_service(
IS_NEVER_CALLED,
AddCategoryCommand::new("foo".into(), None, UUID, UUID).unwrap(),
))
.add_product(mock_add_product_service(IS_NEVER_CALLED, get_command()))
.add_customization(mock_add_customization_service(
IS_NEVER_CALLED,
add_customization_command::tests::get_command(),
))
.update_product(mock_update_product_service(
IS_NEVER_CALLED,
update_product_command::tests::get_command(),
))
.update_customization(mock_update_customization_service(
IS_NEVER_CALLED,
get_update_customization_command(),
))
.update_category(mock_update_category_service(
IS_NEVER_CALLED,
get_update_category_command(),
))
.update_store(mock_update_store_service(
IS_NEVER_CALLED,
get_update_store_cmd(),
))
.build()
.unwrap(),
)
});
.unwrap();
let (cqrs, store_query): (
let (cqrs, _store_query): (
Arc<PostgresCqrs<Store>>,
Arc<dyn ViewRepository<StoreView, Store>>,
) = (
Arc::new(postgres_es::postgres_cqrs(
db.pool.clone(),
queries,
Arc::new(mock_services),
Arc::new(services),
)),
Arc::new(db.clone()),
);
let rand = crate::utils::random_string::GenerateRandomString {};
let cmd = AddStoreCommandBuilder::default()
.name(rand.get_random(10))
.address(None)
.owner(UUID)
.store_id(UUID)
.build()
.unwrap();
cqrs.execute(
&cmd.store_id().to_string(),
InventoryCommand::AddStore(cmd.clone()),
)
let cmd = AddStoreCommand::new(rand.get_random(10), None, UUID).unwrap();
cqrs.execute("", InventoryCommand::AddStore(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(), 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(),
InventoryCommand::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

@ -14,11 +14,12 @@ use crate::inventory::{
category_id_exists::*, category_name_exists_for_store::*, store_id_exists::*,
},
domain::{
add_category_command::*,
add_category_command::AddCategoryCommand,
category_added_event::{CategoryAddedEvent, CategoryAddedEventBuilder},
category_aggregate::*,
},
};
use crate::utils::uuid::*;
#[automock]
#[async_trait::async_trait]
@ -33,6 +34,7 @@ pub struct AddCategoryService {
db_store_id_exists: StoreIDExistsDBPortObj,
db_category_name_exists_for_store: CategoryNameExistsForStoreDBPortObj,
db_category_id_exists: CategoryIDExistsDBPortObj,
get_uuid: GetUUIDInterfaceObj,
}
#[async_trait::async_trait]
@ -46,19 +48,27 @@ impl AddCategoryUseCase for AddCategoryService {
return Err(InventoryError::StoreIDNotFound);
}
let mut category_id = self.get_uuid.get_uuid();
loop {
if self
.db_category_id_exists
.category_id_exists(cmd.category_id())
.category_id_exists(&category_id)
.await?
{
return Err(InventoryError::DuplicateCategoryID);
category_id = self.get_uuid.get_uuid();
continue;
} else {
break;
}
}
let category = CategoryBuilder::default()
.name(cmd.name().into())
.description(cmd.description().as_ref().map(|s| s.to_string()))
.store_id(*cmd.store_id())
.category_id(*cmd.category_id())
.category_id(category_id)
.build()
.unwrap();
@ -87,8 +97,8 @@ pub mod tests {
use uuid::Uuid;
use crate::tests::bdd::*;
use crate::utils::uuid::tests::UUID;
use crate::{tests::bdd::*, utils::uuid::tests::mock_get_uuid};
pub fn mock_add_category_service(
times: Option<usize>,
@ -101,7 +111,7 @@ pub mod tests {
.description(cmd.description().as_ref().map(|s| s.to_string()))
.added_by_user(*cmd.adding_by())
.store_id(*cmd.store_id())
.category_id(*cmd.category_id())
.category_id(UUID)
.build()
.unwrap();
@ -123,13 +133,8 @@ pub mod tests {
let user_id = UUID;
let store_id = Uuid::new_v4();
let cmd = AddCategoryCommandBuilder::default()
.name(name.into())
.description(Some(description.into()))
.store_id(store_id)
.adding_by(user_id)
.category_id(UUID)
.build()
// description = None
let cmd = AddCategoryCommand::new(name.into(), Some(description.into()), store_id, user_id)
.unwrap();
let s = AddCategoryServiceBuilder::default()
@ -138,6 +143,7 @@ pub mod tests {
IS_CALLED_ONLY_ONCE,
))
.db_category_id_exists(mock_category_id_exists_db_port_false(IS_CALLED_ONLY_ONCE))
.get_uuid(mock_get_uuid(IS_CALLED_ONLY_ONCE))
.build()
.unwrap();
@ -156,13 +162,8 @@ pub mod tests {
let user_id = UUID;
let store_id = Uuid::new_v4();
let cmd = AddCategoryCommandBuilder::default()
.name(name.into())
.description(Some(description.into()))
.store_id(store_id)
.adding_by(user_id)
.category_id(UUID)
.build()
// description = None
let cmd = AddCategoryCommand::new(name.into(), Some(description.into()), store_id, user_id)
.unwrap();
let s = AddCategoryServiceBuilder::default()
@ -171,6 +172,7 @@ pub mod tests {
IS_CALLED_ONLY_ONCE,
))
.db_category_id_exists(mock_category_id_exists_db_port_false(IS_CALLED_ONLY_ONCE))
.get_uuid(mock_get_uuid(IS_CALLED_ONLY_ONCE))
.build()
.unwrap();
@ -187,13 +189,8 @@ pub mod tests {
let user_id = UUID;
let store_id = Uuid::new_v4();
let cmd = AddCategoryCommandBuilder::default()
.name(name.into())
.description(Some(description.into()))
.store_id(store_id)
.adding_by(user_id)
.category_id(UUID)
.build()
// description = None
let cmd = AddCategoryCommand::new(name.into(), Some(description.into()), store_id, user_id)
.unwrap();
let s = AddCategoryServiceBuilder::default()
@ -202,6 +199,7 @@ pub mod tests {
IS_NEVER_CALLED,
))
.db_category_id_exists(mock_category_id_exists_db_port_false(IS_NEVER_CALLED))
.get_uuid(mock_get_uuid(IS_NEVER_CALLED))
.build()
.unwrap();

View file

@ -24,6 +24,7 @@ use crate::inventory::{
product_aggregate::*,
},
};
use crate::utils::uuid::*;
#[automock]
#[async_trait::async_trait]
@ -41,6 +42,7 @@ pub struct AddCustomizationService {
db_product_id_exists: ProductIDExistsDBPortObj,
db_customization_id_exists: CustomizationIDExistsDBPortObj,
db_customization_name_exists_for_product: CustomizationNameExistsForProductDBPortObj,
get_uuid: GetUUIDInterfaceObj,
}
#[async_trait::async_trait]
@ -57,19 +59,25 @@ impl AddCustomizationUseCase for AddCustomizationService {
return Err(InventoryError::ProductIDNotFound);
}
let mut customization_id = self.get_uuid.get_uuid();
loop {
if self
.db_customization_id_exists
.customization_id_exists(cmd.customization_id())
.customization_id_exists(&customization_id)
.await?
{
return Err(InventoryError::DuplicateCustomizationID);
customization_id = self.get_uuid.get_uuid();
continue;
} else {
break;
}
}
let customization = CustomizationBuilder::default()
.name(cmd.name().into())
.deleted(false)
.product_id(*cmd.product_id())
.customization_id(*cmd.customization_id())
.customization_id(customization_id)
.build()
.unwrap();
@ -93,9 +101,11 @@ pub mod tests {
use super::*;
use customization_added_event::tests::get_customization_added_event_from_cmd;
use uuid::Uuid;
use crate::inventory::domain::add_customization_command::tests::get_command;
use crate::tests::bdd::*;
use crate::utils::uuid::tests::UUID;
use crate::{tests::bdd::*, utils::uuid::tests::mock_get_uuid};
pub fn mock_add_customization_service(
times: Option<usize>,
@ -128,16 +138,12 @@ pub mod tests {
.db_customization_name_exists_for_product(
mock_customization_name_exists_for_product_db_port_false(IS_CALLED_ONLY_ONCE),
)
.get_uuid(mock_get_uuid(IS_CALLED_ONLY_ONCE))
.build()
.unwrap();
let res = s.add_customization(cmd.clone()).await.unwrap();
assert_eq!(res.customization().name(), cmd.name());
assert_eq!(res.customization().product_id(), cmd.product_id());
assert_eq!(
res.customization().customization_id(),
cmd.customization_id()
);
// assert_eq!(customization_added_events.len(), cmd.customizations().len());
}
@ -153,6 +159,7 @@ pub mod tests {
.db_customization_name_exists_for_product(
mock_customization_name_exists_for_product_db_port_true(IS_CALLED_ONLY_ONCE),
)
.get_uuid(mock_get_uuid(IS_CALLED_ONLY_ONCE))
.build()
.unwrap();
@ -172,6 +179,7 @@ pub mod tests {
.db_customization_name_exists_for_product(
mock_customization_name_exists_for_product_db_port_false(IS_NEVER_CALLED),
)
.get_uuid(mock_get_uuid(IS_NEVER_CALLED))
.build()
.unwrap();

View file

@ -23,6 +23,7 @@ use crate::inventory::{
product_aggregate::*,
},
};
use crate::utils::uuid::*;
#[automock]
#[async_trait::async_trait]
@ -39,6 +40,7 @@ pub struct AddProductService {
db_product_id_exists: ProductIDExistsDBPortObj,
db_get_category: GetCategoryDBPortObj,
fts_add_product: AddProductToStoreFTSPortObj,
get_uuid: GetUUIDInterfaceObj,
}
#[async_trait::async_trait]
@ -52,12 +54,19 @@ impl AddProductUseCase for AddProductService {
return Err(InventoryError::CategoryIDNotFound);
}
let mut product_id = self.get_uuid.get_uuid();
loop {
if self
.db_product_id_exists
.product_id_exists(cmd.product_id())
.product_id_exists(&product_id)
.await?
{
return Err(InventoryError::DuplicateProductID);
product_id = self.get_uuid.get_uuid();
continue;
} else {
break;
}
}
let product = ProductBuilder::default()
@ -68,7 +77,7 @@ impl AddProductUseCase for AddProductService {
.price(cmd.price().clone())
.category_id(*cmd.category_id())
.quantity(cmd.quantity().clone())
.product_id(*cmd.product_id())
.product_id(product_id)
.build()
.unwrap();
@ -110,8 +119,8 @@ pub mod tests {
use super::*;
use crate::inventory::domain::add_product_command::tests::get_command;
use crate::tests::bdd::*;
use crate::utils::uuid::tests::UUID;
use crate::{tests::bdd::*, utils::uuid::tests::mock_get_uuid};
pub fn mock_add_product_service(
times: Option<usize>,
@ -156,6 +165,7 @@ pub mod tests {
.db_get_category(mock_get_category_db_port(IS_CALLED_ONLY_ONCE))
.db_category_id_exists(mock_category_id_exists_db_port_true(IS_CALLED_ONLY_ONCE))
.fts_add_product(mock_add_product_to_store_fts_port(IS_CALLED_ONLY_ONCE))
.get_uuid(mock_get_uuid(IS_CALLED_ONLY_ONCE))
.build()
.unwrap();
@ -180,6 +190,7 @@ pub mod tests {
mock_product_name_exists_for_category_db_port_true(IS_CALLED_ONLY_ONCE),
)
.db_category_id_exists(mock_category_id_exists_db_port_true(IS_CALLED_ONLY_ONCE))
.get_uuid(mock_get_uuid(IS_CALLED_ONLY_ONCE))
.db_product_id_exists(mock_product_id_exists_db_port_false(IS_CALLED_ONLY_ONCE))
.db_get_category(mock_get_category_db_port(IS_NEVER_CALLED))
.fts_add_product(mock_add_product_to_store_fts_port(IS_NEVER_CALLED))
@ -204,6 +215,7 @@ pub mod tests {
.db_category_id_exists(mock_category_id_exists_db_port_false(IS_CALLED_ONLY_ONCE))
.db_get_category(mock_get_category_db_port(IS_NEVER_CALLED))
.fts_add_product(mock_add_product_to_store_fts_port(IS_NEVER_CALLED))
.get_uuid(mock_get_uuid(IS_NEVER_CALLED))
.build()
.unwrap();

View file

@ -12,11 +12,12 @@ use super::errors::*;
use crate::inventory::{
application::port::output::db::{store_id_exists::*, store_name_exists::*},
domain::{
add_store_command::*,
add_store_command::AddStoreCommand,
store_added_event::{StoreAddedEvent, StoreAddedEventBuilder},
store_aggregate::*,
},
};
use crate::utils::uuid::*;
#[automock]
#[async_trait::async_trait]
@ -30,24 +31,28 @@ pub type AddStoreServiceObj = Arc<dyn AddStoreUseCase>;
pub struct AddStoreService {
db_store_id_exists: StoreIDExistsDBPortObj,
db_store_name_exists: StoreNameExistsDBPortObj,
get_uuid: GetUUIDInterfaceObj,
}
#[async_trait::async_trait]
impl AddStoreUseCase for AddStoreService {
async fn add_store(&self, cmd: AddStoreCommand) -> InventoryResult<StoreAddedEvent> {
if self
.db_store_id_exists
.store_id_exists(cmd.store_id())
.await?
{
return Err(InventoryError::DuplicateStoreID);
let mut store_id = self.get_uuid.get_uuid();
loop {
if self.db_store_id_exists.store_id_exists(&store_id).await? {
store_id = self.get_uuid.get_uuid();
continue;
} else {
break;
}
}
let store = StoreBuilder::default()
.name(cmd.name().into())
.address(cmd.address().as_ref().map(|s| s.to_string()))
.owner(*cmd.owner())
.store_id(*cmd.store_id())
.store_id(store_id)
.build()
.unwrap();
@ -59,7 +64,7 @@ impl AddStoreUseCase for AddStoreService {
.name(store.name().into())
.address(store.address().as_ref().map(|s| s.to_string()))
.owner(*cmd.owner())
.store_id(*cmd.store_id())
.store_id(store_id)
.build()
.unwrap())
}
@ -104,17 +109,12 @@ pub mod tests {
let owner = UUID;
// address = None
let cmd = AddStoreCommandBuilder::default()
.name(name.into())
.address(None)
.owner(owner)
.store_id(UUID)
.build()
.unwrap();
let cmd = AddStoreCommand::new(name.into(), Some(address.into()), owner).unwrap();
let s = AddStoreServiceBuilder::default()
.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))
.get_uuid(mock_get_uuid(IS_CALLED_ONLY_ONCE))
.build()
.unwrap();
@ -132,17 +132,12 @@ pub mod tests {
let owner = UUID;
// address = None
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).unwrap();
let s = AddStoreServiceBuilder::default()
.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))
.get_uuid(mock_get_uuid(IS_CALLED_ONLY_ONCE))
.build()
.unwrap();

View file

@ -18,10 +18,6 @@ pub enum InventoryError {
DuplicateStoreName,
DuplicateProductName,
DuplicateCustomizationName,
DuplicateCustomizationID,
DuplicateStoreID,
DuplicateCategoryID,
DuplicateProductID,
ProductIDNotFound,
CategoryIDNotFound,
CustomizationIDNotFound,
@ -36,10 +32,22 @@ impl From<InventoryDBError> for InventoryError {
InventoryDBError::DuplicateStoreName => Self::DuplicateStoreName,
InventoryDBError::DuplicateProductName => Self::DuplicateProductName,
InventoryDBError::DuplicateCustomizationName => Self::DuplicateCustomizationName,
InventoryDBError::DuplicateStoreID => Self::DuplicateStoreID,
InventoryDBError::DuplicateProductID => Self::DuplicateProductID,
InventoryDBError::DuplicateCategoryID => Self::DuplicateCategoryID,
InventoryDBError::DuplicateCustomizationID => Self::DuplicateCustomizationID,
InventoryDBError::DuplicateStoreID => {
error!("DuplicateStoreID");
Self::InternalError
}
InventoryDBError::DuplicateProductID => {
error!("DuplicateProductID");
Self::InternalError
}
InventoryDBError::DuplicateCategoryID => {
error!("DuplicateCategoryID");
Self::InternalError
}
InventoryDBError::DuplicateCustomizationID => {
error!("DuplicateCustomizationID");
Self::InternalError
}
InventoryDBError::InternalError => Self::InternalError,
InventoryDBError::ProductIDNotFound => InventoryError::ProductIDNotFound,
InventoryDBError::CategoryIDNotFound => InventoryError::CategoryIDNotFound,

View file

@ -15,6 +15,7 @@ use crate::inventory::{
},
domain::{category_aggregate::*, category_updated_event::*, update_category_command::*},
};
use crate::utils::uuid::*;
#[automock]
#[async_trait::async_trait]

View file

@ -2,7 +2,6 @@
//
// SPDX-License-Identifier: AGPL-3.0-or-later
use derive_builder::Builder;
use derive_getters::Getters;
use derive_more::{Display, Error};
use serde::{Deserialize, Serialize};
@ -13,22 +12,21 @@ pub enum AddCategoryCommandError {
NameIsEmpty,
}
#[derive(
Clone, Debug, Builder, Serialize, Deserialize, Eq, PartialEq, Ord, PartialOrd, Getters,
)]
#[builder(build_fn(validate = "Self::validate"))]
#[derive(Clone, Debug, Serialize, Deserialize, Eq, PartialEq, Ord, PartialOrd, Getters)]
pub struct AddCategoryCommand {
#[builder(setter(custom))]
name: String,
#[builder(setter(custom))]
description: Option<String>,
store_id: Uuid,
category_id: Uuid,
adding_by: Uuid,
}
impl AddCategoryCommandBuilder {
pub fn description(&mut self, description: Option<String>) -> &mut Self {
impl AddCategoryCommand {
pub fn new(
name: String,
description: Option<String>,
store_id: Uuid,
adding_by: Uuid,
) -> Result<Self, AddCategoryCommandError> {
let description: Option<String> = if let Some(description) = description {
let description = description.trim();
if description.is_empty() {
@ -39,22 +37,18 @@ impl AddCategoryCommandBuilder {
} else {
None
};
self.description = Some(description);
self
}
pub fn name(&mut self, name: String) -> &mut Self {
let name = name.trim().to_owned();
self.name = Some(name);
self
if name.is_empty() {
return Err(AddCategoryCommandError::NameIsEmpty);
}
pub fn validate(&self) -> Result<(), String> {
if self.name.as_ref().unwrap().is_empty() {
return Err(AddCategoryCommandError::NameIsEmpty.to_string());
}
Ok(())
Ok(Self {
name,
store_id,
description,
adding_by,
})
}
}
@ -71,41 +65,26 @@ mod tests {
let adding_by = UUID;
let store_id = Uuid::new_v4();
let cmd = AddCategoryCommandBuilder::default()
.name(name.into())
.description(None)
.store_id(store_id)
.adding_by(adding_by)
.category_id(UUID)
.build()
.unwrap();
// description = None
let cmd = AddCategoryCommand::new(name.into(), None, store_id, adding_by).unwrap();
assert_eq!(cmd.name(), name);
assert_eq!(cmd.description(), &None);
assert_eq!(cmd.adding_by(), &adding_by);
assert_eq!(cmd.store_id(), &store_id);
let cmd = AddCategoryCommandBuilder::default()
.name(name.into())
.description(Some(description.into()))
.store_id(store_id)
.adding_by(adding_by)
.category_id(UUID)
.build()
// description = Some
let cmd =
AddCategoryCommand::new(name.into(), Some(description.into()), store_id, adding_by)
.unwrap();
assert_eq!(cmd.name(), name);
assert_eq!(cmd.description(), &Some(description.to_owned()));
assert_eq!(cmd.adding_by(), &adding_by);
assert_eq!(cmd.store_id(), &store_id);
// AddCategoryCommandError::NameIsEmpty
assert!(AddCategoryCommandBuilder::default()
.name("".into())
.description(Some(description.into()))
.store_id(store_id)
.adding_by(adding_by)
.category_id(UUID)
.build()
.is_err())
assert_eq!(
AddCategoryCommand::new("".into(), Some(description.into()), store_id, adding_by,),
Err(AddCategoryCommandError::NameIsEmpty)
)
}
}

View file

@ -16,26 +16,28 @@ pub enum AddCustomizationCommandError {
#[derive(
Clone, Debug, Serialize, Deserialize, Eq, PartialEq, Ord, PartialOrd, Getters, Builder,
)]
#[builder(build_fn(validate = "Self::validate"))]
pub struct AddCustomizationCommand {
#[builder(setter(custom))]
pub struct UnvalidatedAddCustomizationCommand {
name: String,
product_id: Uuid,
customization_id: Uuid,
}
impl AddCustomizationCommandBuilder {
pub fn name(&mut self, name: String) -> &mut Self {
self.name = Some(name.trim().to_owned());
self
#[derive(Clone, Debug, Serialize, Deserialize, Eq, PartialEq, Ord, PartialOrd, Getters)]
pub struct AddCustomizationCommand {
name: String,
product_id: Uuid,
}
fn validate(&self) -> Result<(), String> {
let name = self.name.as_ref().unwrap().trim().to_owned();
impl UnvalidatedAddCustomizationCommand {
pub fn validate(self) -> Result<AddCustomizationCommand, AddCustomizationCommandError> {
let name = self.name.trim().to_owned();
if name.is_empty() {
return Err(AddCustomizationCommandError::NameIsEmpty.to_string());
return Err(AddCustomizationCommandError::NameIsEmpty);
}
Ok(())
Ok(AddCustomizationCommand {
name,
product_id: self.product_id,
})
}
}
@ -46,12 +48,13 @@ pub mod tests {
use crate::utils::uuid::tests::UUID;
pub fn get_command() -> AddCustomizationCommand {
AddCustomizationCommandBuilder::default()
UnvalidatedAddCustomizationCommandBuilder::default()
.name("foo".into())
.product_id(UUID.clone())
.customization_id(UUID.clone())
.build()
.unwrap()
.validate()
.unwrap()
}
#[test]
@ -59,11 +62,12 @@ pub mod tests {
let name = "foo";
let product_id = UUID;
let cmd = AddCustomizationCommandBuilder::default()
let cmd = UnvalidatedAddCustomizationCommandBuilder::default()
.name(name.into())
.product_id(product_id.clone())
.customization_id(UUID.clone())
.build()
.unwrap()
.validate()
.unwrap();
assert_eq!(cmd.name(), name);
@ -74,11 +78,14 @@ pub mod tests {
fn test_cmd_name_is_empty() {
let product_id = UUID;
assert!(AddCustomizationCommandBuilder::default()
assert_eq!(
UnvalidatedAddCustomizationCommandBuilder::default()
.name("".into())
.product_id(product_id.clone())
.customization_id(UUID.clone())
.build()
.is_err(),);
.unwrap()
.validate(),
Err(AddCustomizationCommandError::NameIsEmpty)
);
}
}

View file

@ -17,17 +17,24 @@ pub enum AddProductCommandError {
}
#[derive(
Clone, Builder, Debug, Serialize, Deserialize, Eq, PartialEq, Ord, PartialOrd, Getters,
Clone, Debug, Serialize, Deserialize, Eq, PartialEq, Ord, PartialOrd, Getters, Builder,
)]
#[builder(build_fn(validate = "Self::validate"))]
pub struct AddProductCommand {
#[builder(setter(custom))]
pub struct UnvalidatedAddProductCommand {
name: String,
description: Option<String>,
image: Option<String>,
category_id: Uuid,
sku_able: bool,
quantity: Quantity,
price: Price,
adding_by: Uuid,
}
#[derive(Clone, Debug, Serialize, Deserialize, Eq, PartialEq, Ord, PartialOrd, Getters)]
pub struct AddProductCommand {
name: String,
#[builder(setter(custom))]
description: Option<String>,
#[builder(setter(custom))]
image: Option<String>,
product_id: Uuid,
category_id: Uuid,
sku_able: bool,
price: Price,
@ -35,9 +42,9 @@ pub struct AddProductCommand {
adding_by: Uuid,
}
impl AddProductCommandBuilder {
pub fn description(&mut self, description: Option<String>) -> &mut Self {
let description: Option<String> = if let Some(description) = description {
impl UnvalidatedAddProductCommand {
pub fn validate(self) -> Result<AddProductCommand, AddProductCommandError> {
let description: Option<String> = if let Some(description) = self.description {
let description = description.trim();
if description.is_empty() {
None
@ -47,12 +54,8 @@ impl AddProductCommandBuilder {
} else {
None
};
self.description = Some(description);
self
}
pub fn image(&mut self, image: Option<String>) -> &mut Self {
let image: Option<String> = if let Some(image) = image {
let image: Option<String> = if let Some(image) = self.image {
let image = image.trim();
if image.is_empty() {
None
@ -62,22 +65,22 @@ impl AddProductCommandBuilder {
} else {
None
};
self.image = Some(image);
self
let name = self.name.trim().to_owned();
if name.is_empty() {
return Err(AddProductCommandError::NameIsEmpty);
}
pub fn name(&mut self, name: String) -> &mut Self {
let name = name.trim().to_owned();
self.name = Some(name);
self
}
pub fn validate(&self) -> Result<(), String> {
if self.name.as_ref().unwrap().is_empty() {
return Err(AddProductCommandError::NameIsEmpty.to_string());
}
Ok(())
Ok(AddProductCommand {
name,
description,
image,
category_id: self.category_id,
sku_able: self.sku_able,
price: self.price,
quantity: self.quantity,
adding_by: self.adding_by,
})
}
}
@ -90,7 +93,7 @@ pub mod tests {
pub fn get_command() -> AddProductCommand {
let name = "foo";
let adding_by = UUID;
let category_id = UUID;
let category_id = Uuid::new_v4();
let sku_able = false;
let image = Some("image".to_string());
let description = Some("description".to_string());
@ -120,7 +123,7 @@ pub mod tests {
.build()
.unwrap();
AddProductCommandBuilder::default()
let cmd = UnvalidatedAddProductCommandBuilder::default()
.name(name.into())
.description(description.clone())
.image(image.clone())
@ -128,10 +131,11 @@ pub mod tests {
.adding_by(adding_by)
.quantity(quantity)
.sku_able(sku_able)
.product_id(UUID)
.price(price.clone())
.build()
.unwrap()
.unwrap();
cmd.validate().unwrap()
}
#[test]
@ -151,7 +155,7 @@ pub mod tests {
let quantity = Quantity::default();
// description = None
let cmd = AddProductCommandBuilder::default()
let cmd = UnvalidatedAddProductCommandBuilder::default()
.name(name.into())
.description(None)
.image(None)
@ -159,11 +163,12 @@ pub mod tests {
.adding_by(adding_by)
.quantity(quantity.clone())
.sku_able(sku_able)
.product_id(UUID)
.price(price.clone())
.build()
.unwrap();
let cmd = cmd.validate().unwrap();
assert_eq!(cmd.name(), name);
assert_eq!(cmd.description(), &None);
assert_eq!(cmd.adding_by(), &adding_by);
@ -191,19 +196,21 @@ pub mod tests {
let quantity = Quantity::default();
let cmd = AddProductCommandBuilder::default()
let cmd = UnvalidatedAddProductCommandBuilder::default()
.name(name.into())
.description(description.clone())
.image(image.clone())
.category_id(category_id)
.adding_by(adding_by)
.quantity(quantity.clone())
.adding_by(adding_by)
.sku_able(sku_able)
.product_id(UUID)
.price(price.clone())
// .customizations(customizations.clone())
.build()
.unwrap();
let cmd = cmd.validate().unwrap();
assert_eq!(cmd.name(), name);
assert_eq!(cmd.description(), &description);
assert_eq!(cmd.adding_by(), &adding_by);
@ -231,8 +238,7 @@ pub mod tests {
let quantity = Quantity::default();
// AddProductCommandError::NameIsEmpty
assert!(AddProductCommandBuilder::default()
let cmd = UnvalidatedAddProductCommandBuilder::default()
.name("".into())
.description(description.clone())
.image(image.clone())
@ -240,9 +246,11 @@ pub mod tests {
.adding_by(adding_by)
.quantity(quantity)
.sku_able(sku_able)
.product_id(UUID)
.price(price.clone())
.build()
.is_err());
.unwrap();
// AddProductCommandError::NameIsEmpty
assert_eq!(cmd.validate(), Err(AddProductCommandError::NameIsEmpty))
}
}

View file

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

View file

@ -107,14 +107,8 @@ mod aggregate_tests {
let store_id = Uuid::new_v4();
let category_id = UUID;
let cmd = AddCategoryCommandBuilder::default()
.name(name.into())
.description(description.clone())
.store_id(store_id)
.adding_by(adding_by)
.category_id(category_id)
.build()
.unwrap();
let cmd =
AddCategoryCommand::new(name.into(), description.clone(), store_id, adding_by).unwrap();
let expected = CategoryAddedEventBuilder::default()
.name(cmd.name().into())

View file

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

View file

@ -95,62 +95,13 @@ pub mod tests {
use crate::types::quantity::*;
use crate::utils::uuid::tests::UUID;
pub fn get_command_with_product(product: Product) -> UpdateProductCommand {
let name = "foobaaar";
let adding_by = UUID;
let category_id = UUID;
let sku_able = false;
let image = Some("imageeee".to_string());
let description = Some("descriptionnnn".to_string());
let price = PriceBuilder::default()
.minor(0)
.major(100)
.currency(Currency::INR)
.build()
.unwrap();
let quantity = QuantityBuilder::default()
.minor(
QuantityPartBuilder::default()
.number(0)
.unit(QuantityUnit::DiscreteNumber)
.build()
.unwrap(),
)
.major(
QuantityPartBuilder::default()
.number(1)
.unit(QuantityUnit::DiscreteNumber)
.build()
.unwrap(),
)
.build()
.unwrap();
let cmd = UnvalidatedUpdateProductCommandBuilder::default()
.name(name.into())
.description(description.clone())
.image(image.clone())
.category_id(category_id.clone())
.adding_by(adding_by.clone())
.quantity(quantity)
.sku_able(sku_able)
.price(price.clone())
.old_product(product)
.build()
.unwrap();
cmd.validate().unwrap()
}
pub fn get_command() -> UpdateProductCommand {
let name = "foobaaar";
let name = "foo";
let adding_by = UUID;
let category_id = UUID;
let category_id = Uuid::new_v4();
let sku_able = false;
let image = Some("imageeee".to_string());
let description = Some("descriptionnnn".to_string());
let image = Some("image".to_string());
let description = Some("description".to_string());
let price = PriceBuilder::default()
.minor(0)

View file

@ -158,7 +158,6 @@ pub mod tests {
let mut db_url = Url::parse(&settings.database.url).unwrap();
db_url.set_path(&GenerateRandomString.get_random(12));
settings.database.url = db_url.to_string();
println!("Test database URL: {}", settings.database.url);
settings.database.pool = 1;
settings