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
use derive_builder::Builder;
use serde::{Deserialize, Serialize};

pub use cala_types::{entry::*, primitives::EntryId};

use crate::{entity::*, primitives::*};

#[derive(Debug, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum EntryEvent {
    #[cfg(feature = "import")]
    Imported {
        source: DataSource,
        values: EntryValues,
    },
    Initialized {
        values: EntryValues,
    },
}

impl EntityEvent for EntryEvent {
    type EntityId = EntryId;
    fn event_table_name() -> &'static str {
        "cala_entry_events"
    }
}

#[derive(Builder)]
#[builder(pattern = "owned", build_fn(error = "EntityError"))]
pub struct Entry {
    values: EntryValues,
    pub(super) events: EntityEvents<EntryEvent>,
}

impl Entity for Entry {
    type Event = EntryEvent;
}

impl Entry {
    #[cfg(feature = "import")]
    pub(super) fn import(source: DataSourceId, values: EntryValues) -> Self {
        let events = EntityEvents::init(
            values.id,
            [EntryEvent::Imported {
                source: DataSource::Remote { id: source },
                values,
            }],
        );
        Self::try_from(events).expect("Failed to build entry from events")
    }

    pub fn id(&self) -> EntryId {
        self.values.id
    }

    pub fn values(&self) -> &EntryValues {
        &self.values
    }

    pub fn into_values(self) -> EntryValues {
        self.values
    }
}

impl TryFrom<EntityEvents<EntryEvent>> for Entry {
    type Error = EntityError;

    fn try_from(events: EntityEvents<EntryEvent>) -> Result<Self, Self::Error> {
        let mut builder = EntryBuilder::default();
        for event in events.iter() {
            match event {
                #[cfg(feature = "import")]
                EntryEvent::Imported { source: _, values } => {
                    builder = builder.values(values.clone());
                }
                EntryEvent::Initialized { values } => {
                    builder = builder.values(values.clone());
                }
            }
        }
        builder.events(events).build()
    }
}

#[derive(Builder, Debug)]
#[allow(dead_code)]
pub(crate) struct NewEntry {
    #[builder(setter(into))]
    pub id: EntryId,
    #[builder(setter(into))]
    pub(super) transaction_id: TransactionId,
    #[builder(setter(into))]
    pub(super) journal_id: JournalId,
    #[builder(setter(into))]
    pub(super) account_id: AccountId,
    #[builder(setter(into))]
    pub(super) entry_type: String,
    #[builder(setter(into))]
    pub(super) sequence: u32,
    #[builder(default)]
    pub(super) layer: Layer,
    #[builder(setter(into))]
    pub(super) units: rust_decimal::Decimal,
    #[builder(setter(into))]
    pub(super) currency: Currency,
    #[builder(default)]
    pub(super) direction: DebitOrCredit,
    #[builder(setter(strip_option), default)]
    pub(super) description: Option<String>,
}

impl NewEntry {
    pub fn builder() -> NewEntryBuilder {
        NewEntryBuilder::default()
    }

    pub(super) fn to_values(&self) -> EntryValues {
        EntryValues {
            id: self.id,
            transaction_id: self.transaction_id,
            journal_id: self.journal_id,
            account_id: self.account_id,
            entry_type: self.entry_type.clone(),
            sequence: self.sequence,
            layer: self.layer,
            units: self.units,
            currency: self.currency,
            direction: self.direction,
            description: self.description.clone(),
        }
    }

    pub(super) fn initial_events(self) -> EntityEvents<EntryEvent> {
        EntityEvents::init(
            self.id,
            [EntryEvent::Initialized {
                values: EntryValues {
                    id: self.id,
                    transaction_id: self.transaction_id,
                    journal_id: self.journal_id,
                    account_id: self.account_id,
                    entry_type: self.entry_type,
                    sequence: self.sequence,
                    layer: self.layer,
                    units: self.units,
                    currency: self.currency,
                    direction: self.direction,
                    description: self.description,
                },
            }],
        )
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn it_builds() {
        let mut builder = NewEntry::builder();
        let currency = "USD".parse::<Currency>().unwrap();
        let entry_id = EntryId::new();
        builder
            .id(entry_id)
            .transaction_id(TransactionId::new())
            .account_id(AccountId::new())
            .journal_id(JournalId::new())
            .layer(Layer::Settled)
            .entry_type("ENTRY_TYPE")
            .sequence(1u32)
            .units(rust_decimal::Decimal::from(1))
            .currency(currency)
            .direction(DebitOrCredit::Debit);
        let new_entry = builder.build().unwrap();
        assert_eq!(new_entry.id, entry_id);
    }

    #[test]
    fn fails_when_missing_required_fields() {
        let mut builder = NewEntry::builder();
        builder.id(EntryId::new());
        let new_entry = builder.build();
        assert!(new_entry.is_err());
    }
}