1
//! Tag handling for `UpdateTransaction`, run inside the command's DB transaction.
2

            
3
use std::collections::{BTreeMap, HashMap, HashSet};
4

            
5
use finance::price::Price;
6
use finance::split::Split;
7
use finance::tag::{Tag, insert_split_tags};
8
use sqlx::PgConnection;
9
use uuid::Uuid;
10

            
11
use super::tag_replace::unchanged;
12
use super::{CmdError, FinanceEntity};
13
use crate::logical::is_note;
14
use crate::split::split_tags_of;
15
use crate::tag::lock::{Key, KeyChanged};
16

            
17
/// Reject non-tag entities, blank tags and `note` entries in `tags`.
18
182483
pub(super) fn validate_edit_tags(
19
182483
    tags: Option<&HashMap<String, FinanceEntity>>,
20
182483
    split_tags: Option<&[(Uuid, Tag)]>,
21
182483
) -> Result<(), CmdError> {
22
182483
    for entity in tags.into_iter().flat_map(HashMap::values) {
23
46836
        let FinanceEntity::Tag(tag) = entity else {
24
3
            return Err(CmdError::Args("Invalid entity type in tags".to_string()));
25
        };
26
46833
        if is_note(tag) {
27
3
            return Err(CmdError::Args(
28
3
                "The note tag can only be changed with the note argument".to_string(),
29
3
            ));
30
46830
        }
31
46830
        if tag.is_blank() {
32
4
            return Err(CmdError::Args(
33
4
                "Tag name and value must not be blank".to_string(),
34
4
            ));
35
46826
        }
36
    }
37
182473
    let split_tags = split_tags.unwrap_or_default();
38
182473
    if split_tags.iter().any(|(_, tag)| tag.is_blank()) {
39
1
        return Err(CmdError::Args(
40
1
            "Tag name and value must not be blank".to_string(),
41
1
        ));
42
182472
    }
43
182472
    let mut seen: HashMap<(Uuid, &str), &Tag> = HashMap::new();
44
182472
    let conflicting = split_tags.iter().any(|(split, tag)| {
45
79507
        seen.insert((*split, tag.normalized().0), tag)
46
3
            .is_some_and(|prev| {
47
3
                (prev.normalized().1, &prev.description) != (tag.normalized().1, &tag.description)
48
3
            })
49
79507
    });
50
182472
    if conflicting {
51
1
        return Err(CmdError::Args(
52
1
            "A split cannot carry two tags with the same name".to_string(),
53
1
        ));
54
182471
    }
55
182471
    Ok(())
56
182483
}
57

            
58
/// Every tag row the edit writes: transaction tags, split tags and the note.
59
23664
fn written_tags<'a>(
60
23664
    tags: Option<&'a HashMap<String, FinanceEntity>>,
61
23664
    split_tags: Option<&'a [(Uuid, Tag)]>,
62
23664
    note_tag: Option<&'a Tag>,
63
23664
) -> Vec<&'a Tag> {
64
23664
    let transaction_tags = tags
65
23664
        .into_iter()
66
23664
        .flat_map(HashMap::values)
67
19936
        .filter_map(|e| match e {
68
19934
            FinanceEntity::Tag(tag) => Some(tag),
69
2
            _ => None,
70
19936
        });
71
23664
    let split_tags = split_tags.unwrap_or_default().iter().map(|(_, tag)| tag);
72
23664
    transaction_tags.chain(split_tags).chain(note_tag).collect()
73
23664
}
74

            
75
23664
fn written_note(note: Option<&str>) -> Option<Tag> {
76
23664
    note.filter(|n| !n.trim().is_empty()).map(note_tag)
77
23664
}
78

            
79
/// Lock, until commit, every tag the edit reads for its revision or writes;
80
/// returns the ids of the tags linked before the edit.
81
23664
pub(super) async fn lock_edit_tags(
82
23664
    conn: &mut PgConnection,
83
23664
    transaction_id: Uuid,
84
23664
    tags: Option<&HashMap<String, FinanceEntity>>,
85
23664
    split_tags: Option<&[(Uuid, Tag)]>,
86
23664
    note: Option<&str>,
87
23664
) -> Result<Result<Vec<Uuid>, KeyChanged>, sqlx::Error> {
88
6456
    let note_tag = written_note(note);
89
6456
    let written = written_tags(tags, split_tags, note_tag.as_ref());
90
6456
    lock_tag_keys(conn, transaction_id, &written).await
91
6456
}
92

            
93
/// Lock, until commit, every tag linked to the transaction or its splits and
94
/// every tag in `written` through the tag lock protocol, so a concurrent
95
/// writer of a shared tag either commits before the revision is recomputed or
96
/// waits. Returns the ids of the linked tags.
97
102625
pub(crate) async fn lock_tag_keys(
98
102625
    conn: &mut PgConnection,
99
102625
    transaction_id: Uuid,
100
102625
    written: &[&Tag],
101
102625
) -> Result<Result<Vec<Uuid>, KeyChanged>, sqlx::Error> {
102
102625
    let linked = linked_tags(conn, transaction_id).await?;
103
102625
    Ok(crate::tag::lock::lock(conn, &linked, written)
104
102625
        .await?
105
102594
        .map(|()| linked.into_iter().map(|(id, _)| id).collect()))
106
102625
}
107

            
108
/// The id and stored key of every tag the transaction or its splits link.
109
103576
pub(crate) async fn linked_tags(
110
103576
    conn: &mut PgConnection,
111
103576
    transaction_id: Uuid,
112
103576
) -> Result<Vec<(Uuid, Key)>, sqlx::Error> {
113
103576
    Ok(sqlx::query_file!(
114
103576
        "sql/select/tags/by_transaction_and_splits.sql",
115
        transaction_id
116
    )
117
103576
    .fetch_all(conn)
118
103576
    .await?
119
    .into_iter()
120
78405
    .map(|row| (row.tag_id, (row.tag_name, row.tag_value)))
121
    .collect())
122
103576
}
123

            
124
30091
pub(super) fn note_tag(value: &str) -> Tag {
125
30091
    Tag {
126
30091
        id: Uuid::new_v4(),
127
30091
        tag_name: "note".to_string(),
128
30091
        tag_value: value.to_string(),
129
30091
        description: None,
130
30091
    }
131
30091
}
132

            
133
17675
async fn unlink_tag(
134
17675
    conn: &mut PgConnection,
135
17675
    transaction_id: Uuid,
136
17675
    tag_id: Uuid,
137
17675
) -> Result<(), CmdError> {
138
7765
    sqlx::query_file!(
139
        "sql/delete/transaction_tags/by_pair.sql",
140
        &transaction_id,
141
        &tag_id
142
    )
143
7765
    .execute(conn)
144
7765
    .await?;
145
7765
    Ok(())
146
7765
}
147

            
148
/// Unlink the transaction's note tags (`notes`) or all its other tags.
149
16755
pub(super) async fn unlink_tags(
150
16755
    conn: &mut PgConnection,
151
16755
    transaction_id: Uuid,
152
16755
    notes: bool,
153
16755
) -> Result<(), CmdError> {
154
5514
    let linked = sqlx::query_file_as!(Tag, "sql/select/tags/by_transaction.sql", &transaction_id)
155
5514
        .fetch_all(&mut *conn)
156
5514
        .await?;
157
17999
    for tag in linked.iter().filter(|tag| is_note(tag) == notes) {
158
5491
        unlink_tag(conn, transaction_id, tag.id).await?;
159
    }
160
5514
    Ok(())
161
5514
}
162

            
163
/// Replace all non-note transaction tags with `tags`. A stored link that
164
/// already holds the wanted tag stays as it is; only the others are unlinked
165
/// and upserted. The caller deletes the tag rows this leaves unreferenced.
166
16542
pub(super) async fn replace_transaction_tags(
167
16542
    conn: &mut PgConnection,
168
16542
    transaction_id: Uuid,
169
16542
    tags: &HashMap<String, FinanceEntity>,
170
16542
) -> Result<(), CmdError> {
171
5838
    let stored = sqlx::query_file_as!(Tag, "sql/select/tags/by_transaction.sql", &transaction_id)
172
5838
        .fetch_all(&mut *conn)
173
5838
        .await?;
174
5838
    let mut held: BTreeMap<&str, Vec<&Tag>> = BTreeMap::new();
175
20286
    for tag in stored.iter().filter(|tag| !is_note(tag)) {
176
14793
        held.entry(tag.normalized().0).or_default().push(tag);
177
    }
178
5838
    let mut changed: Vec<&Tag> = Vec::new();
179
5838
    for entity in tags.values() {
180
14333
        let FinanceEntity::Tag(tag) = entity else {
181
            return Err(CmdError::Args("Invalid entity type in tags".to_string()));
182
        };
183
14333
        match held.remove(tag.normalized().0) {
184
12865
            Some(same) if unchanged(&same, tag) => {}
185
            Some(other) => {
186
346
                for stale in other {
187
346
                    unlink_tag(conn, transaction_id, stale.id).await?;
188
                }
189
346
                changed.push(tag);
190
            }
191
1468
            None => changed.push(tag),
192
        }
193
    }
194
5838
    for stale in held.into_values().flatten() {
195
1928
        unlink_tag(conn, transaction_id, stale.id).await?;
196
    }
197
5838
    for tag in changed {
198
1814
        let tag_id = tag.commit(&mut *conn).await?;
199
1814
        sqlx::query_file!(
200
            "sql/insert/transaction_tags/transaction_tag.sql",
201
            transaction_id,
202
            tag_id
203
        )
204
1814
        .execute(&mut *conn)
205
1814
        .await?;
206
    }
207
5838
    Ok(())
208
5838
}
209

            
210
/// The split tags linked to the transaction's splits, with their split ids.
211
7452
pub(super) async fn stored_split_tags(
212
7452
    conn: &mut PgConnection,
213
7452
    transaction_id: Uuid,
214
7452
) -> Result<Vec<(Uuid, Tag)>, CmdError> {
215
4247
    Ok(sqlx::query_file!(
216
4247
        "sql/select/tags/split_links_by_transaction.sql",
217
        transaction_id
218
    )
219
4247
    .fetch_all(conn)
220
4247
    .await?
221
    .into_iter()
222
13973
    .map(|row| {
223
13973
        let tag = Tag {
224
13973
            id: row.id,
225
13973
            tag_name: row.tag_name,
226
13973
            tag_value: row.tag_value,
227
13973
            description: row.description,
228
13973
        };
229
13973
        (row.split_id, tag)
230
13973
    })
231
    .collect())
232
4247
}
233

            
234
/// Attach `split_tags` to the transaction's current splits.
235
/// The splits are new, so a `stored` split tag (of any old split) that already
236
/// holds the wanted tag is relinked as it is, without touching the shared row.
237
7451
pub(super) async fn add_split_tags(
238
7451
    conn: &mut PgConnection,
239
7451
    transaction_id: Uuid,
240
7451
    split_tags: &[(Uuid, Tag)],
241
7451
    stored: &[(Uuid, Tag)],
242
7451
) -> Result<(), CmdError> {
243
    let split_ids: HashSet<Uuid> =
244
4246
        sqlx::query_file!("sql/select/splits/by_transaction.sql", transaction_id)
245
4246
            .fetch_all(&mut *conn)
246
4246
            .await?
247
            .into_iter()
248
15224
            .map(|row| row.id)
249
            .collect();
250

            
251
13195
    if split_tags.iter().any(|(id, _)| !split_ids.contains(id)) {
252
1
        return Err(CmdError::Args(
253
1
            "Split tag references a split that is not part of this transaction".to_string(),
254
1
        ));
255
4245
    }
256
4245
    let mut changed: Vec<(Uuid, Tag)> = Vec::new();
257
4245
    for (split_id, tag) in split_tags {
258
13194
        let mut held: Vec<&Tag> = stored
259
13194
            .iter()
260
            .map(|(_, held)| held)
261
46999
            .filter(|held| held.normalized() == tag.normalized())
262
            .collect();
263
25847
        held.dedup_by_key(|held| held.id);
264
13194
        match (unchanged(&held, tag), held.first()) {
265
            (true, Some(same)) => {
266
13007
                sqlx::query_file!("sql/insert/split_tags/split_tag.sql", split_id, same.id)
267
13007
                    .execute(&mut *conn)
268
13007
                    .await?;
269
            }
270
187
            _ => changed.push((*split_id, tag.clone())),
271
        }
272
    }
273
4245
    insert_split_tags(conn, &changed).await?;
274
4245
    Ok(())
275
4246
}
276

            
277
/// The locked transaction as stored: the data its revision digests.
278
pub(crate) struct StoredState {
279
    pub(crate) revision: String,
280
    pub(crate) tags: Vec<Tag>,
281
    pub(crate) splits: Vec<Split>,
282
    pub(crate) split_tags: HashMap<Uuid, Vec<Tag>>,
283
    pub(crate) prices: Vec<Price>,
284
}
285

            
286
impl StoredState {
287
    /// `Unkeepable` with the reason when the logical form cannot keep the transaction.
288
18904
    pub(crate) fn ensure_keepable(&self) -> Result<(), CmdError> {
289
18904
        crate::logical::form_refusal(&self.tags, &self.splits, &self.split_tags, &self.prices)
290
18904
            .map_err(CmdError::Unkeepable)
291
18904
    }
292
}
293

            
294
/// The locked transaction's stored data with its revision: the note as
295
/// `GetTransactionDetail` presents it, every other transaction tag and every
296
/// split tag.
297
22199
pub(crate) async fn stored_state(
298
22199
    conn: &mut PgConnection,
299
22199
    transaction_id: Uuid,
300
22199
    post_date: chrono::DateTime<chrono::Utc>,
301
22199
) -> Result<StoredState, sqlx::Error> {
302
    let tags: Vec<Tag> =
303
22199
        sqlx::query_file_as!(Tag, "sql/select/tags/by_transaction.sql", transaction_id)
304
22199
            .fetch_all(&mut *conn)
305
22199
            .await?;
306
22199
    let splits: Vec<Split> = sqlx::query_file_as!(
307
        Split,
308
22199
        "sql/select/splits/by_transaction.sql",
309
        transaction_id
310
    )
311
22199
    .fetch_all(&mut *conn)
312
22199
    .await?;
313
22199
    let split_tags = split_tags_of(&mut *conn, &splits).await?;
314
22199
    let prices = transaction_prices(conn, transaction_id).await?;
315
    let revision =
316
22199
        crate::logical::stored_revision(post_date, tags.clone(), &splits, &split_tags, &prices);
317
22199
    Ok(StoredState {
318
22199
        revision,
319
22199
        tags,
320
22199
        splits,
321
22199
        split_tags,
322
22199
        prices,
323
22199
    })
324
22199
}
325

            
326
/// The revision of the locked transaction.
327
947
pub(crate) async fn current_revision(
328
947
    conn: &mut PgConnection,
329
947
    transaction_id: Uuid,
330
947
    post_date: chrono::DateTime<chrono::Utc>,
331
947
) -> Result<String, sqlx::Error> {
332
947
    Ok(stored_state(conn, transaction_id, post_date)
333
947
        .await?
334
        .revision)
335
947
}
336

            
337
/// The prices of the transaction's splits.
338
24778
pub(crate) async fn transaction_prices(
339
24778
    conn: &mut PgConnection,
340
24778
    transaction_id: Uuid,
341
24778
) -> Result<Vec<Price>, sqlx::Error> {
342
    Ok(
343
24778
        sqlx::query_file!("sql/select/prices/by_transaction.sql", transaction_id)
344
24778
            .fetch_all(conn)
345
24778
            .await?
346
            .into_iter()
347
            .map(|row| Price {
348
7252
                id: row.id,
349
7252
                date: row.price_date,
350
7252
                commodity_id: row.commodity_id,
351
7252
                currency_id: row.currency_id,
352
7252
                commodity_split: row.commodity_split_id,
353
7252
                currency_split: row.currency_split_id,
354
7252
                value_num: row.value_num,
355
7252
                value_denom: row.value_denom,
356
7252
            })
357
            .collect(),
358
    )
359
24778
}