1
//! Loading a stored transaction into a [`TransactionState`] for the batch runner.
2

            
3
use std::collections::HashMap;
4

            
5
use finance::split::Split;
6
use finance::tag::Tag;
7
use sqlx::types::Uuid;
8

            
9
use super::TransactionState;
10
use crate::command::transaction_edit::transaction_prices;
11
use crate::command::{CmdResult, FinanceEntity};
12
use crate::error::ServerError;
13
use crate::user::User;
14

            
15
/// Builds a [`TransactionState`] for a single transaction id: the
16
/// transaction, its splits, and every stored transaction and split tag, so
17
/// script guards see what is already there, with the revision of exactly
18
/// what was loaded for the write-back to verify.
19
///
20
/// # Errors
21
/// A failing read.
22
2579
pub async fn load_transaction_state(
23
2579
    user_id: Uuid,
24
2579
    transaction_id: Uuid,
25
2579
) -> Result<Option<TransactionState>, ServerError> {
26
    use crate::command::transaction::GetTransaction;
27

            
28
2579
    let tx_result = GetTransaction::new()
29
2579
        .user_id(user_id)
30
2579
        .transaction_id(transaction_id)
31
2579
        .run()
32
2579
        .await
33
        .map_err(|e| ServerError::Script(format!("get-transaction {transaction_id}: {e:?}")))?;
34
2579
    let Some(CmdResult::TaggedTransactions { mut entities, .. }) = tx_result else {
35
        return Ok(None);
36
    };
37
2579
    let Some((FinanceEntity::Transaction(tx), _, _amount)) = entities.pop() else {
38
        return Ok(None);
39
    };
40

            
41
2579
    let user = User { id: user_id };
42
2579
    let splits = user.get_transaction_splits(transaction_id).await?;
43
2579
    let transaction_tags = user.get_transaction_tags(transaction_id).await?;
44
2579
    let split_tags = user.split_tags_of(&splits).await?;
45
2579
    let prices = load_prices(&user, transaction_id).await?;
46
2399
    let revision = crate::logical::stored_revision(
47
2399
        tx.post_date,
48
2399
        transaction_tags.clone(),
49
2399
        &splits,
50
2399
        &split_tags,
51
2399
        &prices,
52
2399
    );
53
2399
    let split_tags = flatten_split_tags(&splits, split_tags);
54
2399
    let split_entities: Vec<FinanceEntity> = splits.into_iter().map(FinanceEntity::Split).collect();
55
2399
    let account_names = load_account_names(user_id, &split_entities).await?;
56

            
57
2399
    let mut state = TransactionState::new(tx)
58
2399
        .with(split_entities)
59
2399
        .with_split_tags(split_tags)
60
2399
        .with_account_names(account_names);
61
2399
    state.transaction_tags = transaction_tags;
62
2399
    state.loaded_revision = Some(revision);
63
2399
    Ok(Some(state))
64
2579
}
65

            
66
2579
async fn load_prices(
67
2579
    user: &User,
68
2579
    transaction_id: Uuid,
69
2579
) -> Result<Vec<finance::price::Price>, ServerError> {
70
2579
    let mut conn = user.get_connection().await?;
71
2579
    transaction_prices(&mut conn, transaction_id)
72
2579
        .await
73
180
        .map_err(|err| ServerError::DB(crate::db::DBError::Sqlx(err)))
74
2579
}
75

            
76
/// Every stored tag of every split, with its split id, in split order.
77
2399
fn flatten_split_tags(splits: &[Split], mut by_split: HashMap<Uuid, Vec<Tag>>) -> Vec<(Uuid, Tag)> {
78
2399
    splits
79
2399
        .iter()
80
4854
        .flat_map(|split| {
81
4854
            let tags = by_split.remove(&split.id).unwrap_or_default();
82
4854
            tags.into_iter().map(|tag| (split.id, tag))
83
4854
        })
84
        .collect()
85
2399
}
86

            
87
/// Resolves the display name (the `name` tag) of every distinct posting
88
/// account referenced by `split_entities`, through the public command API.
89
2399
async fn load_account_names(
90
2399
    user_id: Uuid,
91
2399
    split_entities: &[FinanceEntity],
92
2399
) -> Result<HashMap<Uuid, String>, ServerError> {
93
    use crate::command::account::GetAccount;
94

            
95
2399
    let mut names: HashMap<Uuid, String> = HashMap::new();
96
2399
    for entity in split_entities {
97
4854
        let FinanceEntity::Split(split) = entity else {
98
            continue;
99
        };
100
4854
        if names.contains_key(&split.account_id) {
101
56
            continue;
102
4798
        }
103
4798
        let result = GetAccount::new()
104
4798
            .user_id(user_id)
105
4798
            .account_id(split.account_id)
106
4798
            .run()
107
4798
            .await
108
            .map_err(|e| ServerError::Script(format!("get-account {}: {e:?}", split.account_id)))?;
109
4798
        if let Some(CmdResult::TaggedEntities { entities, .. }) = result
110
4798
            && let Some((_, tags)) = entities.first()
111
4798
            && let Some(FinanceEntity::Tag(tag)) = tags.get("name")
112
        {
113
4798
            names.insert(split.account_id, tag.tag_value.clone());
114
        }
115
    }
116
2399
    Ok(names)
117
2399
}