1
//! Writing lowered transaction rows: shared by the logical natives and the
2
//! form path.
3

            
4
use std::collections::HashMap;
5

            
6
use chrono::{DateTime, Utc};
7
use finance::price::Price;
8
use finance::split::Split;
9
use finance::tag::Tag;
10
use forms::FieldError;
11
use server::command::transaction::{CreateTransaction, UpdateTransaction};
12
use server::command::{CmdError, CmdResult, FinanceEntity};
13
use server::logical::{PhysicalSplit, PriceRow, STALE_REVISION};
14
use uuid::Uuid;
15

            
16
use crate::forms::Failure;
17

            
18
/// Physical lowering of a logical payload plus the tags its rows carry.
19
pub(crate) struct Lowered {
20
    pub(crate) splits: Vec<PhysicalSplit>,
21
    pub(crate) prices: Vec<PriceRow>,
22
    pub(crate) split_tags: Vec<(Uuid, Tag)>,
23
}
24

            
25
/// Non-note transaction tags by name.
26
pub(crate) type TransactionTags = HashMap<String, FinanceEntity>;
27

            
28
/// The transaction-level values a create or an update writes.
29
pub(crate) struct Header {
30
    pub(crate) note: Option<String>,
31
    pub(crate) post_date: Option<DateTime<Utc>>,
32
    /// Replaces the non-note transaction tags; `None` leaves them.
33
    pub(crate) tags: Option<TransactionTags>,
34
}
35

            
36
/// Create the transaction for already lowered rows; shared by the logical
37
/// native and the form path.
38
32000
pub(crate) async fn create_lowered(
39
32000
    ctx: &str,
40
32000
    user_id: Uuid,
41
32000
    header: Header,
42
32000
    lowered: Lowered,
43
32000
) -> Result<Uuid, Failure> {
44
32000
    let tx_id = Uuid::new_v4();
45
32000
    let post_date = header.post_date.unwrap_or_else(Utc::now);
46
32000
    let enter_date = Utc::now();
47
32000
    let splits = physical_splits_to_entities(lowered.splits, tx_id);
48
32000
    let mut runner = CreateTransaction::new()
49
32000
        .user_id(user_id)
50
32000
        .id(tx_id)
51
32000
        .post_date(post_date)
52
32000
        .enter_date(enter_date)
53
32000
        .splits(splits);
54
32000
    if let Some(note) = header.note {
55
29068
        runner = runner.note(note);
56
2932
    }
57
32000
    if let Some(tags) = header.tags {
58
19548
        runner = runner.tags(tags);
59
12452
    }
60
32000
    if !lowered.prices.is_empty() {
61
3700
        runner = runner.prices(price_rows_to_entities(lowered.prices, post_date));
62
28300
    }
63
32000
    if !lowered.split_tags.is_empty() {
64
17635
        runner = runner.split_tags(lowered.split_tags);
65
14365
    }
66
32000
    dispatch_tx_result(ctx, runner.run().await)
67
32000
}
68

            
69
/// Replace the splits of a transaction with already lowered rows; shared by
70
/// the logical native and the form path.
71
6000
pub(crate) async fn update_lowered(
72
6000
    ctx: &str,
73
6000
    user_id: Uuid,
74
6000
    transaction_id: Uuid,
75
6000
    header: Header,
76
6000
    lowered: Lowered,
77
6000
    expected_revision: Option<&str>,
78
6000
) -> Result<Uuid, Failure> {
79
    let Header {
80
        note,
81
        post_date,
82
        tags,
83
6000
    } = header;
84
    // A split-only edit must leave the stored dates intact: forward post_date
85
    // only when :date was explicitly provided. The price rows still need a
86
    // fallback observation date when none is given.
87
6000
    let price_date = post_date.unwrap_or_else(Utc::now);
88
6000
    let splits = physical_splits_to_entities(lowered.splits, transaction_id);
89
6000
    let mut runner = UpdateTransaction::new()
90
6000
        .user_id(user_id)
91
6000
        .transaction_id(transaction_id)
92
6000
        .splits(splits)
93
6000
        .refuse_unkeepable(true);
94
6000
    if let Some(post_date) = post_date {
95
5832
        runner = runner.post_date(post_date);
96
168
    }
97
6000
    if let Some(note) = note {
98
5826
        runner = runner.note(note);
99
174
    }
100
6000
    if let Some(tags) = tags {
101
5828
        runner = runner.tags(tags);
102
172
    }
103
6000
    if !lowered.prices.is_empty() {
104
4332
        runner = runner.prices(price_rows_to_entities(lowered.prices, price_date));
105
1668
    }
106
6000
    if !lowered.split_tags.is_empty() {
107
4336
        runner = runner.split_tags(lowered.split_tags);
108
1664
    }
109
6000
    if let Some(revision) = expected_revision {
110
5828
        runner = runner.expected_revision(revision.to_string());
111
172
    }
112
6000
    match runner.run().await {
113
330
        Err(CmdError::Args(message)) if message == STALE_REVISION => {
114
330
            Err(Failure::Invalid(vec![FieldError {
115
330
                field: "revision".to_string(),
116
330
                message,
117
330
            }]))
118
        }
119
5670
        result => dispatch_tx_result(ctx, result),
120
    }
121
6000
}
122

            
123
37691
fn dispatch_tx_result(
124
37691
    ctx: &str,
125
37691
    result: Result<Option<CmdResult>, CmdError>,
126
37691
) -> Result<Uuid, Failure> {
127
37691
    match result {
128
37665
        Ok(Some(CmdResult::Entity(FinanceEntity::Transaction(tx)))) => Ok(tx.id),
129
        Ok(Some(other)) => Err(wasmtime::Error::msg(format!(
130
            "{ctx}: expected Transaction entity, got {other:?}"
131
        ))
132
        .into()),
133
        Ok(None) => Err(wasmtime::Error::msg(format!("{ctx}: command returned no entity")).into()),
134
26
        Err(err) => Err(Failure::from_command(ctx, err)),
135
    }
136
37691
}
137

            
138
/// Convert physical splits to `FinanceEntity::Split` with the given transaction ID.
139
38000
fn physical_splits_to_entities(splits: Vec<PhysicalSplit>, tx_id: Uuid) -> Vec<FinanceEntity> {
140
38000
    splits
141
38000
        .into_iter()
142
85024
        .map(|ps| {
143
85024
            FinanceEntity::Split(Split {
144
85024
                id: ps.id,
145
85024
                tx_id,
146
85024
                account_id: ps.account_id,
147
85024
                commodity_id: ps.commodity_id,
148
85024
                value_num: *ps.value.numer(),
149
85024
                value_denom: *ps.value.denom(),
150
85024
                reconcile_state: ps.reconcile_state,
151
85024
                reconcile_date: None,
152
85024
                lot_id: None,
153
85024
            })
154
85024
        })
155
        .collect()
156
38000
}
157

            
158
/// Convert price rows to `FinanceEntity::Price`, using `post_date` as the
159
/// fallback date when the row carries none.
160
8032
fn price_rows_to_entities(
161
8032
    price_rows: Vec<PriceRow>,
162
8032
    post_date: DateTime<Utc>,
163
8032
) -> Vec<FinanceEntity> {
164
8032
    price_rows
165
8032
        .into_iter()
166
8035
        .map(|pr| {
167
8035
            FinanceEntity::Price(Price {
168
8035
                id: Uuid::new_v4(),
169
8035
                date: pr.date.unwrap_or(post_date),
170
8035
                commodity_id: pr.commodity_id,
171
8035
                currency_id: pr.currency_id,
172
8035
                commodity_split: Some(pr.commodity_split),
173
8035
                currency_split: Some(pr.currency_split),
174
8035
                value_num: pr.value_num,
175
8035
                value_denom: pr.value_denom,
176
8035
            })
177
8035
        })
178
        .collect()
179
8032
}
180

            
181
#[cfg(test)]
182
#[path = "lowering_tests.rs"]
183
mod tests;