1
use crate::command::connection;
2
use chrono::{DateTime, Utc};
3
use sqlx::types::Uuid;
4
use supp_macro::command;
5

            
6
use crate::user::User;
7

            
8
use super::super::{CmdError, CmdResult, PeriodData, ReportData, ReportFilter, ReportMeta};
9
use super::fetch::{
10
    fetch_accounts, fetch_balance_splits_filtered_no_conversion,
11
    fetch_balance_splits_filtered_with_conversion, fetch_balance_splits_no_conversion,
12
    fetch_balance_splits_with_conversion, fetch_date_range_splits_filtered_no_conversion,
13
    fetch_date_range_splits_filtered_with_conversion, fetch_date_range_splits_no_conversion,
14
    fetch_date_range_splits_with_conversion, fetch_target_symbol,
15
};
16
use super::tree::{AccountAmounts, build_tree, report_failure};
17

            
18
14785
async fn fetch_snapshot(
19
14785
    conn: &mut sqlx::PgConnection,
20
14785
    target_commodity_id: Option<Uuid>,
21
14785
    as_of: Option<DateTime<Utc>>,
22
14785
    report_filter: Option<&ReportFilter>,
23
14785
) -> Result<AccountAmounts, CmdError> {
24
6149
    match (target_commodity_id, report_filter) {
25
        (Some(tid), Some(f)) => {
26
2
            let sym = fetch_target_symbol(conn, tid).await?;
27
2
            fetch_balance_splits_filtered_with_conversion(conn, tid, &sym, as_of, f).await
28
        }
29
        (Some(tid), None) => {
30
492
            let sym = fetch_target_symbol(conn, tid).await?;
31
492
            fetch_balance_splits_with_conversion(conn, tid, &sym, as_of).await
32
        }
33
491
        (None, Some(f)) => fetch_balance_splits_filtered_no_conversion(conn, as_of, f).await,
34
5164
        (None, None) => fetch_balance_splits_no_conversion(conn, as_of).await,
35
    }
36
6149
}
37

            
38
/// The range fetchers are end-exclusive; one microsecond (timestamptz precision) makes `as_of` inclusive.
39
7027
fn inclusive_end(as_of: DateTime<Utc>) -> DateTime<Utc> {
40
7027
    as_of
41
7027
        .checked_add_signed(chrono::TimeDelta::microseconds(1))
42
7027
        .unwrap_or(as_of)
43
7027
}
44

            
45
7027
async fn fetch_range(
46
7027
    conn: &mut sqlx::PgConnection,
47
7027
    target_commodity_id: Option<Uuid>,
48
7027
    from: DateTime<Utc>,
49
7027
    to: DateTime<Utc>,
50
7027
    report_filter: Option<&ReportFilter>,
51
7027
) -> Result<AccountAmounts, CmdError> {
52
3703
    match (target_commodity_id, report_filter) {
53
        (Some(tid), Some(f)) => {
54
            let sym = fetch_target_symbol(conn, tid).await?;
55
            fetch_date_range_splits_filtered_with_conversion(conn, tid, &sym, from, to, f).await
56
        }
57
        (Some(tid), None) => {
58
3
            let sym = fetch_target_symbol(conn, tid).await?;
59
3
            fetch_date_range_splits_with_conversion(conn, tid, &sym, from, to).await
60
        }
61
323
        (None, Some(f)) => fetch_date_range_splits_filtered_no_conversion(conn, from, to, f).await,
62
3377
        (None, None) => fetch_date_range_splits_no_conversion(conn, from, to).await,
63
    }
64
3703
}
65

            
66
command! {
67
    BalanceReport {
68
        #[required]
69
        user_id: Uuid,
70
        #[optional]
71
        target_commodity_id: Uuid,
72
        #[optional]
73
        date_from: DateTime<Utc>,
74
        #[optional]
75
        as_of: DateTime<Utc>,
76
        #[optional]
77
        report_filter: ReportFilter,
78
    } => {
79
        super::filter::check_filter_size(
80
            report_filter.as_ref().map_or(0, super::super::ReportFilter::leaves),
81
        )?;
82

            
83
        let user = User { id: user_id };
84
        let mut conn = connection(&user).await?;
85

            
86
        let accounts = fetch_accounts(&mut conn).await?;
87

            
88
        let amounts = match date_from {
89
            Some(from) => {
90
                let to = as_of.unwrap_or_else(Utc::now);
91
                super::period::check_range(from, to)?;
92
                fetch_range(&mut conn, target_commodity_id, from, inclusive_end(to), report_filter.as_ref()).await?
93
            }
94
            None => fetch_snapshot(&mut conn, target_commodity_id, as_of, report_filter.as_ref()).await?,
95
        };
96

            
97
        let roots = build_tree(&accounts, &amounts).map_err(report_failure)?;
98
        let period = PeriodData { label: None, roots };
99

            
100
        Ok(Some(CmdResult::Report(ReportData {
101
            meta: ReportMeta {
102
                date_from,
103
                date_to: as_of,
104
                target_commodity_id,
105
            },
106
            periods: vec![period],
107
        })))
108
    }
109
85386
}