fix&feat: ordering: Aggregate creator provides ID #114

Merged
realaravinth merged 8 commits from ordering-fix-aggregate-id into master 2024-09-24 19:10:16 +05:30
14 changed files with 155 additions and 132 deletions
Showing only changes of commit eba2f7204c - Show all commits

View file

@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
"query": "SELECT \n customer_name,\n order_id,\n created_time,\n deleted\n FROM\n cqrs_ordering_order_query\n WHERE\n order_id = $1;",
"query": "SELECT \n customer_name,\n order_id,\n created_time,\n store_id,\n deleted\n FROM\n cqrs_ordering_order_query\n WHERE\n order_id = $1;",
"describe": {
"columns": [
{
@ -20,6 +20,11 @@
},
{
"ordinal": 3,
"name": "store_id",
"type_info": "Uuid"
},
{
"ordinal": 4,
"name": "deleted",
"type_info": "Bool"
}
@ -30,11 +35,12 @@
]
},
"nullable": [
true,
false,
false,
false,
false
]
},
"hash": "dbe1e41f04a81b2a504b9179911201ec52340d09d45041addd54eb349af82488"
"hash": "4f8a2294b40e4285fa6d4c7bcf648be7320f99002b9a9279981053a5062b0ed8"
}

View file

@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
"query": "INSERT INTO cqrs_ordering_order_query (\n version,\n customer_name,\n order_id,\n created_time,\n deleted\n\n ) VALUES (\n $1, $2, $3, $4, $5\n );",
"query": "INSERT INTO cqrs_ordering_order_query (\n version,\n customer_name,\n order_id,\n created_time,\n store_id,\n deleted\n\n ) VALUES (\n $1, $2, $3, $4, $5, $6\n );",
"describe": {
"columns": [],
"parameters": {
@ -9,10 +9,11 @@
"Text",
"Uuid",
"Timestamptz",
"Uuid",
"Bool"
]
},
"nullable": []
},
"hash": "a342003149f2991ef0280d008f18e664c96299edfd9a11d08487e4db10a10e8b"
"hash": "7e2e91418e136fc5091b27c5f61158cca61e4853bee64e5afc44679e685cd744"
}

View file

@ -1,18 +1,18 @@
{
"db_name": "PostgreSQL",
"query": "UPDATE\n cqrs_ordering_order_query\n SET\n version = $1,\n customer_name = $2,\n order_id = $3,\n created_time = $4,\n deleted = $5;",
"query": "UPDATE\n cqrs_ordering_order_query\n SET\n version = $1,\n customer_name = $2,\n created_time = $3,\n store_id= $4,\n deleted = $5;",
"describe": {
"columns": [],
"parameters": {
"Left": [
"Int8",
"Text",
"Uuid",
"Timestamptz",
"Uuid",
"Bool"
]
},
"nullable": []
},
"hash": "bc7d17aab113d0519c53e5f612116a6e72bb0007a298cdba17f45f4b8bed5f56"
"hash": "876ca2c177175439a1604a2d5aeec785e41473116ceda238a8089bcb33588e3d"
}

View file

@ -8,8 +8,9 @@ CREATE TABLE IF NOT EXISTS cqrs_ordering_order_query
created_time timestamp with time zone DEFAULT (CURRENT_TIMESTAMP) NOT NULL,
order_id UUID NOT NULL UNIQUE,
store_id UUID NOT NULL,
customer_name TEXT NOT NULL,
customer_name TEXT,
deleted BOOLEAN NOT NULL DEFAULT FALSE,

View file

@ -41,15 +41,17 @@ pub mod tests {
"INSERT INTO cqrs_ordering_order_query (
version,
order_id,
store_id,
customer_name,
created_time,
deleted
) VALUES (
$1, $2, $3, $4, $5
$1, $2, $3, $4, $5, $6
);",
1,
order.order_id(),
order.customer_name(),
order.store_id(),
order.customer_name().as_ref().map(|s| s.as_str()),
order.created_time(),
order.deleted().clone(),
)

View file

@ -23,8 +23,9 @@ pub const NEW_ORDER_NON_UUID: &str = "new_order_non_uuid-asdfa";
// be designed to reflect the response dto that will be returned to a user.
#[derive(Debug, Serialize, Deserialize)]
pub struct OrderView {
customer_name: String,
customer_name: Option<String>,
order_id: Uuid,
store_id: Uuid,
created_time: OffsetDateTime,
deleted: bool,
@ -36,6 +37,7 @@ impl Default for OrderView {
customer_name: Default::default(),
order_id: Default::default(),
created_time: OffsetDateTime::now_utc(),
store_id: Default::default(),
deleted: false,
}
}
@ -46,6 +48,7 @@ impl From<OrderView> for Order {
OrderBuilder::default()
.customer_name(v.customer_name)
.order_id(v.order_id)
.store_id(v.store_id)
.created_time(v.created_time)
.deleted(v.deleted)
.build()
@ -60,16 +63,18 @@ impl View<Order> for OrderView {
fn update(&mut self, event: &EventEnvelope<Order>) {
match &event.payload {
OrderingEvent::OrderAdded(val) => {
self.customer_name = val.order().customer_name().into();
self.customer_name = val.order().customer_name().clone();
self.order_id = *val.order().order_id();
self.created_time = val.order().created_time().clone();
self.store_id = *val.order().store_id();
self.deleted = false;
}
OrderingEvent::OrderUpdated(e) => {
let new = e.new_order();
self.customer_name = new.customer_name().into();
self.customer_name = new.customer_name().clone();
self.order_id = *new.order_id();
self.store_id = *new.store_id();
self.created_time = new.created_time().clone();
}
OrderingEvent::OrderDeleted(_) => self.deleted = true,
@ -93,6 +98,7 @@ impl ViewRepository<OrderView, Order> for OrderingDBPostgresAdapter {
customer_name,
order_id,
created_time,
store_id,
deleted
FROM
cqrs_ordering_order_query
@ -122,6 +128,7 @@ impl ViewRepository<OrderView, Order> for OrderingDBPostgresAdapter {
customer_name,
order_id,
created_time,
store_id,
deleted
FROM
cqrs_ordering_order_query
@ -170,15 +177,17 @@ impl ViewRepository<OrderView, Order> for OrderingDBPostgresAdapter {
customer_name,
order_id,
created_time,
store_id,
deleted
) VALUES (
$1, $2, $3, $4, $5
$1, $2, $3, $4, $5, $6
);",
version,
view.customer_name,
view.order_id,
view.created_time,
view.store_id,
view.deleted,
)
.execute(&self.pool)
@ -194,13 +203,13 @@ impl ViewRepository<OrderView, Order> for OrderingDBPostgresAdapter {
SET
version = $1,
customer_name = $2,
order_id = $3,
created_time = $4,
created_time = $3,
store_id= $4,
deleted = $5;",
version,
view.customer_name,
view.order_id,
view.created_time,
view.store_id,
view.deleted,
)
.execute(&self.pool)

View file

@ -11,10 +11,9 @@ use time::OffsetDateTime;
use super::errors::*;
use crate::ordering::{
application::port::output::db::order_id_exists::*,
application::port::output::db::{order_id_exists::*, store_id_exists::*},
domain::{add_order_command::*, order_added_event::*, order_aggregate::*},
};
use crate::utils::uuid::*;
#[automock]
#[async_trait::async_trait]
@ -27,27 +26,33 @@ pub type AddOrderServiceObj = Arc<dyn AddOrderUseCase>;
#[derive(Clone, Builder)]
pub struct AddOrderService {
db_order_id_exists: OrderIDExistsDBPortObj,
get_uuid: GetUUIDInterfaceObj,
db_store_id_exists: StoreIDExistsDBPortObj,
}
#[async_trait::async_trait]
impl AddOrderUseCase for AddOrderService {
async fn add_order(&self, cmd: AddOrderCommand) -> OrderingResult<OrderAddedEvent> {
let mut order_id = self.get_uuid.get_uuid();
loop {
if self.db_order_id_exists.order_id_exists(&order_id).await? {
order_id = self.get_uuid.get_uuid();
continue;
} else {
break;
if !self
.db_store_id_exists
.store_id_exists(cmd.store_id())
.await?
{
return Err(OrderingError::StoreIDNotFound);
}
if self
.db_order_id_exists
.order_id_exists(cmd.order_id())
.await?
{
return Err(OrderingError::DuplicateOrderID);
}
let order = OrderBuilder::default()
.created_time(OffsetDateTime::now_utc())
.customer_name(cmd.customer_name().into())
.order_id(order_id)
.customer_name(cmd.customer_name().clone())
.order_id(*cmd.order_id())
.store_id(*cmd.store_id())
.deleted(false)
.build()
.unwrap();
@ -65,8 +70,7 @@ pub mod tests {
use super::*;
use crate::ordering::domain::order_added_event::tests::get_added_order_event_from_command;
use crate::utils::uuid::tests::UUID;
use crate::{tests::bdd::*, utils::uuid::tests::mock_get_uuid};
use crate::tests::bdd::*;
pub fn mock_add_order_service(
times: Option<usize>,
@ -92,7 +96,7 @@ pub mod tests {
let s = AddOrderServiceBuilder::default()
.db_order_id_exists(mock_order_id_exists_db_port_false(IS_CALLED_ONLY_ONCE))
.get_uuid(mock_get_uuid(IS_CALLED_ONLY_ONCE))
.db_store_id_exists(mock_store_id_exists_db_port_true(IS_CALLED_ONLY_ONCE))
.build()
.unwrap();
@ -100,5 +104,23 @@ pub mod tests {
assert_eq!(res.order().customer_name(), cmd.customer_name());
assert!(!res.order().deleted());
assert_eq!(res.added_by_user(), cmd.adding_by());
assert_eq!(res.order().store_id(), cmd.store_id());
assert_eq!(res.order().order_id(), cmd.order_id());
}
#[actix_rt::test]
async fn test_service_store_id_doesnt_exist() {
let cmd = AddOrderCommand::get_cmd();
let s = AddOrderServiceBuilder::default()
.db_order_id_exists(mock_order_id_exists_db_port_false(IS_NEVER_CALLED))
.db_store_id_exists(mock_store_id_exists_db_port_false(IS_CALLED_ONLY_ONCE))
.build()
.unwrap();
assert_eq!(
s.add_order(cmd.clone()).await,
Err(OrderingError::StoreIDNotFound)
);
}
}

View file

@ -42,8 +42,9 @@ impl DeleteOrderUseCase for DeleteOrderService {
let deleted_order = OrderBuilder::default()
.created_time(cmd.order().created_time().clone())
.customer_name(cmd.order().customer_name().into())
.customer_name(cmd.order().customer_name().clone())
.order_id(*cmd.order().order_id())
.store_id(*cmd.order().store_id())
.deleted(true)
.build()
.unwrap();

View file

@ -7,14 +7,12 @@ use std::sync::Arc;
use derive_builder::Builder;
use mockall::predicate::*;
use mockall::*;
use time::OffsetDateTime;
use super::errors::*;
use crate::ordering::{
application::port::output::db::order_id_exists::*,
domain::{order_aggregate::*, order_updated_event::*, update_order_command::*},
};
use crate::utils::uuid::*;
#[automock]
#[async_trait::async_trait]
@ -42,7 +40,8 @@ impl UpdateOrderUseCase for UpdateOrderService {
let new_order = OrderBuilder::default()
.created_time(cmd.created_time().clone())
.customer_name(cmd.customer_name().into())
.customer_name(cmd.customer_name().clone())
.store_id(*cmd.old_order().store_id())
.order_id(*cmd.old_order().order_id())
.deleted(false)
.build()
@ -62,8 +61,8 @@ pub mod tests {
use super::*;
use crate::ordering::domain::order_updated_event::tests::get_updated_order_event_from_command;
use crate::tests::bdd::*;
use crate::utils::uuid::tests::UUID;
use crate::{tests::bdd::*, utils::uuid::tests::mock_get_uuid};
pub fn mock_update_order_service(
times: Option<usize>,

View file

@ -9,8 +9,6 @@ use serde::{Deserialize, Serialize};
use time::OffsetDateTime;
use uuid::Uuid;
use crate::utils::string::empty_string_err;
#[derive(Debug, Error, Display, Clone, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)]
pub enum AddOrderCommandError {
CustomerNameIsEmpty,
@ -19,34 +17,31 @@ pub enum AddOrderCommandError {
#[derive(
Clone, Debug, Serialize, Deserialize, Eq, PartialEq, Ord, PartialOrd, Getters, Builder,
)]
pub struct UnvalidatedAddOrderCommand {
pub struct AddOrderCommand {
adding_by: Uuid,
#[builder(default = "OffsetDateTime::now_utc()")]
created_time: OffsetDateTime,
customer_name: String,
#[builder(setter(custom))]
customer_name: Option<String>,
store_id: Uuid,
order_id: Uuid,
}
impl UnvalidatedAddOrderCommand {
pub fn validate(self) -> Result<AddOrderCommand, AddOrderCommandError> {
let customer_name = empty_string_err(
self.customer_name,
AddOrderCommandError::CustomerNameIsEmpty,
)?;
Ok(AddOrderCommand {
created_time: self.created_time,
customer_name,
adding_by: self.adding_by,
})
impl AddOrderCommandBuilder {
pub fn customer_name(&mut self, customer_name: Option<String>) -> &mut Self {
self.customer_name = if let Some(customer_name) = customer_name {
let customer_name = customer_name.trim();
if customer_name.is_empty() {
Some(None)
} else {
Some(Some(customer_name.to_string()))
}
} else {
Some(None)
};
self
}
#[derive(Clone, Debug, Serialize, Deserialize, Eq, PartialEq, Ord, PartialOrd, Getters)]
pub struct AddOrderCommand {
created_time: OffsetDateTime,
customer_name: String,
adding_by: Uuid,
}
#[cfg(test)]
@ -62,14 +57,14 @@ mod tests {
let customer_name = "foo";
let adding_by = UUID;
UnvalidatedAddOrderCommandBuilder::default()
.customer_name(customer_name.into())
AddOrderCommandBuilder::default()
.customer_name(Some(customer_name.into()))
.adding_by(adding_by)
.created_time(datetime!(1970-01-01 0:00 UTC))
.store_id(UUID)
.order_id(UUID)
.build()
.unwrap()
.validate()
.unwrap()
}
}
@ -78,31 +73,27 @@ mod tests {
let customer_name = "foo";
let adding_by = UUID;
let cmd = UnvalidatedAddOrderCommandBuilder::default()
.customer_name(customer_name.into())
let _cmd = AddOrderCommandBuilder::default()
.customer_name(Some(customer_name.into()))
.adding_by(adding_by)
.store_id(UUID)
.order_id(UUID)
.build()
.unwrap()
.validate()
.unwrap();
assert_eq!(*cmd.adding_by(), adding_by);
assert_eq!(cmd.customer_name(), customer_name);
}
#[test]
fn test_cmd_customer_name_empty() {
let customer_name = "";
let adding_by = UUID;
assert_eq!(
UnvalidatedAddOrderCommandBuilder::default()
.customer_name(customer_name.into())
.adding_by(adding_by)
let cmd = AddOrderCommandBuilder::default()
.customer_name(Some(customer_name.into()))
.adding_by(UUID)
.store_id(UUID)
.order_id(UUID)
.build()
.unwrap()
.validate(),
Err(AddOrderCommandError::CustomerNameIsEmpty)
);
.unwrap();
assert!(cmd.customer_name().is_none());
}
}

View file

@ -21,11 +21,11 @@ use crate::ordering::{
pub struct Order {
#[builder(default = "OffsetDateTime::now_utc()")]
created_time: OffsetDateTime,
// kot_ids: Vec<Kot>,
store_id: Uuid,
order_id: Uuid,
#[builder(default = "false")]
deleted: bool,
customer_name: String,
customer_name: Option<String>,
}
impl Default for Order {
@ -33,8 +33,9 @@ impl Default for Order {
Self {
created_time: OffsetDateTime::now_utc(),
order_id: Default::default(),
store_id: Default::default(),
deleted: false,
customer_name: Default::default(),
customer_name: None,
}
}
}
@ -51,8 +52,9 @@ mod tests {
OrderBuilder::default()
.created_time(cmd.created_time().clone())
.customer_name("test_product".into())
.order_id(UUID)
.customer_name(Some("test_product".into()))
.order_id(*cmd.order_id())
.store_id(*cmd.store_id())
.build()
.unwrap()
}

View file

@ -27,8 +27,9 @@ pub mod tests {
pub fn get_deleted_order_event_from_command(cmd: &DeleteOrderCommand) -> OrderDeletedEvent {
let deleted_order = OrderBuilder::default()
.created_time(cmd.order().created_time().clone())
.customer_name(cmd.order().customer_name().into())
.customer_name(cmd.order().customer_name().clone())
.order_id(*cmd.order().order_id())
.store_id(*cmd.order().store_id())
.deleted(true)
.build()
.unwrap();

View file

@ -28,8 +28,9 @@ pub mod tests {
pub fn get_updated_order_event_from_command(cmd: &UpdateOrderCommand) -> OrderUpdatedEvent {
let new_order = OrderBuilder::default()
.created_time(cmd.created_time().clone())
.customer_name(cmd.customer_name().into())
.customer_name(cmd.customer_name().clone())
.order_id(*cmd.old_order().order_id())
.store_id(*cmd.old_order().store_id())
.build()
.unwrap();

View file

@ -10,7 +10,6 @@ use time::OffsetDateTime;
use uuid::Uuid;
use super::order_aggregate::*;
use crate::utils::string::empty_string_err;
#[derive(Debug, Error, Display, Clone, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)]
pub enum UpdateOrderCommandError {
@ -20,37 +19,31 @@ pub enum UpdateOrderCommandError {
#[derive(
Clone, Debug, Serialize, Deserialize, Eq, PartialEq, Ord, PartialOrd, Getters, Builder,
)]
pub struct UnvalidatedUpdateOrderCommand {
pub struct UpdateOrderCommand {
adding_by: Uuid,
#[builder(default = "OffsetDateTime::now_utc()")]
created_time: OffsetDateTime,
customer_name: String,
#[builder(setter(custom))]
customer_name: Option<String>,
old_order: Order,
}
impl UnvalidatedUpdateOrderCommand {
pub fn validate(self) -> Result<UpdateOrderCommand, UpdateOrderCommandError> {
let customer_name = empty_string_err(
self.customer_name,
UpdateOrderCommandError::CustomerNameIsEmpty,
)?;
Ok(UpdateOrderCommand {
created_time: self.created_time,
customer_name,
adding_by: self.adding_by,
old_order: self.old_order,
})
impl UpdateOrderCommandBuilder {
pub fn customer_name(&mut self, customer_name: Option<String>) -> &mut Self {
self.customer_name = if let Some(customer_name) = customer_name {
let customer_name = customer_name.trim();
if customer_name.is_empty() {
Some(None)
} else {
Some(Some(customer_name.to_string()))
}
} else {
Some(None)
};
self
}
#[derive(Clone, Debug, Serialize, Deserialize, Eq, PartialEq, Ord, PartialOrd, Getters)]
pub struct UpdateOrderCommand {
created_time: OffsetDateTime,
customer_name: String,
adding_by: Uuid,
old_order: Order,
}
#[cfg(test)]
@ -66,15 +59,13 @@ mod tests {
let customer_name = "foo-new-name";
let adding_by = UUID;
UnvalidatedUpdateOrderCommandBuilder::default()
.customer_name(customer_name.into())
UpdateOrderCommandBuilder::default()
.customer_name(Some(customer_name.into()))
.adding_by(adding_by)
.created_time(datetime!(1970-01-01 0:00 UTC))
.old_order(Order::default())
.build()
.unwrap()
.validate()
.unwrap()
}
}
@ -84,17 +75,15 @@ mod tests {
let adding_by = UUID;
let old_order = Order::default();
let cmd = UnvalidatedUpdateOrderCommandBuilder::default()
.customer_name(customer_name.into())
let cmd = UpdateOrderCommandBuilder::default()
.customer_name(Some(customer_name.into()))
.adding_by(adding_by)
.old_order(old_order.clone())
.build()
.unwrap()
.validate()
.unwrap();
assert_eq!(*cmd.adding_by(), adding_by);
assert_eq!(cmd.customer_name(), customer_name);
assert_eq!(cmd.customer_name().as_ref().unwrap(), customer_name);
assert_eq!(cmd.old_order(), &old_order);
}
@ -103,15 +92,13 @@ mod tests {
let customer_name = "";
let adding_by = UUID;
assert_eq!(
UnvalidatedUpdateOrderCommandBuilder::default()
.customer_name(customer_name.into())
let cmd = UpdateOrderCommandBuilder::default()
.customer_name(Some(customer_name.into()))
.adding_by(adding_by)
.old_order(Order::default())
.build()
.unwrap()
.validate(),
Err(UpdateOrderCommandError::CustomerNameIsEmpty)
);
.unwrap();
assert!(cmd.customer_name().is_none());
}
}