summaryrefslogtreecommitdiff
path: root/src/FundLab.Web/App.fs
blob: 5e891aefe57686f56b4d3e5608ae38f76597f261 (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
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
module FundLab.Web

open System
open System.Globalization
open Elmish
open Elmish.React
open Feliz
open Fable.Core

type Instrument =
    {
        code: string
        name: string
        fundType: string option
    }

type NavObservation =
    {
        navDate: string
        nav: string
        dailyReturn: string option
    }

type ChartPoint =
    {
        x: float
        y: float
        navDate: string
        nav: string
    }

type SeriesPoint =
    {
        x: float
        y: float
        label: string
        value: string
    }

module Chart =
    let private invariant = CultureInfo.InvariantCulture

    let private navValue (observation: NavObservation) =
        Decimal.Parse(observation.nav, NumberStyles.Float, invariant)

    let chartPoints (observations: NavObservation list) =
        let ordered: NavObservation list = observations |> List.sortBy (fun observation -> observation.navDate)
        let values = ordered |> List.map navValue

        match values with
        | [] -> []
        | _ ->
            let minimum = List.min values
            let maximum = List.max values
            let range = maximum - minimum
            let count = List.length ordered

            ordered
            |> List.mapi (fun index observation ->
                let value = navValue observation
                let x =
                    if count = 1 then
                        0.5
                    else
                        float index / float (count - 1)

                let y =
                    if range = 0M then
                        0.5
                    else
                        float ((value - minimum) / range)

                {
                    x = x
                    y = y
                    navDate = observation.navDate
                    nav = observation.nav
                })

    /// Normalizes one named series over a shared, already ordered date axis. Dates
    /// without a value are omitted (a gap, never a zero). `x` is the position on the
    /// full axis so two series stay aligned; `y` is normalized within the series.
    let seriesPoints (dates: string list) (values: (string * string) list) : SeriesPoint list =
        let parsed =
            values
            |> List.choose (fun (date, text) ->
                match Decimal.TryParse(text, NumberStyles.Float, invariant) with
                | true, value -> Some(date, value, text)
                | false, _ -> None)

        match parsed with
        | [] -> []
        | _ ->
            let numbers = parsed |> List.map (fun (_, value, _) -> value)
            let minimum = List.min numbers
            let maximum = List.max numbers
            let range = maximum - minimum
            let count = List.length dates
            let lookup = parsed |> List.map (fun (date, value, text) -> date, (value, text)) |> Map.ofList

            dates
            |> List.mapi (fun index date ->
                match Map.tryFind date lookup with
                | None -> None
                | Some(value, text) ->
                    let x = if count <= 1 then 0.5 else float index / float (count - 1)
                    let y = if range = 0M then 0.5 else float ((value - minimum) / range)
                    Some { x = x; y = y; label = date; value = text })
            |> List.choose id

type RawOptionalText =
    {
        case: string
        fields: string array
    }

type RawInstrument =
    {
        code: string
        name: string
        fundType: obj
    }

type RawSearchResponse =
    {
        instruments: RawInstrument array
    }

type RawObservation =
    {
        navDate: string
        nav: string
        dailyReturn: obj
    }

type RawNavResponse =
    {
        observations: RawObservation array
    }

type CreateFundPayload =
    {
        idempotencyKey: string
        name: string
        initialCash: string
        initialUnitNav: string
        isSynthetic: bool
    }

type FundSummary =
    {
        id: string
        name: string
        currency: string
        initialCash: string
        initialUnitNav: string
        isSynthetic: bool
        availableCash: string
        reservedCash: string
        status: string
    }

type CreateOrderPayload =
    {
        idempotencyKey: string
        fundCode: string
        amount: string
        feeAmount: string
    }

type RawOrder =
    {
        id: string
        fundCode: string
        amount: string
        feeAmount: string
        reservedTotal: string
        status: string
        submittedAt: string
        tradeDate: string
        pendingReason: obj
        confirmedAt: obj
        confirmedNav: obj
        confirmedNavDate: obj
        confirmedUnits: obj
        confirmedInvestedCash: obj
        confirmedResidualCash: obj
    }

type RawPosition =
    {
        instrumentCode: string
        units: string
        reservedUnits: string
        costCash: string
        lastConfirmedAt: string
        valuationNav: obj
        valuationNavDate: obj
        valuationCollectedAt: obj
    }

type RawRebalanceTarget =
    {
        instrumentCode: string
        targetPercent: string
    }

type RawRebalanceOutcome =
    {
        instrumentCode: string
        action: string
        amount: string
        status: string
        orderId: obj
        pendingReason: obj
    }

type RawRebalanceExecution =
    {
        planId: string
        runDate: string
        outcomes: RawRebalanceOutcome array
    }

type RawRebalanceExecutionRecord =
    {
        planId: string
        runDate: string
        instrumentCode: string
        action: string
        amount: string
        status: string
        orderId: obj
        pendingReason: obj
        executedAt: string
    }

type RawRebalanceWeightRow =
    {
        instrumentCode: string
        targetPercent: string
        currentValue: string
        currentPercent: string
        action: string
        deltaAmount: string
        deltaUnits: obj
    }

type RawRebalancePreview =
    {
        planId: string
        runDate: string
        availableCash: string
        equity: string
        rows: RawRebalanceWeightRow array
    }

type RawSipPlan =
    {
        id: string
        instrumentCode: string
        amount: string
        frequency: string
        status: string
        anchorDate: string
        nextTradeDate: string
        lastExecutionStatus: obj
        lastExecutionDate: obj
    }

type RawInvestmentPlan =
    {
        id: string
        fundId: string
        instrumentCode: string
        amount: string
        frequency: string
        status: string
        anchorDate: string
        nextRunDate: string
        lastRunStatus: obj
        lastRunDate: obj
        isSynthetic: bool
        createdAt: string
    }

type RawInvestmentPlanRunOutcome =
    {
        runDate: string
        status: string
        orderId: obj
        pendingReason: obj
    }

type RawInvestmentPlanRunPlan =
    {
        planId: string
        instrumentCode: string
        amount: string
        frequency: string
        runs: RawInvestmentPlanRunOutcome array
        nextRunDate: string
    }

type RawInvestmentPlanRun =
    {
        fundId: string
        processingDate: string
        plans: RawInvestmentPlanRunPlan array
    }

type RawRedemption =
    {
        id: string
        instrumentCode: string
        units: string
        feeAmount: string
        status: string
        submittedAt: string
        tradeDate: string
        pendingReason: obj
        confirmedAt: obj
        confirmedNav: obj
        confirmedNavDate: obj
        confirmedProceeds: obj
        confirmedCostReleased: obj
    }

type RawDividend =
    {
        id: string
        fundId: string
        instrumentCode: string
        navDate: string
        dps: string
        mode: string
        sourceKey: string
        status: string
        grossCash: obj
        creditedUnits: obj
        creditedInvested: obj
        orderId: obj
        pendingReason: obj
        isSynthetic: bool
        createdAt: string
    }

type RawPositions =
    {
        availableCash: string
        reservedCash: string
        positions: RawPosition array
    }

type RawReturnsPoint =
    {
        date: string
        pending: bool
        totalAssets: obj
        unitNav: obj
        cash: string
        reservedCash: string
        holdingsValue: obj
        cumulativeReturn: obj
        netExternalFlow: string
    }

type RawReturns =
    {
        fundId: string
        pending: bool
        dataUpdatedAt: obj
        points: RawReturnsPoint array
    }

type RawMarketNavDates =
    {
        code: string
        dates: string array
    }

type RawMarketNavSeriesPoint =
    {
        navDate: string
        nav: string
        accumulatedNav: obj
    }

type RawMarketNavSeries =
    {
        code: string
        points: RawMarketNavSeriesPoint array
    }

type RawBondQuote =
    {
        code: string
        name: obj
        price: obj
        cleanPrice: obj
        accruedInterest: obj
        date: obj
        maturityDate: obj
        parValue: obj
        valueDate: obj
        couponRate: obj
        rating: obj
        dataStatus: obj
        accruedInterestComputed: obj
        dirtyPrice: obj
        valuationDate: obj
    }

type RawStockQuote =
    {
        code: string
        name: obj
        price: obj
        currency: string
    }

type RawStockDailyObservation =
    {
        date: string
        close: string
        volume: obj
        amount: obj
    }

type RawStockDaily =
    {
        code: string
        observations: RawStockDailyObservation array
    }

type RawStockTrade =
    {
        id: string
        fundId: string
        instrumentCode: string
        stockName: obj
        quantity: string
        price: string
        costCash: string
        executedAt: string
        isSynthetic: bool
    }

type RawStockPosition =
    {
        instrumentCode: string
        stockName: obj
        quantity: string
        costCash: string
        lastTradedAt: string
    }

type RawStockPositions =
    {
        fundId: string
        positions: RawStockPosition array
    }

type RawStockSell =
    {
        id: string
        fundId: string
        instrumentCode: string
        stockName: obj
        quantity: string
        price: string
        feeAmount: string
        proceeds: string
        executedAt: string
        isSynthetic: bool
    }

type RawBondTrade =
    {
        id: string
        fundId: string
        instrumentCode: string
        bondName: obj
        quantity: string
        price: string
        costCash: string
        executedAt: string
        isSynthetic: bool
    }

type RawBondPosition =
    {
        instrumentCode: string
        bondName: obj
        quantity: string
        costCash: string
        lastTradedAt: string
    }

type RawBondPositions =
    {
        fundId: string
        positions: RawBondPosition array
    }

type RawValuationPosition =
    {
        instrumentCode: string
        name: obj
        assetClass: string
        quantity: string
        price: obj
        priceSource: obj
        marketValue: obj
        status: string
    }

type RawFundValuation =
    {
        fundId: string
        currency: string
        cash: string
        positionsMarketValue: string
        portfolioValue: string
        pricedPositions: int
        unavailablePositions: int
        positions: RawValuationPosition array
    }

type RawMarketRefreshTarget =
    {
        instrumentCode: string
        assetClass: string
        snapshotDate: string
        price: string
    }

type RawMarketRefreshFailure =
    {
        instrumentCode: string
        assetClass: string
        reason: string
    }

type RawMarketRefresh =
    {
        fundId: string
        asOfDate: string
        refreshed: RawMarketRefreshTarget array
        failures: RawMarketRefreshFailure array
    }

type CreateAttempt =
    {
        idempotencyKey: string
        name: string
        cash: string
    }

type OrderAttempt =
    {
        idempotencyKey: string
        fundCode: string
        amount: string
        feeAmount: string
    }

type ConfirmAttempt =
    {
        idempotencyKey: string
        orderId: string
    }

type RedemptionAttempt =
    {
        idempotencyKey: string
        instrumentCode: string
        units: string
        feeAmount: string
    }

type RedemptionConfirmAttempt =
    {
        idempotencyKey: string
        orderId: string
    }

type CreateRedemptionPayload =
    {
        idempotencyKey: string
        instrumentCode: string
        units: string
        feeAmount: string
    }

type CapitalAttempt =
    {
        idempotencyKey: string
        amount: string
    }

type CreateCapitalPayload =
    {
        idempotencyKey: string
        amount: string
        note: string
    }

type RawRebalancePlan =
    {
        id: string
        fundId: string
        targets: RawRebalanceTarget array
        status: string
        createdAt: string
    }

type SipAttempt =
    {
        idempotencyKey: string
        instrumentCode: string
        amount: string
        frequency: string
    }

type CreateSipPayload =
    {
        idempotencyKey: string
        instrumentCode: string
        amount: string
        frequency: string
    }

type CreateStockTradePayload =
    {
        idempotencyKey: string
        instrumentCode: string
        quantity: string
    }

type CreateStockSellPayload =
    {
        idempotencyKey: string
        instrumentCode: string
        quantity: string
    }

type StockSellAttempt =
    {
        idempotencyKey: string
        instrumentCode: string
        quantity: string
    }

type CreateBondTradePayload =
    {
        idempotencyKey: string
        instrumentCode: string
        quantity: string
    }

type SipPlan =
    {
        id: string
        instrumentCode: string
        amount: string
        frequency: string
        status: string
        anchorDate: string
        nextTradeDate: string
        lastExecutionStatus: string option
        lastExecutionDate: string option
    }

type InvestmentPlan =
    {
        id: string
        instrumentCode: string
        amount: string
        frequency: string
        status: string
        anchorDate: string
        nextRunDate: string
        lastRunStatus: string option
        lastRunDate: string option
    }

type InvestmentPlanRunOutcome =
    {
        runDate: string
        status: string
        orderId: string option
        pendingReason: string option
    }

type InvestmentPlanRunPlan =
    {
        planId: string
        instrumentCode: string
        amount: string
        frequency: string
        runs: InvestmentPlanRunOutcome list
        nextRunDate: string
    }

type InvestmentPlanRun =
    {
        fundId: string
        processingDate: string
        plans: InvestmentPlanRunPlan list
    }

type RebalanceTarget =
    {
        instrumentCode: string
        targetPercent: string
    }

type RebalanceOutcome =
    {
        instrumentCode: string
        action: string
        amount: string
        status: string
        orderId: string option
        pendingReason: string option
    }

type RebalancePlan =
    {
        id: string
        targets: RebalanceTarget list
        status: string
        createdAt: string
    }

type CreateRebalancePayload =
    {
        idempotencyKey: string
        targets: RebalanceTarget array
    }

type RebalanceTargetDraft =
    {
        code: string
        percent: string
    }

type RebalanceExecutionRecord =
    {
        planId: string
        runDate: string
        instrumentCode: string
        action: string
        amount: string
        status: string
        orderId: string option
        pendingReason: string option
        executedAt: string
    }

type RebalanceWeightRow =
    {
        instrumentCode: string
        targetPercent: string
        currentValue: string
        currentPercent: string
        action: string
        deltaAmount: string
        deltaUnits: string option
    }

type RebalancePreview =
    {
        planId: string
        runDate: string
        availableCash: string
        equity: string
        rows: RebalanceWeightRow list
    }

type OrderDetail =
    {
        id: string
        fundCode: string
        amount: string
        feeAmount: string
        reservedTotal: string
        status: string
        submittedAt: string
        tradeDate: string
        pendingReason: string option
        confirmedAt: string option
        confirmedNav: string option
        confirmedNavDate: string option
        confirmedUnits: string option
        confirmedInvestedCash: string option
        confirmedResidualCash: string option
    }

type Position =
    {
        instrumentCode: string
        units: string
        reservedUnits: string
        costCash: string
        lastConfirmedAt: string
        valuationNav: string option
        valuationNavDate: string option
    }

type RedemptionDetail =
    {
        id: string
        instrumentCode: string
        units: string
        feeAmount: string
        status: string
        submittedAt: string
        tradeDate: string
        pendingReason: string option
        confirmedAt: string option
        confirmedNav: string option
        confirmedNavDate: string option
        confirmedProceeds: string option
        confirmedCostReleased: string option
    }

type DividendRecord =
    {
        id: string
        instrumentCode: string
        navDate: string
        dps: string
        mode: string
        sourceKey: string
        status: string
        grossCash: string option
        creditedUnits: string option
        creditedInvested: string option
        orderId: string option
        pendingReason: string option
        isSynthetic: bool
        createdAt: string
    }

type Positions =
    {
        availableCash: string
        reservedCash: string
        positions: Position list
    }

type ReturnsPoint =
    {
        date: string
        pending: bool
        totalAssets: string option
        unitNav: string option
        cash: string
        reservedCash: string
        holdingsValue: string option
        cumulativeReturn: string option
        netExternalFlow: string
    }

type FundReturns =
    {
        pending: bool
        dataUpdatedAt: string option
        points: ReturnsPoint list
    }

type MarketNavSeriesPoint =
    {
        navDate: string
        nav: string
        accumulatedNav: string option
    }

type BondQuoteView =
    {
        code: string
        name: string option
        price: string option
        cleanPrice: string option
        accruedInterest: string option
        quoteDate: string option
        maturityDate: string option
        parValue: string option
        valueDate: string option
        couponRate: string option
        rating: string option
        dataStatus: string option
        accruedInterestComputed: string option
        dirtyPrice: string option
        valuationDate: string option
    }

type StockQuoteView =
    {
        code: string
        name: string option
        price: string option
        currency: string
    }

type StockDailyBar =
    {
        date: string
        close: string
        volume: string option
        amount: string option
    }

type StockTradeView =
    {
        id: string
        instrumentCode: string
        stockName: string option
        quantity: string
        price: string
        costCash: string
        executedAt: string
    }

type StockPositionView =
    {
        instrumentCode: string
        stockName: string option
        quantity: string
        costCash: string
        lastTradedAt: string
    }

type StockTradeAttempt =
    {
        idempotencyKey: string
        instrumentCode: string
        quantity: string
    }

type BondTradeView =
    {
        id: string
        instrumentCode: string
        bondName: string option
        quantity: string
        price: string
        costCash: string
        executedAt: string
    }

type BondPositionView =
    {
        instrumentCode: string
        bondName: string option
        quantity: string
        costCash: string
        lastTradedAt: string
    }

type ValuationPositionView =
    {
        instrumentCode: string
        name: string option
        assetClass: string
        quantity: string
        price: string option
        priceSource: string option
        marketValue: string option
        status: string
    }

type FundValuationView =
    {
        currency: string
        cash: string
        positionsMarketValue: string
        portfolioValue: string
        pricedPositions: int
        unavailablePositions: int
        positions: ValuationPositionView list
    }

type BondTradeAttempt =
    {
        idempotencyKey: string
        instrumentCode: string
        quantity: string
    }

module Api =
    [<Import("searchInstruments", "./src/api.js")>]
    let searchInstruments (token: string) (query: string) : JS.Promise<RawSearchResponse> = jsNative

    [<Import("getNav", "./src/api.js")>]
    let getNav (token: string) (code: string) : JS.Promise<RawNavResponse> = jsNative

    [<Import("refreshNav", "./src/api.js")>]
    let refreshNav (token: string) (code: string) : JS.Promise<RawNavResponse> = jsNative

    [<Import("createFund", "./src/api.js")>]
    let createFund (token: string) (payload: CreateFundPayload) : JS.Promise<FundSummary> = jsNative

    [<Import("getFund", "./src/api.js")>]
    let getFund (token: string) (fundId: string) : JS.Promise<FundSummary> = jsNative

    [<Import("createOrder", "./src/api.js")>]
    let createOrder (token: string) (fundId: string) (payload: CreateOrderPayload) : JS.Promise<RawOrder> = jsNative

    [<Import("getOrders", "./src/api.js")>]
    let getOrders (token: string) (fundId: string) : JS.Promise<RawOrder array> = jsNative

    [<Import("confirmOrder", "./src/api.js")>]
    let confirmOrder (token: string) (fundId: string) (orderId: string) (idempotencyKey: string) : JS.Promise<RawOrder> = jsNative

    [<Import("getPositions", "./src/api.js")>]
    let getPositions (token: string) (fundId: string) : JS.Promise<RawPositions> = jsNative

    [<Import("createRedemption", "./src/api.js")>]
    let createRedemption (token: string) (fundId: string) (payload: CreateRedemptionPayload) : JS.Promise<RawRedemption> = jsNative

    [<Import("getRedemptions", "./src/api.js")>]
    let getRedemptions (token: string) (fundId: string) : JS.Promise<RawRedemption array> = jsNative

    [<Import("confirmRedemption", "./src/api.js")>]
    let confirmRedemption (token: string) (fundId: string) (orderId: string) (idempotencyKey: string) : JS.Promise<RawRedemption> = jsNative

    [<Import("getDividends", "./src/api.js")>]
    let getDividends (token: string) (fundId: string) : JS.Promise<RawDividend array> = jsNative

    [<Import("getReturns", "./src/api.js")>]
    let getReturns (token: string) (fundId: string) : JS.Promise<RawReturns> = jsNative

    [<Import("getMarketNavDates", "./src/api.js")>]
    let getMarketNavDates (token: string) (code: string) : JS.Promise<RawMarketNavDates> = jsNative

    [<Import("getMarketNavSeries", "./src/api.js")>]
    let getMarketNavSeries (token: string) (code: string) : JS.Promise<RawMarketNavSeries> = jsNative

    [<Import("getBondQuote", "./src/api.js")>]
    let getBondQuote (token: string) (code: string) : JS.Promise<RawBondQuote> = jsNative

    [<Import("getStockQuote", "./src/api.js")>]
    let getStockQuote (token: string) (code: string) : JS.Promise<RawStockQuote> = jsNative

    [<Import("getStockDaily", "./src/api.js")>]
    let getStockDaily (token: string) (code: string) (days: int) : JS.Promise<RawStockDaily> = jsNative

    [<Import("createStockTrade", "./src/api.js")>]
    let createStockTrade (token: string) (fundId: string) (payload: CreateStockTradePayload) : JS.Promise<RawStockTrade> = jsNative

    [<Import("getStockPositions", "./src/api.js")>]
    let getStockPositions (token: string) (fundId: string) : JS.Promise<RawStockPositions> = jsNative

    [<Import("createStockSell", "./src/api.js")>]
    let createStockSell (token: string) (fundId: string) (payload: CreateStockSellPayload) : JS.Promise<RawStockSell> = jsNative

    [<Import("createBondTrade", "./src/api.js")>]
    let createBondTrade (token: string) (fundId: string) (payload: CreateBondTradePayload) : JS.Promise<RawBondTrade> = jsNative

    [<Import("getBondPositions", "./src/api.js")>]
    let getBondPositions (token: string) (fundId: string) : JS.Promise<RawBondPositions> = jsNative

    [<Import("getFundValuation", "./src/api.js")>]
    let getFundValuation (token: string) (fundId: string) : JS.Promise<RawFundValuation> = jsNative

    [<Import("refreshFundMarketData", "./src/api.js")>]
    let refreshFundMarketData (token: string) (fundId: string) : JS.Promise<RawMarketRefresh> = jsNative

    [<Import("createCapitalDeposit", "./src/api.js")>]
    let createCapitalDeposit (token: string) (fundId: string) (payload: CreateCapitalPayload) : JS.Promise<obj> = jsNative

    [<Import("createRebalancePlan", "./src/api.js")>]
    let createRebalancePlan (token: string) (fundId: string) (payload: CreateRebalancePayload) : JS.Promise<RawRebalancePlan> = jsNative

    [<Import("getRebalancePlans", "./src/api.js")>]
    let getRebalancePlans (token: string) (fundId: string) : JS.Promise<RawRebalancePlan array> = jsNative

    [<Import("archiveRebalancePlan", "./src/api.js")>]
    let archiveRebalancePlan (token: string) (fundId: string) (planId: string) : JS.Promise<RawRebalancePlan> = jsNative

    [<Import("executeRebalancePlan", "./src/api.js")>]
    let executeRebalancePlan (token: string) (fundId: string) (planId: string) : JS.Promise<RawRebalanceExecution> = jsNative

    [<Import("previewRebalancePlan", "./src/api.js")>]
    let previewRebalancePlan (token: string) (fundId: string) (planId: string) : JS.Promise<RawRebalancePreview> = jsNative

    [<Import("getRebalanceExecutions", "./src/api.js")>]
    let getRebalanceExecutions (token: string) (fundId: string) : JS.Promise<RawRebalanceExecutionRecord array> = jsNative

    [<Import("createSipPlan", "./src/api.js")>]
    let createSipPlan (token: string) (fundId: string) (payload: CreateSipPayload) : JS.Promise<RawSipPlan> = jsNative

    [<Import("getSipPlans", "./src/api.js")>]
    let getSipPlans (token: string) (fundId: string) : JS.Promise<RawSipPlan array> = jsNative

    [<Import("pauseSipPlan", "./src/api.js")>]
    let pauseSipPlan (token: string) (fundId: string) (planId: string) : JS.Promise<RawSipPlan> = jsNative

    [<Import("resumeSipPlan", "./src/api.js")>]
    let resumeSipPlan (token: string) (fundId: string) (planId: string) : JS.Promise<RawSipPlan> = jsNative

    [<Import("getInvestmentPlans", "./src/api.js")>]
    let getInvestmentPlans (token: string) (fundId: string) : JS.Promise<RawInvestmentPlan array> = jsNative

    [<Import("runInvestmentPlans", "./src/api.js")>]
    let runInvestmentPlans (token: string) (fundId: string) : JS.Promise<RawInvestmentPlanRun> = jsNative

    let decodeOptionalText (raw: obj) : string option =
        if isNull raw then
            None
        else
            match raw with
            | :? string as value -> Some value
            | _ ->
                let envelope = unbox<RawOptionalText> raw

                if isNull (box envelope.fields) || envelope.fields.Length = 0 then
                    None
                else
                    Some envelope.fields[0]

    let decodeInstrument (raw: RawInstrument) : Instrument =
        {
            code = raw.code
            name = raw.name
            fundType = decodeOptionalText raw.fundType
        }

    let decodeSearch (raw: RawSearchResponse) : Instrument list =
        raw.instruments |> Array.map decodeInstrument |> List.ofArray

    let decodeObservation (raw: RawObservation) : NavObservation =
        {
            navDate = raw.navDate
            nav = raw.nav
            dailyReturn = decodeOptionalText raw.dailyReturn
        }

    let decodeNav (raw: RawNavResponse) : NavObservation list =
        raw.observations |> Array.map decodeObservation |> List.ofArray

    let decodeOrder (raw: RawOrder) : OrderDetail =
        {
            id = raw.id
            fundCode = raw.fundCode
            amount = raw.amount
            feeAmount = raw.feeAmount
            reservedTotal = raw.reservedTotal
            status = raw.status
            submittedAt = raw.submittedAt
            tradeDate = raw.tradeDate
            pendingReason = decodeOptionalText raw.pendingReason
            confirmedAt = decodeOptionalText raw.confirmedAt
            confirmedNav = decodeOptionalText raw.confirmedNav
            confirmedNavDate = decodeOptionalText raw.confirmedNavDate
            confirmedUnits = decodeOptionalText raw.confirmedUnits
            confirmedInvestedCash = decodeOptionalText raw.confirmedInvestedCash
            confirmedResidualCash = decodeOptionalText raw.confirmedResidualCash
        }

    let decodePosition (raw: RawPosition) : Position =
        {
            instrumentCode = raw.instrumentCode
            units = raw.units
            reservedUnits = raw.reservedUnits
            costCash = raw.costCash
            lastConfirmedAt = raw.lastConfirmedAt
            valuationNav = decodeOptionalText raw.valuationNav
            valuationNavDate = decodeOptionalText raw.valuationNavDate
        }

    let decodePositions (raw: RawPositions) : Positions =
        {
            availableCash = raw.availableCash
            reservedCash = raw.reservedCash
            positions = raw.positions |> Array.map decodePosition |> List.ofArray
        }

    let decodeRebalancePlan (raw: RawRebalancePlan) : RebalancePlan =
        {
            id = raw.id
            targets =
                raw.targets
                |> Array.map (fun target ->
                    {
                        instrumentCode = target.instrumentCode
                        targetPercent = target.targetPercent
                    })
                |> Array.toList
            status = raw.status
            createdAt = raw.createdAt
        }

    let decodeRebalanceOutcome (raw: RawRebalanceOutcome) : RebalanceOutcome =
        {
            instrumentCode = raw.instrumentCode
            action = raw.action
            amount = raw.amount
            status = raw.status
            orderId = decodeOptionalText raw.orderId
            pendingReason = decodeOptionalText raw.pendingReason
        }

    let decodeRebalanceExecutionRecord (raw: RawRebalanceExecutionRecord) : RebalanceExecutionRecord =
        {
            planId = raw.planId
            runDate = raw.runDate
            instrumentCode = raw.instrumentCode
            action = raw.action
            amount = raw.amount
            status = raw.status
            orderId = decodeOptionalText raw.orderId
            pendingReason = decodeOptionalText raw.pendingReason
            executedAt = raw.executedAt
        }

    let decodeRebalanceWeightRow (raw: RawRebalanceWeightRow) : RebalanceWeightRow =
        {
            instrumentCode = raw.instrumentCode
            targetPercent = raw.targetPercent
            currentValue = raw.currentValue
            currentPercent = raw.currentPercent
            action = raw.action
            deltaAmount = raw.deltaAmount
            deltaUnits = decodeOptionalText raw.deltaUnits
        }

    let decodeRebalancePreview (raw: RawRebalancePreview) : RebalancePreview =
        {
            planId = raw.planId
            runDate = raw.runDate
            availableCash = raw.availableCash
            equity = raw.equity
            rows = raw.rows |> Array.map decodeRebalanceWeightRow |> Array.toList
        }

    let decodeSipPlan (raw: RawSipPlan) : SipPlan =
        {
            id = raw.id
            instrumentCode = raw.instrumentCode
            amount = raw.amount
            frequency = raw.frequency
            status = raw.status
            anchorDate = raw.anchorDate
            nextTradeDate = raw.nextTradeDate
            lastExecutionStatus = decodeOptionalText raw.lastExecutionStatus
            lastExecutionDate = decodeOptionalText raw.lastExecutionDate
        }

    let decodeInvestmentPlan (raw: RawInvestmentPlan) : InvestmentPlan =
        {
            id = raw.id
            instrumentCode = raw.instrumentCode
            amount = raw.amount
            frequency = raw.frequency
            status = raw.status
            anchorDate = raw.anchorDate
            nextRunDate = raw.nextRunDate
            lastRunStatus = decodeOptionalText raw.lastRunStatus
            lastRunDate = decodeOptionalText raw.lastRunDate
        }

    let decodeInvestmentPlanRunOutcome (raw: RawInvestmentPlanRunOutcome) : InvestmentPlanRunOutcome =
        {
            runDate = raw.runDate
            status = raw.status
            orderId = decodeOptionalText raw.orderId
            pendingReason = decodeOptionalText raw.pendingReason
        }

    let decodeInvestmentPlanRunPlan (raw: RawInvestmentPlanRunPlan) : InvestmentPlanRunPlan =
        {
            planId = raw.planId
            instrumentCode = raw.instrumentCode
            amount = raw.amount
            frequency = raw.frequency
            runs = raw.runs |> Array.map decodeInvestmentPlanRunOutcome |> Array.toList
            nextRunDate = raw.nextRunDate
        }

    let decodeInvestmentPlanRun (raw: RawInvestmentPlanRun) : InvestmentPlanRun =
        {
            fundId = raw.fundId
            processingDate = raw.processingDate
            plans = raw.plans |> Array.map decodeInvestmentPlanRunPlan |> Array.toList
        }

    let decodeRedemption (raw: RawRedemption) : RedemptionDetail =
        {
            id = raw.id
            instrumentCode = raw.instrumentCode
            units = raw.units
            feeAmount = raw.feeAmount
            status = raw.status
            submittedAt = raw.submittedAt
            tradeDate = raw.tradeDate
            pendingReason = decodeOptionalText raw.pendingReason
            confirmedAt = decodeOptionalText raw.confirmedAt
            confirmedNav = decodeOptionalText raw.confirmedNav
            confirmedNavDate = decodeOptionalText raw.confirmedNavDate
            confirmedProceeds = decodeOptionalText raw.confirmedProceeds
            confirmedCostReleased = decodeOptionalText raw.confirmedCostReleased
        }

    let decodeDividend (raw: RawDividend) : DividendRecord =
        {
            id = raw.id
            instrumentCode = raw.instrumentCode
            navDate = raw.navDate
            dps = raw.dps
            mode = raw.mode
            sourceKey = raw.sourceKey
            status = raw.status
            grossCash = decodeOptionalText raw.grossCash
            creditedUnits = decodeOptionalText raw.creditedUnits
            creditedInvested = decodeOptionalText raw.creditedInvested
            orderId = decodeOptionalText raw.orderId
            pendingReason = decodeOptionalText raw.pendingReason
            isSynthetic = raw.isSynthetic
            createdAt = raw.createdAt
        }

    let decodeReturnsPoint (raw: RawReturnsPoint) : ReturnsPoint =
        {
            date = raw.date
            pending = raw.pending
            totalAssets = decodeOptionalText raw.totalAssets
            unitNav = decodeOptionalText raw.unitNav
            cash = raw.cash
            reservedCash = raw.reservedCash
            holdingsValue = decodeOptionalText raw.holdingsValue
            cumulativeReturn = decodeOptionalText raw.cumulativeReturn
            netExternalFlow = raw.netExternalFlow
        }

    let decodeReturns (raw: RawReturns) : FundReturns =
        {
            pending = raw.pending
            dataUpdatedAt = decodeOptionalText raw.dataUpdatedAt
            points = raw.points |> Array.map decodeReturnsPoint |> Array.toList
        }

    let decodeNavSeriesPoint (raw: RawMarketNavSeriesPoint) : MarketNavSeriesPoint =
        {
            navDate = raw.navDate
            nav = raw.nav
            accumulatedNav = decodeOptionalText raw.accumulatedNav
        }

    let decodeBondQuote (raw: RawBondQuote) : BondQuoteView =
        {
            code = raw.code
            name = decodeOptionalText raw.name
            price = decodeOptionalText raw.price
            cleanPrice = decodeOptionalText raw.cleanPrice
            accruedInterest = decodeOptionalText raw.accruedInterest
            quoteDate = decodeOptionalText raw.date
            maturityDate = decodeOptionalText raw.maturityDate
            parValue = decodeOptionalText raw.parValue
            valueDate = decodeOptionalText raw.valueDate
            couponRate = decodeOptionalText raw.couponRate
            rating = decodeOptionalText raw.rating
            dataStatus = decodeOptionalText raw.dataStatus
            accruedInterestComputed = decodeOptionalText raw.accruedInterestComputed
            dirtyPrice = decodeOptionalText raw.dirtyPrice
            valuationDate = decodeOptionalText raw.valuationDate
        }

    let decodeStockQuote (raw: RawStockQuote) : StockQuoteView =
        {
            code = raw.code
            name = decodeOptionalText raw.name
            price = decodeOptionalText raw.price
            currency = raw.currency
        }

    let decodeStockDailyBar (raw: RawStockDailyObservation) : StockDailyBar =
        {
            date = raw.date
            close = raw.close
            volume = decodeOptionalText raw.volume
            amount = decodeOptionalText raw.amount
        }

    let decodeStockTrade (raw: RawStockTrade) : StockTradeView =
        {
            id = raw.id
            instrumentCode = raw.instrumentCode
            stockName = decodeOptionalText raw.stockName
            quantity = raw.quantity
            price = raw.price
            costCash = raw.costCash
            executedAt = raw.executedAt
        }

    let decodeStockPosition (raw: RawStockPosition) : StockPositionView =
        {
            instrumentCode = raw.instrumentCode
            stockName = decodeOptionalText raw.stockName
            quantity = raw.quantity
            costCash = raw.costCash
            lastTradedAt = raw.lastTradedAt
        }

    let decodeBondTrade (raw: RawBondTrade) : BondTradeView =
        {
            id = raw.id
            instrumentCode = raw.instrumentCode
            bondName = decodeOptionalText raw.bondName
            quantity = raw.quantity
            price = raw.price
            costCash = raw.costCash
            executedAt = raw.executedAt
        }

    let decodeBondPosition (raw: RawBondPosition) : BondPositionView =
        {
            instrumentCode = raw.instrumentCode
            bondName = decodeOptionalText raw.bondName
            quantity = raw.quantity
            costCash = raw.costCash
            lastTradedAt = raw.lastTradedAt
        }

    let decodeValuationPosition (raw: RawValuationPosition) : ValuationPositionView =
        {
            instrumentCode = raw.instrumentCode
            name = decodeOptionalText raw.name
            assetClass = raw.assetClass
            quantity = raw.quantity
            price = decodeOptionalText raw.price
            priceSource = decodeOptionalText raw.priceSource
            marketValue = decodeOptionalText raw.marketValue
            status = raw.status
        }

    let decodeFundValuation (raw: RawFundValuation) : FundValuationView =
        {
            currency = raw.currency
            cash = raw.cash
            positionsMarketValue = raw.positionsMarketValue
            portfolioValue = raw.portfolioValue
            pricedPositions = raw.pricedPositions
            unavailablePositions = raw.unavailablePositions
            positions = raw.positions |> Array.toList |> List.map decodeValuationPosition
        }

type Model =
    {
        token: string
        query: string
        searchSeq: int
        navSeq: int
        searchResults: Instrument list
        selected: Instrument option
        observations: NavObservation list
        searchInFlight: bool
        navInFlight: bool
        fundName: string
        fundCash: string
        fundSeq: int
        fundInFlight: bool
        createdFund: FundSummary option
        lastCreateAttempt: CreateAttempt option
        orderCode: string
        orderAmount: string
        orderFee: string
        orderCreateSeq: int
        orderReadSeq: int
        orderInFlight: bool
        lastOrderAttempt: OrderAttempt option
        orders: OrderDetail list
        confirmSeq: int
        confirmInFlight: bool
        lastConfirmAttempt: ConfirmAttempt option
        positions: Positions option
        positionsSeq: int
        positionsInFlight: bool
        redemptionCode: string
        redemptionUnits: string
        redemptionFee: string
        redemptionCreateSeq: int
        redemptionReadSeq: int
        redemptionInFlight: bool
        lastRedemptionAttempt: RedemptionAttempt option
        redemptions: RedemptionDetail list
        redemptionConfirmSeq: int
        redemptionConfirmInFlight: bool
        lastRedemptionConfirmAttempt: RedemptionConfirmAttempt option
        capitalAmount: string
        capitalSeq: int
        capitalInFlight: bool
        lastCapitalAttempt: CapitalAttempt option
        capitalNote: string option
        sipCode: string
        sipAmount: string
        sipFrequency: string
        sipCreateSeq: int
        sipReadSeq: int
        sipInFlight: bool
        sipStatusSeq: int
        sipStatusInFlight: bool
        lastSipAttempt: SipAttempt option
        sipPlans: SipPlan list
        rebalTargets: RebalanceTargetDraft list
        rebalCreateSeq: int
        rebalReadSeq: int
        rebalArchiveSeq: int
        rebalArchiveInFlight: bool
        rebalInFlight: bool
        rebalExecuteSeq: int
        rebalExecuteInFlight: bool
        rebalPlans: RebalancePlan list
        rebalResult: RebalanceOutcome list option
        rebalPreviewSeq: int
        rebalPreviewInFlight: bool
        rebalPreview: RebalancePreview option
        rebalExecutionsReadSeq: int
        rebalExecutionsInFlight: bool
        rebalExecutions: RebalanceExecutionRecord list
        dividendReadSeq: int
        dividendInFlight: bool
        dividends: DividendRecord list
        returnsReadSeq: int
        returnsInFlight: bool
        returns: FundReturns option
        navDatesReadSeq: int
        navDatesInFlight: bool
        navDates: string list
        navDatesAvailable: bool
        navSeriesReadSeq: int
        navSeriesInFlight: bool
        navSeries: MarketNavSeriesPoint list
        navSeriesAvailable: bool
        bondCode: string
        bondQuoteSeq: int
        bondQuoteInFlight: bool
        bondQuote: BondQuoteView option
        bondQuoteMessage: string option
        stockCode: string
        stockQuoteSeq: int
        stockQuoteInFlight: bool
        stockQuote: StockQuoteView option
        stockQuoteMessage: string option
        stockDailySeq: int
        stockDailyInFlight: bool
        stockDaily: StockDailyBar list
        stockDailyMessage: string option
        stockTradeQuantity: string
        stockTradeSeq: int
        stockTradeInFlight: bool
        lastStockTrade: StockTradeView option
        lastStockTradeAttempt: StockTradeAttempt option
        stockTradeMessage: string option
        stockPositionsReadSeq: int
        stockPositionsInFlight: bool
        stockPositions: StockPositionView list
        stockPositionsMessage: string option
        stockSellQuantities: Map<string, string>
        stockSellAttempts: Map<string, StockSellAttempt>
        stockSellSeq: int
        stockSellInFlight: bool
        stockSellMessage: string option
        bondTradeQuantity: string
        bondTradeSeq: int
        bondTradeInFlight: bool
        lastBondTrade: BondTradeView option
        lastBondTradeAttempt: BondTradeAttempt option
        bondTradeMessage: string option
        bondPositionsReadSeq: int
        bondPositionsInFlight: bool
        bondPositions: BondPositionView list
        bondPositionsMessage: string option
        valuationReadSeq: int
        valuationInFlight: bool
        valuation: FundValuationView option
        valuationMessage: string option
        marketRefreshSeq: int
        marketRefreshInFlight: bool
        marketRefreshMessage: string option
        returnsSelectedDate: string option
        planReadSeq: int
        planInFlight: bool
        planRunSeq: int
        planRunInFlight: bool
        investmentPlans: InvestmentPlan list
        lastPlanRun: InvestmentPlanRun option
        error: string option
    }

type Msg =
    | TokenChanged of string
    | QueryChanged of string
    | SearchRequested
    | SearchCompleted of requestId: int * instruments: Instrument list
    | SearchFailed of requestId: int * message: string
    | InstrumentSelected of Instrument
    | LoadNavRequested
    | RefreshNavRequested
    | NavCompleted of requestId: int * observations: NavObservation list
    | NavFailed of requestId: int * message: string
    | FundNameChanged of string
    | FundCashChanged of string
    | FundCreateRequested
    | FundCreateCompleted of requestId: int * fund: FundSummary
    | FundCreateFailed of requestId: int * message: string
    | FundReadRequested
    | FundReadCompleted of requestId: int * fund: FundSummary
    | FundReadFailed of requestId: int * message: string
    | OrderCodeChanged of string
    | OrderAmountChanged of string
    | OrderFeeChanged of string
    | OrderCreateRequested
    | OrderCreateCompleted of requestId: int * fundId: string * order: RawOrder
    | OrderCreateFailed of requestId: int * fundId: string * message: string
    | OrdersReadRequested
    | OrdersReadCompleted of requestId: int * orders: RawOrder array
    | OrdersReadFailed of requestId: int * message: string
    | OrderConfirmRequested of orderId: string
    | OrderConfirmCompleted of requestId: int * orderId: string * order: RawOrder
    | OrderConfirmFailed of requestId: int * orderId: string * message: string
    | PositionsReadRequested
    | PositionsReadCompleted of requestId: int * positions: RawPositions
    | PositionsReadFailed of requestId: int * message: string
    | RedemptionCodeChanged of string
    | RedemptionUnitsChanged of string
    | RedemptionFeeChanged of string
    | RedemptionCreateRequested
    | RedemptionCreateCompleted of requestId: int * fundId: string * order: RawRedemption
    | RedemptionCreateFailed of requestId: int * fundId: string * message: string
    | RedemptionsReadRequested
    | RedemptionsReadCompleted of requestId: int * orders: RawRedemption array
    | RedemptionsReadFailed of requestId: int * message: string
    | RedemptionConfirmRequested of orderId: string
    | RedemptionConfirmCompleted of requestId: int * orderId: string * order: RawRedemption
    | RedemptionConfirmFailed of requestId: int * orderId: string * message: string
    | CapitalAmountChanged of string
    | CapitalDepositRequested
    | CapitalDepositCompleted of requestId: int * amount: string
    | CapitalDepositFailed of requestId: int * message: string
    | SipCodeChanged of string
    | SipAmountChanged of string
    | SipFrequencyChanged of string
    | SipPlanCreateRequested
    | SipPlanCreateCompleted of requestId: int * fundId: string * plan: RawSipPlan
    | SipPlanCreateFailed of requestId: int * fundId: string * message: string
    | SipPlansReadRequested
    | SipPlansReadCompleted of requestId: int * plans: RawSipPlan array
    | SipPlansReadFailed of requestId: int * message: string
    | SipPlanPauseRequested of planId: string
    | SipPlanResumeRequested of planId: string
    | SipPlanStatusChanged of requestId: int * plan: RawSipPlan
    | SipPlanStatusChangeFailed of requestId: int * message: string
    | RebalTargetCodeChanged of index: int * value: string
    | RebalTargetPercentChanged of index: int * value: string
    | RebalTargetAdded
    | RebalTargetRemoved of index: int
    | RebalancePlanCreateRequested
    | RebalancePlanCreateCompleted of requestId: int * fundId: string * plan: RawRebalancePlan
    | RebalancePlanCreateFailed of requestId: int * fundId: string * message: string
    | RebalancePlansReadRequested
    | RebalancePlansReadCompleted of requestId: int * plans: RawRebalancePlan array
    | RebalancePlansReadFailed of requestId: int * message: string
    | RebalancePlanArchiveRequested of planId: string
    | RebalancePlanArchived of requestId: int * plan: RawRebalancePlan
    | RebalancePlanArchiveFailed of requestId: int * message: string
    | RebalancePreviewRequested of planId: string
    | RebalancePreviewCompleted of requestId: int * preview: RawRebalancePreview
    | RebalancePreviewFailed of requestId: int * message: string
    | RebalanceExecuteRequested of planId: string
    | RebalanceExecuted of requestId: int * result: RawRebalanceExecution
    | RebalanceExecuteFailed of requestId: int * message: string
    | RebalanceExecutionsReadRequested
    | RebalanceExecutionsReadCompleted of requestId: int * records: RawRebalanceExecutionRecord array
    | RebalanceExecutionsReadFailed of requestId: int * message: string
    | DividendsReadRequested
    | DividendsReadCompleted of requestId: int * records: RawDividend array
    | DividendsReadFailed of requestId: int * message: string
    | ReturnsReadRequested
    | ReturnsReadCompleted of requestId: int * returns: RawReturns
    | ReturnsReadFailed of requestId: int * message: string
    | NavDatesReadRequested
    | NavDatesReadCompleted of requestId: int * dates: RawMarketNavDates
    | NavDatesReadFailed of requestId: int * message: string
    | NavSeriesReadRequested
    | NavSeriesReadCompleted of requestId: int * series: RawMarketNavSeries
    | NavSeriesReadFailed of requestId: int * message: string
    | BondCodeChanged of string
    | BondQuoteRequested
    | BondQuoteCompleted of requestId: int * quote: RawBondQuote
    | BondQuoteFailed of requestId: int * message: string
    | StockCodeChanged of string
    | StockQuoteRequested
    | StockQuoteCompleted of requestId: int * quote: RawStockQuote
    | StockQuoteFailed of requestId: int * message: string
    | StockDailyRequested
    | StockDailyCompleted of requestId: int * daily: RawStockDaily
    | StockDailyFailed of requestId: int * message: string
    | StockTradeQuantityChanged of string
    | StockTradeRequested
    | StockTradeCompleted of requestId: int * fundId: string * trade: RawStockTrade
    | StockTradeFailed of requestId: int * fundId: string * message: string
    | StockPositionsReadRequested
    | StockPositionsReadCompleted of requestId: int * fundId: string * positions: RawStockPositions
    | StockPositionsReadFailed of requestId: int * fundId: string * message: string
    | StockSellQuantityChanged of code: string * value: string
    | StockSellRequested of code: string
    | StockSellCompleted of requestId: int * fundId: string * code: string * sell: RawStockSell
    | StockSellFailed of requestId: int * fundId: string * code: string * message: string
    | BondTradeQuantityChanged of string
    | BondTradeRequested
    | BondTradeCompleted of requestId: int * fundId: string * trade: RawBondTrade
    | BondTradeFailed of requestId: int * fundId: string * message: string
    | BondPositionsReadRequested
    | BondPositionsReadCompleted of requestId: int * fundId: string * positions: RawBondPositions
    | BondPositionsReadFailed of requestId: int * fundId: string * message: string
    | ValuationReadRequested
    | ValuationReadCompleted of requestId: int * fundId: string * valuation: RawFundValuation
    | ValuationReadFailed of requestId: int * fundId: string * message: string
    | MarketRefreshRequested
    | MarketRefreshCompleted of requestId: int * fundId: string * response: RawMarketRefresh
    | MarketRefreshFailed of requestId: int * fundId: string * message: string
    | ReturnsDateChanged of string
    | InvestmentPlansReadRequested
    | InvestmentPlansReadCompleted of requestId: int * plans: RawInvestmentPlan array
    | InvestmentPlansReadFailed of requestId: int * message: string
    | InvestmentPlansRunRequested
    | InvestmentPlansRunCompleted of requestId: int * fundId: string * run: RawInvestmentPlanRun
    | InvestmentPlansRunFailed of requestId: int * fundId: string * message: string

let defaultInitialUnitNav = "1.00000000"

let private cashPattern =
    Text.RegularExpressions.Regex("^[0-9]{1,18}(\.[0-9]{1,2})?$", Text.RegularExpressions.RegexOptions.Compiled)

let isValidCashText (text: string) = cashPattern.IsMatch text

let isPositiveCash (text: string) =
    match Decimal.TryParse(text, NumberStyles.Float, CultureInfo.InvariantCulture) with
    | true, value -> value > 0M
    | false, _ -> false

let isNonNegativeCash (text: string) =
    match Decimal.TryParse(text, NumberStyles.Float, CultureInfo.InvariantCulture) with
    | true, value -> value >= 0M
    | false, _ -> false

let private quantityPattern =
    Text.RegularExpressions.Regex("^[0-9]{1,18}$", Text.RegularExpressions.RegexOptions.Compiled)

let isValidQuantityText (text: string) =
    quantityPattern.IsMatch text
    && match Decimal.TryParse(text, NumberStyles.Float, CultureInfo.InvariantCulture) with
       | true, value -> value > 0M
       | false, _ -> false

let resolveCreateKey (lastAttempt: CreateAttempt option) (name: string) (cash: string) =
    match lastAttempt with
    | Some attempt when attempt.name = name && attempt.cash = cash -> attempt.idempotencyKey
    | _ -> Guid.NewGuid().ToString("N")

let resolveOrderKey (lastAttempt: OrderAttempt option) (code: string) (amount: string) (fee: string) =
    match lastAttempt with
    | Some attempt when attempt.fundCode = code && attempt.amount = amount && attempt.feeAmount = fee ->
        attempt.idempotencyKey
    | _ -> Guid.NewGuid().ToString("N")

let init () =
    {
        token = ""
        query = ""
        searchSeq = 0
        navSeq = 0
        searchResults = []
        selected = None
        observations = []
        searchInFlight = false
        navInFlight = false
        fundName = ""
        fundCash = ""
        fundSeq = 0
        fundInFlight = false
        createdFund = None
        lastCreateAttempt = None
        orderCode = ""
        orderAmount = ""
        orderFee = ""
        orderCreateSeq = 0
        orderReadSeq = 0
        orderInFlight = false
        lastOrderAttempt = None
        orders = []
        confirmSeq = 0
        confirmInFlight = false
        lastConfirmAttempt = None
        positions = None
        positionsSeq = 0
        positionsInFlight = false
        redemptionCode = ""
        redemptionUnits = ""
        redemptionFee = ""
        redemptionCreateSeq = 0
        redemptionReadSeq = 0
        redemptionInFlight = false
        lastRedemptionAttempt = None
        redemptions = []
        redemptionConfirmSeq = 0
        redemptionConfirmInFlight = false
        lastRedemptionConfirmAttempt = None
        capitalAmount = ""
        capitalSeq = 0
        capitalInFlight = false
        lastCapitalAttempt = None
        capitalNote = None
        sipCode = ""
        sipAmount = ""
        sipFrequency = "weekly"
        sipCreateSeq = 0
        sipReadSeq = 0
        sipInFlight = false
        sipStatusSeq = 0
        sipStatusInFlight = false
        lastSipAttempt = None
        sipPlans = []
        rebalTargets = [ { code = ""; percent = "" }; { code = ""; percent = "" } ]
        rebalCreateSeq = 0
        rebalReadSeq = 0
        rebalArchiveSeq = 0
        rebalArchiveInFlight = false
        rebalInFlight = false
        rebalExecuteSeq = 0
        rebalExecuteInFlight = false
        rebalPlans = []
        rebalResult = None
        rebalPreviewSeq = 0
        rebalPreviewInFlight = false
        rebalPreview = None
        rebalExecutionsReadSeq = 0
        rebalExecutionsInFlight = false
        rebalExecutions = []
        dividendReadSeq = 0
        dividendInFlight = false
        dividends = []
        returnsReadSeq = 0
        returnsInFlight = false
        returns = None
        navDatesReadSeq = 0
        navDatesInFlight = false
        navDates = []
        navDatesAvailable = false
        navSeriesReadSeq = 0
        navSeriesInFlight = false
        navSeries = []
        navSeriesAvailable = false
        bondCode = ""
        bondQuoteSeq = 0
        bondQuoteInFlight = false
        bondQuote = None
        bondQuoteMessage = None
        stockCode = ""
        stockQuoteSeq = 0
        stockQuoteInFlight = false
        stockQuote = None
        stockQuoteMessage = None
        stockDailySeq = 0
        stockDailyInFlight = false
        stockDaily = []
        stockDailyMessage = None
        stockTradeQuantity = ""
        stockTradeSeq = 0
        stockTradeInFlight = false
        lastStockTrade = None
        lastStockTradeAttempt = None
        stockTradeMessage = None
        stockPositionsReadSeq = 0
        stockPositionsInFlight = false
        stockPositions = []
        stockPositionsMessage = None
        stockSellQuantities = Map.empty
        stockSellAttempts = Map.empty
        stockSellSeq = 0
        stockSellInFlight = false
        stockSellMessage = None
        bondTradeQuantity = ""
        bondTradeSeq = 0
        bondTradeInFlight = false
        lastBondTrade = None
        lastBondTradeAttempt = None
        bondTradeMessage = None
        bondPositionsReadSeq = 0
        bondPositionsInFlight = false
        bondPositions = []
        bondPositionsMessage = None
        valuationReadSeq = 0
        valuationInFlight = false
        valuation = None
        valuationMessage = None
        marketRefreshSeq = 0
        marketRefreshInFlight = false
        marketRefreshMessage = None
        returnsSelectedDate = None
        planReadSeq = 0
        planInFlight = false
        planRunSeq = 0
        planRunInFlight = false
        investmentPlans = []
        lastPlanRun = None
        error = None
    }

let private errorText (error: exn) =
    if String.IsNullOrWhiteSpace error.Message then
        "请求失败"
    else
        error.Message

let private searchCommand token query requestId =
    Cmd.OfPromise.either
        (fun () -> Api.searchInstruments token query)
        ()
        (fun raw -> SearchCompleted(requestId, Api.decodeSearch raw))
        (fun error -> SearchFailed(requestId, errorText error))

let private navCommand token code requestId =
    Cmd.OfPromise.either
        (fun () -> Api.getNav token code)
        ()
        (fun raw -> NavCompleted(requestId, Api.decodeNav raw))
        (fun error -> NavFailed(requestId, errorText error))

let private refreshCommand token code requestId =
    Cmd.OfPromise.either
        (fun () -> Api.refreshNav token code)
        ()
        (fun raw -> NavCompleted(requestId, Api.decodeNav raw))
        (fun error -> NavFailed(requestId, errorText error))

let private createFundCommand token payload requestId =
    Cmd.OfPromise.either
        (fun () -> Api.createFund token payload)
        ()
        (fun fund -> FundCreateCompleted(requestId, fund))
        (fun error -> FundCreateFailed(requestId, errorText error))

let private readFundCommand token fundId requestId =
    Cmd.OfPromise.either
        (fun () -> Api.getFund token fundId)
        ()
        (fun fund -> FundReadCompleted(requestId, fund))
        (fun error -> FundReadFailed(requestId, errorText error))

let private createOrderCommand token fundId payload requestId =
    Cmd.OfPromise.either
        (fun () -> Api.createOrder token fundId payload)
        ()
        (fun order -> OrderCreateCompleted(requestId, fundId, order))
        (fun error -> OrderCreateFailed(requestId, fundId, errorText error))

let private readOrdersCommand token fundId requestId =
    Cmd.OfPromise.either
        (fun () -> Api.getOrders token fundId)
        ()
        (fun orders -> OrdersReadCompleted(requestId, orders))
        (fun error -> OrdersReadFailed(requestId, errorText error))

let private confirmOrderCommand token fundId orderId idempotencyKey requestId =
    Cmd.OfPromise.either
        (fun () -> Api.confirmOrder token fundId orderId idempotencyKey)
        ()
        (fun order -> OrderConfirmCompleted(requestId, orderId, order))
        (fun error -> OrderConfirmFailed(requestId, orderId, errorText error))

let private readPositionsCommand token fundId requestId =
    Cmd.OfPromise.either
        (fun () -> Api.getPositions token fundId)
        ()
        (fun positions -> PositionsReadCompleted(requestId, positions))
        (fun error -> PositionsReadFailed(requestId, errorText error))

let private createRedemptionCommand token fundId payload requestId =
    Cmd.OfPromise.either
        (fun () -> Api.createRedemption token fundId payload)
        ()
        (fun order -> RedemptionCreateCompleted(requestId, fundId, order))
        (fun error -> RedemptionCreateFailed(requestId, fundId, errorText error))

let private readRedemptionsCommand token fundId requestId =
    Cmd.OfPromise.either
        (fun () -> Api.getRedemptions token fundId)
        ()
        (fun orders -> RedemptionsReadCompleted(requestId, orders))
        (fun error -> RedemptionsReadFailed(requestId, errorText error))

let private confirmRedemptionCommand token fundId orderId idempotencyKey requestId =
    Cmd.OfPromise.either
        (fun () -> Api.confirmRedemption token fundId orderId idempotencyKey)
        ()
        (fun order -> RedemptionConfirmCompleted(requestId, orderId, order))
        (fun error -> RedemptionConfirmFailed(requestId, orderId, errorText error))

let private createCapitalDepositCommand token fundId payload requestId =
    Cmd.OfPromise.either
        (fun () -> Api.createCapitalDeposit token fundId payload)
        ()
        (fun _ -> CapitalDepositCompleted(requestId, payload.amount))
        (fun error -> CapitalDepositFailed(requestId, errorText error))

let private createSipPlanCommand token fundId payload requestId =
    Cmd.OfPromise.either
        (fun () -> Api.createSipPlan token fundId payload)
        ()
        (fun plan -> SipPlanCreateCompleted(requestId, fundId, plan))
        (fun error -> SipPlanCreateFailed(requestId, fundId, errorText error))

let private readSipPlansCommand token fundId requestId =
    Cmd.OfPromise.either
        (fun () -> Api.getSipPlans token fundId)
        ()
        (fun plans -> SipPlansReadCompleted(requestId, plans))
        (fun error -> SipPlansReadFailed(requestId, errorText error))

let private pauseSipPlanCommand token fundId planId requestId =
    Cmd.OfPromise.either
        (fun () -> Api.pauseSipPlan token fundId planId)
        ()
        (fun plan -> SipPlanStatusChanged(requestId, plan))
        (fun error -> SipPlanStatusChangeFailed(requestId, errorText error))

let private resumeSipPlanCommand token fundId planId requestId =
    Cmd.OfPromise.either
        (fun () -> Api.resumeSipPlan token fundId planId)
        ()
        (fun plan -> SipPlanStatusChanged(requestId, plan))
        (fun error -> SipPlanStatusChangeFailed(requestId, errorText error))

let private createRebalancePlanCommand token fundId payload requestId =
    Cmd.OfPromise.either
        (fun () -> Api.createRebalancePlan token fundId payload)
        ()
        (fun plan -> RebalancePlanCreateCompleted(requestId, fundId, plan))
        (fun error -> RebalancePlanCreateFailed(requestId, fundId, errorText error))

let private readRebalancePlansCommand token fundId requestId =
    Cmd.OfPromise.either
        (fun () -> Api.getRebalancePlans token fundId)
        ()
        (fun plans -> RebalancePlansReadCompleted(requestId, plans))
        (fun error -> RebalancePlansReadFailed(requestId, errorText error))

let private archiveRebalancePlanCommand token fundId planId requestId =
    Cmd.OfPromise.either
        (fun () -> Api.archiveRebalancePlan token fundId planId)
        ()
        (fun plan -> RebalancePlanArchived(requestId, plan))
        (fun error -> RebalancePlanArchiveFailed(requestId, errorText error))

let private executeRebalanceCommand token fundId planId requestId =
    Cmd.OfPromise.either
        (fun () -> Api.executeRebalancePlan token fundId planId)
        ()
        (fun result -> RebalanceExecuted(requestId, result))
        (fun error -> RebalanceExecuteFailed(requestId, errorText error))

let private previewRebalanceCommand token fundId planId requestId =
    Cmd.OfPromise.either
        (fun () -> Api.previewRebalancePlan token fundId planId)
        ()
        (fun preview -> RebalancePreviewCompleted(requestId, preview))
        (fun error -> RebalancePreviewFailed(requestId, errorText error))

let private readRebalanceExecutionsCommand token fundId requestId =
    Cmd.OfPromise.either
        (fun () -> Api.getRebalanceExecutions token fundId)
        ()
        (fun records -> RebalanceExecutionsReadCompleted(requestId, records))
        (fun error -> RebalanceExecutionsReadFailed(requestId, errorText error))

let private readDividendsCommand token fundId requestId =
    Cmd.OfPromise.either
        (fun () -> Api.getDividends token fundId)
        ()
        (fun records -> DividendsReadCompleted(requestId, records))
        (fun error -> DividendsReadFailed(requestId, errorText error))

let private readReturnsCommand token fundId requestId =
    Cmd.OfPromise.either
        (fun () -> Api.getReturns token fundId)
        ()
        (fun returns -> ReturnsReadCompleted(requestId, returns))
        (fun error -> ReturnsReadFailed(requestId, errorText error))

let private readNavDatesCommand token code requestId =
    Cmd.OfPromise.either
        (fun () -> Api.getMarketNavDates token code)
        ()
        (fun dates -> NavDatesReadCompleted(requestId, dates))
        (fun error -> NavDatesReadFailed(requestId, errorText error))

let private readNavSeriesCommand token code requestId =
    Cmd.OfPromise.either
        (fun () -> Api.getMarketNavSeries token code)
        ()
        (fun series -> NavSeriesReadCompleted(requestId, series))
        (fun error -> NavSeriesReadFailed(requestId, errorText error))

let private readBondQuoteCommand token code requestId =
    Cmd.OfPromise.either
        (fun () -> Api.getBondQuote token code)
        ()
        (fun quote -> BondQuoteCompleted(requestId, quote))
        (fun error -> BondQuoteFailed(requestId, errorText error))

let private readStockQuoteCommand token code requestId =
    Cmd.OfPromise.either
        (fun () -> Api.getStockQuote token code)
        ()
        (fun quote -> StockQuoteCompleted(requestId, quote))
        (fun error -> StockQuoteFailed(requestId, errorText error))

let private readStockDailyCommand token code days requestId =
    Cmd.OfPromise.either
        (fun () -> Api.getStockDaily token code days)
        ()
        (fun daily -> StockDailyCompleted(requestId, daily))
        (fun error -> StockDailyFailed(requestId, errorText error))

let private createStockTradeCommand token fundId payload requestId =
    Cmd.OfPromise.either
        (fun () -> Api.createStockTrade token fundId payload)
        ()
        (fun trade -> StockTradeCompleted(requestId, fundId, trade))
        (fun error -> StockTradeFailed(requestId, fundId, errorText error))

let private readStockPositionsCommand token fundId requestId =
    Cmd.OfPromise.either
        (fun () -> Api.getStockPositions token fundId)
        ()
        (fun positions -> StockPositionsReadCompleted(requestId, fundId, positions))
        (fun error -> StockPositionsReadFailed(requestId, fundId, errorText error))

let private createStockSellCommand token fundId payload requestId =
    Cmd.OfPromise.either
        (fun () -> Api.createStockSell token fundId payload)
        ()
        (fun sell -> StockSellCompleted(requestId, fundId, payload.instrumentCode, sell))
        (fun error -> StockSellFailed(requestId, fundId, payload.instrumentCode, errorText error))

let private createBondTradeCommand token fundId payload requestId =
    Cmd.OfPromise.either
        (fun () -> Api.createBondTrade token fundId payload)
        ()
        (fun trade -> BondTradeCompleted(requestId, fundId, trade))
        (fun error -> BondTradeFailed(requestId, fundId, errorText error))

let private readBondPositionsCommand token fundId requestId =
    Cmd.OfPromise.either
        (fun () -> Api.getBondPositions token fundId)
        ()
        (fun positions -> BondPositionsReadCompleted(requestId, fundId, positions))
        (fun error -> BondPositionsReadFailed(requestId, fundId, errorText error))

let private readValuationCommand token fundId requestId =
    Cmd.OfPromise.either
        (fun () -> Api.getFundValuation token fundId)
        ()
        (fun valuation -> ValuationReadCompleted(requestId, fundId, valuation))
        (fun error -> ValuationReadFailed(requestId, fundId, errorText error))

let private refreshMarketDataCommand token fundId requestId =
    Cmd.OfPromise.either
        (fun () -> Api.refreshFundMarketData token fundId)
        ()
        (fun response -> MarketRefreshCompleted(requestId, fundId, response))
        (fun error -> MarketRefreshFailed(requestId, fundId, errorText error))

let private readInvestmentPlansCommand token fundId requestId =
    Cmd.OfPromise.either
        (fun () -> Api.getInvestmentPlans token fundId)
        ()
        (fun plans -> InvestmentPlansReadCompleted(requestId, plans))
        (fun error -> InvestmentPlansReadFailed(requestId, errorText error))

let private runInvestmentPlansCommand token fundId requestId =
    Cmd.OfPromise.either
        (fun () -> Api.runInvestmentPlans token fundId)
        ()
        (fun run -> InvestmentPlansRunCompleted(requestId, fundId, run))
        (fun error -> InvestmentPlansRunFailed(requestId, fundId, errorText error))

let private dispatchSipStatusChange model planId pause =
    match model.createdFund with
    | Some fund when not (String.IsNullOrWhiteSpace model.token) && not model.sipStatusInFlight ->
        let requestId = model.sipStatusSeq + 1

        { model with sipStatusSeq = requestId; sipStatusInFlight = true; error = None },
        (if pause then
             pauseSipPlanCommand model.token fund.id planId requestId
         else
             resumeSipPlanCommand model.token fund.id planId requestId)
    | _ -> model, Cmd.none

let update message model =
    match message with
    | TokenChanged token ->
        {
            model with
                token = token
                searchSeq = model.searchSeq + 1
                navSeq = model.navSeq + 1
                searchResults = []
                selected = None
                observations = []
                searchInFlight = false
                navInFlight = false
                fundName = ""
                fundCash = ""
                fundSeq = model.fundSeq + 1
                fundInFlight = false
                createdFund = None
                lastCreateAttempt = None
                orderCode = ""
                orderAmount = ""
                orderFee = ""
                orderCreateSeq = model.orderCreateSeq + 1
                orderReadSeq = model.orderReadSeq + 1
                orderInFlight = false
                lastOrderAttempt = None
                orders = []
                confirmSeq = model.confirmSeq + 1
                confirmInFlight = false
                lastConfirmAttempt = None
                positions = None
                positionsSeq = model.positionsSeq + 1
                positionsInFlight = false
                redemptionCode = ""
                redemptionUnits = ""
                redemptionFee = ""
                redemptionCreateSeq = model.redemptionCreateSeq + 1
                redemptionReadSeq = model.redemptionReadSeq + 1
                redemptionInFlight = false
                lastRedemptionAttempt = None
                redemptions = []
                redemptionConfirmSeq = model.redemptionConfirmSeq + 1
                redemptionConfirmInFlight = false
                lastRedemptionConfirmAttempt = None
                capitalAmount = ""
                capitalSeq = model.capitalSeq + 1
                capitalInFlight = false
                lastCapitalAttempt = None
                capitalNote = None
                sipCode = ""
                sipAmount = ""
                sipFrequency = "weekly"
                sipCreateSeq = model.sipCreateSeq + 1
                sipReadSeq = model.sipReadSeq + 1
                sipInFlight = false
                lastSipAttempt = None
                sipPlans = []
                rebalTargets = [ { code = ""; percent = "" }; { code = ""; percent = "" } ]
                rebalCreateSeq = model.rebalCreateSeq + 1
                rebalReadSeq = model.rebalReadSeq + 1
                rebalInFlight = false
                rebalExecuteSeq = model.rebalExecuteSeq + 1
                rebalExecuteInFlight = false
                rebalPlans = []
                rebalResult = None
                rebalPreviewSeq = model.rebalPreviewSeq + 1
                rebalPreviewInFlight = false
                rebalPreview = None
                rebalExecutionsReadSeq = model.rebalExecutionsReadSeq + 1
                rebalExecutionsInFlight = false
                rebalExecutions = []
                dividendReadSeq = model.dividendReadSeq + 1
                dividendInFlight = false
                dividends = []
                returnsReadSeq = model.returnsReadSeq + 1
                returnsInFlight = false
                returns = None
                navDatesReadSeq = model.navDatesReadSeq + 1
                navDatesInFlight = false
                navDates = []
                navDatesAvailable = false
                navSeriesReadSeq = model.navSeriesReadSeq + 1
                navSeriesInFlight = false
                navSeries = []
                navSeriesAvailable = false
                returnsSelectedDate = None
                planReadSeq = model.planReadSeq + 1
                planInFlight = false
                planRunSeq = model.planRunSeq + 1
                planRunInFlight = false
                investmentPlans = []
                lastPlanRun = None
                error = None
        },
        Cmd.none
    | QueryChanged query ->
        { model with query = query; error = None }, Cmd.none
    | SearchRequested ->
        let query = model.query.Trim()

        if String.IsNullOrWhiteSpace model.token then
            { model with error = Some "请输入 API token" }, Cmd.none
        elif String.IsNullOrWhiteSpace query then
            { model with error = Some "请输入基金名称或六位代码" }, Cmd.none
        else
            let requestId = model.searchSeq + 1

            {
                model with
                    query = query
                    searchSeq = requestId
                    searchInFlight = true
                    error = None
            },
            searchCommand model.token query requestId
    | SearchCompleted (requestId, instruments) ->
        if requestId = model.searchSeq then
            {
                model with
                    searchResults = instruments
                    searchInFlight = false
                    error = None
            },
            Cmd.none
        else
            model, Cmd.none
    | SearchFailed (requestId, message) ->
        if requestId = model.searchSeq then
            { model with searchInFlight = false; error = Some message }, Cmd.none
        else
            model, Cmd.none
    | InstrumentSelected instrument ->
        if String.IsNullOrWhiteSpace model.token then
            { model with error = Some "请输入 API token" }, Cmd.none
        else
            let requestId = model.navSeq + 1

            {
                model with
                    selected = Some instrument
                    observations = []
                    navSeq = requestId
                    navInFlight = true
                    error = None
            },
            navCommand model.token instrument.code requestId
    | LoadNavRequested ->
        match model.selected with
        | Some instrument when not (String.IsNullOrWhiteSpace model.token) ->
            let requestId = model.navSeq + 1

            {
                model with
                    navSeq = requestId
                    navInFlight = true
                    error = None
            },
            navCommand model.token instrument.code requestId
        | Some _ ->
            { model with error = Some "请输入 API token" }, Cmd.none
        | None ->
            { model with error = Some "请先选择一个基金" }, Cmd.none
    | RefreshNavRequested ->
        match model.selected with
        | Some instrument when not (String.IsNullOrWhiteSpace model.token) ->
            let requestId = model.navSeq + 1

            {
                model with
                    navSeq = requestId
                    navInFlight = true
                    error = None
            },
            refreshCommand model.token instrument.code requestId
        | Some _ ->
            { model with error = Some "请输入 API token" }, Cmd.none
        | None ->
            { model with error = Some "请先选择一个基金" }, Cmd.none
    | NavCompleted (requestId, observations) ->
        if requestId = model.navSeq then
            {
                model with
                    observations = observations |> List.sortBy (fun observation -> observation.navDate)
                    navInFlight = false
                    error = None
            },
            Cmd.none
        else
            model, Cmd.none
    | NavFailed (requestId, message) ->
        if requestId = model.navSeq then
            { model with navInFlight = false; error = Some message }, Cmd.none
        else
            model, Cmd.none
    | FundNameChanged value ->
        { model with fundName = value; error = None; lastCreateAttempt = None }, Cmd.none
    | FundCashChanged value ->
        { model with fundCash = value; error = None; lastCreateAttempt = None }, Cmd.none
    | FundCreateRequested ->
        let name = model.fundName.Trim()
        let cash = model.fundCash.Trim()

        if String.IsNullOrWhiteSpace model.token then
            { model with error = Some "请输入 API token" }, Cmd.none
        elif name = "" then
            { model with error = Some "请输入基金名称" }, Cmd.none
        elif not (isValidCashText cash) then
            { model with error = Some "初始现金必须是合法金额,例如 10000.00" }, Cmd.none
        elif model.fundInFlight then
            model, Cmd.none
        else
            let requestId = model.fundSeq + 1
            let idempotencyKey = resolveCreateKey model.lastCreateAttempt name cash

            {
                model with
                    fundName = name
                    fundCash = cash
                    fundSeq = requestId
                    fundInFlight = true
                    lastCreateAttempt = Some { idempotencyKey = idempotencyKey; name = name; cash = cash }
                    error = None
            },
            createFundCommand
                model.token
                {
                    idempotencyKey = idempotencyKey
                    name = name
                    initialCash = cash
                    initialUnitNav = defaultInitialUnitNav
                    isSynthetic = false
                }
                requestId
    | FundCreateCompleted (requestId, fund) ->
        if requestId = model.fundSeq then
            {
                model with
                    createdFund = Some fund
                    fundInFlight = false
                    lastCreateAttempt = None
                    orderCreateSeq = model.orderCreateSeq + 1
                    orderReadSeq = model.orderReadSeq + 1
                    orderInFlight = false
                    lastOrderAttempt = None
                    orders = []
                    confirmSeq = model.confirmSeq + 1
                    confirmInFlight = false
                    lastConfirmAttempt = None
                    positions = None
                    positionsSeq = model.positionsSeq + 1
                    positionsInFlight = false
                    redemptionCode = ""
                    redemptionUnits = ""
                    redemptionFee = ""
                    redemptionCreateSeq = model.redemptionCreateSeq + 1
                    redemptionReadSeq = model.redemptionReadSeq + 1
                    redemptionInFlight = false
                    lastRedemptionAttempt = None
                    redemptions = []
                    redemptionConfirmSeq = model.redemptionConfirmSeq + 1
                    redemptionConfirmInFlight = false
                    lastRedemptionConfirmAttempt = None
                    capitalAmount = ""
                    capitalSeq = model.capitalSeq + 1
                    capitalInFlight = false
                    lastCapitalAttempt = None
                    capitalNote = None
                    sipCode = ""
                    sipAmount = ""
                    sipFrequency = "weekly"
                    sipCreateSeq = model.sipCreateSeq + 1
                    sipReadSeq = model.sipReadSeq + 1
                    sipInFlight = false
                    lastSipAttempt = None
                    sipPlans = []
                    rebalTargets = [ { code = ""; percent = "" }; { code = ""; percent = "" } ]
                    rebalCreateSeq = model.rebalCreateSeq + 1
                    rebalReadSeq = model.rebalReadSeq + 1
                    rebalInFlight = false
                    rebalExecuteSeq = model.rebalExecuteSeq + 1
                    rebalExecuteInFlight = false
                    rebalPlans = []
                    rebalResult = None
                    rebalPreviewSeq = model.rebalPreviewSeq + 1
                    rebalPreviewInFlight = false
                    rebalPreview = None
                    rebalExecutionsReadSeq = model.rebalExecutionsReadSeq + 1
                    rebalExecutionsInFlight = false
                    rebalExecutions = []
                    dividendReadSeq = model.dividendReadSeq + 1
                    dividendInFlight = false
                    dividends = []
                    returnsReadSeq = model.returnsReadSeq + 1
                    returnsInFlight = false
                    returns = None
                    navDatesReadSeq = model.navDatesReadSeq + 1
                    navDatesInFlight = false
                    navDates = []
                    navDatesAvailable = false
                    navSeriesReadSeq = model.navSeriesReadSeq + 1
                    navSeriesInFlight = false
                    navSeries = []
                    navSeriesAvailable = false
                    returnsSelectedDate = None
                    planReadSeq = model.planReadSeq + 1
                    planInFlight = false
                    planRunSeq = model.planRunSeq + 1
                    planRunInFlight = false
                    investmentPlans = []
                    lastPlanRun = None
                    error = None
            },
            Cmd.batch [ Cmd.ofMsg OrdersReadRequested; Cmd.ofMsg ReturnsReadRequested; Cmd.ofMsg InvestmentPlansReadRequested ]
        else
            model, Cmd.none
    | FundCreateFailed (requestId, message) ->
        if requestId = model.fundSeq then
            { model with fundInFlight = false; error = Some message }, Cmd.none
        else
            model, Cmd.none
    | FundReadRequested ->
        match model.createdFund with
        | Some fund when not (String.IsNullOrWhiteSpace model.token) ->
            if model.fundInFlight then
                model, Cmd.none
            else
                let requestId = model.fundSeq + 1

                { model with fundSeq = requestId; fundInFlight = true; error = None },
                readFundCommand model.token fund.id requestId
        | Some _ ->
            { model with error = Some "请输入 API token" }, Cmd.none
        | None ->
            { model with error = Some "请先创建一个基金" }, Cmd.none
    | FundReadCompleted (requestId, fund) ->
        if requestId = model.fundSeq then
            { model with createdFund = Some fund; fundInFlight = false; error = None }, Cmd.none
        else
            model, Cmd.none
    | FundReadFailed (requestId, message) ->
        if requestId = model.fundSeq then
            { model with fundInFlight = false; error = Some message }, Cmd.none
        else
            model, Cmd.none
    | OrderCodeChanged value ->
        { model with orderCode = value; error = None; lastOrderAttempt = None }, Cmd.none
    | OrderAmountChanged value ->
        { model with orderAmount = value; error = None; lastOrderAttempt = None }, Cmd.none
    | OrderFeeChanged value ->
        { model with orderFee = value; error = None; lastOrderAttempt = None }, Cmd.none
    | OrderCreateRequested ->
        let code = model.orderCode.Trim()
        let amount = model.orderAmount.Trim()
        let fee = model.orderFee.Trim()

        if String.IsNullOrWhiteSpace model.token then
            { model with error = Some "请输入 API token" }, Cmd.none
        elif model.createdFund.IsNone then
            { model with error = Some "请先创建一个基金" }, Cmd.none
        elif code = "" then
            { model with error = Some "请输入基金代码" }, Cmd.none
        elif not (isValidCashText amount) || not (isPositiveCash amount) then
            { model with error = Some "认购金额必须是大于零的两位小数金额,例如 100.00" }, Cmd.none
        elif not (isValidCashText fee) || not (isNonNegativeCash fee) then
            { model with error = Some "认购手续费必须是不小于零的两位小数金额,例如 0.00" }, Cmd.none
        elif model.orderInFlight then
            model, Cmd.none
        else
            let requestId = model.orderCreateSeq + 1
            let idempotencyKey = resolveOrderKey model.lastOrderAttempt code amount fee

            {
                model with
                    orderCode = code
                    orderAmount = amount
                    orderFee = fee
                    orderCreateSeq = requestId
                    orderInFlight = true
                    lastOrderAttempt =
                        Some
                            {
                                idempotencyKey = idempotencyKey
                                fundCode = code
                                amount = amount
                                feeAmount = fee
                            }
                    error = None
            },
            createOrderCommand
                model.token
                model.createdFund.Value.id
                {
                    idempotencyKey = idempotencyKey
                    fundCode = code
                    amount = amount
                    feeAmount = fee
                }
                requestId
    | OrderCreateCompleted (requestId, fundId, order) ->
        if requestId = model.orderCreateSeq
           && (match model.createdFund with Some fund -> fund.id = fundId | None -> false) then
            {
                model with
                    orderInFlight = false
                    lastOrderAttempt = None
                    error = None
            },
            Cmd.batch [ Cmd.ofMsg FundReadRequested; Cmd.ofMsg OrdersReadRequested; Cmd.ofMsg ReturnsReadRequested ]
        else
            model, Cmd.none
    | OrderCreateFailed (requestId, fundId, message) ->
        if requestId = model.orderCreateSeq
           && (match model.createdFund with Some fund -> fund.id = fundId | None -> false) then
            { model with orderInFlight = false; error = Some message }, Cmd.none
        else
            model, Cmd.none
    | OrdersReadRequested ->
        match model.createdFund with
        | Some fund when not (String.IsNullOrWhiteSpace model.token) ->
            let requestId = model.orderReadSeq + 1

            { model with orderReadSeq = requestId; error = None },
            readOrdersCommand model.token fund.id requestId
        | Some _ ->
            { model with error = Some "请输入 API token" }, Cmd.none
        | None ->
            model, Cmd.none
    | OrdersReadCompleted (requestId, orders) ->
        if requestId = model.orderReadSeq then
            {
                model with
                    orders = orders |> Array.map Api.decodeOrder |> Array.toList
                    error = None
            },
            Cmd.none
        else
            model, Cmd.none
    | OrdersReadFailed (requestId, message) ->
        if requestId = model.orderReadSeq then
            { model with error = Some message }, Cmd.none
        else
            model, Cmd.none
    | OrderConfirmRequested orderId ->
        match model.createdFund with
        | Some fund when not (String.IsNullOrWhiteSpace model.token) && not model.confirmInFlight ->
            let requestId = model.confirmSeq + 1
            let idempotencyKey = Guid.NewGuid().ToString("N")

            {
                model with
                    confirmSeq = requestId
                    confirmInFlight = true
                    lastConfirmAttempt = Some { idempotencyKey = idempotencyKey; orderId = orderId }
                    error = None
            },
            confirmOrderCommand model.token fund.id orderId idempotencyKey requestId
        | Some _ when model.confirmInFlight -> model, Cmd.none
        | Some _ -> { model with error = Some "请输入 API token" }, Cmd.none
        | None -> model, Cmd.none
    | OrderConfirmCompleted (requestId, orderId, raw) ->
        if requestId = model.confirmSeq
           && (model.lastConfirmAttempt |> Option.exists (fun attempt -> attempt.orderId = orderId)) then
            let confirmed = Api.decodeOrder raw

            let orders =
                model.orders
                |> List.map (fun order -> if order.id = confirmed.id then confirmed else order)

            { model with confirmInFlight = false; lastConfirmAttempt = None; orders = orders; error = None },
            Cmd.batch [ Cmd.ofMsg FundReadRequested; Cmd.ofMsg PositionsReadRequested; Cmd.ofMsg ReturnsReadRequested ]
        else
            model, Cmd.none
    | OrderConfirmFailed (requestId, orderId, message) ->
        if requestId = model.confirmSeq
           && (model.lastConfirmAttempt |> Option.exists (fun attempt -> attempt.orderId = orderId)) then
            { model with confirmInFlight = false; lastConfirmAttempt = None; error = Some message },
            Cmd.ofMsg OrdersReadRequested
        else
            model, Cmd.none
    | PositionsReadRequested ->
        match model.createdFund with
        | Some fund when not (String.IsNullOrWhiteSpace model.token) && not model.positionsInFlight ->
            let requestId = model.positionsSeq + 1

            { model with positionsSeq = requestId; positionsInFlight = true; error = None },
            readPositionsCommand model.token fund.id requestId
        | Some _ -> model, Cmd.none
        | None -> model, Cmd.none
    | PositionsReadCompleted (requestId, raw) ->
        if requestId = model.positionsSeq then
            {
                model with
                    positions = Some(Api.decodePositions raw)
                    positionsInFlight = false
                    error = None
            },
            Cmd.none
        else
            model, Cmd.none
    | PositionsReadFailed (requestId, message) ->
        if requestId = model.positionsSeq then
            { model with positionsInFlight = false; error = Some message }, Cmd.none
        else
            model, Cmd.none
    | RedemptionCodeChanged value ->
        { model with redemptionCode = value; error = None; lastRedemptionAttempt = None }, Cmd.none
    | RedemptionUnitsChanged value ->
        { model with redemptionUnits = value; error = None; lastRedemptionAttempt = None }, Cmd.none
    | RedemptionFeeChanged value ->
        { model with redemptionFee = value; error = None; lastRedemptionAttempt = None }, Cmd.none
    | RedemptionCreateRequested ->
        let code = model.redemptionCode.Trim()
        let units = model.redemptionUnits.Trim()
        let fee = model.redemptionFee.Trim()

        if String.IsNullOrWhiteSpace model.token then
            { model with error = Some "请输入 API token" }, Cmd.none
        elif model.createdFund.IsNone then
            { model with error = Some "请先创建一个基金" }, Cmd.none
        elif code = "" then
            { model with error = Some "请输入基金代码" }, Cmd.none
        elif Decimal.TryParse(units, NumberStyles.Float, CultureInfo.InvariantCulture) |> fst |> not then
            { model with error = Some "赎回份额必须是合法的八位小数份额数,例如 100.00000000" }, Cmd.none
        elif Decimal.Parse(units, NumberStyles.Float, CultureInfo.InvariantCulture) <= 0m then
            { model with error = Some "赎回份额必须是大于零的八位小数份额数,例如 100.00000000" }, Cmd.none
        elif not (isValidCashText fee) || not (isNonNegativeCash fee) then
            { model with error = Some "赎回手续费必须是不小于零的两位小数金额,例如 0.00" }, Cmd.none
        elif model.redemptionInFlight then
            model, Cmd.none
        else
            let requestId = model.redemptionCreateSeq + 1

            let idempotencyKey =
                match model.lastRedemptionAttempt with
                | Some attempt when
                    attempt.instrumentCode = code
                    && attempt.units = units
                    && attempt.feeAmount = fee
                    ->
                    attempt.idempotencyKey
                | _ -> Guid.NewGuid().ToString("N")

            {
                model with
                    redemptionCode = code
                    redemptionUnits = units
                    redemptionFee = fee
                    redemptionCreateSeq = requestId
                    redemptionInFlight = true
                    lastRedemptionAttempt =
                        Some
                            {
                                idempotencyKey = idempotencyKey
                                instrumentCode = code
                                units = units
                                feeAmount = fee
                            }
                    error = None
            },
            createRedemptionCommand
                model.token
                model.createdFund.Value.id
                {
                    idempotencyKey = idempotencyKey
                    instrumentCode = code
                    units = units
                    feeAmount = fee
                }
                requestId
    | RedemptionCreateCompleted (requestId, fundId, order) ->
        if requestId = model.redemptionCreateSeq
           && (match model.createdFund with Some fund -> fund.id = fundId | None -> false) then
            {
                model with
                    redemptionInFlight = false
                    lastRedemptionAttempt = None
                    error = None
            },
            Cmd.batch [ Cmd.ofMsg FundReadRequested; Cmd.ofMsg RedemptionsReadRequested; Cmd.ofMsg PositionsReadRequested ]
        else
            model, Cmd.none
    | RedemptionCreateFailed (requestId, fundId, message) ->
        if requestId = model.redemptionCreateSeq
           && (match model.createdFund with Some fund -> fund.id = fundId | None -> false) then
            { model with redemptionInFlight = false; error = Some message }, Cmd.none
        else
            model, Cmd.none
    | RedemptionsReadRequested ->
        match model.createdFund with
        | Some fund when not (String.IsNullOrWhiteSpace model.token) ->
            let requestId = model.redemptionReadSeq + 1

            { model with redemptionReadSeq = requestId; error = None },
            readRedemptionsCommand model.token fund.id requestId
        | Some _ ->
            { model with error = Some "请输入 API token" }, Cmd.none
        | None ->
            model, Cmd.none
    | RedemptionsReadCompleted (requestId, orders) ->
        if requestId = model.redemptionReadSeq then
            {
                model with
                    redemptions = orders |> Array.map Api.decodeRedemption |> Array.toList
                    error = None
            },
            Cmd.none
        else
            model, Cmd.none
    | RedemptionsReadFailed (requestId, message) ->
        if requestId = model.redemptionReadSeq then
            { model with error = Some message }, Cmd.none
        else
            model, Cmd.none
    | RedemptionConfirmRequested orderId ->
        match model.createdFund with
        | Some fund when not (String.IsNullOrWhiteSpace model.token) && not model.redemptionConfirmInFlight ->
            let requestId = model.redemptionConfirmSeq + 1
            let idempotencyKey = Guid.NewGuid().ToString("N")

            {
                model with
                    redemptionConfirmSeq = requestId
                    redemptionConfirmInFlight = true
                    lastRedemptionConfirmAttempt = Some { idempotencyKey = idempotencyKey; orderId = orderId }
                    error = None
            },
            confirmRedemptionCommand model.token fund.id orderId idempotencyKey requestId
        | Some _ when model.redemptionConfirmInFlight -> model, Cmd.none
        | Some _ -> { model with error = Some "请输入 API token" }, Cmd.none
        | None -> model, Cmd.none
    | RedemptionConfirmCompleted (requestId, orderId, raw) ->
        if requestId = model.redemptionConfirmSeq
           && (model.lastRedemptionConfirmAttempt |> Option.exists (fun attempt -> attempt.orderId = orderId)) then
            let confirmed = Api.decodeRedemption raw

            let redemptions =
                model.redemptions
                |> List.map (fun order -> if order.id = confirmed.id then confirmed else order)

            { model with redemptionConfirmInFlight = false; lastRedemptionConfirmAttempt = None; redemptions = redemptions; error = None },
            Cmd.batch [ Cmd.ofMsg FundReadRequested; Cmd.ofMsg PositionsReadRequested; Cmd.ofMsg ReturnsReadRequested ]
        else
            model, Cmd.none
    | RedemptionConfirmFailed (requestId, orderId, message) ->
        if requestId = model.redemptionConfirmSeq
           && (model.lastRedemptionConfirmAttempt |> Option.exists (fun attempt -> attempt.orderId = orderId)) then
            { model with redemptionConfirmInFlight = false; lastRedemptionConfirmAttempt = None; error = Some message },
            Cmd.ofMsg RedemptionsReadRequested
        else
            model, Cmd.none
    | CapitalAmountChanged value ->
        { model with capitalAmount = value; error = None; lastCapitalAttempt = None }, Cmd.none
    | CapitalDepositRequested ->
        let amount = model.capitalAmount.Trim()

        if String.IsNullOrWhiteSpace model.token then
            { model with error = Some "请输入 API token" }, Cmd.none
        elif model.createdFund.IsNone then
            { model with error = Some "请先创建一个基金" }, Cmd.none
        elif not (isValidCashText amount) || not (isPositiveCash amount) then
            { model with error = Some "追加金额必须是大于零的两位小数金额,例如 1000.00" }, Cmd.none
        elif model.capitalInFlight then
            model, Cmd.none
        else
            let requestId = model.capitalSeq + 1

            let idempotencyKey =
                match model.lastCapitalAttempt with
                | Some attempt when attempt.amount = amount -> attempt.idempotencyKey
                | _ -> Guid.NewGuid().ToString("N")

            {
                model with
                    capitalAmount = amount
                    capitalSeq = requestId
                    capitalInFlight = true
                    lastCapitalAttempt = Some { idempotencyKey = idempotencyKey; amount = amount }
                    error = None
            },
            createCapitalDepositCommand
                model.token
                model.createdFund.Value.id
                {
                    idempotencyKey = idempotencyKey
                    amount = amount
                    note = "追加资金"
                }
                requestId
    | CapitalDepositCompleted (requestId, amount) ->
        if requestId = model.capitalSeq then
            {
                model with
                    capitalInFlight = false
                    capitalNote = Some(sprintf "追加成功 + %s(现金余额已刷新)" amount)
                    error = None
            },
            Cmd.batch [ Cmd.ofMsg FundReadRequested; Cmd.ofMsg ReturnsReadRequested ]
        else
            model, Cmd.none
    | CapitalDepositFailed (requestId, message) ->
        if requestId = model.capitalSeq then
            { model with capitalInFlight = false; error = Some message }, Cmd.none
        else
            model, Cmd.none
    | SipCodeChanged value ->
        { model with sipCode = value; error = None; lastSipAttempt = None }, Cmd.none
    | SipAmountChanged value ->
        { model with sipAmount = value; error = None; lastSipAttempt = None }, Cmd.none
    | SipFrequencyChanged value ->
        { model with sipFrequency = value; error = None; lastSipAttempt = None }, Cmd.none
    | SipPlanCreateRequested ->
        let code = model.sipCode.Trim()
        let amount = model.sipAmount.Trim()

        if String.IsNullOrWhiteSpace model.token then
            { model with error = Some "请输入 API token" }, Cmd.none
        elif model.createdFund.IsNone then
            { model with error = Some "请先创建一个基金" }, Cmd.none
        elif code = "" then
            { model with error = Some "请输入基金代码" }, Cmd.none
        elif not (isValidCashText amount) || not (isPositiveCash amount) then
            { model with error = Some "定投金额必须是大于零的两位小数金额,例如 200.00" }, Cmd.none
        elif model.sipInFlight then
            model, Cmd.none
        else
            let requestId = model.sipCreateSeq + 1

            let idempotencyKey =
                match model.lastSipAttempt with
                | Some attempt when
                    attempt.instrumentCode = code
                    && attempt.amount = amount
                    && attempt.frequency = model.sipFrequency
                    ->
                    attempt.idempotencyKey
                | _ -> Guid.NewGuid().ToString("N")

            {
                model with
                    sipCode = code
                    sipAmount = amount
                    sipCreateSeq = requestId
                    sipInFlight = true
                    lastSipAttempt =
                        Some
                            {
                                idempotencyKey = idempotencyKey
                                instrumentCode = code
                                amount = amount
                                frequency = model.sipFrequency
                            }
                    error = None
            },
            createSipPlanCommand
                model.token
                model.createdFund.Value.id
                {
                    idempotencyKey = idempotencyKey
                    instrumentCode = code
                    amount = amount
                    frequency = model.sipFrequency
                }
                requestId
    | SipPlanCreateCompleted (requestId, fundId, plan) ->
        if requestId = model.sipCreateSeq
           && (match model.createdFund with Some fund -> fund.id = fundId | None -> false) then
            {
                model with
                    sipInFlight = false
                    lastSipAttempt = None
                    error = None
            },
            Cmd.ofMsg SipPlansReadRequested
        else
            model, Cmd.none
    | SipPlanCreateFailed (requestId, fundId, message) ->
        if requestId = model.sipCreateSeq
           && (match model.createdFund with Some fund -> fund.id = fundId | None -> false) then
            { model with sipInFlight = false; error = Some message }, Cmd.none
        else
            model, Cmd.none
    | SipPlansReadRequested ->
        match model.createdFund with
        | Some fund when not (String.IsNullOrWhiteSpace model.token) ->
            let requestId = model.sipReadSeq + 1

            { model with sipReadSeq = requestId; error = None },
            readSipPlansCommand model.token fund.id requestId
        | Some _ ->
            { model with error = Some "请输入 API token" }, Cmd.none
        | None ->
            model, Cmd.none
    | SipPlansReadCompleted (requestId, plans) ->
        if requestId = model.sipReadSeq then
            {
                model with
                    sipPlans = plans |> Array.map Api.decodeSipPlan |> Array.toList
                    error = None
            },
            Cmd.none
        else
            model, Cmd.none
    | SipPlansReadFailed (requestId, message) ->
        if requestId = model.sipReadSeq then
            { model with error = Some message }, Cmd.none
        else
            model, Cmd.none
    | SipPlanPauseRequested planId -> dispatchSipStatusChange model planId true
    | SipPlanResumeRequested planId -> dispatchSipStatusChange model planId false
    | SipPlanStatusChanged (requestId, plan) ->
        if requestId = model.sipStatusSeq then
            let decoded = Api.decodeSipPlan plan

            {
                model with
                    sipStatusInFlight = false
                    sipPlans =
                        model.sipPlans
                        |> List.map (fun existing -> if existing.id = decoded.id then decoded else existing)
                    error = None
            },
            Cmd.none
        else
            model, Cmd.none
    | SipPlanStatusChangeFailed (requestId, message) ->
        if requestId = model.sipStatusSeq then
            { model with sipStatusInFlight = false; error = Some message }, Cmd.none
        else
            model, Cmd.none
    | RebalTargetCodeChanged (index, value) ->
        {
            model with
                rebalTargets =
                    model.rebalTargets
                    |> List.mapi (fun i draft -> if i = index then { draft with code = value } else draft)
                error = None
        },
        Cmd.none
    | RebalTargetPercentChanged (index, value) ->
        {
            model with
                rebalTargets =
                    model.rebalTargets
                    |> List.mapi (fun i draft -> if i = index then { draft with percent = value } else draft)
                error = None
        },
        Cmd.none
    | RebalTargetAdded ->
        { model with rebalTargets = model.rebalTargets @ [ { code = ""; percent = "" } ]; error = None }, Cmd.none
    | RebalTargetRemoved index ->
        {
            model with
                rebalTargets =
                    model.rebalTargets
                    |> List.mapi (fun i draft -> i, draft)
                    |> List.filter (fun (i, _) -> i <> index)
                    |> List.map snd
                error = None
        },
        Cmd.none
    | RebalancePlanCreateRequested ->
        let participating =
            model.rebalTargets
            |> List.map (fun draft -> draft.code.Trim(), draft.percent.Trim())
            |> List.filter (fun (code, _) -> code <> "")

        if String.IsNullOrWhiteSpace model.token then
            { model with error = Some "请输入 API token" }, Cmd.none
        elif model.createdFund.IsNone then
            { model with error = Some "请先创建一个基金" }, Cmd.none
        elif participating.IsEmpty then
            { model with error = Some "请输入至少一个目标基金代码" }, Cmd.none
        elif
            participating
            |> List.exists (fun (_, percent) -> not (isValidCashText percent) || not (isNonNegativeCash percent))
        then
            { model with error = Some "目标比例必须是不小于 0 的两位小数百分数,例如 60.00" }, Cmd.none
        else
            let total =
                participating
                |> List.sumBy (fun (_, percent) ->
                    Decimal.Parse(percent, NumberStyles.Float, CultureInfo.InvariantCulture))

            if total <> 100m then
                { model with error = Some "目标比例合计必须等于 100" }, Cmd.none
            elif model.rebalInFlight then
                model, Cmd.none
            else
                let requestId = model.rebalCreateSeq + 1

                {
                    model with
                        rebalCreateSeq = requestId
                        rebalInFlight = true
                        rebalResult = None
                        rebalPreview = None
                        error = None
                },
                createRebalancePlanCommand
                    model.token
                    model.createdFund.Value.id
                    {
                        idempotencyKey = Guid.NewGuid().ToString("N")
                        targets =
                            participating
                            |> List.map (fun (code, percent) -> { instrumentCode = code; targetPercent = percent })
                            |> List.toArray
                    }
                    requestId
    | RebalancePlanCreateCompleted (requestId, fundId, plan) ->
        if requestId = model.rebalCreateSeq
           && (match model.createdFund with Some fund -> fund.id = fundId | None -> false) then
            {
                model with
                    rebalInFlight = false
                    rebalResult = None
                    error = None
            },
            Cmd.ofMsg RebalancePlansReadRequested
        else
            model, Cmd.none
    | RebalancePlanCreateFailed (requestId, fundId, message) ->
        if requestId = model.rebalCreateSeq
           && (match model.createdFund with Some fund -> fund.id = fundId | None -> false) then
            { model with rebalInFlight = false; error = Some message }, Cmd.none
        else
            model, Cmd.none
    | RebalancePlansReadRequested ->
        match model.createdFund with
        | Some fund when not (String.IsNullOrWhiteSpace model.token) ->
            let requestId = model.rebalReadSeq + 1

            { model with rebalReadSeq = requestId },
            readRebalancePlansCommand model.token fund.id requestId
        | Some _ ->
            { model with error = Some "请输入 API token" }, Cmd.none
        | None ->
            model, Cmd.none
    | RebalancePlansReadCompleted (requestId, plans) ->
        if requestId = model.rebalReadSeq then
            {
                model with
                    rebalPlans = plans |> Array.map Api.decodeRebalancePlan |> Array.toList
                    error = None
            },
            Cmd.none
        else
            model, Cmd.none
    | RebalancePlansReadFailed (requestId, message) ->
        if requestId = model.rebalReadSeq then
            { model with error = Some message }, Cmd.none
        else
            model, Cmd.none
    | RebalancePlanArchiveRequested planId ->
        match model.createdFund with
        | Some fund when not (String.IsNullOrWhiteSpace model.token) && not model.rebalArchiveInFlight ->
            let requestId = model.rebalArchiveSeq + 1
            { model with rebalArchiveSeq = requestId; rebalArchiveInFlight = true; error = None },
            archiveRebalancePlanCommand model.token fund.id planId requestId
        | _ -> model, Cmd.none
    | RebalancePlanArchived (requestId, plan) ->
        if requestId = model.rebalArchiveSeq then
            let decoded = Api.decodeRebalancePlan plan

            {
                model with
                    rebalArchiveInFlight = false
                    rebalPlans =
                        model.rebalPlans
                        |> List.map (fun existing -> if existing.id = decoded.id then decoded else existing)
                    error = None
            },
            Cmd.none
        else
            model, Cmd.none
    | RebalancePlanArchiveFailed (requestId, message) ->
        if requestId = model.rebalArchiveSeq then
            { model with rebalArchiveInFlight = false; error = Some message }, Cmd.none
        else
            model, Cmd.none
    | RebalancePreviewRequested planId ->
        match model.createdFund with
        | Some fund when not (String.IsNullOrWhiteSpace model.token) && not model.rebalPreviewInFlight ->
            let requestId = model.rebalPreviewSeq + 1

            {
                model with
                    rebalPreviewSeq = requestId
                    rebalPreviewInFlight = true
                    rebalPreview = None
                    error = None
            },
            previewRebalanceCommand model.token fund.id planId requestId
        | Some _ when model.rebalPreviewInFlight -> model, Cmd.none
        | Some _ -> { model with error = Some "请输入 API token" }, Cmd.none
        | None -> model, Cmd.none
    | RebalancePreviewCompleted (requestId, raw) ->
        if requestId = model.rebalPreviewSeq then
            {
                model with
                    rebalPreviewInFlight = false
                    rebalPreview = Some(Api.decodeRebalancePreview raw)
                    error = None
            },
            Cmd.none
        else
            model, Cmd.none
    | RebalancePreviewFailed (requestId, message) ->
        if requestId = model.rebalPreviewSeq then
            { model with rebalPreviewInFlight = false; error = Some message }, Cmd.none
        else
            model, Cmd.none
    | RebalanceExecuteRequested planId ->
        match model.createdFund with
        | Some fund when not (String.IsNullOrWhiteSpace model.token) && not model.rebalExecuteInFlight ->
            let requestId = model.rebalExecuteSeq + 1

            {
                model with
                    rebalExecuteSeq = requestId
                    rebalExecuteInFlight = true
                    rebalResult = None
                    error = None
            },
            executeRebalanceCommand model.token fund.id planId requestId
        | Some _ when model.rebalExecuteInFlight -> model, Cmd.none
        | Some _ -> { model with error = Some "请输入 API token" }, Cmd.none
        | None -> model, Cmd.none
    | RebalanceExecuted (requestId, raw) ->
        if requestId = model.rebalExecuteSeq then
            {
                model with
                    rebalExecuteInFlight = false
                    rebalPreview = None
                    rebalResult =
                        Some
                            (raw.outcomes
                             |> Array.map (fun outcome ->
                                 {
                                     instrumentCode = outcome.instrumentCode
                                     action = outcome.action
                                     amount = outcome.amount
                                     status = outcome.status
                                     orderId = Api.decodeOptionalText outcome.orderId
                                     pendingReason = Api.decodeOptionalText outcome.pendingReason
                                 })
                             |> Array.toList)
                    error = None
            },
            Cmd.batch
                [
                    Cmd.ofMsg FundReadRequested
                    Cmd.ofMsg OrdersReadRequested
                    Cmd.ofMsg PositionsReadRequested
                    Cmd.ofMsg RebalanceExecutionsReadRequested
                ]
        else
            model, Cmd.none
    | RebalanceExecuteFailed (requestId, message) ->
        if requestId = model.rebalExecuteSeq then
            { model with rebalExecuteInFlight = false; error = Some message }, Cmd.none
        else
            model, Cmd.none
    | RebalanceExecutionsReadRequested ->
        match model.createdFund with
        | Some fund when not (String.IsNullOrWhiteSpace model.token) ->
            let requestId = model.rebalExecutionsReadSeq + 1

            { model with rebalExecutionsReadSeq = requestId; rebalExecutionsInFlight = true },
            readRebalanceExecutionsCommand model.token fund.id requestId
        | Some _ ->
            { model with error = Some "请输入 API token" }, Cmd.none
        | None ->
            model, Cmd.none
    | RebalanceExecutionsReadCompleted (requestId, records) ->
        if requestId = model.rebalExecutionsReadSeq then
            {
                model with
                    rebalExecutionsInFlight = false
                    rebalExecutions = records |> Array.map Api.decodeRebalanceExecutionRecord |> Array.toList
                    error = None
            },
            Cmd.none
        else
            model, Cmd.none
    | RebalanceExecutionsReadFailed (requestId, message) ->
        if requestId = model.rebalExecutionsReadSeq then
            { model with rebalExecutionsInFlight = false; error = Some message }, Cmd.none
        else
            model, Cmd.none
    | DividendsReadRequested ->
        match model.createdFund with
        | Some fund when not (String.IsNullOrWhiteSpace model.token) ->
            let requestId = model.dividendReadSeq + 1

            {
                model with
                    dividendReadSeq = requestId
                    dividendInFlight = true
                    error = None
            },
            readDividendsCommand model.token fund.id requestId
        | Some _ -> { model with error = Some "请输入 API token" }, Cmd.none
        | None -> model, Cmd.none
    | DividendsReadCompleted (requestId, records) ->
        if requestId = model.dividendReadSeq then
            {
                model with
                    dividends = records |> Array.map Api.decodeDividend |> Array.toList
                    dividendInFlight = false
                    error = None
            },
            Cmd.none
        else
            model, Cmd.none
    | DividendsReadFailed (requestId, message) ->
        if requestId = model.dividendReadSeq then
            { model with dividendInFlight = false; error = Some message }, Cmd.none
        else
            model, Cmd.none
    | ReturnsReadRequested ->
        match model.createdFund with
        | Some fund when not (String.IsNullOrWhiteSpace model.token) ->
            let requestId = model.returnsReadSeq + 1

            {
                model with
                    returnsReadSeq = requestId
                    returnsInFlight = true
                    error = None
            },
            Cmd.batch
                [
                    readReturnsCommand model.token fund.id requestId
                    Cmd.ofMsg NavDatesReadRequested
                    Cmd.ofMsg NavSeriesReadRequested
                ]
        | Some _ -> { model with error = Some "请输入 API token" }, Cmd.none
        | None -> model, Cmd.none
    | ReturnsReadCompleted (requestId, returns) ->
        if requestId = model.returnsReadSeq then
            {
                model with
                    returns = Some(Api.decodeReturns returns)
                    returnsInFlight = false
                    error = None
            },
            Cmd.none
        else
            model, Cmd.none
    | ReturnsReadFailed (requestId, message) ->
        if requestId = model.returnsReadSeq then
            { model with returnsInFlight = false; error = Some message }, Cmd.none
        else
            model, Cmd.none
    | NavDatesReadRequested ->
        match model.createdFund with
        | Some _ when String.IsNullOrWhiteSpace model.token ->
            { model with error = Some "请输入 API token" }, Cmd.none
        | Some _ ->
            let heldCode =
                model.positions
                |> Option.bind (fun positions -> positions.positions |> List.tryHead)
                |> Option.map (fun position -> position.instrumentCode)

            match heldCode with
            | Some code ->
                let requestId = model.navDatesReadSeq + 1

                {
                    model with
                        navDatesReadSeq = requestId
                        navDatesInFlight = true
                },
                readNavDatesCommand model.token code requestId
            | None ->
                {
                    model with
                        navDates = []
                        navDatesAvailable = false
                        navDatesInFlight = false
                },
                Cmd.none
        | None -> model, Cmd.none
    | NavDatesReadCompleted (requestId, dates) ->
        if requestId = model.navDatesReadSeq then
            let resolved = dates.dates |> Array.toList

            {
                model with
                    navDates = resolved
                    navDatesAvailable = not (List.isEmpty resolved)
                    navDatesInFlight = false
            },
            Cmd.none
        else
            model, Cmd.none
    | NavDatesReadFailed (requestId, _) ->
        if requestId = model.navDatesReadSeq then
            {
                model with
                    navDates = []
                    navDatesAvailable = false
                    navDatesInFlight = false
            },
            Cmd.none
        else
            model, Cmd.none
    | NavSeriesReadRequested ->
        match model.createdFund with
        | Some _ when String.IsNullOrWhiteSpace model.token ->
            { model with error = Some "请输入 API token" }, Cmd.none
        | Some _ ->
            let heldCode =
                model.positions
                |> Option.bind (fun positions -> positions.positions |> List.tryHead)
                |> Option.map (fun position -> position.instrumentCode)

            match heldCode with
            | Some code ->
                let requestId = model.navSeriesReadSeq + 1

                {
                    model with
                        navSeriesReadSeq = requestId
                        navSeriesInFlight = true
                },
                readNavSeriesCommand model.token code requestId
            | None ->
                {
                    model with
                        navSeries = []
                        navSeriesAvailable = false
                        navSeriesInFlight = false
                },
                Cmd.none
        | None -> model, Cmd.none
    | NavSeriesReadCompleted (requestId, series) ->
        if requestId = model.navSeriesReadSeq then
            let resolved = series.points |> Array.toList |> List.map Api.decodeNavSeriesPoint

            {
                model with
                    navSeries = resolved
                    navSeriesAvailable = not (List.isEmpty resolved)
                    navSeriesInFlight = false
            },
            Cmd.none
        else
            model, Cmd.none
    | NavSeriesReadFailed (requestId, _) ->
        if requestId = model.navSeriesReadSeq then
            {
                model with
                    navSeries = []
                    navSeriesAvailable = false
                    navSeriesInFlight = false
            },
            Cmd.none
        else
            model, Cmd.none
    | BondCodeChanged value -> { model with bondCode = value }, Cmd.none
    | BondQuoteRequested ->
        let code = model.bondCode.Trim()

        if String.IsNullOrWhiteSpace model.token then
            { model with bondQuoteMessage = Some "请输入 API token"; bondQuote = None }, Cmd.none
        elif String.IsNullOrWhiteSpace code then
            { model with bondQuoteMessage = Some "请输入六位债券代码"; bondQuote = None }, Cmd.none
        else
            let requestId = model.bondQuoteSeq + 1

            {
                model with
                    bondQuoteSeq = requestId
                    bondQuoteInFlight = true
                    bondQuoteMessage = None
                    bondQuote = None
            },
            readBondQuoteCommand model.token code requestId
    | BondQuoteCompleted (requestId, quote) ->
        if requestId = model.bondQuoteSeq then
            {
                model with
                    bondQuote = Some(Api.decodeBondQuote quote)
                    bondQuoteMessage = None
                    bondQuoteInFlight = false
            },
            Cmd.none
        else
            model, Cmd.none
    | BondQuoteFailed (requestId, message) ->
        if requestId = model.bondQuoteSeq then
            {
                model with
                    bondQuote = None
                    bondQuoteMessage = Some(sprintf "债券行情不可用 — %s" message)
                    bondQuoteInFlight = false
            },
            Cmd.none
        else
            model, Cmd.none
    | StockCodeChanged value -> { model with stockCode = value }, Cmd.none
    | StockQuoteRequested ->
        let code = model.stockCode.Trim()

        if String.IsNullOrWhiteSpace model.token then
            { model with stockQuoteMessage = Some "请输入 API token"; stockQuote = None }, Cmd.none
        elif String.IsNullOrWhiteSpace code then
            { model with stockQuoteMessage = Some "请输入六位股票代码"; stockQuote = None }, Cmd.none
        else
            let requestId = model.stockQuoteSeq + 1

            {
                model with
                    stockQuoteSeq = requestId
                    stockQuoteInFlight = true
                    stockQuoteMessage = None
                    stockQuote = None
            },
            readStockQuoteCommand model.token code requestId
    | StockQuoteCompleted (requestId, quote) ->
        if requestId = model.stockQuoteSeq then
            {
                model with
                    stockQuote = Some(Api.decodeStockQuote quote)
                    stockQuoteMessage = None
                    stockQuoteInFlight = false
            },
            Cmd.none
        else
            model, Cmd.none
    | StockQuoteFailed (requestId, message) ->
        if requestId = model.stockQuoteSeq then
            let text =
                if message.Contains("six digits") then
                    "无效代码 — 请输入六位股票代码"
                else
                    sprintf "股票行情不可用 — %s" message

            {
                model with
                    stockQuote = None
                    stockQuoteMessage = Some text
                    stockQuoteInFlight = false
            },
            Cmd.none
        else
            model, Cmd.none
    | StockDailyRequested ->
        let code = model.stockCode.Trim()

        if String.IsNullOrWhiteSpace model.token then
            { model with stockDailyMessage = Some "请输入 API token"; stockDaily = [] }, Cmd.none
        elif String.IsNullOrWhiteSpace code then
            { model with stockDailyMessage = Some "请输入六位股票代码"; stockDaily = [] }, Cmd.none
        else
            let requestId = model.stockDailySeq + 1

            {
                model with
                    stockDailySeq = requestId
                    stockDailyInFlight = true
                    stockDailyMessage = None
                    stockDaily = []
            },
            readStockDailyCommand model.token code 5 requestId
    | StockDailyCompleted (requestId, daily) ->
        if requestId = model.stockDailySeq then
            let rows = daily.observations |> Array.toList |> List.map Api.decodeStockDailyBar

            {
                model with
                    stockDaily = rows
                    stockDailyMessage = (if List.isEmpty rows then Some "股票日线不可用 — 暂无数据" else None)
                    stockDailyInFlight = false
            },
            Cmd.none
        else
            model, Cmd.none
    | StockDailyFailed (requestId, message) ->
        if requestId = model.stockDailySeq then
            {
                model with
                    stockDaily = []
                    stockDailyMessage = Some(sprintf "股票日线不可用 — %s" message)
                    stockDailyInFlight = false
            },
            Cmd.none
        else
            model, Cmd.none
    | StockTradeQuantityChanged value -> { model with stockTradeQuantity = value }, Cmd.none
    | StockTradeRequested ->
        let code = model.stockCode.Trim()
        let quantity = model.stockTradeQuantity.Trim()

        if String.IsNullOrWhiteSpace model.token then
            { model with stockTradeMessage = Some "请输入 API token" }, Cmd.none
        elif model.createdFund.IsNone then
            { model with stockTradeMessage = Some "请先创建一个基金" }, Cmd.none
        elif code.Length <> 6 || not (code |> Seq.forall Char.IsDigit) then
            { model with stockTradeMessage = Some "无效代码 — 请输入六位股票代码" }, Cmd.none
        elif not (isValidQuantityText quantity) then
            { model with stockTradeMessage = Some "数量必须是大于零的整数股数,例如 100" }, Cmd.none
        elif model.stockTradeInFlight then
            model, Cmd.none
        else
            let requestId = model.stockTradeSeq + 1

            let idempotencyKey =
                match model.lastStockTradeAttempt with
                | Some attempt when attempt.instrumentCode = code && attempt.quantity = quantity -> attempt.idempotencyKey
                | _ -> Guid.NewGuid().ToString("N")

            {
                model with
                    stockCode = code
                    stockTradeQuantity = quantity
                    stockTradeSeq = requestId
                    stockTradeInFlight = true
                    lastStockTradeAttempt =
                        Some
                            {
                                idempotencyKey = idempotencyKey
                                instrumentCode = code
                                quantity = quantity
                            }
                    stockTradeMessage = None
            },
            createStockTradeCommand
                model.token
                model.createdFund.Value.id
                { idempotencyKey = idempotencyKey; instrumentCode = code; quantity = quantity }
                requestId
    | StockTradeCompleted (requestId, fundId, trade) ->
        if requestId = model.stockTradeSeq
           && (match model.createdFund with Some fund -> fund.id = fundId | None -> false) then
            {
                model with
                    stockTradeInFlight = false
                    lastStockTrade = Some(Api.decodeStockTrade trade)
                    lastStockTradeAttempt = None
                    stockTradeMessage = None
            },
            Cmd.ofMsg StockPositionsReadRequested
        else
            model, Cmd.none
    | StockTradeFailed (requestId, fundId, message) ->
        if requestId = model.stockTradeSeq
           && (match model.createdFund with Some fund -> fund.id = fundId | None -> false) then
            { model with stockTradeInFlight = false; stockTradeMessage = Some(sprintf "买入失败 — %s" message) }, Cmd.none
        else
            model, Cmd.none
    | StockPositionsReadRequested ->
        match model.createdFund with
        | Some fund when not (String.IsNullOrWhiteSpace model.token) ->
            let requestId = model.stockPositionsReadSeq + 1

            {
                model with
                    stockPositionsReadSeq = requestId
                    stockPositionsInFlight = true
                    stockPositionsMessage = None
            },
            readStockPositionsCommand model.token fund.id requestId
        | _ -> model, Cmd.none
    | StockPositionsReadCompleted (requestId, fundId, positions) ->
        if requestId = model.stockPositionsReadSeq
           && (match model.createdFund with Some fund -> fund.id = fundId | None -> false) then
            {
                model with
                    stockPositions = positions.positions |> Array.toList |> List.map Api.decodeStockPosition
                    stockPositionsInFlight = false
                    stockPositionsMessage = None
            },
            Cmd.none
        else
            model, Cmd.none
    | StockPositionsReadFailed (requestId, fundId, message) ->
        if requestId = model.stockPositionsReadSeq
           && (match model.createdFund with Some fund -> fund.id = fundId | None -> false) then
            {
                model with
                    stockPositions = []
                    stockPositionsInFlight = false
                    stockPositionsMessage = Some(sprintf "持仓不可用 — %s" message)
            },
            Cmd.none
        else
            model, Cmd.none
    | StockSellQuantityChanged (code, value) ->
        { model with stockSellQuantities = Map.add code value model.stockSellQuantities }, Cmd.none
    | StockSellRequested code ->
        match model.createdFund with
        | Some fund when not (String.IsNullOrWhiteSpace model.token) ->
            let quantity = (model.stockSellQuantities |> Map.tryFind code |> Option.defaultValue "").Trim()

            if not (isValidQuantityText quantity) then
                { model with stockSellMessage = Some "卖出数量必须是大于零的整数股数,例如 100" }, Cmd.none
            else
                let requestId = model.stockSellSeq + 1

                let idempotencyKey =
                    match model.stockSellAttempts |> Map.tryFind code with
                    | Some attempt when attempt.quantity = quantity -> attempt.idempotencyKey
                    | _ -> Guid.NewGuid().ToString("N")

                let payload : CreateStockSellPayload =
                    { idempotencyKey = idempotencyKey; instrumentCode = code; quantity = quantity }

                let attempt : StockSellAttempt =
                    { idempotencyKey = idempotencyKey; instrumentCode = code; quantity = quantity }

                {
                    model with
                        stockSellSeq = requestId
                        stockSellInFlight = true
                        stockSellMessage = None
                        stockSellAttempts = Map.add code attempt model.stockSellAttempts
                },
                createStockSellCommand model.token fund.id payload requestId
        | _ when String.IsNullOrWhiteSpace model.token ->
            { model with stockSellMessage = Some "请输入 API token" }, Cmd.none
        | _ ->
            { model with stockSellMessage = Some "请先创建一个基金" }, Cmd.none
    | StockSellCompleted (requestId, fundId, code, sell) ->
        if requestId = model.stockSellSeq
           && (match model.createdFund with Some fund -> fund.id = fundId | None -> false) then
            {
                model with
                    stockSellInFlight = false
                    stockSellMessage =
                        Some(sprintf "已卖出 %s %s 股:成交价 %s,回收现金 %s" code sell.quantity sell.price sell.proceeds)
                    stockSellQuantities = Map.remove code model.stockSellQuantities
                    stockSellAttempts = Map.remove code model.stockSellAttempts
            },
            Cmd.batch [ Cmd.ofMsg StockPositionsReadRequested; Cmd.ofMsg ValuationReadRequested ]
        else
            model, Cmd.none
    | StockSellFailed (requestId, fundId, code, message) ->
        if requestId = model.stockSellSeq
           && (match model.createdFund with Some fund -> fund.id = fundId | None -> false) then
            { model with stockSellInFlight = false; stockSellMessage = Some(sprintf "卖出失败 — %s" message) }, Cmd.none
        else
            model, Cmd.none
    | BondTradeQuantityChanged value -> { model with bondTradeQuantity = value }, Cmd.none
    | BondTradeRequested ->
        let code = model.bondCode.Trim()
        let quantity = model.bondTradeQuantity.Trim()

        if String.IsNullOrWhiteSpace model.token then
            { model with bondTradeMessage = Some "请输入 API token" }, Cmd.none
        elif model.createdFund.IsNone then
            { model with bondTradeMessage = Some "请先创建一个基金" }, Cmd.none
        elif code.Length <> 6 || not (code |> Seq.forall Char.IsDigit) then
            { model with bondTradeMessage = Some "无效代码 — 请输入六位债券代码" }, Cmd.none
        elif not (isValidQuantityText quantity) then
            { model with bondTradeMessage = Some "数量必须是大于零的整数张数,例如 10" }, Cmd.none
        elif model.bondTradeInFlight then
            model, Cmd.none
        else
            let requestId = model.bondTradeSeq + 1

            let idempotencyKey =
                match model.lastBondTradeAttempt with
                | Some attempt when attempt.instrumentCode = code && attempt.quantity = quantity -> attempt.idempotencyKey
                | _ -> Guid.NewGuid().ToString("N")

            {
                model with
                    bondCode = code
                    bondTradeQuantity = quantity
                    bondTradeSeq = requestId
                    bondTradeInFlight = true
                    lastBondTradeAttempt =
                        Some
                            {
                                idempotencyKey = idempotencyKey
                                instrumentCode = code
                                quantity = quantity
                            }
                    bondTradeMessage = None
            },
            createBondTradeCommand
                model.token
                model.createdFund.Value.id
                { idempotencyKey = idempotencyKey; instrumentCode = code; quantity = quantity }
                requestId
    | BondTradeCompleted (requestId, fundId, trade) ->
        if requestId = model.bondTradeSeq
           && (match model.createdFund with Some fund -> fund.id = fundId | None -> false) then
            {
                model with
                    bondTradeInFlight = false
                    lastBondTrade = Some(Api.decodeBondTrade trade)
                    lastBondTradeAttempt = None
                    bondTradeMessage = None
            },
            Cmd.ofMsg BondPositionsReadRequested
        else
            model, Cmd.none
    | BondTradeFailed (requestId, fundId, message) ->
        if requestId = model.bondTradeSeq
           && (match model.createdFund with Some fund -> fund.id = fundId | None -> false) then
            { model with bondTradeInFlight = false; bondTradeMessage = Some(sprintf "买入失败 — %s" message) }, Cmd.none
        else
            model, Cmd.none
    | BondPositionsReadRequested ->
        match model.createdFund with
        | Some fund when not (String.IsNullOrWhiteSpace model.token) ->
            let requestId = model.bondPositionsReadSeq + 1

            {
                model with
                    bondPositionsReadSeq = requestId
                    bondPositionsInFlight = true
                    bondPositionsMessage = None
            },
            readBondPositionsCommand model.token fund.id requestId
        | _ -> model, Cmd.none
    | BondPositionsReadCompleted (requestId, fundId, positions) ->
        if requestId = model.bondPositionsReadSeq
           && (match model.createdFund with Some fund -> fund.id = fundId | None -> false) then
            {
                model with
                    bondPositions = positions.positions |> Array.toList |> List.map Api.decodeBondPosition
                    bondPositionsInFlight = false
                    bondPositionsMessage = None
            },
            Cmd.none
        else
            model, Cmd.none
    | BondPositionsReadFailed (requestId, fundId, message) ->
        if requestId = model.bondPositionsReadSeq
           && (match model.createdFund with Some fund -> fund.id = fundId | None -> false) then
            {
                model with
                    bondPositions = []
                    bondPositionsInFlight = false
                    bondPositionsMessage = Some(sprintf "持仓不可用 — %s" message)
            },
            Cmd.none
        else
            model, Cmd.none
    | ValuationReadRequested ->
        match model.createdFund with
        | Some fund when not (String.IsNullOrWhiteSpace model.token) ->
            let requestId = model.valuationReadSeq + 1

            {
                model with
                    valuationReadSeq = requestId
                    valuationInFlight = true
                    valuationMessage = None
            },
            readValuationCommand model.token fund.id requestId
        | _ -> model, Cmd.none
    | ValuationReadCompleted (requestId, fundId, valuation) ->
        if requestId = model.valuationReadSeq
           && (match model.createdFund with Some fund -> fund.id = fundId | None -> false) then
            {
                model with
                    valuation = Some(Api.decodeFundValuation valuation)
                    valuationInFlight = false
                    valuationMessage = None
            },
            Cmd.none
        else
            model, Cmd.none
    | ValuationReadFailed (requestId, fundId, message) ->
        if requestId = model.valuationReadSeq
           && (match model.createdFund with Some fund -> fund.id = fundId | None -> false) then
            {
                model with
                    valuation = None
                    valuationInFlight = false
                    valuationMessage = Some(sprintf "组合估值不可用 — %s" message)
            },
            Cmd.none
        else
            model, Cmd.none
    | MarketRefreshRequested ->
        match model.createdFund with
        | Some fund when not (String.IsNullOrWhiteSpace model.token) ->
            let requestId = model.marketRefreshSeq + 1

            {
                model with
                    marketRefreshSeq = requestId
                    marketRefreshInFlight = true
                    marketRefreshMessage = None
            },
            refreshMarketDataCommand model.token fund.id requestId
        | _ -> model, Cmd.none
    | MarketRefreshCompleted (requestId, fundId, response) ->
        if requestId = model.marketRefreshSeq
           && (match model.createdFund with Some fund -> fund.id = fundId | None -> false) then
            {
                model with
                    marketRefreshInFlight = false
                    marketRefreshMessage =
                        Some(sprintf "行情刷新完成(%s):更新 %d 项,失败 %d 项" response.asOfDate response.refreshed.Length response.failures.Length)
            },
            Cmd.ofMsg ValuationReadRequested
        else
            model, Cmd.none
    | MarketRefreshFailed (requestId, fundId, message) ->
        if requestId = model.marketRefreshSeq
           && (match model.createdFund with Some fund -> fund.id = fundId | None -> false) then
            {
                model with
                    marketRefreshInFlight = false
                    marketRefreshMessage = Some(sprintf "行情刷新失败 — %s" message)
            },
            Cmd.none
        else
            model, Cmd.none
    | ReturnsDateChanged value ->
        { model with returnsSelectedDate = (if String.IsNullOrWhiteSpace value then None else Some value) }, Cmd.none
    | InvestmentPlansReadRequested ->
        match model.createdFund with
        | Some fund when not (String.IsNullOrWhiteSpace model.token) ->
            let requestId = model.planReadSeq + 1

            {
                model with
                    planReadSeq = requestId
                    planInFlight = true
                    error = None
            },
            readInvestmentPlansCommand model.token fund.id requestId
        | Some _ -> { model with error = Some "请输入 API token" }, Cmd.none
        | None -> model, Cmd.none
    | InvestmentPlansReadCompleted (requestId, plans) ->
        if requestId = model.planReadSeq then
            {
                model with
                    investmentPlans = plans |> Array.map Api.decodeInvestmentPlan |> Array.toList
                    planInFlight = false
                    error = None
            },
            Cmd.none
        else
            model, Cmd.none
    | InvestmentPlansReadFailed (requestId, message) ->
        if requestId = model.planReadSeq then
            { model with planInFlight = false; error = Some message }, Cmd.none
        else
            model, Cmd.none
    | InvestmentPlansRunRequested ->
        match model.createdFund with
        | Some fund when not (String.IsNullOrWhiteSpace model.token) ->
            if model.planRunInFlight then
                model, Cmd.none
            else
                let requestId = model.planRunSeq + 1

                {
                    model with
                        planRunSeq = requestId
                        planRunInFlight = true
                        error = None
                },
                runInvestmentPlansCommand model.token fund.id requestId
        | Some _ -> { model with error = Some "请输入 API token" }, Cmd.none
        | None -> model, Cmd.none
    | InvestmentPlansRunCompleted (requestId, fundId, run) ->
        if requestId = model.planRunSeq
           && (match model.createdFund with Some fund -> fund.id = fundId | None -> false) then
            let decoded = Api.decodeInvestmentPlanRun run

            {
                model with
                    planRunInFlight = false
                    lastPlanRun = Some decoded
                    error = None
            },
            Cmd.batch
                [
                    Cmd.ofMsg InvestmentPlansReadRequested
                    Cmd.ofMsg FundReadRequested
                    Cmd.ofMsg PositionsReadRequested
                    Cmd.ofMsg ReturnsReadRequested
                ]
        else
            model, Cmd.none
    | InvestmentPlansRunFailed (requestId, fundId, message) ->
        if requestId = model.planRunSeq
           && (match model.createdFund with Some fund -> fund.id = fundId | None -> false) then
            { model with planRunInFlight = false; error = Some message }, Cmd.none
        else
            model, Cmd.none

let private navText (text: string) =
    match Decimal.TryParse(text, NumberStyles.Float, CultureInfo.InvariantCulture) with
    | true, value -> value.ToString("0.00000000", CultureInfo.InvariantCulture)
    | false, _ -> text

let private latestStats (observations: NavObservation list) =
    let ordered: NavObservation list = observations |> List.sortBy (fun observation -> observation.navDate)

    match ordered with
    | [] -> None
    | ordered ->
        let first = List.head ordered
        let latest = List.last ordered

        Some(
            navText latest.nav,
            latest.dailyReturn |> Option.map (fun value -> value + "%"),
            first.navDate,
            latest.navDate
        )

let private chartView (observations: NavObservation list) =
    let points = Chart.chartPoints observations

    if List.isEmpty points then
        Html.div [ prop.className "chart-empty"; prop.text "选择基金后加载历史净值" ]
    else
        let width = 960.0
        let height = 320.0
        let padding = 28.0
        let chartWidth = width - padding * 2.0
        let chartHeight = height - padding * 2.0

        let coordinates =
            points
            |> List.map (fun point ->
                padding + point.x * chartWidth,
                padding + (1.0 - point.y) * chartHeight)

        let gridLines =
            [ 0 .. 4 ]
            |> List.map (fun index ->
                let y = padding + float index / 4.0 * chartHeight

                Svg.line [
                    svg.x1 padding
                    svg.y1 y
                    svg.x2 (width - padding)
                    svg.y2 y
                    svg.stroke "#e2e8f0"
                    svg.strokeWidth 1
                ])

        let markers =
            coordinates
            |> List.mapi (fun index (x, y) ->
                Svg.circle [
                    svg.cx x
                    svg.cy y
                    svg.r 3.5
                    svg.fill "#f59e0b"
                ])

        Html.div [
            prop.className "chart-wrap"
            prop.children [
                Svg.svg [
                    svg.className "nav-chart"
                    svg.viewBox (0, 0, 960, 320)
                    svg.children [
                        yield! gridLines
                        Svg.polyline [
                            svg.points coordinates
                            svg.fill "none"
                            svg.stroke "#1e40af"
                            svg.strokeWidth 3
                        ]
                        yield! markers
                    ]
                ]
                Html.div [
                    prop.className "chart-axis"
                    prop.children [
                        Html.span [ prop.text (points |> List.head |> fun point -> point.navDate) ]
                        Html.span [ prop.text (points |> List.last |> fun point -> point.navDate) ]
                    ]
                ]
            ]
        ]

let private resultRow instrument dispatch =
    Html.button [
        prop.className "result-row"
        prop.onClick (fun _ -> dispatch (InstrumentSelected instrument))
        prop.children [
            Html.span [ prop.className "result-code"; prop.text instrument.code ]
            Html.span [ prop.className "result-name"; prop.text instrument.name ]
            Html.span [ prop.className "result-type"; prop.text (instrument.fundType |> Option.defaultValue "基金") ]
        ]
    ]

let private searchPanel model dispatch =
    Html.section [
        prop.className "panel search-panel"
        prop.children [
            Html.div [
                prop.className "section-heading"
                prop.children [
                    Html.div [
                        Html.p [ prop.className "eyebrow"; prop.text "01 / FIND" ]
                        Html.h2 "先锁定真实代码"
                    ]
                    Html.span [ prop.className "section-note"; prop.text "AKShare · exact match" ]
                ]
            ]
            Html.div [
                prop.className "search-row"
                prop.children [
                    Html.input [
                        prop.className "text-input search-input"
                        prop.placeholder "输入基金名称或六位代码"
                        prop.value model.query
                        prop.onChange (fun value -> dispatch (QueryChanged value))
                    ]
                    Html.button [
                        prop.className "primary-action"
                        prop.disabled model.searchInFlight
                        prop.onClick (fun _ -> dispatch SearchRequested)
                        prop.text (if model.searchInFlight then "查询中..." else "搜索")
                    ]
                ]
            ]
            if List.isEmpty model.searchResults then
                Html.p [ prop.className "hint"; prop.text "搜索结果会保留来源与代码,避免名称歧义。" ]
            else
                Html.div [
                    prop.className "result-list"
                    prop.children (model.searchResults |> List.map (fun instrument -> resultRow instrument dispatch))
                ]
        ]
    ]

let private navPanel model dispatch =
    let selectedName =
        model.selected
        |> Option.map (fun instrument -> instrument.name)
        |> Option.defaultValue "尚未选择基金"

    Html.section [
        prop.className "panel nav-panel"
        prop.children [
            Html.div [
                prop.className "section-heading"
                prop.children [
                    Html.div [
                        Html.p [ prop.className "eyebrow"; prop.text "02 / TRACE" ]
                        Html.h2 selectedName
                    ]
                    match model.selected with
                    | Some instrument ->
                        Html.div [
                            prop.className "instrument-meta"
                            prop.children [
                                Html.span [ prop.className "code-chip"; prop.text instrument.code ]
                                Html.span [ prop.className "section-note"; prop.text (instrument.fundType |> Option.defaultValue "基金") ]
                            ]
                        ]
                    | None -> Html.none
                ]
            ]
            match latestStats model.observations with
            | None ->
                Html.div [
                    prop.className "chart-placeholder"
                    prop.children [
                        Html.div [ prop.className "placeholder-line" ]
                        Html.p "历史净值会在这里形成一条可追溯的曲线"
                        Html.span "数据来自已持久化的日频观察值"
                    ]
                ]
            | Some(latestNav, dailyReturn, fromDate, toDate) ->
                Html.div [
                    prop.className "nav-content"
                    prop.children [
                        Html.div [
                            prop.className "metric-strip"
                            prop.children [
                                Html.div [
                                    prop.className "metric"
                                    prop.children [
                                        Html.span "最新单位净值"
                                        Html.strong latestNav
                                    ]
                                ]
                                Html.div [
                                    prop.className "metric"
                                    prop.children [
                                        Html.span "最新日收益"
                                        Html.strong (dailyReturn |> Option.defaultValue "暂无")
                                    ]
                                ]
                                Html.div [
                                    prop.className "metric"
                                    prop.children [
                                        Html.span "观察区间"
                                        Html.strong (sprintf "%s — %s" fromDate toDate)
                                    ]
                                ]
                            ]
                        ]
                        chartView model.observations
                    ]
                ]
            Html.div [
                prop.className "panel-actions"
                prop.children [
                    Html.button [
                        prop.className "secondary-action"
                        prop.disabled (model.navInFlight || model.selected.IsNone)
                        prop.onClick (fun _ -> dispatch LoadNavRequested)
                        prop.text "重新读取"
                    ]
                    Html.button [
                        prop.className "primary-action"
                        prop.disabled (model.navInFlight || model.selected.IsNone)
                        prop.onClick (fun _ -> dispatch RefreshNavRequested)
                        prop.text (if model.navInFlight then "同步中..." else "刷新 AKShare")
                    ]
                ]
            ]
        ]
    ]

let private fundSummaryRow (label: string) (value: string) =
    Html.div [
        prop.className "fund-detail-row"
        prop.children [
            Html.span [ prop.className "fund-detail-label"; prop.text label ]
            Html.span [ prop.className "fund-detail-value"; prop.text value ]
        ]
    ]

let private fundPanel model dispatch =
    Html.section [
        prop.className "panel fund-panel"
        prop.children [
            Html.div [
                prop.className "section-heading"
                prop.children [
                    Html.div [
                        Html.p [ prop.className "eyebrow"; prop.text "03 / CREATE" ]
                        Html.h2 "创建一笔真实基金"
                    ]
                    Html.span [ prop.className "section-note"; prop.text "PostgreSQL · idempotent" ]
                ]
            ]
            Html.div [
                prop.className "fund-form-row"
                prop.children [
                    Html.label [
                        prop.className "field-label"
                        prop.children [
                            Html.span "基金名称"
                            Html.input [
                                prop.className "text-input fund-name-input"
                                prop.placeholder "例如 稳健一号"
                                prop.value model.fundName
                                prop.onChange (fun value -> dispatch (FundNameChanged value))
                            ]
                        ]
                    ]
                    Html.label [
                        prop.className "field-label"
                        prop.children [
                            Html.span "初始现金(元)"
                            Html.input [
                                prop.className "text-input fund-cash-input"
                                prop.placeholder "例如 10000.00"
                                prop.value model.fundCash
                                prop.onChange (fun value -> dispatch (FundCashChanged value))
                            ]
                        ]
                    ]
                    Html.button [
                        prop.className "primary-action fund-create-action"
                        prop.disabled model.fundInFlight
                        prop.onClick (fun _ -> dispatch FundCreateRequested)
                        prop.text ((if model.fundInFlight then "创建中..." else "创建基金"): string)
                    ]
                ]
            ]
            Html.p [
                prop.className "hint"
                prop.text "初始单位净值固定为 1.00000000;金额以 decimal 字符串提交,不经过浮点运算。"
            ]
            match model.createdFund with
            | Some fund ->
                Html.div [
                    prop.className "fund-summary"
                    prop.children [
                        fundSummaryRow "基金ID" fund.id
                        fundSummaryRow "名称" fund.name
                        fundSummaryRow "币种" fund.currency
                        fundSummaryRow "初始现金" fund.initialCash
                        fundSummaryRow "可用现金" fund.availableCash
                        fundSummaryRow "保留现金" fund.reservedCash
                        fundSummaryRow "初始单位净值" fund.initialUnitNav
                        fundSummaryRow "份额" "0(新基金尚未买入持仓)"
                        fundSummaryRow "状态" fund.status
                        fundSummaryRow "数据来源" (if fund.isSynthetic then "合成(测试标记)" else "真实建档")
                        Html.div [
                            prop.className "panel-actions"
                            prop.children [
                                Html.button [
                                    prop.className "secondary-action fund-read-action"
                                    prop.disabled model.fundInFlight
                                    prop.onClick (fun _ -> dispatch FundReadRequested)
                                    prop.text ((if model.fundInFlight then "读取中..." else "重新读取"): string)
                                ]
                            ]
                        ]
                    ]
                ]
            | None ->
                Html.p [
                    prop.className "hint"
                    prop.text "创建成功后,这里会展示服务端返回的基金档案,可通过重新读取复核持久化结果。"
                ]
            match model.createdFund with
            | Some _ ->
                Html.div [
                    prop.className "capital-block"
                    prop.children [
                        Html.label [
                            prop.className "field-label"
                            prop.children [
                                Html.span "追加资金(元)"
                                Html.input [
                                    prop.className "text-input capital-amount-input"
                                    prop.placeholder "例如 1000.00"
                                    prop.value model.capitalAmount
                                    prop.onChange (fun value -> dispatch (CapitalAmountChanged value))
                                ]
                            ]
                        ]
                        Html.button [
                            prop.className "primary-action capital-deposit-action"
                            prop.disabled model.capitalInFlight
                            prop.onClick (fun _ -> dispatch CapitalDepositRequested)
                            prop.text ((if model.capitalInFlight then "追加中..." else "追加资金"): string)
                        ]
                    ]
                ]
                Html.p [
                    prop.className "hint capital-result"
                    prop.text
                        (match model.capitalNote with
                         | Some note -> note
                         | None -> "追加资金直接计入可用现金,不产生份额、不分摊成本、不计入已实现收益。")
                ]
            | None -> Html.none
        ]
    ]

let private orderStatusText (status: string) =
    if status = "submitted" then "已提交 · 待确认"
    elif status = "pending_nav" then "等待净值"
    elif status = "confirmed" then "已确认"
    else status

let private orderRow (order: OrderDetail) model dispatch =
    let confirmButton =
        if order.status = "submitted" || order.status = "pending_nav" then
            Html.button [
                prop.className "secondary-action order-confirm-action"
                prop.disabled model.confirmInFlight
                prop.onClick (fun _ -> dispatch (OrderConfirmRequested order.id))
                prop.text (if model.confirmInFlight then "确认中..." else "确认净值")
            ]
        else
            Html.none

    let detailText =
        match order.status with
        | "confirmed" ->
            [
                sprintf "确认净值 %s" (order.confirmedNav |> Option.defaultValue "—")
                sprintf "份额 %s" (order.confirmedUnits |> Option.defaultValue "—")
                sprintf "净值日期 %s" (order.confirmedNavDate |> Option.defaultValue "—")
                sprintf "成交金额 %s" (order.confirmedInvestedCash |> Option.defaultValue "—")
                sprintf "退回现金 %s" (order.confirmedResidualCash |> Option.defaultValue "—")
            ]
            |> String.concat " · "
        | "pending_nav" ->
            "等待净值 · " + (order.pendingReason |> Option.defaultValue "净值尚未公布")
        | _ -> "已冻结现金;净值确认后按交易日成交。"

    Html.div [
        prop.className "order-row"
        prop.children [
            Html.span [ prop.className "order-code"; prop.text order.fundCode ]
            Html.span [ prop.className "order-cell"; prop.text (sprintf "金额 %s" order.amount) ]
            Html.span [ prop.className "order-cell"; prop.text (sprintf "手续费 %s" order.feeAmount) ]
            Html.span [ prop.className "order-cell"; prop.text (sprintf "预留合计 %s" order.reservedTotal) ]
            Html.span [ prop.className "order-cell"; prop.text (sprintf "交易日 %s" order.tradeDate) ]
            Html.span [ prop.className "order-status"; prop.text (orderStatusText order.status) ]
            Html.span [ prop.className "order-detail"; prop.text detailText ]
            confirmButton
            Html.span [ prop.className "order-cell"; prop.text order.submittedAt ]
        ]
    ]

let private subscribePanel model dispatch =
    Html.section [
        prop.className "panel subscribe-panel"
        prop.children [
            Html.div [
                prop.className "section-heading"
                prop.children [
                    Html.div [
                        Html.p [ prop.className "eyebrow"; prop.text "04 / SUBSCRIBE" ]
                        Html.h2 "认购一笔基金(模拟)"
                    ]
                    Html.span [ prop.className "section-note"; prop.text "Pending · no execution" ]
                ]
            ]
            Html.div [
                prop.className "fund-form-row"
                prop.children [
                    Html.label [
                        prop.className "field-label"
                        prop.children [
                            Html.span "基金代码"
                            Html.input [
                                prop.className "text-input order-code-input"
                                prop.placeholder "六位基金代码"
                                prop.value model.orderCode
                                prop.onChange (fun value -> dispatch (OrderCodeChanged value))
                            ]
                        ]
                    ]
                    Html.label [
                        prop.className "field-label"
                        prop.children [
                            Html.span "认购金额(元)"
                            Html.input [
                                prop.className "text-input order-amount-input"
                                prop.placeholder "例如 100.00"
                                prop.value model.orderAmount
                                prop.onChange (fun value -> dispatch (OrderAmountChanged value))
                            ]
                        ]
                    ]
                    Html.label [
                        prop.className "field-label"
                        prop.children [
                            Html.span "认购手续费(元)"
                            Html.input [
                                prop.className "text-input order-fee-input"
                                prop.placeholder "0.00 或 1.50"
                                prop.value model.orderFee
                                prop.onChange (fun value -> dispatch (OrderFeeChanged value))
                            ]
                        ]
                    ]
                    Html.button [
                        prop.className "primary-action order-submit-action"
                        prop.disabled model.orderInFlight
                        prop.onClick (fun _ -> dispatch OrderCreateRequested)
                        prop.text ((if model.orderInFlight then "下单中..." else "认购下单"): string)
                    ]
                ]
            ]
            Html.p [
                prop.className "hint"
                prop.text "金额与手续费按两位小数字符串提交,手续费允许 0.00;下单即冻结现金,订单保持已提交 · 待确认,不产生任何份额或收益。"
            ]
            Html.div [
                prop.className "pending-orders"
                prop.children [
                    if List.isEmpty model.orders then
                        Html.p [ prop.className "hint"; prop.text "暂无待确认订单" ]
                    else
                        yield! (model.orders |> List.map (fun order -> orderRow order model dispatch))
                ]
            ]
            Html.div [
                prop.className "panel-actions"
                prop.children [
                    Html.button [
                        prop.className "secondary-action orders-refresh-action"
                        prop.onClick (fun _ -> dispatch OrdersReadRequested)
                        prop.text "刷新订单"
                    ]
                    Html.button [
                        prop.className "secondary-action positions-refresh-action"
                        prop.disabled model.positionsInFlight
                        prop.onClick (fun _ -> dispatch PositionsReadRequested)
                        prop.text ((if model.positionsInFlight then "读取中..." else "刷新持仓"): string)
                    ]
                ]
            ]
        ]
    ]

let private positionRow (position: Position) =
    let valuation =
        match position.valuationNav, position.valuationNavDate with
        | Some nav, Some navDate -> sprintf "%s(%s)" nav navDate
        | _ -> "估值待更新"

    let frozen =
        if position.reservedUnits <> "0.00000000" then
            Html.span [ prop.className "order-cell"; prop.text (sprintf "冻结份额 %s" position.reservedUnits) ]
        else
            Html.none

    Html.div [
        prop.className "order-row position-row"
        prop.children [
            Html.span [ prop.className "order-code"; prop.text position.instrumentCode ]
            Html.span [ prop.className "order-cell"; prop.text (sprintf "份额 %s" position.units) ]
            frozen
            Html.span [ prop.className "order-cell"; prop.text (sprintf "成本 %s" position.costCash) ]
            Html.span [ prop.className "order-cell"; prop.text (sprintf "最新估值净值 %s" valuation) ]
            Html.span [ prop.className "order-cell"; prop.text (sprintf "最近确认 %s" position.lastConfirmedAt) ]
        ]
    ]

let private positionsPanel model dispatch =
    Html.section [
        prop.className "panel positions-panel"
        prop.children [
            Html.div [
                prop.className "section-heading"
                prop.children [
                    Html.div [
                        Html.p [ prop.className "eyebrow"; prop.text "05 / HOLDINGS" ]
                        Html.h2 "确认后持仓"
                    ]
                    Html.span [ prop.className "section-note"; prop.text "Positions · confirmed units" ]
                ]
            ]
            match model.createdFund, model.positions with
            | Some _, Some positions ->
                Html.div [
                    prop.className "positions-summary"
                    prop.children [
                        fundSummaryRow "可用现金" positions.availableCash
                        fundSummaryRow "保留现金" positions.reservedCash
                    ]
                ]

                if List.isEmpty positions.positions then
                    Html.p [ prop.className "hint"; prop.text "暂无持仓,确认认购后这里会展示份额与估值。" ]
                else
                    yield! (positions.positions |> List.map positionRow)
            | Some _, None ->
                Html.p [ prop.className "hint"; prop.text "持仓尚未读取,点击「刷新持仓」获取确认后份额。" ]
            | None, _ ->
                Html.p [ prop.className "hint"; prop.text "创建基金后,这里会展示确认后的持仓与现金。" ]
            Html.div [
                prop.className "panel-actions"
                prop.children [
                    Html.button [
                        prop.className "secondary-action positions-read-action"
                        prop.disabled (model.positionsInFlight || model.createdFund.IsNone)
                        prop.onClick (fun _ -> dispatch PositionsReadRequested)
                        prop.text ((if model.positionsInFlight then "读取中..." else "刷新持仓"): string)
                    ]
                ]
            ]
        ]
    ]

let private redemptionStatusText (status: string) =
    if status = "submitted" then "已提交 · 待确认"
    elif status = "pending_nav" then "等待净值"
    elif status = "confirmed" then "已确认"
    else status

let private redemptionRow (order: RedemptionDetail) model dispatch =
    let confirmButton =
        if order.status = "submitted" || order.status = "pending_nav" then
            Html.button [
                prop.className "secondary-action redemption-confirm-action"
                prop.disabled model.redemptionConfirmInFlight
                prop.onClick (fun _ -> dispatch (RedemptionConfirmRequested order.id))
                prop.text (if model.redemptionConfirmInFlight then "确认中..." else "确认赎回")
            ]
        else
            Html.none

    let detailText =
        match order.status with
        | "confirmed" ->
            [
                sprintf "确认净值 %s" (order.confirmedNav |> Option.defaultValue "—")
                sprintf "赎回到账 %s" (order.confirmedProceeds |> Option.defaultValue "—")
                sprintf "核销成本 %s" (order.confirmedCostReleased |> Option.defaultValue "—")
                sprintf "净值日期 %s" (order.confirmedNavDate |> Option.defaultValue "—")
            ]
            |> String.concat " · "
        | "pending_nav" ->
            "等待净值 · " + (order.pendingReason |> Option.defaultValue "净值尚未公布")
        | _ -> "已冻结份额;净值确认后按交易日结算到账。"

    Html.div [
        prop.className "order-row"
        prop.children [
            Html.span [ prop.className "order-code"; prop.text order.instrumentCode ]
            Html.span [ prop.className "order-cell"; prop.text (sprintf "份额 %s" order.units) ]
            Html.span [ prop.className "order-cell"; prop.text (sprintf "手续费 %s" order.feeAmount) ]
            Html.span [ prop.className "order-cell"; prop.text (sprintf "交易日 %s" order.tradeDate) ]
            Html.span [ prop.className "order-status"; prop.text (redemptionStatusText order.status) ]
            Html.span [ prop.className "order-detail"; prop.text detailText ]
            confirmButton
            Html.span [ prop.className "order-cell"; prop.text order.submittedAt ]
        ]
    ]

let private redeemPanel model dispatch =
    Html.section [
        prop.className "panel redeem-panel"
        prop.children [
            Html.div [
                prop.className "section-heading"
                prop.children [
                    Html.div [
                        Html.p [ prop.className "eyebrow"; prop.text "06 / REDEEM" ]
                        Html.h2 "赎回已确认持仓(模拟)"
                    ]
                    Html.span [ prop.className "section-note"; prop.text "Pending · units frozen" ]
                ]
            ]
            Html.div [
                prop.className "fund-form-row"
                prop.children [
                    Html.label [
                        prop.className "field-label"
                        prop.children [
                            Html.span "基金代码"
                            Html.input [
                                prop.className "text-input redemption-code-input"
                                prop.placeholder "六位基金代码"
                                prop.value model.redemptionCode
                                prop.onChange (fun value -> dispatch (RedemptionCodeChanged value))
                            ]
                        ]
                    ]
                    Html.label [
                        prop.className "field-label"
                        prop.children [
                            Html.span "赎回份额"
                            Html.input [
                                prop.className "text-input redemption-units-input"
                                prop.placeholder "例如 100.00000000"
                                prop.value model.redemptionUnits
                                prop.onChange (fun value -> dispatch (RedemptionUnitsChanged value))
                            ]
                        ]
                    ]
                    Html.label [
                        prop.className "field-label"
                        prop.children [
                            Html.span "赎回手续费(元)"
                            Html.input [
                                prop.className "text-input redemption-fee-input"
                                prop.placeholder "0.00 或 1.50"
                                prop.value model.redemptionFee
                                prop.onChange (fun value -> dispatch (RedemptionFeeChanged value))
                            ]
                        ]
                    ]
                    Html.button [
                        prop.className "primary-action redemption-submit-action"
                        prop.disabled model.redemptionInFlight
                        prop.onClick (fun _ -> dispatch RedemptionCreateRequested)
                        prop.text ((if model.redemptionInFlight then "赎回中..." else "提交赎回"): string)
                    ]
                ]
            ]
            Html.p [
                prop.className "hint"
                prop.text "份额与手续费按小数字符串提交;提交即冻结对应份额,确认前不产生任何现金变化。"
            ]
            Html.div [
                prop.className "pending-redemptions"
                prop.children [
                    if List.isEmpty model.redemptions then
                        Html.p [ prop.className "hint"; prop.text "暂无赎回订单" ]
                    else
                        yield! (model.redemptions |> List.map (fun order -> redemptionRow order model dispatch))
                ]
            ]
            Html.div [
                prop.className "panel-actions"
                prop.children [
                    Html.button [
                        prop.className "secondary-action redemptions-refresh-action"
                        prop.onClick (fun _ -> dispatch RedemptionsReadRequested)
                        prop.text "刷新赎回订单"
                    ]
                ]
            ]
        ]
    ]

let private sipFrequencyText (frequency: string) =
    if frequency = "weekly" then "每周"
    elif frequency = "biweekly" then "每两周"
    elif frequency = "monthly" then "每月"
    else frequency

let private sipPlanRow dispatch (plan: SipPlan) =
    Html.div [
        prop.className "order-row"
        prop.children [
            Html.span [ prop.className "order-code"; prop.text plan.instrumentCode ]
            Html.span [ prop.className "order-cell"; prop.text (sprintf "金额 %s" plan.amount) ]
            Html.span [ prop.className "order-cell"; prop.text (sprintf "频率 %s" (sipFrequencyText plan.frequency)) ]
            Html.span [ prop.className "order-cell"; prop.text (sprintf "起投日 %s" plan.anchorDate) ]
            Html.span [ prop.className "order-cell"; prop.text (sprintf "下次扣款 %s" plan.nextTradeDate) ]

            let lastExecution =
                match plan.lastExecutionStatus with
                | Some status ->
                    let label =
                        if status = "succeeded" then "已执行"
                        elif status = "pending_nav" then "待净值"
                        elif status = "insufficient_cash" then "现金不足"
                        elif status = "failed" then "失败"
                        else status

                    sprintf "最近执行 %s(%s)" label (plan.lastExecutionDate |> Option.defaultValue "—")
                | None -> "最近执行 暂无"

            Html.span [ prop.className "order-cell"; prop.text lastExecution ]
            Html.span [
                prop.className "order-status"
                prop.text (
                    if plan.status = "active" then "进行中"
                    elif plan.status = "paused" then "已暂停"
                    else plan.status
                )
            ]
            Html.span [
                prop.className "order-cell sip-plan-actions"
                prop.children [
                    if plan.status = "paused" then
                        Html.button [
                            prop.className "secondary-action sip-resume-action"
                            prop.onClick (fun _ -> dispatch (SipPlanResumeRequested plan.id))
                            prop.text "恢复"
                        ]
                    else
                        Html.button [
                            prop.className "secondary-action sip-pause-action"
                            prop.onClick (fun _ -> dispatch (SipPlanPauseRequested plan.id))
                            prop.text "暂停"
                        ]
                ]
            ]
        ]
    ]

let private sipPanel model dispatch =
    Html.section [
        prop.className "panel sip-panel"
        prop.children [
            Html.div [
                prop.className "section-heading"
                prop.children [
                    Html.div [
                        Html.p [ prop.className "eyebrow"; prop.text "07 / SIP" ]
                        Html.h2 "定期定额投资计划"
                    ]
                    Html.span [ prop.className "section-note"; prop.text "SIP · schedule only" ]
                ]
            ]
            Html.div [
                prop.className "fund-form-row"
                prop.children [
                    Html.label [
                        prop.className "field-label"
                        prop.children [
                            Html.span "基金代码"
                            Html.input [
                                prop.className "text-input sip-code-input"
                                prop.placeholder "六位基金代码"
                                prop.value model.sipCode
                                prop.onChange (fun value -> dispatch (SipCodeChanged value))
                            ]
                        ]
                    ]
                    Html.label [
                        prop.className "field-label"
                        prop.children [
                            Html.span "每期金额(元)"
                            Html.input [
                                prop.className "text-input sip-amount-input"
                                prop.placeholder "例如 200.00"
                                prop.value model.sipAmount
                                prop.onChange (fun value -> dispatch (SipAmountChanged value))
                            ]
                        ]
                    ]
                    Html.label [
                        prop.className "field-label"
                        prop.children [
                            Html.span "频率"
                            Html.select [
                                prop.className "text-input sip-frequency-input"
                                prop.value model.sipFrequency
                                prop.onChange (fun value -> dispatch (SipFrequencyChanged value))
                                prop.children [
                                    Html.option [ prop.value "weekly"; prop.text "每周" ]
                                    Html.option [ prop.value "biweekly"; prop.text "每两周" ]
                                    Html.option [ prop.value "monthly"; prop.text "每月" ]
                                ]
                            ]
                        ]
                    ]
                    Html.button [
                        prop.className "primary-action sip-submit-action"
                        prop.disabled model.sipInFlight
                        prop.onClick (fun _ -> dispatch SipPlanCreateRequested)
                        prop.text ((if model.sipInFlight then "创建中..." else "创建定投计划"): string)
                    ]
                ]
            ]
            Html.p [
                prop.className "hint"
                prop.text "计划只登记扣款节奏与金额;到期执行将在后续接入,当前不扣款、不动份额与净值。"
            ]
            Html.div [
                prop.className "sip-plans"
                prop.children [
                    if List.isEmpty model.sipPlans then
                        Html.p [ prop.className "hint"; prop.text "暂无定投计划" ]
                    else
                        yield! (model.sipPlans |> List.map (sipPlanRow dispatch))
                ]
            ]
            Html.div [
                prop.className "panel-actions"
                prop.children [
                    Html.button [
                        prop.className "secondary-action sip-plans-refresh-action"
                        prop.onClick (fun _ -> dispatch SipPlansReadRequested)
                        prop.text "刷新计划"
                    ]
                ]
            ]
        ]
    ]

let private rebalanceOutcomeRow (outcome: RebalanceOutcome) =
    let statusText =
        if outcome.status = "succeeded" then "已确认"
        elif outcome.status = "pending_nav" then "待净值"
        elif outcome.status = "insufficient_cash" then "现金不足"
        elif outcome.status = "insufficient_units" then "持仓不足"
        elif outcome.status = "failed" then "失败"
        elif outcome.status.StartsWith("skipped_") then "已跳过"
        else outcome.status

    let actionText =
        if outcome.action = "buy" then "买入"
        elif outcome.action = "sell" then "卖出"
        else outcome.action

    Html.div [
        prop.className "order-row"
        prop.children [
            Html.span [ prop.className "order-code"; prop.text outcome.instrumentCode ]
            Html.span [ prop.className "order-cell"; prop.text (sprintf "%s %s 元" actionText outcome.amount) ]
            Html.span [ prop.className "order-status"; prop.text statusText ]

            match outcome.pendingReason with
            | Some reason -> Html.span [ prop.className "order-detail"; prop.text reason ]
            | None -> Html.none
        ]
    ]

let private rebalanceActionText (action: string) =
    if action = "buy" then "买入"
    elif action = "sell" then "卖出"
    elif action = "hold" then "持有"
    else action

let private rebalanceTargetDraftRow (index: int) (draft: RebalanceTargetDraft) dispatch =
    Html.div [
        prop.className "fund-form-row rebalance-target-row"
        prop.children [
            Html.label [
                prop.className "field-label"
                prop.children [
                    Html.span (sprintf "目标基金 %d" (index + 1))
                    Html.input [
                        prop.className "text-input rebalance-target-code-input"
                        prop.placeholder "六位基金代码(留空则不参与)"
                        prop.value draft.code
                        prop.onChange (fun value -> dispatch (RebalTargetCodeChanged(index, value)))
                    ]
                ]
            ]
            Html.label [
                prop.className "field-label"
                prop.children [
                    Html.span "目标比例"
                    Html.input [
                        prop.className "text-input rebalance-target-percent-input"
                        prop.placeholder "例如 60.00"
                        prop.value draft.percent
                        prop.onChange (fun value -> dispatch (RebalTargetPercentChanged(index, value)))
                    ]
                ]
            ]
            Html.button [
                prop.className "secondary-action rebalance-target-remove-action"
                prop.onClick (fun _ -> dispatch (RebalTargetRemoved index))
                prop.text "删除"
            ]
        ]
    ]

let private rebalanceWeightRow (row: RebalanceWeightRow) =
    Html.div [
        prop.className "order-row rebalance-preview-row"
        prop.children [
            Html.span [ prop.className "order-code"; prop.text row.instrumentCode ]
            Html.span [
                prop.className "order-cell"
                prop.text (sprintf "目标 %s%% / 当前 %s%%" row.targetPercent row.currentPercent)
            ]
            Html.span [
                prop.className "order-cell"
                prop.text (
                    match row.deltaUnits with
                    | Some units -> sprintf "%s %s 元 / %s 份" (rebalanceActionText row.action) row.deltaAmount units
                    | None -> sprintf "%s %s 元" (rebalanceActionText row.action) row.deltaAmount
                )
            ]
        ]
    ]

let private rebalanceExecutionRow (record: RebalanceExecutionRecord) =
    let statusText =
        if record.status = "succeeded" then "已确认"
        elif record.status = "pending_nav" then "待净值"
        elif record.status = "insufficient_cash" then "现金不足"
        elif record.status = "insufficient_units" then "持仓不足"
        elif record.status = "failed" then "失败"
        elif record.status.StartsWith("skipped_") then "已跳过"
        else record.status

    Html.div [
        prop.className "order-row rebalance-execution-row"
        prop.children [
            Html.span [ prop.className "order-code"; prop.text record.instrumentCode ]
            Html.span [
                prop.className "order-cell"
                prop.text (sprintf "%s %s %s 元" record.runDate (rebalanceActionText record.action) record.amount)
            ]
            Html.span [ prop.className "order-status"; prop.text statusText ]

            match record.pendingReason with
            | Some reason -> Html.span [ prop.className "order-detail"; prop.text reason ]
            | None -> Html.none
        ]
    ]

let private rebalancePanel model dispatch =
    Html.section [
        prop.className "panel rebalance-panel"
        prop.children [
            Html.div [
                prop.className "section-heading"
                prop.children [
                    Html.div [
                        Html.p [ prop.className "eyebrow"; prop.text "12 / REBALANCE" ]
                        Html.h2 "组合再平衡"
                    ]
                    Html.span [ prop.className "section-note"; prop.text "Rebalance - target weights & execution" ]
                ]
            ]
            Html.div [
                prop.className "rebalance-targets"
                prop.children [
                    yield!
                        (model.rebalTargets
                         |> List.mapi (fun index draft -> rebalanceTargetDraftRow index draft dispatch))
                    Html.div [
                        prop.className "fund-form-row"
                        prop.children [
                            Html.button [
                                prop.className "secondary-action rebalance-target-add-action"
                                prop.onClick (fun _ -> dispatch RebalTargetAdded)
                                prop.text "添加目标"
                            ]
                            Html.button [
                                prop.className "primary-action rebalance-submit-action"
                                prop.disabled model.rebalInFlight
                                prop.onClick (fun _ -> dispatch RebalancePlanCreateRequested)
                                prop.text ((if model.rebalInFlight then "创建中..." else "创建计划"): string)
                            ]
                        ]
                    ]
                ]
            ]
            Html.p [
                prop.className "hint"
                prop.text
                    "参与的目标比例合计必须为 100,代码留空的行不参与;执行时按当日估值快照计算差额,经与手工单相同的下单与确认管线成交。"
            ]
            Html.div [
                prop.className "rebalance-plans"
                prop.children [
                    if List.isEmpty model.rebalPlans then
                        Html.p [ prop.className "hint"; prop.text "暂无再平衡计划" ]
                    else
                        yield!
                            (model.rebalPlans
                             |> List.map (fun plan ->
                                 Html.div [
                                     prop.className "order-row rebalance-plan-row"
                                     prop.children [
                                         Html.span [
                                             prop.className "order-cell"
                                             prop.text
                                                 (plan.targets
                                                  |> List.map (fun target -> sprintf "%s %s%%" target.instrumentCode target.targetPercent)
                                                  |> String.concat " / ")
                                         ]
                                         Html.span [
                                             prop.className "order-status"
                                             prop.text (if plan.status = "archived" then "已归档" else "进行中")
                                         ]
                                         (if plan.status = "active" then
                                              Html.span [
                                                  prop.className "order-actions"
                                                  prop.children [
                                                      Html.button [
                                                          prop.className "secondary-action rebalance-preview-action"
                                                          prop.disabled model.rebalPreviewInFlight
                                                          prop.onClick (fun _ -> dispatch (RebalancePreviewRequested plan.id))
                                                          prop.text ((if model.rebalPreviewInFlight then "计算中..." else "预览差额"): string)
                                                      ]
                                                      Html.button [
                                                          prop.className "secondary-action rebalance-execute-action"
                                                          prop.disabled model.rebalExecuteInFlight
                                                          prop.onClick (fun _ -> dispatch (RebalanceExecuteRequested plan.id))
                                                          prop.text ((if model.rebalExecuteInFlight then "执行中..." else "执行再平衡"): string)
                                                      ]
                                                      Html.button [
                                                          prop.className "secondary-action rebalance-archive-action"
                                                          prop.disabled model.rebalArchiveInFlight
                                                          prop.onClick (fun _ -> dispatch (RebalancePlanArchiveRequested plan.id))
                                                          prop.text "归档"
                                                      ]
                                                  ]
                                              ]
                                          else
                                              Html.none)
                                     ]
                                 ]))
                ]
            ]
            match model.rebalPreview with
            | Some preview ->
                let hasDrift =
                    preview.rows |> List.exists (fun row -> row.action <> "hold")

                Html.div [
                    prop.className "rebalance-preview"
                    prop.children [
                        Html.p [
                            prop.className "hint"
                            prop.text (
                                sprintf
                                    "估值快照 %s:权益 %s 元 / 可用现金 %s 元%s"
                                    preview.runDate
                                    preview.equity
                                    preview.availableCash
                                    (if hasDrift then "" else ",当前权重已在容差内")
                            )
                        ]
                        yield! (preview.rows |> List.map rebalanceWeightRow)
                    ]
                ]
            | None -> Html.none
            match model.rebalResult with
            | Some outcomes ->
                Html.div [
                    prop.className "rebalance-result"
                    prop.children [
                        Html.p [ prop.className "hint"; prop.text "最近一次执行:" ]

                        if List.isEmpty outcomes then
                            Html.p [
                                prop.className "hint"
                                prop.text "当前权重已在容差内,本次未产生任何交易"
                            ]
                        else
                            yield! (outcomes |> List.map rebalanceOutcomeRow)
                    ]
                ]
            | None -> Html.none
            Html.div [
                prop.className "rebalance-executions"
                prop.children [
                    Html.p [ prop.className "hint"; prop.text "执行记录:" ]

                    if List.isEmpty model.rebalExecutions then
                        Html.p [ prop.className "hint"; prop.text "暂无执行记录" ]
                    else
                        yield! (model.rebalExecutions |> List.map rebalanceExecutionRow)
                ]
            ]
            Html.div [
                prop.className "panel-actions"
                prop.children [
                    Html.button [
                        prop.className "secondary-action rebalance-plans-refresh-action"
                        prop.onClick (fun _ -> dispatch RebalancePlansReadRequested)
                        prop.text "刷新计划"
                    ]
                    Html.button [
                        prop.className "secondary-action rebalance-executions-refresh-action"
                        prop.disabled model.rebalExecutionsInFlight
                        prop.onClick (fun _ -> dispatch RebalanceExecutionsReadRequested)
                        prop.text ((if model.rebalExecutionsInFlight then "刷新中..." else "刷新执行记录"): string)
                    ]
                ]
            ]
        ]
    ]


let private dividendModeText (mode: string) =
    match mode with
    | "reinvest" -> "红利再投资"
    | _ -> "现金"

let private dividendStatusText (status: string) =
    match status with
    | "cash_credited"
    | "succeeded" -> "已入账"
    | "pending_nav" -> "待净值"
    | other -> other

let private dividendPanel model dispatch =
    Html.section [
        prop.className "panel dividend-panel"
        prop.children [
            Html.div [
                prop.className "section-heading"
                prop.children [
                    Html.div [
                        Html.p [ prop.className "eyebrow"; prop.text "09 / DIVIDEND" ]
                        Html.h2 "分红记录"
                    ]
                    Html.span [ prop.className "section-note"; prop.text "Dividends - booked history" ]
                ]
            ]
            Html.div [
                prop.className "dividend-history"
                prop.children [
                    if List.isEmpty model.dividends then
                        Html.p [ prop.className "hint"; prop.text "暂无分红记录" ]
                    else
                        yield!
                            (model.dividends
                             |> List.map (fun record ->
                                 Html.div [
                                     prop.className "order-row dividend-row"
                                     prop.children [
                                         Html.span [ prop.className "order-code"; prop.text record.instrumentCode ]
                                         Html.span [
                                             prop.className "order-cell"
                                             prop.text (sprintf "持仓日期 %s" record.navDate)
                                         ]
                                         Html.span [
                                             prop.className "order-cell"
                                             prop.text (sprintf "类型 %s" (dividendModeText record.mode))
                                         ]
                                         Html.span [
                                             prop.className "order-cell"
                                             prop.text (sprintf "每份分红 %s" record.dps)
                                         ]
                                         match record.grossCash with
                                         | Some cash ->
                                             Html.span [
                                                 prop.className "order-cell"
                                                 prop.text (sprintf "入账现金 %s" cash)
                                             ]
                                         | None -> Html.none
                                         match record.creditedUnits with
                                         | Some units ->
                                             Html.span [
                                                 prop.className "order-cell"
                                                 prop.text (sprintf "入账份额 %s" units)
                                             ]
                                         | None -> Html.none
                                         Html.span [ prop.className "order-status"; prop.text (dividendStatusText record.status) ]
                                         Html.span [
                                             prop.className "order-cell dividend-key"
                                             prop.title record.sourceKey
                                             prop.text record.sourceKey
                                         ]
                                     ]
                                 ]))
                ]
            ]
            Html.div [
                prop.className "panel-actions"
                prop.children [
                    Html.button [
                        prop.className "secondary-action dividend-refresh-action"
                        prop.disabled model.dividendInFlight
                        prop.onClick (fun _ -> dispatch DividendsReadRequested)
                        prop.text ((if model.dividendInFlight then "读取中..." else "刷新分红记录"): string)
                    ]
                ]
            ]
        ]
    ]

let private moneyText (text: string) =
    match Decimal.TryParse(text, NumberStyles.Float, CultureInfo.InvariantCulture) with
    | true, value -> value.ToString("0.00", CultureInfo.InvariantCulture)
    | false, _ -> text

let private shortTimestamp (text: string) =
    if String.IsNullOrWhiteSpace text then
        "暂无"
    else
        let normalized = text.Replace("T", " ")
        if normalized.Length >= 16 then normalized.Substring(0, 16) else normalized

let private returnsChartView (points: ReturnsPoint list) =
    let dates = points |> List.map (fun point -> point.date)

    let totalSeries =
        points
        |> List.choose (fun point -> point.totalAssets |> Option.map (fun value -> point.date, value))

    let navSeries =
        points
        |> List.choose (fun point -> point.unitNav |> Option.map (fun value -> point.date, value))

    let totalPoints = Chart.seriesPoints dates totalSeries
    let navPoints = Chart.seriesPoints dates navSeries

    if List.isEmpty totalPoints && List.isEmpty navPoints then
        Html.div [ prop.className "chart-empty"; prop.text "暂无收益数据" ]
    else
        let width = 960.0
        let height = 320.0
        let padding = 28.0
        let chartWidth = width - padding * 2.0
        let chartHeight = height - padding * 2.0

        let coordinates (series: SeriesPoint list) =
            series
            |> List.map (fun point -> padding + point.x * chartWidth, padding + (1.0 - point.y) * chartHeight)

        let gridLines =
            [ 0 .. 4 ]
            |> List.map (fun index ->
                let y = padding + float index / 4.0 * chartHeight

                Svg.line [
                    svg.x1 padding
                    svg.y1 y
                    svg.x2 (width - padding)
                    svg.y2 y
                    svg.stroke "#e2e8f0"
                    svg.strokeWidth 1
                ])

        let markers color (series: SeriesPoint list) =
            coordinates series
            |> List.map (fun (x, y) ->
                Svg.circle [
                    svg.cx x
                    svg.cy y
                    svg.r 3.5
                    svg.fill color
                ])

        Html.div [
            prop.className "chart-wrap returns-chart"
            prop.children [
                Svg.svg [
                    svg.className "nav-chart"
                    svg.viewBox (0, 0, 960, 320)
                    svg.children [
                        yield! gridLines
                        if List.length totalPoints >= 2 then
                            yield
                                Svg.polyline [
                                    svg.points (coordinates totalPoints)
                                    svg.fill "none"
                                    svg.stroke "#1e40af"
                                    svg.strokeWidth 3
                                ]
                        if List.length navPoints >= 2 then
                            yield
                                Svg.polyline [
                                    svg.points (coordinates navPoints)
                                    svg.fill "none"
                                    svg.stroke "#f59e0b"
                                    svg.strokeWidth 3
                                ]
                        yield! markers "#1e40af" totalPoints
                        yield! markers "#f59e0b" navPoints
                    ]
                ]
                Html.div [
                    prop.className "chart-axis"
                    prop.children [
                        Html.span [ prop.text (points |> List.head |> fun point -> point.date) ]
                        Html.span [ prop.text (points |> List.last |> fun point -> point.date) ]
                    ]
                ]
            ]
        ]

let private marketNavSeriesView (points: MarketNavSeriesPoint list) =
    let ordered = points |> List.sortBy (fun point -> point.navDate)
    let dates = ordered |> List.map (fun point -> point.navDate)
    let navSeries = ordered |> List.map (fun point -> point.navDate, point.nav)
    let navPoints = Chart.seriesPoints dates navSeries

    let empty =
        Html.div [
            prop.className "chart-empty returns-nav-series-empty"
            prop.hidden (not (List.isEmpty navPoints))
            prop.text "暂无真实净值数据"
        ]

    let chart =
        if List.isEmpty navPoints then
            Html.none
        else
            let width = 960.0
            let height = 320.0
            let padding = 28.0
            let chartWidth = width - padding * 2.0
            let chartHeight = height - padding * 2.0

            let coordinates (series: SeriesPoint list) =
                series
                |> List.map (fun point -> padding + point.x * chartWidth, padding + (1.0 - point.y) * chartHeight)

            let gridLines =
                [ 0 .. 4 ]
                |> List.map (fun index ->
                    let y = padding + float index / 4.0 * chartHeight

                    Svg.line [
                        svg.x1 padding
                        svg.y1 y
                        svg.x2 (width - padding)
                        svg.y2 y
                        svg.stroke "#e2e8f0"
                        svg.strokeWidth 1
                    ])

            Html.div [
                prop.className "chart-wrap returns-nav-series-chart"
                prop.children [
                    Svg.svg [
                        svg.className "nav-chart"
                        svg.viewBox (0, 0, 960, 320)
                        svg.children [
                            yield! gridLines
                            yield
                                Svg.polyline [
                                    svg.points (coordinates navPoints)
                                    svg.fill "none"
                                    svg.stroke "#f59e0b"
                                    svg.strokeWidth 3
                                ]
                            yield!
                                (coordinates navPoints
                                 |> List.map (fun (x, y) ->
                                     Svg.circle [
                                         svg.className "nav-series-marker"
                                         svg.cx x
                                         svg.cy y
                                         svg.r 3.5
                                         svg.fill "#f59e0b"
                                     ]))
                        ]
                    ]
                    Html.div [
                        prop.className "chart-axis"
                        prop.children [
                            Html.span [ prop.text (ordered |> List.head |> fun point -> point.navDate) ]
                            Html.span [ prop.text (ordered |> List.last |> fun point -> point.navDate) ]
                        ]
                    ]
                ]
            ]

    Html.div [
        prop.className "returns-nav-series"
        prop.custom ("data-nav-series-points", string (List.length navPoints))
        prop.children [ empty; chart ]
    ]

let private returnsPanel model dispatch =
    let visiblePoints =
        match model.returns with
        | None -> []
        | Some returns ->
            match model.returnsSelectedDate with
            | Some selected -> returns.points |> List.filter (fun point -> point.date <= selected)
            | None -> returns.points

    let latest (selector: ReturnsPoint -> string option) = visiblePoints |> List.rev |> List.tryPick selector

    let totalAssets = latest (fun point -> point.totalAssets)
    let cumulativeReturn = latest (fun point -> point.cumulativeReturn)
    let updatedAt = model.returns |> Option.bind (fun returns -> returns.dataUpdatedAt)

    Html.section [
        prop.className "panel returns-panel"
        prop.children [
            Html.div [
                prop.className "section-heading"
                prop.children [
                    Html.div [
                        Html.p [ prop.className "eyebrow"; prop.text "10 / RETURNS" ]
                        Html.h2 "收益与资产曲线"
                    ]
                    Html.span [ prop.className "section-note"; prop.text "Returns - cash-flow adjusted" ]
                ]
            ]
            Html.div [
                prop.className "returns-date-picker"
                prop.custom (
                    "data-nav-dates-state",
                    (if model.navDatesAvailable then "available" else "empty")
                )
                prop.children [
                    Html.label [
                        prop.className "field-label"
                        prop.children [
                            Html.span "真实净值日期"
                            Html.select [
                                prop.className "text-input returns-date-input"
                                prop.disabled (not model.navDatesAvailable)
                                prop.value (defaultArg model.returnsSelectedDate "")
                                prop.onChange (fun value -> dispatch (ReturnsDateChanged value))
                                prop.children [
                                    Html.option [ prop.value ""; prop.text "最新" ]
                                    yield!
                                        (model.navDates
                                         |> List.map (fun date -> Html.option [ prop.value date; prop.text date ]))
                                ]
                            ]
                        ]
                    ]
                    Html.p [
                        prop.className "returns-date-empty"
                        prop.hidden model.navDatesAvailable
                        prop.text "暂无真实净值数据"
                    ]
                ]
            ]
            match model.returns with
            | None ->
                Html.p [ prop.className "hint"; prop.text "创建基金后可读取收益曲线。" ]
            | Some returns when List.isEmpty returns.points ->
                Html.p [ prop.className "hint"; prop.text "暂无收益数据" ]
            | Some returns ->
                Html.div [
                    prop.className "nav-content"
                    prop.children [
                        Html.div [
                            prop.className "metric-strip"
                            prop.children [
                                Html.div [
                                    prop.className "metric"
                                    prop.children [
                                        Html.span "总资产"
                                        Html.strong (totalAssets |> Option.map moneyText |> Option.defaultValue "暂无")
                                    ]
                                ]
                                Html.div [
                                    prop.className "metric"
                                    prop.children [
                                        Html.span "累计收益"
                                        Html.strong (cumulativeReturn |> Option.map moneyText |> Option.defaultValue "暂无")
                                    ]
                                ]
                                Html.div [
                                    prop.className "metric"
                                    prop.children [
                                        Html.span "数据更新时间"
                                        Html.strong (updatedAt |> Option.map shortTimestamp |> Option.defaultValue "暂无")
                                    ]
                                ]
                            ]
                        ]
                        returnsChartView visiblePoints
                        Html.p [
                            prop.className "returns-note"
                            prop.text "蓝线 总资产 / 橙线 单位净值(各自归一化);缺少净值的数据点不连线,也不补零。"
                        ]
                        Html.p [
                            prop.className "returns-subheading"
                            prop.text "持仓基金真实净值序列(AKShare 多日)"
                        ]
                        marketNavSeriesView model.navSeries
                        if returns.pending then
                            Html.p [
                                prop.className "returns-pending"
                                prop.text "部分持有基金缺少估值日净值,相关日期标记为待更新。"
                            ]
                    ]
                ]
            Html.div [
                prop.className "panel-actions"
                prop.children [
                    Html.button [
                        prop.className "secondary-action returns-refresh-action"
                        prop.disabled model.returnsInFlight
                        prop.onClick (fun _ -> dispatch ReturnsReadRequested)
                        prop.text ((if model.returnsInFlight then "读取中..." else "刷新收益曲线"): string)
                    ]
                ]
            ]
        ]
    ]

let private investmentPlanFrequencyText (frequency: string) =
    if frequency = "daily" then "每日"
    elif frequency = "weekly" then "每周"
    elif frequency = "monthly" then "每月"
    else frequency

let private investmentPlanRunStatusText (status: string) =
    if status = "succeeded" then "已执行"
    elif status = "pending_nav" then "待净值"
    elif status = "insufficient_cash" then "现金不足"
    elif status = "failed" then "失败"
    else status

let private investmentPlanRow (plan: InvestmentPlan) =
    Html.div [
        prop.className "order-row"
        prop.children [
            Html.span [ prop.className "order-code"; prop.text plan.instrumentCode ]
            Html.span [ prop.className "order-cell"; prop.text (sprintf "金额 %s" plan.amount) ]
            Html.span [ prop.className "order-cell"; prop.text (sprintf "频率 %s" (investmentPlanFrequencyText plan.frequency)) ]
            Html.span [ prop.className "order-cell"; prop.text (sprintf "起始日 %s" plan.anchorDate) ]
            Html.span [ prop.className "order-cell"; prop.text (sprintf "下次执行 %s" plan.nextRunDate) ]

            let lastRun =
                match plan.lastRunStatus with
                | Some status ->
                    sprintf "最近执行 %s(%s)" (investmentPlanRunStatusText status) (plan.lastRunDate |> Option.defaultValue "—")
                | None -> "最近执行 暂无"

            Html.span [ prop.className "order-cell"; prop.text lastRun ]
            Html.span [ prop.className "order-status"; prop.text (if plan.status = "active" then "进行中" else plan.status) ]
        ]
    ]

let private investmentPlanRunRow (plan: InvestmentPlanRunPlan) =
    Html.div [
        prop.className "order-row"
        prop.children [
            Html.span [ prop.className "order-code"; prop.text plan.instrumentCode ]
            Html.span [ prop.className "order-cell"; prop.text (sprintf "金额 %s" plan.amount) ]
            Html.span [ prop.className "order-cell"; prop.text (sprintf "频率 %s" (investmentPlanFrequencyText plan.frequency)) ]

            let runs =
                if List.isEmpty plan.runs then
                    "本次无到期扣款"
                else
                    plan.runs
                    |> List.map (fun run -> sprintf "%s %s" run.runDate (investmentPlanRunStatusText run.status))
                    |> String.concat "、"

            Html.span [ prop.className "order-cell"; prop.text runs ]
            Html.span [ prop.className "order-cell"; prop.text (sprintf "下次执行 %s" plan.nextRunDate) ]
        ]
    ]

let private investmentPlansPanel model dispatch =
    Html.section [
        prop.className "panel plans-panel"
        prop.children [
            Html.div [
                prop.className "section-heading"
                prop.children [
                    Html.div [
                        Html.p [ prop.className "eyebrow"; prop.text "11 / PLANS" ]
                        Html.h2 "定投计划执行"
                    ]
                    Html.span [ prop.className "section-note"; prop.text "scheduled contribution" ]
                ]
            ]
            Html.p [
                prop.className "hint"
                prop.text "执行到期计划:按当日净值扣款买入,重复执行不产生第二笔;存款与买入都不计入收益。"
            ]
            Html.div [
                prop.className "sip-plans plans-list"
                prop.children [
                    if List.isEmpty model.investmentPlans then
                        Html.p [ prop.className "hint"; prop.text "暂无定投计划" ]
                    else
                        yield! (model.investmentPlans |> List.map investmentPlanRow)
                ]
            ]
            match model.lastPlanRun with
            | Some run ->
                Html.div [
                    prop.className "plans-run-result"
                    prop.children [
                        Html.p [ prop.className "hint"; prop.text (sprintf "最近执行处理日 %s" run.processingDate) ]

                        if List.isEmpty run.plans then
                            Html.p [ prop.className "hint"; prop.text "本次没有可执行的计划" ]
                        else
                            yield! (run.plans |> List.map investmentPlanRunRow)
                    ]
                ]
            | None -> Html.none
            Html.div [
                prop.className "panel-actions"
                prop.children [
                    Html.button [
                        prop.className "primary-action plans-run-action"
                        prop.disabled model.planRunInFlight
                        prop.onClick (fun _ -> dispatch InvestmentPlansRunRequested)
                        prop.text ((if model.planRunInFlight then "执行中..." else "执行到期计划"): string)
                    ]
                    Html.button [
                        prop.className "secondary-action plans-refresh-action"
                        prop.disabled model.planInFlight
                        prop.onClick (fun _ -> dispatch InvestmentPlansReadRequested)
                        prop.text ((if model.planInFlight then "读取中..." else "刷新计划"): string)
                    ]
                ]
            ]
        ]
    ]

let private bondQuoteMetric (label: string) (value: string option) =
    Html.div [
        prop.className "metric"
        prop.children [
            Html.span label
            Html.strong (value |> Option.defaultValue "—")
        ]
    ]

let private bondsPanel model dispatch =
    Html.section [
        prop.className "panel bonds-panel"
        prop.children [
            Html.div [
                prop.className "section-heading"
                prop.children [
                    Html.div [
                        Html.p [ prop.className "eyebrow"; prop.text "13 / BONDS" ]
                        Html.h2 "债券行情探针"
                    ]
                    Html.span [ prop.className "section-note"; prop.text "AKShare · convertible spot" ]
                ]
            ]
            Html.p [
                prop.className "bonds-note"
                prop.text "数据来源实时 AKShare 可转债行情,仅查询单一债券代码,不做本地模拟。"
            ]
            Html.div [
                prop.className "search-row"
                prop.children [
                    Html.input [
                        prop.className "text-input bond-code-input"
                        prop.placeholder "输入六位债券代码,如 110075"
                        prop.value model.bondCode
                        prop.onChange (fun value -> dispatch (BondCodeChanged value))
                    ]
                    Html.button [
                        prop.className "primary-action bond-quote-action"
                        prop.disabled model.bondQuoteInFlight
                        prop.onClick (fun _ -> dispatch BondQuoteRequested)
                        prop.text ((if model.bondQuoteInFlight then "查询中..." else "查询行情"): string)
                    ]
                ]
            ]
            Html.p [
                prop.className "bond-quote-unavailable"
                prop.hidden (model.bondQuoteMessage.IsNone)
                prop.text (model.bondQuoteMessage |> Option.defaultValue "")
            ]
            match model.bondQuote with
            | Some quote ->
                Html.div [
                    prop.className "nav-content bond-quote-result"
                    prop.children [
                        Html.div [
                            prop.className "metric-strip"
                            prop.children [
                                bondQuoteMetric "名称" quote.name
                                bondQuoteMetric "净价" quote.cleanPrice
                                bondQuoteMetric "应计利息" quote.accruedInterestComputed
                                bondQuoteMetric "全价" quote.dirtyPrice
                                bondQuoteMetric "票息率" quote.couponRate
                                bondQuoteMetric "面值" quote.parValue
                                bondQuoteMetric "起息日" quote.valueDate
                                bondQuoteMetric "到期日" quote.maturityDate
                                bondQuoteMetric "评级" quote.rating
                                bondQuoteMetric "估值日期" quote.valuationDate
                                bondQuoteMetric "数据质量" quote.dataStatus
                            ]
                        ]
                    ]
                ]
            | None ->
                Html.p [ prop.className "hint"; prop.text "查询后显示名称/价格/到期日;缺失字段以「—」表示,不补零。" ]
            Html.div [
                prop.className "bond-trade"
                prop.children [
                    Html.p [ prop.className "returns-subheading"; prop.text "买入(以实时行情价成交)" ]
                    Html.div [
                        prop.className "search-row"
                        prop.children [
                            Html.input [
                                prop.className "text-input bond-trade-quantity-input"
                                prop.placeholder "买入数量(整数张),如 10"
                                prop.value model.bondTradeQuantity
                                prop.onChange (fun value -> dispatch (BondTradeQuantityChanged value))
                            ]
                            Html.button [
                                prop.className "primary-action bond-trade-action"
                                prop.disabled model.bondTradeInFlight
                                prop.onClick (fun _ -> dispatch BondTradeRequested)
                                prop.text ((if model.bondTradeInFlight then "买入中..." else "买入"): string)
                            ]
                            Html.button [
                                prop.className "secondary-action bond-positions-refresh-action"
                                prop.disabled model.bondPositionsInFlight
                                prop.onClick (fun _ -> dispatch BondPositionsReadRequested)
                                prop.text ((if model.bondPositionsInFlight then "读取中..." else "刷新持仓"): string)
                            ]
                        ]
                    ]
                    Html.p [
                        prop.className "bond-trade-unavailable"
                        prop.hidden (model.bondTradeMessage.IsNone)
                        prop.text (model.bondTradeMessage |> Option.defaultValue "")
                    ]
                ]
            ]
            Html.div [
                prop.className "bond-positions"
                prop.hidden (List.isEmpty model.bondPositions)
                prop.children (
                    Html.p [ prop.className "returns-subheading"; prop.text "债券持仓" ]
                    :: Html.div [
                        prop.className "bond-positions-row bond-positions-header"
                        prop.children [
                            Html.span [ prop.className "fund-detail-label"; prop.text "代码" ]
                            Html.span [ prop.className "fund-detail-label"; prop.text "名称" ]
                            Html.span [ prop.className "fund-detail-label"; prop.text "数量" ]
                            Html.span [ prop.className "fund-detail-label"; prop.text "成本" ]
                        ]
                    ]
                    :: (model.bondPositions
                        |> List.map (fun position ->
                            Html.div [
                                prop.className "bond-positions-row bond-position-row"
                                prop.children [
                                    Html.span [ prop.className "fund-detail-value"; prop.text position.instrumentCode ]
                                    Html.span [ prop.className "fund-detail-value"; prop.text (position.bondName |> Option.defaultValue "—") ]
                                    Html.span [ prop.className "fund-detail-value"; prop.text position.quantity ]
                                    Html.span [ prop.className "fund-detail-value"; prop.text position.costCash ]
                                ]
                            ]))
                )
            ]
            Html.p [
                prop.className "bond-positions-unavailable"
                prop.hidden (model.bondPositionsMessage.IsNone)
                prop.text (model.bondPositionsMessage |> Option.defaultValue "")
            ]
        ]
    ]

let private stocksPanel model dispatch =
    Html.section [
        prop.className "panel stocks-panel"
        prop.children [
            Html.div [
                prop.className "section-heading"
                prop.children [
                    Html.div [
                        Html.p [ prop.className "eyebrow"; prop.text "14 / STOCKS" ]
                        Html.h2 "股票行情探针"
                    ]
                    Html.span [ prop.className "section-note"; prop.text "AKShare · A-share spot" ]
                ]
            ]
            Html.p [
                prop.className "bonds-note"
                prop.text "数据来源实时 AKShare A 股行情,仅查询单一六位代码,不做本地模拟,不补零。"
            ]
            Html.div [
                prop.className "search-row"
                prop.children [
                    Html.input [
                        prop.className "text-input stock-code-input"
                        prop.placeholder "输入六位股票代码,如 600519"
                        prop.value model.stockCode
                        prop.onChange (fun value -> dispatch (StockCodeChanged value))
                    ]
                    Html.button [
                        prop.className "primary-action stock-quote-action"
                        prop.disabled model.stockQuoteInFlight
                        prop.onClick (fun _ -> dispatch StockQuoteRequested)
                        prop.text ((if model.stockQuoteInFlight then "查询中..." else "查询行情"): string)
                    ]
                    Html.button [
                        prop.className "secondary-action stock-daily-action"
                        prop.disabled model.stockDailyInFlight
                        prop.onClick (fun _ -> dispatch StockDailyRequested)
                        prop.text ((if model.stockDailyInFlight then "读取中..." else "查询近5日日线"): string)
                    ]
                ]
            ]
            Html.p [
                prop.className "stock-quote-unavailable"
                prop.hidden (model.stockQuoteMessage.IsNone)
                prop.text (model.stockQuoteMessage |> Option.defaultValue "")
            ]
            match model.stockQuote with
            | Some quote ->
                Html.div [
                    prop.className "nav-content stock-quote-result"
                    prop.children [
                        Html.div [
                            prop.className "metric-strip"
                            prop.children [
                                bondQuoteMetric "名称" quote.name
                                bondQuoteMetric "价格" quote.price
                                bondQuoteMetric "币种" (Some quote.currency)
                            ]
                        ]
                    ]
                ]
            | None ->
                Html.p [ prop.className "hint"; prop.text "查询后显示名称/价格/币种;缺失字段以「—」表示。" ]
            Html.div [
                prop.className "stock-daily"
                prop.hidden (List.isEmpty model.stockDaily)
                prop.children (
                    Html.p [ prop.className "returns-subheading"; prop.text "近 5 个交易日收盘" ]
                    :: (model.stockDaily
                        |> List.map (fun bar ->
                            Html.div [
                                prop.className "order-row stock-daily-row"
                                prop.children [
                                    Html.span [ prop.className "fund-detail-label"; prop.text bar.date ]
                                    Html.span [ prop.className "fund-detail-value"; prop.text bar.close ]
                                ]
                            ]))
                )
            ]
            Html.p [
                prop.className "stock-daily-unavailable"
                prop.hidden (model.stockDailyMessage.IsNone)
                prop.text (model.stockDailyMessage |> Option.defaultValue "")
            ]
            Html.div [
                prop.className "stock-trade"
                prop.children [
                    Html.p [ prop.className "returns-subheading"; prop.text "买入(以实时行情价成交)" ]
                    Html.div [
                        prop.className "search-row"
                        prop.children [
                            Html.input [
                                prop.className "text-input stock-trade-quantity-input"
                                prop.placeholder "买入数量(整数股),如 100"
                                prop.value model.stockTradeQuantity
                                prop.onChange (fun value -> dispatch (StockTradeQuantityChanged value))
                            ]
                            Html.button [
                                prop.className "primary-action stock-trade-action"
                                prop.disabled model.stockTradeInFlight
                                prop.onClick (fun _ -> dispatch StockTradeRequested)
                                prop.text ((if model.stockTradeInFlight then "买入中..." else "买入"): string)
                            ]
                            Html.button [
                                prop.className "secondary-action stock-positions-refresh-action"
                                prop.disabled model.stockPositionsInFlight
                                prop.onClick (fun _ -> dispatch StockPositionsReadRequested)
                                prop.text ((if model.stockPositionsInFlight then "读取中..." else "刷新持仓"): string)
                            ]
                        ]
                    ]
                    Html.p [
                        prop.className "stock-trade-unavailable"
                        prop.hidden (model.stockTradeMessage.IsNone)
                        prop.text (model.stockTradeMessage |> Option.defaultValue "")
                    ]
                ]
            ]
            Html.div [
                prop.className "stock-positions"
                prop.hidden (List.isEmpty model.stockPositions)
                prop.children (
                    Html.p [ prop.className "returns-subheading"; prop.text "股票持仓" ]
                    :: Html.div [
                        prop.className "stock-positions-row stock-positions-header"
                        prop.children [
                            Html.span [ prop.className "fund-detail-label"; prop.text "代码" ]
                            Html.span [ prop.className "fund-detail-label"; prop.text "名称" ]
                            Html.span [ prop.className "fund-detail-label"; prop.text "数量" ]
                            Html.span [ prop.className "fund-detail-label"; prop.text "成本" ]
                            Html.span [ prop.className "fund-detail-label"; prop.text "卖出数量" ]
                            Html.span [ prop.className "fund-detail-label"; prop.text "操作" ]
                        ]
                    ]
                    :: (model.stockPositions
                        |> List.map (fun position ->
                            Html.div [
                                prop.className "stock-positions-row stock-position-row"
                                prop.children [
                                    Html.span [ prop.className "fund-detail-value"; prop.text position.instrumentCode ]
                                    Html.span [ prop.className "fund-detail-value"; prop.text (position.stockName |> Option.defaultValue "—") ]
                                    Html.span [ prop.className "fund-detail-value"; prop.text position.quantity ]
                                    Html.span [ prop.className "fund-detail-value"; prop.text position.costCash ]
                                    Html.input [
                                        prop.className "text-input stock-sell-quantity-input"
                                        prop.placeholder "卖出数量"
                                        prop.value (model.stockSellQuantities |> Map.tryFind position.instrumentCode |> Option.defaultValue "")
                                        prop.onChange (fun value -> dispatch (StockSellQuantityChanged(position.instrumentCode, value)))
                                    ]
                                    Html.button [
                                        prop.className "secondary-action stock-sell-action"
                                        prop.disabled model.stockSellInFlight
                                        prop.onClick (fun _ -> dispatch (StockSellRequested position.instrumentCode))
                                        prop.text ((if model.stockSellInFlight then "卖出中..." else "卖出"): string)
                                    ]
                                ]
                            ]))
                )
            ]
            Html.p [
                prop.className "stock-positions-unavailable"
                prop.hidden (model.stockPositionsMessage.IsNone)
                prop.text (model.stockPositionsMessage |> Option.defaultValue "")
            ]
            Html.p [
                prop.className "stock-sell-message"
                prop.hidden (model.stockSellMessage.IsNone)
                prop.text (model.stockSellMessage |> Option.defaultValue "")
            ]
            Html.div [
                prop.className "fund-valuation"
                prop.children [
                    Html.p [ prop.className "returns-subheading"; prop.text "组合估值" ]
                    Html.div [
                        prop.className "search-row"
                        prop.children [
                            Html.button [
                                prop.className "secondary-action valuation-refresh-action"
                                prop.disabled model.valuationInFlight
                                prop.onClick (fun _ -> dispatch ValuationReadRequested)
                                prop.text ((if model.valuationInFlight then "估值中..." else "刷新估值"): string)
                            ]
                            Html.button [
                                prop.className "secondary-action market-refresh-action"
                                prop.disabled model.marketRefreshInFlight
                                prop.onClick (fun _ -> dispatch MarketRefreshRequested)
                                prop.text ((if model.marketRefreshInFlight then "刷新中..." else "刷新行情"): string)
                            ]
                        ]
                    ]
                    Html.p [
                        prop.className "market-refresh-message"
                        prop.hidden (model.marketRefreshMessage.IsNone)
                        prop.text (model.marketRefreshMessage |> Option.defaultValue "")
                    ]
                    match model.valuation with
                    | Some valuation ->
                        Html.div [
                            prop.className "valuation-content"
                            prop.children (
                                [ Html.div [
                                      prop.className "metric-strip valuation-metrics"
                                      prop.children [
                                          bondQuoteMetric "现金" (Some valuation.cash)
                                          bondQuoteMetric "持仓市值" (Some valuation.positionsMarketValue)
                                          bondQuoteMetric "组合合计" (Some valuation.portfolioValue)
                                          bondQuoteMetric "已定价/缺失" (Some(sprintf "%d / %d" valuation.pricedPositions valuation.unavailablePositions))
                                      ]
                                  ] ]
                                @ (valuation.positions
                                   |> List.map (fun position ->
                                       Html.div [
                                           prop.className (
                                               if position.status = "unavailable" then
                                                   "valuation-row valuation-position-row valuation-unavailable"
                                               else
                                                   "valuation-row valuation-position-row"
                                           )
                                           prop.children [
                                               Html.span [ prop.className "fund-detail-label"; prop.text position.instrumentCode ]
                                               Html.span [ prop.className "fund-detail-value"; prop.text (position.name |> Option.defaultValue "—") ]
                                               Html.span [ prop.className "fund-detail-value"; prop.text position.quantity ]
                                               Html.span [
                                                   prop.className "fund-detail-value"
                                                   prop.text (position.marketValue |> Option.defaultValue "缺失")
                                               ]
                                               Html.span [ prop.className "fund-detail-value"; prop.text (position.priceSource |> Option.defaultValue "—") ]
                                           ]
                                       ]))
                            )
                        ]
                    | None -> Html.p [ prop.className "hint"; prop.text "刷新后显示现金/持仓市值/组合合计;缺失行情标的不补零,标记为缺失。" ]
                    Html.p [
                        prop.className "valuation-unavailable"
                        prop.hidden (model.valuationMessage.IsNone)
                        prop.text (model.valuationMessage |> Option.defaultValue "")
                    ]
                ]
            ]
        ]
    ]

let view model dispatch =
    Html.main [
        prop.className "app-shell"
        prop.children [
            Html.header [
                prop.className "topbar"
                prop.children [
                    Html.div [
                        prop.className "brand"
                        prop.children [
                            Html.span [ prop.className "brand-mark"; prop.text "F" ]
                            Html.span "FUND LAB"
                        ]
                    ]
                    Html.span [ prop.className "topbar-status"; prop.text "LEDGER / 3D-1" ]
                ]
            ]
            Html.div [
                prop.className "hero"
                prop.children [
                    Html.div [
                        prop.className "hero-copy"
                        prop.children [
                            Html.p [ prop.className "eyebrow"; prop.text "人民币模拟基金 · 观察台" ]
                            Html.h1 "把净值曲线,先看清楚。"
                            Html.p "从真实基金代码开始,读取、校验并追踪每日单位净值。认购只生成待确认订单并冻结现金,不执行真实交易。"
                        ]
                    ]
                    Html.div [
                        prop.className "token-card"
                        prop.children [
                            Html.label [
                                prop.className "field-label"
                                prop.children [
                                    Html.span "API TOKEN"
                                    Html.input [
                                        prop.className "text-input token-input"
                                        prop.type' "password"
                                        prop.placeholder "仅保存在当前页面内存"
                                        prop.value model.token
                                        prop.onChange (fun value -> dispatch (TokenChanged value))
                                    ]
                                ]
                            ]
                            Html.p [ prop.className "token-note"; prop.text "请求通过 Bearer header 发送,不写入构建产物。" ]
                        ]
                    ]
                ]
            ]
            match model.error with
            | Some message -> Html.div [ prop.className "error-banner"; prop.text message ]
            | None -> Html.none
            searchPanel model dispatch
            navPanel model dispatch
            fundPanel model dispatch
            subscribePanel model dispatch
            positionsPanel model dispatch
            redeemPanel model dispatch
            sipPanel model dispatch
            dividendPanel model dispatch
            returnsPanel model dispatch
            investmentPlansPanel model dispatch
            rebalancePanel model dispatch
            bondsPanel model dispatch
            stocksPanel model dispatch
            Html.footer [ prop.className "footer-note"; prop.text "SOURCE · AKShare   /   STORAGE · PostgreSQL   /   LEDGER · CREATE & READ & SUBSCRIBE" ]
        ]
    ]

let start () =
    Program.mkProgram (fun () -> init (), Cmd.none) update view
    |> Program.withReactSynchronous "fund-lab-root"
    |> Program.run