-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain_test.go
More file actions
3986 lines (3222 loc) · 126 KB
/
Copy pathmain_test.go
File metadata and controls
3986 lines (3222 loc) · 126 KB
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
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package main
import (
"context"
"fmt"
"os"
"testing"
"time"
"github.com/j0lvera/pgbudget/testutils/pgcontainer"
"github.com/jackc/pgx/v5"
is_ "github.com/matryer/is"
"github.com/rs/zerolog"
)
var (
testDSN string
log zerolog.Logger
)
func TestMain(m *testing.M) {
// Setup logging
log = zerolog.New(os.Stdout).With().Timestamp().Logger()
// Create a context with timeout for setup
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)
defer cancel()
// Configure and start the PostgreSQL container
cfg := pgcontainer.NewConfig()
cfg.WithLogger(&log).WithMigrationsPath("migrations") // Path relative to project root (src)
pgContainer := pgcontainer.NewPgContainer(cfg)
output, err := pgContainer.Start(ctx)
if err != nil {
log.Fatal().Err(err).Msg("Failed to start PostgreSQL container")
}
// Store the DSN for tests to use
testDSN = output.DSN()
// Run the tests
exitCode := m.Run()
// Exit with the same code as the tests
os.Exit(exitCode)
}
// getBalance fetches raw counters from ledger.get_balance
func getBalance(ctx context.Context, conn *pgx.Conn, accountUUID string) (int64, int64, error) {
var debits, credits int64
err := conn.QueryRow(ctx,
`select debits_total, credits_total from ledger.get_balance($1)`,
accountUUID,
).Scan(&debits, &credits)
return debits, credits, err
}
// setTestUserContext sets the user context for the database session
// This simulates what the Go microservice would do for each authenticated request
func setTestUserContext(ctx context.Context, conn *pgx.Conn, userID string) error {
// Set the session variable to persist for the entire connection
_, err := conn.Exec(ctx, "SELECT set_config('app.current_user_id', $1, false)", userID)
return err
}
// verifyTestUserContext verifies that the user context is set correctly
func verifyTestUserContext(ctx context.Context, conn *pgx.Conn, expectedUserID string) error {
var userFromSession string
err := conn.QueryRow(ctx, `SELECT utils.get_user()`).Scan(&userFromSession)
if err != nil {
return fmt.Errorf("failed to get user from utils.get_user(): %w", err)
}
if userFromSession != expectedUserID {
return fmt.Errorf("expected user %q, got %q", expectedUserID, userFromSession)
}
return nil
}
func TestLedger(t *testing.T) {
is := is_.New(t)
ctx := context.Background()
conn, err := pgx.Connect(ctx, testDSN)
is.NoErr(err)
t.Cleanup(func() { conn.Close(ctx) })
testUserID := "ledger_test_user"
err = setTestUserContext(ctx, conn, testUserID)
is.NoErr(err)
t.Run("SchemaExists", func(t *testing.T) {
is := is_.New(t)
var exists bool
err := conn.QueryRow(ctx, `
select exists (
select 1 from information_schema.schemata where schema_name = 'ledger'
)
`).Scan(&exists)
is.NoErr(err)
is.True(exists)
})
// create a ledger for subsequent tests
var ledgerUUID string
t.Run("CreateLedger", func(t *testing.T) {
is := is_.New(t)
err := conn.QueryRow(ctx, `select ledger.create_ledger('Test Ledger')`).Scan(&ledgerUUID)
is.NoErr(err)
is.True(len(ledgerUUID) == 8)
})
t.Run("CreateLedgerWithDescription", func(t *testing.T) {
is := is_.New(t)
var uuid string
err := conn.QueryRow(ctx, `select ledger.create_ledger('Described Ledger', 'A test ledger')`).Scan(&uuid)
is.NoErr(err)
var desc *string
err = conn.QueryRow(ctx, `select description from data.ledgers where uuid = $1`, uuid).Scan(&desc)
is.NoErr(err)
is.True(desc != nil)
is.Equal(*desc, "A test ledger")
})
t.Run("CreateLedgerRejectsEmptyName", func(t *testing.T) {
is := is_.New(t)
_, err := conn.Exec(ctx, `select ledger.create_ledger('')`)
is.True(err != nil)
_, err = conn.Exec(ctx, `select ledger.create_ledger(' ')`)
is.True(err != nil)
})
// create accounts for transaction tests
var checkingUUID, savingsUUID, visaUUID, incomeUUID string
t.Run("CreateAccount", func(t *testing.T) {
is := is_.New(t)
err := conn.QueryRow(ctx, `select ledger.create_account($1, 'Checking')`, ledgerUUID).Scan(&checkingUUID)
is.NoErr(err)
is.True(len(checkingUUID) == 8)
err = conn.QueryRow(ctx, `select ledger.create_account($1, 'Savings')`, ledgerUUID).Scan(&savingsUUID)
is.NoErr(err)
err = conn.QueryRow(ctx, `select ledger.create_account($1, 'Visa')`, ledgerUUID).Scan(&visaUUID)
is.NoErr(err)
err = conn.QueryRow(ctx, `select ledger.create_account($1, 'Revenue')`, ledgerUUID).Scan(&incomeUUID)
is.NoErr(err)
})
t.Run("CreateAccountRejectsEmptyName", func(t *testing.T) {
is := is_.New(t)
_, err := conn.Exec(ctx, `select ledger.create_account($1, '')`, ledgerUUID)
is.True(err != nil)
})
t.Run("CreateAccountRejectsInvalidLedger", func(t *testing.T) {
is := is_.New(t)
_, err := conn.Exec(ctx, `select ledger.create_account('nonexistent', 'Checking')`)
is.True(err != nil)
})
// post_transaction tests
t.Run("PostTransaction", func(t *testing.T) {
is := is_.New(t)
var txUUID string
err := conn.QueryRow(ctx, `
select ledger.post_transaction($1, $2, $3, 100000, '2025-03-15', 'Paycheck')
`, ledgerUUID, checkingUUID, incomeUUID).Scan(&txUUID)
is.NoErr(err)
is.True(len(txUUID) == 8)
})
t.Run("PostTransactionUpdatesCounters", func(t *testing.T) {
is := is_.New(t)
// checking was debited 100000
var debits, credits int64
err := conn.QueryRow(ctx, `
select debits_total, credits_total from data.accounts where uuid = $1
`, checkingUUID).Scan(&debits, &credits)
is.NoErr(err)
is.Equal(debits, int64(100000))
is.Equal(credits, int64(0))
// income was credited 100000
err = conn.QueryRow(ctx, `
select debits_total, credits_total from data.accounts where uuid = $1
`, incomeUUID).Scan(&debits, &credits)
is.NoErr(err)
is.Equal(debits, int64(0))
is.Equal(credits, int64(100000))
})
t.Run("PostTransactionCreatesBalanceHistory", func(t *testing.T) {
is := is_.New(t)
// should have balance history entries for both accounts
var count int
err := conn.QueryRow(ctx, `
select count(*) from data.balances
where user_data = $1
`, testUserID).Scan(&count)
is.NoErr(err)
is.Equal(count, 2) // one for debit account, one for credit account
})
t.Run("PostTransactionBalanceHistoryIsCorrect", func(t *testing.T) {
is := is_.New(t)
// checking: debits_total=100000, credits_total=0
var debits, credits int64
err := conn.QueryRow(ctx, `
select debits_total, credits_total from data.balances
where account_id = (select id from data.accounts where uuid = $1)
order by transaction_id desc limit 1
`, checkingUUID).Scan(&debits, &credits)
is.NoErr(err)
is.Equal(debits, int64(100000))
is.Equal(credits, int64(0))
})
t.Run("PostMultipleTransactions", func(t *testing.T) {
is := is_.New(t)
// spend from checking to visa (simulating a payment)
var txUUID string
err := conn.QueryRow(ctx, `
select ledger.post_transaction($1, $2, $3, 25000, '2025-03-16', 'Visa payment')
`, ledgerUUID, visaUUID, checkingUUID).Scan(&txUUID)
is.NoErr(err)
// checking: debited 100000 (paycheck), credited 25000 (visa payment)
var debits, credits int64
err = conn.QueryRow(ctx, `
select debits_total, credits_total from data.accounts where uuid = $1
`, checkingUUID).Scan(&debits, &credits)
is.NoErr(err)
is.Equal(debits, int64(100000))
is.Equal(credits, int64(25000))
// visa: debited 25000
err = conn.QueryRow(ctx, `
select debits_total, credits_total from data.accounts where uuid = $1
`, visaUUID).Scan(&debits, &credits)
is.NoErr(err)
is.Equal(debits, int64(25000))
is.Equal(credits, int64(0))
})
t.Run("BalanceFromCounters", func(t *testing.T) {
is := is_.New(t)
var debits, credits int64
// checking: debits=100000 credits=25000
debits, credits, err := getBalance(ctx, conn, checkingUUID)
is.NoErr(err)
is.Equal(debits, int64(100000))
is.Equal(credits, int64(25000))
// income: debits=0 credits=100000
debits, credits, err = getBalance(ctx, conn, incomeUUID)
is.NoErr(err)
is.Equal(debits, int64(0))
is.Equal(credits, int64(100000))
// visa: debits=25000 credits=0
debits, credits, err = getBalance(ctx, conn, visaUUID)
is.NoErr(err)
is.Equal(debits, int64(25000))
is.Equal(credits, int64(0))
})
t.Run("PostTransactionRejectsZeroAmount", func(t *testing.T) {
is := is_.New(t)
_, err := conn.Exec(ctx, `
select ledger.post_transaction($1, $2, $3, 0, '2025-03-15', 'Zero')
`, ledgerUUID, checkingUUID, incomeUUID)
is.True(err != nil)
})
t.Run("PostTransactionRejectsNegativeAmount", func(t *testing.T) {
is := is_.New(t)
_, err := conn.Exec(ctx, `
select ledger.post_transaction($1, $2, $3, -100, '2025-03-15', 'Negative')
`, ledgerUUID, checkingUUID, incomeUUID)
is.True(err != nil)
})
t.Run("PostTransactionRejectsSameAccount", func(t *testing.T) {
is := is_.New(t)
_, err := conn.Exec(ctx, `
select ledger.post_transaction($1, $2, $2, 100, '2025-03-15', 'Self')
`, ledgerUUID, checkingUUID)
is.True(err != nil)
})
t.Run("PostTransactionRejectsInvalidDebit", func(t *testing.T) {
is := is_.New(t)
_, err := conn.Exec(ctx, `
select ledger.post_transaction($1, 'nonexistent', $2, 100, '2025-03-15', 'Bad')
`, ledgerUUID, incomeUUID)
is.True(err != nil)
})
t.Run("PostTransactionRejectsInvalidCredit", func(t *testing.T) {
is := is_.New(t)
_, err := conn.Exec(ctx, `
select ledger.post_transaction($1, $2, 'nonexistent', 100, '2025-03-15', 'Bad')
`, ledgerUUID, checkingUUID)
is.True(err != nil)
})
t.Run("PostTransactionRejectsInvalidLedger", func(t *testing.T) {
is := is_.New(t)
_, err := conn.Exec(ctx, `
select ledger.post_transaction('nonexistent', $1, $2, 100, '2025-03-15', 'Bad')
`, checkingUUID, incomeUUID)
is.True(err != nil)
})
t.Run("PostTransactionDefaultDate", func(t *testing.T) {
is := is_.New(t)
// omit the date parameter to use the default (current_date)
var txUUID string
err := conn.QueryRow(ctx, `
select ledger.post_transaction($1, $2, $3, 500)
`, ledgerUUID, checkingUUID, incomeUUID).Scan(&txUUID)
is.NoErr(err)
var txDate time.Time
err = conn.QueryRow(ctx, `select date from data.transactions where uuid = $1`, txUUID).Scan(&txDate)
is.NoErr(err)
now := time.Now().UTC()
is.Equal(txDate.Year(), now.Year())
is.Equal(txDate.Month(), now.Month())
is.Equal(txDate.Day(), now.Day())
})
// --- void and correct tests ---
// set up a fresh ledger for void/correct tests to avoid interference
var voidLedgerUUID, voidCheckingUUID, voidIncomeUUID string
t.Run("VoidSetup", func(t *testing.T) {
is := is_.New(t)
err := conn.QueryRow(ctx, `select ledger.create_ledger('Void Test Ledger')`).Scan(&voidLedgerUUID)
is.NoErr(err)
err = conn.QueryRow(ctx, `select ledger.create_account($1, 'Checking')`, voidLedgerUUID).Scan(&voidCheckingUUID)
is.NoErr(err)
err = conn.QueryRow(ctx, `select ledger.create_account($1, 'Revenue')`, voidLedgerUUID).Scan(&voidIncomeUUID)
is.NoErr(err)
})
t.Run("VoidCreatesReversal", func(t *testing.T) {
is := is_.New(t)
// post a transaction
var txUUID string
err := conn.QueryRow(ctx, `
select ledger.post_transaction($1, $2, $3, 50000, '2025-03-15', 'Original payment')
`, voidLedgerUUID, voidCheckingUUID, voidIncomeUUID).Scan(&txUUID)
is.NoErr(err)
// verify counters before void
debits, credits, err := getBalance(ctx, conn, voidCheckingUUID)
is.NoErr(err)
is.Equal(debits, int64(50000))
is.Equal(credits, int64(0))
// void it
var reversalUUID string
err = conn.QueryRow(ctx, `select ledger.void($1, 'Wrong amount')`, txUUID).Scan(&reversalUUID)
is.NoErr(err)
is.True(len(reversalUUID) == 8)
// after void: reversal credits the same amount back, net zero
debits, credits, err = getBalance(ctx, conn, voidCheckingUUID)
is.NoErr(err)
is.Equal(debits, int64(50000))
is.Equal(credits, int64(50000))
})
t.Run("VoidCreatesTransactionLog", func(t *testing.T) {
is := is_.New(t)
var mutationType, reason string
err := conn.QueryRow(ctx, `
select mutation_type, reason from data.transaction_log
where user_data = $1
order by created_at desc limit 1
`, testUserID).Scan(&mutationType, &reason)
is.NoErr(err)
is.Equal(mutationType, "deletion")
is.Equal(reason, "Wrong amount")
})
t.Run("VoidRejectsInvalidTransaction", func(t *testing.T) {
is := is_.New(t)
_, err := conn.Exec(ctx, `select ledger.void('nonexistent')`)
is.True(err != nil)
})
t.Run("CorrectChangesAmount", func(t *testing.T) {
is := is_.New(t)
// post a transaction
var txUUID string
err := conn.QueryRow(ctx, `
select ledger.post_transaction($1, $2, $3, 10000, '2025-03-20', 'Groceries')
`, voidLedgerUUID, voidCheckingUUID, voidIncomeUUID).Scan(&txUUID)
is.NoErr(err)
// correct amount from 10000 to 15000
var correctionUUID string
err = conn.QueryRow(ctx, `
select ledger.correct($1, p_amount := 15000, p_reason := 'Was $100 not $150')
`, txUUID).Scan(&correctionUUID)
is.NoErr(err)
is.True(len(correctionUUID) == 8)
is.True(correctionUUID != txUUID) // should be a new transaction
// verify corrected transaction has new amount
var amount int64
err = conn.QueryRow(ctx, `select amount from data.transactions where uuid = $1`, correctionUUID).Scan(&amount)
is.NoErr(err)
is.Equal(amount, int64(15000))
})
t.Run("CorrectPreservesUnchangedFields", func(t *testing.T) {
is := is_.New(t)
// post a transaction
var txUUID string
err := conn.QueryRow(ctx, `
select ledger.post_transaction($1, $2, $3, 20000, '2025-04-01', 'Rent')
`, voidLedgerUUID, voidCheckingUUID, voidIncomeUUID).Scan(&txUUID)
is.NoErr(err)
// correct only the description
var correctionUUID string
err = conn.QueryRow(ctx, `
select ledger.correct($1, p_description := 'April rent')
`, txUUID).Scan(&correctionUUID)
is.NoErr(err)
// verify amount and date carried over, description changed
var amount int64
var desc string
var txDate time.Time
err = conn.QueryRow(ctx, `
select amount, description, date from data.transactions where uuid = $1
`, correctionUUID).Scan(&amount, &desc, &txDate)
is.NoErr(err)
is.Equal(amount, int64(20000)) // unchanged
is.Equal(desc, "April rent") // changed
is.Equal(txDate.Day(), 1) // unchanged
})
t.Run("CorrectCreatesTransactionLog", func(t *testing.T) {
is := is_.New(t)
var mutationType string
var reversalID, correctionID *int64
err := conn.QueryRow(ctx, `
select mutation_type, reversal_transaction_id, correction_transaction_id
from data.transaction_log
where user_data = $1 and mutation_type = 'correction'
order by created_at desc limit 1
`, testUserID).Scan(&mutationType, &reversalID, &correctionID)
is.NoErr(err)
is.Equal(mutationType, "correction")
is.True(reversalID != nil) // reversal was created
is.True(correctionID != nil) // correction was created
})
t.Run("CorrectRejectsInvalidTransaction", func(t *testing.T) {
is := is_.New(t)
_, err := conn.Exec(ctx, `select ledger.correct('nonexistent', p_amount := 100)`)
is.True(err != nil)
})
t.Run("CorrectBalancesAreCorrect", func(t *testing.T) {
is := is_.New(t)
// fresh ledger for clean balance check
var freshLedger, freshChecking, freshIncome string
err := conn.QueryRow(ctx, `select ledger.create_ledger('Balance Correct Test')`).Scan(&freshLedger)
is.NoErr(err)
err = conn.QueryRow(ctx, `select ledger.create_account($1, 'Checking')`, freshLedger).Scan(&freshChecking)
is.NoErr(err)
err = conn.QueryRow(ctx, `select ledger.create_account($1, 'Revenue')`, freshLedger).Scan(&freshIncome)
is.NoErr(err)
// post 10000
var txUUID string
err = conn.QueryRow(ctx, `
select ledger.post_transaction($1, $2, $3, 10000, '2025-03-15', 'Original')
`, freshLedger, freshChecking, freshIncome).Scan(&txUUID)
is.NoErr(err)
// correct to 15000 — reversal (-10000) + new (+15000) = net 15000
_, err = conn.Exec(ctx, `select ledger.correct($1, p_amount := 15000)`, txUUID)
is.NoErr(err)
// checking: original 10000 debit + reversal 10000 credit + new 15000 debit
debits, credits, err := getBalance(ctx, conn, freshChecking)
is.NoErr(err)
is.Equal(debits, int64(25000)) // 10000 + 15000
is.Equal(credits, int64(10000)) // reversal
})
}
func TestLedgerQueries(t *testing.T) {
is := is_.New(t)
ctx := context.Background()
conn, err := pgx.Connect(ctx, testDSN)
is.NoErr(err)
t.Cleanup(func() { conn.Close(ctx) })
testUserID := "ledger_queries_test_user"
err = setTestUserContext(ctx, conn, testUserID)
is.NoErr(err)
// set up ledger with accounts and transactions
var ledgerUUID, checkingUUID, savingsUUID, revenueUUID string
err = conn.QueryRow(ctx, `select ledger.create_ledger('Query Test Ledger')`).Scan(&ledgerUUID)
is.NoErr(err)
err = conn.QueryRow(ctx, `select ledger.create_account($1, 'Checking')`, ledgerUUID).Scan(&checkingUUID)
is.NoErr(err)
err = conn.QueryRow(ctx, `select ledger.create_account($1, 'Savings')`, ledgerUUID).Scan(&savingsUUID)
is.NoErr(err)
err = conn.QueryRow(ctx, `select ledger.create_account($1, 'Revenue')`, ledgerUUID).Scan(&revenueUUID)
is.NoErr(err)
// post some transactions
// 1. income: debit checking 100000, credit revenue
_, err = conn.Exec(ctx, `select ledger.post_transaction($1, $2, $3, 100000, '2025-03-01', 'Paycheck')`, ledgerUUID, checkingUUID, revenueUUID)
is.NoErr(err)
// 2. transfer: debit savings 30000, credit checking (move to savings)
_, err = conn.Exec(ctx, `select ledger.post_transaction($1, $2, $3, 30000, '2025-03-05', 'To savings')`, ledgerUUID, savingsUUID, checkingUUID)
is.NoErr(err)
// 3. another income: debit checking 50000, credit revenue
_, err = conn.Exec(ctx, `select ledger.post_transaction($1, $2, $3, 50000, '2025-03-15', 'Freelance')`, ledgerUUID, checkingUUID, revenueUUID)
is.NoErr(err)
t.Run("GetBalance", func(t *testing.T) {
is := is_.New(t)
// checking: debits=150000, credits=30000
debits, credits, err := getBalance(ctx, conn, checkingUUID)
is.NoErr(err)
is.Equal(debits, int64(150000))
is.Equal(credits, int64(30000))
// savings: debits=30000, credits=0
debits, credits, err = getBalance(ctx, conn, savingsUUID)
is.NoErr(err)
is.Equal(debits, int64(30000))
is.Equal(credits, int64(0))
// revenue: debits=0, credits=150000
debits, credits, err = getBalance(ctx, conn, revenueUUID)
is.NoErr(err)
is.Equal(debits, int64(0))
is.Equal(credits, int64(150000))
})
t.Run("GetBalanceRejectsInvalidAccount", func(t *testing.T) {
is := is_.New(t)
_, err := conn.Exec(ctx, `select ledger.get_balance('nonexistent')`)
is.True(err != nil)
})
t.Run("GetBalances", func(t *testing.T) {
is := is_.New(t)
type accountBalance struct {
UUID string
Name string
Debits int64
Credits int64
}
rows, err := conn.Query(ctx, `select * from ledger.get_balances($1)`, ledgerUUID)
is.NoErr(err)
defer rows.Close()
var balances []accountBalance
for rows.Next() {
var ab accountBalance
err := rows.Scan(&ab.UUID, &ab.Name, &ab.Debits, &ab.Credits)
is.NoErr(err)
balances = append(balances, ab)
}
is.NoErr(rows.Err())
// should have at least our 3 accounts
is.True(len(balances) >= 3)
// find our accounts and verify counters
var foundChecking, foundSavings, foundRevenue bool
for _, ab := range balances {
switch ab.UUID {
case checkingUUID:
is.Equal(ab.Debits, int64(150000))
is.Equal(ab.Credits, int64(30000))
foundChecking = true
case savingsUUID:
is.Equal(ab.Debits, int64(30000))
is.Equal(ab.Credits, int64(0))
foundSavings = true
case revenueUUID:
is.Equal(ab.Debits, int64(0))
is.Equal(ab.Credits, int64(150000))
foundRevenue = true
}
}
is.True(foundChecking)
is.True(foundSavings)
is.True(foundRevenue)
})
t.Run("GetBalancesRejectsInvalidLedger", func(t *testing.T) {
is := is_.New(t)
_, err := conn.Exec(ctx, `select * from ledger.get_balances('nonexistent')`)
is.True(err != nil)
})
t.Run("GetHistory", func(t *testing.T) {
is := is_.New(t)
type historyRow struct {
TxUUID string
Date time.Time
Description string
Counterparty string
Amount int64
Direction string
DebitsTotal int64
CreditsTotal int64
}
rows, err := conn.Query(ctx, `select * from ledger.get_history($1)`, checkingUUID)
is.NoErr(err)
defer rows.Close()
var history []historyRow
for rows.Next() {
var h historyRow
err := rows.Scan(&h.TxUUID, &h.Date, &h.Description, &h.Counterparty, &h.Amount, &h.Direction, &h.DebitsTotal, &h.CreditsTotal)
is.NoErr(err)
history = append(history, h)
}
is.NoErr(rows.Err())
// checking has 3 transactions, newest first
is.Equal(len(history), 3)
// most recent: Freelance (debit checking 50000)
is.Equal(history[0].Description, "Freelance")
is.Equal(history[0].Amount, int64(50000))
is.Equal(history[0].Direction, "debit")
is.Equal(history[0].DebitsTotal, int64(150000))
is.Equal(history[0].CreditsTotal, int64(30000))
// middle: To savings (credit checking 30000)
is.Equal(history[1].Description, "To savings")
is.Equal(history[1].Amount, int64(30000))
is.Equal(history[1].Direction, "credit")
is.Equal(history[1].DebitsTotal, int64(100000))
is.Equal(history[1].CreditsTotal, int64(30000))
// oldest: Paycheck (debit checking 100000)
is.Equal(history[2].Description, "Paycheck")
is.Equal(history[2].Amount, int64(100000))
is.Equal(history[2].Direction, "debit")
is.Equal(history[2].DebitsTotal, int64(100000))
is.Equal(history[2].CreditsTotal, int64(0))
})
t.Run("GetHistoryCounterparty", func(t *testing.T) {
is := is_.New(t)
rows, err := conn.Query(ctx, `select counterparty from ledger.get_history($1)`, checkingUUID)
is.NoErr(err)
defer rows.Close()
var counterparties []string
for rows.Next() {
var cp string
err := rows.Scan(&cp)
is.NoErr(err)
counterparties = append(counterparties, cp)
}
is.NoErr(rows.Err())
// counterparty is the other account in each transaction
is.Equal(counterparties[0], "Revenue") // Freelance: debit checking, credit revenue
is.Equal(counterparties[1], "Savings") // To savings: debit savings, credit checking
is.Equal(counterparties[2], "Revenue") // Paycheck: debit checking, credit revenue
})
t.Run("GetHistoryRejectsInvalidAccount", func(t *testing.T) {
is := is_.New(t)
_, err := conn.Exec(ctx, `select * from ledger.get_history('nonexistent')`)
is.True(err != nil)
})
}
func TestLinkedTransfers(t *testing.T) {
is := is_.New(t)
ctx := context.Background()
conn, err := pgx.Connect(ctx, testDSN)
is.NoErr(err)
t.Cleanup(func() { conn.Close(ctx) })
testUserID := "linked_test_user"
err = setTestUserContext(ctx, conn, testUserID)
is.NoErr(err)
var ledgerUUID string
err = conn.QueryRow(ctx, `select ledger.create_ledger('Linked Test')`).Scan(&ledgerUUID)
is.NoErr(err)
// manually create the clearing account (internal, for linked transfers)
var clearingUUID string
err = conn.QueryRow(ctx, `
insert into data.accounts (name, ledger_id, user_data, visibility)
values ('clearing', (select id from data.ledgers where uuid = $1), $2, 'internal')
returning uuid
`, ledgerUUID, testUserID).Scan(&clearingUUID)
is.NoErr(err)
// create user accounts
var checkingUUID, visaUUID, revenueUUID string
err = conn.QueryRow(ctx, `select ledger.create_account($1, 'Checking')`, ledgerUUID).Scan(&checkingUUID)
is.NoErr(err)
err = conn.QueryRow(ctx, `select ledger.create_account($1, 'Visa')`, ledgerUUID).Scan(&visaUUID)
is.NoErr(err)
err = conn.QueryRow(ctx, `select ledger.create_account($1, 'Revenue')`, ledgerUUID).Scan(&revenueUUID)
is.NoErr(err)
// seed checking with balance
_, err = conn.Exec(ctx, `select ledger.post_transaction($1, $2, $3, 500000, '2025-03-01', 'Seed')`, ledgerUUID, checkingUUID, revenueUUID)
is.NoErr(err)
t.Run("ClearingAccountVisibility", func(t *testing.T) {
is := is_.New(t)
is.True(len(clearingUUID) == 8)
// clearing account should NOT show in default get_accounts
var count int
err := conn.QueryRow(ctx, `
select count(*) from ledger.get_accounts($1)
where account_name = 'clearing'
`, ledgerUUID).Scan(&count)
is.NoErr(err)
is.Equal(count, 0) // hidden by default
// but should show with include_internal
err = conn.QueryRow(ctx, `
select count(*) from ledger.get_accounts($1, true)
where account_name = 'clearing'
`, ledgerUUID).Scan(&count)
is.NoErr(err)
is.Equal(count, 1)
})
t.Run("PostLinkedCreditCardPayment", func(t *testing.T) {
is := is_.New(t)
var uuids []string
err := conn.QueryRow(ctx, `
select ledger.post_linked($1, $2::jsonb)
`, ledgerUUID, fmt.Sprintf(`[
{"debit": "%s", "credit": "%s", "amount": 50000, "date": "2025-03-28", "description": "VISA PAYMENT"},
{"debit": "%s", "credit": "%s", "amount": 50000, "date": "2025-03-30", "description": "PAYMENT RECEIVED"}
]`, clearingUUID, checkingUUID, visaUUID, clearingUUID)).Scan(&uuids)
is.NoErr(err)
is.Equal(len(uuids), 2)
// verify both share the same link_id
var link1, link2 *int64
err = conn.QueryRow(ctx, `select link_id from data.transactions where uuid = $1`, uuids[0]).Scan(&link1)
is.NoErr(err)
err = conn.QueryRow(ctx, `select link_id from data.transactions where uuid = $1`, uuids[1]).Scan(&link2)
is.NoErr(err)
is.True(link1 != nil)
is.True(link2 != nil)
is.Equal(*link1, *link2) // same link_id
})
t.Run("ClearingAccountNetsToZero", func(t *testing.T) {
is := is_.New(t)
debits, credits, err := getBalance(ctx, conn, clearingUUID)
is.NoErr(err)
is.Equal(debits, credits) // clearing always nets to zero
})
t.Run("GetHistoryResolvesCounterparty", func(t *testing.T) {
is := is_.New(t)
// checking history should show Visa as counterparty, not Clearing
var counterparty string
err := conn.QueryRow(ctx, `
select counterparty from ledger.get_history($1)
where description = 'VISA PAYMENT'
`, checkingUUID).Scan(&counterparty)
is.NoErr(err)
is.Equal(counterparty, "Visa") // resolved through clearing
// visa history should show Checking as counterparty
err = conn.QueryRow(ctx, `
select counterparty from ledger.get_history($1)
where description = 'PAYMENT RECEIVED'
`, visaUUID).Scan(&counterparty)
is.NoErr(err)
is.Equal(counterparty, "Checking") // resolved through clearing
})
t.Run("GetHistoryShowsCorrectDatesPerSide", func(t *testing.T) {
is := is_.New(t)
// checking should show March 28
var checkingDate time.Time
err := conn.QueryRow(ctx, `
select date from ledger.get_history($1)
where description = 'VISA PAYMENT'
`, checkingUUID).Scan(&checkingDate)
is.NoErr(err)
is.Equal(checkingDate.Day(), 28)
// visa should show March 30
var visaDate time.Time
err = conn.QueryRow(ctx, `
select date from ledger.get_history($1)
where description = 'PAYMENT RECEIVED'
`, visaUUID).Scan(&visaDate)
is.NoErr(err)
is.Equal(visaDate.Day(), 30)
})
t.Run("LinkedIsAtomic", func(t *testing.T) {
is := is_.New(t)
// second entry has invalid account — whole batch should fail
_, err := conn.Exec(ctx, `
select ledger.post_linked($1, $2::jsonb)
`, ledgerUUID, fmt.Sprintf(`[
{"debit": "%s", "credit": "%s", "amount": 1000, "description": "Good"},
{"debit": "nonexistent", "credit": "%s", "amount": 1000, "description": "Bad"}
]`, clearingUUID, checkingUUID, clearingUUID))
is.True(err != nil)
})
t.Run("LinkedRequiresAtLeastTwo", func(t *testing.T) {
is := is_.New(t)
_, err := conn.Exec(ctx, `
select ledger.post_linked($1, $2::jsonb)
`, ledgerUUID, fmt.Sprintf(`[
{"debit": "%s", "credit": "%s", "amount": 1000}
]`, clearingUUID, checkingUUID))
is.True(err != nil) // needs at least 2
})
t.Run("LinkedWithThreeLegs", func(t *testing.T) {
is := is_.New(t)
// split payment: checking pays $300, visa pays $200, total $500 to revenue
var uuids []string
err := conn.QueryRow(ctx, `
select ledger.post_linked($1, $2::jsonb)
`, ledgerUUID, fmt.Sprintf(`[
{"debit": "%s", "credit": "%s", "amount": 30000, "date": "2025-04-01", "description": "Checking portion"},
{"debit": "%s", "credit": "%s", "amount": 20000, "date": "2025-04-01", "description": "Visa portion"},
{"debit": "%s", "credit": "%s", "amount": 50000, "date": "2025-04-01", "description": "Total to revenue"}
]`, clearingUUID, checkingUUID, clearingUUID, visaUUID, revenueUUID, clearingUUID)).Scan(&uuids)
is.NoErr(err)
is.Equal(len(uuids), 3)
// clearing still nets to zero
debits, credits, err := getBalance(ctx, conn, clearingUUID)
is.NoErr(err)
is.Equal(debits, credits)
})
}
func TestAccountClosing(t *testing.T) {
is := is_.New(t)
ctx := context.Background()
conn, err := pgx.Connect(ctx, testDSN)
is.NoErr(err)
t.Cleanup(func() { conn.Close(ctx) })
testUserID := "closing_test_user"
err = setTestUserContext(ctx, conn, testUserID)
is.NoErr(err)
var ledgerUUID, checkingUUID, savingsUUID, revenueUUID string
err = conn.QueryRow(ctx, `select ledger.create_ledger('Closing Test')`).Scan(&ledgerUUID)
is.NoErr(err)
err = conn.QueryRow(ctx, `select ledger.create_account($1, 'Checking')`, ledgerUUID).Scan(&checkingUUID)
is.NoErr(err)
err = conn.QueryRow(ctx, `select ledger.create_account($1, 'Savings')`, ledgerUUID).Scan(&savingsUUID)
is.NoErr(err)
err = conn.QueryRow(ctx, `select ledger.create_account($1, 'Revenue')`, ledgerUUID).Scan(&revenueUUID)
is.NoErr(err)
// seed some balance
_, err = conn.Exec(ctx, `select ledger.post_transaction($1, $2, $3, 100000, '2025-03-01', 'Seed')`, ledgerUUID, checkingUUID, revenueUUID)
is.NoErr(err)
t.Run("CloseAccount", func(t *testing.T) {
is := is_.New(t)
_, err := conn.Exec(ctx, `select ledger.close_account($1)`, savingsUUID)
is.NoErr(err)
var isClosed bool
err = conn.QueryRow(ctx, `select is_closed from data.accounts where uuid = $1`, savingsUUID).Scan(&isClosed)
is.NoErr(err)
is.True(isClosed)
})
t.Run("PostTransactionRejectedOnClosedDebit", func(t *testing.T) {
is := is_.New(t)
_, err := conn.Exec(ctx, `
select ledger.post_transaction($1, $2, $3, 1000, '2025-03-02', 'Should fail')
`, ledgerUUID, savingsUUID, revenueUUID)
is.True(err != nil)
})
t.Run("PostTransactionRejectedOnClosedCredit", func(t *testing.T) {
is := is_.New(t)
_, err := conn.Exec(ctx, `
select ledger.post_transaction($1, $2, $3, 1000, '2025-03-02', 'Should fail')
`, ledgerUUID, checkingUUID, savingsUUID)
is.True(err != nil)
})
t.Run("ReserveRejectedOnClosedAccount", func(t *testing.T) {
is := is_.New(t)
_, err := conn.Exec(ctx, `
select ledger.reserve($1, $2, $3, 1000, 300)
`, ledgerUUID, savingsUUID, revenueUUID)
is.True(err != nil)
})
t.Run("CommitRejectedOnClosedAccount", func(t *testing.T) {
is := is_.New(t)
// reserve on open accounts first
var txUUID string
err := conn.QueryRow(ctx, `
select ledger.reserve($1, $2, $3, 5000, 300, '2025-03-03', 'Before close')
`, ledgerUUID, checkingUUID, revenueUUID).Scan(&txUUID)
is.NoErr(err)
// close the checking account
_, err = conn.Exec(ctx, `select ledger.close_account($1)`, checkingUUID)