1
use chrono::{DateTime, Utc};
2
use finance::error::FinanceError;
3
use num_rational::Rational64;
4
use sqlx::types::Uuid;
5

            
6
use super::super::{CmdError, ReportFilter};
7
use super::filter::SqlParam;
8
use super::tree::{
9
    AccountAmounts, AccountRow, ConversionTarget, accumulate_split, accumulate_split_converted,
10
    checked_product, ratio, report_failure,
11
};
12

            
13
pub(super) struct BreakdownSplit {
14
    pub commodity_id: Uuid,
15
    pub commodity_symbol: String,
16
    pub value: Rational64,
17
    pub category: Option<String>,
18
}
19

            
20
35157
pub(super) async fn fetch_accounts(
21
35157
    conn: &mut sqlx::PgConnection,
22
35157
) -> Result<Vec<AccountRow>, CmdError> {
23
15993
    let rows = sqlx::query_file!("sql/report/accounts/with_names.sql")
24
15993
        .fetch_all(conn)
25
15993
        .await?;
26
15993
    Ok(rows
27
15993
        .into_iter()
28
        .map(|r| AccountRow {
29
39447
            account_id: r.account_id,
30
39447
            parent_id: r.parent_id,
31
39447
            account_name: r.account_name,
32
39447
            account_type: r.account_type,
33
39447
        })
34
        .collect())
35
15993
}
36

            
37
4341
pub(super) async fn fetch_target_symbol(
38
4341
    conn: &mut sqlx::PgConnection,
39
4341
    target_commodity_id: Uuid,
40
4341
) -> Result<String, CmdError> {
41
    Ok(
42
1635
        sqlx::query_file_scalar!("sql/select/commodities/symbol.sql", &target_commodity_id)
43
1635
            .fetch_optional(conn)
44
1635
            .await?
45
            .unwrap_or_else(|| target_commodity_id.to_string()),
46
    )
47
1635
}
48

            
49
11890
pub(super) async fn fetch_balance_splits_no_conversion(
50
11890
    conn: &mut sqlx::PgConnection,
51
11890
    as_of: Option<DateTime<Utc>>,
52
11890
) -> Result<AccountAmounts, CmdError> {
53
5164
    let rows = sqlx::query_file!("sql/report/splits/all.sql", as_of)
54
5164
        .fetch_all(conn)
55
5164
        .await?;
56

            
57
5162
    let mut amounts = AccountAmounts::new();
58
5162
    for r in rows {
59
14480
        accumulate_split(
60
14480
            &mut amounts,
61
14480
            r.account_id,
62
14480
            r.commodity_id,
63
14480
            ratio(r.value_num, r.value_denom).map_err(report_failure)?,
64
14479
            &r.commodity_symbol,
65
        )
66
14479
        .map_err(report_failure)?;
67
    }
68
5161
    Ok(amounts)
69
5164
}
70

            
71
1268
pub(super) async fn fetch_balance_splits_with_conversion(
72
1268
    conn: &mut sqlx::PgConnection,
73
1268
    target_commodity_id: Uuid,
74
1268
    target_symbol: &str,
75
1268
    as_of: Option<DateTime<Utc>>,
76
1268
) -> Result<AccountAmounts, CmdError> {
77
492
    let rows = sqlx::query_file!(
78
492
        "sql/report/splits/all_with_conversion.sql",
79
        &target_commodity_id,
80
        as_of
81
    )
82
492
    .fetch_all(conn)
83
492
    .await?;
84

            
85
492
    let target = ConversionTarget {
86
492
        commodity_id: target_commodity_id,
87
492
        symbol: target_symbol,
88
492
    };
89
492
    let mut amounts = AccountAmounts::new();
90
492
    for r in rows {
91
1726
        accumulate_split_converted(
92
1726
            &mut amounts,
93
1726
            r.account_id,
94
1726
            r.commodity_id,
95
1726
            ratio(r.value_num, r.value_denom).map_err(report_failure)?,
96
1726
            &r.commodity_symbol,
97
1726
            &target,
98
1726
            (r.price_num, r.price_denom),
99
        )
100
6
        .map_err(|e| CmdError::Finance(FinanceError::Report(e)))?;
101
    }
102
486
    Ok(amounts)
103
492
}
104

            
105
6303
pub(super) async fn fetch_date_range_splits_no_conversion(
106
6303
    conn: &mut sqlx::PgConnection,
107
6303
    from: DateTime<Utc>,
108
6303
    to: DateTime<Utc>,
109
6303
) -> Result<AccountAmounts, CmdError> {
110
3377
    let rows = sqlx::query_file!("sql/report/splits/date_range.sql", from, to)
111
3377
        .fetch_all(conn)
112
3377
        .await?;
113

            
114
3377
    let mut amounts = AccountAmounts::new();
115
3377
    for r in rows {
116
3914
        accumulate_split(
117
3914
            &mut amounts,
118
3914
            r.account_id,
119
3914
            r.commodity_id,
120
3914
            ratio(r.value_num, r.value_denom).map_err(report_failure)?,
121
3914
            &r.commodity_symbol,
122
        )
123
3914
        .map_err(report_failure)?;
124
    }
125
3377
    Ok(amounts)
126
3377
}
127

            
128
182
pub(super) async fn fetch_date_range_splits_with_conversion(
129
182
    conn: &mut sqlx::PgConnection,
130
182
    target_commodity_id: Uuid,
131
182
    target_symbol: &str,
132
182
    from: DateTime<Utc>,
133
182
    to: DateTime<Utc>,
134
182
) -> Result<AccountAmounts, CmdError> {
135
3
    let rows = sqlx::query_file!(
136
3
        "sql/report/splits/date_range_with_conversion.sql",
137
        &target_commodity_id,
138
        from,
139
        to
140
    )
141
3
    .fetch_all(conn)
142
3
    .await?;
143

            
144
3
    let target = ConversionTarget {
145
3
        commodity_id: target_commodity_id,
146
3
        symbol: target_symbol,
147
3
    };
148
3
    let mut amounts = AccountAmounts::new();
149
3
    for r in rows {
150
28
        accumulate_split_converted(
151
28
            &mut amounts,
152
28
            r.account_id,
153
28
            r.commodity_id,
154
28
            ratio(r.value_num, r.value_denom).map_err(report_failure)?,
155
28
            &r.commodity_symbol,
156
28
            &target,
157
28
            (r.price_num, r.price_denom),
158
        )
159
        .map_err(|e| CmdError::Finance(FinanceError::Report(e)))?;
160
    }
161
3
    Ok(amounts)
162
3
}
163

            
164
1446
pub(super) async fn fetch_balance_splits_filtered_no_conversion(
165
1446
    conn: &mut sqlx::PgConnection,
166
1446
    as_of: Option<DateTime<Utc>>,
167
1446
    filter: &ReportFilter,
168
1446
) -> Result<AccountAmounts, CmdError> {
169
    use sqlx::Row;
170

            
171
491
    let base_sql = concat!(
172
        "SELECT s.account_id, s.commodity_id, s.value_num, s.value_denom, ",
173
        "t_symbol.tag_value AS commodity_symbol ",
174
        "FROM splits AS s ",
175
        "INNER JOIN transactions AS t ON s.tx_id = t.id ",
176
        "INNER JOIN commodity_tags AS ct_symbol ON s.commodity_id = ct_symbol.commodity_id ",
177
        "INNER JOIN tags AS t_symbol ON (ct_symbol.tag_id = t_symbol.id AND t_symbol.tag_name = 'symbol') ",
178
        "WHERE ($1::timestamptz IS NULL OR t.post_date <= $1)"
179
    );
180

            
181
491
    let mut bind_offset: i32 = 1;
182
491
    let (where_clause, params) = filter.to_sql(&mut bind_offset);
183
491
    let full_sql = format!("{base_sql} AND {where_clause}");
184

            
185
491
    let mut query = sqlx::query(sqlx::AssertSqlSafe(full_sql)).bind(as_of);
186
491
    for p in &params {
187
997
        query = match p {
188
5
            SqlParam::Uuid(v) => query.bind(*v),
189
            SqlParam::UuidVec(v) => query.bind(v),
190
320
            SqlParam::I64(v) => query.bind(*v),
191
672
            SqlParam::String(v) => query.bind(v.as_str()),
192
            SqlParam::StringVec(v) => query.bind(v),
193
        };
194
    }
195

            
196
491
    let rows = query.fetch_all(&mut *conn).await?;
197

            
198
491
    let mut amounts = AccountAmounts::new();
199
491
    for r in &rows {
200
365
        let account_id: Uuid = r.get("account_id");
201
365
        let commodity_id: Uuid = r.get("commodity_id");
202
365
        let value_num: i64 = r.get("value_num");
203
365
        let value_denom: i64 = r.get("value_denom");
204
365
        let commodity_symbol: String = r.get("commodity_symbol");
205
365
        accumulate_split(
206
365
            &mut amounts,
207
365
            account_id,
208
365
            commodity_id,
209
365
            ratio(value_num, value_denom).map_err(report_failure)?,
210
365
            &commodity_symbol,
211
        )
212
365
        .map_err(report_failure)?;
213
    }
214
491
    Ok(amounts)
215
491
}
216

            
217
181
pub(super) async fn fetch_balance_splits_filtered_with_conversion(
218
181
    conn: &mut sqlx::PgConnection,
219
181
    target_commodity_id: Uuid,
220
181
    target_symbol: &str,
221
181
    as_of: Option<DateTime<Utc>>,
222
181
    filter: &ReportFilter,
223
181
) -> Result<AccountAmounts, CmdError> {
224
    use sqlx::Row;
225

            
226
2
    let base_sql = concat!(
227
        "SELECT s.id AS split_id, s.account_id, s.commodity_id, s.value_num, s.value_denom, ",
228
        "t_symbol.tag_value AS commodity_symbol, ",
229
        "p.value_num AS price_num, p.value_denom AS price_denom ",
230
        "FROM splits AS s ",
231
        "INNER JOIN transactions AS t ON s.tx_id = t.id ",
232
        "INNER JOIN commodity_tags AS ct_symbol ON s.commodity_id = ct_symbol.commodity_id ",
233
        "INNER JOIN tags AS t_symbol ON (ct_symbol.tag_id = t_symbol.id AND t_symbol.tag_name = 'symbol') ",
234
        "LEFT JOIN LATERAL (",
235
        "  SELECT pr.value_num, pr.value_denom FROM prices AS pr ",
236
        "  WHERE pr.commodity_split_id = s.id AND pr.currency_id = $1 ",
237
        "  ORDER BY pr.price_date DESC, pr.id LIMIT 1",
238
        ") AS p ON TRUE ",
239
        "WHERE ($2::timestamptz IS NULL OR t.post_date <= $2)"
240
    );
241

            
242
2
    let mut bind_offset: i32 = 2;
243
2
    let (where_clause, params) = filter.to_sql(&mut bind_offset);
244
2
    let full_sql = format!("{base_sql} AND {where_clause}");
245

            
246
2
    let mut query = sqlx::query(sqlx::AssertSqlSafe(full_sql))
247
2
        .bind(target_commodity_id)
248
2
        .bind(as_of);
249
2
    for p in &params {
250
2
        query = match p {
251
2
            SqlParam::Uuid(v) => query.bind(*v),
252
            SqlParam::UuidVec(v) => query.bind(v),
253
            SqlParam::I64(v) => query.bind(*v),
254
            SqlParam::String(v) => query.bind(v.as_str()),
255
            SqlParam::StringVec(v) => query.bind(v),
256
        };
257
    }
258

            
259
2
    let rows = query.fetch_all(&mut *conn).await?;
260

            
261
2
    let target = ConversionTarget {
262
2
        commodity_id: target_commodity_id,
263
2
        symbol: target_symbol,
264
2
    };
265
2
    let mut amounts = AccountAmounts::new();
266
2
    for r in &rows {
267
44
        let account_id: Uuid = r.get("account_id");
268
44
        let commodity_id: Uuid = r.get("commodity_id");
269
44
        let value_num: i64 = r.get("value_num");
270
44
        let value_denom: i64 = r.get("value_denom");
271
44
        let commodity_symbol: String = r.get("commodity_symbol");
272
44
        let price_num: Option<i64> = r.get("price_num");
273
44
        let price_denom: Option<i64> = r.get("price_denom");
274
44
        accumulate_split_converted(
275
44
            &mut amounts,
276
44
            account_id,
277
44
            commodity_id,
278
44
            ratio(value_num, value_denom).map_err(report_failure)?,
279
44
            &commodity_symbol,
280
44
            &target,
281
44
            (price_num, price_denom),
282
        )
283
        .map_err(|e| CmdError::Finance(FinanceError::Report(e)))?;
284
    }
285
2
    Ok(amounts)
286
2
}
287

            
288
25429
pub(super) async fn fetch_date_range_splits_filtered_no_conversion(
289
25429
    conn: &mut sqlx::PgConnection,
290
25429
    from: DateTime<Utc>,
291
25429
    to: DateTime<Utc>,
292
25429
    filter: &ReportFilter,
293
25429
) -> Result<AccountAmounts, CmdError> {
294
    use sqlx::Row;
295

            
296
10684
    let base_sql = concat!(
297
        "SELECT s.account_id, s.commodity_id, s.value_num, s.value_denom, t.post_date, ",
298
        "t_symbol.tag_value AS commodity_symbol ",
299
        "FROM splits AS s ",
300
        "INNER JOIN transactions AS t ON s.tx_id = t.id ",
301
        "INNER JOIN commodity_tags AS ct_symbol ON s.commodity_id = ct_symbol.commodity_id ",
302
        "INNER JOIN tags AS t_symbol ON (ct_symbol.tag_id = t_symbol.id AND t_symbol.tag_name = 'symbol') ",
303
        "WHERE t.post_date >= $1 AND t.post_date < $2"
304
    );
305

            
306
10684
    let mut bind_offset: i32 = 2;
307
10684
    let (where_clause, params) = filter.to_sql(&mut bind_offset);
308
10684
    let full_sql = format!("{base_sql} AND {where_clause}");
309

            
310
10684
    let mut query = sqlx::query(sqlx::AssertSqlSafe(full_sql))
311
10684
        .bind(from)
312
10684
        .bind(to);
313
10684
    for p in &params {
314
23957
        query = match p {
315
15
            SqlParam::Uuid(v) => query.bind(*v),
316
            SqlParam::UuidVec(v) => query.bind(v),
317
320
            SqlParam::I64(v) => query.bind(*v),
318
23622
            SqlParam::String(v) => query.bind(v.as_str()),
319
            SqlParam::StringVec(v) => query.bind(v),
320
        };
321
    }
322

            
323
10684
    let rows = query.fetch_all(&mut *conn).await?;
324

            
325
10684
    let mut amounts = AccountAmounts::new();
326
10684
    for r in &rows {
327
4418
        let account_id: Uuid = r.get("account_id");
328
4418
        let commodity_id: Uuid = r.get("commodity_id");
329
4418
        let value_num: i64 = r.get("value_num");
330
4418
        let value_denom: i64 = r.get("value_denom");
331
4418
        let commodity_symbol: String = r.get("commodity_symbol");
332
4418
        accumulate_split(
333
4418
            &mut amounts,
334
4418
            account_id,
335
4418
            commodity_id,
336
4418
            ratio(value_num, value_denom).map_err(report_failure)?,
337
4418
            &commodity_symbol,
338
        )
339
4418
        .map_err(report_failure)?;
340
    }
341
10364
    Ok(amounts)
342
10684
}
343

            
344
4157
pub(super) async fn fetch_date_range_splits_filtered_with_conversion(
345
4157
    conn: &mut sqlx::PgConnection,
346
4157
    target_commodity_id: Uuid,
347
4157
    target_symbol: &str,
348
4157
    from: DateTime<Utc>,
349
4157
    to: DateTime<Utc>,
350
4157
    filter: &ReportFilter,
351
4157
) -> Result<AccountAmounts, CmdError> {
352
    use sqlx::Row;
353

            
354
994
    let base_sql = concat!(
355
        "SELECT s.id AS split_id, s.account_id, s.commodity_id, s.value_num, s.value_denom, ",
356
        "t_symbol.tag_value AS commodity_symbol, t.post_date, ",
357
        "p.value_num AS price_num, p.value_denom AS price_denom ",
358
        "FROM splits AS s ",
359
        "INNER JOIN transactions AS t ON s.tx_id = t.id ",
360
        "INNER JOIN commodity_tags AS ct_symbol ON s.commodity_id = ct_symbol.commodity_id ",
361
        "INNER JOIN tags AS t_symbol ON (ct_symbol.tag_id = t_symbol.id AND t_symbol.tag_name = 'symbol') ",
362
        "LEFT JOIN LATERAL (",
363
        "  SELECT pr.value_num, pr.value_denom FROM prices AS pr ",
364
        "  WHERE pr.commodity_split_id = s.id AND pr.currency_id = $1 ",
365
        "  ORDER BY pr.price_date DESC, pr.id LIMIT 1",
366
        ") AS p ON TRUE ",
367
        "WHERE t.post_date >= $2 AND t.post_date < $3"
368
    );
369

            
370
994
    let mut bind_offset: i32 = 3;
371
994
    let (where_clause, params) = filter.to_sql(&mut bind_offset);
372
994
    let full_sql = format!("{base_sql} AND {where_clause}");
373

            
374
994
    let mut query = sqlx::query(sqlx::AssertSqlSafe(full_sql))
375
994
        .bind(target_commodity_id)
376
994
        .bind(from)
377
994
        .bind(to);
378
994
    for p in &params {
379
1992
        query = match p {
380
4
            SqlParam::Uuid(v) => query.bind(*v),
381
            SqlParam::UuidVec(v) => query.bind(v),
382
            SqlParam::I64(v) => query.bind(*v),
383
1988
            SqlParam::String(v) => query.bind(v.as_str()),
384
            SqlParam::StringVec(v) => query.bind(v),
385
        };
386
    }
387

            
388
994
    let rows = query.fetch_all(&mut *conn).await?;
389

            
390
994
    let target = ConversionTarget {
391
994
        commodity_id: target_commodity_id,
392
994
        symbol: target_symbol,
393
994
    };
394
994
    let mut amounts = AccountAmounts::new();
395
994
    for r in &rows {
396
692
        let account_id: Uuid = r.get("account_id");
397
692
        let commodity_id: Uuid = r.get("commodity_id");
398
692
        let value_num: i64 = r.get("value_num");
399
692
        let value_denom: i64 = r.get("value_denom");
400
692
        let commodity_symbol: String = r.get("commodity_symbol");
401
692
        let price_num: Option<i64> = r.get("price_num");
402
692
        let price_denom: Option<i64> = r.get("price_denom");
403
692
        accumulate_split_converted(
404
692
            &mut amounts,
405
692
            account_id,
406
692
            commodity_id,
407
692
            ratio(value_num, value_denom).map_err(report_failure)?,
408
692
            &commodity_symbol,
409
692
            &target,
410
692
            (price_num, price_denom),
411
        )
412
4
        .map_err(|e| CmdError::Finance(FinanceError::Report(e)))?;
413
    }
414
990
    Ok(amounts)
415
994
}
416

            
417
17856
pub(super) async fn fetch_date_range_breakdown_filtered_no_conversion(
418
17856
    conn: &mut sqlx::PgConnection,
419
17856
    from: DateTime<Utc>,
420
17856
    to: DateTime<Utc>,
421
17856
    tag_name: &str,
422
17856
    filter: &ReportFilter,
423
17856
) -> Result<Vec<BreakdownSplit>, CmdError> {
424
    use sqlx::Row;
425

            
426
9039
    let base_sql = concat!(
427
        "SELECT s.account_id, s.commodity_id, s.value_num, s.value_denom, ",
428
        "t_symbol.tag_value AS commodity_symbol, ",
429
        "COALESCE(",
430
        "(SELECT t_cat.tag_value FROM split_tags AS st_cat ",
431
        "INNER JOIN tags AS t_cat ON st_cat.tag_id = t_cat.id ",
432
        "WHERE st_cat.split_id = s.id AND t_cat.tag_name = $3 LIMIT 1), ",
433
        "(SELECT t_cat.tag_value FROM transaction_tags AS tt_cat ",
434
        "INNER JOIN tags AS t_cat ON tt_cat.tag_id = t_cat.id ",
435
        "WHERE tt_cat.tx_id = s.tx_id AND t_cat.tag_name = $3 LIMIT 1)",
436
        ") AS category_value ",
437
        "FROM splits AS s ",
438
        "INNER JOIN transactions AS t ON s.tx_id = t.id ",
439
        "INNER JOIN commodity_tags AS ct_symbol ON s.commodity_id = ct_symbol.commodity_id ",
440
        "INNER JOIN tags AS t_symbol ON (ct_symbol.tag_id = t_symbol.id AND t_symbol.tag_name = 'symbol') ",
441
        "WHERE t.post_date >= $1 AND t.post_date < $2"
442
    );
443

            
444
9039
    let mut bind_offset: i32 = 3;
445
9039
    let (where_clause, params) = filter.to_sql(&mut bind_offset);
446
9039
    let full_sql = format!("{base_sql} AND {where_clause}");
447

            
448
9039
    let mut query = sqlx::query(sqlx::AssertSqlSafe(full_sql))
449
9039
        .bind(from)
450
9039
        .bind(to)
451
9039
        .bind(tag_name);
452
9039
    for p in &params {
453
20023
        query = match p {
454
1
            SqlParam::Uuid(v) => query.bind(*v),
455
            SqlParam::UuidVec(v) => query.bind(v),
456
            SqlParam::I64(v) => query.bind(*v),
457
10983
            SqlParam::String(v) => query.bind(v.as_str()),
458
9039
            SqlParam::StringVec(v) => query.bind(v),
459
        };
460
    }
461

            
462
9039
    let rows = query.fetch_all(&mut *conn).await?;
463

            
464
9039
    let mut out = Vec::with_capacity(rows.len());
465
9039
    for r in &rows {
466
13667
        let commodity_id: Uuid = r.get("commodity_id");
467
13667
        let value_num: i64 = r.get("value_num");
468
13667
        let value_denom: i64 = r.get("value_denom");
469
13667
        let commodity_symbol: String = r.get("commodity_symbol");
470
13667
        let category: Option<String> = r.get("category_value");
471
13667
        out.push(BreakdownSplit {
472
13667
            commodity_id,
473
13667
            commodity_symbol,
474
13667
            value: ratio(value_num, value_denom).map_err(report_failure)?,
475
13667
            category,
476
        });
477
    }
478
9039
    Ok(out)
479
9039
}
480

            
481
2351
pub(super) async fn fetch_date_range_breakdown_filtered_with_conversion(
482
2351
    conn: &mut sqlx::PgConnection,
483
2351
    target_commodity_id: Uuid,
484
2351
    target_symbol: &str,
485
2351
    from: DateTime<Utc>,
486
2351
    to: DateTime<Utc>,
487
2351
    tag_name: &str,
488
2351
    filter: &ReportFilter,
489
2351
) -> Result<Vec<BreakdownSplit>, CmdError> {
490
    use sqlx::Row;
491

            
492
660
    let base_sql = concat!(
493
        "SELECT s.id AS split_id, s.account_id, s.commodity_id, s.value_num, s.value_denom, ",
494
        "t_symbol.tag_value AS commodity_symbol, ",
495
        "p.value_num AS price_num, p.value_denom AS price_denom, ",
496
        "COALESCE(",
497
        "(SELECT t_cat.tag_value FROM split_tags AS st_cat ",
498
        "INNER JOIN tags AS t_cat ON st_cat.tag_id = t_cat.id ",
499
        "WHERE st_cat.split_id = s.id AND t_cat.tag_name = $4 LIMIT 1), ",
500
        "(SELECT t_cat.tag_value FROM transaction_tags AS tt_cat ",
501
        "INNER JOIN tags AS t_cat ON tt_cat.tag_id = t_cat.id ",
502
        "WHERE tt_cat.tx_id = s.tx_id AND t_cat.tag_name = $4 LIMIT 1)",
503
        ") AS category_value ",
504
        "FROM splits AS s ",
505
        "INNER JOIN transactions AS t ON s.tx_id = t.id ",
506
        "INNER JOIN commodity_tags AS ct_symbol ON s.commodity_id = ct_symbol.commodity_id ",
507
        "INNER JOIN tags AS t_symbol ON (ct_symbol.tag_id = t_symbol.id AND t_symbol.tag_name = 'symbol') ",
508
        "LEFT JOIN LATERAL (",
509
        "  SELECT pr.value_num, pr.value_denom FROM prices AS pr ",
510
        "  WHERE pr.commodity_split_id = s.id AND pr.currency_id = $1 ",
511
        "  ORDER BY pr.price_date DESC, pr.id LIMIT 1",
512
        ") AS p ON TRUE ",
513
        "WHERE t.post_date >= $2 AND t.post_date < $3"
514
    );
515

            
516
660
    let mut bind_offset: i32 = 4;
517
660
    let (where_clause, params) = filter.to_sql(&mut bind_offset);
518
660
    let full_sql = format!("{base_sql} AND {where_clause}");
519

            
520
660
    let mut query = sqlx::query(sqlx::AssertSqlSafe(full_sql))
521
660
        .bind(target_commodity_id)
522
660
        .bind(from)
523
660
        .bind(to)
524
660
        .bind(tag_name);
525
660
    for p in &params {
526
1320
        query = match p {
527
            SqlParam::Uuid(v) => query.bind(*v),
528
            SqlParam::UuidVec(v) => query.bind(v),
529
            SqlParam::I64(v) => query.bind(*v),
530
660
            SqlParam::String(v) => query.bind(v.as_str()),
531
660
            SqlParam::StringVec(v) => query.bind(v),
532
        };
533
    }
534

            
535
660
    let rows = query.fetch_all(&mut *conn).await?;
536

            
537
660
    let mut out = Vec::with_capacity(rows.len());
538
660
    for r in &rows {
539
1978
        let commodity_id: Uuid = r.get("commodity_id");
540
1978
        let value_num: i64 = r.get("value_num");
541
1978
        let value_denom: i64 = r.get("value_denom");
542
1978
        let commodity_symbol: String = r.get("commodity_symbol");
543
1978
        let price_num: Option<i64> = r.get("price_num");
544
1978
        let price_denom: Option<i64> = r.get("price_denom");
545
1978
        let category: Option<String> = r.get("category_value");
546

            
547
1978
        let value = ratio(value_num, value_denom).map_err(report_failure)?;
548
1978
        let converted = if commodity_id == target_commodity_id {
549
1968
            value
550
10
        } else if let (Some(pn), Some(pd)) = (price_num, price_denom) {
551
6
            checked_product(value, ratio(pn, pd).map_err(report_failure)?)
552
6
                .map_err(report_failure)?
553
        } else {
554
4
            return Err(CmdError::Finance(FinanceError::Report(
555
4
                finance::error::ReportError::MissingConversion {
556
4
                    from_commodity: commodity_symbol,
557
4
                    to_commodity: target_symbol.to_owned(),
558
4
                },
559
4
            )));
560
        };
561
1974
        out.push(BreakdownSplit {
562
1974
            commodity_id: target_commodity_id,
563
1974
            commodity_symbol: target_symbol.to_owned(),
564
1974
            value: converted,
565
1974
            category,
566
1974
        });
567
    }
568
656
    Ok(out)
569
660
}