stateset-db 1.22.0

Database implementations for StateSet iCommerce
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
//! PostgreSQL implementation of General Ledger repository

use super::{block_on, map_db_error};
use chrono::{DateTime, NaiveDate, Utc};
use rust_decimal::Decimal;
use sqlx::postgres::PgPool;
use sqlx::{FromRow, Postgres, QueryBuilder};
use stateset_core::{
    AccountStatus, AccountSubType, AccountType, AutoPostingConfig, BalanceSheet, BalanceSheetLine,
    BalanceSide, BatchResult, CommerceError, CreateAutoPostingConfig, CreateGlAccount,
    CreateGlPeriod, CreateJournalEntry, CreateJournalEntryLine, Currency, CurrencyCode,
    FX_REVALUATION_REFERENCE, GeneralLedgerRepository, GlAccount, GlAccountFilter, GlPeriod,
    GlPeriodFilter, IncomeStatement, IncomeStatementLine, InvoiceId, JournalEntry,
    JournalEntryFilter, JournalEntryLine, JournalEntrySource, JournalEntryStatus, JournalEntryType,
    PeriodStatus, Result, RevaluationResult, TrialBalance, TrialBalanceLine,
    create_default_chart_of_accounts, generate_journal_entry_number,
};
use uuid::Uuid;

#[derive(Debug, Clone)]
pub struct PgGeneralLedgerRepository {
    pool: PgPool,
}

#[derive(FromRow)]
struct AccountRow {
    id: Uuid,
    account_number: String,
    name: String,
    description: Option<String>,
    account_type: String,
    account_sub_type: Option<String>,
    parent_account_id: Option<Uuid>,
    is_header: bool,
    is_posting: bool,
    normal_balance: String,
    currency: CurrencyCode,
    status: String,
    current_balance: Decimal,
    created_at: DateTime<Utc>,
    updated_at: DateTime<Utc>,
}

#[derive(FromRow)]
struct PeriodRow {
    id: Uuid,
    period_name: String,
    fiscal_year: i32,
    period_number: i32,
    start_date: NaiveDate,
    end_date: NaiveDate,
    status: String,
    closed_at: Option<DateTime<Utc>>,
    closed_by: Option<String>,
    locked_at: Option<DateTime<Utc>>,
    locked_by: Option<String>,
    created_at: DateTime<Utc>,
    updated_at: DateTime<Utc>,
}

#[derive(FromRow)]
struct JournalEntryRow {
    id: Uuid,
    entry_number: String,
    entry_date: NaiveDate,
    period_id: Uuid,
    entry_type: String,
    source: String,
    source_document_type: Option<String>,
    source_document_id: Option<Uuid>,
    description: String,
    total_debits: Decimal,
    total_credits: Decimal,
    is_balanced: bool,
    status: String,
    posted_at: Option<DateTime<Utc>>,
    posted_by: Option<String>,
    reversed_entry_id: Option<Uuid>,
    reversing_entry_id: Option<Uuid>,
    created_at: DateTime<Utc>,
    updated_at: DateTime<Utc>,
}

#[derive(FromRow)]
struct JournalEntryLineRow {
    id: Uuid,
    journal_entry_id: Uuid,
    line_number: i32,
    account_id: Uuid,
    account_number: Option<String>,
    account_name: Option<String>,
    description: Option<String>,
    debit_amount: Decimal,
    credit_amount: Decimal,
    currency: CurrencyCode,
    reference_type: Option<String>,
    reference_id: Option<Uuid>,
    created_at: DateTime<Utc>,
}

#[derive(FromRow)]
struct AutoPostingConfigRow {
    id: Uuid,
    config_name: String,
    cash_account_id: Uuid,
    accounts_receivable_account_id: Uuid,
    inventory_account_id: Uuid,
    accounts_payable_account_id: Uuid,
    unearned_revenue_account_id: Option<Uuid>,
    sales_revenue_account_id: Uuid,
    shipping_revenue_account_id: Option<Uuid>,
    cogs_account_id: Uuid,
    bad_debt_expense_account_id: Option<Uuid>,
    fx_gain_loss_account_id: Option<Uuid>,
    auto_post_depreciation: bool,
    auto_post_revenue_recognition: bool,
    is_active: bool,
    created_at: DateTime<Utc>,
    updated_at: DateTime<Utc>,
}

impl PgGeneralLedgerRepository {
    pub const fn new(pool: PgPool) -> Self {
        Self { pool }
    }

    fn row_to_account(row: AccountRow) -> Result<GlAccount> {
        let AccountRow {
            id,
            account_number,
            name,
            description,
            account_type,
            account_sub_type,
            parent_account_id,
            is_header,
            is_posting,
            normal_balance,
            currency,
            status,
            current_balance,
            created_at,
            updated_at,
        } = row;

        let account_type: AccountType = account_type.parse().map_err(|e| {
            CommerceError::DatabaseError(format!(
                "Invalid gl_account.account_type '{}': {}",
                account_type, e
            ))
        })?;
        let account_sub_type = match account_sub_type {
            Some(value) if !value.trim().is_empty() => Some(value.parse().map_err(|e| {
                CommerceError::DatabaseError(format!(
                    "Invalid gl_account.account_sub_type '{}': {}",
                    value, e
                ))
            })?),
            _ => None,
        };
        let normal_balance: BalanceSide = normal_balance.parse().map_err(|e| {
            CommerceError::DatabaseError(format!(
                "Invalid gl_account.normal_balance '{}': {}",
                normal_balance, e
            ))
        })?;
        let status: AccountStatus = status.parse().map_err(|e| {
            CommerceError::DatabaseError(format!("Invalid gl_account.status '{}': {}", status, e))
        })?;

        Ok(GlAccount {
            id,
            account_number,
            name,
            description,
            account_type,
            account_sub_type,
            parent_account_id,
            is_header,
            is_posting,
            normal_balance,
            currency,
            status,
            current_balance,
            created_at,
            updated_at,
        })
    }

    fn row_to_period(row: PeriodRow) -> Result<GlPeriod> {
        let PeriodRow {
            id,
            period_name,
            fiscal_year,
            period_number,
            start_date,
            end_date,
            status,
            closed_at,
            closed_by,
            locked_at,
            locked_by,
            created_at,
            updated_at,
        } = row;

        let status: PeriodStatus = status.parse().map_err(|e| {
            CommerceError::DatabaseError(format!("Invalid gl_period.status '{}': {}", status, e))
        })?;

        Ok(GlPeriod {
            id,
            period_name,
            fiscal_year,
            period_number,
            start_date,
            end_date,
            status,
            closed_at,
            closed_by,
            locked_at,
            locked_by,
            created_at,
            updated_at,
        })
    }

    fn row_to_journal_entry(row: JournalEntryRow) -> Result<JournalEntry> {
        let JournalEntryRow {
            id,
            entry_number,
            entry_date,
            period_id,
            entry_type,
            source,
            source_document_type,
            source_document_id,
            description,
            total_debits,
            total_credits,
            is_balanced,
            status,
            posted_at,
            posted_by,
            reversed_entry_id,
            reversing_entry_id,
            created_at,
            updated_at,
        } = row;

        let entry_type: JournalEntryType = entry_type.parse().map_err(|e| {
            CommerceError::DatabaseError(format!(
                "Invalid gl_journal_entry.entry_type '{}': {}",
                entry_type, e
            ))
        })?;
        let source: JournalEntrySource = source.parse().map_err(|e| {
            CommerceError::DatabaseError(format!(
                "Invalid gl_journal_entry.source '{}': {}",
                source, e
            ))
        })?;
        let status: JournalEntryStatus = status.parse().map_err(|e| {
            CommerceError::DatabaseError(format!(
                "Invalid gl_journal_entry.status '{}': {}",
                status, e
            ))
        })?;

        Ok(JournalEntry {
            id,
            entry_number,
            entry_date,
            period_id,
            entry_type,
            source,
            source_document_type,
            source_document_id,
            description,
            total_debits,
            total_credits,
            is_balanced,
            status,
            posted_at,
            posted_by,
            reversed_entry_id,
            reversing_entry_id,
            lines: Vec::new(),
            created_at,
            updated_at,
        })
    }

    fn row_to_journal_entry_line(row: JournalEntryLineRow) -> JournalEntryLine {
        JournalEntryLine {
            id: row.id,
            journal_entry_id: row.journal_entry_id,
            line_number: row.line_number,
            account_id: row.account_id,
            account_number: row.account_number,
            account_name: row.account_name,
            description: row.description,
            debit_amount: row.debit_amount,
            credit_amount: row.credit_amount,
            currency: row.currency,
            reference_type: row.reference_type,
            reference_id: row.reference_id,
            created_at: row.created_at,
        }
    }

    fn row_to_auto_posting_config(row: AutoPostingConfigRow) -> AutoPostingConfig {
        AutoPostingConfig {
            id: row.id,
            config_name: row.config_name,
            cash_account_id: row.cash_account_id,
            accounts_receivable_account_id: row.accounts_receivable_account_id,
            inventory_account_id: row.inventory_account_id,
            accounts_payable_account_id: row.accounts_payable_account_id,
            unearned_revenue_account_id: row.unearned_revenue_account_id,
            sales_revenue_account_id: row.sales_revenue_account_id,
            shipping_revenue_account_id: row.shipping_revenue_account_id,
            cogs_account_id: row.cogs_account_id,
            bad_debt_expense_account_id: row.bad_debt_expense_account_id,
            fx_gain_loss_account_id: row.fx_gain_loss_account_id,
            auto_post_depreciation: row.auto_post_depreciation,
            auto_post_revenue_recognition: row.auto_post_revenue_recognition,
            is_active: row.is_active,
            created_at: row.created_at,
            updated_at: row.updated_at,
        }
    }

    async fn update_account_balance_tx(
        &self,
        tx: &mut sqlx::Transaction<'_, Postgres>,
        account_id: Uuid,
        debit: Decimal,
        credit: Decimal,
    ) -> Result<()> {
        let updated = sqlx::query(
            "UPDATE gl_accounts
             SET current_balance = current_balance + (
                CASE
                    WHEN normal_balance = 'debit' THEN $1 - $2
                    ELSE $2 - $1
                END
             )
             WHERE id = $3",
        )
        .bind(debit)
        .bind(credit)
        .bind(account_id)
        .execute(tx.as_mut())
        .await
        .map_err(map_db_error)?;

        if updated.rows_affected() == 0 {
            return Err(CommerceError::NotFound);
        }

        Ok(())
    }

    pub async fn create_account_async(&self, input: CreateGlAccount) -> Result<GlAccount> {
        let id = Uuid::new_v4();
        let now = Utc::now();
        let normal_balance = input.account_type.normal_balance();
        let currency = input.currency.unwrap_or(CurrencyCode::USD);
        let is_header = input.is_header.unwrap_or(false);
        let is_posting = input.is_posting.unwrap_or(true);

        sqlx::query(
            "INSERT INTO gl_accounts (id, account_number, name, description, account_type,
                account_sub_type, parent_account_id, is_header, is_posting, normal_balance,
                currency, status, current_balance, created_at, updated_at)
             VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15)",
        )
        .bind(id)
        .bind(&input.account_number)
        .bind(&input.name)
        .bind(input.description)
        .bind(input.account_type.to_string())
        .bind(input.account_sub_type.map(|s| s.to_string()))
        .bind(input.parent_account_id)
        .bind(is_header)
        .bind(is_posting)
        .bind(normal_balance.to_string())
        .bind(currency)
        .bind(AccountStatus::Active.to_string())
        .bind(Decimal::ZERO)
        .bind(now)
        .bind(now)
        .execute(&self.pool)
        .await
        .map_err(map_db_error)?;

        self.get_account_async(id).await?.ok_or(CommerceError::NotFound)
    }

    pub async fn get_account_async(&self, id: Uuid) -> Result<Option<GlAccount>> {
        let row = sqlx::query_as::<_, AccountRow>(
            "SELECT id, account_number, name, description, account_type, account_sub_type,
                    parent_account_id, is_header, is_posting, normal_balance, currency, status,
                    current_balance, created_at, updated_at
             FROM gl_accounts WHERE id = $1",
        )
        .bind(id)
        .fetch_optional(&self.pool)
        .await
        .map_err(map_db_error)?;

        row.map(Self::row_to_account).transpose()
    }

    pub async fn get_account_by_number_async(
        &self,
        account_number: &str,
    ) -> Result<Option<GlAccount>> {
        let row = sqlx::query_as::<_, AccountRow>(
            "SELECT id, account_number, name, description, account_type, account_sub_type,
                    parent_account_id, is_header, is_posting, normal_balance, currency, status,
                    current_balance, created_at, updated_at
             FROM gl_accounts WHERE account_number = $1",
        )
        .bind(account_number)
        .fetch_optional(&self.pool)
        .await
        .map_err(map_db_error)?;

        row.map(Self::row_to_account).transpose()
    }

    pub async fn update_account_async(
        &self,
        id: Uuid,
        input: stateset_core::UpdateGlAccount,
    ) -> Result<GlAccount> {
        sqlx::query(
            "UPDATE gl_accounts SET
                name = COALESCE($1, name),
                description = COALESCE($2, description),
                parent_account_id = COALESCE($3, parent_account_id),
                status = COALESCE($4, status),
                updated_at = $5
             WHERE id = $6",
        )
        .bind(input.name)
        .bind(input.description)
        .bind(input.parent_account_id)
        .bind(input.status.map(|s| s.to_string()))
        .bind(Utc::now())
        .bind(id)
        .execute(&self.pool)
        .await
        .map_err(map_db_error)?;

        self.get_account_async(id).await?.ok_or(CommerceError::NotFound)
    }

    pub async fn list_accounts_async(&self, filter: GlAccountFilter) -> Result<Vec<GlAccount>> {
        let mut builder = QueryBuilder::<Postgres>::new(
            "SELECT id, account_number, name, description, account_type, account_sub_type,
                    parent_account_id, is_header, is_posting, normal_balance, currency, status,
                    current_balance, created_at, updated_at
             FROM gl_accounts WHERE 1=1",
        );

        if let Some(account_type) = filter.account_type {
            builder.push(" AND account_type = ").push_bind(account_type.to_string());
        }
        if let Some(account_sub_type) = filter.account_sub_type {
            builder.push(" AND account_sub_type = ").push_bind(account_sub_type.to_string());
        }
        if let Some(parent_account_id) = filter.parent_account_id {
            builder.push(" AND parent_account_id = ").push_bind(parent_account_id);
        }
        if let Some(status) = filter.status {
            builder.push(" AND status = ").push_bind(status.to_string());
        }
        if let Some(is_posting) = filter.is_posting {
            builder.push(" AND is_posting = ").push_bind(is_posting);
        }
        if let Some(is_header) = filter.is_header {
            builder.push(" AND is_header = ").push_bind(is_header);
        }
        if let Some(search) = filter.search {
            let term = format!("%{}%", search);
            builder
                .push(" AND (name ILIKE ")
                .push_bind(term.clone())
                .push(" OR account_number ILIKE ")
                .push_bind(term)
                .push(")");
        }

        builder.push(" ORDER BY account_number");

        builder.push(" LIMIT ").push_bind(super::effective_limit(filter.limit));
        if let Some(offset) = filter.offset {
            builder.push(" OFFSET ").push_bind(offset as i64);
        }

        let rows = builder
            .build_query_as::<AccountRow>()
            .fetch_all(&self.pool)
            .await
            .map_err(map_db_error)?;

        rows.into_iter().map(Self::row_to_account).collect::<Result<Vec<_>>>()
    }

    pub async fn get_account_hierarchy_async(&self) -> Result<Vec<GlAccount>> {
        self.list_accounts_async(GlAccountFilter::default()).await
    }

    pub async fn delete_account_async(&self, id: Uuid) -> Result<()> {
        let count: i64 =
            sqlx::query_scalar("SELECT COUNT(*) FROM gl_journal_entry_lines WHERE account_id = $1")
                .bind(id)
                .fetch_one(&self.pool)
                .await
                .map_err(map_db_error)?;

        if count > 0 {
            return Err(CommerceError::ValidationError(
                "Cannot delete account with existing transactions".into(),
            ));
        }

        sqlx::query("DELETE FROM gl_accounts WHERE id = $1")
            .bind(id)
            .execute(&self.pool)
            .await
            .map_err(map_db_error)?;

        Ok(())
    }

    pub async fn initialize_chart_of_accounts_async(&self) -> Result<Vec<GlAccount>> {
        let defaults = create_default_chart_of_accounts();
        let mut accounts = Vec::new();

        for input in defaults {
            if self.get_account_by_number_async(&input.account_number).await?.is_none() {
                accounts.push(self.create_account_async(input).await?);
            }
        }

        Ok(accounts)
    }

    pub async fn create_period_async(&self, input: CreateGlPeriod) -> Result<GlPeriod> {
        let id = Uuid::new_v4();
        let now = Utc::now();

        sqlx::query(
            "INSERT INTO gl_periods (id, period_name, fiscal_year, period_number, start_date,
                end_date, status, created_at, updated_at)
             VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)",
        )
        .bind(id)
        .bind(&input.period_name)
        .bind(input.fiscal_year)
        .bind(input.period_number)
        .bind(input.start_date)
        .bind(input.end_date)
        .bind(PeriodStatus::Future.to_string())
        .bind(now)
        .bind(now)
        .execute(&self.pool)
        .await
        .map_err(map_db_error)?;

        self.get_period_async(id).await?.ok_or(CommerceError::NotFound)
    }

    pub async fn get_period_async(&self, id: Uuid) -> Result<Option<GlPeriod>> {
        let row = sqlx::query_as::<_, PeriodRow>(
            "SELECT id, period_name, fiscal_year, period_number, start_date, end_date,
                    status, closed_at, closed_by, locked_at, locked_by, created_at, updated_at
             FROM gl_periods WHERE id = $1",
        )
        .bind(id)
        .fetch_optional(&self.pool)
        .await
        .map_err(map_db_error)?;

        row.map(Self::row_to_period).transpose()
    }

    pub async fn get_current_period_async(&self) -> Result<Option<GlPeriod>> {
        let row = sqlx::query_as::<_, PeriodRow>(
            "SELECT id, period_name, fiscal_year, period_number, start_date, end_date,
                    status, closed_at, closed_by, locked_at, locked_by, created_at, updated_at
             FROM gl_periods WHERE status = 'open' ORDER BY start_date DESC LIMIT 1",
        )
        .fetch_optional(&self.pool)
        .await
        .map_err(map_db_error)?;

        row.map(Self::row_to_period).transpose()
    }

    pub async fn get_period_for_date_async(&self, date: NaiveDate) -> Result<Option<GlPeriod>> {
        let row = sqlx::query_as::<_, PeriodRow>(
            "SELECT id, period_name, fiscal_year, period_number, start_date, end_date,
                    status, closed_at, closed_by, locked_at, locked_by, created_at, updated_at
             FROM gl_periods WHERE start_date <= $1 AND end_date >= $1",
        )
        .bind(date)
        .fetch_optional(&self.pool)
        .await
        .map_err(map_db_error)?;

        row.map(Self::row_to_period).transpose()
    }

    pub async fn list_periods_async(&self, filter: GlPeriodFilter) -> Result<Vec<GlPeriod>> {
        let mut builder = QueryBuilder::<Postgres>::new(
            "SELECT id, period_name, fiscal_year, period_number, start_date, end_date,
                    status, closed_at, closed_by, locked_at, locked_by, created_at, updated_at
             FROM gl_periods WHERE 1=1",
        );

        if let Some(fiscal_year) = filter.fiscal_year {
            builder.push(" AND fiscal_year = ").push_bind(fiscal_year);
        }
        if let Some(status) = filter.status {
            builder.push(" AND status = ").push_bind(status.to_string());
        }

        // Order by period identity (unique, deterministic), matching SQLite — not
        // `start_date`, which can tie and disagrees when a lower-numbered period has
        // a later start date.
        builder.push(" ORDER BY fiscal_year DESC, period_number DESC");

        builder.push(" LIMIT ").push_bind(super::effective_limit(filter.limit));
        if let Some(offset) = filter.offset {
            builder.push(" OFFSET ").push_bind(offset as i64);
        }

        let rows = builder
            .build_query_as::<PeriodRow>()
            .fetch_all(&self.pool)
            .await
            .map_err(map_db_error)?;

        rows.into_iter().map(Self::row_to_period).collect::<Result<Vec<_>>>()
    }

    pub async fn open_period_async(&self, id: Uuid) -> Result<GlPeriod> {
        sqlx::query("UPDATE gl_periods SET status = 'open' WHERE id = $1 AND status = 'future'")
            .bind(id)
            .execute(&self.pool)
            .await
            .map_err(map_db_error)?;

        self.get_period_async(id).await?.ok_or(CommerceError::NotFound)
    }

    pub async fn close_period_async(&self, id: Uuid, closed_by: &str) -> Result<GlPeriod> {
        let now = Utc::now();
        sqlx::query(
            "UPDATE gl_periods SET status = 'closed', closed_at = $1, closed_by = $2
             WHERE id = $3 AND status = 'open'",
        )
        .bind(now)
        .bind(closed_by)
        .bind(id)
        .execute(&self.pool)
        .await
        .map_err(map_db_error)?;

        self.get_period_async(id).await?.ok_or(CommerceError::NotFound)
    }

    pub async fn lock_period_async(&self, id: Uuid, locked_by: &str) -> Result<GlPeriod> {
        let now = Utc::now();
        sqlx::query(
            "UPDATE gl_periods SET status = 'locked', locked_at = $1, locked_by = $2
             WHERE id = $3 AND status = 'closed'",
        )
        .bind(now)
        .bind(locked_by)
        .bind(id)
        .execute(&self.pool)
        .await
        .map_err(map_db_error)?;

        self.get_period_async(id).await?.ok_or(CommerceError::NotFound)
    }

    pub async fn reopen_period_async(&self, id: Uuid) -> Result<GlPeriod> {
        sqlx::query(
            "UPDATE gl_periods SET status = 'open', closed_at = NULL, closed_by = NULL
             WHERE id = $1 AND status = 'closed'",
        )
        .bind(id)
        .execute(&self.pool)
        .await
        .map_err(map_db_error)?;

        self.get_period_async(id).await?.ok_or(CommerceError::NotFound)
    }

    pub async fn create_journal_entry_async(
        &self,
        input: CreateJournalEntry,
    ) -> Result<JournalEntry> {
        let id = Uuid::new_v4();
        let now = Utc::now();
        let entry_number = generate_journal_entry_number();

        let period = self.get_period_for_date_async(input.entry_date).await?.ok_or_else(|| {
            CommerceError::ValidationError(format!("No period found for date {}", input.entry_date))
        })?;

        if !period.can_post() {
            return Err(CommerceError::ValidationError(
                "Period is not open for posting".to_string(),
            ));
        }

        let total_debits: Decimal = input.lines.iter().map(|l| l.debit_amount).sum();
        let total_credits: Decimal = input.lines.iter().map(|l| l.credit_amount).sum();
        let is_balanced = total_debits == total_credits;
        let lines_are_valid = input.lines.iter().all(|l| {
            (l.debit_amount > Decimal::ZERO && l.credit_amount == Decimal::ZERO)
                || (l.debit_amount == Decimal::ZERO && l.credit_amount > Decimal::ZERO)
        });

        if !lines_are_valid {
            return Err(CommerceError::ValidationError(
                "Each journal line must have either a positive debit or a positive credit"
                    .to_string(),
            ));
        }

        let mut tx = self.pool.begin().await.map_err(map_db_error)?;

        sqlx::query(
            "INSERT INTO gl_journal_entries (id, entry_number, entry_date, period_id, entry_type,
                source, source_document_type, source_document_id, description, total_debits,
                total_credits, is_balanced, status, created_at, updated_at)
             VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15)",
        )
        .bind(id)
        .bind(&entry_number)
        .bind(input.entry_date)
        .bind(period.id)
        .bind(input.entry_type.unwrap_or(JournalEntryType::Standard).to_string())
        .bind(JournalEntrySource::Manual.to_string())
        .bind(input.source_document_type.clone())
        .bind(input.source_document_id)
        .bind(&input.description)
        .bind(total_debits)
        .bind(total_credits)
        .bind(is_balanced)
        .bind(JournalEntryStatus::Draft.to_string())
        .bind(now)
        .bind(now)
        .execute(tx.as_mut())
        .await
        .map_err(map_db_error)?;

        for (line_num, line) in input.lines.iter().enumerate() {
            let line_id = Uuid::new_v4();
            let account =
                self.get_account_async(line.account_id).await?.ok_or(CommerceError::NotFound)?;

            sqlx::query(
                "INSERT INTO gl_journal_entry_lines (id, journal_entry_id, line_number, account_id,
                    account_number, account_name, description, debit_amount, credit_amount, currency,
                    reference_type, reference_id, created_at)
                 VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13)",
            )
            .bind(line_id)
            .bind(id)
            .bind((line_num + 1) as i32)
            .bind(line.account_id)
            .bind(account.account_number)
            .bind(account.name)
            .bind(line.description.clone())
            .bind(line.debit_amount)
            .bind(line.credit_amount)
            .bind(account.currency)
            .bind(line.reference_type.clone())
            .bind(line.reference_id)
            .bind(now)
            .execute(tx.as_mut())
            .await
            .map_err(map_db_error)?;
        }

        tx.commit().await.map_err(map_db_error)?;

        if input.auto_post.unwrap_or(false) && is_balanced {
            return self.post_journal_entry_async(id, "system").await;
        }

        self.get_journal_entry_async(id).await?.ok_or(CommerceError::NotFound)
    }

    pub async fn get_journal_entry_async(&self, id: Uuid) -> Result<Option<JournalEntry>> {
        let row = sqlx::query_as::<_, JournalEntryRow>(
            "SELECT id, entry_number, entry_date, period_id, entry_type, source,
                    source_document_type, source_document_id, description, total_debits,
                    total_credits, is_balanced, status, posted_at, posted_by,
                    reversed_entry_id, reversing_entry_id, created_at, updated_at
             FROM gl_journal_entries WHERE id = $1",
        )
        .bind(id)
        .fetch_optional(&self.pool)
        .await
        .map_err(map_db_error)?;

        match row {
            Some(row) => {
                let mut entry = Self::row_to_journal_entry(row)?;
                entry.lines = self.get_journal_entry_lines_async(id).await?;
                Ok(Some(entry))
            }
            None => Ok(None),
        }
    }

    pub async fn get_journal_entry_by_number_async(
        &self,
        number: &str,
    ) -> Result<Option<JournalEntry>> {
        let id = sqlx::query_scalar::<_, Uuid>(
            "SELECT id FROM gl_journal_entries WHERE entry_number = $1",
        )
        .bind(number)
        .fetch_optional(&self.pool)
        .await
        .map_err(map_db_error)?;

        match id {
            Some(id) => self.get_journal_entry_async(id).await,
            None => Ok(None),
        }
    }

    pub async fn list_journal_entries_async(
        &self,
        filter: JournalEntryFilter,
    ) -> Result<Vec<JournalEntry>> {
        let columns = "je.id, je.entry_number, je.entry_date, je.period_id, je.entry_type, je.source,\
            je.source_document_type, je.source_document_id, je.description, je.total_debits,\
            je.total_credits, je.is_balanced, je.status, je.posted_at, je.posted_by,\
            je.reversed_entry_id, je.reversing_entry_id, je.created_at, je.updated_at";
        let mut builder = QueryBuilder::<Postgres>::new("SELECT DISTINCT ");
        builder.push(columns).push(" FROM gl_journal_entries je");

        if filter.account_id.is_some() {
            builder.push(" JOIN gl_journal_entry_lines l ON je.id = l.journal_entry_id");
        }

        builder.push(" WHERE 1=1");

        if let Some(period_id) = filter.period_id {
            builder.push(" AND je.period_id = ").push_bind(period_id);
        }
        if let Some(entry_type) = filter.entry_type {
            builder.push(" AND je.entry_type = ").push_bind(entry_type.to_string());
        }
        if let Some(source) = filter.source {
            builder.push(" AND je.source = ").push_bind(source.to_string());
        }
        if let Some(status) = filter.status {
            builder.push(" AND je.status = ").push_bind(status.to_string());
        }
        if let Some(account_id) = filter.account_id {
            builder.push(" AND l.account_id = ").push_bind(account_id);
        }
        if let Some(from_date) = filter.from_date {
            builder.push(" AND je.entry_date >= ").push_bind(from_date);
        }
        if let Some(to_date) = filter.to_date {
            builder.push(" AND je.entry_date <= ").push_bind(to_date);
        }
        if let Some(source_doc_type) = filter.source_document_type {
            builder.push(" AND je.source_document_type = ").push_bind(source_doc_type);
        }
        if let Some(source_doc_id) = filter.source_document_id {
            builder.push(" AND je.source_document_id = ").push_bind(source_doc_id);
        }
        if let Some(search) = filter.search {
            let term = format!("%{}%", search);
            builder
                .push(" AND (je.entry_number ILIKE ")
                .push_bind(term.clone())
                .push(" OR je.description ILIKE ")
                .push_bind(term)
                .push(")");
        }

        // Deterministic tiebreak by entry number for same-date entries, matching
        // SQLite.
        builder.push(" ORDER BY je.entry_date DESC, je.entry_number DESC");

        builder.push(" LIMIT ").push_bind(super::effective_limit(filter.limit));
        if let Some(offset) = filter.offset {
            builder.push(" OFFSET ").push_bind(offset as i64);
        }

        let rows = builder
            .build_query_as::<JournalEntryRow>()
            .fetch_all(&self.pool)
            .await
            .map_err(map_db_error)?;

        let mut entries = Vec::new();
        for row in rows {
            let mut entry = Self::row_to_journal_entry(row)?;
            entry.lines = self.get_journal_entry_lines_async(entry.id).await?;
            entries.push(entry);
        }

        Ok(entries)
    }

    pub async fn post_journal_entry_async(
        &self,
        id: Uuid,
        posted_by: &str,
    ) -> Result<JournalEntry> {
        let entry = self.get_journal_entry_async(id).await?.ok_or(CommerceError::NotFound)?;

        if !entry.can_post() {
            return Err(CommerceError::ValidationError(
                "Entry cannot be posted - must be draft and balanced".to_string(),
            ));
        }

        let now = Utc::now();
        let mut tx = self.pool.begin().await.map_err(map_db_error)?;

        // The status guard takes the row lock; a concurrent poster blocks on
        // it and then matches zero rows, so the balance updates below can
        // only commit together with exactly one draft -> posted transition.
        let updated = sqlx::query(
            "UPDATE gl_journal_entries SET status = 'posted', posted_at = $1, posted_by = $2
             WHERE id = $3 AND status = 'draft'",
        )
        .bind(now)
        .bind(posted_by)
        .bind(id)
        .execute(tx.as_mut())
        .await
        .map_err(map_db_error)?;

        if updated.rows_affected() == 0 {
            return Err(CommerceError::Conflict(
                "Journal entry was modified concurrently".to_string(),
            ));
        }

        for line in &entry.lines {
            self.update_account_balance_tx(
                &mut tx,
                line.account_id,
                line.debit_amount,
                line.credit_amount,
            )
            .await?;
        }

        tx.commit().await.map_err(map_db_error)?;

        self.get_journal_entry_async(id).await?.ok_or(CommerceError::NotFound)
    }

    pub async fn void_journal_entry_async(&self, id: Uuid) -> Result<JournalEntry> {
        let entry = self.get_journal_entry_async(id).await?.ok_or(CommerceError::NotFound)?;

        if !entry.can_void() {
            return Err(CommerceError::ValidationError(
                "Entry cannot be voided - must be posted".to_string(),
            ));
        }

        let mut tx = self.pool.begin().await.map_err(map_db_error)?;

        // The status guard takes the row lock; a concurrent voider blocks on
        // it and then matches zero rows, so the balance reversal below can
        // only commit together with exactly one posted -> voided transition.
        let updated = sqlx::query(
            "UPDATE gl_journal_entries SET status = 'voided' WHERE id = $1 AND status = 'posted'",
        )
        .bind(id)
        .execute(tx.as_mut())
        .await
        .map_err(map_db_error)?;

        if updated.rows_affected() == 0 {
            return Err(CommerceError::Conflict(
                "Journal entry was modified concurrently".to_string(),
            ));
        }

        for line in &entry.lines {
            self.update_account_balance_tx(
                &mut tx,
                line.account_id,
                line.credit_amount,
                line.debit_amount,
            )
            .await?;
        }

        tx.commit().await.map_err(map_db_error)?;

        self.get_journal_entry_async(id).await?.ok_or(CommerceError::NotFound)
    }

    pub async fn reverse_journal_entry_async(
        &self,
        id: Uuid,
        reversal_date: NaiveDate,
    ) -> Result<JournalEntry> {
        let entry = self.get_journal_entry_async(id).await?.ok_or(CommerceError::NotFound)?;

        if entry.status != JournalEntryStatus::Posted {
            return Err(CommerceError::ValidationError(
                "Can only reverse posted entries".to_string(),
            ));
        }

        // Claim the entry (posted -> reversed) before creating the reversing
        // entry, which commits its own transactions; the status guard ensures
        // concurrent reversals cannot both create (and auto-post) a reversal.
        let claimed = sqlx::query(
            "UPDATE gl_journal_entries SET status = 'reversed' WHERE id = $1 AND status = 'posted'",
        )
        .bind(id)
        .execute(&self.pool)
        .await
        .map_err(map_db_error)?;

        if claimed.rows_affected() == 0 {
            return Err(CommerceError::Conflict(
                "Journal entry was modified concurrently".to_string(),
            ));
        }

        let reversing_lines: Vec<CreateJournalEntryLine> = entry
            .lines
            .iter()
            .map(|l| CreateJournalEntryLine {
                account_id: l.account_id,
                description: Some(format!("Reversal of {}", entry.entry_number)),
                debit_amount: l.credit_amount,
                credit_amount: l.debit_amount,
                reference_type: l.reference_type.clone(),
                reference_id: l.reference_id,
            })
            .collect();

        let reversing_entry = match self
            .create_journal_entry_async(CreateJournalEntry {
                entry_date: reversal_date,
                entry_type: Some(JournalEntryType::Reversing),
                description: format!("Reversal of {}", entry.entry_number),
                lines: reversing_lines,
                source_document_type: Some("reversal".to_string()),
                source_document_id: Some(entry.id),
                auto_post: Some(true),
            })
            .await
        {
            Ok(reversing_entry) => reversing_entry,
            Err(e) => {
                // Best-effort release of the claim so the entry is not left
                // marked reversed without a reversing entry.
                let _ = sqlx::query(
                    "UPDATE gl_journal_entries SET status = 'posted' WHERE id = $1 AND status = 'reversed'",
                )
                .bind(id)
                .execute(&self.pool)
                .await;
                return Err(e);
            }
        };

        sqlx::query("UPDATE gl_journal_entries SET reversing_entry_id = $1 WHERE id = $2")
            .bind(reversing_entry.id)
            .bind(id)
            .execute(&self.pool)
            .await
            .map_err(map_db_error)?;

        sqlx::query("UPDATE gl_journal_entries SET reversed_entry_id = $1 WHERE id = $2")
            .bind(id)
            .bind(reversing_entry.id)
            .execute(&self.pool)
            .await
            .map_err(map_db_error)?;

        self.get_journal_entry_async(reversing_entry.id).await?.ok_or(CommerceError::NotFound)
    }

    pub async fn get_journal_entry_lines_async(
        &self,
        journal_entry_id: Uuid,
    ) -> Result<Vec<JournalEntryLine>> {
        let rows = sqlx::query_as::<_, JournalEntryLineRow>(
            "SELECT id, journal_entry_id, line_number, account_id, account_number, account_name,
                    description, debit_amount, credit_amount, currency, reference_type, reference_id,
                    created_at
             FROM gl_journal_entry_lines WHERE journal_entry_id = $1 ORDER BY line_number",
        )
        .bind(journal_entry_id)
        .fetch_all(&self.pool)
        .await
        .map_err(map_db_error)?;

        Ok(rows.into_iter().map(Self::row_to_journal_entry_line).collect())
    }

    pub async fn get_auto_posting_config_async(&self) -> Result<Option<AutoPostingConfig>> {
        let row = sqlx::query_as::<_, AutoPostingConfigRow>(
            "SELECT id, config_name, cash_account_id, accounts_receivable_account_id, inventory_account_id,
                    accounts_payable_account_id, unearned_revenue_account_id, sales_revenue_account_id,
                    shipping_revenue_account_id, cogs_account_id, bad_debt_expense_account_id,
                    fx_gain_loss_account_id, auto_post_depreciation, auto_post_revenue_recognition,
                    is_active, created_at, updated_at
             FROM gl_auto_posting_config WHERE is_active = TRUE LIMIT 1",
        )
        .fetch_optional(&self.pool)
        .await
        .map_err(map_db_error)?;

        Ok(row.map(Self::row_to_auto_posting_config))
    }

    pub async fn set_auto_posting_config_async(
        &self,
        input: CreateAutoPostingConfig,
    ) -> Result<AutoPostingConfig> {
        let id = Uuid::new_v4();
        let now = Utc::now();

        sqlx::query(
            "INSERT INTO gl_auto_posting_config (id, config_name, cash_account_id, accounts_receivable_account_id,
                inventory_account_id, accounts_payable_account_id, unearned_revenue_account_id,
                sales_revenue_account_id, shipping_revenue_account_id, cogs_account_id,
                bad_debt_expense_account_id, fx_gain_loss_account_id, auto_post_depreciation,
                auto_post_revenue_recognition, is_active, created_at, updated_at)
             VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17)",
        )
        .bind(id)
        .bind(&input.config_name)
        .bind(input.cash_account_id)
        .bind(input.accounts_receivable_account_id)
        .bind(input.inventory_account_id)
        .bind(input.accounts_payable_account_id)
        .bind(input.unearned_revenue_account_id)
        .bind(input.sales_revenue_account_id)
        .bind(input.shipping_revenue_account_id)
        .bind(input.cogs_account_id)
        .bind(input.bad_debt_expense_account_id)
        .bind(input.fx_gain_loss_account_id)
        .bind(input.auto_post_depreciation)
        .bind(input.auto_post_revenue_recognition)
        .bind(true)
        .bind(now)
        .bind(now)
        .execute(&self.pool)
        .await
        .map_err(map_db_error)?;

        self.get_auto_posting_config_async().await?.ok_or(CommerceError::NotFound)
    }

    pub async fn auto_post_invoice_async(&self, invoice_id: Uuid) -> Result<JournalEntry> {
        let config = self.get_auto_posting_config_async().await?.ok_or_else(|| {
            CommerceError::ValidationError("Auto-posting not configured".to_string())
        })?;

        let (amount, invoice_date): (Decimal, DateTime<Utc>) =
            sqlx::query_as("SELECT total, invoice_date FROM invoices WHERE id = $1")
                .bind(invoice_id)
                .fetch_one(&self.pool)
                .await
                .map_err(map_db_error)?;

        let entry_date = invoice_date.date_naive();

        self.create_journal_entry_async(CreateJournalEntry {
            entry_date,
            entry_type: Some(JournalEntryType::Standard),
            description: format!("Invoice {}", invoice_id),
            lines: vec![
                CreateJournalEntryLine::debit(
                    config.accounts_receivable_account_id,
                    amount,
                    Some("Accounts Receivable".to_string()),
                ),
                CreateJournalEntryLine::credit(
                    config.sales_revenue_account_id,
                    amount,
                    Some("Sales Revenue".to_string()),
                ),
            ],
            source_document_type: Some("invoice".to_string()),
            source_document_id: Some(invoice_id),
            auto_post: Some(true),
        })
        .await
    }

    pub async fn auto_post_payment_received_async(&self, payment_id: Uuid) -> Result<JournalEntry> {
        let config = self.get_auto_posting_config_async().await?.ok_or_else(|| {
            CommerceError::ValidationError("Auto-posting not configured".to_string())
        })?;

        let (amount, paid_at): (Decimal, DateTime<Utc>) = sqlx::query_as(
            "SELECT amount, COALESCE(paid_at, created_at) FROM payments WHERE id = $1",
        )
        .bind(payment_id)
        .fetch_one(&self.pool)
        .await
        .map_err(map_db_error)?;

        let entry_date = paid_at.date_naive();

        self.create_journal_entry_async(CreateJournalEntry {
            entry_date,
            entry_type: Some(JournalEntryType::Standard),
            description: format!("Payment {}", payment_id),
            lines: vec![
                CreateJournalEntryLine::debit(
                    config.cash_account_id,
                    amount,
                    Some("Cash".to_string()),
                ),
                CreateJournalEntryLine::credit(
                    config.accounts_receivable_account_id,
                    amount,
                    Some("Accounts Receivable".to_string()),
                ),
            ],
            source_document_type: Some("payment".to_string()),
            source_document_id: Some(payment_id),
            auto_post: Some(true),
        })
        .await
    }

    pub async fn auto_post_bill_async(&self, bill_id: Uuid) -> Result<JournalEntry> {
        let config = self.get_auto_posting_config_async().await?.ok_or_else(|| {
            CommerceError::ValidationError("Auto-posting not configured".to_string())
        })?;

        let (amount, bill_date): (Decimal, NaiveDate) =
            sqlx::query_as("SELECT total_amount, bill_date FROM ap_bills WHERE id = $1")
                .bind(bill_id)
                .fetch_one(&self.pool)
                .await
                .map_err(map_db_error)?;

        self.create_journal_entry_async(CreateJournalEntry {
            entry_date: bill_date,
            entry_type: Some(JournalEntryType::Standard),
            description: format!("Bill {}", bill_id),
            lines: vec![
                CreateJournalEntryLine::debit(
                    config.inventory_account_id,
                    amount,
                    Some("Inventory/Expense".to_string()),
                ),
                CreateJournalEntryLine::credit(
                    config.accounts_payable_account_id,
                    amount,
                    Some("Accounts Payable".to_string()),
                ),
            ],
            source_document_type: Some("bill".to_string()),
            source_document_id: Some(bill_id),
            auto_post: Some(true),
        })
        .await
    }

    pub async fn auto_post_bill_payment_async(&self, payment_id: Uuid) -> Result<JournalEntry> {
        let config = self.get_auto_posting_config_async().await?.ok_or_else(|| {
            CommerceError::ValidationError("Auto-posting not configured".to_string())
        })?;

        let (amount, payment_date): (Decimal, NaiveDate) =
            sqlx::query_as("SELECT amount, payment_date FROM ap_payments WHERE id = $1")
                .bind(payment_id)
                .fetch_one(&self.pool)
                .await
                .map_err(map_db_error)?;

        self.create_journal_entry_async(CreateJournalEntry {
            entry_date: payment_date,
            entry_type: Some(JournalEntryType::Standard),
            description: format!("Bill Payment {}", payment_id),
            lines: vec![
                CreateJournalEntryLine::debit(
                    config.accounts_payable_account_id,
                    amount,
                    Some("Accounts Payable".to_string()),
                ),
                CreateJournalEntryLine::credit(
                    config.cash_account_id,
                    amount,
                    Some("Cash".to_string()),
                ),
            ],
            source_document_type: Some("bill_payment".to_string()),
            source_document_id: Some(payment_id),
            auto_post: Some(true),
        })
        .await
    }

    pub async fn auto_post_inventory_cost_async(
        &self,
        cost_transaction_id: Uuid,
    ) -> Result<JournalEntry> {
        let config = self.get_auto_posting_config_async().await?.ok_or_else(|| {
            CommerceError::ValidationError("Auto-posting not configured".to_string())
        })?;

        let (cost, created_at, transaction_type): (Decimal, DateTime<Utc>, String) =
            sqlx::query_as(
                "SELECT total_cost, created_at, transaction_type FROM cost_transactions WHERE id = $1",
            )
            .bind(cost_transaction_id)
            .fetch_one(&self.pool)
            .await
            .map_err(map_db_error)?;

        let entry_date = created_at.date_naive();
        let is_issue = transaction_type == "issue" || transaction_type == "sale";
        let (debit_account, credit_account) = if is_issue {
            (config.cogs_account_id, config.inventory_account_id)
        } else {
            (config.inventory_account_id, config.cogs_account_id)
        };

        self.create_journal_entry_async(CreateJournalEntry {
            entry_date,
            entry_type: Some(JournalEntryType::Standard),
            description: format!("Inventory Cost {}", cost_transaction_id),
            lines: vec![
                CreateJournalEntryLine::debit(
                    debit_account,
                    cost,
                    Some(if is_issue { "COGS" } else { "Inventory" }.to_string()),
                ),
                CreateJournalEntryLine::credit(
                    credit_account,
                    cost,
                    Some(if is_issue { "Inventory" } else { "COGS" }.to_string()),
                ),
            ],
            source_document_type: Some("cost_transaction".to_string()),
            source_document_id: Some(cost_transaction_id),
            auto_post: Some(true),
        })
        .await
    }

    pub async fn auto_post_write_off_async(&self, write_off_id: Uuid) -> Result<JournalEntry> {
        let config = self.get_auto_posting_config_async().await?.ok_or_else(|| {
            CommerceError::ValidationError("Auto-posting not configured".to_string())
        })?;

        let bad_debt_account = config.bad_debt_expense_account_id.ok_or_else(|| {
            CommerceError::ValidationError("Bad debt expense account not configured".to_string())
        })?;

        let (amount, write_off_date): (Decimal, NaiveDate) =
            sqlx::query_as("SELECT amount, write_off_date FROM ar_write_offs WHERE id = $1")
                .bind(write_off_id)
                .fetch_one(&self.pool)
                .await
                .map_err(map_db_error)?;

        self.create_journal_entry_async(CreateJournalEntry {
            entry_date: write_off_date,
            entry_type: Some(JournalEntryType::Standard),
            description: format!("Write-off {}", write_off_id),
            lines: vec![
                CreateJournalEntryLine::debit(
                    bad_debt_account,
                    amount,
                    Some("Bad Debt Expense".to_string()),
                ),
                CreateJournalEntryLine::credit(
                    config.accounts_receivable_account_id,
                    amount,
                    Some("Accounts Receivable".to_string()),
                ),
            ],
            source_document_type: Some("write_off".to_string()),
            source_document_id: Some(write_off_id),
            auto_post: Some(true),
        })
        .await
    }

    pub async fn get_trial_balance_async(&self, as_of_date: NaiveDate) -> Result<TrialBalance> {
        let rows = sqlx::query_as::<_, (Uuid, String, String, String, String, Decimal)>(
            "SELECT id, account_number, name, account_type, normal_balance, current_balance
             FROM gl_accounts WHERE is_posting = TRUE AND status = 'active' ORDER BY account_number",
        )
        .fetch_all(&self.pool)
        .await
        .map_err(map_db_error)?;

        let mut lines = Vec::new();
        let mut total_debits = Decimal::ZERO;
        let mut total_credits = Decimal::ZERO;

        for (id, number, name, account_type, normal_balance, balance) in rows {
            let normal: BalanceSide = normal_balance.parse().map_err(|e| {
                CommerceError::DatabaseError(format!(
                    "Invalid gl_account.normal_balance '{}': {}",
                    normal_balance, e
                ))
            })?;
            let (debit_balance, credit_balance) = match normal {
                BalanceSide::Debit => (balance, Decimal::ZERO),
                BalanceSide::Credit => (Decimal::ZERO, balance),
                _ => (balance, Decimal::ZERO),
            };
            let account_type: AccountType = account_type.parse().map_err(|e| {
                CommerceError::DatabaseError(format!(
                    "Invalid gl_account.account_type '{}': {}",
                    account_type, e
                ))
            })?;

            lines.push(TrialBalanceLine {
                account_id: id,
                account_number: number,
                account_name: name,
                account_type,
                debit_balance,
                credit_balance,
            });

            total_debits += debit_balance;
            total_credits += credit_balance;
        }

        Ok(TrialBalance {
            as_of_date,
            period_id: None,
            total_debits,
            total_credits,
            is_balanced: total_debits == total_credits,
            lines,
        })
    }

    pub async fn get_balance_sheet_async(&self, as_of_date: NaiveDate) -> Result<BalanceSheet> {
        let rows = sqlx::query_as::<_, (Uuid, String, String, String, Option<String>, Decimal, String)>(
            "SELECT id, account_number, name, account_type, account_sub_type, current_balance, normal_balance
             FROM gl_accounts
             WHERE is_posting = TRUE AND status = 'active'
               AND account_type IN ('asset', 'liability', 'equity')
             ORDER BY account_number",
        )
        .fetch_all(&self.pool)
        .await
        .map_err(map_db_error)?;

        let mut assets = Vec::new();
        let mut liabilities = Vec::new();
        let mut equity = Vec::new();
        let mut total_assets = Decimal::ZERO;
        let mut total_liabilities = Decimal::ZERO;
        let mut total_equity = Decimal::ZERO;

        for (id, number, name, account_type, sub_type, balance, _normal_balance) in rows {
            let account_type: AccountType = account_type.parse().map_err(|e| {
                CommerceError::DatabaseError(format!(
                    "Invalid gl_account.account_type '{}': {}",
                    account_type, e
                ))
            })?;
            let sub_type = match sub_type {
                Some(value) if !value.trim().is_empty() => Some(value.parse().map_err(|e| {
                    CommerceError::DatabaseError(format!(
                        "Invalid gl_account.account_sub_type '{}': {}",
                        value, e
                    ))
                })?),
                _ => None,
            };
            let line = BalanceSheetLine {
                account_id: id,
                account_number: number,
                account_name: name,
                account_sub_type: sub_type,
                balance,
                indent_level: 0,
                is_total: false,
            };

            match account_type {
                AccountType::Asset => {
                    total_assets += balance;
                    assets.push(line);
                }
                AccountType::Liability => {
                    total_liabilities += balance;
                    liabilities.push(line);
                }
                AccountType::Equity => {
                    total_equity += balance;
                    equity.push(line);
                }
                _ => {}
            }
        }

        Ok(BalanceSheet {
            as_of_date,
            total_assets,
            total_liabilities,
            total_equity,
            assets,
            liabilities,
            equity,
        })
    }

    pub async fn get_income_statement_async(
        &self,
        start_date: NaiveDate,
        end_date: NaiveDate,
    ) -> Result<IncomeStatement> {
        let rows =
            sqlx::query_as::<_, (Uuid, String, String, String, Option<String>, Decimal, Decimal)>(
                "SELECT a.id, a.account_number, a.name, a.account_type, a.account_sub_type,
                    COALESCE(SUM(l.debit_amount), 0) AS total_debits,
                    COALESCE(SUM(l.credit_amount), 0) AS total_credits
             FROM gl_accounts a
             LEFT JOIN gl_journal_entry_lines l ON a.id = l.account_id
             LEFT JOIN gl_journal_entries je ON l.journal_entry_id = je.id
             WHERE a.is_posting = TRUE AND a.status = 'active'
               AND a.account_type IN ('revenue', 'expense')
               AND (je.status = 'posted' OR je.id IS NULL)
               AND (je.entry_date >= $1 AND je.entry_date <= $2 OR je.id IS NULL)
             GROUP BY a.id
             ORDER BY a.account_number",
            )
            .bind(start_date)
            .bind(end_date)
            .fetch_all(&self.pool)
            .await
            .map_err(map_db_error)?;

        let mut revenue_lines = Vec::new();
        let mut expense_lines = Vec::new();
        let mut total_revenue = Decimal::ZERO;
        let mut total_expenses = Decimal::ZERO;

        for (id, number, name, account_type, sub_type, total_debits, total_credits) in rows {
            let account_type: AccountType = account_type.parse().map_err(|e| {
                CommerceError::DatabaseError(format!(
                    "Invalid gl_account.account_type '{}': {}",
                    account_type, e
                ))
            })?;
            let amount = match account_type {
                AccountType::Revenue => total_credits - total_debits,
                AccountType::Expense => total_debits - total_credits,
                _ => Decimal::ZERO,
            };

            if amount == Decimal::ZERO {
                continue;
            }

            let line = IncomeStatementLine {
                account_id: id,
                account_number: number,
                account_name: name,
                account_sub_type: match sub_type {
                    Some(value) if !value.trim().is_empty() => {
                        Some(value.parse().map_err(|e| {
                            CommerceError::DatabaseError(format!(
                                "Invalid gl_account.account_sub_type '{}': {}",
                                value, e
                            ))
                        })?)
                    }
                    _ => None,
                },
                amount,
                indent_level: 0,
                is_total: false,
            };

            match account_type {
                AccountType::Revenue => {
                    total_revenue += amount;
                    revenue_lines.push(line);
                }
                AccountType::Expense => {
                    total_expenses += amount;
                    expense_lines.push(line);
                }
                _ => {}
            }
        }

        Ok(IncomeStatement {
            period_start: start_date,
            period_end: end_date,
            total_revenue,
            total_expenses,
            net_income: total_revenue - total_expenses,
            revenue_lines,
            expense_lines,
        })
    }

    pub async fn get_account_balance_async(
        &self,
        account_id: Uuid,
        _as_of_date: Option<NaiveDate>,
    ) -> Result<Option<Decimal>> {
        Ok(self.get_account_async(account_id).await?.map(|account| account.current_balance))
    }

    pub async fn get_account_transactions_async(
        &self,
        account_id: Uuid,
        filter: JournalEntryFilter,
    ) -> Result<Vec<JournalEntryLine>> {
        let mut builder = QueryBuilder::<Postgres>::new(
            "SELECT l.id, l.journal_entry_id, l.line_number, l.account_id, l.account_number,
                    l.account_name, l.description, l.debit_amount, l.credit_amount, l.currency,
                    l.reference_type, l.reference_id, l.created_at
             FROM gl_journal_entry_lines l
             JOIN gl_journal_entries je ON l.journal_entry_id = je.id
             WHERE l.account_id = ",
        );
        builder.push_bind(account_id);

        if let Some(status) = filter.status {
            builder.push(" AND je.status = ").push_bind(status.to_string());
        }
        if let Some(from_date) = filter.from_date {
            builder.push(" AND je.entry_date >= ").push_bind(from_date);
        }
        if let Some(to_date) = filter.to_date {
            builder.push(" AND je.entry_date <= ").push_bind(to_date);
        }

        builder.push(" ORDER BY je.entry_date DESC, l.line_number");

        builder.push(" LIMIT ").push_bind(super::effective_limit(filter.limit));

        let rows = builder
            .build_query_as::<JournalEntryLineRow>()
            .fetch_all(&self.pool)
            .await
            .map_err(map_db_error)?;

        Ok(rows.into_iter().map(Self::row_to_journal_entry_line).collect())
    }

    pub async fn run_period_close_async(
        &self,
        period_id: Uuid,
        closed_by: &str,
    ) -> Result<JournalEntry> {
        let period = self.get_period_async(period_id).await?.ok_or(CommerceError::NotFound)?;

        if period.status != PeriodStatus::Open {
            return Err(CommerceError::ValidationError("Period must be open to close".to_string()));
        }

        let income_statement =
            self.get_income_statement_async(period.start_date, period.end_date).await?;

        if income_statement.net_income == Decimal::ZERO
            && income_statement.revenue_lines.iter().all(|l| l.amount == Decimal::ZERO)
            && income_statement.expense_lines.iter().all(|l| l.amount == Decimal::ZERO)
        {
            return Err(CommerceError::ValidationError("No net income to close".to_string()));
        }

        let retained_earnings = self
            .list_accounts_async(GlAccountFilter {
                account_sub_type: Some(AccountSubType::RetainedEarnings),
                ..Default::default()
            })
            .await?
            .into_iter()
            .next()
            .ok_or_else(|| {
                CommerceError::ValidationError("Retained earnings account not found".to_string())
            })?;

        let mut lines = Vec::new();

        for rev in income_statement.revenue_lines {
            // Revenue is credit-normal: positive balances close with a debit,
            // contra-normal (negative) balances with a credit.
            let memo = Some(format!("Close {} to Retained Earnings", rev.account_name));
            if rev.amount > Decimal::ZERO {
                lines.push(CreateJournalEntryLine::debit(rev.account_id, rev.amount, memo));
            } else if rev.amount < Decimal::ZERO {
                lines.push(CreateJournalEntryLine::credit(rev.account_id, rev.amount.abs(), memo));
            }
        }

        for exp in income_statement.expense_lines {
            // Expenses are debit-normal: positive balances close with a
            // credit, contra-normal balances (e.g. a net FX gain on an
            // expense-type gain/loss account) with a debit.
            let memo = Some(format!("Close {} to Retained Earnings", exp.account_name));
            if exp.amount > Decimal::ZERO {
                lines.push(CreateJournalEntryLine::credit(exp.account_id, exp.amount, memo));
            } else if exp.amount < Decimal::ZERO {
                lines.push(CreateJournalEntryLine::debit(exp.account_id, exp.amount.abs(), memo));
            }
        }

        if income_statement.net_income > Decimal::ZERO {
            lines.push(CreateJournalEntryLine::credit(
                retained_earnings.id,
                income_statement.net_income,
                Some("Net income to Retained Earnings".to_string()),
            ));
        } else if income_statement.net_income < Decimal::ZERO {
            lines.push(CreateJournalEntryLine::debit(
                retained_earnings.id,
                income_statement.net_income.abs(),
                Some("Net loss to Retained Earnings".to_string()),
            ));
        }

        let closing_entry = self
            .create_journal_entry_async(CreateJournalEntry {
                entry_date: period.end_date,
                entry_type: Some(JournalEntryType::Closing),
                description: format!("Closing entries for {}", period.period_name),
                lines,
                source_document_type: Some("period_close".to_string()),
                source_document_id: Some(period_id),
                auto_post: Some(true),
            })
            .await?;

        self.close_period_async(period_id, closed_by).await?;

        Ok(closing_entry)
    }

    /// Look up the exchange rate converting one `from` unit into `to` units,
    /// falling back to the inverse of the reverse pair when only that is set.
    async fn lookup_rate_async(&self, from: &str, to: &str) -> Result<Option<Decimal>> {
        let direct: Option<Decimal> = sqlx::query_scalar(
            "SELECT rate FROM exchange_rates WHERE base_currency = $1 AND quote_currency = $2",
        )
        .bind(from)
        .bind(to)
        .fetch_optional(&self.pool)
        .await
        .map_err(map_db_error)?;
        if let Some(rate) = direct {
            return Ok(Some(rate));
        }

        let inverse: Option<Decimal> = sqlx::query_scalar(
            "SELECT rate FROM exchange_rates WHERE base_currency = $1 AND quote_currency = $2",
        )
        .bind(to)
        .bind(from)
        .fetch_optional(&self.pool)
        .await
        .map_err(map_db_error)?;
        Ok(inverse.and_then(|rate| if rate.is_zero() { None } else { Some(Decimal::ONE / rate) }))
    }

    /// Resolve the account receiving unrealized FX gains/losses: the
    /// configured `fx_gain_loss_account_id`, else the first active posting
    /// account with an Other Expense / Other Revenue sub-type.
    async fn resolve_fx_gain_loss_account_async(&self) -> Result<Uuid> {
        if let Some(id) = self
            .get_auto_posting_config_async()
            .await?
            .and_then(|config| config.fx_gain_loss_account_id)
        {
            return Ok(id);
        }
        for sub_type in [AccountSubType::OtherExpense, AccountSubType::OtherRevenue] {
            let fallback = self
                .list_accounts_async(GlAccountFilter {
                    account_sub_type: Some(sub_type),
                    status: Some(AccountStatus::Active),
                    is_posting: Some(true),
                    limit: Some(1),
                    ..Default::default()
                })
                .await?
                .into_iter()
                .next();
            if let Some(account) = fallback {
                return Ok(account.id);
            }
        }
        Err(CommerceError::ValidationError(
            "No FX gain/loss account configured for revaluation".to_string(),
        ))
    }

    pub async fn revalue_async(
        &self,
        as_of_date: NaiveDate,
        base_currency: Option<Currency>,
    ) -> Result<RevaluationResult> {
        let base = match base_currency {
            Some(base) => base,
            None => {
                let code: Option<String> =
                    sqlx::query_scalar("SELECT base_currency FROM store_currency_settings LIMIT 1")
                        .fetch_optional(&self.pool)
                        .await
                        .map_err(map_db_error)?;
                match code {
                    Some(code) => code.parse::<Currency>().map_err(|e| {
                        CommerceError::DatabaseError(format!(
                            "Invalid store base currency {code:?}: {e}"
                        ))
                    })?,
                    None => Currency::default(),
                }
            }
        };
        let base_code: CurrencyCode = base.code().parse().map_err(|e| {
            CommerceError::ValidationError(format!(
                "Base currency {} is not a valid ISO code: {e}",
                base.code()
            ))
        })?;
        let base_places = u32::from(base.decimal_places());

        let accounts = self
            .list_accounts_async(GlAccountFilter {
                status: Some(AccountStatus::Active),
                is_posting: Some(true),
                ..Default::default()
            })
            .await?;

        let mut lines: Vec<stateset_core::RevaluationLine> = Vec::new();
        for account in accounts {
            if account.currency == base_code {
                continue;
            }

            // Outstanding foreign-currency balance: posted lines excluding
            // prior base-currency FX revaluation adjustments.
            let row: (Decimal, Decimal) = sqlx::query_as(
                "SELECT COALESCE(SUM(l.debit_amount), 0), COALESCE(SUM(l.credit_amount), 0)
                 FROM gl_journal_entry_lines l
                 JOIN gl_journal_entries je ON l.journal_entry_id = je.id
                 WHERE l.account_id = $1 AND je.status = 'posted'
                   AND (l.reference_type IS NULL OR l.reference_type != $2)",
            )
            .bind(account.id)
            .bind(FX_REVALUATION_REFERENCE)
            .fetch_one(&self.pool)
            .await
            .map_err(map_db_error)?;
            let foreign_balance = account.balance_effect(row.0, row.1);

            if foreign_balance.is_zero() && account.current_balance.is_zero() {
                continue;
            }

            let rate = self
                .lookup_rate_async(account.currency.as_str(), base.code())
                .await?
                .ok_or_else(|| {
                    CommerceError::ValidationError(format!(
                        "No exchange rate available for {} -> {}",
                        account.currency,
                        base.code()
                    ))
                })?;

            lines.push(stateset_core::compute_revaluation_line(
                &account,
                foreign_balance,
                rate,
                base_places,
            ));
        }

        let total_unrealized_gain_loss: Decimal =
            lines.iter().map(|l| l.unrealized_gain_loss).sum();

        let journal_entry = if lines.iter().any(|l| !l.adjustment.is_zero()) {
            let fx_account_id = self.resolve_fx_gain_loss_account_async().await?;
            let entry_lines = stateset_core::build_revaluation_journal_lines(&lines, fx_account_id);
            Some(
                self.create_journal_entry_async(CreateJournalEntry {
                    entry_date: as_of_date,
                    entry_type: Some(JournalEntryType::Adjusting),
                    description: format!("FX revaluation as of {as_of_date}"),
                    lines: entry_lines,
                    source_document_type: Some(FX_REVALUATION_REFERENCE.to_string()),
                    source_document_id: None,
                    auto_post: Some(true),
                })
                .await?,
            )
        } else {
            None
        };

        Ok(RevaluationResult {
            as_of_date,
            base_currency: base_code,
            total_unrealized_gain_loss,
            lines,
            journal_entry,
        })
    }

    pub async fn create_accounts_batch_async(
        &self,
        inputs: Vec<CreateGlAccount>,
    ) -> Result<BatchResult<GlAccount>> {
        let mut result = BatchResult::new();

        for (index, input) in inputs.into_iter().enumerate() {
            match self.create_account_async(input).await {
                Ok(account) => result.record_success(account),
                Err(e) => result.record_failure(index, None, &e),
            }
        }

        Ok(result)
    }

    pub async fn get_accounts_batch_async(&self, ids: Vec<Uuid>) -> Result<Vec<GlAccount>> {
        let mut accounts = Vec::new();
        for id in ids {
            if let Some(account) = self.get_account_async(id).await? {
                accounts.push(account);
            }
        }
        Ok(accounts)
    }
}

impl GeneralLedgerRepository for PgGeneralLedgerRepository {
    fn create_account(&self, input: CreateGlAccount) -> Result<GlAccount> {
        block_on(self.create_account_async(input))
    }

    fn get_account(&self, id: Uuid) -> Result<Option<GlAccount>> {
        block_on(self.get_account_async(id))
    }

    fn get_account_by_number(&self, account_number: &str) -> Result<Option<GlAccount>> {
        block_on(self.get_account_by_number_async(account_number))
    }

    fn update_account(&self, id: Uuid, input: stateset_core::UpdateGlAccount) -> Result<GlAccount> {
        block_on(self.update_account_async(id, input))
    }

    fn list_accounts(&self, filter: GlAccountFilter) -> Result<Vec<GlAccount>> {
        block_on(self.list_accounts_async(filter))
    }

    fn get_account_hierarchy(&self) -> Result<Vec<GlAccount>> {
        block_on(self.get_account_hierarchy_async())
    }

    fn delete_account(&self, id: Uuid) -> Result<()> {
        block_on(self.delete_account_async(id))
    }

    fn initialize_chart_of_accounts(&self) -> Result<Vec<GlAccount>> {
        block_on(self.initialize_chart_of_accounts_async())
    }

    fn create_period(&self, input: CreateGlPeriod) -> Result<GlPeriod> {
        block_on(self.create_period_async(input))
    }

    fn get_period(&self, id: Uuid) -> Result<Option<GlPeriod>> {
        block_on(self.get_period_async(id))
    }

    fn get_current_period(&self) -> Result<Option<GlPeriod>> {
        block_on(self.get_current_period_async())
    }

    fn get_period_for_date(&self, date: NaiveDate) -> Result<Option<GlPeriod>> {
        block_on(self.get_period_for_date_async(date))
    }

    fn list_periods(&self, filter: GlPeriodFilter) -> Result<Vec<GlPeriod>> {
        block_on(self.list_periods_async(filter))
    }

    fn open_period(&self, id: Uuid) -> Result<GlPeriod> {
        block_on(self.open_period_async(id))
    }

    fn close_period(&self, id: Uuid, closed_by: &str) -> Result<GlPeriod> {
        block_on(self.close_period_async(id, closed_by))
    }

    fn lock_period(&self, id: Uuid, locked_by: &str) -> Result<GlPeriod> {
        block_on(self.lock_period_async(id, locked_by))
    }

    fn reopen_period(&self, id: Uuid) -> Result<GlPeriod> {
        block_on(self.reopen_period_async(id))
    }

    fn create_journal_entry(&self, input: CreateJournalEntry) -> Result<JournalEntry> {
        block_on(self.create_journal_entry_async(input))
    }

    fn get_journal_entry(&self, id: Uuid) -> Result<Option<JournalEntry>> {
        block_on(self.get_journal_entry_async(id))
    }

    fn get_journal_entry_by_number(&self, number: &str) -> Result<Option<JournalEntry>> {
        block_on(self.get_journal_entry_by_number_async(number))
    }

    fn list_journal_entries(&self, filter: JournalEntryFilter) -> Result<Vec<JournalEntry>> {
        block_on(self.list_journal_entries_async(filter))
    }

    fn post_journal_entry(&self, id: Uuid, posted_by: &str) -> Result<JournalEntry> {
        block_on(self.post_journal_entry_async(id, posted_by))
    }

    fn void_journal_entry(&self, id: Uuid) -> Result<JournalEntry> {
        block_on(self.void_journal_entry_async(id))
    }

    fn reverse_journal_entry(&self, id: Uuid, reversal_date: NaiveDate) -> Result<JournalEntry> {
        block_on(self.reverse_journal_entry_async(id, reversal_date))
    }

    fn get_journal_entry_lines(&self, journal_entry_id: Uuid) -> Result<Vec<JournalEntryLine>> {
        block_on(self.get_journal_entry_lines_async(journal_entry_id))
    }

    fn get_auto_posting_config(&self) -> Result<Option<AutoPostingConfig>> {
        block_on(self.get_auto_posting_config_async())
    }

    fn set_auto_posting_config(&self, input: CreateAutoPostingConfig) -> Result<AutoPostingConfig> {
        block_on(self.set_auto_posting_config_async(input))
    }

    fn auto_post_invoice(&self, invoice_id: InvoiceId) -> Result<JournalEntry> {
        block_on(self.auto_post_invoice_async(invoice_id.into_uuid()))
    }

    fn auto_post_payment_received(&self, payment_id: Uuid) -> Result<JournalEntry> {
        block_on(self.auto_post_payment_received_async(payment_id))
    }

    fn auto_post_bill(&self, bill_id: Uuid) -> Result<JournalEntry> {
        block_on(self.auto_post_bill_async(bill_id))
    }

    fn auto_post_bill_payment(&self, payment_id: Uuid) -> Result<JournalEntry> {
        block_on(self.auto_post_bill_payment_async(payment_id))
    }

    fn auto_post_inventory_cost(&self, cost_transaction_id: Uuid) -> Result<JournalEntry> {
        block_on(self.auto_post_inventory_cost_async(cost_transaction_id))
    }

    fn auto_post_write_off(&self, write_off_id: Uuid) -> Result<JournalEntry> {
        block_on(self.auto_post_write_off_async(write_off_id))
    }

    fn get_trial_balance(&self, as_of_date: NaiveDate) -> Result<TrialBalance> {
        block_on(self.get_trial_balance_async(as_of_date))
    }

    fn get_balance_sheet(&self, as_of_date: NaiveDate) -> Result<BalanceSheet> {
        block_on(self.get_balance_sheet_async(as_of_date))
    }

    fn get_income_statement(
        &self,
        start_date: NaiveDate,
        end_date: NaiveDate,
    ) -> Result<IncomeStatement> {
        block_on(self.get_income_statement_async(start_date, end_date))
    }

    fn get_account_balance(
        &self,
        account_id: Uuid,
        as_of_date: Option<NaiveDate>,
    ) -> Result<Option<Decimal>> {
        block_on(self.get_account_balance_async(account_id, as_of_date))
    }

    fn get_account_transactions(
        &self,
        account_id: Uuid,
        filter: JournalEntryFilter,
    ) -> Result<Vec<JournalEntryLine>> {
        block_on(self.get_account_transactions_async(account_id, filter))
    }

    fn run_period_close(&self, period_id: Uuid, closed_by: &str) -> Result<JournalEntry> {
        block_on(self.run_period_close_async(period_id, closed_by))
    }

    fn revalue(
        &self,
        as_of_date: NaiveDate,
        base_currency: Option<Currency>,
    ) -> Result<RevaluationResult> {
        block_on(self.revalue_async(as_of_date, base_currency))
    }

    fn create_accounts_batch(
        &self,
        inputs: Vec<CreateGlAccount>,
    ) -> Result<BatchResult<GlAccount>> {
        block_on(self.create_accounts_batch_async(inputs))
    }

    fn get_accounts_batch(&self, ids: Vec<Uuid>) -> Result<Vec<GlAccount>> {
        block_on(self.get_accounts_batch_async(ids))
    }
}