feat: ordering: Order ID is provided by caller

This commit is contained in:
Aravinth Manivannan 2024-09-24 17:26:28 +05:30
parent 7c3676e84d
commit eba2f7204c
Signed by: realaravinth
GPG key ID: F8F50389936984FF
14 changed files with 155 additions and 132 deletions

View file

@ -1,6 +1,6 @@
{ {
"db_name": "PostgreSQL", "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": { "describe": {
"columns": [ "columns": [
{ {
@ -20,6 +20,11 @@
}, },
{ {
"ordinal": 3, "ordinal": 3,
"name": "store_id",
"type_info": "Uuid"
},
{
"ordinal": 4,
"name": "deleted", "name": "deleted",
"type_info": "Bool" "type_info": "Bool"
} }
@ -30,11 +35,12 @@
] ]
}, },
"nullable": [ "nullable": [
true,
false, false,
false, false,
false, false,
false false
] ]
}, },
"hash": "dbe1e41f04a81b2a504b9179911201ec52340d09d45041addd54eb349af82488" "hash": "4f8a2294b40e4285fa6d4c7bcf648be7320f99002b9a9279981053a5062b0ed8"
} }

View file

@ -1,6 +1,6 @@
{ {
"db_name": "PostgreSQL", "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": { "describe": {
"columns": [], "columns": [],
"parameters": { "parameters": {
@ -9,10 +9,11 @@
"Text", "Text",
"Uuid", "Uuid",
"Timestamptz", "Timestamptz",
"Uuid",
"Bool" "Bool"
] ]
}, },
"nullable": [] "nullable": []
}, },
"hash": "a342003149f2991ef0280d008f18e664c96299edfd9a11d08487e4db10a10e8b" "hash": "7e2e91418e136fc5091b27c5f61158cca61e4853bee64e5afc44679e685cd744"
} }

View file

@ -1,18 +1,18 @@
{ {
"db_name": "PostgreSQL", "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": { "describe": {
"columns": [], "columns": [],
"parameters": { "parameters": {
"Left": [ "Left": [
"Int8", "Int8",
"Text", "Text",
"Uuid",
"Timestamptz", "Timestamptz",
"Uuid",
"Bool" "Bool"
] ]
}, },
"nullable": [] "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, created_time timestamp with time zone DEFAULT (CURRENT_TIMESTAMP) NOT NULL,
order_id UUID NOT NULL UNIQUE, 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, deleted BOOLEAN NOT NULL DEFAULT FALSE,

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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