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
use std::collections::HashMap;
use std::error::Error;
use std::fmt::{self};

use chekov::error::HandleError;
use chekov::prelude::*;
use futures::future::BoxFuture;
use futures::FutureExt;
use serde::Serialize;
use sqlx::postgres::PgRow;
use sqlx::types::Json;
use sqlx::{Acquire, PgPool, Row};
use uuid::Uuid;

use crate::commands::*;
use crate::events::order::{GiftCardAdded, OrderCanceled, OrderCreated, OrderValidated};

#[derive(Clone, Debug, PartialEq, Serialize)]
pub enum OrderStatus {
    Unknown,
    Created,
    Canceled,
    #[allow(dead_code)]
    Paid,
    Validated,
}

impl Default for OrderStatus {
    fn default() -> Self {
        Self::Unknown
    }
}

#[derive(Clone, Debug, Serialize, serde::Deserialize)]
pub struct Item {
    amount: i64,
    price: i64,
}

#[derive(Debug)]
pub enum OrderError {
    AlreadyCreated,
    CantBeCanceled,
    CantAddCard,
    ValidationError,
}

impl fmt::Display for OrderError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            OrderError::AlreadyCreated => write!(f, "Order is already created"),
            OrderError::CantBeCanceled => write!(f, "Order can't be canceled"),
            OrderError::CantAddCard => write!(f, "Can't add the card to this order"),
            OrderError::ValidationError => write!(f, "Can't validate this order"),
        }
    }
}
impl Error for OrderError {}

#[derive(Default, Debug, Clone, chekov::Aggregate, Serialize)]
#[aggregate(identity = "order")]
pub struct Order {
    pub order_id: Option<Uuid>,
    pub account_id: Option<Uuid>,
    pub status: OrderStatus,
    pub items: HashMap<Uuid, Item>,
    pub total_price: i64,
}

impl CommandExecutor<CreateOrder> for Order {
    fn execute(cmd: CreateOrder, state: &Self) -> ExecutionResult<OrderCreated> {
        if state.status != OrderStatus::Unknown {
            return Err(CommandExecutorError::ExecutionError(Box::new(
                OrderError::AlreadyCreated,
            )));
        }

        Ok(vec![OrderCreated {
            order_id: cmd.order_id,
            account_id: cmd.account_id,
        }])
    }
}

impl CommandExecutor<CancelOrder> for Order {
    fn execute(cmd: CancelOrder, state: &Self) -> ExecutionResult<OrderCanceled> {
        match state.status {
            OrderStatus::Created | OrderStatus::Validated => Ok(vec![OrderCanceled {
                order_id: cmd.order_id,
                account_id: state.account_id.unwrap(),
                total_price: state.total_price,
            }]),
            OrderStatus::Unknown | OrderStatus::Canceled | OrderStatus::Paid => Err(
                CommandExecutorError::ExecutionError(Box::new(OrderError::CantBeCanceled)),
            ),
        }
    }
}

impl CommandExecutor<ValidateOrder> for Order {
    fn execute(cmd: ValidateOrder, state: &Self) -> ExecutionResult<OrderValidated> {
        if state.status == OrderStatus::Created && !state.items.is_empty() {
            return Ok(vec![OrderValidated {
                order_id: cmd.order_id,
                account_id: state.account_id.unwrap(),
                items: state.items.clone(),
                total_price: state.total_price,
            }]);
        }

        Err(CommandExecutorError::ExecutionError(Box::new(
            OrderError::ValidationError,
        )))
    }
}

impl CommandExecutor<AddGiftCardToOrder> for Order {
    fn execute(cmd: AddGiftCardToOrder, state: &Self) -> ExecutionResult<GiftCardAdded> {
        if state.status == OrderStatus::Created
            && cmd.price > 0
            && cmd.amount > 0
            && !state.items.iter().any(|(id, _)| id == &cmd.gift_card_id)
        {
            return Ok(vec![GiftCardAdded {
                order_id: cmd.order_id,
                gift_card_id: cmd.gift_card_id,
                amount: cmd.amount,
                price: cmd.price,
            }]);
        }

        Err(CommandExecutorError::ExecutionError(Box::new(
            OrderError::CantAddCard,
        )))
    }
}

#[chekov::applier]
impl EventApplier<OrderCreated> for Order {
    fn apply(&mut self, event: &OrderCreated) -> Result<(), chekov::prelude::ApplyError> {
        self.status = OrderStatus::Created;
        self.order_id = Some(event.order_id);
        self.account_id = Some(event.account_id);

        Ok(())
    }
}

#[chekov::applier]
impl EventApplier<OrderCanceled> for Order {
    fn apply(&mut self, _: &OrderCanceled) -> Result<(), ApplyError> {
        self.status = OrderStatus::Canceled;

        Ok(())
    }
}

#[chekov::applier]
impl EventApplier<GiftCardAdded> for Order {
    fn apply(&mut self, event: &GiftCardAdded) -> Result<(), chekov::prelude::ApplyError> {
        self.items.insert(
            event.gift_card_id,
            Item {
                amount: event.amount as i64,
                price: event.price,
            },
        );

        Ok(())
    }
}

#[chekov::applier]
impl EventApplier<OrderValidated> for Order {
    fn apply(&mut self, _: &OrderValidated) -> Result<(), ApplyError> {
        self.status = OrderStatus::Validated;

        Ok(())
    }
}

#[derive(chekov::EventHandler, Clone)]
pub struct OrderProjector {
    pub pool: PgPool,
}

#[chekov::event_handler]
impl chekov::event::Handler<OrderCreated> for OrderProjector {
    fn handle(&mut self, event: &OrderCreated) -> BoxFuture<Result<(), HandleError>> {
        let event = event.clone();
        let pool = self.pool.acquire();
        async move {
            let p = pool.await.unwrap();
            let _result = OrderRepository::create(&event, p).await;

            Ok(())
        }
        .boxed()
    }
}

#[chekov::event_handler]
impl chekov::event::Handler<GiftCardAdded> for OrderProjector {
    fn handle(&mut self, event: &GiftCardAdded) -> BoxFuture<Result<(), HandleError>> {
        let event = event.clone();
        let pool = self.pool.acquire();
        async move {
            let p = pool.await.unwrap();
            let _result = OrderRepository::add_gift_card(&event, p).await;

            Ok(())
        }
        .boxed()
    }
}

pub struct OrderRepository {}

impl OrderRepository {
    pub async fn create(
        entity: &OrderCreated,
        mut pool: sqlx::pool::PoolConnection<sqlx::Postgres>,
    ) -> Result<Order, sqlx::Error> {
        let mut tx = pool.begin().await?;
        let todo = sqlx::query(
            "INSERT INTO orders (order_id, account_id) VALUES ($1, $2) RETURNING order_id, account_id, items, total_price",
        )
        .bind(entity.order_id)
        .bind(entity.account_id)
        .map(|row: PgRow| Order {
            order_id: row.get(0),
            account_id: row.get(1),
            items: row.get::<Json<HashMap<Uuid, Item>>, _>(2).0,
            total_price: row.get(3),
            status: OrderStatus::Created
        })
        .fetch_one(&mut tx)
        .await?;

        tx.commit().await?;
        Ok(todo)
    }

    pub async fn add_gift_card(
        entity: &GiftCardAdded,
        mut pool: sqlx::pool::PoolConnection<sqlx::Postgres>,
    ) -> Result<Order, sqlx::Error> {
        let json = format!(
            r#"{{"{}": {{"amount": {}, "price": {}}}}}"#,
            entity.gift_card_id, entity.amount, entity.price
        );

        let mut tx = pool.begin().await?;
        let todo = sqlx::query(
            r#"UPDATE orders SET items = items::jsonb || $1::jsonb WHERE order_id = $2 RETURNING order_id, account_id, items, total_price"#
        )
            .bind(&json)
            .bind(entity.order_id)
            .map(|row: PgRow| Order {
                order_id: row.get(0),
                account_id: row.get(1),
                items: row.get::<Json<HashMap<Uuid, Item>>, _>(2).0,
                total_price: row.get(3),
                status: OrderStatus::Created
            })
            .fetch_one(&mut tx)
            .await?;

        tx.commit().await?;
        Ok(todo)
    }
}