1
//! A [`TransactionState`] serialized for one script run, and that run's
2
//! output entities applied back onto it.
3

            
4
use std::collections::{HashMap, HashSet};
5

            
6
use finance::split::Split;
7
use finance::tag::Tag;
8
use scripting::{ContextType, EntityData, EntityType, MemorySerializer, Operation, ParsedEntity};
9
use sqlx::types::Uuid;
10
use sqlx::types::chrono::{DateTime, TimeZone, Utc};
11

            
12
use super::{DEFAULT_OUTPUT_SIZE, TransactionState};
13
use crate::error::ServerError;
14

            
15
pub(super) type IndexTable = HashMap<u32, (EntityType, Uuid)>;
16

            
17
/// The owner and tag id behind one serialized tag occurrence.
18
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
19
pub(super) enum TagLink {
20
    Transaction(Uuid),
21
    Split(Uuid, Uuid),
22
}
23

            
24
impl TagLink {
25
7
    fn tag_id(self) -> Uuid {
26
7
        match self {
27
7
            Self::Transaction(tag_id) | Self::Split(_, tag_id) => tag_id,
28
        }
29
7
    }
30
}
31

            
32
/// Serialized tag id to the occurrence it names. A tag shared by the
33
/// transaction and its splits is one tag id, so every split occurrence gets
34
/// its own serialized id and a deletion reaches only that occurrence.
35
pub(super) type TagLinks = HashMap<Uuid, TagLink>;
36

            
37
3092
pub(super) fn serialize_state(state: &TransactionState) -> (Vec<u8>, IndexTable, TagLinks) {
38
3092
    let mut serializer = MemorySerializer::new();
39
3092
    let mut index_table = IndexTable::new();
40
3092
    let mut tag_links = TagLinks::new();
41

            
42
3092
    serializer.set_context(ContextType::EntityCreate, EntityType::Transaction);
43

            
44
3092
    let is_multi_currency = state
45
3092
        .splits
46
3092
        .iter()
47
6175
        .map(|s| s.commodity_id)
48
        .collect::<HashSet<_>>()
49
        .len()
50
3092
        > 1;
51

            
52
3092
    let tx_idx = serializer.add_transaction_from(scripting::TransactionFromArgs {
53
3092
        transaction: &state.transaction,
54
3092
        is_primary: true,
55
3092
        split_count: state.splits.len() as u32,
56
3092
        tag_count: state.transaction_tags.len() as u32,
57
3092
        is_multi_currency,
58
3092
    });
59
3092
    serializer.set_primary(tx_idx);
60
3092
    index_table.insert(tx_idx, (EntityType::Transaction, state.transaction.id));
61

            
62
3092
    let mut split_indices: HashMap<Uuid, u32> = HashMap::new();
63
3092
    for split in &state.splits {
64
6175
        let account_name = state
65
6175
            .account_names
66
6175
            .get(&split.account_id)
67
6175
            .map_or("", String::as_str);
68
6175
        let split_idx = serializer.add_split_from(split, tx_idx as i32, account_name);
69
6175
        split_indices.insert(split.id, split_idx);
70
6175
        index_table.insert(split_idx, (EntityType::Split, split.id));
71
    }
72

            
73
3092
    for tag in &state.transaction_tags {
74
2020
        tag_links.insert(tag.id, TagLink::Transaction(tag.id));
75
2020
        add_tag(&mut serializer, tag.id, tx_idx as i32, tag);
76
    }
77

            
78
3092
    for (split_id, tag) in &state.split_tags {
79
737
        let parent_idx = split_indices.get(split_id).map_or(-1, |idx| *idx as i32);
80
737
        let wire_id = Uuid::new_v4();
81
737
        tag_links.insert(wire_id, TagLink::Split(*split_id, tag.id));
82
737
        add_tag(&mut serializer, wire_id, parent_idx, tag);
83
    }
84

            
85
3092
    (
86
3092
        serializer.finalize(DEFAULT_OUTPUT_SIZE),
87
3092
        index_table,
88
3092
        tag_links,
89
3092
    )
90
3092
}
91

            
92
2757
fn add_tag(serializer: &mut MemorySerializer, wire_id: Uuid, parent_idx: i32, tag: &Tag) {
93
2757
    serializer.add_tag(
94
2757
        *wire_id.as_bytes(),
95
2757
        parent_idx,
96
2757
        false,
97
2757
        false,
98
2757
        &tag.tag_name,
99
2757
        &tag.tag_value,
100
2757
    );
101
2757
}
102

            
103
2180
pub(super) fn apply_parsed_entities(
104
2180
    state: &mut TransactionState,
105
2180
    entities: Vec<ParsedEntity>,
106
2180
    index_table: &mut IndexTable,
107
2180
    tag_links: &TagLinks,
108
2180
) -> Result<(), ServerError> {
109
2180
    let mut next_idx = index_table.len() as u32;
110

            
111
2180
    for entity in entities {
112
2733
        let entity_id = Uuid::from_bytes(entity.id);
113
2733
        let created = match (entity.entity_type, entity.operation, entity.data) {
114
2544
            (EntityType::Tag, Operation::Create, EntityData::Tag { name, value }) => Some((
115
2544
                EntityType::Tag,
116
2544
                create_tag(state, index_table, entity.parent_idx, name, value),
117
2544
            )),
118
            (EntityType::Split, Operation::Create, data @ EntityData::Split { .. }) => {
119
                Some((EntityType::Split, create_split(state, data)))
120
            }
121
            (EntityType::Split, Operation::Update, data @ EntityData::Split { .. }) => {
122
                update_split(state, entity_id, data);
123
                None
124
            }
125
            (
126
                EntityType::Transaction,
127
                Operation::Update,
128
                EntityData::Transaction {
129
                    post_date,
130
                    enter_date,
131
                    ..
132
                },
133
            ) => {
134
                tracing::debug!("script: update transaction {entity_id}");
135
                state.transaction.post_date = millis_to_datetime(post_date);
136
                state.transaction.enter_date = millis_to_datetime(enter_date);
137
                None
138
            }
139
            (EntityType::Split, Operation::Delete, _) => {
140
                tracing::debug!("script: delete split {entity_id}");
141
                state.splits.retain(|s| s.id != entity_id);
142
                state.split_tags.retain(|(id, _)| *id != entity_id);
143
                None
144
            }
145
            (EntityType::Tag, Operation::Delete, _) => {
146
8
                tracing::debug!("script: delete tag {entity_id}");
147
8
                match tag_links.get(&entity_id) {
148
8
                    Some(link) => delete_tag_link(state, *link),
149
                    None => tracing::warn!("Deleted tag {entity_id} is not in the script input"),
150
                }
151
8
                None
152
            }
153
181
            _ => None,
154
        };
155
2733
        if let Some(created) = created {
156
2544
            index_table.insert(next_idx, created);
157
2544
            next_idx += 1;
158
189
        }
159
    }
160
2180
    Ok(())
161
2180
}
162

            
163
2544
fn create_tag(
164
2544
    state: &mut TransactionState,
165
2544
    index_table: &IndexTable,
166
2544
    parent_idx: i32,
167
2544
    name: String,
168
2544
    value: String,
169
2544
) -> Uuid {
170
2544
    let tag = Tag {
171
2544
        id: Uuid::new_v4(),
172
2544
        tag_name: name,
173
2544
        tag_value: value,
174
2544
        description: None,
175
2544
    };
176
2544
    let tag_id = tag.id;
177
2544
    match index_table.get(&(parent_idx as u32)) {
178
        Some(&(EntityType::Transaction, tx_id)) => {
179
1443
            tracing::debug!(
180
                "script: create tag \"{}\"=\"{}\" on transaction {tx_id}",
181
                tag.tag_name,
182
                tag.tag_value
183
            );
184
1443
            state.transaction_tags.push(tag);
185
        }
186
        Some(&(EntityType::Split, split_id)) => {
187
1101
            tracing::debug!(
188
                "script: create tag \"{}\"=\"{}\" on split {split_id}",
189
                tag.tag_name,
190
                tag.tag_value
191
            );
192
1101
            state.split_tags.push((split_id, tag));
193
        }
194
        _ => tracing::warn!("Tag parent_idx {parent_idx} not found in index table"),
195
    }
196
2544
    state.created_tags.insert(tag_id);
197
2544
    tag_id
198
2544
}
199

            
200
fn create_split(state: &mut TransactionState, data: EntityData) -> Uuid {
201
    let split_id = Uuid::new_v4();
202
    if let EntityData::Split {
203
        account_id,
204
        commodity_id,
205
        value_num,
206
        value_denom,
207
        reconcile_state,
208
        reconcile_date,
209
    } = data
210
    {
211
        let account_id = Uuid::from_bytes(account_id);
212
        tracing::debug!(
213
            "script: create split {split_id} account={account_id} value={value_num}/{value_denom}"
214
        );
215
        state.splits.push(Split {
216
            id: split_id,
217
            tx_id: state.transaction.id,
218
            account_id,
219
            commodity_id: Uuid::from_bytes(commodity_id),
220
            value_num,
221
            value_denom,
222
            reconcile_state: reconciled(reconcile_state),
223
            reconcile_date: reconciled_at(reconcile_date),
224
            lot_id: None,
225
        });
226
    }
227
    split_id
228
}
229

            
230
fn update_split(state: &mut TransactionState, split_id: Uuid, data: EntityData) {
231
    if let EntityData::Split {
232
        account_id,
233
        commodity_id,
234
        value_num,
235
        value_denom,
236
        reconcile_state,
237
        reconcile_date,
238
    } = data
239
        && let Some(split) = state.splits.iter_mut().find(|s| s.id == split_id)
240
    {
241
        tracing::debug!("script: update split {split_id} value={value_num}/{value_denom}");
242
        split.account_id = Uuid::from_bytes(account_id);
243
        split.commodity_id = Uuid::from_bytes(commodity_id);
244
        split.value_num = value_num;
245
        split.value_denom = value_denom;
246
        split.reconcile_state = reconciled(reconcile_state);
247
        split.reconcile_date = reconciled_at(reconcile_date);
248
    }
249
}
250

            
251
fn reconciled(state: u8) -> Option<bool> {
252
    (state != 0).then_some(true)
253
}
254

            
255
fn reconciled_at(millis: i64) -> Option<DateTime<Utc>> {
256
    (millis != 0).then(|| millis_to_datetime(millis))
257
}
258

            
259
/// Drop one tag occurrence; a loaded one is remembered for the write-back.
260
8
fn delete_tag_link(state: &mut TransactionState, link: TagLink) {
261
8
    let removed = match link {
262
        TagLink::Transaction(tag_id) => {
263
6
            remove_first(&mut state.transaction_tags, |tag| tag.id == tag_id)
264
        }
265
4
        TagLink::Split(split_id, tag_id) => remove_first(&mut state.split_tags, |(id, tag)| {
266
4
            (*id, tag.id) == (split_id, tag_id)
267
4
        }),
268
    };
269
8
    if !removed || state.created_tags.remove(&link.tag_id()) {
270
1
        return;
271
7
    }
272
7
    match link {
273
        TagLink::Transaction(tag_id) => {
274
3
            state.deleted_transaction_tags.insert(tag_id);
275
        }
276
        TagLink::Split(split_id, tag_id) => {
277
4
            state.deleted_split_tags.insert((split_id, tag_id));
278
        }
279
    }
280
8
}
281

            
282
8
fn remove_first<T>(items: &mut Vec<T>, matches: impl Fn(&T) -> bool) -> bool {
283
8
    match items.iter().position(matches) {
284
        Some(index) => {
285
7
            items.remove(index);
286
7
            true
287
        }
288
1
        None => false,
289
    }
290
8
}
291

            
292
1
pub(super) fn millis_to_datetime(millis: i64) -> DateTime<Utc> {
293
1
    Utc.timestamp_millis_opt(millis)
294
1
        .single()
295
1
        .unwrap_or_default()
296
1
}