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 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 | 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 33x 33x 33x 33x 33x 38x 12x 50x 33x 84x 2x 33x 12x 12x 12x 12x 12x 12x 12x 12x 10x 10x 10x 9x 1x 8x 8x 8x 8x 8x 6x 6x 6x 6x 6x 6x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 12x 12x 12x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 12x 12x 12x 12x 12x 33x 40x 28x 28x 40x 30x 30x 28x 22x 22x 12x 12x 12x 12x 12x 12x 10x 10x 10x 10x 10x 10x 10x 10x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 158x 439x 109x 109x 109x 35x 35x 35x 35x 2x 39x 1x 1x 39x 39x 39x 39x 39x 106x 106x 3x 103x 75x 28x 106x 1x 1x 1x 1x 1x 1x 38x 71x 71x 71x 71x 71x 71x 71x 40x 5x 5x 5x 40x 38x 38x 70x 70x 1x 70x 70x 70x 38x 32x 38x 1x 1x 2x 1x 2x 2x 2x 2x 1x 1x 1x 1x 38x 38x 38x 38x 49x 23x 26x 38x 38x 23x 23x 20x 40x 20x 20x 20x 20x 41x 41x 25x 41x 41x 41x 41x 41x 45x 45x 45x 1x 41x 41x 38x 41x 1x 1x 40x 40x 40x 40x 40x 40x 40x 41x 40x 70x 37x 33x 18x 15x 15x 15x 15x 15x 15x 15x 15x 3x 2x 2x 2x 8x 16x 16x 16x 16x 16x 5x 16x 28x 4x 9x 9x 9x 9x 5x 4x 2x 2x 2x 2x 2x 2x 2x 2x 9x 9x 9x 9x 7x 7x 2x 9x 8x 8x 8x 8x 8x 8x 8x 8x 11x 8x 8x 8x 8x 8x 5x 5x 5x 3x 2x 2x 2x 2x 2x 2x 2x 2x 5x 5x 5x 5x 3x 3x 2x 5x 6x 6x 6x 6x 6x 6x 6x 6x 12x 6x 6x 6x 6x 6x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 45x 20x 20x 45x 16x 16x 45x 5x 5x 47x 139x 33x 139x 47x 43x 20x 43x 47x 10x 3x 10x 47x 82x 16x 82x 1x 1x 76x 54x 27x 3x 4x 59x 15x 15x 15x 15x 2x 2x 13x 15x 66x 66x 15x 14x 14x 15x 14x 1x 11x 11x 11x 11x 11x 11x 47x 47x 11x 11x 10x 10x 11x 3x 3x 3x 2x 2x 2x 2x 3x 8x 8x 8x 8x 8x 8x 7x 7x 7x 7x 8x 47x 47x 19x 19x 6x 19x 5x 5x 5x 38x 2x 2x 47x 3x 38x 2x 2x 1x 1x 1x 1x 1x 2x 2x 2x 2x 1x 1x 6x 6x 8x 8x 2x 2x 1x 1x 1x 1x 8x 7x 6x 6x 7x 7x 7x 6x 7x 7x 2x 2x 2x 2x 2x 1x 2x 2x 1x 1x 1x 5x 47x 7x 7x 7x 7x 7x 7x 1x 6x 6x 7x 7x 7x 6x 6x 6x 5x 5x 5x 5x 5x 5x 1x 1x 1x 5x 1x 1x 3x 3x 3x 3x 1x 1x 47x 41x 3x 3x 2x 3x 41x 41x 41x 47x 47x 39x 38x 38x 38x 38x 1x 1x 3x 3x 3x 41x 41x 2x 39x 39x 18x 39x 39x 21x 39x 39x 39x 39x 6x 4x 4x 2x 6x 2x 38x 38x 69x 69x 38x 37x 37x 22x 13x 22x 15x 15x 15x 38x 69x 2x 38x 4x 2x 2x 2x 1x 1x 4x 4x 5x 5x 3x 3x 1x 3x 2x 3x 2x 47x 47x 47x 47x 6x 6x 4x 41x 41x 41x 41x 41x 41x 41x 2x 2x 2x 2x 41x 39x 39x 39x 38x 2x 2x 2x 38x 38x 38x 38x 38x 36x 38x 1x 1x 1x 1x 1x 1x 41x 2x 2x 41x 41x 41x 15x 14x 1x 1x 1x 1x 1x 1x 1x 2x 1x 2x 8x 48x 48x 48x 48x 48x 48x 48x 48x 48x 48x 48x 48x 45x 45x 40x 51x 48x 271x 47x 271x 16x 15x 15x 15x 15x 1x 12x 12x 12x 12x 12x 48x 49x 13x 1x 12x 12x 11x 12x 48x 34x 5x 1x 4x 4x 3x 4x 48x 154x 10x 1x 9x 9x 8x 9x 7x 7x 48x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x | import { Injectable, OnDestroy } from '@angular/core';
import { ReplaySubject, Observable, Subject, Subscription, firstValueFrom } from 'rxjs';
import { take } from 'rxjs/operators';
import { AppConstants } from '@unpispas/upp-defs';
import { CommitChange } from './model/base';
import { UserMode } from '@unpispas/upp-base';
import { identificationService } from '@unpispas/upp-base';
import { adhocService } from '@unpispas/upp-base';
import { stateService } from '@unpispas/upp-base';
import { storeService } from '@unpispas/upp-base';
import { languageService } from '@unpispas/upp-base';
import { alertService } from '@unpispas/upp-base';
import { toastService } from '@unpispas/upp-base';
import { clockService } from '@unpispas/upp-base';
import { StorageDDBB, StorageMeta, StorageData } from './cache';
import { cacheService } from './cache';
import { User } from './model/objects/user';
import { QrCode } from './model/objects/qrcode';
import { Place } from './model/objects/place';
/**
* Represents the set of triggers used to configure and update a server connection.
*
* Triggers define the conditions under which the connection is active and synchronized.
* They allow the server to associate the connection with specific entities, such as
* a session, QR code, user, or place.
*/
interface UpdateTriggers {
/**
* The session identifier associated with the connection.
* This value is mandatory and uniquely identifies the session.
*/
SESSION: string,
/**
* The QR code identifier associated with the connection, if applicable.
* If no QR code is associated, this value is `null`.
*/
QRCODE: string | null,
/**
* The user identifier associated with the connection, if applicable.
* If no user is associated, this value is `null`.
*/
USER: string | null,
/**
* The place identifier associated with the connection, if applicable.
* If no place is associated, this value is `null`.
*/
PLACE: string | null
}
type LoadTarget = 'SESSION' | 'PLACE' | 'QRCODE';
/**
* Represents the payload sent to the server for a synchronization request.
*/
interface UpdateRequest {
/**
* The access mode for the session.
* Defines the permissions or roles of the user in the current session.
*/
access: UserMode;
/**
* The timestamp of the last successful response from the server.
* If this is the first request in a session, the value should be `0`.
*/
timestamp: number;
/**
* The target currently being loaded or synchronized.
* Specifies the entity (e.g., SESSION, PLACE, QRCODE) associated with this request.
*/
target: LoadTarget;
}
/**
* Represents the response received from the server after a synchronization request.
*/
interface UpdateRespose {
/**
* The error code indicating the result of the operation.
* A value of `0` typically represents success, while other values indicate specific errors.
*/
errorcode: number;
/**
* The current timestamp for the next synchronization operation.
* Used to track the server's state and synchronize updates incrementally.
*/
timestamp: number;
/**
* The server's time reference for updates.
* This value helps adjust the local client clock to align with the server's timing.
*/
reference: number;
/**
* The target currently loaded or synchronized.
* Mirrors the target specified in the request, representing the entity being synchronized.
*/
target: LoadTarget;
/**
* Indicates whether the committed data has been updated.
* Even on failure, this flag may be set to `true` if some changes were partially applied.
*/
updated: boolean;
/**
* Indicates whether the user's session has expired.
* If `true`, the session needs to be reauthenticated before further requests.
*/
expired: boolean;
/**
* A list of changes in the server data.
* Contains the updated entries resulting from the synchronization operation.
*/
updates: Array <any>;
}
type ConnectionStatus = 'RUNNING' | 'STOPPED' | 'EXPIRED';
/**
* Manages the lifecycle of a client-server connection for data synchronization.
* Includes methods for creating, updating, and releasing the connection,
* as well as controlling data refresh cycles.
*/
class Connection {
private _doCancelUrl = 'connection/cancel';
private _doCreateUrl = 'connection/create';
private _doDeleteUrl = 'connection/delete';
private _doUpdateUrl = 'connection/update';
/**
* Creates a new `Connection` instance.
* @param sync - The `syncService` instance responsible for synchronization.
*/
constructor(private sync: syncService){
// nothing to do
}
/**
* Gets the `adhocService` instance from the provided `syncService`.
*/
private get adhoc(): adhocService {
return this.sync.adhoc;
}
/**
* Gets the `stateService` instance from the provided `syncService`.
*/
private get state(): stateService {
return this.sync.state;
}
/**
* Gets the `Syncronizator` instance from the provided `syncService`.
*/
private get syncr(): Syncronizator {
return this.sync.synchonizer;
}
private _status: ConnectionStatus = 'STOPPED';
/**
* Gets the current connection status.
*/
get status(): ConnectionStatus{
return this._status;
}
/**
* Sets the current connection status.
*/
set status(value: ConnectionStatus){
this._status = value;
}
private _triggers: UpdateTriggers | null = null
/**
* Gets the current update triggers for the connection.
*/
get triggers(){
return this._triggers;
}
/***************************************/
/* CONNECTION CONTROL */
/***************************************/
/**
* Creates a new connection and initializes data refresh.
* @param session - The session ID for the connection.
* @returns A promise resolving to `true` if the connection is created successfully, `false` otherwise.
*/
async CreateConnection(): Promise <boolean> {
const _session = this.state.session;
Iif (_session == null){
throw new Error("[SYNC] Session must be configured!")
}
const _qrcode = this.sync.qrcode ? this.sync.qrcode.objid : null;
const _user = this.sync.user ? this.sync.user.objid : null;
const _place = this.sync.place ? this.sync.place.objid : null;
if (await this.configureTriggers({ SESSION: _session, QRCODE: _qrcode, USER: _user, PLACE: _place })){
await this.initializeRefresh();
}
else E{
if (this.status != 'EXPIRED'){
throw new Error("[SYNC] Cannot configure connection. Triggers not set")
}
else {
console.warn("[SYNC] Cannot configure connection. Session is expired.")
}
}
return true;
}
/**
* Refreshes the connection by reconfiguring the update triggers.
* @returns A promise resolving to `true` if the refresh is successful, `false` otherwise.
*/
async RefreshConnection(): Promise <boolean> {
return await this.configureTriggers(this._triggers);
}
/**
* Releases the current connection and finalizes the refresh cycle.
* @returns A promise resolving to `true` if the release is successful, `false` otherwise.
*/
async ReleaseConnection() : Promise <boolean> {
if (await this.configureTriggers(null)){
await this.finalizeRefresh();
}
return true;
}
/***************************************/
/* ENTRY POINT */
/***************************************/
/**
* Updates the connection to associate a user.
* @param user - The user to associate, or `null` to remove the user.
* @returns A promise resolving to `true` if successful, `false` otherwise.
*/
async SetUser(user: User | null): Promise <boolean> {
if (!this._triggers){
return true; // nothing to update
}
const _triggers: UpdateTriggers = Object.assign({}, this._triggers);
_triggers.QRCODE = null;
_triggers.USER = user ? user.objid : null;
_triggers.PLACE = null;
return await this.UpdateConnection(_triggers);
}
/**
* Updates the connection to associate a place.
* @param place - The place to associate, or `null` to remove the place.
* @returns A promise resolving to `true` if successful, `false` otherwise.
*/
async SetPlace(place: Place | null): Promise <boolean> {
Iif (!this._triggers){
return true; // nothing to update
}
const _triggers: UpdateTriggers = Object.assign({}, this._triggers);
_triggers.QRCODE = null;
_triggers.USER = place?.user?.objid || null;
_triggers.PLACE = place?.objid || null;
return await this.UpdateConnection(_triggers);
}
/**
* Updates the connection to associate a QR code.
* @param qrcode - The QR code to associate, or `null` to remove the QR code.
* @returns A promise resolving to `true` if successful, `false` otherwise.
*/
async SetQrCode(qrcode: QrCode | null): Promise <boolean> {
Iif (!this._triggers){
return false;
}
const _triggers: UpdateTriggers = Object.assign({}, this._triggers);
_triggers.QRCODE = qrcode ? qrcode.objid : null;
_triggers.USER = null;
_triggers.PLACE = null;
return await this.UpdateConnection(_triggers);
}
/**
* Cancels the current data refresh operation.
* @returns A promise resolving to `true` if the cancellation is successful, `false` otherwise.
*/
async CancelRefresh(): Promise <boolean> {
try {
const data = await this.adhoc.DoRequest(this._doCancelUrl, null, null, false);
const _success = (data['errorcode'] == 0);
Iif (!_success){
console.error("[CONNECTED] Error [" + data['errorcode'] + "] sending cancelation");
}
return _success;
}
catch (error: any) {
return this._throwerror(this._doCancelUrl, error);
}
}
/******************************/
/* REFRESH CONTROL */
/******************************/
/**
* Initializes the data refresh process
*/
private async initializeRefresh(){
Iif (this._status == 'EXPIRED'){
this._status = 'STOPPED';
}
console.info("[INITIALIZE] Connected to data service");
await this.resumeRefresh();
}
/**
* Finalizes the data refresh process and runs a final synchronization.
*/
private async finalizeRefresh(){
const _expired = (this._status == 'EXPIRED');
const _started = (this._status == 'RUNNING');
await this.pauseRefresh(false);
if (!_expired && _started){
await this.syncr.DoRefresh(false, false);
}
this._status ='STOPPED';
}
/**
* Pauses the data refresh process.
*/
private async pauseRefresh(stop = true){
if (this._refresh_timeout){
clearTimeout(this._refresh_timeout);
this._refresh_timeout = null;
}
const _expired = (this._status == 'EXPIRED');
if (!_expired){
Iif (stop){
this._status = 'STOPPED';
}
await this.syncr.CancelRefresh();
}
}
/**
* Resumes the data refresh process if the connection is active.
*/
private async resumeRefresh(){
const _expired = (this._status == 'EXPIRED');
if (!_expired){
Iif (this._status == 'RUNNING'){
console.warn("[INITIALIZE] Already running!");
return;
}
this._status = 'RUNNING';
this.repeatRefresh();
}
}
private _refresh_timeout: ReturnType<typeof setTimeout> | null = null;
/**
* Initiates periodic refresh cycles while the connection is active.
*/
private repeatRefresh(){
if (this._refresh_timeout){
clearTimeout(this._refresh_timeout);
this._refresh_timeout = null;
}
this._refresh_timeout = setTimeout(() => {
if (this._status == 'RUNNING') {
this.syncr.DoRefresh(false, false).then(
() => {
this.repeatRefresh();
});
}
else E{
console.info("[SYNC] Skip refresh (not running)")
}
}, AppConstants.MainRefresh);
}
/******************************/
/* UPDATE CONTROL */
/******************************/
/**
* Configures or clears update triggers for the connection.
*
* When triggers are provided, this method sends a request to the server to create
* or update the connection. If triggers are `null`, it sends a request to delete
* the connection.
*
* @param triggers - The `UpdateTriggers` object containing configuration for the connection, or `null` to clear triggers.
* @returns A promise resolving to `true` if the operation is successful, `false` otherwise.
* @throws If triggers are `null` and the connection is not running, an error is thrown.
*/
private async configureTriggers(triggers: UpdateTriggers | null) : Promise <boolean> {
Iif (this._triggers == triggers){
try {
const data = await this.adhoc.DoRequest(this._doUpdateUrl, null, triggers, false);
if (data['errorcode'] == 0){
console.info("[CONNECTED] Connected to server (id: " + data['connection'] + ")");
}
else {
if ((data['errorcode'] == 2) || (data['errorcode'] == 3)){
this.sync.OnSessionExpired();
}
else {
console.error("[CONNECTED] Error [" + data['errorcode'] + "] updating connection");
}
}
return (data['errorcode'] == 0);
}
catch (error: any) {
return this._throwerror(this._doCreateUrl, error);
}
}
if (triggers){
try {
const data = await this.adhoc.DoRequest(this._doCreateUrl, null, triggers, false);
if (data['errorcode'] == 0){
this._triggers = triggers;
console.info("[CONNECTED] Connected to server (id: " + data['connection'] + ")");
}
else E{
if ((data['errorcode'] == 2) || (data['errorcode'] == 3)){
this.sync.OnSessionExpired();
}
else {
console.error("[CONNECTED] Error [" + data['errorcode'] + "] creating connection");
}
}
return (data['errorcode'] == 0);
}
catch (error: any) {
return this._throwerror(this._doCreateUrl, error);
}
}
else {
// if we havent started, we need some triggers
Iif (!(['RUNNING', 'EXPIRED'].includes(this.status))){
throw new Error("[SYNC] update triggers are not set");
}
try {
const data = await this.adhoc.DoRequest(this._doDeleteUrl, null, null, false)
if (data){
if ((data['errorcode'] == 0) || (data['errorcode'] == 2)) {
this._triggers = null;
console.info("[CONNECTED] Disconnected from service")
return true;
}
else E{
console.error("[CONNECTED] Error [" + data['errorcode'] + "] deleting connection");
return false;
}
}
return false; // no data?
}
catch (error: any) {
return this._throwerror(this._doDeleteUrl, error);
}
}
}
/**
* Updates the connection configuration with new triggers or releases the connection.
*
* This method compares the new triggers with the current triggers. If they differ,
* it sends a request to update the configuration on the server. If the triggers
* are `null`, the connection is released.
*
* @param triggers - The new `UpdateTriggers` object, or `null` to release the connection.
* @returns A promise resolving to `true` if the operation is successful, `false` otherwise.
*/
private async UpdateConnection(triggers: UpdateTriggers | null): Promise <boolean> {
Iif (this.status != 'RUNNING'){
throw new Error("[CONNECTED] Cannot update connection if status is '" + this.status + "'")
}
else { // status == 'RUNNING'
if (triggers && triggers.SESSION){
const _change = (JSON.stringify(this._triggers) != JSON.stringify(triggers));
if (_change){
try {
const data = await this.adhoc.DoRequest(this._doUpdateUrl, null, triggers, false);
if (data){
if (data['errorcode'] == 0){
this._triggers = triggers;
console.info("[CONNECTED] Server configuration updated..");
return true;
}
else E{
console.error("[CONNECTED] Error [" + data['errorcode'] + "] updating service");
return false;
}
}
return false; // no data ?
}
catch(error: any){
return this._throwerror(this._doUpdateUrl, error);
}
}
else E{
return true; // no changes
}
}
else E{
return await this.ReleaseConnection();
}
}
}
/******************************/
/* PRIVATE METHODS */
/******************************/
/**
* Logs error messages for failed HTTP requests.
* @param url - The URL of the request.
* @param error - Error details.
* @returns `false` indicating failure.
*/
private _throwerror(url: string, error: any): boolean {
if (error && error.status) {
console.error("[REQUEST] Error [" + error.status + "] in http request '" + url + "'");
}
else {
console.error("[REQUEST] Generic error in http request '" + url + "'");
}
return false;
}
}
/**
* Represents a queue for managing pending changes and updates in a synchronization service.
* The queue handles priorities, processing order, and progress tracking for updates.
*/
class PendingQueue {
private _pending: Array <any> = [];
private _progress = [ 0, 0 ];
private _stage = 0;
private _refreshStage = new Subject<number> ();
/** Observable for tracking refresh stages. */
public OnRefreshStage = this._refreshStage.asObservable();
private _refreshPercent = new Subject<number> ();
/** Observable for tracking the percentage of refresh completion. */
public OnRefreshPercent = this._refreshPercent.asObservable();
private _onChange = new Subject<any>(); // change recovered from server
/** Observable for changes received from the server. */
public OnChange = this._onChange.asObservable();
/**
* Creates a new `PendingQueue` instance.
* @param sync - The synchronization service associated with this queue.
*/
constructor(private sync: syncService){
// nothing to do
}
/**
* Cleans up resources and subscriptions when the queue is destroyed.
*/
OnDestroy(){
this.Reset();
Iif (this._onblock_subscription){
this._onblock_subscription.unsubscribe();
this._onblock_subscription = null;
}
}
/**
* Provides access to the clock service.
*/
private get clock(): clockService {
return this.sync.clock;
}
/**
* Provides access to the state service.
*/
private get state(): stateService {
return this.sync.state;
}
/*********************************/
/* LOADING STATUS */
/*********************************/
/**
* Gets the current stage of the queue.
*/
get Stage(){
return this._stage;
}
/**
* Sets the current stage of the queue. Resets the queue if the stage is set to 0.
*/
set Stage(value){
Iif (value == 0) {
this.Reset();
}
const _next = Math.min(9, value);
if (_next > this._stage){
this._stage = _next
this._refreshStage.next(this.Stage);
setTimeout(() => {
this.NotifyPercent();
}, 0);
}
}
/**
* Gets the number of pending items in the queue.
*/
get length(){
return this._pending.length;
}
/**
* Resets the queue, clearing all pending items and resetting progress and stage.
*/
Reset(){
if (this._process_timeout){
clearTimeout(this._process_timeout);
this._process_timeout = null;
}
this._progress[0] = 0;
this._progress[1] = 0;
this._stage = 0;
this._pending = [];
this._refreshStage.next(this.Stage);
}
/**
* Notifies observers of the current refresh percentage.
*/
private NotifyPercent(){
const percent: number = ((stage: number, current: number, total: number) => {
if (stage === 0) {
return 0; // not started
}
if (stage === 9) {
return 1; // completed
}
return total === 0 ? 0 : Math.floor((current / total) * 100) / 100;
})(this.Stage, this._progress[0], this._progress[1]);
this._refreshPercent.next(percent);
}
/*********************************/
/* QUEUE MANAGEMENT */
/*********************************/
/**
* Merges two change objects, resolving conflicts by using the most recently updated version.
* @param chng1 - The first change object.
* @param chng2 - The second change object.
* @returns A merged change object.
* @throws If the `updated` field is not in a valid date format.
*/
private _MergeChange(chng1: any, chng2: any): any {
try {
const updated1 = new Date(chng1['updated'].replace(' ', 'T') + '.000Z');
const updated2 = new Date(chng2['updated'].replace(' ', 'T') + '.000Z');
const source = updated1.getTime() > updated2.getTime() ? chng1 : chng2;
const target = updated1.getTime() > updated2.getTime() ? chng2 : chng1;
return { ...target, ...source }; // Merge with spread syntax
}
catch {
throw new Error("[SYNC] Invalid date format in received change");
}
}
/**
* Adds items to the queue and updates progress tracking.
* @param _items - The items to enqueue.
*/
private Enqueue(_items: Array <any>){
this._progress[1] += _items.length;
}
/**
* Removes an item from the queue and processes it.
* @param _item - The item to dequeue.
*/
private Dequeue(_item: any){
const _pcnt0 = this._progress[1] === 0 ? 0 : Math.floor((this._progress[0] / this._progress[1]) * 100) / 100;
this._progress[0]++;
const _pcnt1 = this._progress[1] === 0 ? 0 : Math.floor((this._progress[0] / this._progress[1]) * 100) / 100;
this._onChange.next(_item);
this.Stage = parseInt(_item['__priority']);
if (_pcnt0 != _pcnt1){
this.NotifyPercent();
}
}
/**
* Merges and enqueues a list of updates, processing them in priority order.
* @param _updates - The updates to enqueue.
* @param _synchronous - Whether to process updates synchronously.
*/
async Concat(_updates: Array <any>, _synchronous: boolean){
await Promise.resolve(); // release the event loop
function ChangeKey(change: any){
Iif (!('table' in change) || !('objid' in change)){
throw new Error("[SYNC] Invalid update item received (missing fields)")
}
Iif (!change['table'] || !change['objid']){
throw new Error("[SYNC] Invalid update item received (missing index values)")
}
return change['table'] + '@' + change['objid'];
}
if (_updates.length > 0){
const _brief = []; // only for debugging purposes
// set the priority for all updates
for (const _update of _updates){
_update['__priority'] = this._priority(_update);
// reprioritize inserted entries (in range [-9 .. -1])
if (_update['_actn'] == 'do_insert'){
_update['__priority'] -= 10.0;
}
// add to the updates brief report
if (!(_update['table'] in _brief)){
_brief[_update['table']] = 0;
}
_brief[_update['table']]++;
}
_updates.sort((a, b) => {
return (a['__priority'] - b['__priority']);
});
// merge the udpates in the pending list
if (this._pending.length > 0){
const _pndmap = new Map();
for(const _pending of this._pending){
_pndmap.set(ChangeKey(_pending), _pending);
}
for(let _idx = _updates.length - 1; _idx >= 0; _idx--){
const _update = _updates[_idx];
const _pnditm = _pndmap.get(ChangeKey(_update));
let _assign = null;
if (_pnditm){
_assign = this._MergeChange(_update, _pnditm); // merge this entry;
_pndmap.set(ChangeKey(_update), _assign); // replace this entry
_updates.splice(_idx, 1); // remove from updates
}
}
this._pending = [..._pndmap.values()];
}
// enqueue all other updates (not in pending list)
this.Enqueue(_updates);
// release the synchronous entries
if (_updates.length > 0){
this.clock.ClockEnable('synchronous', (this.Stage > 6));
while(_updates.length > 0){
if ((!_synchronous) && (this.Stage > 3)) {
break;
}
this.Dequeue(_updates.shift());
}
this.clock.ClockEnable('synchronous', true);
}
if (_updates.length > 0){
this._pending = this._pending.concat(_updates);
this._pending.sort((a, b) => {
return (a['__priority'] - b['__priority']);
});
}
}
this.ProcessQueue();
}
/*********************************/
/* PROCESS QUEUE */
/*********************************/
private _blockProcessed = new Subject <void> ();
private OnBlockProcessed = this._blockProcessed.asObservable();
private _onblock_subscription: Subscription | null = null;
private _process_timeout: ReturnType<typeof setTimeout> | null = null;
/**
* Processes the queue in stages, prioritizing blocks of updates for efficiency.
*/
private _ProcessQueue(){
let _stage = this.Stage;
if (this._pending.length > 0){
_stage = this._pending[0]['__priority'];
}
const _prioritize = (_stage < 6);
let _todo = Math.min(this._pending.length, _prioritize ? 5000 : 500);
this.clock.ClockEnable('queue', (_todo == 0) || !_prioritize);
const _starttime = performance.now(); // max 50ms execution inside loop
while ((_todo-- > 0) && ((performance.now() - _starttime) < 50)){
const _oldstage = this.Stage;
this.Dequeue(this._pending.shift());
if (_oldstage != this.Stage){
break; // can change the max evaluation size
}
}
this.clock.ClockEnable('queue', true);
if ((this.Stage > 0) && (this._pending.length == 0)){
this.Stage = 9; // ensure that stage 9 is reached
}
// trigger block processed to continue with next block
if (this._pending.length > 0){
this._process_timeout = setTimeout(() => {
this._blockProcessed.next();
}, _prioritize ? 0 : 50);
}
else { // no more items, remove the subscription
if (this._onblock_subscription != null){
this._onblock_subscription.unsubscribe();
this._onblock_subscription = null;
}
}
}
/**
* Starts processing the queue if it's not already being processed.
*/
private ProcessQueue(){
if (this._process_timeout == null){
Iif (this._onblock_subscription != null){
this._onblock_subscription.unsubscribe();
this._onblock_subscription = null;
}
}
if (this._onblock_subscription == null){
this._onblock_subscription = this.OnBlockProcessed.subscribe(
() => {
this._ProcessQueue();
});
this._blockProcessed.next();
}
}
/*********************************/
/* PRIORITY HANDLING */
/*********************************/
/**
* Determines the priority of a given update based on its table and context.
* @param _update - The update to prioritize.
* @returns A numeric priority value.
*/
private _priority(_update: any){
// update synchronously
switch(_update['table']){
case 'SESSION':
Iif (this.state.session == _update['id']){
return 1.1;
}
break;
case 'FCM': return 1.2;
case 'USER': return 1.3;
case 'STAFF': return 1.4;
case 'PLACE':
if (!this.sync.place){
return 1.5;
}
break;
}
// instances without graphical component
switch(_update['table']){
case 'ADDRESS': return 2.1;
case 'STRIPE': return 2.1;
case 'RASPPI': return 2.1;
case 'PLACEOPT': return 2.2;
case 'PLACELINK': return 2.2;
case 'INVOICEBUSINESS': return 2.2;
case 'ACCOUNTINVOICE': return 2.3;
case 'PAYACCOUNT': return 2.4;
case 'CASHCHANGE': return 2.5;
case 'AUDITINFO': return 2.6;
case 'AUDITTILL': return 2.6;
case 'AUDIT': return 2.7;
}
// first order instances
switch(_update['table']){
case 'DRAWITEM':
return 3.1;
case 'PLACEAREA':
case 'RASPPICONNECT':
return 3.2;
case 'QRCODE':
case 'PRINTER':
case 'SCALE':
Iif (_update.status != 'DE'){
return 3.3;
}
break;
case 'OFFERPRODUCTOPT':
case 'DISCOUNTPRODUCT':
case 'EXTRAPRODUCTOPT':
case 'PRINTERPRODUCTOPT':
return 3.4;
case 'PRODUCTOPT':
case 'OFFERPRODUCT':
case 'OFFERPERIOD':
case 'DISCOUNTPERIOD':
case 'EXTRATABLE':
case 'EXTRAPRODUCT':
case 'EXTRAPERIOD':
case 'PRINTERPRODUCT':
return 3.5;
case 'CATEGORYDEP':
case 'PRESELECTOPT':
return 3.6;
case 'CATEGORY':
case 'PRESELECT':
return 3.7;
case 'PRODUCT':
case 'OFFER':
case 'EXTRA':
case 'DISCOUNT':
return 3.8;
}
// product families
switch(_update['table']){
case 'FAMILYPERIOD':
case 'FAMILYPRODUCT':
return 4.1;
case 'FAMILY':
return 4.2;
}
// active tickets & members
switch(_update['table']){
case 'TICKETOFFER':
case 'TICKETEXTRA':
return 5.1;
case 'TICKETOPTION':
case 'TICKETMIXEDPAY':
return 5.2;
case 'TICKETBAI':
case 'TICKETPRODUCT':
case 'TICKETDISCOUNT':
return 5.3;
case 'TICKETCHANGE':
case 'TICKETINVOICE':
case 'TICKETAUDIT':
return 5.4;
case 'SESSION':
return 5.5;
case 'TICKET':
return 5.6;
}
// waiter requests
switch(_update['table']){
case 'ASKWAITER':
Iif (_update['status'] == 'AC'){
return 5.9;
}
break;
}
// place information (this is a place update)
switch(_update['table']){
case 'QRCODE':
case 'PRINTER':
case 'SCALE':
return 6.1;
case 'PAYMENT': return 6.2;
case 'PLACE': return 6.3;
}
// items kept behind due to status
switch(_update['table']){
case 'QRCODE': return 8.1;
case 'TICKETOFFER': return 8.1;
case 'TICKETEXTRA': return 8.1;
case 'TICKETDISCOUNT': return 8.1;
case 'TICKETOPTION': return 8.2;
case 'TICKETMIXEDPAY': return 8.2;
case 'TICKETPRODUCT': return 8.3;
case 'TICKETBAI': return 8.3;
case 'TICKETAUDIT': return 8.3;
case 'ASKWAITER': return 8.4;
case 'TICKETINVOICE': return 8.4;
case 'TICKETCHANGE': return 8.4;
case 'SESSION': return 8.5;
case 'TICKET': return 8.6;
}
// other instance information
console.warn("WARNING: table '" + _update['table'] + "' not prioritized!");
return 9;
}
}
/**
* Manages a mapping of UUIDs to object IDs for tracking resolved synchronization items.
*
* This class provides a simple interface to store, retrieve, and delete mappings between
* unique identifiers (UUIDs) and their corresponding object IDs, ensuring consistency
* and avoiding reassignments.
*/
class ResolvedMap {
private _uuids_done = new Map <string, string> ();
/**
* Adds a new mapping between a UUID and an object ID.
* If the UUID is already mapped, an error is logged, and the mapping is not updated.
*
* @param _uuid - The unique identifier (UUID) to associate.
* @param objid - The object ID to associate with the UUID.
*/
Set(_uuid: string, objid: string): void{
const _objid = this._uuids_done.get(_uuid);
Iif (_objid && _objid != objid){
console.error("[SYNC] Trying to reasign an existing uuid: '" + _uuid + "'");
}
this._uuids_done.set(_uuid, objid);
}
/**
* Retrieves the object ID associated with a given UUID.
*
* @param _uuid - The UUID to look up.
* @returns The associated object ID, or `null` if the UUID is not found.
*/
Get(_uuid: string): string | null {
return this._uuids_done.get(_uuid) || null;
}
/**
* Removes a mapping for a given UUID if exists.
*
* @param _uuid - The UUID whose mapping should be removed.
*/
Del(_uuid: string){
Iif (this._uuids_done.has(_uuid)){
this._uuids_done.delete(_uuid);
}
}
}
interface SessionMeta {
deviceid: string,
sessionid: string,
timestamp: number
}
interface PlaceMeta {
placeid: string,
timestamp: number
}
/**
* Manages cached session and place data for synchronization.
*
* The `CacheManager` class facilitates the loading, saving, and maintaining of
* cached data for sessions and places. It ensures that synchronization operations
* can leverage locally stored data to reduce server load and improve performance.
*
* ### Responsibilities:
* - Manage `StorageDDBB` instances for session and place data.
* - Handle the lifecycle of cached data, including loading and saving.
* - Validate cached data to ensure freshness and relevance.
* - Integrate with the `PendingQueue` to enqueue cached changes for processing.
*/
class CacheManager {
private _databases = new Set <StorageDDBB> ();
private _sessn_database = "upp-stored-session";
private _place_database = "upp-stored-placeinfo-";
/**
* Creates a new instance of `CacheManager`.
*
* @param sync - The synchronization service instance that this manager interacts with.
*/
constructor(public sync: syncService){
// nothing to do
}
/**
* Cleans up all cached databases and releases associated resources.
*
* This method ensures that all open databases are closed and removed
* from the internal set of managed databases.
*/
OnDestroy(){
for (const _database of this._databases){
_database.Close();
}
this._databases.clear();
}
/**
* Provides access to the cache service.
*
* @returns The `cacheService` instance associated with the synchronization service.
*/
get cache(): cacheService {
return this.sync.cache;
}
/**
* Provides access to the pending queue for managing synchronization updates.
*
* @returns The `PendingQueue` instance from the `Syncronizator`.
*/
get pending(): PendingQueue {
return this.sync.synchonizer.pending;
}
/**
* Internal method to load session data from the specified database.
* Validates the session metadata and enqueues the data for synchronization.
* @param database - The storage backend to use.
* @param session - The session ID to load.
* @returns A promise resolving to `true` if the session data is valid, `false` otherwise.
*/
private async _LoadSession(database: StorageDDBB, session: string): Promise <boolean> {
Iif (!this.sync.device){
throw new Error("[CACHE] Session is not ready for recovery!")
}
const _metaitem = new StorageMeta(database);
const _metadata: SessionMeta | null = await _metaitem.Get();
if (!_metadata){
return false; // no stored data
}
if ((_metadata.deviceid != this.sync.device) || (_metadata.sessionid != session)){
return false; // not valid for this session
}
const _elapsed = (new Date().getTime()) - _metadata.timestamp;
Iif (_elapsed > AppConstants.CacheExpiration){
console.warn("[STORAGE] Stored data are outdated!");
return false;
}
// session data is valid: enqueue the items
const _sessiondata: Array <any> = await (new StorageData(database)).GetAll();
if (_sessiondata){
console.info("[CACHE] Recovered " + _sessiondata.length + " changes from session cache");
await this.pending.Concat(_sessiondata, false);
}
return true; // session data is valid and is loading
}
/**
* Loads session data from the cache and validates its freshness.
*
* If the cached data is valid, it is enqueued into the `PendingQueue` for processing.
*
* @param session - The session ID to load data for.
* @returns A promise resolving to `true` if the session data is successfully loaded and valid, `false` otherwise.
*/
async LoadSession(session: string): Promise <boolean> {
const _database: StorageDDBB = await this.cache.Open(this._sessn_database)
if (_database){
const _valid = await this._LoadSession(_database, session);
if (!_valid){
_database.Clean();
_database.Close();
}
else {
this._databases.add(_database);
}
return _valid;
}
return false; // could not open database
}
/**
* Internal method to save session data to the specified database.
* @param database - The storage backend to use.
* @param timestamp - The timestamp for the saved data.
* @param changes - The list of changes to save.
* @returns A promise resolving to `true` if the operation is successful, `false` otherwise.
*/
private async _SaveSession(database: StorageDDBB, timestamp: number, changes: Array <any>): Promise <boolean> {
Iif (!this.sync.device || !this.sync.session){
throw new Error("[CACHE] Session is not ready for storage!")
}
else {
console.info("[CACHE] Storing " + changes.length + " changes into session cache" )
}
const _metaitem = new StorageMeta(database);
const _metadata: SessionMeta = {
deviceid: this.sync.device,
sessionid: this.sync.session,
timestamp: timestamp || new Date().getTime()
}
if (await _metaitem.Set(_metadata)){
const _dataitem = new StorageData(database, (data) => { return data['table'] + '@' + data['objid'] });
database.Begin('DATA');
for (const _change of changes){
await _dataitem.Set(_change); // no lock as we are in transaction
}
return (await database.Flush('DATA'));
}
return false;
}
/**
* Saves session data to the cache.
*
* This method ensures that session metadata and changes are stored persistently,
* and the storage is committed in a transactional manner.
*
* @param changes - The list of changes to save.
* @returns A promise resolving to `true` if the operation is successful, `false` otherwise.
*/
async SaveSession(changes: Array <any>): Promise <boolean> {
const _database: StorageDDBB = await this.cache.Open(this._sessn_database)
if (_database){
this._databases.add(_database);
return await this._SaveSession(_database, this.sync.synchonizer.timestamp('SESSION'), changes);
}
return false; // could not open database
}
/**
* Internal method to load place data from the specified database.
* Validates the place metadata and enqueues the data for synchronization.
* @param database - The storage backend to use.
* @param placeid - The place ID to load.
* @returns A promise resolving to `true` if the place data is valid, `false` otherwise.
*/
private async _LoadPlace(database: StorageDDBB, placeid: string): Promise <boolean> {
const _metaitem = new StorageMeta(database);
const _metadata: PlaceMeta | null = await _metaitem.Get();
if (!_metadata){
return false; // no stored data
}
Iif (_metadata.placeid != placeid){
return false; // not valid for this place
}
const _elapsed = (new Date().getTime()) - _metadata.timestamp;
Iif (_elapsed > AppConstants.CacheExpiration){
console.warn("[STORAGE] Stored data are outdated!");
return false;
}
// place data is valid: enqueue the items
const _placedata: Array <any> = await (new StorageData(database)).GetAll();
if (_placedata){
console.info("[CACHE] Recovered " + _placedata.length + " changes from place [" + placeid + "] cache");
await this.pending.Concat(_placedata, false);
}
return true; // place data is valid and is loading
}
/**
* Loads place data from the cache and validates its freshness.
*
* If the cached data is valid, it is enqueued into the `PendingQueue` for processing.
*
* @param placeid - The place ID to load data for.
* @returns A promise resolving to `true` if the place data is successfully loaded and valid, `false` otherwise.
*/
async LoadPlace(placeid: string): Promise <boolean> {
const _database: StorageDDBB = await this.cache.Open(this._place_database + placeid);
if (_database){
const _valid = await this._LoadPlace(_database, placeid);
if (!_valid){
_database.Clean();
_database.Close();
}
else {
this._databases.add(_database);
}
return _valid;
}
return false; // could not open database
}
/**
* Internal method to save place data to the specified database.
* @param database - The storage backend to use.
* @param timestamp - The timestamp for the saved data.
* @param changes - The list of changes to save.
* @returns A promise resolving to `true` if the operation is successful, `false` otherwise.
*/
private async _SavePlace(database: StorageDDBB, timestamp: number, changes: Array <any>): Promise <boolean> {
Iif (!this.sync.place || !this.sync.place.objid){
throw new Error("[CACHE] Session is not ready for storage!")
}
else {
console.info("[CACHE] Storing " + changes.length + " changes into place [" + this.sync.place.objid + "] cache" )
}
const _metaitem = new StorageMeta(database);
const _metadata: PlaceMeta = {
placeid: this.sync.place.objid,
timestamp: timestamp || new Date().getTime()
}
if (await _metaitem.Set(_metadata)){
const _dataitem = new StorageData(database, (data) => { return data['table'] + '@' + data['objid'] });
database.Begin('DATA');
for (const _change of changes){
await _dataitem.Set(_change); // no lock as we are in transaction
}
return (await database.Flush('DATA'));
}
return false;
}
/**
* Saves place data to the cache.
*
* This method ensures that place metadata and changes are stored persistently,
* and the storage is committed in a transactional manner.
*
* @param placeid - The ID of the place to save data for.
* @param changes - The list of changes to save.
* @returns A promise resolving to `true` if the operation is successful, `false` otherwise.
*/
async SavePlace(placeid: string, changes: Array <any>): Promise <boolean>{
const _database: StorageDDBB = await this.cache.Open(this._place_database + placeid);
if (_database){
this._databases.add(_database);
return await this._SavePlace(_database, this.sync.synchonizer.timestamp('PLACE'), changes);
}
return false; // could not open database
}
}
/**
* Handles the synchronization of data between a client and a server.
*
* The `Syncronizator` class is responsible for managing changes, resolving dependencies,
* refreshing data, and persisting changes during synchronization sessions. It interacts
* with various services such as `Connection`, `PendingQueue`, and `ResolvedMap`.
*/
class Syncronizator {
private _doRefreshUrl = 'sync';
private _onrefresh = false; // set to true if refresh is ongoing
private _timestamp = new Map <LoadTarget, number> (); // timestamp of last succesfull refresh
private _reference = 0; // time reference from the server
private _syncchanges: CommitChange[] = [];
private _waitchanges: CommitChange[] = [];
private _sentchanges: CommitChange[] = [];
private _onRefreshCompleted = new Subject<void>();
/** Observable for refresh completion notifications. */
public OnRefreshCompleted = this._onRefreshCompleted.asObservable();
private _onCommitCompleted = new Subject <void> ();
/** Observable for commit completion notifications. */
public OnCommitCompleted = this._onCommitCompleted.asObservable();
private _onchange_subscription: Subscription | null = null;
private _onChange = new Subject<any>(); // change recovered from server
/** Observable for changes received from the server. */
public OnChange = this._onChange.asObservable();
/**
* Creates a new instance of the `Syncronizator`.
* @param sync - The synchronization service used by the `Syncronizator`.
*/
constructor(public sync: syncService){
// nothing to do
}
/**
* Cleans up resources when the `Syncronizator` is destroyed.
*/
OnDestroy(){
if (this._pending){
this._pending.OnDestroy();
this._pending = null;
}
if (this._cache){
this._cache.OnDestroy();
this._cache = null;
}
if (this._onchange_subscription){
this._onchange_subscription.unsubscribe();
this._onchange_subscription = null;
}
}
private _connection: Connection | null = null;
/**
* Gets the connection instance for managing server interactions.
*/
get connection(): Connection {
if (!this._connection){
this._connection = new Connection(this.sync);
}
return this._connection;
}
private _pending: PendingQueue | null = null;
/**
* Gets the pending queue instance for managing pending changes.
*/
get pending(): PendingQueue {
if (!this._pending){
this._pending = new PendingQueue(this.sync);
}
return this._pending;
}
private _resolved: ResolvedMap | null = null;
/**
* Gets the resolved map instance for managing resolved UUID mappings.
*/
get resolved(): ResolvedMap {
if (!this._resolved){
this._resolved = new ResolvedMap();
}
return this._resolved;
}
private _cache: CacheManager | null = null;
/**
* Gets the cache manager for previous data recovering.
*/
get cache(): CacheManager {
if (!this._cache){
this._cache = new CacheManager(this.sync);
}
return this._cache;
}
/**
* Gets the current connection status.
*/
get status(): ConnectionStatus {
return this.connection.status;
}
/**
* Sets the current connection status.
*/
set status(value: ConnectionStatus){
this.connection.status = value;
}
/**
* Provides access to the state service.
*/
get state(): stateService {
return this.sync.state;
}
/**
* Provides access to the ad-hoc service.
*/
get adhoc(): adhocService {
return this.sync.adhoc;
}
/**
* Provides access to the store service.
*/
get store(): storeService {
return this.sync.store;
}
/**
* Provides access to the language service.
*/
get lang(): languageService {
return this.sync.lang;
}
/**
* Provides access to the toast notification service.
*/
get toast(): toastService {
return this.sync.toast;
}
/**
* Provides access to the last server timestamp update
*/
timestamp(target: LoadTarget): number {
return this._timestamp.get(target) || 0;
}
/**
* Starts the synchronization process by loading pending changes and establishing a connection.
* @param session - The session ID for the connection.
* @returns A promise that resolves to `true` if the operation is successful, `false` otherwise.
*/
async Start(session: string | null) : Promise <boolean> {
this.state.session = session;
console.info("[SYNC] Searching for pending changes..");
const _changes = await this.GetStoredChanges();
if (_changes && _changes.length > 0){
console.warn("[SYNC] Found " + _changes.length + " changes from previous sessions");
this._waitchanges = _changes;
}
else {
console.info("[SYNC] No changes from previous sessions (up to date)");
}
this._onchange_subscription = this.pending.OnChange.subscribe(
(change) => {
this._onChange.next(change);
Iif (('_uuid' in change) && (change['_uuid'])){
this.resolved.Del(change['_uuid']);
}
});
// recover session data from the cache before querying the server
if (session){
try {
await this.cache.LoadSession(session);
}
catch(error: any){
console.error("[SYNC] Error recovering session information: Continuing without data..", error)
}
}
// create the server connection to be notified on updates
if (session){
return await this.connection.CreateConnection();
}
else {
return await this.connection.ReleaseConnection();
}
}
/**
* Stops the synchronization process and releases resources.
*/
async Stop(){
if (this.connection.status != 'STOPPED'){
await this.connection.ReleaseConnection();
if (this._onchange_subscription){
this._onchange_subscription.unsubscribe();
this._onchange_subscription = null;
}
this.state.place = null;
}
}
/***************************************/
/* ENTRY POINT */
/***************************************/
private _placeid: string | null = null;
private _tableid: string | null = null;
/**
* Updates the connection to associate a user.
* @param user - The user to associate, or `null` to remove the user.
* @returns A promise resolving to `true` if successful, `false` otherwise.
*/
async SetUser(user: User | null): Promise <boolean> {
const _success = await this.connection.SetUser(user);
if (_success){
this._timestamp.set('SESSION', 0);
this.pending.Reset();
}
return _success;
}
/**
* Updates the connection to associate a QR code.
* @param qrcode - The QR code to associate, or `null` to remove the QR code.
* @returns A promise resolving to `true` if successful, `false` otherwise.
*/
async SetQrCode(qrcode: QrCode | null): Promise <boolean> {
const _placeid = qrcode?.place?.objid ?? null;
const _success = await this.connection.SetQrCode(qrcode);
if (_success){
this._timestamp.set('QRCODE', 0);
this._tableid = qrcode?.objid || null;
this.state.place = _placeid;
this.pending.Reset();
}
return _success;
}
/**
* Updates the connection to associate a place.
* @param place - The place to associate, or `null` to remove the place.
* @returns A promise resolving to `true` if successful, `false` otherwise.
*/
async SetPlace(place: Place | null): Promise <boolean> {
const _placeid = place?.objid ?? null;
// recover place data from the cache before querying the server
if (place && place.objid){
try {
await this.cache.LoadPlace(place.objid);
}
catch(error: any){
console.error("[SYNC] Error recovering session information: Continuing without data..", error)
}
}
const _success = await this.connection.SetPlace(place);
if (_success){
this._timestamp.set('PLACE', 0);
this._placeid = _placeid;
this.state.place = _placeid;
this.pending.Reset();
}
return _success;
}
/*********************************/
/* PENDING CHANGES PERSISTANCE */
/*********************************/
private _storedsynckey = 'upp-stored-syncdata';
private _storedsyncavl = false; // avoid clearing if not set
/**
* Updates the connection to associate a place.
* @param place - The place to associate, or `null` to remove the place.
* @returns A promise resolving to `true` if successful, `false` otherwise.
*/
private async GetStoredChanges(): Promise <CommitChange[]> {
const _changes = await this.store.Get(this._storedsynckey) as CommitChange[];
if (_changes){
this._storedsyncavl = true; // changes available in storage
}
return _changes;
}
/**
* Saves changes to local storage.
* @param changes - The changes to store.
*/
private async SetStoredChanges(changes: CommitChange[]): Promise <void> {
if (changes.length > 0){
await this.store.Set(this._storedsynckey, changes);
this._storedsyncavl = true; // changes available in storage
}
}
/**
* Removes stored changes from local storage.
*/
private async DelStoredChanges(): Promise <void> {
if (this._storedsyncavl){
this._storedsyncavl = false; // removed changes form storage
await this.store.Del(this._storedsynckey);
}
}
/*********************************/
/* SERVER REFERENCED TIMING */
/*********************************/
private _serverreference = 0; // server elapsed time reference
private get serverreference(): number{
return Math.round((performance.now() - this._serverreference) / 1000);
}
private set serverreference(value: number){
this._serverreference = value;
}
/*********************************/
/* MAIN REFRESH METHODS (COMMIT) */
/*********************************/
/**
* Determines if one change depends on another.
*
* This method checks whether a given change (`a`) is directly or indirectly dependent
* on another change (`b`) based on their relations.
*
* @param a - The change to check for dependencies.
* @param b - The potential dependency.
* @returns `true` if `a` depends on `b`, otherwise `false`.
*/
private CheckDepends(a: CommitChange, b: CommitChange){
const _relation = b.relation;
for(const _dfield in a.requires){
// check if a is direct dependecy of b
const _requires = a.requires[_dfield].relation;
if ('_uuid' in _requires){
if ((_relation['table'] == _requires['table']) && (_relation['_uuid'] == _requires['_uuid'])){
return true; // a is direct dependency of b
}
}
// check if a is indirect dependency of b
const _indirect = a.requires[_dfield].requires;
for (const _ifield in _indirect){
Iif (this.CheckDepends(_indirect[_ifield], b)){
return true; // a is indirect dependency of b
}
}
}
return false; // a is not a dependency of b
}
/**
* Finds the index of a required relation in a map of changes.
*
* @param _require - The relation to search for.
* @param _changes - A map of change keys to their indices.
* @returns The index of the related change, or `-1` if not found.
*/
private RelatedIndex(_require: any, _changes: Map <string, number>){
const _chngekey = _require['table'] + '@' + _require['_uuid'];
Iif (!_require || !_require['table'] || !_require['_uuid']) {
console.error("[COMMIT ERROR]: Invalid _require object:", _require);
return -1; // invalid require data
}
const _position = _changes.get(_chngekey);
if (typeof _position !== 'undefined'){
return _position;
}
return -1; // relation not found
}
/**
* Validates the integrity of changes by checking dependencies and order.
*
* Ensures that changes are sorted in the correct order based on their dependencies
* and checks for missing or improperly ordered relations.
*
* @param changes - The list of changes to validate.
* @returns `true` if all changes are valid and correctly ordered, otherwise throws an error.
* @throws If a missing or misordered relation is detected.
*/
private CheckChanges(changes: CommitChange[]): boolean {
// sort the changes, based on dependencies (dependencies go first)
let _pvt = 0;
while(_pvt < changes.length){
let _hasDepends = false;
for(let _idx = _pvt+1; _idx < changes.length; _idx++){
_hasDepends = this.CheckDepends(changes[_pvt], changes[_idx]);
if (_hasDepends){
const _swap = changes[_idx];
changes[_idx] = changes[_pvt];
changes[_pvt] = _swap;
break; // dependecy found (swapped with current)
}
}
if (!_hasDepends){
_pvt++; // pivot has no dependencies, move to next
}
}
// build an index map for quick relation search
const _relationMap = new Map <string, number> ()
for (let _idx = 0; _idx < changes.length; _idx++){
const relation = changes[_idx].relation
const chngekey = relation['table'] + '@' + relation['_uuid'];
_relationMap.set(chngekey, _idx);
}
// check for missing relations
for(let _idx=0; _idx < changes.length; _idx++){
const _change = changes[_idx];
for(const _field in _change.requires){
const _require = _change.requires[_field].relation;
if (!('objid' in _require) || (!_require.objid)){
let _message: string | null = null
const _pos = this.RelatedIndex(_require, _relationMap);
if (_pos == -1){
_message = "@commit_error_relation_not_found";
}
Iif (_pos > _idx){
_message = "@commit_error_relation_bad_order";
}
if (_message){
const _error = {
missing: _change,
require: _require,
changes: changes.slice(0),
message: _message
};
console.error("[COMMIT ERROR]: ", JSON.stringify(_error));
throw(_error);
}
}
}
}
return true;
}
private _logcommits = false;
/**
* Commits a set of changes to the server, ensuring dependency order and integrity.
*
* This method consolidates changes, validates their dependencies, and sends them to the server
* for synchronization. It also handles ongoing refresh operations during the commit process.
*
* @param changes - The list of changes to commit.
* @param force - Whether to force the commit immediately.
* @returns A promise resolving to `true` if the operation succeeds, otherwise `false`.
*/
async FlushChanges(changes: CommitChange[], force = false) : Promise <boolean> {
const _targetlist: CommitChange[] = (this._onrefresh) ? this._waitchanges : this._syncchanges;
function _changeKey(change: any){
return change['relation']['table'] + '@' + (change['relation']['objid'] || change['relation']['_uuid']);
}
const _targetmap = new Map <string, CommitChange> ();
console.info("[COMMIT] commiting " + changes.length + " entries (now = " + force + ")");
if (changes.length == 0){
return true; // no changes to commit
}
for (const _target of _targetlist){
_targetmap.set(_changeKey(_target), _target);
}
// complete the target list with the incoming changes
for(const change of changes){
const _changekey: string= _changeKey(change);
Iif (this._logcommits){
console.info("[COMMIT] on table '" + change.entrynfo['table'] + "' (" + (this._onrefresh ? 'synchanges': 'waitchanges') + "):", change.entrynfo);
const _previous: CommitChange | undefined = _targetmap.get(_changekey);
Iif (_previous){
console.info("[COMMIT] remove previous '" + _previous.entrynfo['table'] + "':", change.entrynfo);
}
}
_targetmap.set(_changekey, change); // replace any previous changes over this object
}
// check the changes integrity and commit
const _tocommit: CommitChange[] = [..._targetmap.values()];
try{
if (this.CheckChanges(_tocommit)){
_targetlist.push(..._tocommit);
const _cancel = performance.now();
await this.CancelRefresh();
console.info("[COMMIT] Cancel ongoing completed in: " + (performance.now() - _cancel).toFixed(2) + " ms");
this.SetStoredChanges(_tocommit); // after the last refresh is done
if (force){
const _forced = performance.now();
await this.ForceRefresh();
console.info("[COMMIT] Forced commit completed in: " + (performance.now() - _forced).toFixed(2) + " ms");
}
};
return true;
}
catch(error: any){
this.toast.ShowAlert('danger', this.lang.tr(error.message));
}
return false;
}
/*********************************/
/* MAIN REFRESH METHODS (UPDATE) */
/*********************************/
/**
* Resolves changes in the synchronization list by adding server references and
* converting "insert" actions to "update" when applicable.
*/
private _resolve_syncchanges(): void {
const _serverreference = this._reference + this.serverreference; // adjust local interval to server time
for(const _change of this._syncchanges){
_change.reference = _serverreference;
if (_change.entrynfo['_actn'] == "do_insert"){
const _objid = this.resolved.Get(_change.entrynfo['_uuid']);
Iif (_objid){
_change.entrynfo['objid'] = _objid;
_change.entrynfo['_actn'] = "do_update";
}
}
}
}
private _lastchanges = 0; // reduce number of logs (only on size changed)
/**
* Prepares the current changes for synchronization by resolving dependencies
* and adjusting server references.
*
* This method moves the current set of changes to a sent list, ensuring
* that server-referenced values are updated before sending.
*
* @returns The number of changes prepared for synchronization.
*/
private _prepare_syncronize(): number {
if (this._lastchanges != this._syncchanges.length){
this._resolve_syncchanges(); // add server reference value to changes
if (this._syncchanges.length > 0){
console.info("[STORAGE]: Updating the changeset with " + this._syncchanges.length + " changes.");
}
this._lastchanges = this._syncchanges.length;
}
this._sentchanges = this._syncchanges;
this._syncchanges = [];
return this._sentchanges.length;
}
private _serverretries = 5; // retries for server errors
private _httperretries = 50; // retries for connection errors
/**
* Handles the successful completion of a synchronization operation.
*
* This method clears the list of sent changes and deletes stored changes from local storage.
*/
private _onsuccess_syncronize(updated: boolean){
if (updated){ // clear the changes stored in cache
this.DelStoredChanges();
this._sentchanges = [];
this._serverretries = 5;
this._httperretries = 50;
}
else { // try to resend on the next loop
this._syncchanges.push(...this._sentchanges);
this._sentchanges = [];
}
}
/**
* Handles the failure of a synchronization operation.
*
* This method restores sent changes back to the synchronization list
* and deletes stored changes to prevent inconsistencies.
*/
private _onfailure_synchronize(source: 'HTTPER' | 'SERVER'){
Iif ((this._syncchanges.length > 0) || (this._sentchanges.length > 0)){
let _cancelretries = false;
let _pndingretries = 0;
switch(source){
case 'HTTPER':
_pndingretries = this._httperretries;
break;
case 'SERVER':
_pndingretries = this._serverretries;
break;
}
console.warn("[SYNC] Cannot commit changes (pending retries " + _pndingretries + ")!")
Iif ((source == 'HTTPER') && (--this._httperretries == 0)){
_cancelretries = true;
}
Iif ((source == 'SERVER') && (--this._serverretries == 0)){
_cancelretries = true;
}
Iif (_cancelretries){
this._serverretries = 5;
this._httperretries = 50;
this.DelStoredChanges();
this._sentchanges = [];
this._syncchanges = [];
this.toast.ShowAlert('danger', this.lang.tr('@service_commit_failed'), 60000)
return; // this is a critical failure (probably code error on server side)
}
}
this._syncchanges.push(...this._sentchanges);
this._sentchanges = [];
}
/**
* Handles the failure of a synchronization operation.
*
* This method restores sent changes back to the synchronization list
* and deletes stored changes to prevent inconsistencies.
*/
private _prepare_request(): UpdateRequest {
const _access = this.state.Access;
if (!_access){
throw new Error("[SYNC] Access mode has not been initialized!")
}
let _target: LoadTarget | null = null;
if (!_target && this.sync.place){
_target = 'PLACE';
}
Iif (!_target && this.sync.qrcode){
_target = 'QRCODE';
}
if (!_target && this.sync.session && this.sync.device){
_target = 'SESSION';
}
Iif (!_target){
throw new Error("[SYNC] Cannot determine session target!")
}
const _getparams: any = {
access: _access,
timestamp: this.timestamp(_target),
target: _target,
}
Iif (this._tableid){
_getparams['table'] = this._tableid;
}
return _getparams;
}
/**
* Resolves dependencies within a single change by replacing UUID references with object IDs.
*
* @param _change - The change to resolve.
*/
private _resolve_change(_change: CommitChange){
if ('_uuid' in _change.relation){
const _objid = this.resolved.Get(_change.relation['_uuid']);
if (_objid){
_change.relation['objid'] = _objid;
}
}
for(const _requires in _change.requires){
this._resolve_change(_change.requires[_requires]);
}
}
/**
* Resolves server response updates by mapping UUIDs to object IDs and updating pending changes.
*
* This method processes the server response, resolving any pending changes based on
* their requirements and removing any that have been fully processed.
*
* @param response - The server response containing updates and metadata.
*/
private async _resolve_response(response: UpdateRespose){
const _updates = response.updates;
// remove volatile responses from server
for(let _idx = _updates.length - 1; _idx >= 0; _idx--){
const _update = _updates[_idx];
Iif (('_vltl' in _update) && (_update['_vltl'] == true)){
_updates.splice(_idx, 1);
}
}
// update the database cache entries
if (_updates.length > 0){
console.info("[SYNCHRONIZE] Updating [" + _updates.length + "] entries from server");
switch(response['target']){
case 'SESSION':
if ((this.sync.user) && (this.sync.user.objid)){
await this.cache.SaveSession(_updates);
}
break;
case 'QRCODE':
// nothing to do
break;
case 'PLACE':
if ((this.sync.place) && (this.sync.place.objid)){
await this.cache.SavePlace(this.sync.place.objid, _updates);
}
break;
}
}
// keep the resolved items in the _uuid list
for (const _update of _updates){
if (('_actn' in _update) && (_update['_actn'] == 'do_insert')){
this.resolved.Set(_update['_uuid'], _update['objid']);
}
}
// resolve any waiting change to the final value
for(const _change of this._waitchanges){
if ((_change.entrynfo['_actn'] == "do_insert")) {
Iif (!('_uuid' in _change.entrynfo)){
throw new Error("[SYNC] invalid change information in entry to insert (uuid is not provided)")
}
const _objid = this.resolved.Get(_change.entrynfo['_uuid']);
if (_objid){
_change.entrynfo['objid'] = _objid;
_change.entrynfo['_actn'] = "do_update";
}
}
// if requirements have been resolved, add resolved objid
this._resolve_change(_change);
// skip update if change is still pending
for(let _idx = _updates.length - 1; _idx >= 0; _idx--){
const _update = _updates[_idx];
if (_change.entrynfo['table'] == _update['table']){
let _skip = false;
if (('_uuid' in _change.entrynfo) && (_change.entrynfo['_uuid'] == _update['_uuid'])){
_skip = true; // found change by _uuid
}
if (('objid' in _change.entrynfo) && (_change.entrynfo['objid'] == _update['objid'])){
_skip = true; // found change by objid
}
if (_skip){
_updates.splice(_idx, 1);
}
}
}
}
}
/**
* Executes a data refresh, sending updates to the server and retrieving changes.
* @param reset - Whether to reset the state before refreshing.
* @param forced - Whether to force a refresh, bypassing normal conditions.
* @returns A promise resolving to `true` if successful, `false` otherwise.
*/
async DoRefresh(reset: boolean, forced: boolean): Promise <boolean> {
let _success = false;
const _connected = (this.connection.status == 'RUNNING');
Iif (this._onrefresh){
return false; // skip this refresh (one is ongoing)
}
if (!_connected){
console.info("[SYNC] Not connected: Skiping refresh operation");
// delay next refresh (1 secs) - wait for connection with server
await new Promise(resolve => setTimeout(resolve, 1000));
return false;
}
try {
let data: UpdateRespose | null = null;
this._onrefresh = true;
Iif (reset){
this.pending.Reset();
this._timestamp.set('SESSION', 0);
this._timestamp.set('PLACE', 0);
this._timestamp.set('QRCODE', 0);
}
const _commitsize = this._prepare_syncronize();
try {
data = await this.adhoc.DoRequest(this._doRefreshUrl, this._prepare_request(), this._sentchanges, false);
}
catch(error: any){
this._onfailure_synchronize('HTTPER');
Iif (error && error.status) {
console.error("[REQUEST] Error [" + error.status + "] in http request '" + this._doRefreshUrl + "'");
}
else {
console.error("[REQUEST] Generic error in http request '" + this._doRefreshUrl + "' (" + error + ")");
}
// delay next refresh (2 secs) - this is a communication error
await new Promise(resolve => setTimeout(resolve, 2000));
}
if (data){
this._onsuccess_syncronize(data['updated']);
_success = (data.errorcode == 0);
if (_success){
// notify that changes has been commited to server
if (_commitsize > 0){
console.info("[SYNCHRONIZE] Writing [" + _commitsize + "] entries to server");
this.OnRefreshCompleted.pipe(take(1)).subscribe(
() => {
this._onCommitCompleted.next();
});
}
// update the waitchanges array with the server entries
await this._resolve_response(data);
this._timestamp.set(data.target, data.timestamp);
this._reference = data.reference;
this.serverreference = performance.now();
if (this._pending){ // is destroyed??
this._pending.Concat(data['updates'], forced)
.catch((error) => {
console.error(error);
});;
}
Iif (data['expired']){
console.warn("[SERVICE] Client connection lost or expired: Reconnecting");
if (await this.connection.RefreshConnection()){
console.info("[SERVICE] Client connection succesfully restored");
}
else {
console.error("[SERVICE] Could not restore client connection. Refresh operations may fail!");
};
}
}
else {
if (!data.updated){
this._onfailure_synchronize('SERVER');
}
Iif (data.errorcode == 2){
this.sync.OnSessionExpired();
}
else {
console.error("[SERVICE] Error [" + data['errorcode'] + "] in '" + this._doRefreshUrl + "'");
this.toast.ShowAlert('danger', this.lang.tr('@service_request_error_' + data['errorcode']));
}
// delay next refresh (10 secs) - this is a server error
await new Promise(resolve => setTimeout(resolve, 10000));
}
}
// move the waitchanges to synchanges for the next refresh
if (this._waitchanges.length > 0){
this._syncchanges.push(...this._waitchanges);
this._waitchanges = [];
}
}
finally {
this._onrefresh = false;
this._onRefreshCompleted.next();
}
return _success;
}
/**
* Cancels an ongoing refresh operation.
*/
async CancelRefresh(): Promise <void> {
if (!this._onrefresh){
return; // no refresh in progress
}
const _cancelled = new Promise <void> ((resolve) => {
const _wait = performance.now();
this.OnRefreshCompleted.pipe(take(1)).subscribe(
() => {
console.info("[COMMIT] Ongoing refresh returned in " + (performance.now() - _wait).toFixed(2) + " ms.");
resolve();
});
this.connection.CancelRefresh();
})
await _cancelled;
}
/**
* Forces a refresh operation regardless of the current state.
*/
async ForceRefresh(): Promise <void> {
if (this._onrefresh){
await firstValueFrom(this.OnRefreshCompleted);
}
await this.DoRefresh(false, true);
}
/**
* Cancels the current refresh and resets the pending queue
*/
async ResetSynchronization(){
await this.CancelRefresh();
this.pending.Reset();
}
}
/**
* Provides synchronization services between the client and the server.
*
* The `syncService` class manages user sessions, device identification, and
* data synchronization using a `Syncronizator`. It also handles session expiration
* and provides observable streams for external components to react to changes.
*/
@Injectable({
providedIn: 'root'
})
export class syncService implements OnDestroy {
private _onReleased = new Subject <void> ();
/** Observable that emits when the session is fully released. */
OnReleased = this._onReleased.asObservable();
private _onExpired = new Subject <void> ();
/** Observable that emits when the session expires. */
public OnExpired = this._onExpired.asObservable();
private _isReady = new ReplaySubject<boolean>(1);
/** Observable that emits whenever the service is ready */
public IsReady = this._isReady.asObservable();
/**
* Creates a new instance of the synchronization service.
*
* @param lang - The language service for translations.
* @param store - The storage service for local persistence.
* @param cache - The cache service to avoid server complete reload
* @param adhoc - The ad-hoc request service for API calls.
* @param state - The state service for session and device data.
* @param clock - The clock service for scheduling tasks.
* @param toast - The toast notification service.
* @param platform - The platform service for device-specific operations.
* @param alertCtrl - The alert controller for displaying modals.
*/
constructor(public lang: languageService, public store: storeService, public cache: cacheService, public adhoc: adhocService, public state: stateService, public clock: clockService, public toast: toastService, private deviceid: identificationService, private alertCtrl: alertService){
this.deviceid.DeviceId().then(
(deviceid) => {
this.state.device = deviceid;
this._isReady.next(true);
this._isReady.complete();
});
}
/**
* Cleans up resources and stops the synchronizer when the service is destroyed.
*/
ngOnDestroy(){
if (this._syncronizer){
this._syncronizer.OnDestroy();
this._syncronizer = null;
}
}
/**
* Gets the current session identifier.
*/
get session(): string | null {
return this.state.session;
}
/**
* Gets the current device identifier.
*/
get device(): string | null {
return this.state.device;
}
private _syncronizer: Syncronizator | null = null;
/**
* Gets the synchronizer instance.
* The instance is lazily created if it does not already exist.
*/
get synchonizer(): Syncronizator {
if (!this._syncronizer){
this._syncronizer = new Syncronizator(this);
}
return this._syncronizer;
}
/**
* Exposes the `OnChange` observable from the synchronizer.
*/
get OnChange(): Observable <any> {
return this.synchonizer.OnChange;
}
/***************************************/
/* START/STOP SESSION */
/***************************************/
/**
* Starts the synchronization service.
*
* Initializes the device ID, sets up the synchronizer, and establishes a session.
*
* @param session - The session ID to start.
* @returns A promise resolving to `true` if the operation is successful, otherwise `false`.
* @throws If the device ID cannot be established.
*/
async Start(session: string | null) : Promise <boolean> {
if (this.state.device){
console.info("[SYNC] Device id is '" + this.state.device+ "'");
const _result = await this.synchonizer.Start(session);
Iif (!_result){
this.state.session = null;
}
return _result;
}
else {
throw new Error("[SYNC] Device id has not been set!");
}
}
/**
* Stops the synchronization service.
*
* Closes the connection, clears the session, and stops the synchronizer.
*/
async Stop() : Promise <void> {
console.info("[FINALIZE] Closing data service connection");
await this.synchonizer.Stop();
this._onReleased.next();
this.state.session = null;
console.info("[FINALIZE] Syncronization is stopped");
}
/***************************************/
/* ENTRY POINT */
/***************************************/
private _user: User | null = null;
/**
* Gets the currently associated user.
*/
get user() : User | null {
return this._user;
}
/**
* Updates the user associated with the synchronization service.
*
* @param user - The user to associate, or `null` to disassociate the user.
* @returns A promise resolving to `true` if the operation is successful, otherwise `false`.
*/
async SetUser(user: User | null): Promise <boolean> {
if (this._user == user){
return true; // no changes
}
const _result = await this.synchonizer.SetUser(user);
if (_result){
this._user = user;
}
return _result;
}
private _qrcode: QrCode | null = null;
/**
* Gets the currently associated QR code.
*/
get qrcode() : QrCode | null {
return this._qrcode;
}
/**
* Updates the QR code associated with the synchronization service.
*
* @param qrcode - The QR code to associate, or `null` to disassociate the QR code.
* @returns A promise resolving to `true` if the operation is successful, otherwise `false`.
*/
async SetQrCode(qrcode: QrCode | null): Promise <boolean> {
if (this._qrcode == qrcode){
return true; // no changes
}
const _result = await this.synchonizer.SetQrCode(qrcode);
if (_result){
this._qrcode = qrcode;
}
return _result;
}
private _place: Place | null = null;
/**
* Gets the currently associated place.
*/
get place() : Place | null {
return this._place;
}
/**
* Updates the place associated with the synchronization service.
*
* @param place - The place to associate, or `null` to disassociate the place.
* @returns A promise resolving to `true` if the operation is successful, otherwise `false`.
*/
async SetPlace(place: Place | null): Promise <boolean> {
if (this._place == place){
return true; // no changes
}
const _result = await this.synchonizer.SetPlace(place);
if (_result){
this._place = place;
}
return _result;
}
/***************************************/
/* SYNCHRONIZATION CONTROL */
/***************************************/
/**
* Resets the synchronization stage to its initial state.
*
* @returns A promise resolving when the reset is complete.
*/
async ResetStage(): Promise <void> {
await this.synchonizer.ResetSynchronization();
}
/**
* Flushes changes to the server.
*
* @param changes - The list of changes to flush.
* @param force - Whether to force the flush immediately.
* @returns A promise resolving to `true` if the operation is successful, otherwise `false`.
*/
async Flush(changes: CommitChange[], force = false) : Promise <boolean> {
return await this.synchonizer.FlushChanges(changes, force);
}
/*********************************/
/* EXPIRATION MODAL */
/*********************************/
private _expired_notified = false;
/**
* Handles the expiration of a user session.
*
* Stops the synchronizer, optionally notifies the user via a modal alert, and emits an expiration event.
* @param showModal - If true, shows the session-expired modal. Set to false when expiration happens
* during restore (e.g. stored login with expired session) so the user is not interrupted.
*/
async OnSessionExpired(showModal = true){
Iif (this._expired_notified){
return;
}
if (this.synchonizer.status != 'EXPIRED'){
this.synchonizer.status = 'EXPIRED';
this._expired_notified = true;
await this.synchonizer.Stop();
Iif (!showModal){
this._expired_notified = false;
this._onExpired.next();
return;
}
const alert = this.alertCtrl.alert({
header: this.lang.tr('@user_session_expired_title'),
message: this.lang.tr('@user_session_expired_message'),
backdropDismiss: true,
buttons: [{
text: this.lang.tr('@ok'),
handler: () => {
setTimeout(() => {
alert.dismiss(true);
}, 100);
return false;
}
}]
});
alert.onDidDismiss().then(
() => {
this._expired_notified = false;
this._onExpired.next();
});
await alert.present();
}
}
} |