All files / account-summary/domain account-summary-event-handler-clean.ts

57.69% Statements 401/695
48.78% Branches 220/451
68.75% Functions 55/80
57.84% Lines 398/688

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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                                                                                                                  1x                   17x 17x 17x 17x 17x   17x 17x           13x 13x   12x 12x         12x 14x   14x 3x       3x     11x 11x         12x   12x           12x     12x 12x                                                 12x   12x                   12x         12x       12x 1x     11x   11x       1x           10x 10x   10x 12x           12x   11x 11x                     9x                       9x 9x       9x     9x           9x       9x   1x       1x                 9x   9x     9x                 9x   9x                       9x                         12x 17x 17x 17x 17x   17x         14x       11x     24x             27x                             12x   12x 12x               12x 11x       11x 11x   11x 1x               1x       11x       11x 19x 19x   11x 7x 7x   11x                   12x       12x   12x 12x 12x     12x 12x 12x 12x 12x     12x 10x         10x 10x   10x                           12x     12x     12x 12x       12x               12x                                                   12x         12x   11x   11x   11x       4x   7x                                 12x     11x                     11x             11x       11x     11x 11x   11x           11x   11x 4x 7x 7x                                                                                                                                                                                                                                                                                                             4x               4x 12x   4x 14x       4x 4x 4x   4x     4x       4x           4x         4x   4x                                                                               4x                                                     7x               7x     7x 14x   7x 7x       7x 7x     7x 7x   7x                   7x       7x           7x         7x   7x   2x 2x 3x   2x             2x 2x         2x           2x                     2x       7x 2x     7x         7x                                                                                               11x 22x   18x 18x         18x         18x         18x   18x                                                     11x 9x   7x 7x             7x         7x           7x           7x     7x 7x       7x                                                                     4x       4x     4x                   4x           4x               4x   4x     4x     4x   4x                                   3x                                                                                                   3x               2x             2x                   1x   1x       1x                   7x                 7x                                                                                                                                                     7x     7x         4x           4x                             4x                                                                               4x     4x   4x     4x                                   4x             4x                                   4x             4x             4x           4x           4x           4x                 11x 11x 26x             11x 11x 21x                     13x 33x                 13x 29x                               7x                             6x 6x   6x 6x 6x 6x 6x 6x   6x                                                                   11x     11x         11x 2x       11x   9x     9x             9x     11x               22x   22x 22x   22x 22x 58x     22x 22x 47x       22x   22x         22x         22x           22x 58x 58x   58x                   58x               58x   58x               58x 33x 33x               22x                                         4x   4x         4x             4x                                                                     4x 4x 3x 3x 3x   3x         3x 3x   3x               3x       3x   4x           9x   9x 13x   13x 13x   13x 13x               13x     13x   13x                                                 13x 13x 13x 13x     13x       13x               13x 13x     9x                 9x     9x           9x                 9x 9x                       9x                 4x                   18x                     18x     18x 54x   6x 6x   48x                       48x   12x 12x   36x                                                                                                                                     2x 2x                             2x             2x                 2x 2x 2x   2x                       2x                             15x                                                                                                                                   15x   15x                       15x           3x   3x     3x   3x               3x       12x                           3x   3x         3x 4x           3x         3x           3x                                                                                                         4x     4x   4x               4x                 4x   4x       4x                         4x 4x 4x 4x 4x         4x   4x     4x             4x                                                             8x                               8x   8x                                   15x     15x         15x 15x   15x 33x       90x           15x         15x 15x   15x                 15x                 15x         15x                                                                                                                                                                                           15x   12x     12x           12x 12x               3x   3x     3x           3x 3x                                                                                                          
import { autoInjectable, inject, singleton } from "tsyringe";
import { tokens } from "../../registry/tokens.js";
import {
  AccountSummaryEventV2,
  MetricsArray,
  MetricsMap,
  SummaryArray,
  SummaryMap,
  MetricsValue,
  SummaryValue,
} from "./account-summary-event.js";
import type { Logger } from "pino";
import { AppDataSourceService } from "./data-source.js";
import { AccountSummaryEntity } from "../entity/account.summary.entity.js";
import { AccountSummaryDbStore } from "../store/summary-db.store.js";
import { AccountSummaryRedisStore } from "../store/summary-redis.store.js";
import type { KafkaProducer } from "../../commons/interfaces/kafka-producer.base.js";
import { GtiEvent } from "./gti-event.js";
import { MoreThan, Repository } from "typeorm";
// import { BackfillCacheService } from "./backfill-cache.service.js";
import { Result } from "../../tr8-script/domain/utils/types.js";
import { RedisProcessedEventStore } from "../store/processed-redis.store.js";
import { AmountMapper } from "../../commons/mappers/amount.mapper.js";
import {
  plus,
  minus,
  times,
  divide,
  absolute,
} from "../../tr8-script/domain/utils/math.js";
import { Amount } from "../../tr8-script/domain/value.js";
import { TransactionLogService } from "./transaction-log.service.js";
 
interface ProcessingContext {
  event: AccountSummaryEventV2;
  bookId: string;
  transactionTime: Date;
  transactionDateOnly: Date;
  scriptId: string;
  partition: number;
  offset: string;
  summaryMap: SummaryMap;
  metricsMap: MetricsMap;
  order_side: string;
  trade_type: string;
  ticker: string;
  price: Amount;
  share_quantity: Amount;
  asset_average_costs_basis?: Amount;
  prefix: string;
  fee: Amount;
  is_canceled: boolean;
  position_intent: string;
}
 
@singleton()
@autoInjectable()
class AccountSummaryEventHandlerClean {
  private cancelHandler?: {
    handle: (
      event: AccountSummaryEventV2,
      partition: number,
      offset: string,
    ) => Promise<Result<AccountSummaryEntity[], Error>>;
  }; // Will be lazily loaded
 
  constructor(
    @inject(tokens.Logger) private readonly logger: Logger,
    private appDataSourceService: AppDataSourceService,
    private readonly accountSummaryDbStore: AccountSummaryDbStore,
    private accountSummaryRedisStore: AccountSummaryRedisStore,
    private processedRedisStore: RedisProcessedEventStore,
    @inject(tokens.GtiEventProducer)
    private readonly gtiEventProducer: KafkaProducer<GtiEvent>,
    private readonly transactionLogService: TransactionLogService,
  ) {
    // private backfillCacheService: BackfillCacheService,
  }
 
  async sendToGtiEvent(events: AccountSummaryEntity[]): Promise<void> {
    this.logger.info({ events }, "sendToGtiEvent events");
    if (!events.length) return;
 
    const latestEventsMap = this.buildLatestEventsMap(events);
    this.logger.info(
      { latestEventsMap: Object.fromEntries(latestEventsMap) },
      "sendToGtiEvent latestEventsMap",
    );
 
    for (const event of latestEventsMap.values()) {
      this.logger.info({ event }, "sendToGtiEvent processing event");
 
      if (this.shouldSkipGtiEvent(event.book_id)) {
        this.logger.info(
          { book_id: event.book_id },
          "Skipping event with book_id",
        );
        continue;
      }
 
      const gtiEvent = this.buildGtiEvent(event);
      await this.gtiEventProducer.send(gtiEvent);
    }
  }
 
  private isCancelEvent(event: AccountSummaryEventV2): boolean {
    try {
      const metadata =
        typeof event.metadata === "string"
          ? JSON.parse(event.metadata)
          : event.metadata;
 
      // Accept both "true" and "1" as valid is_canceled values
      const isCanceled =
        metadata?.is_canceled === "true" || metadata?.is_canceled === "1";
      // Use alpaca_non_trade_event_id as the canonical identifier for cancel events
      // This is consistent across all events from Alpaca
      const alpacaEventId = metadata?.alpaca_non_trade_event_id;
      return isCanceled && !!alpacaEventId;
    } catch {
      return false;
    }
  }
 
  private async getCancelHandler() {
    if (!this.cancelHandler) {
      // Lazy load to avoid circular dependency
      const { AccountSummaryEventHandlerWithCancel } = await import(
        "./account-summary-event-handler-with-cancel.js"
      );
      const { container } = await import("tsyringe");
      this.cancelHandler = container.resolve(
        AccountSummaryEventHandlerWithCancel,
      );
    }
    return this.cancelHandler;
  }
 
  async handle(
    event: AccountSummaryEventV2,
    partition: number,
    offset: string,
  ): Promise<Result<AccountSummaryEntity[], Error>> {
    try {
      // Check if this is a cancel event - delegate to cancel handler
      Iif (this.isCancelEvent(event)) {
        this.logger.info(
          {},
          "[AccountSummaryHandler] Detected cancel event, delegating to cancel handler",
        );
        const cancelHandler = await this.getCancelHandler();
        return await cancelHandler.handle(event, partition, offset);
      }
 
      // Early validation and duplicate check
      const validationResult = await this.validateAndCheckDuplicate(
        event,
        partition,
        offset,
      );
      Iif (!validationResult.ok) {
        return validationResult;
      }
 
      if (validationResult.value.isDuplicate) {
        return { ok: true, value: [] };
      }
 
      const bookIds = this.extractBookIds(event);
 
      if (
        bookIds.length === 0 &&
        (!event.metrics || event.metrics.length === 0)
      ) {
        return {
          ok: false,
          error: new Error("No bookIds and no metrics to process"),
        };
      }
 
      const processedSummaries: AccountSummaryEntity[] = [];
      const bookIdErrors: Error[] = [];
 
      for (const bookId of bookIds) {
        const context = this.createProcessingContext(
          event,
          bookId,
          partition,
          offset,
        );
        const bookResult = await this.processBookId(context);
 
        if (bookResult.ok) {
          processedSummaries.push(...bookResult.value);
        } else E{
          this.logger.error(
            { err: bookResult.error, bookId },
            "Failed to process bookId",
          );
          bookIdErrors.push(bookResult.error);
        }
      }
 
      // If any bookId processing failed, return error to trigger DLQ
      Iif (bookIdErrors.length > 0) {
        const errorMessages = bookIdErrors.map((e) => e.message).join("; ");
        return {
          ok: false,
          error: new Error(
            `Failed to process ${bookIdErrors.length}/${bookIds.length} bookId(s): ${errorMessages}`,
          ),
        };
      }
 
      // Save transaction to log BEFORE saving summary to prevent double-processing on retry
      // If txlog fails, summary won't be saved yet, so retry will be safe
      const txLogResult = await this.saveTransactionToLog(event);
      Iif (!txLogResult.ok) {
        return { ok: false, error: txLogResult.error };
      }
 
      const mergedResults = await this.mergeAndSaveResults(processedSummaries);
 
      // Save processed event, send to GTI, and update backfill
      const finalizeResult = await this.finalizeProcessing(
        event,
        partition,
        offset,
        mergedResults,
      );
      Iif (!finalizeResult.ok) {
        return { ok: false, error: finalizeResult.error };
      }
 
      return { ok: true, value: mergedResults };
    } catch (err) {
      this.logger.error(
        { err },
        "[AccountSummaryHandler] Failed to handle event",
      );
      return { ok: false, error: err as Error };
    }
  }
 
  // ===== PRIVATE HELPER METHODS =====
 
  private async saveTransactionToLog(
    event: AccountSummaryEventV2,
  ): Promise<Result<void, Error>> {
    try {
      // Check if txlog already exists for this event (idempotency check for retries)
      const existingTxLogs = await this.transactionLogService.findAllByEventId(
        event.id,
      );
      Iif (existingTxLogs.length > 0) {
        this.logger.info(
          { eventId: event.id, count: existingTxLogs.length },
          "[AccountSummaryHandler] Transaction log already exists, skipping save",
        );
        return { ok: true, value: undefined };
      }
 
      const transactionDetails =
        this.transactionLogService.extractTransactionDetails(event);
 
      for (const details of transactionDetails) {
        const result = await this.transactionLogService.saveTransaction(
          details,
        );
        if (!result.ok) {
          this.logger.error(
            { err: result.error, eventId: event.id },
            "[AccountSummaryHandler] Failed to save transaction to log",
          );
          return { ok: false, error: result.error };
        }
      }
      return { ok: true, value: undefined };
    } catch (err) {
      this.logger.error(
        { err, eventId: event.id },
        "[AccountSummaryHandler] Error saving transaction to log",
      );
      return { ok: false, error: err as Error };
    }
  }
 
  private buildLatestEventsMap(
    events: AccountSummaryEntity[],
  ): Map<string, AccountSummaryEntity> {
    return events.reduce((map, event) => {
      Iif (!event.transaction_time) return map;
      const existing = map.get(event.book_id);
      Eif (!existing || event.transaction_time > existing.transaction_time!) {
        map.set(event.book_id, event);
      }
      return map;
    }, new Map<string, AccountSummaryEntity>());
  }
 
  private shouldSkipGtiEvent(bookId: string): boolean {
    return bookId.includes("gotrade");
  }
 
  private buildGtiEvent(event: AccountSummaryEntity): GtiEvent {
    return {
      book_id: event.book_id,
      summary: event.summary
        ? event.summary.map(({ account_id, value }) => ({
            account_id,
            value,
          }))
        : [],
      transaction_time: new Date(event.transaction_time!).toISOString(),
      metrics: event.metrics.map(
        ({ account_id, book_type, book_id, amount }) => ({
          account_id,
          book_type,
          book_id,
          value: amount,
        }),
      ),
    };
  }
 
  private async validateAndCheckDuplicate(
    event: AccountSummaryEventV2,
    partition: number,
    offset: string,
  ): Promise<Result<{ isDuplicate: boolean }, Error>> {
    const eventId = `${partition}#${offset}#${event.id}`;
 
    const processedEvent = await this.processedRedisStore.get(eventId);
    Iif (!processedEvent.ok) {
      this.logger.error(
        { err: processedEvent.error },
        "[AccountSummaryHandler] Failed to get from Redis",
      );
      return { ok: false, error: processedEvent.error };
    }
 
    if (processedEvent.value != null) {
      this.logger.info(
        { processedEvent: processedEvent.value },
        "processedEvent found",
      );
      const incomingOffset = BigInt(offset);
      const existingOffset = BigInt(processedEvent.value.offset);
 
      if (incomingOffset <= existingOffset) {
        this.logger.info(
          {
            offset,
            existingOffset: processedEvent.value.offset,
            scriptId: event.id,
          },
          "[AccountSummaryHandler] Skipping event: offset <= existing offset",
        );
        return { ok: true, value: { isDuplicate: true } };
      }
    }
 
    return { ok: true, value: { isDuplicate: false } };
  }
 
  private extractBookIds(event: AccountSummaryEventV2): string[] {
    const txlogBookIds = (event.txlogs ?? [])
      .map((tx) => tx.book?.book)
      .filter((id): id is string => typeof id === "string");
 
    const metricBookIds = (event.metrics ?? [])
      .map((metric) => metric.book?.book)
      .filter((id): id is string => typeof id === "string");
 
    return Array.from(new Set([...txlogBookIds, ...metricBookIds]));
  }
 
  private createProcessingContext(
    event: AccountSummaryEventV2,
    bookId: string,
    partition: number,
    offset: string,
  ): ProcessingContext {
    const metadata =
      typeof event.metadata === "string"
        ? JSON.parse(event.metadata)
        : event.metadata;
 
    this.logger.info({ metadata }, "[METADATA] Raw metadata");
 
    const transactionTime = new Date(metadata.transaction_time);
    const transactionDateOnly = new Date(transactionTime);
    transactionDateOnly.setHours(0, 0, 0, 0);
 
    // Handle both trading and non-trading metadata formats with safe defaults
    const order_side = metadata.order_side || "unknown";
    const trade_type = metadata.trade_type || "unknown";
    const ticker = metadata.ticker || metadata.symbol || "unknown";
    const is_canceled: boolean = metadata?.is_canceled === "true";
    const position_intent = metadata.position_intent || "unknown";
 
    // Helper function to convert decimal string to Amount with proper scale
    const parseDecimalToAmount = (value: string): Amount => {
      Iif (!value || value === "0") {
        return AmountMapper.fromDTO({ amount: "0", scale: "0" });
      }
 
      // Handle decimal values by converting to integer with appropriate scale
      const decimalParts = value.split(".");
      if (decimalParts.length === 1) {
        // No decimal part, use scale 0
        return AmountMapper.fromDTO({ amount: value, scale: "0" });
      } else E{
        // Has decimal part, calculate scale and convert to integer
        const integerPart = decimalParts[0] || "0";
        const decimalPart = decimalParts[1] || "";
        const scale = decimalPart.length;
        const amountAsInteger = integerPart + decimalPart;
        return AmountMapper.fromDTO({
          amount: amountAsInteger,
          scale: scale.toString(),
        });
      }
    };
 
    const price = metadata.price
      ? parseDecimalToAmount(metadata.price.toString())
      : AmountMapper.fromDTO({ amount: "0", scale: "0" });
    const share_quantity = metadata.share_quantity
      ? parseDecimalToAmount(metadata.share_quantity.toString())
      : AmountMapper.fromDTO({ amount: "0", scale: "0" });
    const prefix = metadata.prefix || "gti-production-ledger";
    const fee = metadata.fee
      ? parseDecimalToAmount(metadata.fee.toString())
      : AmountMapper.fromDTO({ amount: "0", scale: "0" });
 
    this.logger.info(
      `[METADATA] Extracted values: order_side=${order_side}, trade_type=${trade_type}, ticker=${
        metadata.ticker || "0"
      } (parsed: ${AmountMapper.toDTO(price).amount}), share_quantity=${
        metadata.share_quantity || "0"
      } (parsed: ${AmountMapper.toDTO(share_quantity).amount})`,
    );
 
    return {
      event,
      bookId,
      transactionTime,
      transactionDateOnly,
      scriptId: event.id,
      partition,
      offset,
      summaryMap: new Map(),
      metricsMap: new Map(),
      order_side,
      trade_type,
      ticker,
      price,
      share_quantity,
      prefix,
      fee,
      is_canceled,
      position_intent,
    };
  }
 
  private async processBookId(
    context: ProcessingContext,
  ): Promise<Result<AccountSummaryEntity[], Error>> {
    const repository =
      this.appDataSourceService.AppDataSource.getRepository(
        AccountSummaryEntity,
      );
 
    // Get latest account summary
    const latestSummary = await this.getLatestAccountSummary(context.bookId);
 
    this.logger.info({ latestSummary }, "latestAccountSummary BEFORE txlog");
 
    const scenario = this.determineProcessingScenario(context, latestSummary);
 
    switch (scenario) {
      case "backfill":
        return await this.processBackfillScenario(context, repository);
      case "same_day":
        return await this.processSameDayScenario(context, latestSummary);
      case "future_day":
        return await this.processFutureDayScenario(
          context,
          latestSummary,
          repository,
        );
      case "new_summary":
        return await this.processNewSummaryScenario(context, repository);
      default:
        return { ok: false, error: new Error(`Unknown scenario: ${scenario}`) };
    }
  }
 
  private async getLatestAccountSummary(
    bookId: string,
  ): Promise<AccountSummaryEntity | null> {
    // Try Redis first
    let latestSummary =
      await this.accountSummaryRedisStore.getLatestAccountSummaryRedis(bookId);
 
    // Fallback to DB if not in Redis
    Iif (!latestSummary) {
      const repository =
        this.appDataSourceService.AppDataSource.getRepository(
          AccountSummaryEntity,
        );
      latestSummary = await this.accountSummaryDbStore.getLatestAccountSummary(
        repository,
        bookId,
      );
    }
 
    return latestSummary;
  }
 
  private determineProcessingScenario(
    context: ProcessingContext,
    latestSummary: AccountSummaryEntity | null,
  ): "backfill" | "same_day" | "future_day" | "new_summary" {
    Iif (!latestSummary) {
      return "new_summary";
    }
 
    const latestSummaryDate = new Date(
      latestSummary.transaction_time ?? new Date(),
    );
    const latestSummaryDateOnly = new Date(latestSummaryDate);
    latestSummaryDateOnly.setHours(0, 0, 0, 0);
 
    const daysDifference = Math.floor(
      (context.transactionDateOnly.getTime() -
        latestSummaryDateOnly.getTime()) /
        (1000 * 60 * 60 * 24),
    );
 
    Iif (daysDifference < 0) {
      return "backfill";
    } else if (daysDifference === 0) {
      return "same_day";
    } else if (daysDifference > 0) {
      return "future_day";
    } else E{
      return "new_summary";
    }
  }
 
  private async processBackfillScenario(
    context: ProcessingContext,
    repository: Repository<AccountSummaryEntity>,
  ): Promise<Result<AccountSummaryEntity[], Error>> {
    const updatedSummaries: AccountSummaryEntity[] = [];
 
    // 1. Check if a summary for this exact transaction time already exists
    const summaryForTransactionTime = await this.getSummaryAtTxTime(
      context.bookId,
      context.transactionTime,
    );
 
    let baseSummary: AccountSummaryEntity | null = null;
 
    if (summaryForTransactionTime) {
      // Path A: A summary for today (the backfill day) already exists. Use it as the base.
      baseSummary = summaryForTransactionTime;
      this.populateMapsFromSummary(context, summaryForTransactionTime);
    } else {
      // Path B: No summary for today. Use the summary from the day before as the base.
      const lastSummaryBeforeTransaction =
        await this.getSummaryBeforeTransaction(
          context.bookId,
          context.transactionTime,
        );
      if (lastSummaryBeforeTransaction) {
        baseSummary = lastSummaryBeforeTransaction;
        this.populateMapsFromSummary(context, lastSummaryBeforeTransaction);
      }
    }
 
    // 2. Save snapshot before mutation
    const beforeSummary = baseSummary?.summary
      ? baseSummary.summary.map((e) => ({ ...e }))
      : [];
    const beforeMetrics = baseSummary?.metrics
      ? baseSummary.metrics.map((m) => ({ ...m }))
      : [];
 
    // 3. Apply the changes from the current event to the established base
    this.updateSummaryWithTxlogs(context);
    this.updateMetricsWithTxlogs(context);
 
    // 4. Create or update the summary for the backfill time
    let updatedBackfillSummary: AccountSummaryEntity;
    if (summaryForTransactionTime) {
      // We started with an existing summary, so we update it
      updatedBackfillSummary = this.updateExistingSummary(
        summaryForTransactionTime,
        context,
      );
    } else {
      // We started from a previous day (or nothing), so we create a new summary
      const summaryArray = this.summaryMapToArray(context.summaryMap);
      const metricsArray = this.metricsMapToArray(context.metricsMap);
      updatedBackfillSummary = this.createNewSummary(
        repository,
        context,
        summaryArray,
        metricsArray,
      );
    }
    updatedSummaries.push(updatedBackfillSummary);
 
    // 5. Calculate changes introduced by this event
    const summaryChangesMap = this.calculateChangesMap(
      updatedBackfillSummary.summary ?? undefined,
      beforeSummary,
    );
    const metricsChangesMap = this.calculateChangesMap(
      updatedBackfillSummary.metrics ?? undefined,
      beforeMetrics,
    );
 
    this.logger.info(
      `[processBackfillScenario] Summary changes keys: ${Array.from(
        summaryChangesMap.keys(),
      ).join(", ")}`,
    );
    this.logger.info(
      `[processBackfillScenario] Metrics changes keys: ${Array.from(
        metricsChangesMap.keys(),
      ).join(", ")}`,
    );
 
    // 6. Propagate changes to all future summaries
    const futureItems = await this.getFutureAccountSummaries(
      context.bookId,
      context.transactionTime,
    );
 
    const correctedFuture: AccountSummaryEntity[] = [];
 
    for (const item of futureItems) {
      // --- Summary ---
      const baseSummaryMap: SummaryMap = new Map();
      (item.summary ?? []).forEach(({ account_id, value, scale }) => {
        baseSummaryMap.set(account_id, { value, scale });
      });
      const newSummaryMap = this.applyChangesMap(
        baseSummaryMap,
        summaryChangesMap,
        context.bookId,
      ) as SummaryMap;
 
      // --- Metrics ---
      const baseMetricsMap: MetricsMap = new Map();
      (item.metrics ?? []).forEach(
        ({ account_id, book_type, book_id, amount, scale }) => {
          baseMetricsMap.set(account_id, { book_type, book_id, amount, scale });
        },
      );
      const newMetricsMap = this.applyChangesMap(
        baseMetricsMap,
        metricsChangesMap,
        context.bookId,
      ) as MetricsMap;
 
      const tmpCtx: ProcessingContext = {
        ...context,
        bookId: item.book_id,
        transactionTime: item.transaction_time!,
        scriptId: item.latest_journal_id!,
        partition: item.partition,
        offset: item.offset,
        summaryMap: newSummaryMap,
        metricsMap: newMetricsMap,
      };
 
      correctedFuture.push(this.updateExistingSummary(item, tmpCtx));
    }
 
    updatedSummaries.push(...correctedFuture);
 
    this.logger.info(
      `[processBackfillScenario] Updated ${updatedSummaries.length} summaries (1 backfill + ${correctedFuture.length} future)`,
    );
 
    return { ok: true, value: updatedSummaries };
  }
 
  private async processSameDayScenario(
    context: ProcessingContext,
    latestSummary: AccountSummaryEntity | null,
  ): Promise<Result<AccountSummaryEntity[], Error>> {
    Iif (!latestSummary) {
      return {
        ok: false,
        error: new Error("Latest summary is null for same-day scenario"),
      };
    }
 
    // Save snapshot before mutation
    const beforeSummary = latestSummary.summary
      ? latestSummary.summary.map((e) => ({ ...e }))
      : [];
    const beforeMetrics = latestSummary.metrics
      ? latestSummary.metrics.map((m) => ({ ...m }))
      : [];
 
    // Update summary today with txlog & metrics
    this.populateMapsFromSummary(context, latestSummary);
    this.updateSummaryWithTxlogs(context);
    this.updateMetricsWithTxlogs(context);
 
    const updatedToday = this.updateExistingSummary(latestSummary, context);
 
    // Calculate changes introduced by this event
    const summaryChangesMap = this.calculateChangesMap(
      updatedToday.summary ?? undefined,
      beforeSummary,
    );
    const metricsChangesMap = this.calculateChangesMap(
      updatedToday.metrics ?? undefined,
      beforeMetrics,
    );
 
    // Propagate changes to all future snapshots
    const futureItems = await this.getFutureAccountSummaries(
      context.bookId,
      context.transactionTime,
    );
 
    const correctedFuture: AccountSummaryEntity[] = [];
 
    for (const item of futureItems) {
      // --- Summary ---
      const baseSummaryMap: SummaryMap = new Map();
      (item.summary ?? []).forEach(({ account_id, value, scale }) => {
        baseSummaryMap.set(account_id, { value, scale });
      });
      const newSummaryMap = this.applyChangesMap(
        baseSummaryMap,
        summaryChangesMap,
        context.bookId,
      ) as SummaryMap;
 
      // --- Metrics ---
      const baseMetricsMap: MetricsMap = new Map();
      (item.metrics ?? []).forEach(
        ({ account_id, book_type, book_id, amount, scale }) => {
          baseMetricsMap.set(account_id, { book_type, book_id, amount, scale });
        },
      );
      const newMetricsMap = this.applyChangesMap(
        baseMetricsMap,
        metricsChangesMap,
        context.bookId,
      ) as MetricsMap;
 
      const tmpCtx: ProcessingContext = {
        ...context,
        bookId: item.book_id,
        transactionTime: item.transaction_time!,
        scriptId: item.latest_journal_id!,
        partition: item.partition,
        offset: item.offset,
        summaryMap: newSummaryMap,
        metricsMap: newMetricsMap,
      };
 
      correctedFuture.push(this.updateExistingSummary(item, tmpCtx));
    }
 
    // Return results
    return { ok: true, value: [updatedToday, ...correctedFuture] };
  }
 
  /**
   * Processes an event whose transaction date is AFTER the latest snapshot date.
   *
   * FIX: Previously this method used computeChanges() + propagateChangesToFutureDays()
   * which computed raw BigInt diffs without preserving scale information. When the
   * existing snapshot had a different scale (e.g. scale 2) than the txlog change
   * (e.g. scale 12), the raw diff was meaningless and corrupted future snapshots.
   *
   * Example of the old bug:
   *   - Before: C-FC = 2957 (scale 2, i.e. $29.57)
   *   - After updateSummaryWithTxlogs: C-FC = 18000000000000 (scale 12, i.e. $18.00)
   *   - Old computeChanges: diff = 18000000000000 - 2957 = 17999999997043 (meaningless)
   *   - Old propagation: future C-FC = 2957 + 17999999997043 = 18000000000000, scale stays "2"
   *     → $180,000,000,000 instead of $18.00
   *
   * Now uses calculateChangesMap() (returns Map<string, Amount> with scale) +
   * applyChangesMap() (uses plus() via Dinero.js for scale-aware arithmetic),
   * consistent with processSameDayScenario and processBackfillScenario.
   */
  private async processFutureDayScenario(
    context: ProcessingContext,
    latestSummary: AccountSummaryEntity | null,
    repository: Repository<AccountSummaryEntity>,
  ): Promise<Result<AccountSummaryEntity[], Error>> {
    Iif (!latestSummary) {
      return {
        ok: false,
        error: new Error("Latest summary is null for future day scenario"),
      };
    }
 
    // Load current state into summaryMap / metricsMap
    this.populateMapsFromSummary(context, latestSummary);
 
    // Save snapshot before mutation (as SummaryArray/MetricsArray to preserve scale)
    const beforeSummary = latestSummary.summary
      ? latestSummary.summary.map((e) => ({ ...e }))
      : [];
    const beforeMetrics = latestSummary.metrics
      ? latestSummary.metrics.map((m) => ({ ...m }))
      : [];
 
    // Update maps with txlogs & metrics event
    this.updateSummaryWithTxlogs(context);
    this.updateMetricsWithTxlogs(context);
 
    // Save today's snapshot
    const summaryArray = this.summaryMapToArray(context.summaryMap);
    const metricsArray = this.metricsMapToArray(context.metricsMap);
 
    const todaySummary = this.createNewSummary(
      repository,
      context,
      summaryArray,
      metricsArray,
    );
 
    // Calculate scale-aware changes (Map<string, Amount>) using the same
    // approach as processSameDayScenario and processBackfillScenario.
    // This preserves scale info so propagation to future snapshots is correct.
    const summaryChangesMap = this.calculateChangesMap(
      todaySummary.summary ?? undefined,
      beforeSummary,
    );
    const metricsChangesMap = this.calculateChangesMap(
      todaySummary.metrics ?? undefined,
      beforeMetrics,
    );
 
    // Propagate scale-aware changes to all future snapshots using applyChangesMap + plus()
    const futureItems = await this.getFutureAccountSummaries(
      context.bookId,
      context.transactionTime,
    );
 
    const correctedFuture: AccountSummaryEntity[] = [];
 
    for (const item of futureItems) {
      // --- Summary ---
      const baseSummaryMap: SummaryMap = new Map();
      (item.summary ?? []).forEach(({ account_id, value, scale }) => {
        baseSummaryMap.set(account_id, { value, scale });
      });
      const newSummaryMap = this.applyChangesMap(
        baseSummaryMap,
        summaryChangesMap,
        context.bookId,
      ) as SummaryMap;
 
      // --- Metrics ---
      const baseMetricsMap: MetricsMap = new Map();
      (item.metrics ?? []).forEach(
        ({ account_id, book_type, book_id, amount, scale }) => {
          baseMetricsMap.set(account_id, { book_type, book_id, amount, scale });
        },
      );
      const newMetricsMap = this.applyChangesMap(
        baseMetricsMap,
        metricsChangesMap,
        context.bookId,
      ) as MetricsMap;
 
      const tmpCtx: ProcessingContext = {
        ...context,
        bookId: item.book_id,
        transactionTime: item.transaction_time!,
        scriptId: item.latest_journal_id!,
        partition: item.partition,
        offset: item.offset,
        summaryMap: newSummaryMap,
        metricsMap: newMetricsMap,
      };
 
      correctedFuture.push(this.updateExistingSummary(item, tmpCtx));
    }
 
    // Save updated future snapshots to Redis
    if (correctedFuture.length > 0) {
      await this.accountSummaryRedisStore.set(context.bookId, correctedFuture);
    }
 
    this.logger.info(
      "[processFutureDayScenario] Final summary before return:",
      todaySummary.summary,
    );
 
    return { ok: true, value: [todaySummary, ...correctedFuture] };
  }
 
  private async processNewSummaryScenario(
    context: ProcessingContext,
    repository: Repository<AccountSummaryEntity>,
  ): Promise<Result<AccountSummaryEntity[], Error>> {
    this.buildSummaryFromTxlogs(context);
    this.buildMetricsFromTxlogs(context);
 
    const summaryArray = this.summaryMapToArray(context.summaryMap);
    const metricsArray = this.metricsMapToArray(context.metricsMap);
 
    const summary = this.createNewSummary(
      repository,
      context,
      summaryArray,
      metricsArray,
    );
 
    this.logger.info(
      "[processNewSummaryScenario] Final summary before return:",
      summary.summary,
    );
 
    return { ok: true, value: [summary] };
  }
 
  // ===== BUSINESS LOGIC METHODS (moved from stores) =====
 
  private buildSummaryFromTxlogs(context: ProcessingContext): void {
    for (const tx of context.event.txlogs.filter(
      (tx) => tx.book.book === context.bookId,
    )) {
      const key = tx.account;
      const amountDto = AmountMapper.fromDTO({
        amount: tx.change.amount.toString(),
        scale: tx.change.scale.toString(),
      });
 
      context.summaryMap.set(key, {
        value: AmountMapper.toDTO(amountDto).amount,
        scale: AmountMapper.toDTO(amountDto).scale,
      });
    }
  }
 
  private updateSummaryWithTxlogs(context: ProcessingContext): void {
    for (const tx of context.event.txlogs.filter(
      (tx) => tx.book.book === context.bookId,
    )) {
      const key = tx.account;
      const existingSummary = context.summaryMap.get(key) || {
        value: "0",
        scale: "0",
      };
 
      const existingAmount = AmountMapper.fromDTO({
        amount: existingSummary.value.toString(),
        scale: existingSummary.scale.toString(),
      });
 
      const changeAmount = AmountMapper.fromDTO({
        amount: tx.change.amount.toString(),
        scale: tx.change.scale.toString(),
      });
 
      const newAmount = plus(existingAmount, changeAmount) as Amount;
 
      context.summaryMap.set(key, {
        value: AmountMapper.toDTO(newAmount).amount,
        scale: AmountMapper.toDTO(newAmount).scale,
      });
    }
  }
 
  private buildMetricsFromTxlogs(context: ProcessingContext): void {
    for (const metric of context.event.metrics.filter(
      (m) => m.book.book === context.bookId,
    )) {
      const key = metric.account;
      const amountDto = AmountMapper.fromDTO({
        amount: metric.change.amount.toString(),
        scale: metric.change.scale.toString(),
      });
 
      context.metricsMap.set(key, {
        book_type: metric.book.type,
        book_id: metric.book.book,
        amount: AmountMapper.toDTO(amountDto).amount,
        scale: AmountMapper.toDTO(amountDto).scale,
      });
    }
  }
 
  private updateMetricsWithTxlogs(context: ProcessingContext): void {
    for (const metric of context.event.metrics.filter(
      (m) => m.book.book === context.bookId,
    )) {
      const key = metric.account;
      const existingMetric = context.metricsMap.get(key) || {
        book_type: metric.book.type,
        book_id: metric.book.book,
        amount: "0",
        scale: "0",
      };
 
      const existingAmount = AmountMapper.fromDTO({
        amount: existingMetric.amount.toString(),
        scale: existingMetric.scale.toString(),
      });
 
      const changeAmount = AmountMapper.fromDTO({
        amount: metric.change.amount.toString(),
        scale: metric.change.scale.toString(),
      });
 
      // Check if this metric has corresponding summary accounts
      const totalQty = this.getTotalQuantity(key, changeAmount, context);
 
      let newAmount: Amount;
 
      // Check if this is OPASN or OPEXP event
      const eventMetadata =
        typeof context.event.metadata === "string"
          ? JSON.parse(context.event.metadata)
          : context.event.metadata;
      const isOpasn = eventMetadata?.event_type === "OPASN";
      const isOpexp = eventMetadata?.event_type === "OPEXP";
 
      // Special handling for buy_to_close, OPASN, and OPEXP with positive ADD on cost basis
      // Example: Short @ 500, buy to close 1 contract, cost basis -1000 should become -500
      if (
        key.includes("OP-OWN-") &&
        key.includes("COST-BASIS") &&
        (context.position_intent === "buy_to_close" || isOpasn || isOpexp) &&
        changeAmount.amount > 0n &&
        existingAmount.amount < 0n // Cost basis is negative (short position)
      ) {
        // Use the same formula as calculateCostBasisFormula
        // Formula: CurrentValue - (SubQty * (CurrentValue/TotalQty))
        // But we need to calculate using absolute values and then add
 
        // For buy_to_close short position:
        // existingAmount is negative (e.g., -1000 for 2 contracts shorted)
        // changeAmount is positive qty being closed (e.g., 1)
        // We use formula: valuePerUnit = existingAmount / totalQty
        // reductionAmount = changeAmount * valuePerUnit
        // newAmount = existingAmount + reductionAmount
 
        // Calculate using the formula similar to calculateCostBasisFormula
        // valuePerUnit = currentValue / totalQty
        // const absChangeAmount = changeAmount; // positive qty
 
        // Use formula: reduction = changeQty * (existingAmount / (existingAmount/changeQty + changeQty))
        // Simplified: For short positions, calculate proportional cost basis removal
 
        // Actually, use the same pattern as calculateCostBasisFormula:
        // newValue = currentValue - (subQty * (currentValue/totalQty))
        // For buy_to_close: newValue = existingAmount + (closeQty * (existingAmount/totalQtyBefore))
 
        // Since we're dealing with metrics ADD command with positive value,
        // we need to calculate: howMuch cost basis to ADD (reduce the negative)
        // Formula: abs(existingAmount / (totalQty/closeQty)) * closeQty
        //        = abs(existingAmount) / totalQty * closeQty
 
        // Get totalQty from summary - this is AFTER txlog update, so we need to add back the change
        const totalQtyAfter = this.getTotalQuantity(key, changeAmount, context);
 
        // Calculate totalQtyBefore for both cases (partial and full close)
        let totalQtyBefore: Amount;
        if (totalQtyAfter && totalQtyAfter.amount !== 0n) {
          // Partial close: Total qty BEFORE = totalQtyAfter - changeAmount
          // For short: -1 (after) - 1 (close) = -2 (before)
          totalQtyBefore = minus(totalQtyAfter, changeAmount) as Amount;
        } else E{
          // Full close: totalQtyAfter = 0, so totalQtyBefore = 0 - changeAmount = -changeAmount
          // For short closing 1: 0 - 1 = -1 (before)
          totalQtyBefore = {
            amount: -changeAmount.amount,
            scale: changeAmount.scale,
          } as Amount;
        }
 
        const logPrefix = isOpasn
          ? "[OPASN]"
          : isOpexp
          ? "[OPEXP]"
          : "[BUY-TO-CLOSE]";
 
        this.logger.info(
          `${logPrefix} Qty calculation: totalQtyAfter=${
            totalQtyAfter ? AmountMapper.toDTO(totalQtyAfter).amount : "0"
          }, changeQty=${
            AmountMapper.toDTO(changeAmount).amount
          }, totalQtyBefore=${AmountMapper.toDTO(totalQtyBefore).amount}`,
        );
 
        if (totalQtyBefore.amount !== 0n) {
          // Calculate average cost basis per contract: existingAmount / totalQtyBefore
          const valuePerUnit = divide(existingAmount, totalQtyBefore) as Amount;
 
          // Calculate reduction amount: changeQty * valuePerUnit
          const reductionAmount = times(changeAmount, valuePerUnit) as Amount;
 
          // Add to existing (reducing the negative value)
          newAmount = plus(existingAmount, reductionAmount) as Amount;
 
          this.logger.info(
            `${logPrefix} Applied calculateCostBasisFormula logic for ${key}: ` +
              `existingAmount=${AmountMapper.toDTO(existingAmount).amount}, ` +
              `totalQtyBefore=${AmountMapper.toDTO(totalQtyBefore).amount}, ` +
              `changeQty=${AmountMapper.toDTO(changeAmount).amount}, ` +
              `valuePerUnit=${AmountMapper.toDTO(valuePerUnit).amount}, ` +
              `reductionAmount=${
                AmountMapper.toDTO(reductionAmount).amount
              }, ` +
              `newAmount=${AmountMapper.toDTO(newAmount).amount}`,
          );
        } else E{
          // Should never happen, but fallback just in case
          newAmount = plus(existingAmount, changeAmount) as Amount;
          this.logger.warn(
            `${logPrefix} TotalQtyBefore is 0 for ${key}, using normal calculation`,
          );
        }
      I} else if (
        // Special handling for cost basis metrics with sell orders that have valid trading metadata
        key.includes("COST-BASIS") &&
        context.order_side === "sell" &&
        context.position_intent !== "sell_to_open" &&
        context.ticker &&
        context.price &&
        this.isNegativeChange(changeAmount)
      ) {
        // For sell orders, calculate the proper cost basis reduction based on proportional shares sold
        // Get the correct total quantity for calculating average cost basis
        const correctTotalQty = this.getTotalQuantity(
          key,
          changeAmount,
          context,
        );
 
        let costBasisReduction: Amount;
        if (correctTotalQty && correctTotalQty.amount > 0n) {
          // Calculate average cost basis per share
          const asset_average_costs_basis = divide(
            existingAmount,
            correctTotalQty,
          ) as Amount;
 
          // Calculate cost basis reduction for the quantity being sold
          costBasisReduction = times(
            asset_average_costs_basis,
            context.share_quantity,
          ) as Amount;
 
          // Make it negative for reduction
          costBasisReduction = {
            amount: -costBasisReduction.amount,
            scale: costBasisReduction.scale,
          };
        } else {
          // Fallback: use direct txlog change
          costBasisReduction = changeAmount;
        }
 
        newAmount = plus(existingAmount, costBasisReduction) as Amount;
 
        this.logger.info(
          `Cost basis calculated reduction for sell order ${key}: ${
            AmountMapper.toDTO(existingAmount).amount
          } + ${AmountMapper.toDTO(costBasisReduction).amount} = ${
            AmountMapper.toDTO(newAmount).amount
          } (sold ${AmountMapper.toDTO(context.share_quantity).amount} shares)`,
        );
      } else if (
        this.isNegativeChange(changeAmount) &&
        context.position_intent !== "sell_to_open" &&
        totalQty &&
        totalQty.amount !== 0n
      ) {
        // Apply negative metric formula ONLY if we have valid quantity accounts
        // Skip for sell_to_open (opening short position) - should use direct addition
        newAmount = this.calculateCostBasisFormula(
          context,
          key,
          existingAmount,
          changeAmount,
          totalQty,
        );
        this.logger.info(
          `Negative metric calculation applied for ${key}: ${
            AmountMapper.toDTO(newAmount).amount
          }`,
        );
      } else {
        // Fallback to normal calculation for:
        // 1. Positive changes
        // 2. Negative changes without corresponding summary accounts (like C-CSW)
        // 3. Cases where totalQty is 0 or null
        newAmount = plus(existingAmount, changeAmount) as Amount;
 
        Eif (
          this.isNegativeChange(changeAmount) &&
          (!totalQty || totalQty.amount === 0n)
        ) {
          this.logger.info(
            `Using normal calculation for ${key} (no quantity accounts found): ${
              AmountMapper.toDTO(existingAmount).amount
            } + ${AmountMapper.toDTO(changeAmount).amount} = ${
              AmountMapper.toDTO(newAmount).amount
            }`,
          );
        }
      }
 
      context.metricsMap.set(key, {
        book_type: existingMetric.book_type,
        book_id: existingMetric.book_id,
        amount: AmountMapper.toDTO(newAmount).amount,
        scale: AmountMapper.toDTO(newAmount).scale,
      });
 
      // Process sell-side realized P&L logic for valid trading metadata
      // Skip P&L calculation for sell_to_open (opening short position)
      Iif (
        context.order_side === "sell" &&
        context.position_intent !== "sell_to_open" &&
        key.includes("COST-BASIS")
      ) {
        this.logger.info(
          `[SELL-SIDE] Processing sell order for metric ${key}: ticker=${
            context.ticker
          }, price=${AmountMapper.toDTO(context.price).amount}, quantity=${
            AmountMapper.toDTO(context.share_quantity).amount
          }`,
        );
 
        // Calculate realized P&L using the correct formula:
        // realized_pl_amount = (price * share_quantity) - (asset_average_costs_basis * share_quantity)
 
        // Get the correct total quantity for calculating average cost basis
        const correctTotalQty = this.getTotalQuantity(
          key,
          changeAmount,
          context,
        );
 
        let asset_average_costs_basis: Amount;
        if (correctTotalQty && correctTotalQty.amount > 0n) {
          // Calculate average cost basis per share
          asset_average_costs_basis = divide(
            existingAmount,
            correctTotalQty,
          ) as Amount;
        } else {
          // Fallback: use existing calculation
          asset_average_costs_basis = this.getAverageCostsBasis(
            totalQty,
            existingAmount,
          );
        }
 
        // Calculate cost basis for the quantity being sold
        const costBasisForSale = times(
          asset_average_costs_basis,
          context.share_quantity,
        ) as Amount;
 
        this.logger.info(
          `[SELL-ORDER] Total quantity: ${
            AmountMapper.toDTO(correctTotalQty || totalQty).amount
          }, ` +
            `Total cost basis: ${AmountMapper.toDTO(existingAmount).amount}, ` +
            `Average cost basis per share: ${
              AmountMapper.toDTO(asset_average_costs_basis).amount
            }, ` +
            `Cost basis for sale: ${
              AmountMapper.toDTO(costBasisForSale).amount
            }`,
        );
 
        const realized_pl_amount = this.calculateRealizedPnL(
          context,
          costBasisForSale,
        );
 
        this.logger.info(
          `[SELL-SIDE] Calculated realized P&L for ${key}: ${
            AmountMapper.toDTO(realized_pl_amount).amount
          }`,
        );
 
        this.updateRealizedMetrics(context, realized_pl_amount);
      }
 
      // Process buy-side realized P&L logic for buy_to_close (closing short position)
      // Also handle option expiry (event_type: OPEXP) and option assignment (event_type: OPASN)
      // Note: eventMetadata is already defined above for OPASN/OPEXP detection
      const isBuyToClose =
        context.order_side === "buy" &&
        context.position_intent === "buy_to_close";
 
      if (
        (isBuyToClose || isOpexp || isOpasn) &&
        key.includes("COST-BASIS") &&
        key.includes("OP-OWN-") // Only for options positions
      ) {
        const logPrefix = isOpexp
          ? "[OPEXP]"
          : isOpasn
          ? "[OPASN]"
          : "[BUY-TO-CLOSE]";
 
        this.logger.info(
          `${logPrefix} Processing ${
            isOpexp
              ? "option expiry"
              : isOpasn
              ? "option assignment"
              : "buy to close"
          } for metric ${key}: existing=${
            AmountMapper.toDTO(existingAmount).amount
          }, change=${AmountMapper.toDTO(changeAmount).amount}, new=${
            AmountMapper.toDTO(newAmount).amount
          }`,
        );
 
        // For OPEXP (expire worthless), check if short or long position
        Iif (isOpexp && newAmount.amount === 0n) {
          // Extract ticker from cost basis account
          // Format: C-TOTAL-COST-BASIS-OP-OWN-{TICKER}
          const tickerMatch = key.match(/OP-OWN-(.+)-COST-BASIS$/);
          const ticker = tickerMatch ? tickerMatch[1] : "";
 
          // Check if this is a short position by looking for reserve release in txlogs
          const hasReserveRelease = context.event.txlogs.some(
            (txlog) =>
              txlog.account.includes(`S-RES-OP-${ticker}`) ||
              txlog.account.includes(`C-RES-OP-${ticker}`),
          );
 
          // Short position: cost basis is negative (premium received)
          // Long position: cost basis is positive (premium paid)
          // P&L = -existingAmount (inverse the cost basis)
          const realized_pl_amount = {
            amount: -existingAmount.amount,
            scale: existingAmount.scale,
          } as Amount;
 
          const positionType = hasReserveRelease ? "SHORT" : "LONG";
          this.logger.info(
            `${logPrefix} ${positionType} position fully closed. Cost basis=${
              AmountMapper.toDTO(existingAmount).amount
            }, Realized P&L=${AmountMapper.toDTO(realized_pl_amount).amount}`,
          );
 
          this.updateRealizedMetrics(context, realized_pl_amount);
          continue; // Skip normal buy-to-close calculation
        }
 
        // For buy to close, P&L = existing cost basis + (quantity × close_price)
        // Example: Short @ $300 (cost basis = -300), Close @ $200 (add +200)
        // Final cost basis = -300 + 200 = -100 (profit $100)
 
        // The newAmount already contains the updated cost basis after adding the close transaction
        // So we can calculate P&L from the change in cost basis
 
        // Get the correct total quantity BEFORE close for calculating average cost basis
        const totalQtyAfter = this.getTotalQuantity(key, changeAmount, context);
 
        let asset_average_costs_basis: Amount;
        if (totalQtyAfter && totalQtyAfter.amount !== 0n) {
          // Calculate totalQty BEFORE close (same logic as cost basis calculation)
          const totalQtyBefore = minus(totalQtyAfter, changeAmount) as Amount;
 
          // Calculate average cost basis per share/contract
          asset_average_costs_basis = divide(
            existingAmount,
            totalQtyBefore,
          ) as Amount;
        } else E{
          // Position fully closed, calculate from what we had before
          // totalQtyBefore = 0 - changeAmount = -changeAmount
          const totalQtyBefore = {
            amount: -changeAmount.amount,
            scale: changeAmount.scale,
          } as Amount;
          asset_average_costs_basis = divide(
            existingAmount,
            totalQtyBefore,
          ) as Amount;
        }
 
        // Calculate totalQtyBefore for logging
        const totalQtyBeforeForLog = totalQtyAfter
          ? (minus(totalQtyAfter, changeAmount) as Amount)
          : ({
              amount: -changeAmount.amount,
              scale: changeAmount.scale,
            } as Amount);
 
        this.logger.info(
          `[BUY-TO-CLOSE] Total quantity before: ${
            AmountMapper.toDTO(totalQtyBeforeForLog).amount
          }, ` +
            `Total cost basis before: ${
              AmountMapper.toDTO(existingAmount).amount
            }, ` +
            `Average cost basis: ${
              AmountMapper.toDTO(asset_average_costs_basis).amount
            }`,
        );
 
        // Calculate P&L for buy to close (short position)
        // Formula: (short_price × quantity) - (close_price × quantity)
        // The avg_cost_basis is already positive because we divide negative cost basis by negative quantity
        // Example: Short @ $5 per contract, 2 contracts = -1000 cost basis, -2 qty
        // avg_cost_basis = -1000 / -2 = 500 (positive, per contract value)
 
        const absoluteCostBasis = {
          amount: asset_average_costs_basis.amount, // Already positive from division
          scale: asset_average_costs_basis.scale,
        } as Amount;
 
        // Use changeAmount (filled quantity) not share_quantity (total order quantity)
        // For partial fills, we only calculate P&L for the filled portion
        const costBasisForClose = times(
          absoluteCostBasis,
          changeAmount, // Use filled qty, not total order qty
        ) as Amount;
 
        // For buy to close, the formula is REVERSED:
        // P&L = cost_basis - (close_price × quantity)
        this.logger.info(
          `[BUY-TO-CLOSE] BEFORE P&L calc: costBasisForClose=${
            AmountMapper.toDTO(costBasisForClose).amount
          }, changeAmount=${AmountMapper.toDTO(changeAmount).amount}`,
        );
 
        const realized_pl_amount = this.calculateRealizedPnLBuyToClose(
          context,
          costBasisForClose,
          changeAmount, // Pass filled qty, not total order qty
        );
 
        this.logger.info(
          `[BUY-TO-CLOSE] AFTER P&L calc, realized_pl_amount=${
            AmountMapper.toDTO(realized_pl_amount).amount
          }`,
        );
 
        this.updateRealizedMetrics(context, realized_pl_amount);
      }
    }
  }
 
  private populateMapsFromSummary(
    context: ProcessingContext,
    summary: AccountSummaryEntity,
  ): void {
    Eif (summary.summary) {
      for (const entry of summary.summary) {
        context.summaryMap.set(entry.account_id, {
          value: entry.value,
          scale: entry.scale,
        });
      }
    }
 
    Eif (summary.metrics) {
      for (const metric of summary.metrics) {
        context.metricsMap.set(metric.account_id, {
          book_type: metric.book_type,
          book_id: metric.book_id,
          amount: metric.amount,
          scale: metric.scale,
        });
      }
    }
  }
 
  private summaryMapToArray(summaryMap: SummaryMap): SummaryArray {
    return Array.from(summaryMap.entries()).map(
      ([account_id, { value, scale }]) => ({
        account_id,
        value,
        scale,
      }),
    );
  }
 
  private metricsMapToArray(metricsMap: MetricsMap): MetricsArray {
    return Array.from(metricsMap.entries()).map(
      ([account_id, { book_type, book_id, amount, scale }]) => ({
        account_id,
        book_type,
        book_id,
        amount,
        scale,
      }),
    );
  }
 
  private createNewSummary(
    repository: Repository<AccountSummaryEntity>,
    context: ProcessingContext,
    summaryArray: SummaryArray,
    metricsArray: MetricsArray,
  ): AccountSummaryEntity {
    return repository.create({
      book_id: context.bookId,
      transaction_time: context.transactionTime,
      summary: summaryArray,
      latest_journal_id: context.scriptId,
      partition: context.partition,
      offset: context.offset,
      metrics: metricsArray,
    });
  }
 
  private updateExistingSummary(
    summary: AccountSummaryEntity,
    context: ProcessingContext,
  ): AccountSummaryEntity {
    const summaryArray = this.summaryMapToArray(context.summaryMap);
    const metricsArray = this.metricsMapToArray(context.metricsMap);
 
    summary.summary = summaryArray;
    summary.metrics = metricsArray;
    summary.latest_journal_id = context.scriptId;
    summary.transaction_time = context.transactionTime;
    summary.partition = context.partition;
    summary.offset = context.offset;
 
    return summary;
  }
 
  private async getSummaryBeforeTransaction(
    bookId: string,
    transactionTime: Date,
  ): Promise<AccountSummaryEntity | null> {
    // Try Redis first
    let summary =
      await this.accountSummaryRedisStore.getAccountSummariesBeforeRedis(
        bookId,
        transactionTime,
      );
 
    // Fallback to DB
    if (!summary) {
      const repository =
        this.appDataSourceService.AppDataSource.getRepository(
          AccountSummaryEntity,
        );
      summary = await this.accountSummaryDbStore.getSummaryLessThan(
        repository,
        bookId,
        transactionTime,
      );
    }
 
    return summary;
  }
 
  private async getFutureAccountSummaries(
    bookId: string,
    transactionTime: Date,
  ): Promise<AccountSummaryEntity[]> {
    let futureAccountSummary: AccountSummaryEntity[] = [];
 
    const redisResults =
      await this.accountSummaryRedisStore.getAccountSummariesAfterRedis(
        bookId,
        transactionTime,
      );
 
    if (redisResults && redisResults.length > 0) {
      futureAccountSummary = redisResults;
    }
 
    // Fallback to DB if not in Redis
    if (futureAccountSummary.length === 0) {
      const repository =
        this.appDataSourceService.AppDataSource.getRepository(
          AccountSummaryEntity,
        );
      const results = await repository.find({
        where: {
          book_id: bookId,
          transaction_time: MoreThan(transactionTime),
        },
        order: { transaction_time: "ASC" },
      });
      futureAccountSummary = results.length > 0 ? results : [];
    }
 
    return futureAccountSummary;
  }
 
  // Helper to calculate the difference between two summary/metric arrays
  private calculateChangesMap(
    currentState?: SummaryArray | MetricsArray,
    oldBaseState?: SummaryArray | MetricsArray,
  ): Map<string, Amount> {
    const changesMap = new Map<string, Amount>();
    type Item = SummaryArray[number] | MetricsArray[number];
    const currentMap = new Map<string, Item>();
    const oldBaseMap = new Map<string, Item>();
 
    Eif (currentState) {
      for (const item of currentState) {
        currentMap.set(item.account_id, item);
      }
    }
    Eif (oldBaseState) {
      for (const item of oldBaseState) {
        oldBaseMap.set(item.account_id, item);
      }
    }
 
    const allKeys = new Set([...currentMap.keys(), ...oldBaseMap.keys()]);
 
    this.logger.info(
      `[calculateChangesMap] Current state keys: ${Array.from(
        currentMap.keys(),
      ).join(", ")}`,
    );
    this.logger.info(
      `[calculateChangesMap] Old base state keys: ${Array.from(
        oldBaseMap.keys(),
      ).join(", ")}`,
    );
    this.logger.info(
      `[calculateChangesMap] All keys to process: ${Array.from(allKeys).join(
        ", ",
      )}`,
    );
 
    for (const key of allKeys) {
      const currentItem = currentMap.get(key);
      const oldItem = oldBaseMap.get(key);
 
      const currentAmount = currentItem
        ? AmountMapper.fromDTO({
            amount:
              ("value" in currentItem
                ? currentItem.value
                : currentItem.amount) ?? "0",
            scale: currentItem.scale ?? "0",
          })
        : AmountMapper.fromDTO({ amount: "0", scale: "0" });
 
      const oldAmount = oldItem
        ? AmountMapper.fromDTO({
            amount:
              ("value" in oldItem ? oldItem.value : oldItem.amount) ?? "0",
            scale: oldItem.scale ?? "0",
          })
        : AmountMapper.fromDTO({ amount: "0", scale: "0" });
 
      const change = minus(currentAmount, oldAmount) as Amount;
 
      this.logger.info(
        `[calculateChangesMap] Key: ${key}, Current: ${
          AmountMapper.toDTO(currentAmount).amount
        }, Old: ${AmountMapper.toDTO(oldAmount).amount}, Change: ${
          AmountMapper.toDTO(change).amount
        }`,
      );
 
      if (change.amount !== 0n) {
        changesMap.set(key, change);
        this.logger.info(
          `[calculateChangesMap] Added change for ${key}: ${
            AmountMapper.toDTO(change).amount
          }`,
        );
      }
    }
 
    return changesMap;
  }
 
  // Helper to apply a changes map to a base map
  private applyChangesMap(
    baseMap: SummaryMap,
    changesMap: Map<string, Amount>,
    bookId: string,
  ): SummaryMap;
  private applyChangesMap(
    baseMap: MetricsMap,
    changesMap: Map<string, Amount>,
    bookId: string,
  ): MetricsMap;
  private applyChangesMap(
    baseMap: SummaryMap | MetricsMap,
    changesMap: Map<string, Amount>,
    bookId: string,
  ): SummaryMap | MetricsMap {
    // Type guard to determine which kind of map we're dealing with.
    // We check the structure of the first value in the map.
    const firstValue = baseMap.values().next().value;
 
    this.logger.info(
      `[applyChangesMap] Base map keys: ${Array.from(baseMap.keys()).join(
        ", ",
      )}`,
    );
    this.logger.info(
      `[applyChangesMap] Changes map keys: ${Array.from(changesMap.keys()).join(
        ", ",
      )}`,
    );
 
    // Handle MetricsMap
    Iif (firstValue && "book_type" in firstValue) {
      const resultMap = new Map(baseMap as MetricsMap);
      for (const [accountId, change] of changesMap.entries()) {
        const baseEntry = resultMap.get(accountId);
        const baseAmountValue = baseEntry?.amount ?? "0";
        const baseScaleValue = baseEntry?.scale ?? "0";
 
        const baseAmount = AmountMapper.fromDTO({
          amount: baseAmountValue,
          scale: baseScaleValue,
        });
 
        const newAmount = plus(baseAmount, change) as Amount;
        const newAmountDTO = AmountMapper.toDTO(newAmount);
 
        this.logger.info(
          `[applyChangesMap] Metrics ${accountId}: Base ${
            AmountMapper.toDTO(baseAmount).amount
          } + Change ${AmountMapper.toDTO(change).amount} = ${
            newAmountDTO.amount
          }`,
        );
 
        // We must preserve the other properties of the metric
        const newMetric: MetricsValue = {
          book_id: baseEntry?.book_id ?? bookId, // Use context bookId for new metrics
          book_type: baseEntry?.book_type ?? "normal", // Default if new
          ...newAmountDTO,
        };
        resultMap.set(accountId, newMetric);
      }
      return resultMap;
    }
 
    // Handle SummaryMap (or an empty map)
    const resultMap = new Map(baseMap as SummaryMap);
    for (const [accountId, change] of changesMap.entries()) {
      const baseEntry = resultMap.get(accountId);
      const baseAmountValue = baseEntry?.value ?? "0";
      const baseScaleValue = baseEntry?.scale ?? "0";
 
      const baseAmount = AmountMapper.fromDTO({
        amount: baseAmountValue,
        scale: baseScaleValue,
      });
 
      const newAmount = plus(baseAmount, change) as Amount;
      const newAmountDTO = AmountMapper.toDTO(newAmount);
 
      this.logger.info(
        `[applyChangesMap] Summary ${accountId}: Base ${
          AmountMapper.toDTO(baseAmount).amount
        } + Change ${AmountMapper.toDTO(change).amount} = ${
          newAmountDTO.amount
        }`,
      );
 
      const newSummary: SummaryValue = {
        value: newAmountDTO.amount,
        scale: newAmountDTO.scale,
      };
      resultMap.set(accountId, newSummary);
    }
    return resultMap;
  }
 
  private async mergeAndSaveResults(
    processedSummaries: AccountSummaryEntity[],
  ): Promise<AccountSummaryEntity[]> {
    const mergedResults: AccountSummaryEntity[] = [];
 
    for (const result of processedSummaries) {
      this.logger.info({ result }, "result processedSummaries");
 
      const bookId = result.book_id;
      this.logger.info({ bookId }, "processing bookId");
 
      const existingResult = await this.accountSummaryRedisStore.get(bookId);
      Iif (!existingResult.ok) {
        this.logger.error(
          { err: existingResult.error, bookId },
          "[AccountSummary] Failed to get Redis data",
        );
        continue;
      }
 
      const existingData = existingResult.value;
      let mergedResult: AccountSummaryEntity[];
 
      this.logger.info({ existingData }, "existingData BEFORE merge");
 
      Iif (existingData) {
        const existingEntry = existingData.find(
          (entry) =>
            entry.book_id === result.book_id &&
            entry.transaction_time &&
            result.transaction_time &&
            new Date(entry.transaction_time).toDateString() ===
              new Date(result.transaction_time).toDateString(),
        );
 
        this.logger.info({ existingEntry }, "existingEntry found");
 
        if (existingEntry) {
          this.logger.info({}, "existingEntry ada");
          Object.assign(existingEntry, result);
        } else {
          this.logger.info({}, "existingEntry tidak ada");
          const newEntry = new AccountSummaryEntity();
          Object.assign(newEntry, result);
          existingData.push(newEntry);
        }
 
        mergedResult = existingData;
        this.logger.info({ mergedResult }, "mergedResult existingData");
      } else {
        const newEntry = new AccountSummaryEntity();
        Object.assign(newEntry, result);
        mergedResult = [newEntry];
        this.logger.info({ mergedResult }, "mergedResult ga ada");
      }
 
      const saveResult = await this.accountSummaryRedisStore.set(
        bookId,
        mergedResult,
      );
      Iif (!saveResult.ok) {
        this.logger.error(
          { err: saveResult.error, bookId },
          "[AccountSummary] Failed to save Redis data",
        );
        continue;
      }
 
      mergedResults.push(...mergedResult);
      this.logger.info({ mergedResult }, "mergedResult result");
    }
 
    return mergedResults;
  }
 
  private async finalizeProcessing(
    event: AccountSummaryEventV2,
    partition: number,
    offset: string,
    mergedResults: AccountSummaryEntity[],
  ): Promise<Result<void, Error>> {
    const eventId = `${partition}#${offset}#${event.id}`;
 
    // Save to processed Redis
    const redisResult = await this.processedRedisStore.set(
      eventId,
      event.id,
      partition,
      offset,
    );
    Iif (!redisResult.ok) {
      this.logger.error(
        { err: redisResult.error, eventId },
        "[AccountSummaryHandler] Failed to save processed event to Redis",
      );
      return { ok: false, error: redisResult.error };
    }
 
    // Send to GTI - await and check for errors
    try {
      await this.sendToGtiEvent(mergedResults);
    } catch (err) {
      this.logger.error(
        { err, eventId },
        "[AccountSummaryHandler] Failed to send to GTI",
      );
      return { ok: false, error: err as Error };
    }
 
    // Update backfill
    // this.backfillCacheService.updateBackfill(mergedResults);
 
    return { ok: true, value: undefined };
  }
 
  // ===== NEGATIVE METRIC HELPER METHODS =====
 
  /**
   * Check if change amount is negative
   */
  private isNegativeChange(changeAmount: Amount): boolean {
    return changeAmount.amount < 0n;
  }
 
  /**
   * Extract account name from metric account
   * Example: "S-OWN-FCEL-COST-BASIS" -> "S-OWN-FCEL"
   * Example: "S-FCEL-REALIZE-L" -> "S-FCEL"
   */
  private extractAccountNameFromMetric(metricAccount: string): string {
    // Remove common suffixes
    const withoutSuffix = metricAccount
      .replace("-COST-BASIS", "")
      .replace("-REALIZE-PL", "")
      .replace("-REALIZE-L", "")
      .replace("-REALIZE-S", "")
      .replace("-TOTAL", "")
      .replace("-USD", "")
      .replace("-IDR", "");
 
    // For patterns like "testing-S-OWN-GOOGL-COST-BASIS"
    // We want to extract "S-OWN-GOOGL"
    const parts = withoutSuffix.split("-");
 
    // Look for S-OWN-SYMBOL or OP-OWN-INSTRUMENT patterns
    for (let i = 0; i < parts.length - 2; i++) {
      if (parts[i] === "S" && parts[i + 1] === "OWN") {
        // Found S-OWN pattern, extract S-OWN-SYMBOL
        const accountName = parts.slice(i, i + 3).join("-");
        return accountName;
      }
      Iif (parts[i] === "S" && parts[i + 1] === "RES") {
        // Found S-RES pattern, extract S-RES-SYMBOL or S-RES-OP-TICKER
        if (parts[i + 2] === "OP" && parts.length > i + 3) {
          // S-RES-OP-TICKER pattern
          const accountName = parts.slice(i, i + 4).join("-");
          return accountName;
        } else {
          // Traditional S-RES-SYMBOL pattern
          const accountName = parts.slice(i, i + 3).join("-");
          return accountName;
        }
      }
      if (parts[i] === "OP" && parts[i + 1] === "OWN") {
        // Found OP-OWN pattern, extract OP-OWN-INSTRUMENT
        const accountName = parts.slice(i).join("-");
        return accountName;
      }
      Iif (parts[i] === "C" && parts[i + 1] === "RES") {
        // Found C-RES pattern, extract C-RES or C-RES-OP-TICKER
        if (parts[i + 2] === "OP" && parts.length > i + 3) {
          // C-RES-OP-TICKER pattern
          const accountName = parts.slice(i, i + 4).join("-");
          return accountName;
        } else {
          // Traditional C-RES pattern
          const accountName = parts.slice(i, i + 2).join("-");
          return accountName;
        }
      }
    }
 
    // Fallback to original logic if no pattern found
    if (parts.length >= 3) {
      // Look for pattern starting with S- or B- or OP- or other account indicators
      let accountName = "";
 
      // Find the index where account name starts (usually after "ledger")
      const ledgerIndex = parts.findIndex((part) => part === "ledger");
      if (ledgerIndex >= 0 && ledgerIndex + 1 < parts.length) {
        // Take parts after "ledger"
        const accountParts = parts.slice(ledgerIndex + 1);
 
        // For OPTIONS with long instrument names: OP-OWN-COIN250620C00690000
        if (accountParts.length >= 3 && accountParts[0] === "OP") {
          accountName = accountParts.join("-"); // OP-OWN-COIN250620C00690000
        } else if (accountParts.length >= 3) {
          // S-OWN-FCEL pattern (3 parts)
          accountName = accountParts.slice(0, 3).join("-");
        } else if (accountParts.length >= 2) {
          // S-FCEL pattern (2 parts)
          accountName = accountParts.slice(0, 2).join("-");
        } else if (accountParts.length >= 1 && accountParts[0]) {
          // Single part
          accountName = accountParts[0];
        }
      } else {
        // Fallback: take last few parts
        if (parts.length >= 5) {
          accountName = parts.slice(-3).join("-"); // S-OWN-FCEL
        } else if (parts.length >= 4) {
          accountName = parts.slice(-2).join("-"); // S-FCEL
        } else {
          accountName = parts.slice(-1).join("-");
        }
      }
 
      return accountName;
    }
 
    return withoutSuffix;
  }
 
  /**
   * Calculate negative metric using formula:
   * CurrentValue - (SubQty * (CurrentValue/(TotalQty + SubQty)))
   * Now supports multiple account summation (RES + OWN, OP-RES + OP-OWN)
   */
  private calculateCostBasisFormula(
    context: ProcessingContext,
    metricAccount: string,
    currentValue: Amount,
    changeAmount: Amount,
    totalQty: Amount,
  ): Amount {
    try {
      Iif (context.is_canceled) {
        this.logger.info(
          `[CANCELLED] Skipping average cost basis. Using direct reduction: currentValue - subQty`,
        );
 
        const subQty: Amount = {
          amount: -changeAmount.amount,
          scale: changeAmount.scale,
        };
 
        const newValue = minus(currentValue, subQty);
        return newValue as Amount;
      }
 
      // SubQty is absolute value of changeAmount (since it's negative)
      const subQty: Amount = {
        amount: -changeAmount.amount, // Make it positive
        scale: changeAmount.scale,
      };
 
      // For sell orders, check if all shares are being sold
      // If totalQty == subQty, then all shares are sold and cost basis should be 0
      Iif (totalQty.amount === subQty.amount) {
        this.logger.info(
          `All shares sold for ${metricAccount}, setting cost basis to 0`,
        );
        return { amount: 0n, scale: currentValue.scale };
      }
 
      // Formula: CurrentValue - (SubQty * (CurrentValue/TotalQty))
      // This maintains the correct proportional reduction
      const valuePerUnit = divide(currentValue, totalQty); // CurrentValue/TotalQty
      const reductionAmount = times(subQty, valuePerUnit); // SubQty * (CurrentValue/TotalQty)
      const newValue = minus(currentValue, reductionAmount); // CurrentValue - reductionAmount
 
      this.logger.info(
        `Negative metric calculation - Account: ${metricAccount}, CurrentValue: ${
          AmountMapper.toDTO(currentValue).amount
        }, TotalQty: ${AmountMapper.toDTO(totalQty).amount}, SubQty: ${
          AmountMapper.toDTO(subQty).amount
        }, ValuePerUnit: ${
          AmountMapper.toDTO(valuePerUnit).amount
        }, ReductionAmount: ${
          AmountMapper.toDTO(reductionAmount).amount
        }, NewValue: ${AmountMapper.toDTO(newValue).amount}`,
      );
 
      return newValue as Amount;
    } catch (error) {
      this.logger.error(
        `Error in negative metric calculation for ${metricAccount}: ${error}`,
      );
      return plus(currentValue, changeAmount) as Amount; // Fallback to normal calculation
    }
  }
 
  private getTotalQuantity(
    metricAccount: string,
    changeAmount: Amount,
    context: ProcessingContext,
  ): Amount {
    // For sell orders with cost basis metrics, we need special handling
    Iif (context.order_side === "sell" && metricAccount.includes("COST-BASIS")) {
      // Try to get the original quantity from txlogs (amount sold)
      const soldQuantity = this.calculateOriginalQuantityFromTxlogs(
        context,
        metricAccount,
      );
 
      // Try to get total quantity from current summary data (amount remaining)
      const remainingQuantity = this.calculateTotalQuantity(
        metricAccount,
        context,
      );
 
      if (soldQuantity && remainingQuantity) {
        // Original quantity = remaining quantity + sold quantity
        const originalTotalQty = plus(
          remainingQuantity,
          soldQuantity,
        ) as Amount;
 
        this.logger.info(
          `[SELL-ORDER] Calculated original quantity for ${metricAccount}: ${
            AmountMapper.toDTO(originalTotalQty).amount
          } (remaining: ${
            AmountMapper.toDTO(remainingQuantity).amount
          } + sold: ${AmountMapper.toDTO(soldQuantity).amount})`,
        );
        return originalTotalQty;
      }
 
      if (soldQuantity) {
        // Only sold quantity available, use it
        this.logger.info(
          `[SELL-ORDER] Using sold quantity from txlogs for ${metricAccount}: ${
            AmountMapper.toDTO(soldQuantity).amount
          }`,
        );
        return soldQuantity;
      }
 
      if (remainingQuantity) {
        // Only remaining quantity available, calculate original by adding sold amount
        const soldQuantity = absolute(changeAmount);
        const originalTotalQty = plus(
          remainingQuantity,
          soldQuantity,
        ) as Amount;
 
        this.logger.info(
          `[SELL-ORDER] Calculated original quantity from summary for ${metricAccount}: ${
            AmountMapper.toDTO(originalTotalQty).amount
          } (remaining: ${
            AmountMapper.toDTO(remainingQuantity).amount
          } + sold: ${AmountMapper.toDTO(soldQuantity).amount})`,
        );
        return originalTotalQty;
      }
 
      // Final fallback: use the sold quantity if we can't determine the original quantity
      this.logger.warn(
        `[SELL-ORDER] Could not determine original quantity for ${metricAccount}, using sold quantity as fallback`,
      );
      return context.share_quantity;
    }
 
    // Calculate total quantity (may be sum of multiple accounts)
    const totalQty = this.calculateTotalQuantity(metricAccount, context);
 
    Iif (!totalQty || totalQty.amount === 0n) {
      this.logger.info(
        `No quantity accounts found for ${metricAccount}, will use normal calculation instead of complex formula`,
      );
      return { amount: 0n, scale: 0n }; // Return zero to indicate no quantity accounts
    }
 
    // For non-sell events with negative cost basis change (e.g., dividend),
    // the totalQty from summaryMap is AFTER the qty change was applied.
    // We need to calculate the ORIGINAL qty BEFORE the change.
    // Example 1: Dividend adds +20 shares (txlog +20), summaryMap shows 420, original = 420 - 20 = 400
    // Example 2: Dividend subs -20 shares (txlog -20), summaryMap shows 380, original = 380 - (-20) = 400
    if (
      context.order_side !== "sell" &&
      metricAccount.includes("COST-BASIS") &&
      changeAmount.amount < 0n
    ) {
      // Find the qty change from txlogs for this asset
      const qtyChange = this.getQtyChangeFromTxlogs(metricAccount, context);
 
      Eif (qtyChange && qtyChange.amount !== 0n) {
        // Calculate original qty by reversing the txlog change
        // original = current - change (works for both positive and negative changes)
        const originalQty = minus(totalQty, qtyChange) as Amount;
 
        this.logger.info(
          `[NON-SELL] Calculated original quantity for ${metricAccount}: ${
            AmountMapper.toDTO(originalQty).amount
          } (current: ${AmountMapper.toDTO(totalQty).amount} - change: ${
            AmountMapper.toDTO(qtyChange).amount
          })`,
        );
 
        return originalQty;
      }
    }
 
    return totalQty;
  }
 
  /**
   * Get the quantity change from txlogs for a specific asset
   * Used to calculate original quantity before txlog changes were applied
   * Example: For COST-BASIS metric "S-OWN-BRK.B-COST-BASIS", find change in "S-OWN-BRK.B"
   */
  private getQtyChangeFromTxlogs(
    metricAccount: string,
    context: ProcessingContext,
  ): Amount | null {
    // Extract the asset account pattern from cost basis metric
    // e.g., "gti-staging-S-OWN-BRK.B-COST-BASIS" -> "S-OWN-BRK.B"
    const accountName = this.extractAccountNameFromMetric(metricAccount);
 
    Iif (!accountName) {
      return null;
    }
 
    // Find the corresponding txlog entry for this asset
    for (const txlog of context.event.txlogs) {
      if (
        txlog.book.book === context.bookId &&
        txlog.account.includes(accountName) &&
        !txlog.account.includes("COST-BASIS") &&
        !txlog.account.includes("REALIZE")
      ) {
        const qtyChange = AmountMapper.fromDTO({
          amount: txlog.change.amount.toString(),
          scale: txlog.change.scale.toString(),
        });
 
        this.logger.info(
          `[getQtyChangeFromTxlogs] Found qty change for ${accountName}: ${
            AmountMapper.toDTO(qtyChange).amount
          } from txlog account ${txlog.account}`,
        );
 
        return qtyChange;
      }
    }
 
    return null;
  }
 
  private getAverageCostsBasis(totalQty: Amount, currentValue: Amount): Amount {
    // For realized P&L calculation: ValuePerUnit = CurrentValue / TotalQty
    // This is used for calculating average cost basis for realized P&L
    // This is different from the negative metric formula
    const valuePerUnit = divide(currentValue, totalQty);
 
    return valuePerUnit;
  }
 
  /**
   * Calculate realized P&L amount for SELL (long position)
   * Formula: (Sale Price * Quantity) - (Average Cost Basis * Quantity)
   */
  private calculateRealizedPnL(
    context: ProcessingContext,
    costBasisForSale: Amount,
  ): Amount {
    // Formula: (price * share_quantity) - cost_basis_for_sale
    const grossProceeds = times(
      context.price,
      context.share_quantity,
    ) as Amount;
 
    const realizedPL = minus(grossProceeds, costBasisForSale) as Amount;
 
    return realizedPL;
  }
 
  /**
   * Calculate realized P&L amount for BUY TO CLOSE (short position)
   * Formula: (Average Cost Basis * Quantity) - (Close Price * Quantity)
   * Example: Short @ $300, Close @ $200, qty = 1
   * P&L = 300 - 200 = 100 profit
   */
  private calculateRealizedPnLBuyToClose(
    context: ProcessingContext,
    costBasisForClose: Amount,
    filledQty: Amount, // Use filled quantity, not total order quantity
  ): Amount {
    // Formula: cost_basis_for_close - (price * filled_quantity * 100)
    // For options: price is per share (e.g., $10 per share)
    // 1 contract = 100 shares, so total = price × qty × 100
    // NO FEE included per user request
 
    // Calculate close proceeds
    // For options: price × filledQty × 100 (shares per contract)
    const priceTimesQty = times(context.price, filledQty) as Amount;
 
    let closeProceeds: Amount;
    if (context.trade_type === "options") {
      // Multiply by 100 for options (shares per contract)
      closeProceeds = times(priceTimesQty, {
        amount: 100n,
        scale: 0n,
      }) as Amount;
    } else E{
      closeProceeds = priceTimesQty;
    }
 
    this.logger.info(
      `[P&L-CALC] costBasisForClose=${
        AmountMapper.toDTO(costBasisForClose).amount
      }, ` +
        `price=${AmountMapper.toDTO(context.price).amount}, ` +
        `filledQty=${AmountMapper.toDTO(filledQty).amount}, ` +
        `closeProceeds=${AmountMapper.toDTO(closeProceeds).amount}`,
    );
 
    const realizedPL = minus(costBasisForClose, closeProceeds) as Amount;
 
    this.logger.info(
      `[P&L-CALC] realizedPL=${AmountMapper.toDTO(realizedPL).amount}`,
    );
 
    return realizedPL;
  }
 
  /**
   * Update realized metrics (P&L, Profit, Loss) based on realized P&L amount
   * Following the specification:
   * - For loss: REALIZE-PL SUB amount, REALIZE-L ADD amount
   * - For profit: REALIZE-PL ADD amount, REALIZE-P ADD amount
   */
  private updateRealizedMetrics(
    context: ProcessingContext,
    realized_pl_amount: Amount,
  ): void {
    const prefix = context.prefix;
    const ticker = context.ticker;
    let assetType = "";
    if (context.trade_type === "options") {
      assetType = "OP";
    } else E{
      assetType = "S";
    }
 
    if (realized_pl_amount.amount < 0n) {
      // Handle Loss scenario - convert to positive for ledger entry
      const absoluteLoss = absolute(realized_pl_amount) as Amount;
 
      // REALIZE-PL SUB realized_pl_amount (subtract the loss)
      this.updateOrCreateMetric(
        context,
        `${prefix}-${assetType}-${ticker}-REALIZE-PL`,
        { amount: -absoluteLoss.amount, scale: absoluteLoss.scale },
      );
 
      // REALIZE-L ADD realized_pl_amount (add the loss amount)
      this.updateOrCreateMetric(
        context,
        `${prefix}-${assetType}-${ticker}-REALIZE-L`,
        absoluteLoss,
      );
    E} else if (realized_pl_amount.amount > 0n) {
      // Handle Profit scenario
      // REALIZE-PL ADD realized_pl_amount
      this.updateOrCreateMetric(
        context,
        `${prefix}-${assetType}-${ticker}-REALIZE-PL`,
        realized_pl_amount,
      );
 
      // REALIZE-P ADD realized_pl_amount
      this.updateOrCreateMetric(
        context,
        `${prefix}-${assetType}-${ticker}-REALIZE-P`,
        realized_pl_amount,
      );
    }
  }
 
  /**
   * Helper method to update or create metric in context
   */
  private updateOrCreateMetric(
    context: ProcessingContext,
    metricKey: string,
    amount: Amount,
  ): void {
    Iif (context.metricsMap.has(metricKey)) {
      const existingMetric = context.metricsMap.get(metricKey)!;
      const existingAmount = AmountMapper.fromDTO({
        amount: existingMetric.amount.toString(),
        scale: existingMetric.scale.toString(),
      });
 
      const newAmount = plus(existingAmount, amount) as Amount;
 
      context.metricsMap.set(metricKey, {
        book_type: "normal",
        book_id: context.bookId,
        amount: AmountMapper.toDTO(newAmount).amount,
        scale: AmountMapper.toDTO(newAmount).scale,
      });
    } else {
      const finalAmount = amount;
 
      context.metricsMap.set(metricKey, {
        book_type: "normal",
        book_id: context.bookId,
        amount: AmountMapper.toDTO(finalAmount).amount,
        scale: AmountMapper.toDTO(finalAmount).scale,
      });
    }
  }
 
  /**
   * Calculate total quantity from multiple accounts if needed
   * For REALIZE: S-FCEL-REALIZE-L → S-OWN-FCEL + S-RES-FCEL
   * For OPTIONS: OP-OWN-COIN250620C00690000-COST-BASIS → OP-OWN-COIN250620C00690000 + OP-RES-COIN250620C00690000
   */
  private calculateTotalQuantity(
    metricAccount: string,
    context: ProcessingContext,
  ): Amount | null {
    const accountName = this.extractAccountNameFromMetric(metricAccount);
 
    // Get base patterns for quantity calculation
    const quantityPatterns = this.getQuantityPatterns(
      accountName,
      metricAccount,
    );
 
    let totalQty: Amount = { amount: 0n, scale: 0n };
    let foundAccounts = 0;
 
    for (const pattern of quantityPatterns) {
      for (const [
        summaryAccount,
        summaryEntry,
      ] of context.summaryMap.entries()) {
        if (
          summaryAccount.includes(pattern) &&
          !summaryAccount.includes("COST-BASIS") &&
          !summaryAccount.includes("TOTAL") &&
          !summaryAccount.includes("REALIZE")
        ) {
          const accountQty = AmountMapper.fromDTO({
            amount: summaryEntry.value,
            scale: summaryEntry.scale,
          });
 
          totalQty = plus(totalQty, accountQty) as Amount;
          foundAccounts++;
 
          this.logger.info(
            `Found quantity account: ${summaryAccount} = ${
              AmountMapper.toDTO(accountQty).amount
            }`,
          );
        }
      }
    }
 
    Iif (foundAccounts === 0) {
      this.logger.warn(
        `No quantity accounts found for patterns: ${quantityPatterns.join(
          ", ",
        )}`,
      );
      return null;
    }
 
    this.logger.info(
      `Total quantity calculated: ${
        AmountMapper.toDTO(totalQty).amount
      } from ${foundAccounts} accounts`,
    );
    return totalQty;
  }
 
  /**
   * Calculate original quantity from txlogs for sell orders
   * For sell orders, we need to know the original quantity before the sale
   * to calculate the correct average cost basis
   */
  private calculateOriginalQuantityFromTxlogs(
    context: ProcessingContext,
    costBasisKey: string,
  ): Amount | null {
    // Extract the symbol from the cost basis key
    // e.g., "testing-S-OWN-MSTR-COST-BASIS" → "MSTR"
    const symbol = this.extractSymbolFromCostBasisKey(costBasisKey);
 
    if (!symbol) {
      return null;
    }
 
    // Look for the stock account changes in txlogs
    // For sell orders, we expect negative changes in OWN and RES accounts
    let originalQuantity: Amount = { amount: 0n, scale: 0n };
 
    for (const txlog of context.event.txlogs) {
      const account = txlog.account;
 
      // Check if this is a stock account for our symbol
      // More flexible pattern matching: account contains S-OWN-{symbol}, S-RES-{symbol}, or S-RES-OP-{ticker}
      if (
        account.includes(`S-OWN-${symbol}`) ||
        account.includes(`S-RES-${symbol}`) ||
        account.includes(`S-RES-OP-${symbol}`)
      ) {
        const changeAmount = AmountMapper.fromDTO({
          amount: txlog.change.amount.toString(),
          scale: txlog.change.scale.toString(),
        });
 
        // For sell orders, changes are negative, so we need to add the absolute value
        // to get the original quantity
        if (changeAmount.amount < 0n) {
          const absoluteChange = absolute(changeAmount) as Amount;
          originalQuantity = plus(originalQuantity, absoluteChange) as Amount;
        }
      }
    }
 
    if (originalQuantity.amount > 0n) {
      this.logger.info(
        `[SELL-ORDER] Calculated original quantity from txlogs: ${
          AmountMapper.toDTO(originalQuantity).amount
        }`,
      );
      return originalQuantity;
    }
    return null;
  }
 
  /**
   * Extract symbol from cost basis key
   * e.g., "testing-S-OWN-MSTR-COST-BASIS" → "MSTR"
   */
  private extractSymbolFromCostBasisKey(costBasisKey: string): string | null {
    const parts = costBasisKey.split("-");
 
    // Look for the pattern: prefix-S-OWN-SYMBOL-COST-BASIS
    for (let i = 0; i < parts.length - 2; i++) {
      if (
        parts[i] === "S" &&
        parts[i + 1] === "OWN" &&
        parts[i + 3] === "COST" &&
        parts[i + 4] === "BASIS"
      ) {
        const symbol = parts[i + 2];
        return symbol || null; // The symbol is between OWN and COST
      }
    }
 
    return null;
  }
 
  /**
   * Get patterns to search for quantity calculation
   * All metrics use same summation strategy:
   * - S-OWN-{symbol}-{metric} → search [S-OWN-{symbol}, S-RES-{symbol}]
   * - OP-OWN-{instrument}-{metric} → search [OP-OWN-{instrument}, OP-RES-{instrument}]
   * - Fallback: if RES not found, use OWN only
   */
  private getQuantityPatterns(
    accountName: string,
    metricAccount: string,
  ): string[] {
    // Options pattern: OP-OWN-{instrument}-{metric}
    if (metricAccount.includes("OP-OWN-")) {
      // From: OP-OWN-COIN250620C00690000-COST-BASIS → extract COIN250620C00690000
      let instrumentPart = accountName.replace("OP-OWN-", "");
 
      // Remove metric suffixes from the end
      instrumentPart = instrumentPart
        .replace("-COST-BASIS", "")
        .replace("-REALIZE-PL", "")
        .replace("-REALIZE-L", "")
        .replace("-REALIZE-S", "");
 
      Eif (instrumentPart) {
        return [
          `OP-OWN-${instrumentPart}`, // OP-OWN-COIN250620C00690000
          `OP-RES-${instrumentPart}`, // OP-RES-COIN250620C00690000
        ];
      }
    }
 
    // Stocks pattern: S-OWN-{symbol}-{metric}
    Eif (metricAccount.includes("S-OWN-")) {
      // From: S-OWN-FCEL-COST-BASIS → extract FCEL
      let symbol = accountName.replace("S-OWN-", "");
 
      // Remove metric suffixes from the end
      symbol = symbol
        .replace("-COST-BASIS", "")
        .replace("-REALIZE-PL", "")
        .replace("-REALIZE-L", "")
        .replace("-REALIZE-S", "");
 
      Eif (symbol) {
        return [
          `S-OWN-${symbol}`, // S-OWN-FCEL
          `S-RES-${symbol}`, // S-RES-FCEL (traditional)
          `S-RES-OP-${symbol}`, // S-RES-OP-{TICKER} (options)
        ];
      }
    }
 
    // Fallback for old patterns
    const parts = accountName.split("-");
    if (parts.length >= 3) {
      return [parts.slice(1).join("-")]; // OWN-FCEL (fallback to old pattern)
    } else if (parts.length >= 2) {
      return [accountName]; // Direct match
    }
 
    return [accountName];
  }
 
  /**
   * Get summary with exact timestamp `transactionTime`.
   * 1. Search Redis first (previous events may be stored there but not flushed to DB)
   * 2. Fallback to database query if not found
   */
  private async getSummaryAtTxTime(
    bookId: string,
    transactionTime: Date,
  ): Promise<AccountSummaryEntity | null> {
    // 1. Redis
    const redisRes = await this.accountSummaryRedisStore.get(bookId);
    if (redisRes.ok && Array.isArray(redisRes.value)) {
      const exact = redisRes.value.find(
        (s) =>
          s.transaction_time &&
          new Date(s.transaction_time).getTime() === transactionTime.getTime(),
      );
      if (exact) {
        return exact as AccountSummaryEntity;
      }
    }
 
    // 2. Database
    const repository =
      this.appDataSourceService.AppDataSource.getRepository(
        AccountSummaryEntity,
      );
    return repository.findOne({
      where: { book_id: bookId, transaction_time: transactionTime },
    });
  }
}
 
export { AccountSummaryEventHandlerClean };