1
use std::collections::HashMap;
2

            
3
use chrono::{DateTime, TimeZone, Utc};
4
use finance::{price::Price, split::Split};
5
use sqlx::types::Uuid;
6

            
7
use super::super::super::{CmdResult, commodity::CreateCommodity, transaction::CreateTransaction};
8
use super::super::super::{FinanceEntity, account::CreateAccount, account::SetAccountTag};
9
use crate::user::User;
10

            
11
73701
pub fn at(y: i32, mo: u32, d: u32, h: u32, mi: u32, s: u32) -> DateTime<Utc> {
12
73701
    Utc.with_ymd_and_hms(y, mo, d, h, mi, s)
13
73701
        .single()
14
73701
        .unwrap_or(DateTime::<Utc>::MIN_UTC)
15
73701
}
16

            
17
/// The one ledger every report fixture reads.
18
pub struct Ledger {
19
    pub user: User,
20
    commodities: HashMap<&'static str, Uuid>,
21
    accounts: HashMap<&'static str, Uuid>,
22
}
23

            
24
pub type Leg = (&'static str, &'static str, i64, i64);
25

            
26
impl Ledger {
27
174185
    pub fn commodity(&self, symbol: &str) -> Uuid {
28
174185
        self.commodities.get(symbol).copied().unwrap_or_default()
29
174185
    }
30

            
31
210199
    pub fn account(&self, name: &str) -> Uuid {
32
210199
        self.accounts.get(name).copied().unwrap_or_default()
33
210199
    }
34

            
35
1267
    pub fn symbol(&self, id: Uuid) -> String {
36
1267
        self.commodities
37
1267
            .iter()
38
3430
            .find_map(|(symbol, cid)| (*cid == id).then(|| (*symbol).to_owned()))
39
            .unwrap_or_else(|| "<unknown>".to_owned())
40
1267
    }
41

            
42
18372
    async fn commodity_new(&mut self, symbol: &'static str) -> anyhow::Result<()> {
43
18372
        let result = CreateCommodity::new()
44
18372
            .symbol(symbol.to_owned())
45
18372
            .name(symbol.to_owned())
46
18372
            .user_id(self.user.id)
47
18372
            .run()
48
18372
            .await?;
49
18372
        let Some(CmdResult::String(id)) = result else {
50
            anyhow::bail!("commodity {symbol} not created");
51
        };
52
18372
        self.commodities.insert(symbol, Uuid::parse_str(&id)?);
53
18372
        Ok(())
54
18372
    }
55

            
56
85736
    async fn account_new(
57
85736
        &mut self,
58
85736
        name: &'static str,
59
85736
        parent: Option<&str>,
60
85736
        kind: Option<&str>,
61
85736
    ) -> anyhow::Result<()> {
62
85736
        let mut cmd = CreateAccount::new()
63
85736
            .name(name.to_owned())
64
85736
            .user_id(self.user.id);
65
85736
        if let Some(parent) = parent {
66
61240
            cmd = cmd.parent(self.account(parent));
67
24496
        }
68
85736
        let Some(CmdResult::Entity(FinanceEntity::Account(account))) = cmd.run().await? else {
69
            anyhow::bail!("account {name} not created");
70
        };
71
85736
        self.accounts.insert(name, account.id);
72
85736
        if let Some(kind) = kind {
73
73488
            SetAccountTag::new()
74
73488
                .user_id(self.user.id)
75
73488
                .account_id(account.id)
76
73488
                .tag_name("type".to_owned())
77
73488
                .tag_value(kind.to_owned())
78
73488
                .run()
79
73488
                .await?;
80
12248
        }
81
85736
        Ok(())
82
85736
    }
83

            
84
    /// Posts a balanced transaction of `legs` at `when`.
85
74028
    pub async fn post(
86
74028
        &self,
87
74028
        when: DateTime<Utc>,
88
74028
        legs: &[Leg],
89
74028
    ) -> anyhow::Result<(Uuid, Vec<Uuid>)> {
90
74028
        let tx_id = Uuid::new_v4();
91
74028
        let splits: Vec<Split> = legs
92
74028
            .iter()
93
            .map(|&(account, commodity, value_num, value_denom)| Split {
94
148056
                id: Uuid::new_v4(),
95
148056
                tx_id,
96
148056
                account_id: self.account(account),
97
148056
                commodity_id: self.commodity(commodity),
98
148056
                value_num,
99
148056
                value_denom,
100
148056
                reconcile_state: None,
101
148056
                reconcile_date: None,
102
148056
                lot_id: None,
103
148056
            })
104
            .collect();
105
148056
        let split_ids = splits.iter().map(|s| s.id).collect();
106
74028
        CreateTransaction::new()
107
74028
            .user_id(self.user.id)
108
74028
            .splits(splits.into_iter().map(FinanceEntity::Split).collect())
109
74028
            .id(tx_id)
110
74028
            .post_date(when)
111
74028
            .enter_date(when)
112
74028
            .run()
113
74028
            .await?;
114
74028
        Ok((tx_id, split_ids))
115
74028
    }
116

            
117
61240
    async fn tag_tx(&self, tx_id: Uuid, name: &str, value: &str) -> anyhow::Result<()> {
118
61240
        self.user
119
61240
            .create_transaction_tag(tx_id, name.to_owned(), value.to_owned(), None)
120
61240
            .await?;
121
61240
        Ok(())
122
61240
    }
123

            
124
12248
    async fn tag_split(&self, split_id: Uuid, value: &str) -> anyhow::Result<()> {
125
12248
        self.user
126
12248
            .create_split_tag(split_id, "category".to_owned(), value.to_owned(), None)
127
12248
            .await?;
128
12248
        Ok(())
129
12248
    }
130

            
131
12248
    async fn price_eur_usd(&self, split_id: Uuid, when: DateTime<Utc>) -> anyhow::Result<()> {
132
12248
        let price = Price {
133
12248
            id: Uuid::new_v4(),
134
12248
            date: when,
135
12248
            commodity_id: self.commodity("EUR"),
136
12248
            currency_id: self.commodity("USD"),
137
12248
            commodity_split: Some(split_id),
138
12248
            currency_split: None,
139
12248
            value_num: 6,
140
12248
            value_denom: 5,
141
12248
        };
142
12248
        let mut conn = self.user.get_connection().await?;
143
12248
        sqlx::query_file!(
144
            "sql/insert/prices/price.sql",
145
            price.id,
146
            price.commodity_id,
147
            price.currency_id,
148
            price.commodity_split,
149
            price.currency_split,
150
            price.date,
151
            price.value_num,
152
            price.value_denom
153
        )
154
12248
        .execute(&mut *conn)
155
12248
        .await?;
156
12248
        Ok(())
157
12248
    }
158
}
159

            
160
/// USD and EUR (priced EUR to USD at 6/5, per split), JPY (never priced),
161
/// three account levels, and dates on month, quarter and year edges.
162
6124
pub async fn seed(user: User) -> anyhow::Result<Ledger> {
163
6124
    let mut l = Ledger {
164
6124
        user,
165
6124
        commodities: HashMap::new(),
166
6124
        accounts: HashMap::new(),
167
6124
    };
168
6124
    for symbol in ["USD", "EUR", "JPY"] {
169
18372
        l.commodity_new(symbol).await?;
170
    }
171
6124
    let tree = [
172
6124
        ("Assets", None, Some("asset")),
173
6124
        ("Bank", Some("Assets"), Some("asset")),
174
6124
        ("Checking", Some("Bank"), Some("asset")),
175
6124
        ("Savings", Some("Bank"), Some("asset")),
176
6124
        ("Income", None, Some("income")),
177
6124
        ("Work", Some("Income"), Some("income")),
178
6124
        ("Salary", Some("Work"), Some("income")),
179
6124
        ("Expenses", None, Some("expense")),
180
6124
        ("Living", Some("Expenses"), Some("expense")),
181
6124
        ("Food", Some("Living"), Some("expense")),
182
6124
        ("Rent", Some("Living"), Some("expense")),
183
6124
        ("Leisure", Some("Expenses"), Some("expense")),
184
6124
        ("Equity", None, None),
185
6124
        ("Opening", Some("Equity"), None),
186
6124
    ];
187
6124
    for (name, parent, kind) in tree {
188
85736
        l.account_new(name, parent, kind).await?;
189
    }
190

            
191
6124
    l.post(
192
6124
        at(2024, 12, 31, 23, 59, 59),
193
6124
        &[("Checking", "USD", 1000, 1), ("Opening", "USD", -1000, 1)],
194
6124
    )
195
6124
    .await?;
196

            
197
6124
    let (tx, _) = l
198
6124
        .post(
199
6124
            at(2025, 1, 1, 0, 0, 0),
200
6124
            &[("Checking", "USD", 3000, 1), ("Salary", "USD", -3000, 1)],
201
6124
        )
202
6124
        .await?;
203
6124
    l.tag_tx(tx, "category", "salary").await?;
204

            
205
6124
    let (tx, splits) = l
206
6124
        .post(
207
6124
            at(2025, 1, 15, 12, 0, 0),
208
6124
            &[
209
6124
                ("Food", "USD", 12050, 100),
210
6124
                ("Checking", "USD", -12050, 100),
211
6124
            ],
212
6124
        )
213
6124
        .await?;
214
6124
    l.tag_tx(tx, "category", "groceries").await?;
215
6124
    l.tag_split(splits[0], "food").await?;
216

            
217
6124
    let (tx, _) = l
218
6124
        .post(
219
6124
            at(2025, 1, 31, 23, 59, 59),
220
6124
            &[("Rent", "USD", 800, 1), ("Checking", "USD", -800, 1)],
221
6124
        )
222
6124
        .await?;
223
6124
    l.tag_tx(tx, "category", "housing").await?;
224
6124
    l.tag_tx(tx, "project", "home").await?;
225

            
226
6124
    l.post(
227
6124
        at(2025, 2, 1, 0, 0, 0),
228
6124
        &[("Food", "USD", 45, 1), ("Checking", "USD", -45, 1)],
229
6124
    )
230
6124
    .await?;
231

            
232
6124
    l.post(
233
6124
        at(2025, 2, 5, 9, 0, 0),
234
6124
        &[("Savings", "USD", 500, 1), ("Checking", "USD", -500, 1)],
235
6124
    )
236
6124
    .await?;
237

            
238
6124
    let when = at(2025, 2, 10, 12, 0, 0);
239
6124
    let (tx, splits) = l
240
6124
        .post(
241
6124
            when,
242
6124
            &[("Leisure", "EUR", 60, 1), ("Savings", "EUR", -60, 1)],
243
6124
        )
244
6124
        .await?;
245
6124
    l.tag_tx(tx, "category", "fun").await?;
246
6124
    for split in splits {
247
12248
        l.price_eur_usd(split, when).await?;
248
    }
249

            
250
6124
    let (_, splits) = l
251
6124
        .post(
252
6124
            at(2025, 3, 31, 23, 59, 59),
253
6124
            &[("Food", "USD", 30, 1), ("Checking", "USD", -30, 1)],
254
6124
        )
255
6124
        .await?;
256
6124
    l.tag_split(splits[0], "food").await?;
257

            
258
6124
    let (tx, _) = l
259
6124
        .post(
260
6124
            at(2025, 4, 1, 0, 0, 0),
261
6124
            &[("Checking", "USD", 3000, 1), ("Salary", "USD", -3000, 1)],
262
6124
        )
263
6124
        .await?;
264
6124
    l.tag_tx(tx, "category", "salary").await?;
265

            
266
6124
    let (tx, _) = l
267
6124
        .post(
268
6124
            at(2025, 6, 15, 12, 0, 0),
269
6124
            &[("Rent", "USD", 800, 1), ("Checking", "USD", -800, 1)],
270
6124
        )
271
6124
        .await?;
272
6124
    l.tag_tx(tx, "category", "housing").await?;
273
6124
    l.tag_tx(tx, "project", "home").await?;
274

            
275
6124
    let (tx, _) = l
276
6124
        .post(
277
6124
            at(2025, 12, 20, 12, 0, 0),
278
6124
            &[("Leisure", "JPY", 5000, 1), ("Savings", "JPY", -5000, 1)],
279
6124
        )
280
6124
        .await?;
281
6124
    l.tag_tx(tx, "category", "fun").await?;
282

            
283
6124
    let (tx, _) = l
284
6124
        .post(
285
6124
            at(2026, 1, 1, 0, 0, 0),
286
6124
            &[("Food", "USD", 10, 1), ("Checking", "USD", -10, 1)],
287
6124
        )
288
6124
        .await?;
289
6124
    l.tag_tx(tx, "category", "food").await?;
290
6124
    Ok(l)
291
6124
}