1
use super::BalanceReport;
2

            
3
use chrono::NaiveDate;
4
use num_rational::Rational64;
5

            
6
use super::super::{
7
    CmdResult, FinanceEntity, PeriodGrouping, ReportData, ReportFilter, ReportNode,
8
};
9
use crate::{
10
    command::{account::CreateAccount, commodity::CreateCommodity, transaction::CreateTransaction},
11
    db::install_test_pool,
12
};
13
use finance::{price::Price, split::Split};
14
use sqlx::{
15
    PgPool,
16
    types::Uuid,
17
    types::chrono::{DateTime, Utc},
18
};
19
use supp_macro::local_db_sqlx_test;
20
use tokio::sync::OnceCell;
21

            
22
static CONTEXT: OnceCell<()> = OnceCell::const_new();
23
static USER: OnceCell<crate::user::User> = OnceCell::const_new();
24

            
25
26
async fn setup() {
26
26
    CONTEXT
27
26
        .get_or_init(|| async {
28
26
            crate::telemetry::init_test_logging();
29
52
        })
30
26
        .await;
31
52
    USER.get_or_init(|| async { crate::user::User { id: Uuid::new_v4() } })
32
26
        .await;
33
26
}
34

            
35
34
fn extract_commodity_id(result: Option<CmdResult>) -> Uuid {
36
34
    if let Some(CmdResult::String(id)) = result {
37
34
        Uuid::parse_str(&id).unwrap()
38
    } else {
39
        panic!("Expected commodity ID");
40
    }
41
34
}
42

            
43
62
fn extract_account_id(result: Option<CmdResult>) -> Uuid {
44
62
    if let Some(CmdResult::Entity(FinanceEntity::Account(acc))) = result {
45
62
        acc.id
46
    } else {
47
        panic!("Expected account entity");
48
    }
49
62
}
50

            
51
12
fn extract_report(result: Option<CmdResult>) -> ReportData {
52
12
    if let Some(CmdResult::Report(data)) = result {
53
12
        data
54
    } else {
55
        panic!("Expected Report result");
56
    }
57
12
}
58

            
59
33
fn find_node(roots: &[ReportNode], account_id: Uuid) -> Option<&ReportNode> {
60
33
    for node in roots {
61
32
        if node.account_id == account_id {
62
19
            return Some(node);
63
13
        }
64
13
        if let Some(found) = find_node(&node.children, account_id) {
65
6
            return Some(found);
66
7
        }
67
    }
68
8
    None
69
33
}
70

            
71
21
fn node_amount(node: &ReportNode, commodity_id: Uuid) -> Option<Rational64> {
72
21
    node.amounts
73
21
        .iter()
74
22
        .find(|ca| ca.commodity_id == commodity_id)
75
20
        .map(|ca| ca.amount)
76
21
}
77

            
78
34
async fn create_commodity(user_id: Uuid, symbol: &str, name: &str) -> Uuid {
79
34
    extract_commodity_id(
80
34
        CreateCommodity::new()
81
34
            .symbol(symbol.to_string())
82
34
            .name(name.to_string())
83
34
            .user_id(user_id)
84
34
            .run()
85
34
            .await
86
            .unwrap(),
87
    )
88
34
}
89

            
90
62
async fn create_account(user_id: Uuid, name: &str, parent: Option<Uuid>) -> Uuid {
91
62
    match parent {
92
4
        Some(pid) => extract_account_id(
93
4
            CreateAccount::new()
94
4
                .name(name.to_string())
95
4
                .user_id(user_id)
96
4
                .parent(pid)
97
4
                .run()
98
4
                .await
99
                .unwrap(),
100
        ),
101
58
        None => extract_account_id(
102
58
            CreateAccount::new()
103
58
                .name(name.to_string())
104
58
                .user_id(user_id)
105
58
                .run()
106
58
                .await
107
                .unwrap(),
108
        ),
109
    }
110
62
}
111

            
112
47
async fn create_tx(
113
47
    user_id: Uuid,
114
47
    post_date: DateTime<Utc>,
115
47
    splits: Vec<(Uuid, Uuid, i64, i64)>,
116
47
) -> (Uuid, Vec<Uuid>) {
117
47
    let tx_id = Uuid::new_v4();
118
47
    let mut split_ids = Vec::new();
119
47
    let split_entities: Vec<FinanceEntity> = splits
120
47
        .into_iter()
121
97
        .map(|(account_id, commodity_id, value_num, value_denom)| {
122
97
            let sid = Uuid::new_v4();
123
97
            split_ids.push(sid);
124
97
            FinanceEntity::Split(Split {
125
97
                id: sid,
126
97
                tx_id,
127
97
                account_id,
128
97
                commodity_id,
129
97
                value_num,
130
97
                value_denom,
131
97
                reconcile_state: None,
132
97
                reconcile_date: None,
133
97
                lot_id: None,
134
97
            })
135
97
        })
136
        .collect();
137
47
    CreateTransaction::new()
138
47
        .user_id(user_id)
139
47
        .splits(split_entities)
140
47
        .id(tx_id)
141
47
        .post_date(post_date)
142
47
        .enter_date(post_date)
143
47
        .run()
144
47
        .await
145
        .unwrap();
146
47
    (tx_id, split_ids)
147
47
}
148

            
149
13
async fn insert_price(
150
13
    user: &crate::user::User,
151
13
    commodity_split_id: Uuid,
152
13
    commodity_id: Uuid,
153
13
    currency_id: Uuid,
154
13
    date: DateTime<Utc>,
155
13
    value_num: i64,
156
13
    value_denom: i64,
157
13
) {
158
13
    let price = Price {
159
13
        id: Uuid::new_v4(),
160
13
        date,
161
13
        commodity_id,
162
13
        currency_id,
163
13
        commodity_split: Some(commodity_split_id),
164
13
        currency_split: None,
165
13
        value_num,
166
13
        value_denom,
167
13
    };
168
13
    let mut conn = user.get_connection().await.unwrap();
169
13
    sqlx::query_file!(
170
        "sql/insert/prices/price.sql",
171
        price.id,
172
        price.commodity_id,
173
        price.currency_id,
174
        price.commodity_split,
175
        price.currency_split,
176
        price.date,
177
        price.value_num,
178
        price.value_denom
179
    )
180
13
    .execute(&mut *conn)
181
13
    .await
182
    .unwrap();
183
13
}
184

            
185
// --- BalanceReport tests ---
186

            
187
#[local_db_sqlx_test]
188
async fn test_balance_report_single_currency(pool: PgPool) {
189
    let user = USER.get().unwrap();
190
    user.commit().await.expect("Failed to commit user");
191

            
192
    let usd = create_commodity(user.id, "USD", "US Dollar").await;
193
    let assets = create_account(user.id, "Assets", None).await;
194
    let bank = create_account(user.id, "Bank", Some(assets)).await;
195
    let expenses = create_account(user.id, "Expenses", None).await;
196

            
197
    let d = DateTime::<Utc>::from_timestamp(1700000000, 0).unwrap();
198
    create_tx(
199
        user.id,
200
        d,
201
        vec![(bank, usd, -200, 1), (expenses, usd, 200, 1)],
202
    )
203
    .await;
204

            
205
    let report = extract_report(BalanceReport::new().user_id(user.id).run().await.unwrap());
206

            
207
    assert_eq!(report.periods.len(), 1);
208
    assert!(report.periods[0].label.is_none());
209

            
210
    let bank_node = find_node(&report.periods[0].roots, bank).unwrap();
211
    assert_eq!(node_amount(bank_node, usd), Some(Rational64::new(-200, 1)));
212
    assert_eq!(bank_node.depth, 1);
213
    assert_eq!(bank_node.account_path, "Assets:Bank");
214

            
215
    let assets_node = find_node(&report.periods[0].roots, assets).unwrap();
216
    assert_eq!(
217
        node_amount(assets_node, usd),
218
        Some(Rational64::new(-200, 1))
219
    );
220

            
221
    let expenses_node = find_node(&report.periods[0].roots, expenses).unwrap();
222
    assert_eq!(
223
        node_amount(expenses_node, usd),
224
        Some(Rational64::new(200, 1))
225
    );
226
}
227

            
228
#[local_db_sqlx_test]
229
async fn test_balance_report_multi_currency(pool: PgPool) {
230
    let user = USER.get().unwrap();
231
    user.commit().await.expect("Failed to commit user");
232

            
233
    let usd = create_commodity(user.id, "USD", "US Dollar").await;
234
    let eur = create_commodity(user.id, "EUR", "Euro").await;
235
    let acc_a = create_account(user.id, "Account A", None).await;
236
    let acc_b = create_account(user.id, "Account B", None).await;
237

            
238
    let d = DateTime::<Utc>::from_timestamp(1700000000, 0).unwrap();
239
    create_tx(
240
        user.id,
241
        d,
242
        vec![(acc_a, usd, 100, 1), (acc_b, usd, -100, 1)],
243
    )
244
    .await;
245
    create_tx(user.id, d, vec![(acc_a, eur, 50, 1), (acc_b, eur, -50, 1)]).await;
246

            
247
    let report = extract_report(BalanceReport::new().user_id(user.id).run().await.unwrap());
248

            
249
    let node_a = find_node(&report.periods[0].roots, acc_a).unwrap();
250
    assert_eq!(node_a.amounts.len(), 2);
251
    assert_eq!(node_amount(node_a, usd), Some(Rational64::new(100, 1)));
252
    assert_eq!(node_amount(node_a, eur), Some(Rational64::new(50, 1)));
253
}
254

            
255
#[local_db_sqlx_test]
256
async fn test_balance_report_with_conversion(pool: PgPool) {
257
    let user = USER.get().unwrap();
258
    user.commit().await.expect("Failed to commit user");
259

            
260
    let usd = create_commodity(user.id, "USD", "US Dollar").await;
261
    let eur = create_commodity(user.id, "EUR", "Euro").await;
262
    let acc_a = create_account(user.id, "Account A", None).await;
263
    let acc_b = create_account(user.id, "Account B", None).await;
264

            
265
    let d = DateTime::<Utc>::from_timestamp(1700000000, 0).unwrap();
266
    create_tx(
267
        user.id,
268
        d,
269
        vec![(acc_a, usd, 100, 1), (acc_b, usd, -100, 1)],
270
    )
271
    .await;
272
    let (_tx2, split_ids) =
273
        create_tx(user.id, d, vec![(acc_a, eur, 50, 1), (acc_b, eur, -50, 1)]).await;
274

            
275
    // Insert split-specific prices for EUR→USD conversion (1.2 USD per EUR)
276
    insert_price(user, split_ids[0], eur, usd, d, 12, 10).await;
277
    insert_price(user, split_ids[1], eur, usd, d, 12, 10).await;
278

            
279
    let report = extract_report(
280
        BalanceReport::new()
281
            .user_id(user.id)
282
            .target_commodity_id(usd)
283
            .run()
284
            .await
285
            .unwrap(),
286
    );
287

            
288
    let node_a = find_node(&report.periods[0].roots, acc_a).unwrap();
289
    assert_eq!(node_a.amounts.len(), 1);
290
    // 100 USD + 50 EUR * 1.2 = 100 + 60 = 160 USD
291
    assert_eq!(node_amount(node_a, usd), Some(Rational64::new(160, 1)));
292
}
293

            
294
#[local_db_sqlx_test]
295
async fn test_balance_report_missing_conversion(pool: PgPool) {
296
    let user = USER.get().unwrap();
297
    user.commit().await.expect("Failed to commit user");
298

            
299
    let usd = create_commodity(user.id, "USD", "US Dollar").await;
300
    let eur = create_commodity(user.id, "EUR", "Euro").await;
301
    let acc_a = create_account(user.id, "Account A", None).await;
302
    let acc_b = create_account(user.id, "Account B", None).await;
303

            
304
    let d = DateTime::<Utc>::from_timestamp(1700000000, 0).unwrap();
305
    create_tx(user.id, d, vec![(acc_a, eur, 50, 1), (acc_b, eur, -50, 1)]).await;
306

            
307
    let result = BalanceReport::new()
308
        .user_id(user.id)
309
        .target_commodity_id(usd)
310
        .run()
311
        .await;
312

            
313
    assert!(result.is_err());
314
}
315

            
316
/// A split whose commodity is already the target currency must contribute
317
/// its face value exactly once, even when the LEFT JOIN to `prices` finds
318
/// no matching row. Regression test for a bug where the report double-
319
/// counted already-target-currency splits alongside their converted
320
/// counterparts.
321
#[local_db_sqlx_test]
322
async fn test_balance_report_conversion_includes_target_currency_splits(pool: PgPool) {
323
    let user = USER.get().unwrap();
324
    user.commit().await.expect("Failed to commit user");
325

            
326
    let usd = create_commodity(user.id, "USD", "US Dollar").await;
327
    let eur = create_commodity(user.id, "EUR", "Euro").await;
328
    let acc_a = create_account(user.id, "Account A", None).await;
329
    let acc_b = create_account(user.id, "Account B", None).await;
330

            
331
    let d = DateTime::<Utc>::from_timestamp(1700000000, 0).unwrap();
332
    create_tx(
333
        user.id,
334
        d,
335
        vec![(acc_a, usd, 100, 1), (acc_b, usd, -100, 1)],
336
    )
337
    .await;
338
    let (_tx2, split_ids) =
339
        create_tx(user.id, d, vec![(acc_a, eur, 50, 1), (acc_b, eur, -50, 1)]).await;
340
    insert_price(user, split_ids[0], eur, usd, d, 12, 10).await;
341
    insert_price(user, split_ids[1], eur, usd, d, 12, 10).await;
342

            
343
    let report = extract_report(
344
        BalanceReport::new()
345
            .user_id(user.id)
346
            .target_commodity_id(usd)
347
            .run()
348
            .await
349
            .unwrap(),
350
    );
351

            
352
    let node_a = find_node(&report.periods[0].roots, acc_a).unwrap();
353
    // 100 USD (no conversion needed) + 50 EUR * 1.2 = 160 USD. A bug that
354
    // skipped target-currency splits would yield 60; one that double-counted
355
    // them would yield 260.
356
    assert_eq!(node_amount(node_a, usd), Some(Rational64::new(160, 1)));
357
}
358

            
359
/// Duplicate (commodity_split_id, currency_id) rows in the `prices` table
360
/// (possible via bulk imports or manual edits) must not multiply a split's
361
/// contribution. The report should converge on a single price row per
362
/// split, not sum over every matching price.
363
#[local_db_sqlx_test]
364
async fn test_balance_report_conversion_is_stable_with_duplicate_prices(pool: PgPool) {
365
    let user = USER.get().unwrap();
366
    user.commit().await.expect("Failed to commit user");
367

            
368
    let usd = create_commodity(user.id, "USD", "US Dollar").await;
369
    let eur = create_commodity(user.id, "EUR", "Euro").await;
370
    let acc_a = create_account(user.id, "Account A", None).await;
371
    let acc_b = create_account(user.id, "Account B", None).await;
372

            
373
    let d = DateTime::<Utc>::from_timestamp(1700000000, 0).unwrap();
374
    let (_tx, split_ids) =
375
        create_tx(user.id, d, vec![(acc_a, eur, 50, 1), (acc_b, eur, -50, 1)]).await;
376

            
377
    // Two price rows for the same (commodity_split_id, currency_id). A naive
378
    // LEFT JOIN would emit the split twice and double-count it.
379
    insert_price(user, split_ids[0], eur, usd, d, 12, 10).await;
380
    insert_price(user, split_ids[0], eur, usd, d, 12, 10).await;
381
    insert_price(user, split_ids[1], eur, usd, d, 12, 10).await;
382

            
383
    let report = extract_report(
384
        BalanceReport::new()
385
            .user_id(user.id)
386
            .target_commodity_id(usd)
387
            .run()
388
            .await
389
            .unwrap(),
390
    );
391

            
392
    let node_a = find_node(&report.periods[0].roots, acc_a).unwrap();
393
    // 50 EUR * 1.2 = 60 USD, regardless of how many duplicate price rows exist.
394
    assert_eq!(node_amount(node_a, usd), Some(Rational64::new(60, 1)));
395
}
396

            
397
/// Multi-commodity account balances must preserve their per-commodity sums
398
/// when one leg converts and the other is already in the target currency.
399
/// Covers aggregation symmetry between the no-conversion leaf path and the
400
/// conversion leaf path inside `accumulate_split_converted`.
401
#[local_db_sqlx_test]
402
async fn test_balance_report_conversion_mixed_commodities_same_account(pool: PgPool) {
403
    let user = USER.get().unwrap();
404
    user.commit().await.expect("Failed to commit user");
405

            
406
    let usd = create_commodity(user.id, "USD", "US Dollar").await;
407
    let eur = create_commodity(user.id, "EUR", "Euro").await;
408
    let acc_a = create_account(user.id, "Account A", None).await;
409
    let acc_b = create_account(user.id, "Account B", None).await;
410

            
411
    let d = DateTime::<Utc>::from_timestamp(1700000000, 0).unwrap();
412
    // Three USD deposits of 100 each to acc_a
413
    for _ in 0..3 {
414
        create_tx(
415
            user.id,
416
            d,
417
            vec![(acc_a, usd, 100, 1), (acc_b, usd, -100, 1)],
418
        )
419
        .await;
420
    }
421
    // Two EUR deposits of 50 each, priced at 1.2 USD/EUR
422
    for _ in 0..2 {
423
        let (_tx, split_ids) =
424
            create_tx(user.id, d, vec![(acc_a, eur, 50, 1), (acc_b, eur, -50, 1)]).await;
425
        insert_price(user, split_ids[0], eur, usd, d, 12, 10).await;
426
        insert_price(user, split_ids[1], eur, usd, d, 12, 10).await;
427
    }
428

            
429
    let report = extract_report(
430
        BalanceReport::new()
431
            .user_id(user.id)
432
            .target_commodity_id(usd)
433
            .run()
434
            .await
435
            .unwrap(),
436
    );
437

            
438
    let node_a = find_node(&report.periods[0].roots, acc_a).unwrap();
439
    // 3 * 100 USD + 2 * (50 EUR * 1.2) = 300 + 120 = 420 USD
440
    assert_eq!(node_amount(node_a, usd), Some(Rational64::new(420, 1)));
441
}
442

            
443
#[local_db_sqlx_test]
444
async fn test_balance_report_as_of(pool: PgPool) {
445
    let user = USER.get().unwrap();
446
    user.commit().await.expect("Failed to commit user");
447

            
448
    let usd = create_commodity(user.id, "USD", "US Dollar").await;
449
    let acc_a = create_account(user.id, "Account A", None).await;
450
    let acc_b = create_account(user.id, "Account B", None).await;
451

            
452
    let d1 = DateTime::<Utc>::from_timestamp(1700000000, 0).unwrap();
453
    let d2 = DateTime::<Utc>::from_timestamp(1700100000, 0).unwrap();
454
    let cutoff = DateTime::<Utc>::from_timestamp(1700050000, 0).unwrap();
455

            
456
    create_tx(
457
        user.id,
458
        d1,
459
        vec![(acc_a, usd, 100, 1), (acc_b, usd, -100, 1)],
460
    )
461
    .await;
462
    create_tx(
463
        user.id,
464
        d2,
465
        vec![(acc_a, usd, 200, 1), (acc_b, usd, -200, 1)],
466
    )
467
    .await;
468

            
469
    let report = extract_report(
470
        BalanceReport::new()
471
            .user_id(user.id)
472
            .as_of(cutoff)
473
            .run()
474
            .await
475
            .unwrap(),
476
    );
477

            
478
    let node_a = find_node(&report.periods[0].roots, acc_a).unwrap();
479
    assert_eq!(node_amount(node_a, usd), Some(Rational64::new(100, 1)));
480
}
481

            
482
#[local_db_sqlx_test]
483
async fn test_balance_report_with_filter(pool: PgPool) {
484
    let user = USER.get().unwrap();
485
    user.commit().await.expect("Failed to commit user");
486

            
487
    let usd = create_commodity(user.id, "USD", "US Dollar").await;
488
    let acc_a = create_account(user.id, "Account A", None).await;
489
    let acc_b = create_account(user.id, "Account B", None).await;
490
    let acc_c = create_account(user.id, "Account C", None).await;
491

            
492
    let d = DateTime::<Utc>::from_timestamp(1700000000, 0).unwrap();
493
    create_tx(
494
        user.id,
495
        d,
496
        vec![(acc_a, usd, 100, 1), (acc_b, usd, -100, 1)],
497
    )
498
    .await;
499
    create_tx(user.id, d, vec![(acc_c, usd, 50, 1), (acc_b, usd, -50, 1)]).await;
500

            
501
    let report = extract_report(
502
        BalanceReport::new()
503
            .user_id(user.id)
504
            .report_filter(ReportFilter::AccountEq(acc_a))
505
            .run()
506
            .await
507
            .unwrap(),
508
    );
509

            
510
    let node_a = find_node(&report.periods[0].roots, acc_a).unwrap();
511
    assert_eq!(node_amount(node_a, usd), Some(Rational64::new(100, 1)));
512
    // acc_c should have no amounts since we filtered to acc_a only
513
    let node_c = find_node(&report.periods[0].roots, acc_c);
514
    assert!(node_c.is_none() || node_amount(node_c.unwrap(), usd).is_none());
515
}
516

            
517
// --- BalanceReport period-mode tests (formerly TrialBalance) ---
518

            
519
#[local_db_sqlx_test]
520
async fn test_balance_report_period_basic(pool: PgPool) {
521
    let user = USER.get().unwrap();
522
    user.commit().await.expect("Failed to commit user");
523

            
524
    let usd = create_commodity(user.id, "USD", "US Dollar").await;
525
    let assets = create_account(user.id, "Assets", None).await;
526
    let liabilities = create_account(user.id, "Liabilities", None).await;
527
    let income = create_account(user.id, "Income", None).await;
528

            
529
    let d = DateTime::<Utc>::from_timestamp(1700000000, 0).unwrap();
530
    create_tx(
531
        user.id,
532
        d,
533
        vec![(assets, usd, 500, 1), (income, usd, -500, 1)],
534
    )
535
    .await;
536
    create_tx(
537
        user.id,
538
        d,
539
        vec![(liabilities, usd, -200, 1), (assets, usd, 200, 1)],
540
    )
541
    .await;
542

            
543
    let from = DateTime::<Utc>::from_timestamp(1699000000, 0).unwrap();
544
    let to = DateTime::<Utc>::from_timestamp(1701000000, 0).unwrap();
545

            
546
    let report = extract_report(
547
        BalanceReport::new()
548
            .user_id(user.id)
549
            .date_from(from)
550
            .as_of(to)
551
            .run()
552
            .await
553
            .unwrap(),
554
    );
555

            
556
    assert_eq!(report.periods.len(), 1);
557
    assert!(report.periods[0].label.is_none());
558

            
559
    let assets_node = find_node(&report.periods[0].roots, assets).unwrap();
560
    assert_eq!(node_amount(assets_node, usd), Some(Rational64::new(700, 1)));
561

            
562
    let liabilities_node = find_node(&report.periods[0].roots, liabilities).unwrap();
563
    assert_eq!(
564
        node_amount(liabilities_node, usd),
565
        Some(Rational64::new(-200, 1))
566
    );
567

            
568
    let income_node = find_node(&report.periods[0].roots, income).unwrap();
569
    assert_eq!(
570
        node_amount(income_node, usd),
571
        Some(Rational64::new(-500, 1))
572
    );
573
}
574

            
575
#[local_db_sqlx_test]
576
async fn test_balance_report_period_with_conversion(pool: PgPool) {
577
    let user = USER.get().unwrap();
578
    user.commit().await.expect("Failed to commit user");
579

            
580
    let usd = create_commodity(user.id, "USD", "US Dollar").await;
581
    let eur = create_commodity(user.id, "EUR", "Euro").await;
582
    let acc_a = create_account(user.id, "Account A", None).await;
583
    let acc_b = create_account(user.id, "Account B", None).await;
584

            
585
    let d = DateTime::<Utc>::from_timestamp(1700000000, 0).unwrap();
586
    create_tx(
587
        user.id,
588
        d,
589
        vec![(acc_a, usd, 100, 1), (acc_b, usd, -100, 1)],
590
    )
591
    .await;
592
    let (_tx2, split_ids) =
593
        create_tx(user.id, d, vec![(acc_a, eur, 80, 1), (acc_b, eur, -80, 1)]).await;
594

            
595
    insert_price(user, split_ids[0], eur, usd, d, 11, 10).await;
596
    insert_price(user, split_ids[1], eur, usd, d, 11, 10).await;
597

            
598
    let from = DateTime::<Utc>::from_timestamp(1699000000, 0).unwrap();
599
    let to = DateTime::<Utc>::from_timestamp(1701000000, 0).unwrap();
600

            
601
    let report = extract_report(
602
        BalanceReport::new()
603
            .user_id(user.id)
604
            .date_from(from)
605
            .as_of(to)
606
            .target_commodity_id(usd)
607
            .run()
608
            .await
609
            .unwrap(),
610
    );
611

            
612
    let node_a = find_node(&report.periods[0].roots, acc_a).unwrap();
613
    assert_eq!(node_a.amounts.len(), 1);
614
    // 100 USD + 80 EUR * 1.1 = 100 + 88 = 188 USD
615
    assert_eq!(node_amount(node_a, usd), Some(Rational64::new(188, 1)));
616
}
617

            
618
#[local_db_sqlx_test]
619
async fn test_balance_report_period_with_filter(pool: PgPool) {
620
    let user = USER.get().unwrap();
621
    user.commit().await.expect("Failed to commit user");
622

            
623
    let usd = create_commodity(user.id, "USD", "US Dollar").await;
624
    let eur = create_commodity(user.id, "EUR", "Euro").await;
625
    let acc_a = create_account(user.id, "Account A", None).await;
626
    let acc_b = create_account(user.id, "Account B", None).await;
627

            
628
    let d = DateTime::<Utc>::from_timestamp(1700000000, 0).unwrap();
629
    create_tx(
630
        user.id,
631
        d,
632
        vec![(acc_a, usd, 100, 1), (acc_b, usd, -100, 1)],
633
    )
634
    .await;
635
    create_tx(user.id, d, vec![(acc_a, eur, 50, 1), (acc_b, eur, -50, 1)]).await;
636

            
637
    let from = DateTime::<Utc>::from_timestamp(1699000000, 0).unwrap();
638
    let to = DateTime::<Utc>::from_timestamp(1701000000, 0).unwrap();
639

            
640
    let report = extract_report(
641
        BalanceReport::new()
642
            .user_id(user.id)
643
            .date_from(from)
644
            .as_of(to)
645
            .report_filter(ReportFilter::CommodityEq(usd))
646
            .run()
647
            .await
648
            .unwrap(),
649
    );
650

            
651
    let node_a = find_node(&report.periods[0].roots, acc_a).unwrap();
652
    assert_eq!(node_a.amounts.len(), 1);
653
    assert_eq!(node_amount(node_a, usd), Some(Rational64::new(100, 1)));
654
    assert!(node_amount(node_a, eur).is_none());
655
}
656

            
657
// --- Hierarchy rollup test ---
658

            
659
#[local_db_sqlx_test]
660
async fn test_balance_report_hierarchy_rollup(pool: PgPool) {
661
    let user = USER.get().unwrap();
662
    user.commit().await.expect("Failed to commit user");
663

            
664
    let usd = create_commodity(user.id, "USD", "US Dollar").await;
665
    let assets = create_account(user.id, "Assets", None).await;
666
    let bank = create_account(user.id, "Bank", Some(assets)).await;
667
    let checking = create_account(user.id, "Checking", Some(bank)).await;
668
    let savings = create_account(user.id, "Savings", Some(bank)).await;
669
    let other = create_account(user.id, "Other", None).await;
670

            
671
    let d = DateTime::<Utc>::from_timestamp(1700000000, 0).unwrap();
672
    create_tx(
673
        user.id,
674
        d,
675
        vec![(checking, usd, 300, 1), (other, usd, -300, 1)],
676
    )
677
    .await;
678
    create_tx(
679
        user.id,
680
        d,
681
        vec![(savings, usd, 700, 1), (other, usd, -700, 1)],
682
    )
683
    .await;
684

            
685
    let report = extract_report(BalanceReport::new().user_id(user.id).run().await.unwrap());
686

            
687
    let checking_node = find_node(&report.periods[0].roots, checking).unwrap();
688
    assert_eq!(
689
        node_amount(checking_node, usd),
690
        Some(Rational64::new(300, 1))
691
    );
692
    assert_eq!(checking_node.account_path, "Assets:Bank:Checking");
693
    assert_eq!(checking_node.depth, 2);
694

            
695
    let savings_node = find_node(&report.periods[0].roots, savings).unwrap();
696
    assert_eq!(
697
        node_amount(savings_node, usd),
698
        Some(Rational64::new(700, 1))
699
    );
700

            
701
    // Bank should roll up: 300 + 700 = 1000
702
    let bank_node = find_node(&report.periods[0].roots, bank).unwrap();
703
    assert_eq!(node_amount(bank_node, usd), Some(Rational64::new(1000, 1)));
704

            
705
    // Assets should roll up: same as bank = 1000
706
    let assets_node = find_node(&report.periods[0].roots, assets).unwrap();
707
    assert_eq!(
708
        node_amount(assets_node, usd),
709
        Some(Rational64::new(1000, 1))
710
    );
711
}
712

            
713
// --- split-tagging helpers for CategoryBreakdown / Activity tests ---
714

            
715
1
async fn tag_tx_category(user: &crate::user::User, tx_id: Uuid, category: &str) {
716
1
    user.create_transaction_tag(tx_id, "category".to_string(), category.to_string(), None)
717
1
        .await
718
        .unwrap();
719
1
}
720

            
721
13
async fn tag_split_category(user: &crate::user::User, split_id: Uuid, category: &str) {
722
13
    user.create_split_tag(split_id, "category".to_string(), category.to_string(), None)
723
13
        .await
724
        .unwrap();
725
13
}
726

            
727
2
async fn tag_split_kv(user: &crate::user::User, split_id: Uuid, name: &str, value: &str) {
728
2
    user.create_split_tag(split_id, name.to_string(), value.to_string(), None)
729
2
        .await
730
        .unwrap();
731
2
}
732

            
733
// --- CategoryBreakdown tests ---
734

            
735
use super::super::{BreakdownData, BreakdownSort};
736
use super::CategoryBreakdown;
737

            
738
12
fn extract_breakdown(result: Option<CmdResult>) -> BreakdownData {
739
12
    if let Some(CmdResult::Breakdown(data)) = result {
740
12
        data
741
    } else {
742
        panic!("Expected Breakdown result");
743
    }
744
12
}
745

            
746
12
fn find_row<'a>(
747
12
    rows: &'a [super::super::BreakdownRow],
748
12
    tag_value: &str,
749
12
) -> Option<&'a super::super::BreakdownRow> {
750
13
    rows.iter().find(|r| r.tag_value == tag_value)
751
12
}
752

            
753
4
fn row_amount(row: &super::super::BreakdownRow, commodity_id: Uuid) -> Option<Rational64> {
754
4
    row.amounts
755
4
        .iter()
756
4
        .find(|a| a.commodity_id == commodity_id)
757
4
        .map(|a| a.amount)
758
4
}
759

            
760
#[local_db_sqlx_test]
761
async fn test_category_breakdown_basic(pool: PgPool) {
762
    let user = USER.get().unwrap();
763
    user.commit().await.expect("Failed to commit user");
764

            
765
    let usd = create_commodity(user.id, "USD", "US Dollar").await;
766
    let expenses = create_account(user.id, "Expenses", None).await;
767
    let checking = create_account(user.id, "Checking", None).await;
768
    tag_account_type(user.id, expenses, "expense").await;
769
    tag_account_type(user.id, checking, "asset").await;
770

            
771
    let d = DateTime::<Utc>::from_timestamp(1700000000, 0).unwrap();
772
    let (_, splits_a) = create_tx(
773
        user.id,
774
        d,
775
        vec![(expenses, usd, 300, 1), (checking, usd, -300, 1)],
776
    )
777
    .await;
778
    let (_, splits_b) = create_tx(
779
        user.id,
780
        d,
781
        vec![(expenses, usd, 150, 1), (checking, usd, -150, 1)],
782
    )
783
    .await;
784
    let (_, splits_c) = create_tx(
785
        user.id,
786
        d,
787
        vec![(expenses, usd, 75, 1), (checking, usd, -75, 1)],
788
    )
789
    .await;
790
    tag_split_category(user, splits_a[0], "food").await;
791
    tag_split_category(user, splits_b[0], "transport").await;
792
    tag_split_category(user, splits_c[0], "food").await;
793

            
794
    let from = DateTime::<Utc>::from_timestamp(1699999000, 0).unwrap();
795
    let to = DateTime::<Utc>::from_timestamp(1700100000, 0).unwrap();
796

            
797
    let breakdown = extract_breakdown(
798
        CategoryBreakdown::new()
799
            .user_id(user.id)
800
            .date_from(from)
801
            .date_to(to)
802
            .run()
803
            .await
804
            .unwrap(),
805
    );
806

            
807
    assert_eq!(breakdown.tag_name, "category");
808
    assert_eq!(breakdown.periods.len(), 1);
809
    let rows = &breakdown.periods[0].rows;
810

            
811
    let food = find_row(rows, "food").expect("food row");
812
    let transport = find_row(rows, "transport").expect("transport row");
813

            
814
1
    let food_total: Rational64 = food.amounts.iter().map(|a| a.amount).sum();
815
1
    let transport_total: Rational64 = transport.amounts.iter().map(|a| a.amount).sum();
816
2
    let abs = |r: Rational64| if r < Rational64::new(0, 1) { -r } else { r };
817
    assert_eq!(abs(food_total), Rational64::new(375, 1));
818
    assert_eq!(abs(transport_total), Rational64::new(150, 1));
819
}
820

            
821
#[local_db_sqlx_test]
822
async fn test_category_breakdown_uncategorized_toggle(pool: PgPool) {
823
    let user = USER.get().unwrap();
824
    user.commit().await.expect("Failed to commit user");
825

            
826
    let usd = create_commodity(user.id, "USD", "US Dollar").await;
827
    let expenses = create_account(user.id, "Expenses", None).await;
828
    let checking = create_account(user.id, "Checking", None).await;
829
    tag_account_type(user.id, expenses, "expense").await;
830
    tag_account_type(user.id, checking, "asset").await;
831

            
832
    let d = DateTime::<Utc>::from_timestamp(1700000000, 0).unwrap();
833
    let (_, splits_tagged) = create_tx(
834
        user.id,
835
        d,
836
        vec![(expenses, usd, 100, 1), (checking, usd, -100, 1)],
837
    )
838
    .await;
839
    create_tx(
840
        user.id,
841
        d,
842
        vec![(expenses, usd, 200, 1), (checking, usd, -200, 1)],
843
    )
844
    .await;
845
    tag_split_category(user, splits_tagged[0], "food").await;
846

            
847
    let from = DateTime::<Utc>::from_timestamp(1699999000, 0).unwrap();
848
    let to = DateTime::<Utc>::from_timestamp(1700100000, 0).unwrap();
849

            
850
    let with_uncat = extract_breakdown(
851
        CategoryBreakdown::new()
852
            .user_id(user.id)
853
            .date_from(from)
854
            .date_to(to)
855
            .run()
856
            .await
857
            .unwrap(),
858
    );
859
    assert!(
860
        find_row(&with_uncat.periods[0].rows, super::super::UNCATEGORIZED_KEY).is_some(),
861
        "uncategorized present by default"
862
    );
863

            
864
    let without_uncat = extract_breakdown(
865
        CategoryBreakdown::new()
866
            .user_id(user.id)
867
            .date_from(from)
868
            .date_to(to)
869
            .include_uncategorized(false)
870
            .run()
871
            .await
872
            .unwrap(),
873
    );
874
    assert!(
875
        find_row(
876
            &without_uncat.periods[0].rows,
877
            super::super::UNCATEGORIZED_KEY
878
        )
879
        .is_none(),
880
        "uncategorized filtered when include_uncategorized=false"
881
    );
882
    assert_eq!(without_uncat.periods[0].rows.len(), 1);
883
}
884

            
885
#[local_db_sqlx_test]
886
async fn test_category_breakdown_sort_orders(pool: PgPool) {
887
    let user = USER.get().unwrap();
888
    user.commit().await.expect("Failed to commit user");
889

            
890
    let usd = create_commodity(user.id, "USD", "US Dollar").await;
891
    let expenses = create_account(user.id, "Expenses", None).await;
892
    let checking = create_account(user.id, "Checking", None).await;
893
    tag_account_type(user.id, expenses, "expense").await;
894
    tag_account_type(user.id, checking, "asset").await;
895

            
896
    let d = DateTime::<Utc>::from_timestamp(1700000000, 0).unwrap();
897
    let (_, s_a) = create_tx(
898
        user.id,
899
        d,
900
        vec![(expenses, usd, 100, 1), (checking, usd, -100, 1)],
901
    )
902
    .await;
903
    let (_, s_b) = create_tx(
904
        user.id,
905
        d,
906
        vec![(expenses, usd, 300, 1), (checking, usd, -300, 1)],
907
    )
908
    .await;
909
    let (_, s_c) = create_tx(
910
        user.id,
911
        d,
912
        vec![(expenses, usd, 200, 1), (checking, usd, -200, 1)],
913
    )
914
    .await;
915
    tag_split_category(user, s_a[0], "alpha").await;
916
    tag_split_category(user, s_b[0], "beta").await;
917
    tag_split_category(user, s_c[0], "gamma").await;
918

            
919
    let from = DateTime::<Utc>::from_timestamp(1699999000, 0).unwrap();
920
    let to = DateTime::<Utc>::from_timestamp(1700100000, 0).unwrap();
921

            
922
    let desc = extract_breakdown(
923
        CategoryBreakdown::new()
924
            .user_id(user.id)
925
            .date_from(from)
926
            .date_to(to)
927
            .include_uncategorized(false)
928
            .target_commodity_id(usd)
929
            .sort_order(BreakdownSort::AmountDesc)
930
            .run()
931
            .await
932
            .unwrap(),
933
    );
934
    let order: Vec<&str> = desc.periods[0]
935
        .rows
936
        .iter()
937
3
        .map(|r| r.tag_value.as_str())
938
        .collect();
939
    assert_eq!(order, ["beta", "gamma", "alpha"]);
940

            
941
    let asc = extract_breakdown(
942
        CategoryBreakdown::new()
943
            .user_id(user.id)
944
            .date_from(from)
945
            .date_to(to)
946
            .include_uncategorized(false)
947
            .target_commodity_id(usd)
948
            .sort_order(BreakdownSort::AmountAsc)
949
            .run()
950
            .await
951
            .unwrap(),
952
    );
953
    let order: Vec<&str> = asc.periods[0]
954
        .rows
955
        .iter()
956
3
        .map(|r| r.tag_value.as_str())
957
        .collect();
958
    assert_eq!(order, ["alpha", "gamma", "beta"]);
959

            
960
    let name_asc = extract_breakdown(
961
        CategoryBreakdown::new()
962
            .user_id(user.id)
963
            .date_from(from)
964
            .date_to(to)
965
            .include_uncategorized(false)
966
            .sort_order(BreakdownSort::NameAsc)
967
            .run()
968
            .await
969
            .unwrap(),
970
    );
971
    let order: Vec<&str> = name_asc.periods[0]
972
        .rows
973
        .iter()
974
3
        .map(|r| r.tag_value.as_str())
975
        .collect();
976
    assert_eq!(order, ["alpha", "beta", "gamma"]);
977
}
978

            
979
#[local_db_sqlx_test]
980
async fn test_category_breakdown_configurable_tag_name(pool: PgPool) {
981
    let user = USER.get().unwrap();
982
    user.commit().await.expect("Failed to commit user");
983

            
984
    let usd = create_commodity(user.id, "USD", "US Dollar").await;
985
    let expenses = create_account(user.id, "Expenses", None).await;
986
    let checking = create_account(user.id, "Checking", None).await;
987
    tag_account_type(user.id, expenses, "expense").await;
988
    tag_account_type(user.id, checking, "asset").await;
989

            
990
    let d = DateTime::<Utc>::from_timestamp(1700000000, 0).unwrap();
991
    let (_, s) = create_tx(
992
        user.id,
993
        d,
994
        vec![(expenses, usd, 100, 1), (checking, usd, -100, 1)],
995
    )
996
    .await;
997
    tag_split_kv(user, s[0], "project", "roof").await;
998
    tag_split_kv(user, s[0], "category", "home").await;
999

            
    let from = DateTime::<Utc>::from_timestamp(1699999000, 0).unwrap();
    let to = DateTime::<Utc>::from_timestamp(1700100000, 0).unwrap();
    let by_project = extract_breakdown(
        CategoryBreakdown::new()
            .user_id(user.id)
            .date_from(from)
            .date_to(to)
            .tag_name("project".to_string())
            .include_uncategorized(false)
            .run()
            .await
            .unwrap(),
    );
    assert_eq!(by_project.tag_name, "project");
    assert!(find_row(&by_project.periods[0].rows, "roof").is_some());
    let by_category = extract_breakdown(
        CategoryBreakdown::new()
            .user_id(user.id)
            .date_from(from)
            .date_to(to)
            .include_uncategorized(false)
            .run()
            .await
            .unwrap(),
    );
    assert_eq!(by_category.tag_name, "category");
    assert!(find_row(&by_category.periods[0].rows, "home").is_some());
}
#[local_db_sqlx_test]
async fn test_category_breakdown_period_grouping(pool: PgPool) {
    let user = USER.get().unwrap();
    user.commit().await.expect("Failed to commit user");
    let usd = create_commodity(user.id, "USD", "US Dollar").await;
    let expenses = create_account(user.id, "Expenses", None).await;
    let checking = create_account(user.id, "Checking", None).await;
    tag_account_type(user.id, expenses, "expense").await;
    tag_account_type(user.id, checking, "asset").await;
    let jan = NaiveDate::from_ymd_opt(2025, 1, 15)
        .unwrap()
        .and_hms_opt(12, 0, 0)
        .unwrap()
        .and_utc();
    let feb = NaiveDate::from_ymd_opt(2025, 2, 10)
        .unwrap()
        .and_hms_opt(12, 0, 0)
        .unwrap()
        .and_utc();
    let (_, s_jan) = create_tx(
        user.id,
        jan,
        vec![(expenses, usd, 100, 1), (checking, usd, -100, 1)],
    )
    .await;
    let (_, s_feb) = create_tx(
        user.id,
        feb,
        vec![(expenses, usd, 300, 1), (checking, usd, -300, 1)],
    )
    .await;
    tag_split_category(user, s_jan[0], "food").await;
    tag_split_category(user, s_feb[0], "food").await;
    let from = NaiveDate::from_ymd_opt(2025, 1, 1)
        .unwrap()
        .and_hms_opt(0, 0, 0)
        .unwrap()
        .and_utc();
    let to = NaiveDate::from_ymd_opt(2025, 3, 1)
        .unwrap()
        .and_hms_opt(0, 0, 0)
        .unwrap()
        .and_utc();
    let bd = extract_breakdown(
        CategoryBreakdown::new()
            .user_id(user.id)
            .date_from(from)
            .date_to(to)
            .period_grouping(PeriodGrouping::Month)
            .include_uncategorized(false)
            .run()
            .await
            .unwrap(),
    );
    assert_eq!(bd.periods.len(), 2);
    assert_eq!(bd.periods[0].label.as_deref(), Some("2025-01"));
    assert_eq!(bd.periods[1].label.as_deref(), Some("2025-02"));
    let jan_food = find_row(&bd.periods[0].rows, "food").unwrap();
    let feb_food = find_row(&bd.periods[1].rows, "food").unwrap();
    assert_eq!(row_amount(jan_food, usd), Some(Rational64::new(100, 1)));
    assert_eq!(row_amount(feb_food, usd), Some(Rational64::new(300, 1)));
}
#[local_db_sqlx_test]
async fn test_category_breakdown_with_filter(pool: PgPool) {
    let user = USER.get().unwrap();
    user.commit().await.expect("Failed to commit user");
    let usd = create_commodity(user.id, "USD", "US Dollar").await;
    let expenses = create_account(user.id, "Expenses", None).await;
    let income = create_account(user.id, "Income", None).await;
    let checking = create_account(user.id, "Checking", None).await;
    tag_account_type(user.id, expenses, "expense").await;
    tag_account_type(user.id, income, "income").await;
    tag_account_type(user.id, checking, "asset").await;
    let d = DateTime::<Utc>::from_timestamp(1700000000, 0).unwrap();
    let (_, s1) = create_tx(
        user.id,
        d,
        vec![(expenses, usd, 100, 1), (checking, usd, -100, 1)],
    )
    .await;
    let (_, s2) = create_tx(
        user.id,
        d,
        vec![(income, usd, -500, 1), (checking, usd, 500, 1)],
    )
    .await;
    tag_split_category(user, s1[0], "food").await;
    tag_split_category(user, s2[0], "salary").await;
    let from = DateTime::<Utc>::from_timestamp(1699999000, 0).unwrap();
    let to = DateTime::<Utc>::from_timestamp(1700100000, 0).unwrap();
    let bd = extract_breakdown(
        CategoryBreakdown::new()
            .user_id(user.id)
            .date_from(from)
            .date_to(to)
            .report_filter(ReportFilter::AccountEq(expenses))
            .include_uncategorized(false)
            .run()
            .await
            .unwrap(),
    );
    assert!(find_row(&bd.periods[0].rows, "food").is_some());
    assert!(find_row(&bd.periods[0].rows, "salary").is_none());
}
// --- ActivityReport tests ---
use super::super::{ActivityData, ActivityGroup, FilterEntity};
use super::ActivityReport;
28
async fn tag_account_type(user_id: Uuid, account_id: Uuid, account_type: &str) {
28
    crate::command::account::SetAccountTag::new()
28
        .user_id(user_id)
28
        .account_id(account_id)
28
        .tag_name("type".to_string())
28
        .tag_value(account_type.to_string())
28
        .run()
28
        .await
        .unwrap();
28
}
5
fn extract_activity(result: Option<CmdResult>) -> ActivityData {
5
    if let Some(CmdResult::Activity(data)) = result {
5
        data
    } else {
        panic!("Expected Activity result");
    }
5
}
12
fn find_group<'a>(
12
    period: &'a super::super::ActivityPeriod,
12
    label: &str,
12
) -> Option<&'a super::super::ActivityGroupResult> {
20
    period.groups.iter().find(|g| g.label == label)
12
}
9
fn group_total(group: &super::super::ActivityGroupResult, commodity_id: Uuid) -> Rational64 {
9
    group
9
        .roots
9
        .iter()
9
        .filter_map(|n| {
9
            n.amounts
9
                .iter()
9
                .find(|a| a.commodity_id == commodity_id)
9
                .map(|a| a.amount)
9
        })
        .sum()
9
}
#[local_db_sqlx_test]
async fn test_activity_report_default_groups(pool: PgPool) {
    let user = USER.get().unwrap();
    user.commit().await.expect("Failed to commit user");
    let usd = create_commodity(user.id, "USD", "US Dollar").await;
    let income = create_account(user.id, "Salary", None).await;
    let expense = create_account(user.id, "Groceries", None).await;
    let asset = create_account(user.id, "Checking", None).await;
    tag_account_type(user.id, income, "income").await;
    tag_account_type(user.id, expense, "expense").await;
    tag_account_type(user.id, asset, "asset").await;
    let d = DateTime::<Utc>::from_timestamp(1700000000, 0).unwrap();
    create_tx(
        user.id,
        d,
        vec![
            (income, usd, -500, 1),
            (expense, usd, 200, 1),
            (asset, usd, 300, 1),
        ],
    )
    .await;
    let from = DateTime::<Utc>::from_timestamp(1699999000, 0).unwrap();
    let to = DateTime::<Utc>::from_timestamp(1700100000, 0).unwrap();
    let activity = extract_activity(
        ActivityReport::new()
            .user_id(user.id)
            .date_from(from)
            .date_to(to)
            .run()
            .await
            .unwrap(),
    );
    assert_eq!(activity.periods.len(), 1);
    let period = &activity.periods[0];
    assert_eq!(period.groups.len(), 2, "default = Income + Expense");
    let income_group = find_group(period, "Income").expect("Income group present");
    let expense_group = find_group(period, "Expense").expect("Expense group present");
    assert!(income_group.flip_sign);
    assert!(!expense_group.flip_sign);
    // Raw sign: income credit is stored as -500 and should come back as -500.
    assert_eq!(group_total(income_group, usd), Rational64::new(-500, 1));
    assert_eq!(group_total(expense_group, usd), Rational64::new(200, 1));
    // Asset account must not appear in either group.
1
    assert!(!income_group.roots.iter().any(|n| n.account_id == asset));
1
    assert!(!expense_group.roots.iter().any(|n| n.account_id == asset));
}
#[local_db_sqlx_test]
async fn test_activity_report_three_way_split(pool: PgPool) {
    let user = USER.get().unwrap();
    user.commit().await.expect("Failed to commit user");
    let usd = create_commodity(user.id, "USD", "US Dollar").await;
    let salary = create_account(user.id, "Salary", None).await;
    let savings = create_account(user.id, "401k", None).await;
    let rent = create_account(user.id, "Rent", None).await;
    tag_account_type(user.id, salary, "income").await;
    tag_account_type(user.id, savings, "savings").await;
    tag_account_type(user.id, rent, "expense").await;
    let d = DateTime::<Utc>::from_timestamp(1700000000, 0).unwrap();
    create_tx(
        user.id,
        d,
        vec![
            (salary, usd, -1000, 1),
            (savings, usd, 300, 1),
            (rent, usd, 700, 1),
        ],
    )
    .await;
    let from = DateTime::<Utc>::from_timestamp(1699999000, 0).unwrap();
    let to = DateTime::<Utc>::from_timestamp(1700100000, 0).unwrap();
    let groups = vec![
        ActivityGroup {
            label: "Income".into(),
            filter: ReportFilter::Tag {
                entity: FilterEntity::Account,
                name: "type".into(),
                value: "income".into(),
            },
            flip_sign: true,
        },
        ActivityGroup {
            label: "Savings".into(),
            filter: ReportFilter::Tag {
                entity: FilterEntity::Account,
                name: "type".into(),
                value: "savings".into(),
            },
            flip_sign: false,
        },
        ActivityGroup {
            label: "Expenses".into(),
            filter: ReportFilter::Tag {
                entity: FilterEntity::Account,
                name: "type".into(),
                value: "expense".into(),
            },
            flip_sign: false,
        },
    ];
    let activity = extract_activity(
        ActivityReport::new()
            .user_id(user.id)
            .date_from(from)
            .date_to(to)
            .groups(groups)
            .run()
            .await
            .unwrap(),
    );
    let period = &activity.periods[0];
    assert_eq!(period.groups.len(), 3);
    assert_eq!(
        group_total(find_group(period, "Income").unwrap(), usd),
        Rational64::new(-1000, 1)
    );
    assert_eq!(
        group_total(find_group(period, "Savings").unwrap(), usd),
        Rational64::new(300, 1)
    );
    assert_eq!(
        group_total(find_group(period, "Expenses").unwrap(), usd),
        Rational64::new(700, 1)
    );
}
#[local_db_sqlx_test]
async fn test_activity_report_custom_tag_classification(pool: PgPool) {
    let user = USER.get().unwrap();
    user.commit().await.expect("Failed to commit user");
    let usd = create_commodity(user.id, "USD", "US Dollar").await;
    let earning = create_account(user.id, "Consulting", None).await;
    let cost = create_account(user.id, "AWS", None).await;
    // Using a different tag name ('role') and different values: any string works.
    crate::command::account::SetAccountTag::new()
        .user_id(user.id)
        .account_id(earning)
        .tag_name("role".to_string())
        .tag_value("earning".to_string())
        .run()
        .await
        .unwrap();
    crate::command::account::SetAccountTag::new()
        .user_id(user.id)
        .account_id(cost)
        .tag_name("role".to_string())
        .tag_value("cost".to_string())
        .run()
        .await
        .unwrap();
    let d = DateTime::<Utc>::from_timestamp(1700000000, 0).unwrap();
    create_tx(
        user.id,
        d,
        vec![(earning, usd, -1000, 1), (cost, usd, 1000, 1)],
    )
    .await;
    let from = DateTime::<Utc>::from_timestamp(1699999000, 0).unwrap();
    let to = DateTime::<Utc>::from_timestamp(1700100000, 0).unwrap();
    let activity = extract_activity(
        ActivityReport::new()
            .user_id(user.id)
            .date_from(from)
            .date_to(to)
            .groups(vec![
                ActivityGroup {
                    label: "Revenue".into(),
                    filter: ReportFilter::Tag {
                        entity: FilterEntity::Account,
                        name: "role".into(),
                        value: "earning".into(),
                    },
                    flip_sign: true,
                },
                ActivityGroup {
                    label: "Costs".into(),
                    filter: ReportFilter::Tag {
                        entity: FilterEntity::Account,
                        name: "role".into(),
                        value: "cost".into(),
                    },
                    flip_sign: false,
                },
            ])
            .run()
            .await
            .unwrap(),
    );
    let period = &activity.periods[0];
    assert!(find_group(period, "Revenue").is_some());
    assert!(find_group(period, "Costs").is_some());
    assert_eq!(
        group_total(find_group(period, "Revenue").unwrap(), usd),
        Rational64::new(-1000, 1)
    );
}
#[local_db_sqlx_test]
async fn test_activity_report_user_filter_composition(pool: PgPool) {
    let user = USER.get().unwrap();
    user.commit().await.expect("Failed to commit user");
    let usd = create_commodity(user.id, "USD", "US Dollar").await;
    let income = create_account(user.id, "Salary", None).await;
    let groceries = create_account(user.id, "Groceries", None).await;
    let rent = create_account(user.id, "Rent", None).await;
    tag_account_type(user.id, income, "income").await;
    tag_account_type(user.id, groceries, "expense").await;
    tag_account_type(user.id, rent, "expense").await;
    let d = DateTime::<Utc>::from_timestamp(1700000000, 0).unwrap();
    create_tx(
        user.id,
        d,
        vec![
            (income, usd, -1500, 1),
            (groceries, usd, 500, 1),
            (rent, usd, 1000, 1),
        ],
    )
    .await;
    let from = DateTime::<Utc>::from_timestamp(1699999000, 0).unwrap();
    let to = DateTime::<Utc>::from_timestamp(1700100000, 0).unwrap();
    let activity = extract_activity(
        ActivityReport::new()
            .user_id(user.id)
            .date_from(from)
            .date_to(to)
            .report_filter(ReportFilter::AccountEq(groceries))
            .run()
            .await
            .unwrap(),
    );
    let period = &activity.periods[0];
    let expense_group = find_group(period, "Expense").unwrap();
    // Only groceries survives the user filter.
    assert_eq!(group_total(expense_group, usd), Rational64::new(500, 1));
    let income_group = find_group(period, "Income").unwrap();
    // Income group's filter excludes groceries, so zero income rows remain.
    assert!(income_group.roots.is_empty());
}
#[local_db_sqlx_test]
async fn test_activity_report_monthly_grouping(pool: PgPool) {
    let user = USER.get().unwrap();
    user.commit().await.expect("Failed to commit user");
    let usd = create_commodity(user.id, "USD", "US Dollar").await;
    let income = create_account(user.id, "Salary", None).await;
    let expense = create_account(user.id, "Groceries", None).await;
    tag_account_type(user.id, income, "income").await;
    tag_account_type(user.id, expense, "expense").await;
    let jan = NaiveDate::from_ymd_opt(2025, 1, 15)
        .unwrap()
        .and_hms_opt(12, 0, 0)
        .unwrap()
        .and_utc();
    let feb = NaiveDate::from_ymd_opt(2025, 2, 10)
        .unwrap()
        .and_hms_opt(12, 0, 0)
        .unwrap()
        .and_utc();
    create_tx(
        user.id,
        jan,
        vec![(income, usd, -100, 1), (expense, usd, 100, 1)],
    )
    .await;
    create_tx(
        user.id,
        feb,
        vec![(income, usd, -200, 1), (expense, usd, 200, 1)],
    )
    .await;
    let from = NaiveDate::from_ymd_opt(2025, 1, 1)
        .unwrap()
        .and_hms_opt(0, 0, 0)
        .unwrap()
        .and_utc();
    let to = NaiveDate::from_ymd_opt(2025, 3, 1)
        .unwrap()
        .and_hms_opt(0, 0, 0)
        .unwrap()
        .and_utc();
    let activity = extract_activity(
        ActivityReport::new()
            .user_id(user.id)
            .date_from(from)
            .date_to(to)
            .period_grouping(PeriodGrouping::Month)
            .run()
            .await
            .unwrap(),
    );
    assert_eq!(activity.periods.len(), 2);
    assert_eq!(activity.periods[0].label.as_deref(), Some("2025-01"));
    assert_eq!(activity.periods[1].label.as_deref(), Some("2025-02"));
    assert_eq!(
        group_total(find_group(&activity.periods[0], "Expense").unwrap(), usd),
        Rational64::new(100, 1)
    );
    assert_eq!(
        group_total(find_group(&activity.periods[1], "Expense").unwrap(), usd),
        Rational64::new(200, 1)
    );
}
#[local_db_sqlx_test]
async fn test_category_breakdown_falls_back_to_transaction_tag(pool: PgPool) {
    let user = USER.get().unwrap();
    user.commit().await.expect("Failed to commit user");
    let usd = create_commodity(user.id, "USD", "US Dollar").await;
    let expenses = create_account(user.id, "Expenses", None).await;
    let checking = create_account(user.id, "Checking", None).await;
    tag_account_type(user.id, expenses, "expense").await;
    tag_account_type(user.id, checking, "asset").await;
    let d = DateTime::<Utc>::from_timestamp(1700000000, 0).unwrap();
    let (tx_id, _) = create_tx(
        user.id,
        d,
        vec![(expenses, usd, 100, 1), (checking, usd, -100, 1)],
    )
    .await;
    // Tag the transaction — no split tag. CategoryBreakdown should pick up
    // the tx-level tag via COALESCE fallback.
    tag_tx_category(user, tx_id, "food").await;
    let from = DateTime::<Utc>::from_timestamp(1699999000, 0).unwrap();
    let to = DateTime::<Utc>::from_timestamp(1700100000, 0).unwrap();
    let bd = extract_breakdown(
        CategoryBreakdown::new()
            .user_id(user.id)
            .date_from(from)
            .date_to(to)
            .include_uncategorized(false)
            .run()
            .await
            .unwrap(),
    );
    let food = find_row(&bd.periods[0].rows, "food").expect("food row via tx tag");
    assert_eq!(row_amount(food, usd), Some(Rational64::new(100, 1)));
}
#[local_db_sqlx_test]
async fn test_category_breakdown_excludes_asset_splits(pool: PgPool) {
    let user = USER.get().unwrap();
    user.commit().await.expect("Failed to commit user");
    let usd = create_commodity(user.id, "USD", "US Dollar").await;
    let expenses = create_account(user.id, "Expenses", None).await;
    let checking = create_account(user.id, "Checking", None).await;
    tag_account_type(user.id, expenses, "expense").await;
    tag_account_type(user.id, checking, "asset").await;
    let d = DateTime::<Utc>::from_timestamp(1700000000, 0).unwrap();
    // Tag BOTH sides of a balanced transaction as 'food'. Under the old
    // "all splits" semantics, the food bucket would sum to zero because
    // +100 and -100 cancel. Under the scope filter, only the expense side
    // counts and food = +100.
    let (_, s) = create_tx(
        user.id,
        d,
        vec![(expenses, usd, 100, 1), (checking, usd, -100, 1)],
    )
    .await;
    tag_split_category(user, s[0], "food").await;
    tag_split_category(user, s[1], "food").await;
    let from = DateTime::<Utc>::from_timestamp(1699999000, 0).unwrap();
    let to = DateTime::<Utc>::from_timestamp(1700100000, 0).unwrap();
    let bd = extract_breakdown(
        CategoryBreakdown::new()
            .user_id(user.id)
            .date_from(from)
            .date_to(to)
            .include_uncategorized(false)
            .run()
            .await
            .unwrap(),
    );
    let food = find_row(&bd.periods[0].rows, "food").expect("food row");
    assert_eq!(
        row_amount(food, usd),
        Some(Rational64::new(100, 1)),
        "asset leg is scoped out; only expense side contributes"
    );
}