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

use super::*;
use crate::events::account::*;
use chekov::event::EventApplier;

#[derive(Debug)]
enum AccountError {
    UnableToCreate,
}

impl fmt::Display for AccountError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            AccountError::UnableToCreate => write!(f, "Can't open account"),
        }
    }
}

impl Error for AccountError {}

impl CommandExecutor<OpenAccount> for Account {
    fn execute(cmd: OpenAccount, state: &Self) -> Result<Vec<AccountOpened>, CommandExecutorError> {
        match state.status {
            AccountStatus::Initialized => Ok(vec![AccountOpened {
                account_id: cmd.account_id,
                name: cmd.name,
                balance: 0,
            }]),
            _ => Err(CommandExecutorError::ExecutionError(Box::new(
                AccountError::UnableToCreate,
            ))),
        }
    }
}

#[chekov::applier]
impl EventApplier<AccountOpened> for Account {
    fn apply(&mut self, event: &AccountOpened) -> Result<(), ApplyError> {
        self.account_id = Some(event.account_id);
        self.status = AccountStatus::Active;

        Ok(())
    }
}