1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
use crate::error::Error;
use crate::inventory::InventoryController;
use crate::item::ItemTitleResolver;
use crate::money::{Currency, Money};
use address::Address;
use async_trait::async_trait;
use chrono::{DateTime, Utc};
use inventory::StockIssue;
use invoice::{Invoice, InvoiceCalculator};
use item::Item;
use price::PriceCalculator;
use serde::{Deserialize, Serialize};
use shipping::{FulfillmentType, FulfillmentTypeSelection, ShippingCalculator, ShippingQuote};
use std::matches;
use uuid::Uuid;
pub mod address;
pub mod error;
pub mod inventory;
pub mod invoice;
pub mod item;
pub mod money;
pub mod price;
pub mod server;
pub mod shipping;
#[derive(Serialize, Deserialize)]
pub enum State {
Shopping,
ItemsConfirmed(DateTime<Utc>),
Completed,
Abandoned,
}
#[derive(Serialize, Deserialize)]
pub struct Checkout {
pub id: Uuid,
pub state: State,
pub currency: Currency,
pub promo_codes: Vec<String>,
pub items: Vec<Item>,
pub fulfillment_type: Option<FulfillmentType>,
pub shipping_address: Option<Address>,
pub shipping_quotes: Vec<ShippingQuote>,
pub invoice: Option<Invoice>,
}
impl Checkout {
async fn enter_shopping_state<C: CheckoutContext + Send>(
&mut self,
ctx: &mut C,
) -> Result<(), CheckoutError> {
match self.state {
State::Shopping => Ok(()),
State::ItemsConfirmed(_) => {
ctx.free_items(&self.items).await?;
self.fulfillment_type = None;
self.shipping_quotes = vec![];
Ok(self.state = State::Shopping)
}
_ => Err(new_invalid_state_error(
"must be in the shopping or items_confirmed state",
)),
}
}
async fn enter_items_confirmed_state<C: CheckoutContext + Send>(
&mut self,
ctx: &mut C,
) -> Result<(), CheckoutError> {
match self.state {
State::ItemsConfirmed(_) => Ok(()),
State::Shopping => {
self.fulfillment_type = None;
if let Some(address) = &self.shipping_address {
self.shipping_quotes = ctx
.get_shipping_quotes(
&self.currency,
&self.promo_codes,
&self.items,
address,
)
.await?;
}
ctx.update_item_prices(&self.currency, &self.promo_codes, &mut self.items)
.await?;
self.update_invoice(ctx).await?;
Ok(self.state = State::ItemsConfirmed(ctx.reserve_items(&self.items).await?))
}
_ => Err(new_invalid_state_error(
"must be in the shopping or items_confirmed state",
)),
}
}
async fn update_invoice<C: CheckoutContext + Send>(
&mut self,
ctx: &mut C,
) -> Result<(), CheckoutError> {
Ok(self.invoice = Some(ctx.generate_invoice(self).await?))
}
pub async fn add_item<C: CheckoutContext + Send>(
&mut self,
ctx: &mut C,
sku: String,
quantity: u64,
) -> Result<(), CheckoutError> {
self.enter_shopping_state(ctx).await?;
let mut is_added = false;
for item in self.items.iter_mut() {
if item.sku == sku {
item.quantity += quantity;
is_added = true;
break;
}
}
if !is_added {
let title = ctx.resolve_item_title(&sku).await?;
let item = Item {
sku: sku.to_string(),
title,
quantity,
price: Money::new(self.currency.clone(), "0"),
discount: Money::new(self.currency.clone(), "0"),
};
self.items.push(item);
}
ctx.update_item_prices(&self.currency, &self.promo_codes, &mut self.items)
.await?;
ctx.on_add_item(self, &sku, quantity).await
}
pub async fn remove_item<C: CheckoutContext + Send>(
&mut self,
ctx: &mut C,
sku: String,
quantity: u64,
) -> Result<(), CheckoutError> {
self.enter_shopping_state(ctx).await?;
let mut index_to_remove: Option<usize> = None;
for (index, item) in self.items.iter_mut().enumerate() {
if item.sku == sku {
if item.quantity <= quantity {
index_to_remove = Some(index);
break;
}
item.quantity -= quantity;
break;
}
}
if let Some(index) = index_to_remove {
self.items.remove(index);
}
ctx.update_item_prices(&self.currency, &self.promo_codes, &mut self.items)
.await?;
ctx.on_remove_item(self, &sku, quantity).await
}
pub async fn confirm_items<C: CheckoutContext + Send>(
&mut self,
ctx: &mut C,
) -> Result<(), CheckoutError> {
self.enter_items_confirmed_state(ctx).await?;
ctx.on_confirm_items(self).await
}
pub async fn update_shipping_address<C: CheckoutContext + Send>(
&mut self,
ctx: &mut C,
address: Address,
) -> Result<(), CheckoutError> {
self.shipping_address = Some(address);
self.fulfillment_type = None;
if let State::ItemsConfirmed(_) = self.state {
self.shipping_quotes = ctx
.get_shipping_quotes(
&self.currency,
&self.promo_codes,
&self.items,
self.shipping_address.as_ref().unwrap(),
)
.await?;
}
ctx.on_update_shipping_address(self).await
}
pub async fn update_fulfillment_type<C: CheckoutContext + Send>(
&mut self,
ctx: &mut C,
fulfillment_type: FulfillmentTypeSelection,
) -> Result<(), CheckoutError> {
if !matches!(self.state, State::ItemsConfirmed(_)) {
return Err(new_invalid_state_error(
"must be in the items_confirmed state",
));
}
match fulfillment_type {
FulfillmentTypeSelection::Pickup => {
self.fulfillment_type = Some(FulfillmentType::Pickup);
}
FulfillmentTypeSelection::Shipping(quote_id) => {
let mut updated = false;
for quote in self.shipping_quotes.iter() {
if quote.id == quote_id {
self.fulfillment_type = Some(FulfillmentType::Shipping(quote.clone()));
updated = true;
break;
}
}
if !updated {
return Err(new_bad_request_error(
"the requested quote is not available",
));
}
}
}
self.update_invoice(ctx).await?;
ctx.on_update_fulfillment_type(self).await
}
}
#[async_trait]
pub trait CheckoutContext:
InvoiceCalculator + ItemTitleResolver + InventoryController + ShippingCalculator + PriceCalculator
{
async fn new() -> Self;
async fn on_add_item(
&mut self,
_co: &Checkout,
_sku: &str,
_quantity: u64,
) -> Result<(), CheckoutError> {
Ok(())
}
async fn on_remove_item(
&mut self,
_co: &Checkout,
_sku: &str,
_quantity: u64,
) -> Result<(), CheckoutError> {
Ok(())
}
async fn on_confirm_items(&mut self, _co: &Checkout) -> Result<(), CheckoutError> {
Ok(())
}
async fn on_update_shipping_address(&mut self, _co: &Checkout) -> Result<(), CheckoutError> {
Ok(())
}
async fn on_update_fulfillment_type(&mut self, _co: &Checkout) -> Result<(), CheckoutError> {
Ok(())
}
}
#[derive(Debug, Serialize, Deserialize)]
pub enum CheckoutError {
InvalidState(Error),
BadRequest(Error),
StockIssue(Vec<StockIssue>),
}
fn new_invalid_state_error(msg: &str) -> CheckoutError {
CheckoutError::InvalidState(Error {
code: String::from("300"),
message: msg.to_string(),
})
}
fn new_bad_request_error(msg: &str) -> CheckoutError {
CheckoutError::BadRequest(Error {
code: String::from("400"),
message: msg.to_string(),
})
}