cala-ledger 0.15.8

An embeddable double sided accounting ledger built on PG/SQLx
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
use chrono::NaiveDate;
use sqlx::PgPool;
use std::collections::HashMap;
use tracing::instrument;

use crate::{
    balance::{account_balance::AccountBalance, error::BalanceError},
    outbox::OutboxPublisher,
};
use cala_types::{
    balance::{BalanceSnapshot, EffectiveBalanceSnapshot},
    outbox::OutboxEventPayload,
    primitives::{AccountId, AccountSetId, BalanceId, Currency, DebitOrCredit, EntryId, JournalId},
};

use super::data::*;

type BalanceRangeResult =
    HashMap<BalanceId, (Option<AccountBalance>, u32, Option<AccountBalance>, u32)>;

#[derive(Debug)]
pub(super) struct LatestBeforeEntry {
    pub snapshot: BalanceSnapshot,
    pub all_time_version: i32,
}

#[derive(Debug, Clone)]
pub(super) struct EffectiveBalanceRepo {
    pool: PgPool,
    publisher: OutboxPublisher,
}

impl EffectiveBalanceRepo {
    pub fn new(pool: &PgPool, publisher: &OutboxPublisher) -> Self {
        Self {
            pool: pool.clone(),
            publisher: publisher.clone(),
        }
    }

    pub async fn find(
        &self,
        journal_id: JournalId,
        account_id: AccountId,
        currency: Currency,
        date: NaiveDate,
    ) -> Result<AccountBalance, BalanceError> {
        self.find_in_op(&self.pool, journal_id, account_id, currency, date)
            .await
    }

    #[instrument(name = "effective_balance.find_in_op", skip_all, err(level = "warn"))]
    pub async fn find_in_op(
        &self,
        op: impl es_entity::IntoOneTimeExecutor<'_>,
        journal_id: JournalId,
        account_id: AccountId,
        currency: Currency,
        date: NaiveDate,
    ) -> Result<AccountBalance, BalanceError> {
        let row = op
            .into_executor()
            .fetch_optional(sqlx::query!(
                r#"
            SELECT values, a.normal_balance_type AS "normal_balance_type!: DebitOrCredit"
            FROM cala_cumulative_effective_balances
            JOIN cala_accounts a
            ON account_id = a.id
            WHERE journal_id = $1
            AND account_id = $2
            AND currency = $3
            AND effective <= $4
            ORDER BY effective DESC, version DESC
            LIMIT 1
            "#,
                journal_id as JournalId,
                account_id as AccountId,
                currency.code(),
                date
            ))
            .await?;

        if let Some(row) = row {
            let details: BalanceSnapshot =
                serde_json::from_value(row.values).expect("Failed to deserialize balance snapshot");
            Ok(AccountBalance::new(row.normal_balance_type, details))
        } else {
            Err(BalanceError::NotFound(journal_id, account_id, currency))
        }
    }

    #[instrument(name = "effective_balance.find_range", skip_all, err(level = "warn"))]
    pub(super) async fn find_range(
        &self,
        journal_id: JournalId,
        account_id: AccountId,
        currency: Currency,
        from: NaiveDate,
        until: Option<NaiveDate>,
    ) -> Result<(Option<AccountBalance>, Option<AccountBalance>, u32), BalanceError> {
        let rows = sqlx::query!(
            r#"
        WITH first AS (
            SELECT
              true AS first, false AS last, values,
              a.normal_balance_type AS "normal_balance_type!: DebitOrCredit",
              all_time_version
            FROM cala_cumulative_effective_balances
            JOIN cala_accounts a
            ON account_id = a.id
            WHERE journal_id = $1
            AND account_id = $2
            AND currency = $3
            AND effective < $4
            ORDER BY effective DESC, version DESC
            LIMIT 1
        ),
        last AS (
            SELECT
              false AS first, true AS last, values,
              a.normal_balance_type AS "normal_balance_type!: DebitOrCredit",
              all_time_version
            FROM cala_cumulative_effective_balances
            JOIN cala_accounts a
            ON account_id = a.id
            WHERE journal_id = $1
            AND account_id = $2
            AND currency = $3
            AND effective <= COALESCE($5, NOW()::DATE)
            ORDER BY effective DESC, version DESC
            LIMIT 1
        )
        SELECT * FROM first
        UNION ALL
        SELECT * FROM last
        "#,
            journal_id as JournalId,
            account_id as AccountId,
            currency.code(),
            from,
            until,
        )
        .fetch_all(&self.pool)
        .await?;

        let mut first = None;
        let mut last = None;
        let mut first_version = 0;
        let mut last_version = 0;
        for row in rows {
            let details: BalanceSnapshot =
                serde_json::from_value(row.values.expect("values is not null"))
                    .expect("Failed to deserialize balance snapshot");
            let balance = Some(AccountBalance::new(row.normal_balance_type, details));
            if row.first.expect("first is not null") {
                first = balance;
                first_version = row.all_time_version.expect("all_time_version") as u32;
            } else {
                last = balance;
                last_version = row.all_time_version.expect("all_time_version") as u32;
            }
        }
        Ok((first, last, last_version - first_version))
    }

    #[instrument(name = "cala_ledger.balances.effective.find_all", skip_all)]
    pub(super) async fn find_all(
        &self,
        ids: &[BalanceId],
        date: NaiveDate,
    ) -> Result<HashMap<BalanceId, AccountBalance>, BalanceError> {
        let mut journal_ids = Vec::with_capacity(ids.len());
        let mut account_ids = Vec::with_capacity(ids.len());
        let mut currencies = Vec::with_capacity(ids.len());
        for (journal_id, account_id, currency) in ids {
            journal_ids.push(uuid::Uuid::from(journal_id));
            account_ids.push(uuid::Uuid::from(account_id));
            currencies.push(currency.code().to_string());
        }

        let rows = sqlx::query!(
            r#"
            WITH balance_ids AS (
              SELECT journal_id, account_id, currency, normal_balance_type
              FROM (
                SELECT * FROM UNNEST($1::uuid[], $2::uuid[], $3::text[])
                AS v(journal_id, account_id, currency)
              ) AS v
              JOIN cala_accounts a
              ON account_id = a.id
            )
            SELECT
                values,
                normal_balance_type as "normal_balance_type!: DebitOrCredit",
                h.journal_id as "journal_id: JournalId",
                h.account_id as "account_id: AccountId",
                h.currency
            FROM balance_ids
            JOIN LATERAL (
                SELECT DISTINCT ON (journal_id, account_id, currency)
                    journal_id, account_id, currency, values
                FROM cala_cumulative_effective_balances
                WHERE journal_id = balance_ids.journal_id
                  AND account_id = balance_ids.account_id
                  AND currency = balance_ids.currency
                  AND effective <= $4
                ORDER BY journal_id, account_id, currency, effective DESC, version DESC
            ) h ON TRUE
            "#,
            &journal_ids[..],
            &account_ids[..],
            &currencies[..],
            date,
        )
        .fetch_all(&self.pool)
        .await?;

        let mut ret = HashMap::new();
        for row in rows {
            let details: BalanceSnapshot =
                serde_json::from_value(row.values).expect("Failed to deserialize balance snapshot");
            let balance_id = (details.journal_id, details.account_id, details.currency);
            let balance = AccountBalance::new(row.normal_balance_type, details);
            ret.insert(balance_id, balance);
        }
        Ok(ret)
    }

    #[instrument(name = "cala_ledger.balances.effective.find_range_all", skip_all)]
    pub(super) async fn find_range_all(
        &self,
        ids: &[BalanceId],
        from: NaiveDate,
        until: Option<NaiveDate>,
    ) -> Result<BalanceRangeResult, BalanceError> {
        let mut journal_ids = Vec::with_capacity(ids.len());
        let mut account_ids = Vec::with_capacity(ids.len());
        let mut currencies = Vec::with_capacity(ids.len());
        for (journal_id, account_id, currency) in ids {
            journal_ids.push(uuid::Uuid::from(journal_id));
            account_ids.push(uuid::Uuid::from(account_id));
            currencies.push(currency.code().to_string());
        }

        let rows = sqlx::query!(
            r#"
            WITH balance_ids AS (
              SELECT journal_id, account_id, currency, normal_balance_type
              FROM (
                SELECT * FROM UNNEST($1::uuid[], $2::uuid[], $3::text[])
                AS v(journal_id, account_id, currency)
              ) AS v
              JOIN cala_accounts a
              ON account_id = a.id
            ),
            first AS (
              SELECT
                true AS first, false AS last, values,
                normal_balance_type,
                all_time_version,
                h.journal_id, h.account_id, h.currency
                FROM balance_ids
                JOIN LATERAL (
                    SELECT DISTINCT ON (journal_id, account_id, currency)
                        journal_id, account_id, currency, values, all_time_version
                    FROM cala_cumulative_effective_balances
                    WHERE journal_id = balance_ids.journal_id
                      AND account_id = balance_ids.account_id
                      AND currency = balance_ids.currency
                      AND effective < $4
                    ORDER BY journal_id, account_id, currency, effective DESC, version DESC
                ) h ON TRUE
            ),
            last AS (
              SELECT
                false AS first, true AS last, values,
                normal_balance_type,
                all_time_version,
                h.journal_id, h.account_id, h.currency
                FROM balance_ids
                JOIN LATERAL (
                    SELECT DISTINCT ON (journal_id, account_id, currency)
                        journal_id, account_id, currency, values, all_time_version
                    FROM cala_cumulative_effective_balances
                    WHERE journal_id = balance_ids.journal_id
                      AND account_id = balance_ids.account_id
                      AND currency = balance_ids.currency
                      AND effective <= COALESCE($5, NOW()::DATE)
                    ORDER BY journal_id, account_id, currency, effective DESC, version DESC
                ) h ON TRUE
            )
            SELECT
                first, last, values, 
                normal_balance_type as "normal_balance_type!: DebitOrCredit",
                all_time_version,
                journal_id as "journal_id: JournalId",
                account_id as "account_id: AccountId",
                currency
            FROM first
            UNION ALL
            SELECT
                first, last, values,
                normal_balance_type as "normal_balance_type!: DebitOrCredit",
                all_time_version,
                journal_id as "journal_id: JournalId",
                account_id as "account_id: AccountId",
                currency
            FROM last"#,
            &journal_ids[..],
            &account_ids[..],
            &currencies[..],
            from,
            until,
        )
        .fetch_all(&self.pool)
        .await?;

        let mut ret = HashMap::new();
        for row in rows {
            let values: serde_json::Value = row.values.expect("values is not null");
            let details: BalanceSnapshot =
                serde_json::from_value(values).expect("Failed to deserialize balance snapshot");
            let balance_id = (details.journal_id, details.account_id, details.currency);
            let balance = AccountBalance::new(row.normal_balance_type, details);
            let entry = ret.entry(balance_id).or_insert((None, 0, None, 0));
            if row.first.expect("first is not null") {
                entry.0 = Some(balance);
                entry.1 = row.all_time_version.expect("all_time_version") as u32;
            } else {
                entry.2 = Some(balance);
                entry.3 = row.all_time_version.expect("all_time_version") as u32;
            }
        }
        Ok(ret)
    }

    #[instrument(
        name = "cala_ledger.balances.effective.find_for_update",
        skip(self, op)
    )]
    pub(super) async fn find_for_update(
        &self,
        op: &mut impl es_entity::AtomicOperation,
        journal_id: JournalId,
        (account_ids, currencies): (Vec<AccountId>, Vec<&str>),
        effective: NaiveDate,
    ) -> Result<HashMap<(AccountId, Currency), EffectiveBalanceData<'_>>, BalanceError> {
        let rows = sqlx::query!(
            r#"
          WITH pairs AS (
            SELECT account_id, currency
            FROM (
              SELECT * FROM UNNEST($2::uuid[], $3::text[]) AS v(account_id, currency)
            ) AS v
            JOIN cala_accounts a
            ON account_id = a.id
            WHERE eventually_consistent = FALSE
          ),
          delete_balances AS (
            DELETE FROM cala_cumulative_effective_balances
            WHERE journal_id = $1
              AND (account_id, currency) IN (SELECT account_id, currency FROM pairs)
              AND effective > $4
            RETURNING account_id, currency, effective, values
          ),
          values AS (
            SELECT 
              p.account_id,
              p.currency,
              b.values,
              b.all_time_version,
              b.effective
            FROM pairs p
            LEFT JOIN LATERAL (
              SELECT DISTINCT ON (account_id, currency)
                account_id,
                currency,
                values,
                all_time_version,
                effective
              FROM cala_cumulative_effective_balances
              WHERE journal_id = $1
                AND effective <= $4
                AND account_id = p.account_id
                AND currency = p.currency
              ORDER BY account_id, currency, all_time_version DESC
            ) b ON TRUE
          )
          SELECT
            v.account_id AS "account_id!: AccountId",
            v.currency AS "currency!",
            v.values AS "values?: serde_json::Value",
            v.all_time_version AS "all_time_version?: i32",
            v.effective AS "effective_date?: chrono::NaiveDate",
            COALESCE(
              jsonb_agg(
                jsonb_build_object('effective', d.effective, 'values', d.values)
              ) FILTER (WHERE d.values IS NOT NULL),
              '[]'::jsonb
            ) AS "deleted_values!: serde_json::Value"
          FROM values v
          LEFT JOIN delete_balances d
            ON v.account_id = d.account_id AND v.currency = d.currency
          GROUP BY v.account_id, v.currency, v.values, v.all_time_version, v.effective
        "#,
            journal_id as JournalId,
            &account_ids as &[AccountId],
            &currencies as &[&str],
            effective
        )
        .fetch_all(op.as_executor())
        .await?;

        let mut ret = HashMap::new();
        for row in rows {
            let last_snapshot = match (row.values, row.effective_date) {
                (Some(values), Some(effective_date)) => {
                    let snapshot = serde_json::from_value::<BalanceSnapshot>(values)
                        .expect("Failed to deserialize balance snapshot");
                    Some((effective_date, snapshot))
                }
                _ => None,
            };

            let updates = serde_json::from_value::<Vec<SnapshotOrEntry>>(row.deleted_values)
                .expect("Failed to deserialize deleted values array");

            let currency = row.currency.parse().expect("Failed to parse currency");
            ret.insert(
                (row.account_id, currency),
                EffectiveBalanceData::new(
                    row.account_id,
                    currency,
                    last_snapshot,
                    row.all_time_version.map(|v| v as u32).unwrap_or(0),
                    updates,
                ),
            );
        }
        Ok(ret)
    }

    #[instrument(
        name = "effective_balance.fetch_member_effective_history",
        skip_all,
        err(level = "warn")
    )]
    pub(super) async fn fetch_member_effective_history(
        &self,
        op: &mut impl es_entity::AtomicOperation,
        journal_id: JournalId,
        account_set_ids: &[AccountSetId],
        min_watermark: Option<i64>,
    ) -> Result<Vec<EffectiveMemberHistoryRow>, BalanceError> {
        let rows = sqlx::query!(
            r#"
            WITH member_accounts AS (
                SELECT DISTINCT m.member_account_id
                FROM cala_account_set_member_accounts m
                LEFT JOIN cala_account_sets s ON s.id = m.member_account_id
                WHERE m.account_set_id = ANY($1)
                  AND s.id IS NULL
            ),
            all_history AS (
                SELECT h.values, h.account_id, h.currency, h.version, h.seq,
                       t.effective AS effective_date
                FROM cala_balance_history h
                JOIN member_accounts ma ON ma.member_account_id = h.account_id
                JOIN cala_entries e ON e.id = h.latest_entry_id
                JOIN cala_transactions t ON t.id = e.transaction_id AND t.journal_id = $2
                WHERE h.journal_id = $2
            ),
            with_prev AS (
                SELECT values,
                       LAG(values) OVER (
                           PARTITION BY account_id, currency ORDER BY version
                       ) as prev_values,
                       seq, effective_date
                FROM all_history
            )
            SELECT values, prev_values, effective_date
            FROM with_prev
            WHERE ($3::bigint IS NULL OR seq > $3)
            ORDER BY effective_date, seq
            "#,
            account_set_ids as &[AccountSetId],
            journal_id as JournalId,
            min_watermark,
        )
        .fetch_all(op.as_executor())
        .await?;

        let mut result = Vec::with_capacity(rows.len());
        for row in rows {
            let snapshot: BalanceSnapshot =
                serde_json::from_value(row.values).expect("Failed to deserialize balance snapshot");
            let prev_snapshot: Option<BalanceSnapshot> = row.prev_values.map(|v| {
                serde_json::from_value(v).expect("Failed to deserialize previous balance snapshot")
            });

            result.push(EffectiveMemberHistoryRow {
                snapshot,
                prev_snapshot,
                effective_date: row.effective_date,
            });
        }

        Ok(result)
    }

    #[instrument(
        name = "effective_balance.fetch_effective_history_from_date",
        skip_all,
        err(level = "warn")
    )]
    pub(super) async fn fetch_effective_history_from_date(
        &self,
        op: &mut impl es_entity::AtomicOperation,
        journal_id: JournalId,
        account_set_ids: &[AccountSetId],
        from_effective: NaiveDate,
    ) -> Result<Vec<EffectiveMemberHistoryRow>, BalanceError> {
        let rows = sqlx::query!(
            r#"
            WITH member_accounts AS (
                SELECT DISTINCT m.member_account_id
                FROM cala_account_set_member_accounts m
                LEFT JOIN cala_account_sets s ON s.id = m.member_account_id
                WHERE m.account_set_id = ANY($1)
                  AND s.id IS NULL
            ),
            all_history AS (
                SELECT h.values, h.account_id, h.currency, h.version, h.seq,
                       t.effective AS effective_date
                FROM cala_balance_history h
                JOIN member_accounts ma ON ma.member_account_id = h.account_id
                JOIN cala_entries e ON e.id = h.latest_entry_id
                JOIN cala_transactions t ON t.id = e.transaction_id AND t.journal_id = $2
                WHERE h.journal_id = $2
            ),
            with_prev AS (
                SELECT values,
                       LAG(values) OVER (
                           PARTITION BY account_id, currency ORDER BY version
                       ) as prev_values,
                       seq, effective_date
                FROM all_history
            )
            SELECT values, prev_values, effective_date
            FROM with_prev
            WHERE effective_date >= $3
            ORDER BY effective_date, seq
            "#,
            account_set_ids as &[AccountSetId],
            journal_id as JournalId,
            from_effective,
        )
        .fetch_all(op.as_executor())
        .await?;

        let mut result = Vec::with_capacity(rows.len());
        for row in rows {
            let snapshot: BalanceSnapshot =
                serde_json::from_value(row.values).expect("Failed to deserialize balance snapshot");
            let prev_snapshot: Option<BalanceSnapshot> = row.prev_values.map(|v| {
                serde_json::from_value(v).expect("Failed to deserialize previous balance snapshot")
            });

            result.push(EffectiveMemberHistoryRow {
                snapshot,
                prev_snapshot,
                effective_date: row.effective_date,
            });
        }

        Ok(result)
    }

    #[instrument(
        name = "effective_balance.delete_at_or_after",
        skip_all,
        err(level = "warn")
    )]
    pub(super) async fn delete_at_or_after(
        &self,
        op: &mut impl es_entity::AtomicOperation,
        journal_id: JournalId,
        account_ids: &[AccountId],
        min_effective_date: NaiveDate,
    ) -> Result<(), BalanceError> {
        sqlx::query!(
            r#"
            DELETE FROM cala_cumulative_effective_balances
            WHERE journal_id = $1
              AND account_id = ANY($2)
              AND effective >= $3
            "#,
            journal_id as JournalId,
            account_ids as &[AccountId],
            min_effective_date,
        )
        .execute(op.as_executor())
        .await?;

        Ok(())
    }

    #[instrument(
        name = "effective_balance.load_latest_before",
        skip_all,
        err(level = "warn")
    )]
    pub(super) async fn load_latest_before(
        &self,
        op: &mut impl es_entity::AtomicOperation,
        journal_id: JournalId,
        account_ids: &[AccountId],
        min_effective_date: NaiveDate,
    ) -> Result<HashMap<(AccountId, Currency), LatestBeforeEntry>, BalanceError> {
        let rows = sqlx::query!(
            r#"
            SELECT DISTINCT ON (account_id, currency)
                account_id AS "account_id!: AccountId",
                currency AS "currency!",
                all_time_version,
                values
            FROM cala_cumulative_effective_balances
            WHERE journal_id = $1
              AND account_id = ANY($2)
              AND effective < $3
            ORDER BY account_id, currency, all_time_version DESC
            "#,
            journal_id as JournalId,
            account_ids as &[AccountId],
            min_effective_date,
        )
        .fetch_all(op.as_executor())
        .await?;

        let mut result = HashMap::new();
        for row in rows {
            let snapshot: BalanceSnapshot =
                serde_json::from_value(row.values).expect("Failed to deserialize balance snapshot");
            let currency: Currency = row.currency.parse().expect("Failed to parse currency");
            result.insert(
                (row.account_id, currency),
                LatestBeforeEntry {
                    snapshot,
                    all_time_version: row.all_time_version,
                },
            );
        }

        Ok(result)
    }

    #[instrument(
        name = "effective_balance.insert_recalc_snapshots",
        skip(self, op, snapshots)
    )]
    pub(super) async fn insert_recalc_snapshots(
        &self,
        op: &mut impl es_entity::AtomicOperation,
        journal_id: JournalId,
        snapshots: Vec<RecalcEffectiveSnapshot>,
    ) -> Result<(), BalanceError> {
        let mut journal_ids = Vec::with_capacity(snapshots.len());
        let mut account_ids = Vec::with_capacity(snapshots.len());
        let mut currencies = Vec::with_capacity(snapshots.len());
        let mut effectives = Vec::with_capacity(snapshots.len());
        let mut versions = Vec::with_capacity(snapshots.len());
        let mut all_time_versions = Vec::with_capacity(snapshots.len());
        let mut entry_ids = Vec::with_capacity(snapshots.len());
        let mut modified_timestamps = Vec::with_capacity(snapshots.len());
        let mut created_timestamps = Vec::with_capacity(snapshots.len());
        let mut values = Vec::with_capacity(snapshots.len());

        for snap in &snapshots {
            journal_ids.push(journal_id);
            account_ids.push(snap.account_id);
            currencies.push(snap.currency.code());
            effectives.push(snap.effective_date);
            versions.push(snap.snapshot.version as i32);
            all_time_versions.push(snap.all_time_version);
            entry_ids.push(snap.snapshot.entry_id);
            modified_timestamps.push(snap.snapshot.modified_at);
            created_timestamps.push(snap.snapshot.created_at);
            values.push(
                serde_json::to_value(&snap.snapshot).expect("Failed to serialize balance snapshot"),
            );
        }

        sqlx::query!(
            r#"
            INSERT INTO cala_cumulative_effective_balances (
              journal_id, account_id, currency, effective, version,
              all_time_version, latest_entry_id, updated_at, created_at, values
            )
            SELECT * FROM UNNEST(
                $1::uuid[],
                $2::uuid[],
                $3::text[],
                $4::date[],
                $5::integer[],
                $6::integer[],
                $7::uuid[],
                $8::timestamptz[],
                $9::timestamptz[],
                $10::jsonb[]
            )
            "#,
            &journal_ids as &[JournalId],
            &account_ids as &[AccountId],
            &currencies[..] as &[&str],
            &effectives[..],
            &versions[..],
            &all_time_versions[..],
            &entry_ids as &[EntryId],
            &modified_timestamps[..],
            &created_timestamps[..],
            &values[..]
        )
        .execute(op.as_executor())
        .await?;

        Ok(())
    }

    #[instrument(
        name = "cala_ledger.balances.effective.insert_new_snapshots",
        skip(self, op, new_balances)
    )]
    pub(crate) async fn insert_new_snapshots(
        &self,
        op: &mut impl es_entity::AtomicOperation,
        journal_id: JournalId,
        new_balances: Vec<EffectiveBalanceSnapshot>,
    ) -> Result<(), BalanceError> {
        let mut journal_ids = Vec::with_capacity(new_balances.len());
        let mut account_ids = Vec::with_capacity(new_balances.len());
        let mut currencies = Vec::with_capacity(new_balances.len());
        let mut effectives = Vec::with_capacity(new_balances.len());
        let mut versions = Vec::with_capacity(new_balances.len());
        let mut all_time_versions = Vec::with_capacity(new_balances.len());
        let mut entry_ids = Vec::with_capacity(new_balances.len());
        let mut modified_timestamps = Vec::with_capacity(new_balances.len());
        let mut created_timestamps = Vec::with_capacity(new_balances.len());
        let mut values = Vec::with_capacity(new_balances.len());

        for balance in new_balances.iter() {
            journal_ids.push(journal_id);
            account_ids.push(balance.account_id);
            currencies.push(balance.currency.code());
            effectives.push(balance.effective);
            versions.push(balance.version as i32);
            all_time_versions.push(balance.all_time_version as i32);
            entry_ids.push(balance.entry_id);
            modified_timestamps.push(balance.modified_at);
            created_timestamps.push(balance.created_at);
            values
                .push(serde_json::to_value(balance).expect("Failed to serialize balance snapshot"));
        }

        sqlx::query!(
            r#"
            INSERT INTO cala_cumulative_effective_balances (
              journal_id, account_id, currency, effective, version, all_time_version, latest_entry_id, updated_at, created_at, values
            )
            SELECT * FROM UNNEST(
                $1::uuid[],
                $2::uuid[],
                $3::text[],
                $4::date[],
                $5::integer[],
                $6::integer[],
                $7::uuid[],
                $8::timestamptz[],
                $9::timestamptz[],
                $10::jsonb[]
            )
            "#,
            &journal_ids as &[JournalId],
            &account_ids as &[AccountId],
            &currencies[..] as &[&str],
            &effectives[..],
            &versions[..],
            &all_time_versions[..],
            &entry_ids as &[EntryId],
            &modified_timestamps[..],
            &created_timestamps[..],
            &values[..]
        )
        .execute(op.as_executor())
        .await?;

        self.publisher
            .publish_all(
                op,
                new_balances.into_iter().map(|balance| {
                    if balance.all_time_version == 1 {
                        OutboxEventPayload::EffectiveBalanceCreated { balance }
                    } else {
                        OutboxEventPayload::EffectiveBalanceUpdated { balance }
                    }
                }),
            )
            .await?;

        Ok(())
    }
}

pub(super) struct EffectiveMemberHistoryRow {
    pub(super) snapshot: BalanceSnapshot,
    pub(super) prev_snapshot: Option<BalanceSnapshot>,
    pub(super) effective_date: NaiveDate,
}

pub(super) struct RecalcEffectiveSnapshot {
    pub(super) account_id: AccountId,
    pub(super) currency: Currency,
    pub(super) effective_date: NaiveDate,
    pub(super) snapshot: BalanceSnapshot,
    pub(super) all_time_version: i32,
}