summaryrefslogtreecommitdiff
path: root/src/FundLab.Api/Persistence.fs
blob: 973544f1de6a30acdb97425db305813cdaa74cb4 (plain)
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
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
namespace FundLab.Api

open System
open System.Data
open System.Data.Common
open System.Globalization
open System.Security.Cryptography
open System.Text
open FundLab.Domain
open Npgsql
open NpgsqlTypes
open System.Text.Json

module ConfirmationPolicy =
    let cutoffTimeOfDay = TimeSpan(15, 0, 0)
    let unitsMaximum = 99999999999999999999.99999999m
    let amountMaximum = 999999999999999999.99m

    let private shanghaiZone =
        lazy (
            try
                TimeZoneInfo.FindSystemTimeZoneById("Asia/Shanghai")
            with _ ->
                TimeZoneInfo.CreateCustomTimeZone(
                    "Asia/Shanghai (UTC+8)",
                    TimeSpan(8, 0, 0),
                    "Asia/Shanghai (UTC+8)",
                    "Asia/Shanghai (UTC+8)"
                )
        )

    let shanghaiDate (moment: DateTimeOffset) : DateOnly =
        DateOnly.FromDateTime(TimeZoneInfo.ConvertTime(moment, shanghaiZone.Value).Date)

    let private isWeekend (date: DateOnly) =
        date.DayOfWeek = DayOfWeek.Saturday || date.DayOfWeek = DayOfWeek.Sunday

    let rec private rollToWeekday (date: DateOnly) =
        if isWeekend date then rollToWeekday (date.AddDays 1) else date

    let isModeledTradingDay (date: DateOnly) : bool = not (isWeekend date)

    /// Test-only clock anchor: modules may pin the trading-date clock by exporting
    /// FUND_LAB_TEST_TRADE_DATE so suites stay independent of the wall clock. Unset in
    /// production, the real Shanghai rule applies unchanged.
    let tradeDateFor (submittedAt: DateTimeOffset) : DateOnly =
        match Environment.GetEnvironmentVariable("FUND_LAB_TEST_TRADE_DATE") with
        | value when not (String.IsNullOrWhiteSpace value) ->
            match DateOnly.TryParseExact(value, "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None) with
            | true, anchored -> anchored
            | _ ->
                let local = TimeZoneInfo.ConvertTime(submittedAt, shanghaiZone.Value)
                let date = DateOnly.FromDateTime(local.Date)
                let candidate = if local.TimeOfDay >= cutoffTimeOfDay then date.AddDays 1 else date
                rollToWeekday candidate
        | _ ->
            let local = TimeZoneInfo.ConvertTime(submittedAt, shanghaiZone.Value)
            let date = DateOnly.FromDateTime(local.Date)
            let candidate = if local.TimeOfDay >= cutoffTimeOfDay then date.AddDays 1 else date
            rollToWeekday candidate

    type NavQuote =
        { NavDate: DateOnly
          Nav: decimal
          CollectedAt: DateTimeOffset
          PublishedAt: DateTimeOffset option }

    type ConfirmationComputation =
        {
            Units: decimal
            InvestedCash: decimal
            ResidualCash: decimal
        }

    let navDeferralReason
        (quote: NavQuote)
        (tradeDate: DateOnly)
        (today: DateOnly)
        (now: DateTimeOffset)
        : string option =
        let tradeDateText = tradeDate.ToString("yyyy-MM-dd")

        if quote.Nav <= 0m then
            Some(sprintf "nav for trade date %s is not positive" tradeDateText)
        elif quote.NavDate > today then
            Some(sprintf "nav for trade date %s is dated in the future" tradeDateText)
        elif quote.CollectedAt > now then
            Some(sprintf "nav for trade date %s is not yet collected" tradeDateText)
        elif quote.PublishedAt |> Option.exists (fun publishedAt -> publishedAt > now) then
            Some(sprintf "nav for trade date %s is not yet published" tradeDateText)
        elif quote.NavDate <> tradeDate then
            Some(sprintf "nav for trade date %s is not available yet" tradeDateText)
        else
            None

    let compute (amount: decimal) (nav: decimal) : Result<ConfirmationComputation, string> =
        if amount <= 0m then
            Error "amount must be positive"
        elif amount > amountMaximum then
            Error "amount exceeds supported precision"
        elif nav <= 0m then
            Error "unit nav must be positive"
        elif nav < 0.00000001m then
            Error "unit nav is below database precision"
        else
            let rawUnits = amount / nav

            if rawUnits > unitsMaximum then
                Error "unit amount exceeds database precision"
            else
                let units = Decimal.Truncate(rawUnits * 100000000m) / 100000000m

                if units <= 0m then
                    Error "amount converts to zero units at this unit nav"
                else
                    let invested = Decimal.Truncate(units * nav * 100m) / 100m

                    Ok
                        {
                            Units = units
                            InvestedCash = invested
                            ResidualCash = amount - invested
                        }

[<CLIMutable>]
type FundCreateCommand =
    {
        Name: string
        InitialCash: decimal
        InitialUnitNav: decimal
        IsSynthetic: bool
    }

type FundRecord =
    {
        Id: Guid
        Name: string
        Currency: string
        InitialCash: decimal
        InitialUnitNav: decimal
        IsSynthetic: bool
        AvailableCash: decimal
        ReservedCash: decimal
        Status: string
    }

type FundWriteResult =
    | Created of FundRecord
    | Replayed of FundRecord
    | IdempotencyConflict
    | Invalid of string

[<CLIMutable>]
type SubscriptionOrderCommand =
    {
        FundCode: string
        Amount: decimal
        FeeAmount: decimal
    }

type ConfirmedQuoteEvidence =
    {
        Nav: decimal
        NavDate: DateOnly
        Source: string
        Revision: string
        CollectedAt: DateTimeOffset
        PublishedAt: DateTimeOffset option
        PayloadHash: string
        FirstSeenAt: DateTimeOffset
    }

type SubscriptionOrderRecord =
    {
        Id: Guid
        FundId: Guid
        FundCode: string
        Amount: decimal
        FeeAmount: decimal
        ReservedTotal: decimal
        Status: string
        SubmittedAt: DateTimeOffset
        IsSynthetic: bool
        TradeDate: DateOnly
        ConfirmIdempotencyKey: string option
        PendingReason: string option
        ConfirmedAt: DateTimeOffset option
        ConfirmedQuote: ConfirmedQuoteEvidence option
        ConfirmedUnits: decimal option
        ConfirmedInvestedCash: decimal option
        ConfirmedResidualCash: decimal option
    }

type SubscriptionOrderWriteResult =
    | OrderCreated of SubscriptionOrderRecord
    | OrderReplayed of SubscriptionOrderRecord
    | OrderIdempotencyConflict
    | OrderInvalid of string
    | OrderFundNotFound
    | OrderInstrumentNotFound
    | OrderInsufficientFunds

type SubscriptionConfirmResult =
    | OrderConfirmed of SubscriptionOrderRecord
    | ConfirmReplayed of SubscriptionOrderRecord
    | ConfirmPendingNav of SubscriptionOrderRecord
    | ConfirmIdempotencyConflict
    | ConfirmAlreadyConfirmed
    | ConfirmOrderNotFound
    | ConfirmInvalidStatus
    | ConfirmInvalid of string

type FundPositionRecord =
    {
        FundId: Guid
        InstrumentCode: string
        Units: decimal
        ReservedUnits: decimal
        CostCash: decimal
        LastConfirmedAt: DateTimeOffset
        ValuationNav: decimal option
        ValuationNavDate: DateOnly option
        ValuationCollectedAt: DateTimeOffset option
    }

type RedemptionCommand =
    {
        InstrumentCode: string
        Units: decimal
        FeeAmount: decimal
    }

type RedemptionOrderRecord =
    {
        Id: Guid
        FundId: Guid
        InstrumentCode: string
        Units: decimal
        FeeAmount: decimal
        Status: string
        IsSynthetic: bool
        SubmittedAt: DateTimeOffset
        TradeDate: DateOnly
        ConfirmIdempotencyKey: string option
        PendingReason: string option
        ConfirmedAt: DateTimeOffset option
        ConfirmedNav: decimal option
        ConfirmedNavDate: DateOnly option
        ConfirmedProceeds: decimal option
        ConfirmedCostReleased: decimal option
    }

type RedemptionWriteResult =
    | RedemptionCreated of RedemptionOrderRecord
    | RedemptionReplayed of RedemptionOrderRecord
    | RedemptionIdempotencyConflict
    | RedemptionInvalid of string
    | RedemptionFundNotFound
    | RedemptionInstrumentNotFound
    | RedemptionInsufficientUnits

type RedemptionConfirmResult =
    | RedemptionConfirmed of RedemptionOrderRecord
    | RedemptionConfirmReplayed of RedemptionOrderRecord
    | RedemptionPendingNav of RedemptionOrderRecord
    | RedemptionConfirmIdempotencyConflict
    | RedemptionAlreadyConfirmed
    | RedemptionOrderNotFound
    | RedemptionInvalidStatus
    | RedemptionInvalid of string

type SipPlanCommand =
    {
        InstrumentCode: string
        Amount: decimal
        Frequency: SipFrequency
    }

type SipPlanRecord =
    {
        Id: Guid
        FundId: Guid
        InstrumentCode: string
        Amount: decimal
        Frequency: SipFrequency
        Status: string
        IsSynthetic: bool
        AnchorDate: DateOnly
        NextTradeDate: DateOnly
        CreatedAt: DateTimeOffset
        LastExecutionStatus: string option
        LastExecutionDate: DateOnly option
    }

type SipPlanWriteResult =
    | SipPlanCreated of SipPlanRecord
    | SipPlanReplayed of SipPlanRecord
    | SipPlanIdempotencyConflict
    | SipPlanInvalid of string
    | SipPlanFundNotFound
    | SipPlanInstrumentNotFound

type SipExecutionOutcome =
    {
        TradeDate: DateOnly
        Status: string
        OrderId: Guid option
        PendingReason: string option
    }

type SipPlanAdvanceResult =
    {
        PlanId: Guid
        InstrumentCode: string
        Amount: decimal
        Frequency: SipFrequency
        Executions: SipExecutionOutcome list
        NextTradeDate: DateOnly
    }

type SipAdvanceResult =
    {
        FundId: Guid
        Plans: SipPlanAdvanceResult list
    }

type RebalanceTarget = RebalancePolicy.TargetAllocation

type RebalancePlanCommand =
    {
        Targets: RebalanceTarget list
    }

type RebalancePlanRecord =
    {
        Id: Guid
        FundId: Guid
        Targets: RebalanceTarget list
        Status: string
        IsSynthetic: bool
        CreatedAt: DateTimeOffset
    }

type RebalanceWriteResult =
    | RebalancePlanCreated of RebalancePlanRecord
    | RebalancePlanReplayed of RebalancePlanRecord
    | RebalanceIdempotencyConflict
    | RebalanceInvalid of string
    | RebalanceFundNotFound
    | RebalanceInstrumentNotFound

type RebalanceOrderOutcome =
    {
        InstrumentCode: string
        Action: string
        Amount: string
        Status: string
        OrderId: Guid option
        PendingReason: string option
    }

type RebalanceExecutionResult =
    {
        PlanId: Guid
        RunDate: DateOnly
        Outcomes: RebalanceOrderOutcome list
    }

type DividendMode = DividendPolicy.DividendMode

type DividendCommand =
    {
        InstrumentCode: string
        NavDate: DateOnly
        Dps: decimal
        Mode: DividendMode
    }

type DividendRecord =
    {
        Id: Guid
        FundId: Guid
        InstrumentCode: string
        NavDate: DateOnly
        Dps: decimal
        Mode: DividendMode
        Status: string
        IsSynthetic: bool
        GrossCash: decimal option
        CreditedUnits: decimal option
        CreditedInvested: decimal option
        OrderId: Guid option
        PendingReason: string option
        CreatedAt: DateTimeOffset
    }

type DividendWriteResult =
    | DividendCredited of DividendRecord
    | DividendReplayed of DividendRecord
    | DividendPendingReinvest of DividendRecord
    | DividendIdempotencyConflict
    | DividendInvalid of string
    | DividendFundNotFound
    | DividendInstrumentNotFound
    | DividendNoHoldings

type DividendStageDecision =
    | StageReplay of Guid
    | StageFail of DividendWriteResult
    | StageBooked of DividendRecord


type CapitalDepositCommand =
    {
        Amount: decimal
        Note: string option
    }

type CapitalDepositRecord =
    {
        Id: Guid
        FundId: Guid
        Amount: decimal
        Note: string option
        IsSynthetic: bool
        CreatedAt: DateTimeOffset
    }

type CapitalDepositWriteResult =
    | CapitalDepositCreated of CapitalDepositRecord
    | CapitalDepositReplayed of CapitalDepositRecord
    | CapitalDepositIdempotencyConflict
    | CapitalDepositInvalid of string
    | CapitalDepositFundNotFound

type FundRepository(connectionString: string) =
    let cashMaximum = 999999999999999999.99m
    let unitNavMaximum = 99999999999999999999.99999999m

    let schema =
        """
        CREATE TABLE IF NOT EXISTS funds (
            id uuid PRIMARY KEY,
            name text NOT NULL,
            currency text NOT NULL,
            initial_cash numeric(20, 2) NOT NULL,
            initial_unit_nav numeric(28, 8) NOT NULL,
            is_synthetic boolean NOT NULL,
            available_cash numeric(20, 2) NOT NULL,
            status text NOT NULL,
            created_at timestamptz NOT NULL DEFAULT now()
        );

        CREATE TABLE IF NOT EXISTS fund_idempotencies (
            idempotency_key text PRIMARY KEY,
            request_hash text NOT NULL,
            fund_id uuid NOT NULL REFERENCES funds(id),
            created_at timestamptz NOT NULL DEFAULT now()
        );

        CREATE TABLE IF NOT EXISTS instruments (
            code text PRIMARY KEY CHECK (code ~ '^[0-9]{6}$'),
            name text NOT NULL,
            fund_type text NULL,
            source text NOT NULL,
            source_revision text NOT NULL,
            source_collected_at timestamptz NOT NULL,
            source_payload_hash text NOT NULL,
            first_seen_at timestamptz NOT NULL DEFAULT now(),
            last_seen_at timestamptz NOT NULL DEFAULT now()
        );

        CREATE TABLE IF NOT EXISTS fund_nav_observations (
            instrument_code text NOT NULL REFERENCES instruments(code),
            nav_date date NOT NULL,
            published_at timestamptz NULL,
            nav numeric(28, 8) NOT NULL,
            accumulated_nav numeric(28, 8) NULL,
            daily_return numeric(20, 8) NULL,
            source text NOT NULL,
            source_revision text NOT NULL,
            source_collected_at timestamptz NOT NULL,
            source_payload_hash text NOT NULL,
            first_seen_at timestamptz NOT NULL DEFAULT now(),
            last_seen_at timestamptz NOT NULL DEFAULT now(),
            PRIMARY KEY (instrument_code, nav_date)
        );

        CREATE INDEX IF NOT EXISTS fund_nav_observations_date_idx
            ON fund_nav_observations (instrument_code, nav_date);

        CREATE TABLE IF NOT EXISTS fund_nav_observation_evidence (
            instrument_code text NOT NULL REFERENCES instruments(code),
            nav_date date NOT NULL,
            source_payload_hash text NOT NULL,
            source_revision text NOT NULL,
            source text NOT NULL,
            source_collected_at timestamptz NOT NULL,
            published_at timestamptz NULL,
            nav numeric(28, 8) NOT NULL,
            first_seen_at timestamptz NOT NULL DEFAULT now(),
            PRIMARY KEY (instrument_code, nav_date, source_payload_hash)
        );

        ALTER TABLE funds ADD COLUMN IF NOT EXISTS reserved_cash numeric(20, 2) NOT NULL DEFAULT 0;

        CREATE TABLE IF NOT EXISTS subscription_orders (
            id uuid PRIMARY KEY,
            fund_id uuid NOT NULL REFERENCES funds(id),
            fund_code text NOT NULL,
            amount numeric(20, 2) NOT NULL CHECK (amount > 0),
            fee_amount numeric(20, 2) NOT NULL CHECK (fee_amount >= 0),
            reserved_total numeric(20, 2) NOT NULL CHECK (reserved_total > 0),
            status text NOT NULL,
            is_synthetic boolean NOT NULL,
            submitted_at timestamptz NOT NULL DEFAULT now()
        );

        ALTER TABLE subscription_orders DROP CONSTRAINT IF EXISTS subscription_orders_fee_amount_check;
        ALTER TABLE subscription_orders ADD CONSTRAINT subscription_orders_fee_amount_check CHECK (fee_amount >= 0);

        CREATE TABLE IF NOT EXISTS subscription_order_idempotencies (
            idempotency_key text PRIMARY KEY,
            request_hash text NOT NULL,
            order_id uuid NOT NULL REFERENCES subscription_orders(id),
            fund_id uuid NOT NULL REFERENCES funds(id),
            created_at timestamptz NOT NULL DEFAULT now()
        );

        ALTER TABLE subscription_orders ADD COLUMN IF NOT EXISTS confirm_idempotency_key text NULL;
        ALTER TABLE subscription_orders ADD COLUMN IF NOT EXISTS pending_reason text NULL;
        ALTER TABLE subscription_orders ADD COLUMN IF NOT EXISTS confirmed_at timestamptz NULL;
        ALTER TABLE subscription_orders ADD COLUMN IF NOT EXISTS confirmed_nav numeric(28, 8) NULL;
        ALTER TABLE subscription_orders ADD COLUMN IF NOT EXISTS confirmed_nav_date date NULL;
        ALTER TABLE subscription_orders ADD COLUMN IF NOT EXISTS confirmed_nav_source text NULL;
        ALTER TABLE subscription_orders ADD COLUMN IF NOT EXISTS confirmed_nav_revision text NULL;
        ALTER TABLE subscription_orders ADD COLUMN IF NOT EXISTS confirmed_nav_collected_at timestamptz NULL;
        ALTER TABLE subscription_orders ADD COLUMN IF NOT EXISTS confirmed_nav_published_at timestamptz NULL;
        ALTER TABLE subscription_orders ADD COLUMN IF NOT EXISTS confirmed_units numeric(28, 8) NULL;
        ALTER TABLE subscription_orders ADD COLUMN IF NOT EXISTS confirmed_invested_cash numeric(20, 2) NULL;
        ALTER TABLE subscription_orders ADD COLUMN IF NOT EXISTS confirmed_residual_cash numeric(20, 2) NULL;

        ALTER TABLE subscription_orders ADD COLUMN IF NOT EXISTS confirmed_nav_payload_hash text NULL;

        ALTER TABLE subscription_orders ADD COLUMN IF NOT EXISTS confirmed_nav_first_seen_at timestamptz NULL;

        ALTER TABLE subscription_orders ADD COLUMN IF NOT EXISTS trade_date date NULL;

        UPDATE subscription_orders SET trade_date = (submitted_at AT TIME ZONE 'Asia/Shanghai')::date WHERE trade_date IS NULL;

        CREATE TABLE IF NOT EXISTS fund_positions (
            fund_id uuid NOT NULL REFERENCES funds(id),
            instrument_code text NOT NULL REFERENCES instruments(code),
            units numeric(28, 8) NOT NULL CHECK (units > 0),
            cost_cash numeric(20, 2) NOT NULL CHECK (cost_cash >= 0),
            first_confirmed_at timestamptz NOT NULL,
            last_confirmed_at timestamptz NOT NULL,
            PRIMARY KEY (fund_id, instrument_code)
        );

        CREATE TABLE IF NOT EXISTS subscription_order_events (
            id bigserial PRIMARY KEY,
            order_id uuid NOT NULL REFERENCES subscription_orders(id),
            event_type text NOT NULL,
            detail jsonb NOT NULL,
            created_at timestamptz NOT NULL DEFAULT now()
        );

        CREATE TABLE IF NOT EXISTS subscription_confirm_idempotencies (
            idempotency_key text PRIMARY KEY,
            request_hash text NOT NULL,
            order_id uuid NOT NULL REFERENCES subscription_orders(id),
            fund_id uuid NOT NULL REFERENCES funds(id),
            created_at timestamptz NOT NULL DEFAULT now()
        );

        CREATE TABLE IF NOT EXISTS redemption_orders (
            id uuid PRIMARY KEY,
            fund_id uuid NOT NULL REFERENCES funds(id),
            instrument_code text NOT NULL REFERENCES instruments(code),
            units numeric(28, 8) NOT NULL CHECK (units > 0),
            fee_amount numeric(20, 2) NOT NULL CHECK (fee_amount >= 0),
            status text NOT NULL,
            is_synthetic boolean NOT NULL,
            submitted_at timestamptz NOT NULL DEFAULT now(),
            trade_date date NOT NULL,
            confirm_idempotency_key text NULL,
            pending_reason text NULL,
            confirmed_at timestamptz NULL,
            confirmed_nav numeric(28, 8) NULL,
            confirmed_nav_date date NULL,
            confirmed_proceeds numeric(20, 2) NULL,
            confirmed_cost_released numeric(20, 2) NULL
        );

        CREATE TABLE IF NOT EXISTS redemption_order_idempotencies (
            idempotency_key text PRIMARY KEY,
            request_hash text NOT NULL,
            order_id uuid NOT NULL REFERENCES redemption_orders(id),
            fund_id uuid NOT NULL REFERENCES funds(id),
            created_at timestamptz NOT NULL DEFAULT now()
        );

        CREATE TABLE IF NOT EXISTS redemption_confirm_idempotencies (
            idempotency_key text PRIMARY KEY,
            request_hash text NOT NULL,
            order_id uuid NOT NULL REFERENCES redemption_orders(id),
            fund_id uuid NOT NULL REFERENCES funds(id),
            created_at timestamptz NOT NULL DEFAULT now()
        );

        ALTER TABLE fund_positions ADD COLUMN IF NOT EXISTS reserved_units numeric(28, 8) NOT NULL DEFAULT 0;

        CREATE TABLE IF NOT EXISTS fund_capital_deposits (
            id uuid PRIMARY KEY,
            fund_id uuid NOT NULL REFERENCES funds(id),
            amount numeric(20, 2) NOT NULL CHECK (amount > 0),
            note text NULL,
            is_synthetic boolean NOT NULL,
            created_at timestamptz NOT NULL DEFAULT now()
        );

        CREATE TABLE IF NOT EXISTS fund_capital_idempotencies (
            idempotency_key text PRIMARY KEY,
            request_hash text NOT NULL,
            deposit_id uuid NOT NULL REFERENCES fund_capital_deposits(id),
            fund_id uuid NOT NULL REFERENCES funds(id),
            created_at timestamptz NOT NULL DEFAULT now()
        );

        CREATE TABLE IF NOT EXISTS sip_plans (
            id uuid PRIMARY KEY,
            fund_id uuid NOT NULL REFERENCES funds(id),
            instrument_code text NOT NULL REFERENCES instruments(code),
            amount numeric(20, 2) NOT NULL CHECK (amount > 0),
            frequency text NOT NULL,
            status text NOT NULL,
            is_synthetic boolean NOT NULL,
            anchor_date date NOT NULL,
            next_trade_date date NOT NULL,
            created_at timestamptz NOT NULL DEFAULT now()
        );

        CREATE TABLE IF NOT EXISTS sip_plan_idempotencies (
            idempotency_key text PRIMARY KEY,
            request_hash text NOT NULL,
            plan_id uuid NOT NULL REFERENCES sip_plans(id),
            fund_id uuid NOT NULL REFERENCES funds(id),
            created_at timestamptz NOT NULL DEFAULT now()
        );

        CREATE TABLE IF NOT EXISTS sip_executions (
            plan_id uuid NOT NULL REFERENCES sip_plans(id),
            trade_date date NOT NULL,
            amount numeric(20, 2) NOT NULL,
            fee_amount numeric(20, 2) NOT NULL,
            status text NOT NULL,
            order_id uuid NULL,
            pending_reason text NULL,
            executed_at timestamptz NOT NULL DEFAULT now(),
            PRIMARY KEY (plan_id, trade_date)
        );

        CREATE TABLE IF NOT EXISTS rebalance_plans (
            id uuid PRIMARY KEY,
            fund_id uuid NOT NULL REFERENCES funds(id),
            status text NOT NULL,
            is_synthetic boolean NOT NULL,
            created_at timestamptz NOT NULL DEFAULT now()
        );

        CREATE TABLE IF NOT EXISTS rebalance_idempotencies (
            idempotency_key text PRIMARY KEY,
            request_hash text NOT NULL,
            plan_id uuid NOT NULL REFERENCES rebalance_plans(id),
            fund_id uuid NOT NULL REFERENCES funds(id),
            created_at timestamptz NOT NULL DEFAULT now()
        );

        CREATE TABLE IF NOT EXISTS rebalance_targets (
            plan_id uuid NOT NULL REFERENCES rebalance_plans(id),
            instrument_code text NOT NULL REFERENCES instruments(code),
            target_percent numeric(9, 2) NOT NULL CHECK (target_percent > 0 AND target_percent <= 100),
            PRIMARY KEY (plan_id, instrument_code)
        );

        CREATE TABLE IF NOT EXISTS dividend_records (
            id uuid PRIMARY KEY,
            fund_id uuid NOT NULL REFERENCES funds(id),
            instrument_code text NOT NULL REFERENCES instruments(code),
            nav_date date NOT NULL,
            dps numeric(28, 8) NOT NULL CHECK (dps > 0),
            mode text NOT NULL,
            status text NOT NULL,
            is_synthetic boolean NOT NULL,
            gross_cash numeric(20, 2) NULL,
            credited_units numeric(28, 8) NULL,
            credited_invested numeric(20, 2) NULL,
            order_id uuid NULL,
            pending_reason text NULL,
            created_at timestamptz NOT NULL DEFAULT now()
        );

        CREATE TABLE IF NOT EXISTS dividend_idempotencies (
            idempotency_key text PRIMARY KEY,
            request_hash text NOT NULL,
            record_id uuid NOT NULL REFERENCES dividend_records(id),
            fund_id uuid NOT NULL REFERENCES funds(id),
            created_at timestamptz NOT NULL DEFAULT now()
        );
        """

    let statusText status =
        match status with
        | FundStatus.Empty -> "empty"
        | FundStatus.Active -> "active"
        | FundStatus.ZeroUnits -> "zero_units"

    let cashText (value: decimal) = value.ToString("0.00", CultureInfo.InvariantCulture)

    let decimalText (value: decimal) = value.ToString("0.00000000", CultureInfo.InvariantCulture)

    let recordFromLedger (fund: LedgerFund) =
        {
            Id = fund.Id
            Name = fund.Name
            Currency = fund.Currency
            InitialCash = fund.InitialCash
            InitialUnitNav = fund.InitialUnitNav
            IsSynthetic = fund.IsSynthetic
            AvailableCash = fund.AvailableCash
            ReservedCash = fund.FrozenCash
            Status = statusText fund.Status
        }

    let recordFromReader (reader: DbDataReader) =
        {
            Id = reader.GetGuid(0)
            Name = reader.GetString(1)
            Currency = reader.GetString(2)
            InitialCash = reader.GetDecimal(3)
            InitialUnitNav = reader.GetDecimal(4)
            IsSynthetic = reader.GetBoolean(5)
            AvailableCash = reader.GetDecimal(6)
            ReservedCash = reader.GetDecimal(7)
            Status = reader.GetString(8)
        }

    let dateTimeOffsetFromReader (reader: DbDataReader) index =
        reader.GetFieldValue<DateTimeOffset>(index)

    let optionalDateTimeOffsetFromReader (reader: DbDataReader) index =
        if reader.IsDBNull(index) then None else Some(dateTimeOffsetFromReader reader index)

    let optionalDecimalFromReader (reader: DbDataReader) index =
        if reader.IsDBNull(index) then None else Some(reader.GetDecimal(index))

    let instrumentRecordFromReader (reader: DbDataReader) : MarketDataInstrumentRecord =
        {
            Code = reader.GetString(0)
            Name = reader.GetString(1)
            FundType = if reader.IsDBNull(2) then None else Some(reader.GetString(2))
            Source = reader.GetString(3)
            SourceRevision = reader.GetString(4)
            SourceCollectedAt = dateTimeOffsetFromReader reader 5
            SourcePayloadHash = reader.GetString(6)
            FirstSeenAt = dateTimeOffsetFromReader reader 7
            LastSeenAt = dateTimeOffsetFromReader reader 8
        }

    let navRecordFromReader (reader: DbDataReader) : MarketDataNavRecord =
        {
            Code = reader.GetString(0)
            NavDate = reader.GetFieldValue<DateOnly>(1)
            PublishedAt = optionalDateTimeOffsetFromReader reader 2
            Nav = reader.GetDecimal(3)
            AccumulatedNav = optionalDecimalFromReader reader 4
            DailyReturn = optionalDecimalFromReader reader 5
            Source = reader.GetString(6)
            SourceRevision = reader.GetString(7)
            SourceCollectedAt = dateTimeOffsetFromReader reader 8
            SourcePayloadHash = reader.GetString(9)
            FirstSeenAt = dateTimeOffsetFromReader reader 10
            LastSeenAt = dateTimeOffsetFromReader reader 11
        }

    let commandWithTransaction (connection: NpgsqlConnection) (transaction: NpgsqlTransaction option) sql =
        let command = connection.CreateCommand()
        command.CommandText <- sql

        match transaction with
        | Some value -> command.Transaction <- value
        | None -> ()

        command

    let addParameter (command: NpgsqlCommand) name dbType (value: obj) =
        let parameter = command.Parameters.Add(name, dbType)
        parameter.Value <- value
        parameter

    let optionalParameterValue value =
        match value with
        | Some actual -> box actual
        | None -> box DBNull.Value

    let findFund connection transaction fundId =
        use command =
            commandWithTransaction
                connection
                transaction
                """
                SELECT id, name, currency, initial_cash, initial_unit_nav,
                       is_synthetic, available_cash, reserved_cash, status
                FROM funds
                WHERE id = @fund_id
                """

        addParameter command "fund_id" NpgsqlDbType.Uuid (box fundId) |> ignore

        use reader = command.ExecuteReader()
        if reader.Read() then Some(recordFromReader reader) else None

    let findIdempotency connection transaction key =
        use command =
            commandWithTransaction
                connection
                transaction
                "SELECT request_hash, fund_id FROM fund_idempotencies WHERE idempotency_key = @idempotency_key"

        addParameter command "idempotency_key" NpgsqlDbType.Text (box key) |> ignore

        use reader = command.ExecuteReader()
        if reader.Read() then Some(reader.GetString(0), reader.GetGuid(1)) else None

    let insertFund connection transaction (fund: LedgerFund) =
        use command =
            commandWithTransaction
                connection
                transaction
                """
                INSERT INTO funds
                    (id, name, currency, initial_cash, initial_unit_nav,
                     is_synthetic, available_cash, reserved_cash, status)
                VALUES
                    (@id, @name, @currency, @initial_cash, @initial_unit_nav,
                     @is_synthetic, @available_cash, @reserved_cash, @status)
                """

        addParameter command "id" NpgsqlDbType.Uuid (box fund.Id) |> ignore
        addParameter command "name" NpgsqlDbType.Text (box fund.Name) |> ignore
        addParameter command "currency" NpgsqlDbType.Text (box fund.Currency) |> ignore
        addParameter command "initial_cash" NpgsqlDbType.Numeric (box fund.InitialCash) |> ignore
        addParameter command "initial_unit_nav" NpgsqlDbType.Numeric (box fund.InitialUnitNav) |> ignore
        addParameter command "is_synthetic" NpgsqlDbType.Boolean (box fund.IsSynthetic) |> ignore
        addParameter command "available_cash" NpgsqlDbType.Numeric (box fund.AvailableCash) |> ignore
        addParameter command "reserved_cash" NpgsqlDbType.Numeric (box fund.FrozenCash) |> ignore
        addParameter command "status" NpgsqlDbType.Text (box (statusText fund.Status)) |> ignore
        command.ExecuteNonQuery() |> ignore

    let insertIdempotency connection transaction key requestHash fundId =
        use command =
            commandWithTransaction
                connection
                transaction
                """
                INSERT INTO fund_idempotencies (idempotency_key, request_hash, fund_id)
                VALUES (@idempotency_key, @request_hash, @fund_id)
                """

        addParameter command "idempotency_key" NpgsqlDbType.Text (box key) |> ignore
        addParameter command "request_hash" NpgsqlDbType.Text (box requestHash) |> ignore
        addParameter command "fund_id" NpgsqlDbType.Uuid (box fundId) |> ignore
        command.ExecuteNonQuery() |> ignore

    let orderStatusText = "submitted"

    let readStringOption (reader: DbDataReader) ordinal =
        if reader.IsDBNull ordinal then None else Some(reader.GetString ordinal)

    let readDecimalOption (reader: DbDataReader) ordinal =
        if reader.IsDBNull ordinal then None else Some(reader.GetDecimal ordinal)

    let orderRecordFromReader (reader: DbDataReader) : SubscriptionOrderRecord =
        let confirmedQuote =
            if reader.IsDBNull(13) then
                None
            else
                Some
                    {
                        Nav = reader.GetDecimal(13)
                        NavDate = reader.GetFieldValue<DateOnly>(14)
                        Source = reader.GetString(15)
                        Revision = reader.GetString(16)
                        CollectedAt = reader.GetFieldValue<DateTimeOffset>(17)
                        PublishedAt =
                            if reader.IsDBNull(18) then
                                None
                            else
                                Some(reader.GetFieldValue<DateTimeOffset>(18))
                        PayloadHash =
                            if reader.IsDBNull(19) then
                                ""
                            else
                                reader.GetString(19)
                        FirstSeenAt =
                            if reader.IsDBNull(20) then
                                DateTimeOffset.UnixEpoch
                            else
                                reader.GetFieldValue<DateTimeOffset>(20)
                    }

        {
            Id = reader.GetGuid(0)
            FundId = reader.GetGuid(1)
            FundCode = reader.GetString(2)
            Amount = reader.GetDecimal(3)
            FeeAmount = reader.GetDecimal(4)
            ReservedTotal = reader.GetDecimal(5)
            Status = reader.GetString(6)
            IsSynthetic = reader.GetBoolean(7)
            SubmittedAt = reader.GetFieldValue<DateTimeOffset>(8)
            TradeDate = reader.GetFieldValue<DateOnly>(9)
            ConfirmIdempotencyKey = readStringOption reader 10
            PendingReason = readStringOption reader 11
            ConfirmedAt =
                if reader.IsDBNull(12) then
                    None
                else
                    Some(reader.GetFieldValue<DateTimeOffset>(12))
            ConfirmedUnits = readDecimalOption reader 21
            ConfirmedQuote = confirmedQuote
            ConfirmedInvestedCash = readDecimalOption reader 22
            ConfirmedResidualCash = readDecimalOption reader 23
        }

    let findOrder connection transaction orderId =
        use command =
            commandWithTransaction
                connection
                transaction
                """
                SELECT id, fund_id, fund_code, amount, fee_amount,
                       reserved_total, status, is_synthetic, submitted_at,
                       trade_date,
                       confirm_idempotency_key, pending_reason, confirmed_at,
                       confirmed_nav, confirmed_nav_date, confirmed_nav_source,
                       confirmed_nav_revision, confirmed_nav_collected_at, confirmed_nav_published_at,
                       confirmed_nav_payload_hash, confirmed_nav_first_seen_at,
                       confirmed_units, confirmed_invested_cash, confirmed_residual_cash
                FROM subscription_orders
                WHERE id = @order_id
                """

        addParameter command "order_id" NpgsqlDbType.Uuid (box orderId) |> ignore

        use reader = command.ExecuteReader()
        if reader.Read() then Some(orderRecordFromReader reader) else None

    let findConfirmIdempotency connection transaction key =
        use command =
            commandWithTransaction
                connection
                transaction
                "SELECT request_hash, fund_id, order_id FROM subscription_confirm_idempotencies WHERE idempotency_key = @idempotency_key"

        addParameter command "idempotency_key" NpgsqlDbType.Text (box key) |> ignore

        use reader = command.ExecuteReader()
        if reader.Read() then
            Some(reader.GetString(0), reader.GetGuid(1), reader.GetGuid(2))
        else
            None

    let findOrderIdempotency connection transaction key =
        use command =
            commandWithTransaction
                connection
                transaction
                "SELECT request_hash, fund_id, order_id FROM subscription_order_idempotencies WHERE idempotency_key = @idempotency_key"

        addParameter command "idempotency_key" NpgsqlDbType.Text (box key) |> ignore

        use reader = command.ExecuteReader()
        if reader.Read() then
            Some(reader.GetString(0), reader.GetGuid(1), reader.GetGuid(2))
        else
            None

    let instrumentExists connection transaction code =
        use command =
            commandWithTransaction
                connection
                transaction
                "SELECT 1 FROM instruments WHERE code = @code"

        addParameter command "code" NpgsqlDbType.Text (box code) |> ignore

        use reader = command.ExecuteReader()
        reader.Read()

    let lockFundForOrder connection transaction fundId =
        use command =
            commandWithTransaction
                connection
                transaction
                "SELECT is_synthetic FROM funds WHERE id = @fund_id FOR UPDATE"

        addParameter command "fund_id" NpgsqlDbType.Uuid (box fundId) |> ignore

        use reader = command.ExecuteReader()
        if reader.Read() then Some(reader.GetBoolean(0)) else None

    let insertSubscriptionOrder connection transaction (order: SubscriptionOrderRecord) =
        use command =
            commandWithTransaction
                connection
                transaction
                """
                INSERT INTO subscription_orders
                    (id, fund_id, fund_code, amount, fee_amount,
                     reserved_total, status, is_synthetic, trade_date)
                VALUES
                    (@id, @fund_id, @fund_code, @amount, @fee_amount,
                     @reserved_total, @status, @is_synthetic, @trade_date)
                RETURNING submitted_at
                """

        addParameter command "id" NpgsqlDbType.Uuid (box order.Id) |> ignore
        addParameter command "fund_id" NpgsqlDbType.Uuid (box order.FundId) |> ignore
        addParameter command "fund_code" NpgsqlDbType.Text (box order.FundCode) |> ignore
        addParameter command "amount" NpgsqlDbType.Numeric (box order.Amount) |> ignore
        addParameter command "fee_amount" NpgsqlDbType.Numeric (box order.FeeAmount) |> ignore
        addParameter command "reserved_total" NpgsqlDbType.Numeric (box order.ReservedTotal) |> ignore
        addParameter command "status" NpgsqlDbType.Text (box order.Status) |> ignore
        addParameter command "is_synthetic" NpgsqlDbType.Boolean (box order.IsSynthetic) |> ignore
        addParameter command "trade_date" NpgsqlDbType.Date (box order.TradeDate) |> ignore

        use reader = command.ExecuteReader()
        reader.Read() |> ignore
        reader.GetFieldValue<DateTimeOffset>(0)

    let insertOrderIdempotency connection transaction key requestHash orderId fundId =
        use command =
            commandWithTransaction
                connection
                transaction
                """
                INSERT INTO subscription_order_idempotencies (idempotency_key, request_hash, order_id, fund_id)
                VALUES (@idempotency_key, @request_hash, @order_id, @fund_id)
                """

        addParameter command "idempotency_key" NpgsqlDbType.Text (box key) |> ignore
        addParameter command "request_hash" NpgsqlDbType.Text (box requestHash) |> ignore
        addParameter command "order_id" NpgsqlDbType.Uuid (box orderId) |> ignore
        addParameter command "fund_id" NpgsqlDbType.Uuid (box fundId) |> ignore
        command.ExecuteNonQuery() |> ignore

    let upsertInstrument connection transaction (payload: MarketDataSearchPayload) payloadHash (instrument: MarketDataInstrument) =
        use command =
            commandWithTransaction
                connection
                transaction
                """
                INSERT INTO instruments
                    (code, name, fund_type, source, source_revision,
                     source_collected_at, source_payload_hash)
                VALUES
                    (@code, @name, @fund_type, @source, @source_revision,
                     @source_collected_at, @source_payload_hash)
                ON CONFLICT (code) DO UPDATE SET
                    name = EXCLUDED.name,
                    fund_type = EXCLUDED.fund_type,
                    source = EXCLUDED.source,
                    source_revision = EXCLUDED.source_revision,
                    source_collected_at = EXCLUDED.source_collected_at,
                    source_payload_hash = EXCLUDED.source_payload_hash,
                    last_seen_at = now()
                """

        addParameter command "code" NpgsqlDbType.Text (box instrument.Code) |> ignore
        addParameter command "name" NpgsqlDbType.Text (box instrument.Name) |> ignore

        addParameter
            command
            "fund_type"
            NpgsqlDbType.Text
            (optionalParameterValue instrument.FundType)
        |> ignore

        addParameter command "source" NpgsqlDbType.Text (box payload.Source) |> ignore
        addParameter command "source_revision" NpgsqlDbType.Text (box payload.SourceRevision) |> ignore
        addParameter command "source_collected_at" NpgsqlDbType.TimestampTz (box payload.CollectedAt) |> ignore
        addParameter command "source_payload_hash" NpgsqlDbType.Text (box payloadHash) |> ignore
        command.ExecuteNonQuery() |> ignore

    let upsertNavObservation connection transaction (payload: MarketDataNavPayload) payloadHash (observation: MarketDataObservation) =
        use command =
            commandWithTransaction
                connection
                transaction
                """
                INSERT INTO fund_nav_observations
                    (instrument_code, nav_date, published_at, nav, accumulated_nav,
                     daily_return, source, source_revision, source_collected_at,
                     source_payload_hash)
                VALUES
                    (@instrument_code, @nav_date, @published_at, @nav, @accumulated_nav,
                     @daily_return, @source, @source_revision, @source_collected_at,
                     @source_payload_hash)
                ON CONFLICT (instrument_code, nav_date) DO UPDATE SET
                    published_at = EXCLUDED.published_at,
                    nav = EXCLUDED.nav,
                    accumulated_nav = EXCLUDED.accumulated_nav,
                    daily_return = EXCLUDED.daily_return,
                    source = EXCLUDED.source,
                    source_revision = EXCLUDED.source_revision,
                    source_collected_at = EXCLUDED.source_collected_at,
                    source_payload_hash = EXCLUDED.source_payload_hash,
                    last_seen_at = now(),
                    first_seen_at =
                        CASE
                            WHEN fund_nav_observations.source_payload_hash = EXCLUDED.source_payload_hash
                                THEN fund_nav_observations.first_seen_at
                            ELSE now()
                        END
                """

        addParameter command "instrument_code" NpgsqlDbType.Text (box payload.Code) |> ignore
        addParameter command "nav_date" NpgsqlDbType.Date (box observation.NavDate) |> ignore

        addParameter
            command
            "published_at"
            NpgsqlDbType.TimestampTz
            (optionalParameterValue observation.PublishedAt)
        |> ignore

        addParameter command "nav" NpgsqlDbType.Numeric (box observation.Nav) |> ignore

        addParameter
            command
            "accumulated_nav"
            NpgsqlDbType.Numeric
            (optionalParameterValue observation.AccumulatedNav)
        |> ignore

        addParameter
            command
            "daily_return"
            NpgsqlDbType.Numeric
            (optionalParameterValue observation.DailyReturn)
        |> ignore

        addParameter command "source" NpgsqlDbType.Text (box payload.Source) |> ignore
        addParameter command "source_revision" NpgsqlDbType.Text (box payload.SourceRevision) |> ignore
        addParameter command "source_collected_at" NpgsqlDbType.TimestampTz (box payload.CollectedAt) |> ignore
        addParameter command "source_payload_hash" NpgsqlDbType.Text (box payloadHash) |> ignore
        command.ExecuteNonQuery() |> ignore

        use evidenceCommand =
            commandWithTransaction
                connection
                transaction
                """
                INSERT INTO fund_nav_observation_evidence
                    (instrument_code, nav_date, source_payload_hash, source_revision, source,
                     source_collected_at, published_at, nav)
                VALUES
                    (@instrument_code, @nav_date, @source_payload_hash, @source_revision, @source,
                     @source_collected_at, @published_at, @nav)
                ON CONFLICT (instrument_code, nav_date, source_payload_hash) DO NOTHING
                """

        addParameter evidenceCommand "instrument_code" NpgsqlDbType.Text (box payload.Code) |> ignore
        addParameter evidenceCommand "nav_date" NpgsqlDbType.Date (box observation.NavDate) |> ignore
        addParameter evidenceCommand "source_payload_hash" NpgsqlDbType.Text (box payloadHash) |> ignore
        addParameter evidenceCommand "source_revision" NpgsqlDbType.Text (box payload.SourceRevision) |> ignore
        addParameter evidenceCommand "source" NpgsqlDbType.Text (box payload.Source) |> ignore
        addParameter evidenceCommand "source_collected_at" NpgsqlDbType.TimestampTz (box payload.CollectedAt) |> ignore

        addParameter
            evidenceCommand
            "published_at"
            NpgsqlDbType.TimestampTz
            (optionalParameterValue observation.PublishedAt)
        |> ignore

        addParameter evidenceCommand "nav" NpgsqlDbType.Numeric (box observation.Nav) |> ignore
        evidenceCommand.ExecuteNonQuery() |> ignore

    let requestHash (command: FundCreateCommand) =
        let invariant = CultureInfo.InvariantCulture
        let encoded (value: string) = sprintf "%d:%s" value.Length value
        let name = if isNull command.Name then "" else command.Name
        let payload =
            String.concat
                "|"
                [
                    "fund-create"
                    encoded name
                    (encoded (command.InitialCash.ToString("G29", invariant)))
                    (encoded (command.InitialUnitNav.ToString("G29", invariant)))
                    (encoded (command.IsSynthetic.ToString()))
                ]

        Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(payload)))

    let validateStorageRange (command: FundCreateCommand) =
        if command.InitialCash > cashMaximum then
            Error "initial cash exceeds database precision"
        elif command.InitialUnitNav > unitNavMaximum then
            Error "initial unit NAV exceeds database precision"
        else
            Ok()

    let orderRequestHash (fundId: Guid) (command: SubscriptionOrderCommand) =
        let invariant = CultureInfo.InvariantCulture
        let encoded (value: string) = sprintf "%d:%s" value.Length value
        let fundCode = if isNull command.FundCode then "" else command.FundCode
        let payload =
            String.concat
                "|"
                [
                    "subscription-order"
                    encoded (fundId.ToString("D"))
                    encoded fundCode
                    (encoded (command.Amount.ToString("G29", invariant)))
                    (encoded (command.FeeAmount.ToString("G29", invariant)))
                ]

        Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(payload)))

    let validateOrderCommand (command: SubscriptionOrderCommand) =
        if String.IsNullOrWhiteSpace command.FundCode then
            Error "fund code cannot be empty"
        elif command.Amount <= 0m then
            Error "amount must be positive"
        elif command.FeeAmount < 0m then
            Error "fee amount cannot be negative"
        elif Decimal.Round(command.Amount, 2) <> command.Amount then
            Error "amount exceeds cash precision"
        elif Decimal.Round(command.FeeAmount, 2) <> command.FeeAmount then
            Error "fee amount exceeds cash precision"
        elif command.Amount > cashMaximum then
            Error "amount exceeds database precision"
        elif command.FeeAmount > cashMaximum then
            Error "fee amount exceeds database precision"
        elif command.Amount + command.FeeAmount > cashMaximum then
            Error "reserved total exceeds database precision"
        else
            Ok()

    let ledgerErrorMessage error =
        match error with
        | InvalidIdentifier label -> sprintf "%s is invalid" label
        | InvalidAmount label -> sprintf "%s is invalid" label
        | InvalidPrecision label -> sprintf "%s has invalid precision" label
        | InvalidState message -> message
        | FundAlreadyExists fundId -> sprintf "fund %O already exists" fundId
        | other -> sprintf "%A" other

    let redemptionRecordFromReader (reader: DbDataReader) : RedemptionOrderRecord =
        {
            Id = reader.GetGuid(0)
            FundId = reader.GetGuid(1)
            InstrumentCode = reader.GetString(2)
            Units = reader.GetDecimal(3)
            FeeAmount = reader.GetDecimal(4)
            Status = reader.GetString(5)
            IsSynthetic = reader.GetBoolean(6)
            SubmittedAt = reader.GetFieldValue<DateTimeOffset>(7)
            TradeDate = reader.GetFieldValue<DateOnly>(8)
            ConfirmIdempotencyKey = readStringOption reader 9
            PendingReason = readStringOption reader 10
            ConfirmedAt = optionalDateTimeOffsetFromReader reader 11
            ConfirmedNav = readDecimalOption reader 12
            ConfirmedNavDate =
                if reader.IsDBNull(13) then
                    None
                else
                    Some(reader.GetFieldValue<DateOnly>(13))
            ConfirmedProceeds = readDecimalOption reader 14
            ConfirmedCostReleased = readDecimalOption reader 15
        }

    let redemptionOrderColumns =
        """
        SELECT id, fund_id, instrument_code, units, fee_amount,
               status, is_synthetic, submitted_at, trade_date,
               confirm_idempotency_key, pending_reason, confirmed_at,
               confirmed_nav, confirmed_nav_date, confirmed_proceeds, confirmed_cost_released
        FROM redemption_orders
        """

    let findRedemptionOrder connection transaction orderId =
        use command =
            commandWithTransaction connection transaction (redemptionOrderColumns + " WHERE id = @order_id")

        addParameter command "order_id" NpgsqlDbType.Uuid (box orderId) |> ignore

        use reader = command.ExecuteReader()
        if reader.Read() then Some(redemptionRecordFromReader reader) else None

    let findRedemptionOrderIdempotency connection transaction key =
        use command =
            commandWithTransaction
                connection
                transaction
                "SELECT request_hash, fund_id, order_id FROM redemption_order_idempotencies WHERE idempotency_key = @idempotency_key"

        addParameter command "idempotency_key" NpgsqlDbType.Text (box key) |> ignore

        use reader = command.ExecuteReader()
        if reader.Read() then
            Some(reader.GetString(0), reader.GetGuid(1), reader.GetGuid(2))
        else
            None

    let findRedemptionConfirmIdempotency connection transaction key =
        use command =
            commandWithTransaction
                connection
                transaction
                "SELECT request_hash, fund_id, order_id FROM redemption_confirm_idempotencies WHERE idempotency_key = @idempotency_key"

        addParameter command "idempotency_key" NpgsqlDbType.Text (box key) |> ignore

        use reader = command.ExecuteReader()
        if reader.Read() then
            Some(reader.GetString(0), reader.GetGuid(1), reader.GetGuid(2))
        else
            None

    let insertRedemptionOrder connection transaction (order: RedemptionOrderRecord) =
        use command =
            commandWithTransaction
                connection
                transaction
                """
                INSERT INTO redemption_orders
                    (id, fund_id, instrument_code, units, fee_amount,
                     status, is_synthetic, trade_date)
                VALUES
                    (@id, @fund_id, @instrument_code, @units, @fee_amount,
                     @status, @is_synthetic, @trade_date)
                RETURNING submitted_at
                """

        addParameter command "id" NpgsqlDbType.Uuid (box order.Id) |> ignore
        addParameter command "fund_id" NpgsqlDbType.Uuid (box order.FundId) |> ignore
        addParameter command "instrument_code" NpgsqlDbType.Text (box order.InstrumentCode) |> ignore
        addParameter command "units" NpgsqlDbType.Numeric (box order.Units) |> ignore
        addParameter command "fee_amount" NpgsqlDbType.Numeric (box order.FeeAmount) |> ignore
        addParameter command "status" NpgsqlDbType.Text (box order.Status) |> ignore
        addParameter command "is_synthetic" NpgsqlDbType.Boolean (box order.IsSynthetic) |> ignore
        addParameter command "trade_date" NpgsqlDbType.Date (box order.TradeDate) |> ignore

        use reader = command.ExecuteReader()
        reader.Read() |> ignore
        reader.GetFieldValue<DateTimeOffset>(0)

    let insertRedemptionOrderIdempotency connection transaction key requestHash orderId fundId =
        use command =
            commandWithTransaction
                connection
                transaction
                """
                INSERT INTO redemption_order_idempotencies (idempotency_key, request_hash, order_id, fund_id)
                VALUES (@idempotency_key, @request_hash, @order_id, @fund_id)
                """

        addParameter command "idempotency_key" NpgsqlDbType.Text (box key) |> ignore
        addParameter command "request_hash" NpgsqlDbType.Text (box requestHash) |> ignore
        addParameter command "order_id" NpgsqlDbType.Uuid (box orderId) |> ignore
        addParameter command "fund_id" NpgsqlDbType.Uuid (box fundId) |> ignore
        command.ExecuteNonQuery() |> ignore

    let insertRedemptionConfirmIdempotency connection transaction key requestHash orderId fundId =
        use command =
            commandWithTransaction
                connection
                transaction
                """
                INSERT INTO redemption_confirm_idempotencies (idempotency_key, request_hash, order_id, fund_id)
                VALUES (@idempotency_key, @request_hash, @order_id, @fund_id)
                """

        addParameter command "idempotency_key" NpgsqlDbType.Text (box key) |> ignore
        addParameter command "request_hash" NpgsqlDbType.Text (box requestHash) |> ignore
        addParameter command "order_id" NpgsqlDbType.Uuid (box orderId) |> ignore
        addParameter command "fund_id" NpgsqlDbType.Uuid (box fundId) |> ignore
        command.ExecuteNonQuery() |> ignore

    let redemptionRequestHash (fundId: Guid) (command: RedemptionCommand) =
        let invariant = CultureInfo.InvariantCulture
        let encoded (value: string) = sprintf "%d:%s" value.Length value
        let code = if isNull command.InstrumentCode then "" else command.InstrumentCode
        let payload =
            String.concat
                "|"
                [
                    "redemption-order"
                    encoded (fundId.ToString("D"))
                    encoded code
                    (encoded (command.Units.ToString("G29", invariant)))
                    (encoded (command.FeeAmount.ToString("G29", invariant)))
                ]

        Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(payload)))

    let validateRedemptionCommand (command: RedemptionCommand) =
        if String.IsNullOrWhiteSpace command.InstrumentCode then
            Error "instrument code cannot be empty"
        elif command.Units <= 0m then
            Error "units must be positive"
        elif command.FeeAmount < 0m then
            Error "fee amount cannot be negative"
        elif Decimal.Round(command.Units, 8) <> command.Units then
            Error "units exceed supported precision"
        elif Decimal.Round(command.FeeAmount, 2) <> command.FeeAmount then
            Error "fee amount exceeds cash precision"
        elif command.Units > RedemptionPolicy.unitsMaximum then
            Error "units exceed database precision"
        elif command.FeeAmount > cashMaximum then
            Error "fee amount exceeds database precision"
        else
            Ok()

    let capitalDepositRecordFromReader (reader: DbDataReader) : CapitalDepositRecord =
        {
            Id = reader.GetGuid(0)
            FundId = reader.GetGuid(1)
            Amount = reader.GetDecimal(2)
            Note = readStringOption reader 3
            IsSynthetic = reader.GetBoolean(4)
            CreatedAt = reader.GetFieldValue<DateTimeOffset>(5)
        }

    let findCapitalDeposit connection transaction depositId =
        use command =
            commandWithTransaction
                connection
                transaction
                "SELECT id, fund_id, amount, note, is_synthetic, created_at FROM fund_capital_deposits WHERE id = @deposit_id"

        addParameter command "deposit_id" NpgsqlDbType.Uuid (box depositId) |> ignore

        use reader = command.ExecuteReader()
        if reader.Read() then Some(capitalDepositRecordFromReader reader) else None

    let findCapitalDepositIdempotency connection transaction key =
        use command =
            commandWithTransaction
                connection
                transaction
                "SELECT request_hash, fund_id, deposit_id FROM fund_capital_idempotencies WHERE idempotency_key = @idempotency_key"

        addParameter command "idempotency_key" NpgsqlDbType.Text (box key) |> ignore

        use reader = command.ExecuteReader()
        if reader.Read() then
            Some(reader.GetString(0), reader.GetGuid(1), reader.GetGuid(2))
        else
            None

    let insertCapitalDeposit connection transaction (deposit: CapitalDepositRecord) =
        use command =
            commandWithTransaction
                connection
                transaction
                """
                INSERT INTO fund_capital_deposits (id, fund_id, amount, note, is_synthetic)
                VALUES (@id, @fund_id, @amount, @note, @is_synthetic)
                RETURNING created_at
                """

        addParameter command "id" NpgsqlDbType.Uuid (box deposit.Id) |> ignore
        addParameter command "fund_id" NpgsqlDbType.Uuid (box deposit.FundId) |> ignore
        addParameter command "amount" NpgsqlDbType.Numeric (box deposit.Amount) |> ignore

        let noteParameter =
            match deposit.Note with
            | Some note -> box note
            | None -> box DBNull.Value

        addParameter command "note" NpgsqlDbType.Text noteParameter |> ignore
        addParameter command "is_synthetic" NpgsqlDbType.Boolean (box deposit.IsSynthetic) |> ignore

        use reader = command.ExecuteReader()
        reader.Read() |> ignore
        reader.GetFieldValue<DateTimeOffset>(0)

    let insertCapitalDepositIdempotency connection transaction key requestHash depositId fundId =
        use command =
            commandWithTransaction
                connection
                transaction
                """
                INSERT INTO fund_capital_idempotencies (idempotency_key, request_hash, deposit_id, fund_id)
                VALUES (@idempotency_key, @request_hash, @deposit_id, @fund_id)
                """

        addParameter command "idempotency_key" NpgsqlDbType.Text (box key) |> ignore
        addParameter command "request_hash" NpgsqlDbType.Text (box requestHash) |> ignore
        addParameter command "deposit_id" NpgsqlDbType.Uuid (box depositId) |> ignore
        addParameter command "fund_id" NpgsqlDbType.Uuid (box fundId) |> ignore
        command.ExecuteNonQuery() |> ignore

    let capitalDepositRequestHash (fundId: Guid) (command: CapitalDepositCommand) =
        let invariant = CultureInfo.InvariantCulture
        let encoded (value: string) = sprintf "%d:%s" value.Length value
        let note = if command.Note.IsNone then "" else command.Note.Value

        let payload =
            String.concat
                "|"
                [
                    "capital-deposit"
                    encoded (fundId.ToString("D"))
                    (encoded (command.Amount.ToString("G29", invariant)))
                    (encoded note)
                ]

        Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(payload)))

    let sipPlanRecordFromReader (reader: DbDataReader) : SipPlanRecord =
        {
            Id = reader.GetGuid(0)
            FundId = reader.GetGuid(1)
            InstrumentCode = reader.GetString(2)
            Amount = reader.GetDecimal(3)
            Frequency =
                match SipPolicy.parseFrequency (reader.GetString(4)) with
                | Some frequency -> frequency
                | None -> failwith "sip plan frequency is invalid"
            Status = reader.GetString(5)
            IsSynthetic = reader.GetBoolean(6)
            AnchorDate = reader.GetFieldValue<DateOnly>(7)
            NextTradeDate = reader.GetFieldValue<DateOnly>(8)
            CreatedAt = reader.GetFieldValue<DateTimeOffset>(9)
            LastExecutionStatus = readStringOption reader 10
            LastExecutionDate =
                if reader.IsDBNull(11) then None else Some(reader.GetFieldValue<DateOnly>(11))
        }

    let findSipPlan connection transaction planId =
        use command =
            commandWithTransaction
                connection
                transaction
                """
                SELECT p.id, p.fund_id, p.instrument_code, p.amount, p.frequency, p.status, p.is_synthetic,
                       p.anchor_date, p.next_trade_date, p.created_at,
                       e.status, e.trade_date
                FROM sip_plans p
                LEFT JOIN LATERAL (
                    SELECT status, trade_date FROM sip_executions
                    WHERE plan_id = p.id ORDER BY executed_at DESC, trade_date DESC LIMIT 1
                ) e ON true
                WHERE p.id = @plan_id
                """

        addParameter command "plan_id" NpgsqlDbType.Uuid (box planId) |> ignore

        use reader = command.ExecuteReader()
        if reader.Read() then Some(sipPlanRecordFromReader reader) else None

    let findSipPlanIdempotency connection transaction key =
        use command =
            commandWithTransaction
                connection
                transaction
                "SELECT request_hash, fund_id, plan_id FROM sip_plan_idempotencies WHERE idempotency_key = @idempotency_key"

        addParameter command "idempotency_key" NpgsqlDbType.Text (box key) |> ignore

        use reader = command.ExecuteReader()
        if reader.Read() then
            Some(reader.GetString(0), reader.GetGuid(1), reader.GetGuid(2))
        else
            None

    let insertSipPlan connection transaction (plan: SipPlanRecord) =
        use command =
            commandWithTransaction
                connection
                transaction
                """
                INSERT INTO sip_plans (id, fund_id, instrument_code, amount, frequency, status, is_synthetic, anchor_date, next_trade_date)
                VALUES (@id, @fund_id, @instrument_code, @amount, @frequency, @status, @is_synthetic, @anchor_date, @next_trade_date)
                RETURNING created_at
                """

        addParameter command "id" NpgsqlDbType.Uuid (box plan.Id) |> ignore
        addParameter command "fund_id" NpgsqlDbType.Uuid (box plan.FundId) |> ignore
        addParameter command "instrument_code" NpgsqlDbType.Text (box plan.InstrumentCode) |> ignore
        addParameter command "amount" NpgsqlDbType.Numeric (box plan.Amount) |> ignore
        addParameter command "frequency" NpgsqlDbType.Text (box (SipPolicy.frequencyText plan.Frequency)) |> ignore
        addParameter command "status" NpgsqlDbType.Text (box plan.Status) |> ignore
        addParameter command "is_synthetic" NpgsqlDbType.Boolean (box plan.IsSynthetic) |> ignore
        addParameter command "anchor_date" NpgsqlDbType.Date (box plan.AnchorDate) |> ignore
        addParameter command "next_trade_date" NpgsqlDbType.Date (box plan.NextTradeDate) |> ignore

        use reader = command.ExecuteReader()
        reader.Read() |> ignore
        reader.GetFieldValue<DateTimeOffset>(0)

    let insertSipPlanIdempotency connection transaction key requestHash planId fundId =
        use command =
            commandWithTransaction
                connection
                transaction
                """
                INSERT INTO sip_plan_idempotencies (idempotency_key, request_hash, plan_id, fund_id)
                VALUES (@idempotency_key, @request_hash, @plan_id, @fund_id)
                """

        addParameter command "idempotency_key" NpgsqlDbType.Text (box key) |> ignore
        addParameter command "request_hash" NpgsqlDbType.Text (box requestHash) |> ignore
        addParameter command "plan_id" NpgsqlDbType.Uuid (box planId) |> ignore
        addParameter command "fund_id" NpgsqlDbType.Uuid (box fundId) |> ignore
        command.ExecuteNonQuery() |> ignore

    let sipPlanRequestHash (fundId: Guid) (command: SipPlanCommand) =
        let invariant = CultureInfo.InvariantCulture
        let encoded (value: string) = sprintf "%d:%s" value.Length value
        let code = if isNull command.InstrumentCode then "" else command.InstrumentCode

        let payload =
            String.concat
                "|"
                [
                    "sip-plan"
                    encoded (fundId.ToString("D"))
                    encoded code
                    (encoded (command.Amount.ToString("G29", invariant)))
                    (encoded (SipPolicy.frequencyText command.Frequency))
                ]

        Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(payload)))

    let rebalancePlanRecordFromReader (reader: DbDataReader) : RebalancePlanRecord =
        {
            Id = reader.GetGuid(0)
            FundId = reader.GetGuid(1)
            Targets = []
            Status = reader.GetString(2)
            IsSynthetic = reader.GetBoolean(3)
            CreatedAt = reader.GetFieldValue<DateTimeOffset>(4)
        }

    let rebalanceTargetsFromReader (reader: DbDataReader) : RebalanceTarget list =
        let targets = ResizeArray<RebalanceTarget>()

        while reader.Read() do
            targets.Add(
                {
                    InstrumentCode = reader.GetString(0)
                    TargetPercent = reader.GetDecimal(1)
                }
            )

        targets |> Seq.toList

    let rebalancePlanWithTargets connection transaction (plan: RebalancePlanRecord) =
        use targetsCommand =
            commandWithTransaction
                connection
                transaction
                "SELECT instrument_code, target_percent FROM rebalance_targets WHERE plan_id = @plan_id ORDER BY instrument_code"

        addParameter targetsCommand "plan_id" NpgsqlDbType.Uuid (box plan.Id) |> ignore

        use reader = targetsCommand.ExecuteReader()
        let targets = rebalanceTargetsFromReader reader
        { plan with Targets = targets }

    let findRebalancePlan connection transaction planId =
        use command =
            commandWithTransaction
                connection
                transaction
                "SELECT id, fund_id, status, is_synthetic, created_at FROM rebalance_plans WHERE id = @plan_id"

        addParameter command "plan_id" NpgsqlDbType.Uuid (box planId) |> ignore

        use reader = command.ExecuteReader()

        if reader.Read() then
            let plan = rebalancePlanRecordFromReader reader
            reader.Close()
            Some(rebalancePlanWithTargets connection transaction plan)
        else
            None

    let findRebalanceIdempotency connection transaction key =
        use command =
            commandWithTransaction
                connection
                transaction
                "SELECT request_hash, fund_id, plan_id FROM rebalance_idempotencies WHERE idempotency_key = @idempotency_key"

        addParameter command "idempotency_key" NpgsqlDbType.Text (box key) |> ignore

        use reader = command.ExecuteReader()
        if reader.Read() then
            Some(reader.GetString(0), reader.GetGuid(1), reader.GetGuid(2))
        else
            None

    let insertRebalancePlan connection transaction (plan: RebalancePlanRecord) =
        use planCommand =
            commandWithTransaction
                connection
                transaction
                """
                INSERT INTO rebalance_plans (id, fund_id, status, is_synthetic)
                VALUES (@id, @fund_id, @status, @is_synthetic)
                RETURNING created_at
                """

        addParameter planCommand "id" NpgsqlDbType.Uuid (box plan.Id) |> ignore
        addParameter planCommand "fund_id" NpgsqlDbType.Uuid (box plan.FundId) |> ignore
        addParameter planCommand "status" NpgsqlDbType.Text (box plan.Status) |> ignore
        addParameter planCommand "is_synthetic" NpgsqlDbType.Boolean (box plan.IsSynthetic) |> ignore

        use reader = planCommand.ExecuteReader()
        reader.Read() |> ignore
        let createdAt = reader.GetFieldValue<DateTimeOffset>(0)
        reader.Close()

        for target in plan.Targets do
            use targetCommand =
                commandWithTransaction
                    connection
                    transaction
                    """
                    INSERT INTO rebalance_targets (plan_id, instrument_code, target_percent)
                    VALUES (@plan_id, @instrument_code, @target_percent)
                    """

            addParameter targetCommand "plan_id" NpgsqlDbType.Uuid (box plan.Id) |> ignore
            addParameter targetCommand "instrument_code" NpgsqlDbType.Text (box target.InstrumentCode) |> ignore
            addParameter targetCommand "target_percent" NpgsqlDbType.Numeric (box target.TargetPercent) |> ignore
            targetCommand.ExecuteNonQuery() |> ignore

        createdAt

    let insertRebalanceIdempotency connection transaction key requestHash planId fundId =
        use command =
            commandWithTransaction
                connection
                transaction
                """
                INSERT INTO rebalance_idempotencies (idempotency_key, request_hash, plan_id, fund_id)
                VALUES (@idempotency_key, @request_hash, @plan_id, @fund_id)
                """

        addParameter command "idempotency_key" NpgsqlDbType.Text (box key) |> ignore
        addParameter command "request_hash" NpgsqlDbType.Text (box requestHash) |> ignore
        addParameter command "plan_id" NpgsqlDbType.Uuid (box planId) |> ignore
        addParameter command "fund_id" NpgsqlDbType.Uuid (box fundId) |> ignore
        command.ExecuteNonQuery() |> ignore

    let rebalanceRequestHash (fundId: Guid) (command: RebalancePlanCommand) =
        let invariant = CultureInfo.InvariantCulture
        let encoded (value: string) = sprintf "%d:%s" value.Length value

        let payload =
            String.concat
                "|"
                ([ "rebalance-plan"; encoded (fundId.ToString("D")) ]
                 @ (command.Targets
                    |> List.sortBy (fun target -> target.InstrumentCode)
                    |> List.collect (fun target ->
                        [
                            encoded target.InstrumentCode
                            encoded (target.TargetPercent.ToString("G29", invariant))
                        ])))

        Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(payload)))

    let validateRebalanceCommand (command: RebalancePlanCommand) =
        match RebalancePolicy.validateTargets command.Targets with
        | Error message -> Error message
        | Ok() -> Ok()
    let dividendRecordFromReader (reader: DbDataReader) : DividendRecord =
        {
            Id = reader.GetGuid(0)
            FundId = reader.GetGuid(1)
            InstrumentCode = reader.GetString(2)
            NavDate = reader.GetFieldValue<DateOnly>(3)
            Dps = reader.GetDecimal(4)
            Mode =
                match DividendPolicy.parseMode (reader.GetString(5)) with
                | Some mode -> mode
                | None -> failwith "dividend mode is invalid"
            Status = reader.GetString(6)
            IsSynthetic = reader.GetBoolean(7)
            GrossCash = readDecimalOption reader 8
            CreditedUnits = readDecimalOption reader 9
            CreditedInvested = readDecimalOption reader 10
            OrderId = if reader.IsDBNull(11) then None else Some(reader.GetGuid(11))
            PendingReason = readStringOption reader 12
            CreatedAt = reader.GetFieldValue<DateTimeOffset>(13)
        }

    let findDividendRecord connection transaction recordId =
        use command =
            commandWithTransaction
                connection
                transaction
                """
                SELECT id, fund_id, instrument_code, nav_date, dps, mode, status, is_synthetic,
                       gross_cash, credited_units, credited_invested, order_id, pending_reason, created_at
                FROM dividend_records WHERE id = @record_id
                """

        addParameter command "record_id" NpgsqlDbType.Uuid (box recordId) |> ignore

        use reader = command.ExecuteReader()
        if reader.Read() then Some(dividendRecordFromReader reader) else None

    let findDividendIdempotency connection transaction key =
        use command =
            commandWithTransaction
                connection
                transaction
                "SELECT request_hash, fund_id, record_id FROM dividend_idempotencies WHERE idempotency_key = @idempotency_key"

        addParameter command "idempotency_key" NpgsqlDbType.Text (box key) |> ignore

        use reader = command.ExecuteReader()
        if reader.Read() then
            Some(reader.GetString(0), reader.GetGuid(1), reader.GetGuid(2))
        else
            None

    let insertDividendRecord connection transaction (record: DividendRecord) =
        use command =
            commandWithTransaction
                connection
                transaction
                """
                INSERT INTO dividend_records
                    (id, fund_id, instrument_code, nav_date, dps, mode, status, is_synthetic, gross_cash)
                VALUES (@id, @fund_id, @instrument_code, @nav_date, @dps, @mode, @status, @is_synthetic, @gross_cash)
                RETURNING created_at
                """

        addParameter command "id" NpgsqlDbType.Uuid (box record.Id) |> ignore
        addParameter command "fund_id" NpgsqlDbType.Uuid (box record.FundId) |> ignore
        addParameter command "instrument_code" NpgsqlDbType.Text (box record.InstrumentCode) |> ignore
        addParameter command "nav_date" NpgsqlDbType.Date (box record.NavDate) |> ignore
        addParameter command "dps" NpgsqlDbType.Numeric (box record.Dps) |> ignore
        addParameter command "mode" NpgsqlDbType.Text (box (DividendPolicy.modeText record.Mode)) |> ignore
        addParameter command "status" NpgsqlDbType.Text (box record.Status) |> ignore
        addParameter command "is_synthetic" NpgsqlDbType.Boolean (box record.IsSynthetic) |> ignore

        let grossParameter =
            match record.GrossCash with
            | Some gross -> box gross
            | None -> box DBNull.Value

        addParameter command "gross_cash" NpgsqlDbType.Numeric grossParameter |> ignore

        use reader = command.ExecuteReader()
        reader.Read() |> ignore
        reader.GetFieldValue<DateTimeOffset>(0)

    let insertDividendIdempotency connection transaction key requestHash recordId fundId =
        use command =
            commandWithTransaction
                connection
                transaction
                """
                INSERT INTO dividend_idempotencies (idempotency_key, request_hash, record_id, fund_id)
                VALUES (@idempotency_key, @request_hash, @record_id, @fund_id)
                """

        addParameter command "idempotency_key" NpgsqlDbType.Text (box key) |> ignore
        addParameter command "request_hash" NpgsqlDbType.Text (box requestHash) |> ignore
        addParameter command "record_id" NpgsqlDbType.Uuid (box recordId) |> ignore
        addParameter command "fund_id" NpgsqlDbType.Uuid (box fundId) |> ignore
        command.ExecuteNonQuery() |> ignore

    let finishDividendRecord connection transaction (recordId: Guid) (status: string) (pendingReason: string option) =
        use command =
            commandWithTransaction
                connection
                transaction
                "UPDATE dividend_records SET status = @status, pending_reason = @reason WHERE id = @record_id"

        addParameter command "status" NpgsqlDbType.Text (box status) |> ignore

        let reasonParameter =
            match pendingReason with
            | Some reason -> box reason
            | None -> box DBNull.Value

        addParameter command "reason" NpgsqlDbType.Text reasonParameter |> ignore
        addParameter command "record_id" NpgsqlDbType.Uuid (box recordId) |> ignore
        command.ExecuteNonQuery() |> ignore

    let dividendRequestHash (fundId: Guid) (command: DividendCommand) =
        let invariant = CultureInfo.InvariantCulture
        let encoded (value: string) = sprintf "%d:%s" value.Length value

        let payload =
            String.concat
                "|"
                [
                    "dividend"
                    encoded (fundId.ToString("D"))
                    encoded command.InstrumentCode
                    encoded (command.NavDate.ToString("yyyy-MM-dd"))
                    (encoded (command.Dps.ToString("G29", invariant)))
                    (encoded (DividendPolicy.modeText command.Mode))
                ]

        Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(payload)))

    let dividendSchemeKey (fundId: Guid) (command: DividendCommand) =
        DividendPolicy.schemeKey fundId command.InstrumentCode command.NavDate command.Mode

    let validateDividendCommand (today: DateOnly) (command: DividendCommand) =
        if String.IsNullOrWhiteSpace command.InstrumentCode then
            Error "instrument code cannot be empty"
        elif command.Dps <= 0m then
            Error "dividend per unit must be positive"
        else
            match DividendPolicy.validateDps command.Dps, DividendPolicy.validateNavDate command.NavDate today with
            | Ok(), Ok() -> Ok()
            | Error message, _
            | _, Error message -> Error message
    member _.EnsureSchema() =
        use connection = new NpgsqlConnection(connectionString)
        connection.Open()
        use command = connection.CreateCommand()
        command.CommandText <- schema
        command.ExecuteNonQuery() |> ignore

    member _.GetFund(fundId: Guid) =
        use connection = new NpgsqlConnection(connectionString)
        connection.Open()
        findFund connection None fundId

    member _.UpsertInstruments(payload: MarketDataSearchPayload, payloadHash: string) =
        use connection = new NpgsqlConnection(connectionString)
        connection.Open()
        use transaction = connection.BeginTransaction(IsolationLevel.ReadCommitted)

        try
            for instrument in payload.Instruments do
                upsertInstrument connection (Some transaction) payload payloadHash instrument

            transaction.Commit()
        with error ->
            try
                transaction.Rollback()
            with _ ->
                ()

            raise error

    member _.GetInstrument(code: string) =
        use connection = new NpgsqlConnection(connectionString)
        connection.Open()

        use command =
            commandWithTransaction
                connection
                None
                """
                SELECT code, name, fund_type, source, source_revision,
                       source_collected_at, source_payload_hash,
                       first_seen_at, last_seen_at
                FROM instruments
                WHERE code = @code
                """

        addParameter command "code" NpgsqlDbType.Text (box code) |> ignore
        use reader = command.ExecuteReader()
        if reader.Read() then Some(instrumentRecordFromReader reader) else None

    member _.UpsertNavObservations(payload: MarketDataNavPayload, payloadHash: string) =
        use connection = new NpgsqlConnection(connectionString)
        connection.Open()
        use transaction = connection.BeginTransaction(IsolationLevel.ReadCommitted)

        try
            for observation in payload.Observations do
                upsertNavObservation connection (Some transaction) payload payloadHash observation

            transaction.Commit()
        with error ->
            try
                transaction.Rollback()
            with _ ->
                ()

            raise error

    member _.GetNav(code: string, fromDate: DateOnly option, toDate: DateOnly option) =
        use connection = new NpgsqlConnection(connectionString)
        connection.Open()

        let conditions = ResizeArray<string>()
        conditions.Add("instrument_code = @instrument_code")

        if fromDate.IsSome then
            conditions.Add("nav_date >= @from_date")

        if toDate.IsSome then
            conditions.Add("nav_date <= @to_date")

        use command =
            commandWithTransaction
                connection
                None
                (sprintf
                    """
                    SELECT instrument_code, nav_date, published_at, nav, accumulated_nav,
                           daily_return, source, source_revision, source_collected_at,
                           source_payload_hash, first_seen_at, last_seen_at
                    FROM fund_nav_observations
                    WHERE %s
                    ORDER BY nav_date ASC
                    """
                    (String.concat " AND " conditions))

        addParameter command "instrument_code" NpgsqlDbType.Text (box code) |> ignore

        match fromDate with
        | Some value -> addParameter command "from_date" NpgsqlDbType.Date (box value) |> ignore
        | None -> ()

        match toDate with
        | Some value -> addParameter command "to_date" NpgsqlDbType.Date (box value) |> ignore
        | None -> ()

        use reader = command.ExecuteReader()
        let records = ResizeArray<MarketDataNavRecord>()

        while reader.Read() do
            records.Add(navRecordFromReader reader)

        records |> Seq.toList

    member _.CreateFund(idempotencyKey: string, command: FundCreateCommand) =
        if String.IsNullOrWhiteSpace idempotencyKey then
            FundWriteResult.Invalid "idempotency key cannot be empty"
        else
            match validateStorageRange command with
            | Error message -> FundWriteResult.Invalid message
            | Ok() ->
                let fingerprint = requestHash command
                use connection = new NpgsqlConnection(connectionString)
                connection.Open()
                use transaction = connection.BeginTransaction(IsolationLevel.ReadCommitted)

                try
                    use lockCommand =
                        commandWithTransaction
                            connection
                            (Some transaction)
                            "SELECT pg_advisory_xact_lock(hashtext(@lock_key))"

                    addParameter lockCommand "lock_key" NpgsqlDbType.Text (box idempotencyKey) |> ignore
                    lockCommand.ExecuteNonQuery() |> ignore

                    match findIdempotency connection (Some transaction) idempotencyKey with
                    | Some(existingHash, fundId) when existingHash = fingerprint ->
                        match findFund connection (Some transaction) fundId with
                        | Some fund ->
                            transaction.Commit()
                            FundWriteResult.Replayed fund
                        | None ->
                            transaction.Rollback()
                            FundWriteResult.Invalid "idempotency record references a missing fund"
                    | Some _ ->
                        transaction.Rollback()
                        FundWriteResult.IdempotencyConflict
                    | None ->
                        let fundId = Guid.NewGuid()

                        match Ledger.initializeFund fundId command.Name command.InitialCash command.InitialUnitNav command.IsSynthetic Ledger.empty with
                        | Error error ->
                            transaction.Rollback()
                            FundWriteResult.Invalid(ledgerErrorMessage error)
                        | Ok state ->
                            match Ledger.getFund fundId state with
                            | Error error ->
                                transaction.Rollback()
                                FundWriteResult.Invalid(ledgerErrorMessage error)
                            | Ok fund ->
                                insertFund connection (Some transaction) fund
                                insertIdempotency connection (Some transaction) idempotencyKey fingerprint fundId
                                transaction.Commit()
                                FundWriteResult.Created(recordFromLedger fund)
                with error ->
                    try
                        transaction.Rollback()
                    with _ ->
                        ()

                    raise error

    member _.CreateSubscriptionOrder(idempotencyKey: string, fundId: Guid, command: SubscriptionOrderCommand, ?tradeDateOverride: DateOnly) : SubscriptionOrderWriteResult =
        if String.IsNullOrWhiteSpace idempotencyKey then
            OrderInvalid "idempotency key cannot be empty"
        else
            match validateOrderCommand command with
            | Error message -> OrderInvalid message
            | Ok() ->
                let fingerprint = orderRequestHash fundId command
                let reservedTotal = command.Amount + command.FeeAmount
                use connection = new NpgsqlConnection(connectionString)
                connection.Open()
                use transaction = connection.BeginTransaction(IsolationLevel.ReadCommitted)

                try
                    use lockCommand =
                        commandWithTransaction
                            connection
                            (Some transaction)
                            "SELECT pg_advisory_xact_lock(hashtext(@lock_key))"

                    addParameter lockCommand "lock_key" NpgsqlDbType.Text (box idempotencyKey) |> ignore
                    lockCommand.ExecuteNonQuery() |> ignore

                    match findOrderIdempotency connection (Some transaction) idempotencyKey with
                    | Some(existingHash, existingFundId, orderId)
                        when existingHash = fingerprint && existingFundId = fundId ->
                        match findOrder connection (Some transaction) orderId with
                        | Some order ->
                            transaction.Commit()
                            OrderReplayed order
                        | None ->
                            transaction.Rollback()
                            OrderInvalid "idempotency record references a missing order"
                    | Some _ ->
                        transaction.Rollback()
                        OrderIdempotencyConflict
                    | None ->
                        match lockFundForOrder connection (Some transaction) fundId with
                        | None ->
                            transaction.Rollback()
                            OrderFundNotFound
                        | Some isSynthetic ->
                            if instrumentExists connection (Some transaction) command.FundCode then
                                use cashCommand =
                                    commandWithTransaction
                                        connection
                                        (Some transaction)
                                        """
                                        UPDATE funds
                                        SET available_cash = available_cash - @reserved_total,
                                            reserved_cash = reserved_cash + @reserved_total
                                        WHERE id = @fund_id AND available_cash >= @reserved_total
                                        """

                                addParameter cashCommand "reserved_total" NpgsqlDbType.Numeric (box reservedTotal) |> ignore
                                addParameter cashCommand "fund_id" NpgsqlDbType.Uuid (box fundId) |> ignore

                                if cashCommand.ExecuteNonQuery() = 0 then
                                    transaction.Rollback()
                                    OrderInsufficientFunds
                                else
                                    let submittedAt = DateTimeOffset.UtcNow
                                    let tradeDate =
                                        tradeDateOverride
                                        |> Option.defaultWith (fun () -> ConfirmationPolicy.tradeDateFor submittedAt)

                                    let order: SubscriptionOrderRecord =
                                        {
                                            Id = Guid.NewGuid()
                                            FundId = fundId
                                            FundCode = command.FundCode
                                            Amount = command.Amount
                                            FeeAmount = command.FeeAmount
                                            ReservedTotal = reservedTotal
                                            Status = orderStatusText
                                            SubmittedAt = submittedAt
                                            IsSynthetic = isSynthetic
                                            TradeDate = tradeDate
                                            ConfirmIdempotencyKey = None
                                            PendingReason = None
                                            ConfirmedAt = None
                                            ConfirmedQuote = None
                                            ConfirmedUnits = None
                                            ConfirmedInvestedCash = None
                                            ConfirmedResidualCash = None
                                        }

                                    let submittedAt = insertSubscriptionOrder connection (Some transaction) order
                                    insertOrderIdempotency connection (Some transaction) idempotencyKey fingerprint order.Id fundId
                                    transaction.Commit()
                                    OrderCreated { order with SubmittedAt = submittedAt }
                            else
                                transaction.Rollback()
                                OrderInstrumentNotFound
                with error ->
                    try
                        transaction.Rollback()
                    with _ ->
                        ()

                    raise error

    member _.GetSubscriptionOrders(fundId: Guid) =
        use connection = new NpgsqlConnection(connectionString)
        connection.Open()

        use command =
            commandWithTransaction
                connection
                None
                """
                SELECT id, fund_id, fund_code, amount, fee_amount,
                       reserved_total, status, is_synthetic, submitted_at,
                       trade_date,
                       confirm_idempotency_key, pending_reason, confirmed_at,
                       confirmed_nav, confirmed_nav_date, confirmed_nav_source,
                       confirmed_nav_revision, confirmed_nav_collected_at, confirmed_nav_published_at,
                       confirmed_nav_payload_hash, confirmed_nav_first_seen_at,
                       confirmed_units, confirmed_invested_cash, confirmed_residual_cash
                FROM subscription_orders
                WHERE fund_id = @fund_id
                ORDER BY submitted_at DESC, id
                """

        addParameter command "fund_id" NpgsqlDbType.Uuid (box fundId) |> ignore

        use reader = command.ExecuteReader()
        let records = ResizeArray<SubscriptionOrderRecord>()

        while reader.Read() do
            records.Add(orderRecordFromReader reader)

        records |> Seq.toList

    member _.CreateSipPlan(idempotencyKey: string, fundId: Guid, command: SipPlanCommand, ?anchorOverride: DateOnly) : SipPlanWriteResult =
        if String.IsNullOrWhiteSpace idempotencyKey then
            SipPlanWriteResult.SipPlanInvalid "idempotency key cannot be empty"
        else
            match SipPolicy.validateAmount command.Amount with
            | Error message -> SipPlanWriteResult.SipPlanInvalid message
            | Ok() ->
                let fingerprint = sipPlanRequestHash fundId command
                use connection = new NpgsqlConnection(connectionString)
                connection.Open()
                use transaction = connection.BeginTransaction(IsolationLevel.ReadCommitted)

                try
                    use lockCommand =
                        commandWithTransaction
                            connection
                            (Some transaction)
                            "SELECT pg_advisory_xact_lock(hashtext(@lock_key))"

                    addParameter lockCommand "lock_key" NpgsqlDbType.Text (box idempotencyKey) |> ignore
                    lockCommand.ExecuteNonQuery() |> ignore

                    match findSipPlanIdempotency connection (Some transaction) idempotencyKey with
                    | Some(existingHash, existingFundId, planId)
                        when existingHash = fingerprint && existingFundId = fundId ->
                        match findSipPlan connection (Some transaction) planId with
                        | Some plan ->
                            transaction.Commit()
                            SipPlanWriteResult.SipPlanReplayed plan
                        | None ->
                            transaction.Rollback()
                            SipPlanWriteResult.SipPlanInvalid "idempotency record references a missing plan"
                    | Some _ ->
                        transaction.Rollback()
                        SipPlanWriteResult.SipPlanIdempotencyConflict
                    | None ->
                        match lockFundForOrder connection (Some transaction) fundId with
                        | None ->
                            transaction.Rollback()
                            SipPlanWriteResult.SipPlanFundNotFound
                        | Some isSynthetic ->
                            if instrumentExists connection (Some transaction) command.InstrumentCode then
                                let anchorDate =
                                    anchorOverride
                                    |> Option.defaultWith (fun () -> ConfirmationPolicy.tradeDateFor DateTimeOffset.UtcNow)

                                let plan: SipPlanRecord =
                                    {
                                        Id = Guid.NewGuid()
                                        FundId = fundId
                                        InstrumentCode = command.InstrumentCode
                                        Amount = command.Amount
                                        Frequency = command.Frequency
                                        Status = "active"
                                        IsSynthetic = isSynthetic
                                        AnchorDate = anchorDate
                                        NextTradeDate = SipPolicy.nextTradeDate command.Frequency anchorDate (anchorDate.AddDays 1)
                                        CreatedAt = DateTimeOffset.UtcNow
                                        LastExecutionStatus = None
                                        LastExecutionDate = None
                                    }

                                let createdAt = insertSipPlan connection (Some transaction) plan
                                insertSipPlanIdempotency connection (Some transaction) idempotencyKey fingerprint plan.Id fundId
                                transaction.Commit()
                                SipPlanWriteResult.SipPlanCreated { plan with CreatedAt = createdAt }
                            else
                                transaction.Rollback()
                                SipPlanWriteResult.SipPlanInstrumentNotFound
                with error ->
                    try
                        transaction.Rollback()
                    with _ ->
                        ()

                    raise error

    member this.AdvanceSipPlans(fundId: Guid, endDate: DateOnly, limit: int) : SipAdvanceResult =
        use connection = new NpgsqlConnection(connectionString)
        connection.Open()

        use transaction = connection.BeginTransaction(IsolationLevel.ReadCommitted)

        try
            use lockCommand =
                commandWithTransaction
                    connection
                    (Some transaction)
                    "SELECT pg_advisory_xact_lock(hashtext(@lock_key))"

            addParameter lockCommand "lock_key" NpgsqlDbType.Text (box (sprintf "sip-advance:%O" fundId)) |> ignore
            lockCommand.ExecuteNonQuery() |> ignore

            // 0. retry phase: confirmations that were pending_nav get re-run once their NAV landed
            use retryCommand =
                commandWithTransaction
                    connection
                    (Some transaction)
                    """
                    SELECT e.plan_id, e.trade_date, e.order_id
                    FROM sip_executions e
                    JOIN sip_plans p ON p.id = e.plan_id
                    WHERE p.fund_id = @fund_id AND e.status = 'pending_nav'
                    ORDER BY e.trade_date
                    """

            addParameter retryCommand "fund_id" NpgsqlDbType.Uuid (box fundId) |> ignore

            use retryReader = retryCommand.ExecuteReader()
            let pendingRetries = ResizeArray<Guid * DateOnly * Guid>()

            while retryReader.Read() do
                pendingRetries.Add(
                    retryReader.GetGuid(0),
                    retryReader.GetFieldValue<DateOnly>(1),
                    retryReader.GetGuid(2)
                )

            retryReader.Close()

            for (retryPlanId, retryDate, retryOrderId) in pendingRetries do
                let confirmKey = sprintf "sip-confirm:%O:%s" retryPlanId (retryDate.ToString("yyyy-MM-dd"))

                match this.ConfirmSubscriptionOrder(confirmKey, fundId, retryOrderId) with
                | SubscriptionConfirmResult.OrderConfirmed _
                | SubscriptionConfirmResult.ConfirmReplayed _ ->
                    use doneCommand =
                        commandWithTransaction
                            connection
                            (Some transaction)
                            "UPDATE sip_executions SET status = 'succeeded', pending_reason = NULL, executed_at = now() WHERE plan_id = @plan_id AND trade_date = @trade_date"

                    addParameter doneCommand "plan_id" NpgsqlDbType.Uuid (box retryPlanId) |> ignore
                    addParameter doneCommand "trade_date" NpgsqlDbType.Date (box retryDate) |> ignore
                    doneCommand.ExecuteNonQuery() |> ignore
                | _ ->
                    // still pending: keep the execution as pending_nav for the next drive
                    ()

            use plansCommand =
                commandWithTransaction
                    connection
                    (Some transaction)
                    "SELECT id, instrument_code, amount, frequency, anchor_date, next_trade_date FROM sip_plans WHERE fund_id = @fund_id AND status = 'active' ORDER BY created_at"

            addParameter plansCommand "fund_id" NpgsqlDbType.Uuid (box fundId) |> ignore

            use plansReader = plansCommand.ExecuteReader()
            let plans = ResizeArray<Guid * string * decimal * SipFrequency * DateOnly * DateOnly>()

            while plansReader.Read() do
                plans.Add(
                    plansReader.GetGuid(0),
                    plansReader.GetString(1),
                    plansReader.GetDecimal(2),
                    (match SipPolicy.parseFrequency (plansReader.GetString(3)) with
                     | Some frequency -> frequency
                     | None -> failwith "sip plan frequency is invalid"),
                    plansReader.GetFieldValue<DateOnly>(4),
                    plansReader.GetFieldValue<DateOnly>(5)
                )

            plansReader.Close()

            let readExecutionsUpTo (planId: Guid) (upTo: DateOnly) =
                use replayCommand =
                    commandWithTransaction
                        connection
                        (Some transaction)
                        """
                        SELECT trade_date, status, order_id, pending_reason
                        FROM sip_executions
                        WHERE plan_id = @plan_id AND trade_date <= @up_to
                        ORDER BY trade_date
                        """

                addParameter replayCommand "plan_id" NpgsqlDbType.Uuid (box planId) |> ignore
                addParameter replayCommand "up_to" NpgsqlDbType.Date (box upTo) |> ignore

                use reader = replayCommand.ExecuteReader()
                let rows = ResizeArray<SipExecutionOutcome>()

                while reader.Read() do
                    rows.Add(
                        {
                            TradeDate = reader.GetFieldValue<DateOnly>(0)
                            Status = reader.GetString(1)
                            OrderId = (if reader.IsDBNull(2) then None else Some(reader.GetGuid(2)))
                            PendingReason = readStringOption reader 3
                        }
                    )

                rows |> Seq.toList

            let advancePlanRow (planId: Guid, code: string, amount: decimal, frequency: SipFrequency, anchor: DateOnly, nextDate: DateOnly) =
                let dueDates =
                    SipPolicy.advancePlan frequency anchor nextDate endDate
                    |> List.truncate (max 1 limit)

                let outcomes = ResizeArray<SipExecutionOutcome>()

                let upsertExecution (tradeDate: DateOnly) =
                    use insertCommand =
                        commandWithTransaction
                            connection
                            (Some transaction)
                            """
                            INSERT INTO sip_executions (plan_id, trade_date, amount, fee_amount, status)
                            VALUES (@plan_id, @trade_date, @amount, @fee_amount, 'processing')
                            ON CONFLICT (plan_id, trade_date) DO NOTHING
                            RETURNING trade_date
                            """

                    addParameter insertCommand "plan_id" NpgsqlDbType.Uuid (box planId) |> ignore
                    addParameter insertCommand "trade_date" NpgsqlDbType.Date (box tradeDate) |> ignore
                    addParameter insertCommand "amount" NpgsqlDbType.Numeric (box amount) |> ignore
                    addParameter insertCommand "fee_amount" NpgsqlDbType.Numeric (box 0m) |> ignore

                    use reader = insertCommand.ExecuteReader()
                    let inserted = reader.Read()
                    reader.Close()
                    inserted

                let setExecution (tradeDate: DateOnly) (status: string) (orderId: Guid option) (reason: string option) =
                    use updateCommand =
                        commandWithTransaction
                            connection
                            (Some transaction)
                            """
                            UPDATE sip_executions
                            SET status = @status,
                                order_id = @order_id,
                                pending_reason = @reason,
                                executed_at = now()
                            WHERE plan_id = @plan_id AND trade_date = @trade_date
                            """

                    addParameter updateCommand "status" NpgsqlDbType.Text (box status) |> ignore

                    let orderParameter =
                        match orderId with
                        | Some value -> box value
                        | None -> box DBNull.Value

                    addParameter updateCommand "order_id" NpgsqlDbType.Uuid orderParameter |> ignore

                    let reasonParameter =
                        match reason with
                        | Some value -> box value
                        | None -> box DBNull.Value

                    addParameter updateCommand "reason" NpgsqlDbType.Text reasonParameter |> ignore
                    addParameter updateCommand "plan_id" NpgsqlDbType.Uuid (box planId) |> ignore
                    addParameter updateCommand "trade_date" NpgsqlDbType.Date (box tradeDate) |> ignore
                    updateCommand.ExecuteNonQuery() |> ignore

                let findExistingExecution (tradeDate: DateOnly) =
                    use selectCommand =
                        commandWithTransaction
                            connection
                            (Some transaction)
                            "SELECT status, order_id, pending_reason FROM sip_executions WHERE plan_id = @plan_id AND trade_date = @trade_date"

                    addParameter selectCommand "plan_id" NpgsqlDbType.Uuid (box planId) |> ignore
                    addParameter selectCommand "trade_date" NpgsqlDbType.Date (box tradeDate) |> ignore

                    use reader = selectCommand.ExecuteReader()

                    if reader.Read() then
                        Some
                            (reader.GetString(0),
                             (if reader.IsDBNull(1) then None else Some(reader.GetGuid(1))),
                             readStringOption reader 2)
                    else
                        None

                let orderIdFor (tradeDate: DateOnly) =
                    let orderKey = sprintf "sip:%O:%s" planId (tradeDate.ToString("yyyy-MM-dd"))

                    match this.CreateSubscriptionOrder(orderKey, fundId, { FundCode = code; Amount = amount; FeeAmount = 0m }, tradeDate) with
                    | SubscriptionOrderWriteResult.OrderCreated order -> Some order.Id
                    | SubscriptionOrderWriteResult.OrderReplayed order -> Some order.Id
                    | SubscriptionOrderWriteResult.OrderInsufficientFunds -> None
                    | other -> failwithf "unexpected sip order result: %A" other

                for tradeDate in dueDates do
                    // 1. claim the slot atomically: same plan + same trade date runs once
                    if upsertExecution tradeDate then
                        // 2. place the order through the shared pipeline with a deterministic key
                        match orderIdFor tradeDate with
                        | None ->
                            setExecution tradeDate "insufficient_cash" None (Some "available cash is not enough for the scheduled amount")
                            outcomes.Add({ TradeDate = tradeDate; Status = "insufficient_cash"; OrderId = None; PendingReason = Some "available cash is not enough for the scheduled amount" })
                        | Some orderId ->
                            // 3. confirm through the shared confirmation pipeline
                            let confirmKey = sprintf "sip-confirm:%O:%s" planId (tradeDate.ToString("yyyy-MM-dd"))

                            match this.ConfirmSubscriptionOrder(confirmKey, fundId, orderId) with
                            | SubscriptionConfirmResult.OrderConfirmed _
                            | SubscriptionConfirmResult.ConfirmReplayed _ ->
                                setExecution tradeDate "succeeded" (Some orderId) None
                                outcomes.Add({ TradeDate = tradeDate; Status = "succeeded"; OrderId = Some orderId; PendingReason = None })
                            | SubscriptionConfirmResult.ConfirmPendingNav record ->
                                setExecution tradeDate "pending_nav" (Some orderId) record.PendingReason
                                outcomes.Add({ TradeDate = tradeDate; Status = "pending_nav"; OrderId = Some orderId; PendingReason = record.PendingReason })
                            | other ->
                                setExecution tradeDate "failed" (Some orderId) (Some (sprintf "%A" other))
                                outcomes.Add({ TradeDate = tradeDate; Status = "failed"; OrderId = Some orderId; PendingReason = Some (sprintf "%A" other) })
                    else
                        match findExistingExecution tradeDate with
                        | Some("succeeded", orderId, reason) ->
                            outcomes.Add({ TradeDate = tradeDate; Status = "succeeded"; OrderId = orderId; PendingReason = reason })
                        | Some(status, orderId, reason) ->
                            outcomes.Add({ TradeDate = tradeDate; Status = status; OrderId = orderId; PendingReason = reason })
                        | None ->
                            outcomes.Add({ TradeDate = tradeDate; Status = "unknown"; OrderId = None; PendingReason = None })

                // 4. roll the plan pointer forward past the processed window
                let rolled =
                    match dueDates with
                    | [] -> nextDate
                    | lastDueDates ->
                        SipPolicy.nextTradeDate frequency anchor ((List.last lastDueDates).AddDays 1)

                if not (List.isEmpty dueDates) then
                    use rollCommand =
                        commandWithTransaction
                            connection
                            (Some transaction)
                            "UPDATE sip_plans SET next_trade_date = @next_date WHERE id = @plan_id"

                    addParameter rollCommand "next_date" NpgsqlDbType.Date (box rolled) |> ignore
                    addParameter rollCommand "plan_id" NpgsqlDbType.Uuid (box planId) |> ignore
                    rollCommand.ExecuteNonQuery() |> ignore

                let replayedOutcomes =
                    if List.isEmpty dueDates then
                        // repeat drive with the same endDate: replay what was already processed
                        readExecutionsUpTo planId endDate
                    else
                        outcomes |> Seq.toList

                {
                    PlanId = planId
                    InstrumentCode = code
                    Amount = amount
                    Frequency = frequency
                    Executions = replayedOutcomes
                    NextTradeDate = rolled
                }

            let planResults = plans |> Seq.map advancePlanRow |> Seq.toList
            transaction.Commit()

            { FundId = fundId; Plans = planResults }
        with error ->
            try
                transaction.Rollback()
            with _ ->
                ()

            raise error

    member _.GetSipPlans(fundId: Guid) =
        use connection = new NpgsqlConnection(connectionString)
        connection.Open()

        use command =
            commandWithTransaction
                connection
                None
                """
                SELECT p.id, p.fund_id, p.instrument_code, p.amount, p.frequency, p.status, p.is_synthetic,
                       p.anchor_date, p.next_trade_date, p.created_at,
                       e.status, e.trade_date
                FROM sip_plans p
                LEFT JOIN LATERAL (
                    SELECT status, trade_date FROM sip_executions
                    WHERE plan_id = p.id ORDER BY executed_at DESC, trade_date DESC LIMIT 1
                ) e ON true
                WHERE p.fund_id = @fund_id
                ORDER BY p.created_at DESC, p.id
                """

        addParameter command "fund_id" NpgsqlDbType.Uuid (box fundId) |> ignore

        use reader = command.ExecuteReader()
        let records = ResizeArray<SipPlanRecord>()

        while reader.Read() do
            records.Add(sipPlanRecordFromReader reader)

        records |> Seq.toList

    member _.CreateRebalancePlan(idempotencyKey: string, fundId: Guid, command: RebalancePlanCommand) : RebalanceWriteResult =
        if String.IsNullOrWhiteSpace idempotencyKey then
            RebalanceWriteResult.RebalanceInvalid "idempotency key cannot be empty"
        else
            match validateRebalanceCommand command with
            | Error message -> RebalanceWriteResult.RebalanceInvalid message
            | Ok() ->
                let fingerprint = rebalanceRequestHash fundId command
                use connection = new NpgsqlConnection(connectionString)
                connection.Open()
                use transaction = connection.BeginTransaction(IsolationLevel.ReadCommitted)

                try
                    use lockCommand =
                        commandWithTransaction
                            connection
                            (Some transaction)
                            "SELECT pg_advisory_xact_lock(hashtext(@lock_key))"

                    addParameter lockCommand "lock_key" NpgsqlDbType.Text (box idempotencyKey) |> ignore
                    lockCommand.ExecuteNonQuery() |> ignore

                    match findRebalanceIdempotency connection (Some transaction) idempotencyKey with
                    | Some(existingHash, existingFundId, planId)
                        when existingHash = fingerprint && existingFundId = fundId ->
                        match findRebalancePlan connection (Some transaction) planId with
                        | Some plan ->
                            transaction.Commit()
                            RebalanceWriteResult.RebalancePlanReplayed plan
                        | None ->
                            transaction.Rollback()
                            RebalanceWriteResult.RebalanceInvalid "idempotency record references a missing plan"
                    | Some _ ->
                        transaction.Rollback()
                        RebalanceWriteResult.RebalanceIdempotencyConflict
                    | None ->
                        match lockFundForOrder connection (Some transaction) fundId with
                        | None ->
                            transaction.Rollback()
                            RebalanceWriteResult.RebalanceFundNotFound
                        | Some isSynthetic ->
                            let missingTarget =
                                command.Targets
                                |> List.tryFind (fun target -> not (instrumentExists connection (Some transaction) target.InstrumentCode))

                            match missingTarget with
                            | Some target ->
                                transaction.Rollback()
                                RebalanceWriteResult.RebalanceInstrumentNotFound
                            | None ->
                                let plan: RebalancePlanRecord =
                                    {
                                        Id = Guid.NewGuid()
                                        FundId = fundId
                                        Targets = command.Targets
                                        Status = "active"
                                        IsSynthetic = isSynthetic
                                        CreatedAt = DateTimeOffset.UtcNow
                                    }

                                let createdAt = insertRebalancePlan connection (Some transaction) plan
                                insertRebalanceIdempotency connection (Some transaction) idempotencyKey fingerprint plan.Id fundId
                                transaction.Commit()
                                RebalanceWriteResult.RebalancePlanCreated { plan with CreatedAt = createdAt }
                with error ->
                    try
                        transaction.Rollback()
                    with _ ->
                        ()

                    raise error

    member _.GetRebalancePlans(fundId: Guid) =
        use connection = new NpgsqlConnection(connectionString)
        connection.Open()

        use command =
            commandWithTransaction
                connection
                None
                "SELECT id, fund_id, status, is_synthetic, created_at FROM rebalance_plans WHERE fund_id = @fund_id ORDER BY created_at DESC, id"

        addParameter command "fund_id" NpgsqlDbType.Uuid (box fundId) |> ignore

        use reader = command.ExecuteReader()
        let plans = ResizeArray<RebalancePlanRecord>()

        while reader.Read() do
            plans.Add(rebalancePlanRecordFromReader reader)

        reader.Close()
        plans |> Seq.toList |> List.map (rebalancePlanWithTargets connection None)

    member this.ExecuteRebalancePlan(planId: Guid) : Result<RebalanceExecutionResult, string> =
        use connection = new NpgsqlConnection(connectionString)
        connection.Open()

        let plan =
            use transaction = connection.BeginTransaction(IsolationLevel.ReadCommitted)

            try
                use lockCommand =
                    commandWithTransaction
                        connection
                        (Some transaction)
                        "SELECT pg_advisory_xact_lock(hashtext(@lock_key))"

                addParameter lockCommand "lock_key" NpgsqlDbType.Text (box (sprintf "rebalance-execute:%O" planId)) |> ignore
                lockCommand.ExecuteNonQuery() |> ignore

                let plan = findRebalancePlan connection (Some transaction) planId
                transaction.Commit()
                plan
            with error ->
                try
                    transaction.Rollback()
                with _ ->
                    ()

                raise error

        match plan with
        | None -> Error "rebalance plan was not found"
        | Some plan ->
            let fundId = plan.FundId
            let runDate = ConfirmationPolicy.tradeDateFor DateTimeOffset.UtcNow

            // snapshot: fund cash plus each holding valued at its latest valuation NAV
            let fund = this.GetFund fundId

            match fund with
            | None -> Error "fund was not found"
            | Some fund ->
                let positions = this.GetFundPositions fundId

                let buildSnapshot (position: FundPositionRecord) : RebalancePolicy.RebalancePositionSnapshot =
                    let marketValue =
                        match position.ValuationNav with
                        | Some nav -> Decimal.Round(position.Units * nav, 2)
                        | None -> 0m

                    {
                        RebalancePolicy.RebalancePositionSnapshot.InstrumentCode = position.InstrumentCode
                        RebalancePolicy.RebalancePositionSnapshot.MarketValue = marketValue
                        RebalancePolicy.RebalancePositionSnapshot.Units = position.Units
                        RebalancePolicy.RebalancePositionSnapshot.AvailableUnits = position.Units - position.ReservedUnits
                        RebalancePolicy.RebalancePositionSnapshot.ValuationNav = position.ValuationNav
                    }

                let snapshots = positions |> List.map buildSnapshot

                let diffs =
                    RebalancePolicy.computeOrders plan.Targets snapshots fund.AvailableCash

                match diffs with
                | Error message -> Error message
                | Ok diffs ->
                    let outcomes = ResizeArray<RebalanceOrderOutcome>()

                    // sells first so freed cash can fund the buys
                    let ordered =
                        diffs
                        |> List.sortBy (fun diff ->
                            match diff.Action with
                            | RebalancePolicy.Sell -> 0
                            | RebalancePolicy.Buy -> 1
                            | RebalancePolicy.Hold -> 2)

                    for diff: RebalancePolicy.RebalanceDiff in ordered do
                        match diff.Action with
                        | RebalancePolicy.Hold -> ()
                        | RebalancePolicy.Buy ->
                            let orderKey = RebalancePolicy.orderKey plan.Id runDate diff.InstrumentCode

                            match
                                this.CreateSubscriptionOrder(
                                    orderKey,
                                    fundId,
                                    { FundCode = diff.InstrumentCode; Amount = diff.Amount; FeeAmount = 0m }
                                )
                            with
                            | SubscriptionOrderWriteResult.OrderCreated order
                            | SubscriptionOrderWriteResult.OrderReplayed order ->
                                let confirmKey = RebalancePolicy.confirmKey plan.Id runDate diff.InstrumentCode

                                match this.ConfirmSubscriptionOrder(confirmKey, fundId, order.Id) with
                                | SubscriptionConfirmResult.OrderConfirmed _
                                | SubscriptionConfirmResult.ConfirmReplayed _ ->
                                    outcomes.Add({ InstrumentCode = diff.InstrumentCode; Action = "buy"; Amount = cashText diff.Amount; Status = "succeeded"; OrderId = Some order.Id; PendingReason = None })
                                | SubscriptionConfirmResult.ConfirmPendingNav record ->
                                    outcomes.Add({ InstrumentCode = diff.InstrumentCode; Action = "buy"; Amount = cashText diff.Amount; Status = "pending_nav"; OrderId = Some order.Id; PendingReason = record.PendingReason })
                                | SubscriptionConfirmResult.ConfirmIdempotencyConflict ->
                                    outcomes.Add({ InstrumentCode = diff.InstrumentCode; Action = "buy"; Amount = cashText diff.Amount; Status = "idempotency_conflict"; OrderId = Some order.Id; PendingReason = None })
                                | other ->
                                    outcomes.Add({ InstrumentCode = diff.InstrumentCode; Action = "buy"; Amount = cashText diff.Amount; Status = "failed"; OrderId = Some order.Id; PendingReason = Some (sprintf "%A" other) })
                            | SubscriptionOrderWriteResult.OrderInsufficientFunds ->
                                outcomes.Add({ InstrumentCode = diff.InstrumentCode; Action = "buy"; Amount = cashText diff.Amount; Status = "insufficient_cash"; OrderId = None; PendingReason = Some "available cash is not enough for the rebalance buy" })
                            | other ->
                                outcomes.Add({ InstrumentCode = diff.InstrumentCode; Action = "buy"; Amount = cashText diff.Amount; Status = "failed"; OrderId = None; PendingReason = Some (sprintf "%A" other) })
                        | RebalancePolicy.Sell ->
                            match diff.Units with
                            | None ->
                                outcomes.Add({ InstrumentCode = diff.InstrumentCode; Action = "sell"; Amount = cashText diff.Amount; Status = "skipped_no_valuation"; OrderId = None; PendingReason = Some "holding has no valuation NAV to price the sell" })
                            | Some units when units <= 0m ->
                                outcomes.Add({ InstrumentCode = diff.InstrumentCode; Action = "sell"; Amount = cashText diff.Amount; Status = "skipped_no_available_units"; OrderId = None; PendingReason = Some "no available units to redeem" })
                            | Some units ->
                                let redeemKey = RebalancePolicy.redemptionKey plan.Id runDate diff.InstrumentCode

                                match
                                    this.CreateRedemptionOrder(
                                        redeemKey,
                                        fundId,
                                        { InstrumentCode = diff.InstrumentCode; Units = units; FeeAmount = 0m }
                                    )
                                with
                                | RedemptionWriteResult.RedemptionCreated order
                                | RedemptionWriteResult.RedemptionReplayed order ->
                                    let confirmKey = RebalancePolicy.redemptionConfirmKey plan.Id runDate diff.InstrumentCode

                                    match this.ConfirmRedemptionOrder(confirmKey, fundId, order.Id) with
                                    | RedemptionConfirmResult.RedemptionConfirmed _
                                    | RedemptionConfirmResult.RedemptionConfirmReplayed _ ->
                                        outcomes.Add({ InstrumentCode = diff.InstrumentCode; Action = "sell"; Amount = cashText diff.Amount; Status = "succeeded"; OrderId = Some order.Id; PendingReason = None })
                                    | RedemptionConfirmResult.RedemptionPendingNav record ->
                                        outcomes.Add({ InstrumentCode = diff.InstrumentCode; Action = "sell"; Amount = cashText diff.Amount; Status = "pending_nav"; OrderId = Some order.Id; PendingReason = record.PendingReason })
                                    | other ->
                                        outcomes.Add({ InstrumentCode = diff.InstrumentCode; Action = "sell"; Amount = cashText diff.Amount; Status = "failed"; OrderId = Some order.Id; PendingReason = Some (sprintf "%A" other) })
                                | RedemptionWriteResult.RedemptionInsufficientUnits ->
                                    outcomes.Add({ InstrumentCode = diff.InstrumentCode; Action = "sell"; Amount = cashText diff.Amount; Status = "insufficient_units"; OrderId = None; PendingReason = Some "available units are not enough for the rebalance sell" })
                                | other ->
                                    outcomes.Add({ InstrumentCode = diff.InstrumentCode; Action = "sell"; Amount = cashText diff.Amount; Status = "failed"; OrderId = None; PendingReason = Some (sprintf "%A" other) })

                    Ok
                        {
                            PlanId = plan.Id
                            RunDate = runDate
                            Outcomes = outcomes |> Seq.toList
                        }

    member this.RegisterDividend(idempotencyKey: string, fundId: Guid, command: DividendCommand) : DividendWriteResult =
        if String.IsNullOrWhiteSpace idempotencyKey then
            DividendWriteResult.DividendInvalid "idempotency key cannot be empty"
        else
            let today = ConfirmationPolicy.tradeDateFor DateTimeOffset.UtcNow

            match validateDividendCommand today command with
            | Error message -> DividendWriteResult.DividendInvalid message
            | Ok() ->
                let schemeKey = dividendSchemeKey fundId command
                let fingerprint = dividendRequestHash fundId command
                use connection = new NpgsqlConnection(connectionString)
                connection.Open()

                // Phase 1: claim the scheme atomically, validate, and book the payout
                let claimedStage =
                    use transaction = connection.BeginTransaction(IsolationLevel.ReadCommitted)

                    try
                        use lockCommand =
                            commandWithTransaction
                                connection
                                (Some transaction)
                                "SELECT pg_advisory_xact_lock(hashtext(@lock_key))"

                        addParameter lockCommand "lock_key" NpgsqlDbType.Text (box schemeKey) |> ignore
                        lockCommand.ExecuteNonQuery() |> ignore

                        match findDividendIdempotency connection (Some transaction) schemeKey with
                        | Some(existingHash, existingFundId, recordId) when existingFundId = fundId ->
                            if existingHash = fingerprint then
                                transaction.Commit()
                                StageReplay recordId
                            else
                                transaction.Rollback()
                                StageFail DividendWriteResult.DividendIdempotencyConflict
                        | Some _ ->
                            transaction.Rollback()
                            StageFail DividendWriteResult.DividendIdempotencyConflict
                        | None ->
                            match lockFundForOrder connection (Some transaction) fundId with
                            | None ->
                                transaction.Rollback()
                                StageFail DividendWriteResult.DividendFundNotFound
                            | Some isSynthetic ->
                                if not (instrumentExists connection (Some transaction) command.InstrumentCode) then
                                    transaction.Rollback()
                                    StageFail DividendWriteResult.DividendInstrumentNotFound
                                else
                                    use positionCommand =
                                        commandWithTransaction
                                            connection
                                            (Some transaction)
                                            "SELECT units FROM fund_positions WHERE fund_id = @fund_id AND instrument_code = @code FOR UPDATE"

                                    addParameter positionCommand "fund_id" NpgsqlDbType.Uuid (box fundId) |> ignore
                                    addParameter positionCommand "code" NpgsqlDbType.Text (box command.InstrumentCode) |> ignore

                                    use positionReader = positionCommand.ExecuteReader()
                                    let positionFound = positionReader.Read()
                                    let heldUnits = if positionFound then positionReader.GetDecimal(0) else 0m
                                    positionReader.Close()

                                    if not positionFound || heldUnits <= 0m then
                                        transaction.Rollback()
                                        StageFail DividendWriteResult.DividendNoHoldings
                                    else
                                        match DividendPolicy.computeCashPayout heldUnits command.Dps with
                                        | Error message ->
                                            transaction.Rollback()
                                            StageFail (DividendWriteResult.DividendInvalid message)
                                        | Ok payout ->
                                            use cashCommand =
                                                commandWithTransaction
                                                    connection
                                                    (Some transaction)
                                                    "UPDATE funds SET available_cash = available_cash + @gross WHERE id = @fund_id"

                                            addParameter cashCommand "gross" NpgsqlDbType.Numeric (box payout.GrossCash) |> ignore
                                            addParameter cashCommand "fund_id" NpgsqlDbType.Uuid (box fundId) |> ignore

                                            if cashCommand.ExecuteNonQuery() = 0 then
                                                transaction.Rollback()
                                                StageFail DividendWriteResult.DividendFundNotFound
                                            else
                                                let recordId = Guid.NewGuid()

                                                let record: DividendRecord =
                                                    {
                                                        Id = recordId
                                                        FundId = fundId
                                                        InstrumentCode = command.InstrumentCode
                                                        NavDate = command.NavDate
                                                        Dps = command.Dps
                                                        Mode = command.Mode
                                                        Status = (if command.Mode = DividendPolicy.Cash then "cash_credited" else "pending_nav")
                                                        IsSynthetic = isSynthetic
                                                        GrossCash = Some payout.GrossCash
                                                        CreditedUnits = None
                                                        CreditedInvested = None
                                                        OrderId = None
                                                        PendingReason = None
                                                        CreatedAt = DateTimeOffset.UtcNow
                                                    }

                                                let createdAt = insertDividendRecord connection (Some transaction) record
                                                insertDividendIdempotency connection (Some transaction) schemeKey fingerprint recordId fundId
                                                transaction.Commit()
                                                StageBooked { record with CreatedAt = createdAt }
                    with error ->
                        try
                            transaction.Rollback()
                        with _ ->
                            ()

                        raise error

                // Confirmation of the reinvestment order settles the dividend record: the
                // credited units/invested cash are persisted and the row is marked succeeded.
                let finalizeDividend (record: DividendRecord) (confirmed: SubscriptionOrderRecord) =
                    let units = confirmed.ConfirmedUnits |> Option.defaultValue 0m
                    let invested = confirmed.ConfirmedInvestedCash |> Option.defaultValue 0m

                    do
                        use finalizeConnection = new NpgsqlConnection(connectionString)
                        finalizeConnection.Open()

                        use finalizeTransaction = finalizeConnection.BeginTransaction(IsolationLevel.ReadCommitted)

                        use finalizeCommand =
                            commandWithTransaction
                                finalizeConnection
                                (Some finalizeTransaction)
                                """
                                UPDATE dividend_records
                                SET status = 'succeeded',
                                    credited_units = @units,
                                    credited_invested = @invested,
                                    pending_reason = NULL
                                WHERE id = @record_id
                                """

                        addParameter finalizeCommand "units" NpgsqlDbType.Numeric (box units) |> ignore
                        addParameter finalizeCommand "invested" NpgsqlDbType.Numeric (box invested) |> ignore
                        addParameter finalizeCommand "record_id" NpgsqlDbType.Uuid (box record.Id) |> ignore
                        finalizeCommand.ExecuteNonQuery() |> ignore
                        finalizeTransaction.Commit()

                    { record with Status = "succeeded"; CreditedUnits = Some units; CreditedInvested = Some invested }

                // Phase 2: replays never re-book; pending reinvestments retry their confirmation
                match claimedStage with
                | StageReplay recordId ->
                    let record =
                        match findDividendRecord connection None recordId with
                        | Some record -> record
                        | None -> failwith "idempotency scheme references a missing dividend"

                    match record.Status, record.OrderId with
                    | "pending_nav", Some orderId ->
                        let confirmKey = sprintf "dividend-confirm:%O:%s:%s:%s" fundId command.InstrumentCode (command.NavDate.ToString("yyyy-MM-dd")) (command.Dps.ToString("G29", CultureInfo.InvariantCulture))

                        match this.ConfirmSubscriptionOrder(confirmKey, fundId, orderId) with
                        | SubscriptionConfirmResult.OrderConfirmed confirmed
                        | SubscriptionConfirmResult.ConfirmReplayed confirmed ->
                            DividendCredited(finalizeDividend record confirmed)
                        | SubscriptionConfirmResult.ConfirmPendingNav _ ->
                            DividendReplayed record
                        | other ->
                            failwithf "unexpected dividend confirm replay result: %A" other
                    | _ ->
                        DividendReplayed record
                | StageFail failure -> failure
                | StageBooked record ->
                    if record.Mode = DividendPolicy.Cash then
                        DividendCredited record
                    else
                        let orderKey = sprintf "dividend:%O:%s:%s:%s" fundId command.InstrumentCode (command.NavDate.ToString("yyyy-MM-dd")) (command.Dps.ToString("G29", CultureInfo.InvariantCulture))
                        let confirmKey = sprintf "dividend-confirm:%O:%s:%s:%s" fundId command.InstrumentCode (command.NavDate.ToString("yyyy-MM-dd")) (command.Dps.ToString("G29", CultureInfo.InvariantCulture))

                        match
                            this.CreateSubscriptionOrder(
                                orderKey,
                                fundId,
                                { FundCode = command.InstrumentCode; Amount = record.GrossCash |> Option.defaultValue 0m; FeeAmount = 0m },
                                command.NavDate
                            )
                        with
                        | SubscriptionOrderWriteResult.OrderCreated order
                        | SubscriptionOrderWriteResult.OrderReplayed order ->
                            do
                                use bindConnection = new NpgsqlConnection(connectionString)
                                bindConnection.Open()

                                use bindTransaction = bindConnection.BeginTransaction(IsolationLevel.ReadCommitted)

                                use bindCommand =
                                    commandWithTransaction
                                        bindConnection
                                        (Some bindTransaction)
                                        "UPDATE dividend_records SET order_id = @order_id WHERE id = @record_id"

                                addParameter bindCommand "order_id" NpgsqlDbType.Uuid (box order.Id) |> ignore
                                addParameter bindCommand "record_id" NpgsqlDbType.Uuid (box record.Id) |> ignore
                                bindCommand.ExecuteNonQuery() |> ignore
                                bindTransaction.Commit()

                            let recordWithOrder = { record with OrderId = Some order.Id }

                            match this.ConfirmSubscriptionOrder(confirmKey, fundId, order.Id) with
                            | SubscriptionConfirmResult.OrderConfirmed confirmed
                            | SubscriptionConfirmResult.ConfirmReplayed confirmed ->
                                DividendCredited(finalizeDividend recordWithOrder confirmed)
                            | SubscriptionConfirmResult.ConfirmPendingNav pending ->
                                DividendPendingReinvest { recordWithOrder with PendingReason = pending.PendingReason }
                            | other ->
                                failwithf "unexpected dividend confirm result: %A" other
                        | other ->
                            failwithf "unexpected dividend order result: %A" other

    member _.GetDividendRecords(fundId: Guid) =
        use connection = new NpgsqlConnection(connectionString)
        connection.Open()

        use command =
            commandWithTransaction
                connection
                None
                """
                SELECT id, fund_id, instrument_code, nav_date, dps, mode, status, is_synthetic,
                       gross_cash, credited_units, credited_invested, order_id, pending_reason, created_at
                FROM dividend_records WHERE fund_id = @fund_id ORDER BY created_at DESC, id
                """

        addParameter command "fund_id" NpgsqlDbType.Uuid (box fundId) |> ignore

        use reader = command.ExecuteReader()
        let records = ResizeArray<DividendRecord>()

        while reader.Read() do
            records.Add(dividendRecordFromReader reader)

        records |> Seq.toList

    member _.CreateCapitalDeposit(idempotencyKey: string, fundId: Guid, command: CapitalDepositCommand) : CapitalDepositWriteResult =
        if String.IsNullOrWhiteSpace idempotencyKey then
            CapitalDepositWriteResult.CapitalDepositInvalid "idempotency key cannot be empty"
        else
            match CapitalPolicy.validateDeposit command.Amount with
            | Error message -> CapitalDepositWriteResult.CapitalDepositInvalid message
            | Ok() ->
                let fingerprint = capitalDepositRequestHash fundId command
                use connection = new NpgsqlConnection(connectionString)
                connection.Open()
                use transaction = connection.BeginTransaction(IsolationLevel.ReadCommitted)

                try
                    use lockCommand =
                        commandWithTransaction
                            connection
                            (Some transaction)
                            "SELECT pg_advisory_xact_lock(hashtext(@lock_key))"

                    addParameter lockCommand "lock_key" NpgsqlDbType.Text (box idempotencyKey) |> ignore
                    lockCommand.ExecuteNonQuery() |> ignore

                    match findCapitalDepositIdempotency connection (Some transaction) idempotencyKey with
                    | Some(existingHash, existingFundId, depositId)
                        when existingHash = fingerprint && existingFundId = fundId ->
                        match findCapitalDeposit connection (Some transaction) depositId with
                        | Some deposit ->
                            transaction.Commit()
                            CapitalDepositWriteResult.CapitalDepositReplayed deposit
                        | None ->
                            transaction.Rollback()
                            CapitalDepositWriteResult.CapitalDepositInvalid "idempotency record references a missing deposit"
                    | Some _ ->
                        transaction.Rollback()
                        CapitalDepositWriteResult.CapitalDepositIdempotencyConflict
                    | None ->
                        match lockFundForOrder connection (Some transaction) fundId with
                        | None ->
                            transaction.Rollback()
                            CapitalDepositWriteResult.CapitalDepositFundNotFound
                        | Some isSynthetic ->
                            use cashCommand =
                                commandWithTransaction
                                    connection
                                    (Some transaction)
                                    "UPDATE funds SET available_cash = available_cash + @amount WHERE id = @fund_id"

                            addParameter cashCommand "amount" NpgsqlDbType.Numeric (box command.Amount) |> ignore
                            addParameter cashCommand "fund_id" NpgsqlDbType.Uuid (box fundId) |> ignore

                            if cashCommand.ExecuteNonQuery() = 0 then
                                transaction.Rollback()
                                CapitalDepositWriteResult.CapitalDepositFundNotFound
                            else
                                let deposit: CapitalDepositRecord =
                                    {
                                        Id = Guid.NewGuid()
                                        FundId = fundId
                                        Amount = command.Amount
                                        Note = command.Note
                                        IsSynthetic = isSynthetic
                                        CreatedAt = DateTimeOffset.UtcNow
                                    }

                                let createdAt = insertCapitalDeposit connection (Some transaction) deposit
                                insertCapitalDepositIdempotency connection (Some transaction) idempotencyKey fingerprint deposit.Id fundId
                                transaction.Commit()
                                CapitalDepositWriteResult.CapitalDepositCreated { deposit with CreatedAt = createdAt }
                with error ->
                    try
                        transaction.Rollback()
                    with _ ->
                        ()

                    raise error

    member _.GetCapitalDeposits(fundId: Guid) =
        use connection = new NpgsqlConnection(connectionString)
        connection.Open()

        use command =
            commandWithTransaction
                connection
                None
                "SELECT id, fund_id, amount, note, is_synthetic, created_at FROM fund_capital_deposits WHERE fund_id = @fund_id ORDER BY created_at DESC, id"

        addParameter command "fund_id" NpgsqlDbType.Uuid (box fundId) |> ignore

        use reader = command.ExecuteReader()
        let records = ResizeArray<CapitalDepositRecord>()

        while reader.Read() do
            records.Add(capitalDepositRecordFromReader reader)

        records |> Seq.toList

    member _.CreateRedemptionOrder(idempotencyKey: string, fundId: Guid, command: RedemptionCommand) : RedemptionWriteResult =
        if String.IsNullOrWhiteSpace idempotencyKey then
            RedemptionWriteResult.RedemptionInvalid "idempotency key cannot be empty"
        else
            match validateRedemptionCommand command with
            | Error message -> RedemptionWriteResult.RedemptionInvalid message
            | Ok() ->
                let fingerprint = redemptionRequestHash fundId command
                use connection = new NpgsqlConnection(connectionString)
                connection.Open()
                use transaction = connection.BeginTransaction(IsolationLevel.ReadCommitted)

                try
                    use lockCommand =
                        commandWithTransaction
                            connection
                            (Some transaction)
                            "SELECT pg_advisory_xact_lock(hashtext(@lock_key))"

                    addParameter lockCommand "lock_key" NpgsqlDbType.Text (box idempotencyKey) |> ignore
                    lockCommand.ExecuteNonQuery() |> ignore

                    match findRedemptionOrderIdempotency connection (Some transaction) idempotencyKey with
                    | Some(existingHash, existingFundId, orderId)
                        when existingHash = fingerprint && existingFundId = fundId ->
                        match findRedemptionOrder connection (Some transaction) orderId with
                        | Some order ->
                            transaction.Commit()
                            RedemptionReplayed order
                        | None ->
                            transaction.Rollback()
                            RedemptionWriteResult.RedemptionInvalid "idempotency record references a missing order"
                    | Some _ ->
                        transaction.Rollback()
                        RedemptionIdempotencyConflict
                    | None ->
                        match lockFundForOrder connection (Some transaction) fundId with
                        | None ->
                            transaction.Rollback()
                            RedemptionFundNotFound
                        | Some isSynthetic ->
                            if instrumentExists connection (Some transaction) command.InstrumentCode then
                                use freezeCommand =
                                    commandWithTransaction
                                        connection
                                        (Some transaction)
                                        """
                                        UPDATE fund_positions
                                        SET reserved_units = reserved_units + @units
                                        WHERE fund_id = @fund_id
                                          AND instrument_code = @code
                                          AND units - reserved_units >= @units
                                        """

                                addParameter freezeCommand "units" NpgsqlDbType.Numeric (box command.Units) |> ignore
                                addParameter freezeCommand "fund_id" NpgsqlDbType.Uuid (box fundId) |> ignore
                                addParameter freezeCommand "code" NpgsqlDbType.Text (box command.InstrumentCode) |> ignore

                                if freezeCommand.ExecuteNonQuery() = 0 then
                                    transaction.Rollback()
                                    RedemptionInsufficientUnits
                                else
                                    let submittedAt = DateTimeOffset.UtcNow
                                    let order: RedemptionOrderRecord =
                                        {
                                            Id = Guid.NewGuid()
                                            FundId = fundId
                                            InstrumentCode = command.InstrumentCode
                                            Units = command.Units
                                            FeeAmount = command.FeeAmount
                                            Status = "submitted"
                                            IsSynthetic = isSynthetic
                                            SubmittedAt = submittedAt
                                            TradeDate = ConfirmationPolicy.tradeDateFor submittedAt
                                            ConfirmIdempotencyKey = None
                                            PendingReason = None
                                            ConfirmedAt = None
                                            ConfirmedNav = None
                                            ConfirmedNavDate = None
                                            ConfirmedProceeds = None
                                            ConfirmedCostReleased = None
                                        }

                                    let submittedAt = insertRedemptionOrder connection (Some transaction) order
                                    insertRedemptionOrderIdempotency connection (Some transaction) idempotencyKey fingerprint order.Id fundId
                                    transaction.Commit()
                                    RedemptionCreated { order with SubmittedAt = submittedAt }
                            else
                                transaction.Rollback()
                                RedemptionInstrumentNotFound
                with error ->
                    try
                        transaction.Rollback()
                    with _ ->
                        ()

                    raise error

    member _.GetRedemptionOrders(fundId: Guid) =
        use connection = new NpgsqlConnection(connectionString)
        connection.Open()

        use command =
            commandWithTransaction connection None (redemptionOrderColumns + " WHERE fund_id = @fund_id ORDER BY submitted_at DESC, id")

        addParameter command "fund_id" NpgsqlDbType.Uuid (box fundId) |> ignore

        use reader = command.ExecuteReader()
        let records = ResizeArray<RedemptionOrderRecord>()

        while reader.Read() do
            records.Add(redemptionRecordFromReader reader)

        records |> Seq.toList

    member _.ConfirmRedemptionOrder(idempotencyKey: string, fundId: Guid, orderId: Guid) : RedemptionConfirmResult =
        if String.IsNullOrWhiteSpace idempotencyKey then
            RedemptionConfirmResult.RedemptionInvalid "idempotency key cannot be empty"
        else
            use connection = new NpgsqlConnection(connectionString)
            connection.Open()
            use transaction = connection.BeginTransaction(IsolationLevel.ReadCommitted)

            try
                let confirmedAt = DateTimeOffset.UtcNow
                let today = ConfirmationPolicy.shanghaiDate confirmedAt

                use lockCommand =
                    commandWithTransaction
                        connection
                        (Some transaction)
                        "SELECT pg_advisory_xact_lock(hashtext(@lock_key))"

                addParameter lockCommand "lock_key" NpgsqlDbType.Text (box (sprintf "confirm-redemption:%O" orderId)) |> ignore
                lockCommand.ExecuteNonQuery() |> ignore

                match findRedemptionOrder connection (Some transaction) orderId with
                | None ->
                    transaction.Rollback()
                    RedemptionOrderNotFound
                | Some order when order.FundId <> fundId ->
                    transaction.Rollback()
                    RedemptionOrderNotFound
                | Some order ->
                    if order.Status = "confirmed" then
                        match order.ConfirmIdempotencyKey with
                        | Some storedKey when storedKey = idempotencyKey ->
                            transaction.Commit()
                            RedemptionConfirmReplayed order
                        | _ ->
                            match findRedemptionConfirmIdempotency connection (Some transaction) idempotencyKey with
                            | Some(_, _, storedOrderId) when storedOrderId = orderId ->
                                transaction.Commit()
                                RedemptionConfirmReplayed order
                            | Some _ ->
                                transaction.Rollback()
                                RedemptionConfirmIdempotencyConflict
                            | None ->
                                transaction.Rollback()
                                RedemptionAlreadyConfirmed
                    elif order.Status <> "submitted" && order.Status <> "pending_nav" then
                        transaction.Rollback()
                        RedemptionInvalidStatus
                    else
                        match findRedemptionConfirmIdempotency connection (Some transaction) idempotencyKey with
                        | Some _ ->
                            transaction.Rollback()
                            RedemptionConfirmIdempotencyConflict
                        | None ->
                            let tradeDate = order.TradeDate
                            let tradeDateText = tradeDate.ToString("yyyy-MM-dd")

                            use quoteCommand =
                                commandWithTransaction
                                    connection
                                    (Some transaction)
                                    """
                                    SELECT o.nav, o.nav_date, o.source, o.source_revision, o.source_collected_at, o.published_at,
                                           o.source_payload_hash, o.first_seen_at, e.first_seen_at
                                    FROM fund_nav_observations o
                                    LEFT JOIN fund_nav_observation_evidence e
                                        ON e.instrument_code = o.instrument_code
                                       AND e.nav_date = o.nav_date
                                       AND e.source_payload_hash = o.source_payload_hash
                                    WHERE o.instrument_code = @code AND o.nav_date = @trade_date AND o.nav > 0
                                    ORDER BY o.source_collected_at DESC, o.published_at DESC NULLS LAST, o.source_revision DESC
                                    LIMIT 1
                                    """

                            addParameter quoteCommand "code" NpgsqlDbType.Text (box order.InstrumentCode) |> ignore
                            addParameter quoteCommand "trade_date" NpgsqlDbType.Date (box tradeDate) |> ignore

                            use quoteReader = quoteCommand.ExecuteReader()
                            let quoteFound = quoteReader.Read()

                            let selectedQuote =
                                if quoteFound then
                                    let evidenceFirstSeen =
                                        if quoteReader.IsDBNull(8) then
                                            None
                                        else
                                            Some(quoteReader.GetFieldValue<DateTimeOffset>(8))

                                    Some
                                        ({
                                            Nav = quoteReader.GetDecimal(0)
                                            NavDate = quoteReader.GetFieldValue<DateOnly>(1)
                                            Source = quoteReader.GetString(2)
                                            Revision = quoteReader.GetString(3)
                                            CollectedAt = quoteReader.GetFieldValue<DateTimeOffset>(4)
                                            PublishedAt =
                                                if quoteReader.IsDBNull(5) then
                                                    None
                                                else
                                                    Some(quoteReader.GetFieldValue<DateTimeOffset>(5))
                                            PayloadHash = quoteReader.GetString(6)
                                            FirstSeenAt = quoteReader.GetFieldValue<DateTimeOffset>(7)
                                         },
                                         evidenceFirstSeen)
                                else
                                    None

                            quoteReader.Close()

                            let boundQuote =
                                match selectedQuote with
                                | Some(quote, Some firstSeen) -> Some { quote with FirstSeenAt = firstSeen }
                                | _ -> None

                            let deferralReason =
                                match selectedQuote with
                                | None ->
                                    Some(sprintf "nav for trade date %s is not available yet" tradeDateText)
                                | Some(_, evidenceFirstSeen) when evidenceFirstSeen.IsNone ->
                                    Some(sprintf "nav revision for trade date %s has no observation evidence recorded" tradeDateText)
                                | Some(quote, _) when quote.FirstSeenAt > confirmedAt ->
                                    Some(sprintf "nav revision for trade date %s was first observed after the confirmation attempt" tradeDateText)
                                | Some(quote, _) ->
                                    ConfirmationPolicy.navDeferralReason
                                        {
                                            Nav = quote.Nav
                                            NavDate = quote.NavDate
                                            CollectedAt = quote.CollectedAt
                                            PublishedAt = quote.PublishedAt
                                        }
                                        tradeDate
                                        today
                                        confirmedAt

                            match deferralReason with
                            | Some reason ->
                                use pendingCommand =
                                    commandWithTransaction
                                        connection
                                        (Some transaction)
                                        """
                                        UPDATE redemption_orders
                                        SET status = 'pending_nav',
                                            pending_reason = @reason,
                                            confirm_idempotency_key = NULL,
                                            confirmed_at = NULL,
                                            confirmed_nav = NULL,
                                            confirmed_nav_date = NULL,
                                            confirmed_proceeds = NULL,
                                            confirmed_cost_released = NULL
                                        WHERE id = @order_id
                                        """

                                addParameter pendingCommand "reason" NpgsqlDbType.Text (box reason) |> ignore
                                addParameter pendingCommand "order_id" NpgsqlDbType.Uuid (box orderId) |> ignore
                                pendingCommand.ExecuteNonQuery() |> ignore
                                transaction.Commit()

                                match findRedemptionOrder connection None orderId with
                                | Some pendingOrder -> RedemptionPendingNav pendingOrder
                                | None -> failwith "pending redemption disappeared after confirmation deferral"
                            | None ->
                                let nav = boundQuote |> Option.get |> fun quote -> quote.Nav

                                use positionCommand =
                                    commandWithTransaction
                                        connection
                                        (Some transaction)
                                        """
                                        SELECT units, reserved_units, cost_cash
                                        FROM fund_positions
                                        WHERE fund_id = @fund_id AND instrument_code = @code
                                        FOR UPDATE
                                        """

                                addParameter positionCommand "fund_id" NpgsqlDbType.Uuid (box fundId) |> ignore
                                addParameter positionCommand "code" NpgsqlDbType.Text (box order.InstrumentCode) |> ignore

                                use positionReader = positionCommand.ExecuteReader()
                                let positionFound = positionReader.Read()
                                let positionUnits = if positionFound then positionReader.GetDecimal(0) else 0m
                                let positionReserved = if positionFound then positionReader.GetDecimal(1) else 0m
                                let positionCost = if positionFound then positionReader.GetDecimal(2) else 0m
                                positionReader.Close()

                                if not positionFound || positionReserved < order.Units then
                                    failwith "frozen units are missing for redemption confirmation"

                                match RedemptionPolicy.compute order.Units nav order.FeeAmount positionCost positionUnits with
                                | Error message ->
                                    use pendingCommand =
                                        commandWithTransaction
                                            connection
                                            (Some transaction)
                                            """
                                            UPDATE redemption_orders
                                            SET status = 'pending_nav',
                                                pending_reason = @reason
                                            WHERE id = @order_id
                                            """

                                    addParameter pendingCommand "reason" NpgsqlDbType.Text (box message) |> ignore
                                    addParameter pendingCommand "order_id" NpgsqlDbType.Uuid (box orderId) |> ignore
                                    pendingCommand.ExecuteNonQuery() |> ignore
                                    transaction.Commit()

                                    match findRedemptionOrder connection None orderId with
                                    | Some pendingOrder -> RedemptionPendingNav pendingOrder
                                    | None -> failwith "pending redemption disappeared after computation failure"
                                | Ok computation ->
                                    use settlePositionCommand =
                                        commandWithTransaction
                                            connection
                                            (Some transaction)
                                            """
                                            UPDATE fund_positions
                                            SET units = units - @units,
                                                reserved_units = reserved_units - @units,
                                                cost_cash = cost_cash - @cost_released
                                            WHERE fund_id = @fund_id
                                              AND instrument_code = @code
                                              AND units > @units
                                              AND reserved_units >= @units
                                              AND cost_cash >= @cost_released
                                            """

                                    addParameter settlePositionCommand "units" NpgsqlDbType.Numeric (box order.Units) |> ignore
                                    addParameter settlePositionCommand "cost_released" NpgsqlDbType.Numeric (box computation.RedeemedCost) |> ignore
                                    addParameter settlePositionCommand "fund_id" NpgsqlDbType.Uuid (box fundId) |> ignore
                                    addParameter settlePositionCommand "code" NpgsqlDbType.Text (box order.InstrumentCode) |> ignore

                                    if settlePositionCommand.ExecuteNonQuery() = 0 then
                                        use deletePositionCommand =
                                            commandWithTransaction
                                                connection
                                                (Some transaction)
                                                """
                                                DELETE FROM fund_positions
                                                WHERE fund_id = @fund_id
                                                  AND instrument_code = @code
                                                  AND units = @units
                                                  AND reserved_units >= @units
                                                  AND cost_cash >= @cost_released
                                                """

                                        addParameter deletePositionCommand "units" NpgsqlDbType.Numeric (box order.Units) |> ignore
                                        addParameter deletePositionCommand "cost_released" NpgsqlDbType.Numeric (box computation.RedeemedCost) |> ignore
                                        addParameter deletePositionCommand "fund_id" NpgsqlDbType.Uuid (box fundId) |> ignore
                                        addParameter deletePositionCommand "code" NpgsqlDbType.Text (box order.InstrumentCode) |> ignore

                                        if deletePositionCommand.ExecuteNonQuery() = 0 then
                                            failwith "position units changed during redemption confirmation"

                                    use cashCommand =
                                        commandWithTransaction
                                            connection
                                            (Some transaction)
                                            """
                                            UPDATE funds
                                            SET available_cash = available_cash + @proceeds
                                            WHERE id = @fund_id
                                            """

                                    addParameter cashCommand "proceeds" NpgsqlDbType.Numeric (box computation.Proceeds) |> ignore
                                    addParameter cashCommand "fund_id" NpgsqlDbType.Uuid (box fundId) |> ignore

                                    if cashCommand.ExecuteNonQuery() = 0 then
                                        failwith "fund disappeared during redemption confirmation"

                                    use confirmCommand =
                                        commandWithTransaction
                                            connection
                                            (Some transaction)
                                            """
                                            UPDATE redemption_orders
                                            SET status = 'confirmed',
                                                pending_reason = NULL,
                                                confirm_idempotency_key = @idempotency_key,
                                                confirmed_at = @confirmed_at,
                                                confirmed_nav = @nav,
                                                confirmed_nav_date = @nav_date,
                                                confirmed_proceeds = @proceeds,
                                                confirmed_cost_released = @cost_released
                                            WHERE id = @order_id
                                            """

                                    addParameter confirmCommand "idempotency_key" NpgsqlDbType.Text (box idempotencyKey) |> ignore
                                    addParameter confirmCommand "confirmed_at" NpgsqlDbType.TimestampTz (box confirmedAt) |> ignore
                                    addParameter confirmCommand "nav" NpgsqlDbType.Numeric (box nav) |> ignore
                                    addParameter confirmCommand "nav_date" NpgsqlDbType.Date (box tradeDate) |> ignore
                                    addParameter confirmCommand "proceeds" NpgsqlDbType.Numeric (box computation.Proceeds) |> ignore
                                    addParameter confirmCommand "cost_released" NpgsqlDbType.Numeric (box computation.RedeemedCost) |> ignore
                                    addParameter confirmCommand "order_id" NpgsqlDbType.Uuid (box orderId) |> ignore
                                    confirmCommand.ExecuteNonQuery() |> ignore

                                    insertRedemptionConfirmIdempotency connection (Some transaction) idempotencyKey "" orderId fundId
                                    transaction.Commit()

                                    match findRedemptionOrder connection None orderId with
                                    | Some confirmedOrder -> RedemptionConfirmed confirmedOrder
                                    | None -> failwith "confirmed redemption disappeared after commit"

            with error ->
                try
                    transaction.Rollback()
                with _ ->
                    ()

                raise error

    member _.ConfirmSubscriptionOrder(idempotencyKey: string, fundId: Guid, orderId: Guid) =
        if String.IsNullOrWhiteSpace idempotencyKey then
            ConfirmInvalid "idempotency key cannot be empty"
        else
            use connection = new NpgsqlConnection(connectionString)
            connection.Open()
            use transaction = connection.BeginTransaction(IsolationLevel.ReadCommitted)

            try
                let confirmedAt = DateTimeOffset.UtcNow
                let today = ConfirmationPolicy.shanghaiDate confirmedAt

                let requestHash =
                    Convert
                        .ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(sprintf "confirm:%O:%O" fundId orderId)))
                        .ToLowerInvariant()

                use lockCommand =
                    commandWithTransaction
                        connection
                        (Some transaction)
                        "SELECT pg_advisory_xact_lock(hashtext(@lock_key))"

                addParameter lockCommand "lock_key" NpgsqlDbType.Text (box (sprintf "confirm-order:%O" orderId)) |> ignore
                lockCommand.ExecuteNonQuery() |> ignore

                match findOrder connection (Some transaction) orderId with
                | None ->
                    transaction.Rollback()
                    ConfirmOrderNotFound
                | Some order when order.FundId <> fundId ->
                    transaction.Rollback()
                    ConfirmOrderNotFound
                | Some order ->
                    if order.Status = "confirmed" then
                        match order.ConfirmIdempotencyKey with
                        | Some storedKey when storedKey = idempotencyKey ->
                            transaction.Commit()
                            ConfirmReplayed order
                        | _ ->
                            match findConfirmIdempotency connection (Some transaction) idempotencyKey with
                            | Some(_, _, storedOrderId) when storedOrderId = orderId ->
                                transaction.Commit()
                                ConfirmReplayed order
                            | Some _ ->
                                transaction.Rollback()
                                ConfirmIdempotencyConflict
                            | None ->
                                transaction.Rollback()
                                ConfirmAlreadyConfirmed
                    elif order.Status <> "submitted" && order.Status <> "pending_nav" then
                        transaction.Rollback()
                        ConfirmInvalidStatus
                    else
                        match findConfirmIdempotency connection (Some transaction) idempotencyKey with
                        | Some _ ->
                            transaction.Rollback()
                            ConfirmIdempotencyConflict
                        | None ->
                            let tradeDate = order.TradeDate
                            let tradeDateText = tradeDate.ToString("yyyy-MM-dd")

                            use quoteCommand =
                                commandWithTransaction
                                    connection
                                    (Some transaction)
                                    """
                                    SELECT o.nav, o.nav_date, o.source, o.source_revision, o.source_collected_at, o.published_at,
                                           o.source_payload_hash, o.first_seen_at, e.first_seen_at
                                    FROM fund_nav_observations o
                                    LEFT JOIN fund_nav_observation_evidence e
                                        ON e.instrument_code = o.instrument_code
                                       AND e.nav_date = o.nav_date
                                       AND e.source_payload_hash = o.source_payload_hash
                                    WHERE o.instrument_code = @code AND o.nav_date = @trade_date AND o.nav > 0
                                    ORDER BY o.source_collected_at DESC, o.published_at DESC NULLS LAST, o.source_revision DESC
                                    LIMIT 1
                                    """

                            addParameter quoteCommand "code" NpgsqlDbType.Text (box order.FundCode) |> ignore
                            addParameter quoteCommand "trade_date" NpgsqlDbType.Date (box tradeDate) |> ignore

                            use quoteReader = quoteCommand.ExecuteReader()
                            let quoteFound = quoteReader.Read()

                            let selectedQuote, evidenceFirstSeen =
                                if quoteFound then
                                    let evidenceFirstSeen =
                                        if quoteReader.IsDBNull(8) then
                                            None
                                        else
                                            Some(quoteReader.GetFieldValue<DateTimeOffset>(8))

                                    Some
                                        {
                                            Nav = quoteReader.GetDecimal(0)
                                            NavDate = quoteReader.GetFieldValue<DateOnly>(1)
                                            Source = quoteReader.GetString(2)
                                            Revision = quoteReader.GetString(3)
                                            CollectedAt = quoteReader.GetFieldValue<DateTimeOffset>(4)
                                            PublishedAt =
                                                if quoteReader.IsDBNull(5) then
                                                    None
                                                else
                                                    Some(quoteReader.GetFieldValue<DateTimeOffset>(5))
                                            PayloadHash = quoteReader.GetString(6)
                                            FirstSeenAt = quoteReader.GetFieldValue<DateTimeOffset>(7)
                                        },
                                    evidenceFirstSeen
                                else
                                    None, None

                            quoteReader.Close()

                            let boundQuote =
                                match selectedQuote, evidenceFirstSeen with
                                | Some quote, Some firstSeen -> Some { quote with FirstSeenAt = firstSeen }
                                | _ -> None

                            let deferralReason =
                                if selectedQuote.IsSome && evidenceFirstSeen.IsNone then
                                    Some(
                                        sprintf
                                            "nav revision for trade date %s has no observation evidence recorded"
                                            tradeDateText
                                    )
                                else
                                    match boundQuote with
                                    | None -> Some(sprintf "nav for trade date %s is not available yet" tradeDateText)
                                    | Some quote when quote.FirstSeenAt > confirmedAt ->
                                        Some(
                                            sprintf
                                                "nav revision for trade date %s was first observed after the confirmation attempt"
                                                tradeDateText
                                        )
                                    | Some quote ->
                                        ConfirmationPolicy.navDeferralReason
                                            {
                                                Nav = quote.Nav
                                                NavDate = quote.NavDate
                                                CollectedAt = quote.CollectedAt
                                                PublishedAt = quote.PublishedAt
                                            }
                                            tradeDate
                                            today
                                            confirmedAt

                            let markPending reason =
                                use pendingCommand =
                                    commandWithTransaction
                                        connection
                                        (Some transaction)
                                        """
                                        UPDATE subscription_orders
                                        SET status = 'pending_nav',
                                            pending_reason = @reason,
                                            confirm_idempotency_key = NULL,
                                            confirmed_at = NULL,
                                            confirmed_nav = NULL,
                                            confirmed_nav_date = NULL,
                                            confirmed_nav_source = NULL,
                                            confirmed_nav_revision = NULL,
                                            confirmed_nav_collected_at = NULL,
                                            confirmed_nav_published_at = NULL,
                                            confirmed_nav_payload_hash = NULL,
                                            confirmed_nav_first_seen_at = NULL,
                                            confirmed_units = NULL,
                                            confirmed_invested_cash = NULL,
                                            confirmed_residual_cash = NULL
                                        WHERE id = @order_id
                                        """

                                addParameter pendingCommand "reason" NpgsqlDbType.Text (box reason) |> ignore
                                addParameter pendingCommand "order_id" NpgsqlDbType.Uuid (box orderId) |> ignore
                                pendingCommand.ExecuteNonQuery() |> ignore

                            let readPendingAfterCommit () =
                                match findOrder connection None orderId with
                                | Some pendingOrder -> ConfirmPendingNav pendingOrder
                                | None -> failwith "pending order disappeared after confirmation deferral"

                            match deferralReason with
                            | Some reason ->
                                markPending reason
                                transaction.Commit()
                                readPendingAfterCommit ()
                            | None ->
                                let quote = boundQuote |> Option.get
                                let source = quote.Source
                                let revision = quote.Revision

                                match ConfirmationPolicy.compute order.Amount quote.Nav with
                                | Error message ->
                                    markPending message
                                    transaction.Commit()
                                    readPendingAfterCommit ()
                                | Ok computation ->
                                    use cashCommand =
                                        commandWithTransaction
                                            connection
                                            (Some transaction)
                                            """
                                            UPDATE funds
                                            SET available_cash = available_cash + @residual,
                                                reserved_cash = reserved_cash - @reserved_total
                                            WHERE id = @fund_id AND reserved_cash >= @reserved_total
                                            """

                                    addParameter cashCommand "residual" NpgsqlDbType.Numeric (box computation.ResidualCash) |> ignore
                                    addParameter cashCommand "reserved_total" NpgsqlDbType.Numeric (box order.ReservedTotal) |> ignore
                                    addParameter cashCommand "fund_id" NpgsqlDbType.Uuid (box fundId) |> ignore

                                    if cashCommand.ExecuteNonQuery() = 0 then
                                        failwith "insufficient reserved cash for order confirmation"

                                    let publishedParameter =
                                        match quote.PublishedAt with
                                        | Some published -> box published
                                        | None -> box DBNull.Value

                                    use confirmCommand =
                                        commandWithTransaction
                                            connection
                                            (Some transaction)
                                            """
                                            UPDATE subscription_orders
                                            SET status = 'confirmed',
                                                pending_reason = NULL,
                                                confirm_idempotency_key = @idempotency_key,
                                                confirmed_at = @confirmed_at,
                                                confirmed_nav = @nav,
                                                confirmed_nav_date = @nav_date,
                                                confirmed_nav_source = @source,
                                                confirmed_nav_revision = @revision,
                                                confirmed_nav_collected_at = @collected_at,
                                                confirmed_nav_published_at = @published_at,
                                                confirmed_nav_payload_hash = @payload_hash,
                                                confirmed_nav_first_seen_at = @first_seen_at,
                                                confirmed_units = @units,
                                                confirmed_invested_cash = @invested,
                                                confirmed_residual_cash = @residual
                                            WHERE id = @order_id
                                            """

                                    addParameter confirmCommand "idempotency_key" NpgsqlDbType.Text (box idempotencyKey) |> ignore
                                    addParameter confirmCommand "confirmed_at" NpgsqlDbType.TimestampTz (box confirmedAt) |> ignore
                                    addParameter confirmCommand "nav" NpgsqlDbType.Numeric (box quote.Nav) |> ignore
                                    addParameter confirmCommand "nav_date" NpgsqlDbType.Date (box quote.NavDate) |> ignore
                                    addParameter confirmCommand "source" NpgsqlDbType.Text (box source) |> ignore
                                    addParameter confirmCommand "revision" NpgsqlDbType.Text (box revision) |> ignore
                                    addParameter confirmCommand "collected_at" NpgsqlDbType.TimestampTz (box quote.CollectedAt) |> ignore
                                    addParameter confirmCommand "published_at" NpgsqlDbType.TimestampTz publishedParameter |> ignore
                                    addParameter confirmCommand "payload_hash" NpgsqlDbType.Text (box quote.PayloadHash) |> ignore
                                    addParameter confirmCommand "first_seen_at" NpgsqlDbType.TimestampTz (box quote.FirstSeenAt) |> ignore
                                    addParameter confirmCommand "units" NpgsqlDbType.Numeric (box computation.Units) |> ignore
                                    addParameter confirmCommand "invested" NpgsqlDbType.Numeric (box computation.InvestedCash) |> ignore
                                    addParameter confirmCommand "residual" NpgsqlDbType.Numeric (box computation.ResidualCash) |> ignore
                                    addParameter confirmCommand "order_id" NpgsqlDbType.Uuid (box orderId) |> ignore
                                    confirmCommand.ExecuteNonQuery() |> ignore

                                    use positionCommand =
                                        commandWithTransaction
                                            connection
                                            (Some transaction)
                                            """
                                            INSERT INTO fund_positions
                                                (fund_id, instrument_code, units, cost_cash, first_confirmed_at, last_confirmed_at)
                                            VALUES
                                                (@fund_id, @code, @units, @invested, @confirmed_at, @confirmed_at)
                                            ON CONFLICT (fund_id, instrument_code) DO UPDATE
                                            SET units = fund_positions.units + EXCLUDED.units,
                                                cost_cash = fund_positions.cost_cash + EXCLUDED.cost_cash,
                                                last_confirmed_at = EXCLUDED.last_confirmed_at
                                            """

                                    addParameter positionCommand "fund_id" NpgsqlDbType.Uuid (box fundId) |> ignore
                                    addParameter positionCommand "code" NpgsqlDbType.Text (box order.FundCode) |> ignore
                                    addParameter positionCommand "units" NpgsqlDbType.Numeric (box computation.Units) |> ignore
                                    addParameter positionCommand "invested" NpgsqlDbType.Numeric (box computation.InvestedCash) |> ignore
                                    addParameter positionCommand "confirmed_at" NpgsqlDbType.TimestampTz (box confirmedAt) |> ignore
                                    positionCommand.ExecuteNonQuery() |> ignore

                                    let publishedJson =
                                        match quote.PublishedAt with
                                        | Some published -> sprintf "\"%O\"" published
                                        | None -> "null"

                                    let detail =
                                        sprintf
                                            "{\"fund_id\":\"%O\",\"order_id\":\"%O\",\"units\":\"%M\",\"invested_cash\":\"%M\",\"residual_cash\":\"%M\",\"quote\":{\"nav_date\":\"%s\",\"nav\":\"%M\",\"source\":%s,\"source_revision\":%s,\"source_collected_at\":\"%O\",\"published_at\":%s,\"source_payload_hash\":%s,\"first_seen_at\":\"%O\"}}"
                                            fundId
                                            orderId
                                            computation.Units
                                            computation.InvestedCash
                                            computation.ResidualCash
                                            (quote.NavDate.ToString("yyyy-MM-dd"))
                                            quote.Nav
                                            (JsonSerializer.Serialize source)
                                            (JsonSerializer.Serialize revision)
                                            quote.CollectedAt
                                            publishedJson
                                            (JsonSerializer.Serialize quote.PayloadHash)
                                            quote.FirstSeenAt

                                    use eventCommand =
                                        commandWithTransaction
                                            connection
                                            (Some transaction)
                                            """
                                            INSERT INTO subscription_order_events (order_id, event_type, detail)
                                            VALUES (@order_id, 'confirmed', @detail)
                                            """

                                    addParameter eventCommand "order_id" NpgsqlDbType.Uuid (box orderId) |> ignore
                                    addParameter eventCommand "detail" NpgsqlDbType.Jsonb (box detail) |> ignore
                                    eventCommand.ExecuteNonQuery() |> ignore

                                    use idempotencyCommand =
                                        commandWithTransaction
                                            connection
                                            (Some transaction)
                                            """
                                            INSERT INTO subscription_confirm_idempotencies
                                                (idempotency_key, request_hash, order_id, fund_id)
                                            VALUES
                                                (@idempotency_key, @request_hash, @order_id, @fund_id)
                                            """

                                    addParameter idempotencyCommand "idempotency_key" NpgsqlDbType.Text (box idempotencyKey) |> ignore
                                    addParameter idempotencyCommand "request_hash" NpgsqlDbType.Text (box requestHash) |> ignore
                                    addParameter idempotencyCommand "order_id" NpgsqlDbType.Uuid (box orderId) |> ignore
                                    addParameter idempotencyCommand "fund_id" NpgsqlDbType.Uuid (box fundId) |> ignore
                                    idempotencyCommand.ExecuteNonQuery() |> ignore

                                    transaction.Commit()

                                    match findOrder connection None orderId with
                                    | Some confirmedOrder -> OrderConfirmed confirmedOrder
                                    | None -> failwith "confirmed order disappeared after commit"
            with error ->
                try
                    transaction.Rollback()
                with _ ->
                    ()

                raise error

    member _.GetFundPositions(fundId: Guid) : FundPositionRecord list =
        use connection = new NpgsqlConnection(connectionString)
        connection.Open()

        use command =
            commandWithTransaction
                connection
                None
                """
                SELECT p.instrument_code, p.units, p.reserved_units, p.cost_cash, p.last_confirmed_at,
                       q.nav, q.nav_date, q.source_collected_at
                FROM fund_positions p
                LEFT JOIN LATERAL (
                    SELECT nav, nav_date, source_collected_at
                    FROM fund_nav_observations
                    WHERE instrument_code = p.instrument_code
                      AND nav_date <= (now() AT TIME ZONE 'Asia/Shanghai')::date
                      AND nav > 0
                      AND source_collected_at <= now()
                      AND (published_at IS NULL OR published_at <= now())
                    ORDER BY nav_date DESC, source_collected_at DESC
                    LIMIT 1
                ) q ON true
                WHERE p.fund_id = @fund_id
                ORDER BY p.instrument_code
                """

        addParameter command "fund_id" NpgsqlDbType.Uuid (box fundId) |> ignore

        use reader = command.ExecuteReader()
        let records = ResizeArray<FundPositionRecord>()

        while reader.Read() do
            let valuationNav =
                if reader.IsDBNull(5) then None else Some(reader.GetDecimal(5))

            let valuationNavDate =
                if reader.IsDBNull(6) then None else Some(reader.GetFieldValue<DateOnly>(6))

            let valuationCollectedAt =
                if reader.IsDBNull(7) then None else Some(reader.GetFieldValue<DateTimeOffset>(7))

            records.Add(
                {
                    FundId = fundId
                    InstrumentCode = reader.GetString(0)
                    Units = reader.GetDecimal(1)
                    ReservedUnits = reader.GetDecimal(2)
                    CostCash = reader.GetDecimal(3)
                    LastConfirmedAt = reader.GetFieldValue<DateTimeOffset>(4)
                    ValuationNav = valuationNav
                    ValuationNavDate = valuationNavDate
                    ValuationCollectedAt = valuationCollectedAt
                }
            )

        records |> Seq.toList