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 | 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 43x 43x 43x 43x 43x 43x 43x 1x 1x 1x 1x 1x 1x 1x 1x 31x 31x 31x 31x 31x 1x 1x 7x 7x 7x 7x 6x 6x 7x 7x 7x 1x 1x 25x 25x 1x 1x 7x 7x 1x 1x 1x 1x 1x 1x 11x 11x 11x 11x 11x 11x 11x 11x 1x 1x 1x 1x 1x 1x 1x 43x 43x 43x 43x 42x 42x 42x 42x 42x 42x 41x 42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 41x 41x 41x 41x 41x 41x 41x 41x 40x 1x 1x 73x 73x 73x 72x 72x 73x 73x 1x 1x 82x 29x 29x 29x 29x 24x 2x 24x 22x 22x 24x 24x 8x 8x 29x 5x 5x 5x 82x 82x 82x 82x 82x 82x 82x 81x 1x 1x 1x 1x 1x 1x 1x 14x 14x 1x 1x 1x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 1x 1x 1x 1x 1x 1x 1x 1x 43x 43x 43x 43x 43x 43x 43x 43x 43x 7x 7x 7x 7x 7x 43x 43x 43x 1x 1x 1x 1x 1x 1x 1x 1x 1x 46x 46x 46x 46x 46x 46x 46x 46x 46x 46x 46x 46x 44x 44x 44x 44x 44x 44x 44x 44x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 44x 44x 44x 44x 6x 44x 44x 44x 44x 2x 2x 2x 2x 2x 2x 2x 2x 44x 44x 44x 44x 44x 44x 44x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 44x 44x 44x 7x 7x 7x 7x 5x 5x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 5x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 5x 44x 46x 46x 46x 46x 46x 46x 46x 46x 1x 1x 1x 1x 1x 1x 1x 1x 41x 41x 41x 41x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 4x 6x 6x 6x 6x 5x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 5x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 6x 6x 39x 39x 41x 41x 41x 41x 1x 1x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 7x 7x 3x 3x 3x 3x 3x 3x 3x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 9x 9x 9x 9x 9x 9x 9x 9x 9x 1x 1x 10x 10x 7x 7x 10x 10x 10x 10x 10x 10x 10x 10x 10x 1x 1x 42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 1x 1x 1x 1x 1x 1x 1x 10x 10x 10x 10x 18x 18x 18x 18x 10x 10x 10x 10x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 1x 1x 9x 9x 24x 24x 24x 24x 18x 18x 6x 24x 24x 24x 24x 24x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 9x 9x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 200x 200x 200x 200x 200x 200x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 200x 200x 200x 200x 3x 3x 3x 3x 3x 3x 3x 3x 3x 200x 200x 158x 158x 158x 158x 158x 200x 200x 200x 200x 200x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 200x 200x 200x 200x 200x 200x 200x 200x 200x 200x 200x 200x 200x 200x 200x 200x 200x 200x 200x 200x 200x 200x 200x 200x 200x 200x 200x 200x 200x 200x 200x 200x 200x 13x 13x 187x 187x 187x 187x 187x 187x 187x 187x 187x 187x 187x 187x 187x 187x 187x 187x 187x 187x 187x 187x 187x 187x 186x 186x 186x 187x 187x 187x 187x 187x 187x 187x 187x 187x 187x 187x 187x 187x 187x 187x 187x 187x 187x 187x 200x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 200x 1x 1x 186x 186x 186x 186x 186x 186x 186x 186x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 186x 186x 186x 186x 186x 186x 186x 186x 186x 186x 56x 56x 56x 56x 56x 56x 56x 56x 14x 14x 14x 14x 14x 56x 12x 12x 1x 1x 42x 30x 30x 2x 2x 30x 55x 56x 45x 45x 186x 186x 186x 186x 186x 186x 186x 186x 186x 186x 98x 98x 52x 52x 52x 28x 52x 2x 2x 52x 52x 52x 52x 52x 52x 52x 52x 52x 98x 40x 40x 40x 40x 40x 40x 40x 40x 40x 40x 40x 40x 40x 40x 40x 40x 40x 40x 40x 40x 40x 40x 40x 40x 40x 40x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 1x 1x 1x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 34x 34x 34x 34x 34x 34x 37x 37x 37x 37x 37x 37x 37x 40x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 40x 186x 186x 185x 1x 1x 1x 1x 6x 6x 6x 6x 6x 6x 6x 12x 6x 6x 1x 1x 45x 45x 45x 42x 42x 42x 42x 3x 3x 3x 3x 3x 1x 1x 89x 89x 89x 89x 89x 88x 88x 88x 88x 1x 1x 1x 1x 1x 1x 1x 39x 39x 39x 1x 1x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 30x 30x 30x 30x 2x 2x 2x 2x 2x 1x 1x 188x 179x 179x 9x 9x 9x 188x 9x 9x 188x 188x 188x 188x 1x 1x 1x 1x 41x 153x 153x 41x 41x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 35x 35x 1x 1x 1x 1x 1x 1x 10x 10x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 10x 10x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 6x 6x 6x 6x 6x 6x 6x 6x 6x 3x 3x 3x 3x 6x 1x 1x 2x 2x 2x 3x 2x 2x 2x 2x 2x 3x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 153x 153x 153x 153x 153x 41x 41x 112x 112x 112x 112x 112x 112x 112x 112x 112x 112x 112x 153x 1x 1x 1x 1x 111x 111x 1x 1x 1x 42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 153x 153x 153x 153x 153x 5x 6x 6x 5x 152x 152x 42x 41x 41x 1x 1x 1x 1x 1x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 3x 2x 2x 2x 3x 10x 10x 10x 10x 10x 10x 10x 10x 10x 1x 1x 46x 46x 46x 46x 46x 1x | import { flatten, keyBy, last, omit, union, uniq } from 'lodash-es';
import { type DataSource } from 'typeorm';
import { computedItemToErrorContext, FormulaParser, ItemsGenerators } from '@amalia/amalia-lang/formula/parsing';
import { type AmaliaFormula } from '@amalia/amalia-lang/formula/types';
import {
isQuota,
QUOTA_TYPES,
TokenType,
VariableType,
type Quota,
type Variable,
} from '@amalia/amalia-lang/tokens/types';
import { type Filter, type Plan, type Rule, type RuleAssignment } from '@amalia/core/models';
import { CalculationType, ConfigurationError, splitTeamScopeArgs, type EngineErrorContext } from '@amalia/core/types';
import { FormatsEnum } from '@amalia/data-capture/fields/types';
import { VirtualCustomObjects, type BaseCustomObjectDefinition } from '@amalia/data-capture/record-models/types';
import { assert, toError } from '@amalia/ext/typescript';
import { type AdminScope } from '@amalia/kernel/auth/types';
import { type StatementCalculationCache } from '@amalia/payout-calculation/compute-engine/core-statement-calculation-cache';
import {
ComputedItemTypes,
DatasetType,
type ComputedFunctionArgs_MATCH_USERS_ASSIGNED,
type ComputedFunctionArgs_SUM,
type ComputedFunctionResult,
type ComputedItem,
type ComputedRule,
type ComputedVariable,
type Dataset,
type FilterDataset,
type MetricsDataset,
type PlanTemplateDehydrated,
type PlanTemplateMetadata,
type PlanTemplateQueryContainerDehydrated,
type QuotaDataset,
} from '@amalia/payout-calculation/types';
import {
RelationshipJoinType,
RelationshipType,
RuleType,
type HoldAndReleaseSettings,
type PlanRuleFieldToDisplay,
type Relationship,
} from '@amalia/payout-definition/plans/types';
import { assertQuotaAllowedInCurrentPlan } from '@amalia/tenants/companies/admin-scopes/auth';
import { type TeamScope } from '@amalia/tenants/teams/types';
import { type PlanTemplateQueryContainer } from '../planTemplate.types';
import { FormulaReplacer } from '../queryContainers/condition/formulaReplacer/FormulaReplacer';
import { type QueryContainer } from '../queryContainers/condition/QueryContainer';
import { prepareQueryContainers } from '../queryContainers/queryBuilders';
const MAX_RECURSION_LEVEL = 2000;
const MAX_TURNS = 100;
type ParsingResultAbstract = {
datasetId?: string;
customObjectDefinition?: BaseCustomObjectDefinition;
};
type ParsingResultVariable = ParsingResultAbstract & {
computedItem: ComputedVariable;
isCurrency: boolean;
};
type ParsingResultDataset = ParsingResultAbstract & {
computedItem: FilterDataset;
};
type ComputedItemPostBuild = {
computedItem: ComputedVariable;
isCurrency: boolean;
datasetId?: string;
customObjectDefinition?: BaseCustomObjectDefinition;
};
/**
* Represents a plan template.
*/
export class PlanTemplate {
protected static readonly ROOT_RELATION_LEVEL = '';
public metadata: PlanTemplateMetadata;
protected readonly statementCalculationCache: StatementCalculationCache;
// =====> Plan template data
protected readonly datasets: Dataset[] = [];
protected computedItems: (ComputedRule | ComputedVariable)[] = [];
protected readonly allElements: (ComputedItem | Dataset)[] = [];
protected holdAndReleaseFields: HoldAndReleaseSettings = {};
protected scopesToFetch: TeamScope[] = [];
// =====> Helpers
public recursionLevel = 0;
protected parentsGraph: Record<string, string[]> | null = null;
protected directChildrenGraph: Record<string, string[]> = {};
protected readonly currencyItems: (ComputedRule | ComputedVariable)[] = [];
protected readonly queryContainers: PlanTemplateQueryContainer[] = [];
// =====> Definitions
// Plan, which contains rules, kpi config, categories, ...
protected readonly plan: Plan;
// Scopes where this plan appears.
protected readonly adminScopes: AdminScope[];
// Indexed by machineName
protected filterDefinitions: Record<Filter['machineName'], Filter> = {};
// Indexed by machineName
protected variableDefinitions: Record<Variable['machineName'], Variable> = {};
// Indexed by machineName.
protected customObjectDefinitions: Record<BaseCustomObjectDefinition['machineName'], BaseCustomObjectDefinition> = {};
// Indexed by machineName.
protected relationshipsDefinition: Record<Relationship['name'], Relationship> = {};
public constructor(plan: Plan, statementCalculationCache: StatementCalculationCache, adminScopes: AdminScope[]) {
this.metadata = {
generatedDate: new Date(),
};
this.plan = plan;
this.statementCalculationCache = statementCalculationCache;
this.adminScopes = adminScopes;
}
// ======================= GETTERS / SETTERS =======================
public getPlan() {
return this.plan;
}
public getCompany() {
return this.statementCalculationCache.company;
}
public getTemplate() {
return {
datasets: this.datasets,
computedItems: this.computedItems,
};
}
public addFilterDefinition(filter: Filter) {
this.filterDefinitions[filter.machineName] = filter;
// Saving the customObjectDefinition if it's the first time we see it.
if (filter.object && !(filter.object.machineName in this.customObjectDefinitions)) {
this.addCustomObjectDefinition(filter.object);
}
if (filter.virtualObjectMachineName && !(filter.virtualObjectMachineName in this.customObjectDefinitions)) {
const customObjectDefinitionOfDataset = this.statementCalculationCache
.getDefinitions()
.getCustomObjectDefinitionByMachineName(filter.virtualObjectMachineName);
assert(customObjectDefinitionOfDataset, `Custom definition not found for ${filter.virtualObjectMachineName}`);
this.addCustomObjectDefinition(customObjectDefinitionOfDataset);
}
}
public addVariableDefinition(variable: Variable) {
this.variableDefinitions[variable.machineName] = variable;
}
public addCustomObjectDefinition(customObject: BaseCustomObjectDefinition) {
this.customObjectDefinitions[customObject.machineName] = customObject;
}
/**
* Return all the definitions we've seen, it will be injected into the
* UserStatement at the start of the compilation and used as a cache.
*/
public getDefinitions() {
return {
plan: omit(this.plan, ['company']),
filters: this.filterDefinitions,
variables: this.variableDefinitions,
customObjects: this.customObjectDefinitions,
relationships: this.relationshipsDefinition,
};
}
// ======================= TEMPLATE BUILDING =======================
/**
* List all rules in the plan and start the computation of the template.
*/
public async build() {
assert(this.plan, 'Cannot call this plan template method out of a plan context');
// No parallel because we don't want concurrency issues.
for (const planRule of this.plan.planRules ?? []) {
const { rule } = planRule;
const computedRule = this.generateComputedRule(rule);
// Init the recursion by parsing the rule's formula (and so on and so on, it's recursive you got it).
await this.findDependenciesOfComputedItem(computedRule, null, null);
}
// After passing on each rule, we need to maintain a hashmap ruleMachineName -> computed rule id.
// This is helpful to retrieve parentIds in the next steps.
const ruleMachineNameToComputedRuleIdHashmap = this.buildRuleMachineNameToComputedRuleIdHashmap();
// Extract and find dependencies of computes items that are part of PLan Configuration
const extractedComputedItemsFromPlanWithCurrency = this.extractMoreComputedItemsFromPlan(
this.statementCalculationCache,
);
// Extract and find dependencies of computed items that are not part of formulas (split, kpis...)
const extractedVariablesWithCurrencyAndDatasetsFromRules = this.extractMoreComputedItemsFromRules(
this.statementCalculationCache,
ruleMachineNameToComputedRuleIdHashmap,
);
const extractedComputedItemsWithCurrency = [
...extractedComputedItemsFromPlanWithCurrency,
...extractedVariablesWithCurrencyAndDatasetsFromRules.variables,
...extractedVariablesWithCurrencyAndDatasetsFromRules.datasets,
...extractedVariablesWithCurrencyAndDatasetsFromRules.virtualDatasets,
];
// Ask to parse all computed items
await this.saveAndParseComputedItems(extractedComputedItemsWithCurrency);
// Do it again with things that should be built at the end (filter to display...)
const extractedComputedItemsWithCurrency2 = this.extractMoreComputedItemsFromRulesPostBuild(
this.statementCalculationCache,
ruleMachineNameToComputedRuleIdHashmap,
);
await this.saveAndParseComputedItems(extractedComputedItemsWithCurrency2);
}
protected buildRuleMachineNameToComputedRuleIdHashmap(): Record<string, string> {
return this.computedItems
.filter((ci) => ci.type === ComputedItemTypes.RULE)
.reduce<Record<string, string>>((acc, curr: ComputedRule) => {
acc[curr.ruleMachineName] = curr.id;
return acc;
}, {});
}
public async saveAndParseComputedItems(extractedComputedItems: (ParsingResultDataset | ParsingResultVariable)[]) {
extractedComputedItems.forEach((parsingResult) => {
const { computedItem, datasetId } = parsingResult;
// If it's a variable, save it (in dataset if object variable, otherwise globally)
if (computedItem.type === ComputedItemTypes.VARIABLE) {
if (datasetId) {
this.saveComputedItemInDataset(datasetId, computedItem);
} else {
this.saveGlobalComputedItem(computedItem);
}
if ((parsingResult as ParsingResultVariable).isCurrency) {
this.currencyItems.push(computedItem);
}
} else {
// Otherwise we need to save the dataset
this.saveDataset(computedItem);
}
});
await Promise.all(
extractedComputedItems.map(({ computedItem, datasetId, customObjectDefinition }) =>
this.findDependenciesOfComputedItem(computedItem, datasetId || null, customObjectDefinition || null),
),
);
}
/**
* When we encounter quotas, we make sure they're not scoped.
* @param quota
* @private
*/
public assertQuotaAllowedInCurrentPlan(quota: Quota) {
assertQuotaAllowedInCurrentPlan(this.plan, this.adminScopes, quota);
}
// Function to add a variable to compute to the list
public addVariableToCompute(
statementCalculationCache: StatementCalculationCache,
listWhereToPushVariable: ParsingResultVariable[],
variableId: string,
parentIds: string[],
ruleName?: string,
) {
const variableDefinition = statementCalculationCache.getDefinitions().getVariableById(variableId);
assert(variableDefinition, new ConfigurationError(`Cannot find variable to add to computation: ${variableId}`));
// If it's a quota, make sure it's not scoped.
if (isQuota(variableDefinition)) {
this.assertQuotaAllowedInCurrentPlan(variableDefinition);
}
// If it's a global variable, make sure there is not one existing with the same machine name that is
// locally scoped, to avoid any kind of PEBKAC.
if (!variableDefinition.planId) {
const variableDefinitionLocal = statementCalculationCache
.getDefinitions()
.getVariable(variableDefinition.machineName, this.plan);
if (variableDefinitionLocal && variableDefinition.id !== variableDefinitionLocal.id) {
throw new ConfigurationError(
`In rule ${ruleName}, the global variable "${variableDefinition.name}" is on display while there is a local one with the same machine name (${variableDefinition.machineName}), this can lead to unintended side effects.`,
{
tokenType: TokenType.RULE,
tokenId: variableDefinition.id,
tokenName: variableDefinition.name,
plan: this.plan.name,
},
);
}
}
// Only global variables (statements + quota) are allowed in this list. Make sure of that, or else it'll crash later.
if (variableDefinition.type === VariableType.object) {
throw new Error(
`Object variables ${variableDefinition.machineName} (${variableDefinition.id}) are not supported in this context. Make sure that kpisToDisplay, challenge variables, split variables, badges... are all referring to statement variables.`,
);
}
listWhereToPushVariable.push({
computedItem: ItemsGenerators.generateGlobalVariable(
variableDefinition.machineName,
variableDefinition.type,
parentIds,
),
isCurrency: variableDefinition.format === FormatsEnum.currency,
});
}
/**
* Based on plan configuration, add more computed items into the parsing.
*
* @param statementCalculationCache
* @returns
*/
public extractMoreComputedItemsFromPlan(
statementCalculationCache: StatementCalculationCache,
): ParsingResultVariable[] {
assert(this.plan, 'Cannot call this plan template method out of a plan context');
const computedItems: ParsingResultVariable[] = [];
(this.plan.badgeConfigurations ?? []).forEach((config) => {
if (config.variableId) {
this.addVariableToCompute(statementCalculationCache, computedItems, config.variableId, []);
}
});
(this.plan.highlightedKpis ?? []).forEach((kpi) => {
this.addVariableToCompute(statementCalculationCache, computedItems, kpi.variableId, []);
if (kpi.minimumVariableId) {
this.addVariableToCompute(statementCalculationCache, computedItems, kpi.minimumVariableId, []);
}
if (kpi.maximumVariableId) {
this.addVariableToCompute(statementCalculationCache, computedItems, kpi.maximumVariableId, []);
}
});
return computedItems;
}
/**
* Based on rule configurations, add more computed items into the parsing.
*
* @param statementCalculationCache
* @param ruleMachineNameToComputedRuleIdHashmap
* @returns all computed items extracted from rule configuration
*/
public extractMoreComputedItemsFromRules(
statementCalculationCache: StatementCalculationCache,
ruleMachineNameToComputedRuleIdHashmap: Record<string, string>,
): {
variables: ParsingResultVariable[];
datasets: ParsingResultDataset[];
virtualDatasets: ParsingResultDataset[];
} {
const resultVariables: ParsingResultVariable[] = [];
const resultsDatasets: ParsingResultDataset[] = [];
const resultVirtualDatasets: ParsingResultDataset[] = [];
(this.plan.planRules ?? []).forEach((planRule) => {
const { rule } = planRule;
// To be able to later link this element with the rule (in reports for instance),
// we mark the rule as a parent to anything created here.
const computedRuleId = ruleMachineNameToComputedRuleIdHashmap[rule.machineName];
const parentIds = computedRuleId ? [computedRuleId] : [];
// ====== Split variables ======
(rule.splitVariables ?? []).forEach((splitVariableId) => {
const splitVariable = statementCalculationCache.getDefinitions().getVariableById(splitVariableId);
assert(splitVariable, `Split variable not found: ${splitVariableId}`);
resultVariables.push({
computedItem: ItemsGenerators.generateGlobalVariable(
splitVariable.machineName,
VariableType.statement,
parentIds,
),
// Currency is always false: split variables are percent variables!
isCurrency: false,
});
});
// ====== Rule KPIs ======
(planRule.kpisToDisplay?.flatMap((section) => section.kpis) ?? []).forEach(({ id }) => {
this.addVariableToCompute(statementCalculationCache, resultVariables, id, parentIds, rule.name);
});
// ====== RULE main kpi overwrite variable ======
if (rule.type === RuleType.NON_PAYOUT && rule.configuration?.mainKpiVariableOverwrite) {
this.addVariableToCompute(
statementCalculationCache,
resultVariables,
rule.configuration.mainKpiVariableOverwrite,
parentIds,
rule.name,
);
}
// ===== RULE show/hide variable =====
if (rule.configuration?.showHideRuleVariableId) {
this.addVariableToCompute(
statementCalculationCache,
resultVariables,
rule.configuration.showHideRuleVariableId,
parentIds,
rule.name,
);
}
// ====== RULE challenge ======
// Ignore challenges with an incomplete configuration.
if (rule.type === RuleType.CHALLENGE && rule.configuration?.challengeComparisonVariableId) {
this.addVariableToCompute(
statementCalculationCache,
resultVariables,
rule.configuration.challengeComparisonVariableId,
parentIds,
rule.name,
);
if (rule.configuration.challengeConditionVariableId) {
this.addVariableToCompute(
statementCalculationCache,
resultVariables,
rule.configuration.challengeConditionVariableId,
parentIds,
rule.name,
);
}
if (rule.configuration.challengeHideConditionVariableId) {
this.addVariableToCompute(
statementCalculationCache,
resultVariables,
rule.configuration.challengeHideConditionVariableId,
parentIds,
rule.name,
);
}
}
// ===== RULE filters to display =====
(planRule.filtersToDisplay ?? []).forEach((filterToDisplay) => {
const filterDefinition = statementCalculationCache.getDefinitions().getFilterById(filterToDisplay.id);
// If the filter exists and is not already in the parsing, add it.
if (!!filterDefinition && !this.datasets.some((d) => d.filterMachineName === filterDefinition.machineName)) {
// Case where the filter is on custom objects.
if (filterDefinition.object) {
// We need to generate an item corresponding to the planRule's filter to display
const generatedItemFromDataset = ItemsGenerators.generateFilterDataset(
{
type: DatasetType.filter,
filterMachineName: filterDefinition.machineName,
customObjectDefinition: { machineName: filterDefinition.object.machineName },
},
parentIds,
) as FilterDataset;
resultsDatasets.push({
computedItem: generatedItemFromDataset,
datasetId: generatedItemFromDataset.id,
customObjectDefinition: filterDefinition.object,
});
} else {
// Handle special filters: metrics, quotas...
let generatedItemFromDataset: FilterDataset | undefined;
if (
[VirtualCustomObjects.OBJECT_METRIC, VirtualCustomObjects.STATEMENT_METRIC].includes(
filterDefinition.virtualObjectMachineName as VirtualCustomObjects,
)
) {
generatedItemFromDataset = ItemsGenerators.generateFilterDataset(
{
type: DatasetType.metrics,
filterMachineName: filterDefinition.machineName,
customObjectDefinition: { machineName: filterDefinition.virtualObjectMachineName! },
},
parentIds,
) as FilterDataset;
} else if (filterDefinition.virtualObjectMachineName === VirtualCustomObjects.QUOTA) {
// Filter is on a virtual object definition.
generatedItemFromDataset = ItemsGenerators.generateFilterDataset(
{
type: DatasetType.quota,
filterMachineName: filterDefinition.machineName,
customObjectDefinition: { machineName: filterDefinition.virtualObjectMachineName },
},
parentIds,
) as FilterDataset;
}
if (generatedItemFromDataset) {
resultVirtualDatasets.push({
computedItem: generatedItemFromDataset,
datasetId: generatedItemFromDataset.id,
customObjectDefinition: generatedItemFromDataset.customObjectDefinition as BaseCustomObjectDefinition,
});
}
}
}
});
});
return {
variables: resultVariables,
datasets: resultsDatasets,
virtualDatasets: resultVirtualDatasets,
};
}
/**
* Same than the method above, but evaluated at the very end of the PlanTemplate computation.
* @param statementCalculationCache
* @param ruleMachineNameToComputedRuleIdHashmap
* @returns all computed items extracted from rule configuration
*/
public extractMoreComputedItemsFromRulesPostBuild(
statementCalculationCache: StatementCalculationCache,
ruleMachineNameToComputedRuleIdHashmap: Record<string, string>,
): ComputedItemPostBuild[] {
const computedItems = (this.plan.planRules ?? []).map((planRule: RuleAssignment) => {
const errorContext: EngineErrorContext = {
tokenType: TokenType.RULE,
plan: this.plan.name,
};
const resultComputedItemsForThisRule: ComputedItemPostBuild[] = [];
// To be able to later link this element with the rule (in reports for instance),
// we mark the rule as a parent to anything created here.
const computedRuleId = ruleMachineNameToComputedRuleIdHashmap[planRule.rule.machineName];
const parentIds = computedRuleId ? [computedRuleId] : [];
// ====== Fields to display ======
// If we have a filter to display, we need to find the matching dataset.
// We also verify that the filter has an object, because for now it's not possible to put object variables
// on metrics so this part will crash on metrics.
(planRule.filtersToDisplay ?? []).forEach((filterToDisplay) => {
// Get filter definition using the id.
const filterDefinition = statementCalculationCache.getDefinitions().getFilterById(filterToDisplay.id);
// If the filter on display has been deleted since, stop here.
if (!filterDefinition) {
return;
}
// If it's a global filter, make sure there is not one existing with the same machine name that is
// locally scoped, to avoid any kind of PEBKAC.
if (!filterDefinition.planId) {
const filterDefinitionLocal = statementCalculationCache
.getDefinitions()
.getFilter(filterDefinition.machineName, this.plan);
if (filterDefinitionLocal && filterDefinition.id !== filterDefinitionLocal.id) {
throw new ConfigurationError(
`In rule ${planRule.rule.name}, the global filter "${filterDefinition.name}" is on display while there is a local one with the same machine name (${filterDefinition.machineName}), this can lead to unintended side effects.`,
{
...errorContext,
tokenId: filterDefinition.id,
tokenName: filterDefinition.name,
plan: this.plan.name,
},
);
}
}
if (filterDefinition.object) {
const { machineName: filterMachineName, object: customObjectDefinition } = filterDefinition;
const dataset = this.datasets.find((d) => d.filterMachineName === filterMachineName);
if (!dataset) {
throw new ConfigurationError(`In rule ${planRule.rule.name}, cannot find filter ${filterMachineName}.`, {
...errorContext,
tokenId: filterDefinition.id,
tokenName: filterDefinition.name,
});
}
const computedItemsOnRootLevelMachineName = new Set(
dataset.computedItems
.filter((ci) => ci.relationLevel === PlanTemplate.ROOT_RELATION_LEVEL)
.map((ci) => ci.variableMachineName),
);
filterToDisplay.fieldsToDisplay
// Remove fields from definition (they're not variables) except if the field comes from a relation.
// Fields to display are only on root level (product requirement), so we just need to check
// on the first level if there is not already a computed field with the same name
.filter(
(fieldToDisplay) =>
fieldToDisplay.relationId ||
(!customObjectDefinition.properties[fieldToDisplay.name] &&
!computedItemsOnRootLevelMachineName.has(fieldToDisplay.name)),
)
// And generate a computed item for each one of them.
.forEach((fieldToDisplay) => {
if (fieldToDisplay.relationId) {
const relationshipList = this.statementCalculationCache.getDefinitions().getRelationships();
const relationship = relationshipList.find(
(relationship) => relationship.id === fieldToDisplay.relationId,
);
assert(
relationship,
new ConfigurationError(
`In rule ${planRule.rule.name}, cannot display ${fieldToDisplay.name}: Relation not found`,
{
tokenMachineName: fieldToDisplay.name,
tokenType: TokenType.RULE,
tokenId: planRule.ruleId,
},
),
);
this.relationshipsDefinition[relationship.name] = relationship;
if (!dataset.relationMachineNames?.includes(relationship.name)) {
dataset.relationMachineNames = [...(dataset.relationMachineNames ?? []), relationship.name];
}
} else {
resultComputedItemsForThisRule.push(
this.generateFieldToDisplayComputedItems(
statementCalculationCache,
planRule,
filterDefinition,
customObjectDefinition,
parentIds,
dataset,
fieldToDisplay,
),
);
}
});
}
});
return resultComputedItemsForThisRule;
});
return flatten(computedItems);
}
protected generateFieldToDisplayComputedItems(
statementCalculationCache: StatementCalculationCache,
planRule: RuleAssignment,
filterDefinition: Filter,
customObjectDefinition: BaseCustomObjectDefinition,
parentIds: string[],
dataset: Dataset,
fieldToDisplay: PlanRuleFieldToDisplay,
): ComputedItemPostBuild {
const variablesDefinitions = statementCalculationCache.getDefinitions().getVariables();
const variableDefinition =
variablesDefinitions.find(
(v) =>
v.machineName === fieldToDisplay.name &&
v.objectId === filterDefinition.object!.id &&
v.planId === this.plan.id,
) ||
variablesDefinitions.find(
(v) => v.machineName === fieldToDisplay.name && v.objectId === filterDefinition.object!.id && !v.planId,
);
if (!variableDefinition) {
throw new ConfigurationError(
`In rule ${planRule.rule.name}, cannot display ${fieldToDisplay.name}: Variable not found`,
{
tokenType: TokenType.FILTER,
tokenId: filterDefinition.id,
tokenName: filterDefinition.name,
},
);
}
// Make a computed item and push it to the list.
return {
computedItem: ItemsGenerators.generateObjectVariable(
fieldToDisplay.name,
customObjectDefinition.machineName,
parentIds,
dataset.id,
// Fields to display are at the root of the dataset.
PlanTemplate.ROOT_RELATION_LEVEL,
),
isCurrency: variableDefinition.format === FormatsEnum.currency,
datasetId: dataset.id,
customObjectDefinition,
};
}
/**
* Extract a list of definitions from the planTemplate for the release service.
*/
public getForReleaseCondition() {
const dataset = this.datasets[0] as FilterDataset;
return {
dataset,
customObjectDefinition: this.customObjectDefinitions[dataset.customObjectDefinition.machineName],
// See the method above to get how they were extracted.
holdAndReleaseFields: this.holdAndReleaseFields,
};
}
/**
* If one day we store the computed plan template in database, we have some post-operations to run
* after fetching it, like building reference hashmaps, adding definitions... that would not make sense
* to store in db.
*/
public async postBuild() {
this.buildDefinitions();
this.buildParentsGraph();
this.buildCurrencyFrom();
this.buildDataToDisplay();
// Verify computability.
await this.traversePlan();
}
public getIndexedPlanWeight(): number {
// Get the list of dataset using statements or object metrics.
const metricsDatasets = this.datasets.filter((d) =>
[VirtualCustomObjects.OBJECT_METRIC, VirtualCustomObjects.STATEMENT_METRIC].includes(
d.customObjectDefinition.machineName as VirtualCustomObjects,
),
);
// We consider that the plan is a manager plan if it contains at least one filter metric using managees.
const isManager = metricsDatasets.some((d) => {
const filterCondition =
d.filterMachineName in this.filterDefinitions && this.filterDefinitions[d.filterMachineName].condition;
const condition = d.type === DatasetType.filter && d.overrideCondition ? d.overrideCondition : filterCondition;
if (!condition) {
return false;
}
return (
condition.includes('user.teamMembers') ||
condition.includes('team.employees') ||
condition.includes('team.managers') ||
this.getScopesToFetch().length
);
});
return isManager ? 100 : 0;
}
protected generateComputedRule(rule: Rule): ComputedRule {
// Build an empty ComputedRule for the current rule.
const computedRule = ItemsGenerators.generateComputedRule(rule);
// Add it to the list.
this.saveGlobalComputedItem(computedRule);
// A rule is monetary, so we need to evaluate its currency.
this.currencyItems.push(computedRule);
return computedRule;
}
/**
* Fetch all definitions needed for the evaluation.
*
* TODO: we can do better than parsing the whole template again just to extract this (probably on designer v3).
*/
public buildDefinitions() {
// Fetch all variables.
this.computedItems
.filter((computedItem) => computedItem.type === ComputedItemTypes.VARIABLE)
.forEach((computedItem) => {
const variableDefinition = this.statementCalculationCache
.getDefinitions()
.getVariable(computedItem.variableMachineName, this.plan);
this.addVariableDefinition(variableDefinition as Variable);
});
// Fetch all filters and customObjectDefinitions.
this.datasets.forEach((dataset) => {
const filterDefinition = this.statementCalculationCache
.getDefinitions()
.getFilter(dataset.filterMachineName, this.plan);
if (filterDefinition) {
this.addFilterDefinition(filterDefinition);
}
// Fetch variables of computedItems in dataset.
dataset.computedItems.forEach((computedItem) => {
const variableDefinition = this.statementCalculationCache
.getDefinitions()
.getVariable(computedItem.variableMachineName, this.plan);
this.addVariableDefinition(variableDefinition as Variable);
});
});
const allRelationsInThisPlanMachineNames = uniq(
this.datasets.flatMap((d) => (d.relationMachineNames ?? []).flatMap((r) => r.split('.'))),
);
const allRelationsInThisPlan = this.statementCalculationCache
.getDefinitions()
.getRelationships()
.filter((r) => allRelationsInThisPlanMachineNames.includes(r.name));
this.relationshipsDefinition = keyBy(allRelationsInThisPlan, 'name');
allRelationsInThisPlan.forEach((r) => {
if (r.type === RelationshipType.ARRAY && r.joinType === RelationshipJoinType.INNER) {
throw new ConfigurationError(
'Due to a technical limitation, inner joins are not available in 1->n relations.',
{ tokenMachineName: r.name, tokenName: r.label, tokenType: TokenType.LINK, tokenId: r.id },
);
}
if (!(r.toDefinitionMachineName in this.customObjectDefinitions)) {
const toDefinition = this.statementCalculationCache
.getDefinitions()
.getCustomObjectDefinitionByMachineName(r.toDefinitionMachineName);
assert(toDefinition, `ToDefinition missing for ${r.toDefinitionMachineName}`);
this.customObjectDefinitions[r.toDefinitionMachineName] = toDefinition;
}
});
}
public buildDataToDisplay() {
// DatasetToDisplay
this.computedItems = this.computedItems.map((ciRule) => {
assert(this.plan, 'Cannot call this plan template method out of a plan context');
// If item is not a rule, return it
if (ciRule.type !== ComputedItemTypes.RULE) {
return ciRule;
}
const ruleDefinition = (this.plan.planRules ?? []).find(
(planRule) => planRule.rule.machineName === ciRule.ruleMachineName,
);
if (ruleDefinition) {
// If the admin provided a list of filters to display, use it.
if (ruleDefinition.filtersToDisplay) {
return {
...ciRule,
datasetToDisplayIds: this.getRuleDatasetsToDisplayIds(ruleDefinition),
};
}
// If the rule is on a filter, use the dataset of the filter.
if (ruleDefinition.rule.filter?.machineName) {
const datasetFromFilter = this.datasets.find(
(dataset) =>
dataset.type === DatasetType.filter &&
dataset.filterMachineName === ruleDefinition.rule.filter!.machineName,
);
if (datasetFromFilter) {
return {
...ciRule,
datasetToDisplayIds: [datasetFromFilter.id],
};
}
}
// If the rule doesn't have a filter, try to find the closest computed SUM and use its filter.
const computedSumsFiltersMachineNames = new Set(
this.computedItems
// All computed ids that are children of the current rule, including the rule itself
// because the SUM can be in the formula of the rule directly.
.filter((ciSum) => ciSum.parentIds.includes(ciRule.id) || ciSum.id === ciRule.id)
.flatMap((ciSum: ComputedItem) => ciSum.evaluations ?? [])
.filter((ev) => ev.function === 'SUM')
.map((sum) => (sum.args as ComputedFunctionArgs_SUM).array),
);
const datasetOnDisplay = (this.datasets as FilterDataset[]).find(
(dataset) =>
!!dataset.filterMachineName && computedSumsFiltersMachineNames.has(`filter.${dataset.filterMachineName}`),
)?.id;
// Find a filterDataset that matches.
return {
...ciRule,
datasetToDisplayIds: datasetOnDisplay ? [datasetOnDisplay] : null,
};
}
// We haven't found an appropriate dataset => return the object as it
return ciRule;
});
}
/**
* Get datasets to display Ids setup from rule configuration.
* @param ruleAssignment
* @private
*/
protected getRuleDatasetsToDisplayIds(ruleAssignment: RuleAssignment): string[] {
assert(this.plan, 'Cannot call this plan template method out of a plan context');
const filtersToDisplay =
this.statementCalculationCache.calculation?.type === CalculationType.FORECAST
? this.plan.forecast?.objectsToDisplay![ruleAssignment.ruleId]?.filtersToDisplay
: ruleAssignment.filtersToDisplay;
return (filtersToDisplay ?? [])
.map((filterToDisplay) => {
const filterDefinition = Object.values(this.filterDefinitions).find(
(filter) => filterToDisplay.id === filter.id,
);
if (!filterDefinition) {
return null;
}
const foundDataset = (this.datasets as FilterDataset[]).find(
(d) =>
[DatasetType.filter, DatasetType.metrics].includes(d.type) &&
d.filterMachineName === filterDefinition.machineName,
);
return foundDataset ? foundDataset.id : null;
})
.filter(Boolean);
}
/**
* Given a computed item, returns the list of all formulas we have to parse.
* @param computedItem
* @private
*/
protected async extractAllFormulasForCurrentItem(
computedItem: ComputedItem | FilterDataset | MetricsDataset | QuotaDataset,
): Promise<AmaliaFormula[]> {
const formulas: AmaliaFormula[] = [];
switch (computedItem.type) {
case DatasetType.filter: {
// In case of a filter, eventually rewrite its condition if it contains object variables.
const { newCondition, changed } = await FormulaReplacer.replaceObjectVariablesInFilterCondition(
this.statementCalculationCache,
computedItem.filterMachineName,
this.plan,
);
if (changed) {
this.saveOverrideConditionInDataset(computedItem.id, newCondition);
}
formulas.push(newCondition);
break;
}
// Not rewriting the condition of metrics filter because they don't contain fields (for now :/).
case DatasetType.quota:
case DatasetType.metrics: {
const filterDefinition = this.statementCalculationCache
.getDefinitions()
.getFilter(computedItem.filterMachineName, this.plan);
// Metrics filter in library don't have a condition.
if (filterDefinition) {
formulas.push(filterDefinition.condition);
}
break;
}
default:
// Add the formula of the item.
formulas.push(
...this.statementCalculationCache.getFormulaParser().getFormulasOfComputedItem(computedItem, this.plan),
);
break;
}
// Remove null and undefined values.
return formulas.filter(Boolean);
}
/**
* Given a computation item, parse its formula and list its dependencies.
*
* RECURSIVE!!
*
* @param computedItem
* @param parentDatasetId
* @param currentObjectDefinition
* @param relationLevel
*/
protected async findDependenciesOfComputedItem(
computedItem: ComputedItem | FilterDataset,
parentDatasetId: string | null,
currentObjectDefinition: BaseCustomObjectDefinition | null | undefined,
relationLevel: string = PlanTemplate.ROOT_RELATION_LEVEL,
) {
// Just in case...
if (this.recursionLevel++ > (this.plan.maxRecursionLevel || MAX_RECURSION_LEVEL)) {
const errorDetails = `Details (can help but not 100% accurate, it's when we intercepted the fact it's too big): Computing ${
computedItem.type
} / ${computedItem.id} ${parentDatasetId ? ` / dataset: ${parentDatasetId}` : ''} ${
currentObjectDefinition ? ` / definition: ${currentObjectDefinition.id}` : ''
}`;
throw new ConfigurationError(
`Too many levels (${
this.plan.maxRecursionLevel || MAX_RECURSION_LEVEL
}) in the build of the template. Is your plan ${this.plan.name || 'release'} recursive? Details: ${errorDetails}`,
);
}
// Grab the formula of the ComputedItem in order to parse its dependencies.
let formulas: AmaliaFormula[] = [];
// All children of this ComputedItem will have for parents the computed
// item itself and all its parents.
const parentIdsOfChildren = computedItem.parentIds.concat(computedItem.id);
let computedItems: ComputedItem[];
let datasets: PlanTemplate['datasets'];
let relationshipLevelsFound: string[];
const errorContext = computedItemToErrorContext(computedItem, {
tokenTraces: parentIdsOfChildren,
plan: this.plan.name,
});
// We designed the PlanTemplate algorithm, so it detects error early in the process, however that
// means that it can throw pretty much from anywhere. Let's wrap the parsing / evaluations part in
// a try / catch, so it can give more infos on where the error happened.
try {
// For the current computed item, get all the formulas we need for parsing.
formulas = await this.extractAllFormulasForCurrentItem(computedItem);
// The item has no formula (a quota for instance), we can stop here.
if (!formulas.length) {
return;
}
// This step returns all the ComputedItem we find in the formula.
// It's not recursive, it just returns what it finds by reading the formula as-is.
const allParsings = formulas.map((formula) =>
this.statementCalculationCache.getFormulaParser().extractNodes({
context: errorContext,
formula,
parentIds: parentIdsOfChildren,
parentDatasetId,
currentObjectDefinition,
relationLevel,
plan: this.plan,
}),
);
// Merge all parsings to get the list of all dependencies of current computed item.
const parsingResult = allParsings.reduce<{
computedItems: ComputedItem[];
datasets: PlanTemplate['datasets'];
relationshipLevelsFound: string[];
}>(
(acc, curr) => ({
computedItems: acc.computedItems.concat(curr.computedItems),
datasets: acc.datasets.concat(curr.datasets),
relationshipLevelsFound: acc.relationshipLevelsFound.concat(curr.relationshipLevelsFound),
}),
{
computedItems: [],
datasets: [],
relationshipLevelsFound: [],
},
);
computedItems = parsingResult.computedItems;
datasets = parsingResult.datasets;
relationshipLevelsFound = parsingResult.relationshipLevelsFound;
// All we found during this parsing is considered as direct children of current element.
this.directChildrenGraph[computedItem.id] = [...datasets, ...computedItems].map((item) => item.id);
// If we find functions to evaluate in the current computed item, add it to its item.
computedItem.evaluations = computedItems.filter((ci) => ci.type === ComputedItemTypes.FUNCTION_RESULT);
// Also if those computed functions rely on scope, add it to the things to load before calculation.
if (computedItem.evaluations.some((e) => e.function === 'MATCH_USERS_ASSIGNED')) {
computedItem.evaluations
.filter((e) => e.function === 'MATCH_USERS_ASSIGNED')
.forEach((e) => {
const { scope } = e.args as ComputedFunctionArgs_MATCH_USERS_ASSIGNED;
// With Team Hierarchy, now scope is in 3 different parts, Role, Scope of the role, Depth on the hierarchy (if 0, no depth limit)
const teamScope = splitTeamScopeArgs(scope);
const newScopesToFetch: TeamScope[] = [...this.scopesToFetch];
const indexScopeAlreadyToFetch = newScopesToFetch.findIndex(
(s) => s.role === teamScope.role && s.scope === teamScope.scope,
);
// Avoid duplicatas via checking if the scope is already in list
// and if teamScope depth is lower than the actual scope to fetch
if (indexScopeAlreadyToFetch === -1) {
newScopesToFetch.push(teamScope);
} else {
const actualDepth = newScopesToFetch[indexScopeAlreadyToFetch].depth;
// here we need to update the maxDepth of this keyword
if (actualDepth < teamScope.depth) {
newScopesToFetch.splice(indexScopeAlreadyToFetch, 1, teamScope);
}
}
this.scopesToFetch = newScopesToFetch;
});
}
} catch (e) {
throw new ConfigurationError(toError(e), errorContext);
}
// The catch block stops here, because after that it's recursive, so we're gonna rethrow on each level
// which is not a good idea. Functions that are throwing ConfigurationError after that should specify the
// context themselves.
// Add datasets that were found in the formula to the template.
await Promise.all(
datasets.map(async (d) => {
this.saveDataset(d);
// Filter can have dependencies (quota variables, object variable that rewrite the condition, ...).
// So it means that we have to fetch their dependencies as well.
const customObjectDefinitionOfDataset = this.statementCalculationCache
.getDefinitions()
.getCustomObjectDefinitionByMachineName(d.customObjectDefinition.machineName);
assert(customObjectDefinitionOfDataset, `Cannot find custom object definition for dataset ${d.id}`);
await this.findDependenciesOfComputedItem(d as FilterDataset, d.id, customObjectDefinitionOfDataset);
}),
);
// Build a list of existing items, so we don't parse them twice.
const existingItems: string[] = [];
// Dispatch the computed items in global and in dataset.
computedItems
.filter((ci) => ci.type === ComputedItemTypes.VARIABLE)
.forEach((ci) => {
// Fetch definition.
const definition = this.statementCalculationCache
.getDefinitions()
.getVariable(ci.variableMachineName, this.plan);
assert(definition, `Definition of variable ${ci.variableMachineName} not found`);
if (QUOTA_TYPES.includes(ci.variableType)) {
// Check the quota is usable in this plan.
assert(isQuota(definition));
this.assertQuotaAllowedInCurrentPlan(definition);
if (!this.saveGlobalComputedItem(ci)) {
existingItems.push(ci.id);
}
} else if (ci.variableType === VariableType.statement) {
// Put global variables into the global list of computed items.
if (!this.saveGlobalComputedItem(ci)) {
existingItems.push(ci.id);
}
} else if (ci.variableType === VariableType.object) {
// Objects variables should be put in the dataset of the object.
if (!this.saveComputedItemInDataset(parentDatasetId, ci)) {
existingItems.push(ci.id);
}
} else {
throw new ConfigurationError(`Unknown variable type: ${ci.variableType}`);
}
if (definition.format === FormatsEnum.currency) {
this.currencyItems.push(ci);
}
});
// Register the relation in the dataset, so they'll be fetched together.
this.addRelationsToFetchInDataset(parentDatasetId, relationshipLevelsFound);
// Looping on new computedItems to find their children. This is when the recursion begins!
await Promise.all(
computedItems
.filter((ci) => !existingItems.includes(ci.id))
.map(async (childComputedItem: ComputedItem) => {
// For variable, it's easy, call it back again.
if (childComputedItem.type === ComputedItemTypes.VARIABLE) {
// If the computed object is on another custom object (it means we're in a relation), use this customObject instead.
const nextCustomObjectDefinition =
childComputedItem.customObjectMachineName &&
childComputedItem.customObjectMachineName !== currentObjectDefinition?.machineName
? this.statementCalculationCache
.getDefinitions()
.getCustomObjectDefinitionByMachineName(childComputedItem.customObjectMachineName)
: currentObjectDefinition;
await this.findDependenciesOfComputedItem(
childComputedItem,
parentDatasetId,
nextCustomObjectDefinition,
// Go down one relation if this computedItem had one.
childComputedItem.relationLevel || relationLevel,
);
} else if (PlanTemplate.isComputedFunctionResult(childComputedItem)) {
// For functions that we stripped down some arguments.
// TODO: refactor needed -- this part should be more generic (each function should be able to have its own logic).
// Will refactor when we have list the specificity of each one of them.
const args = childComputedItem.args as ComputedFunctionArgs_SUM;
// Parse the first parameter to see what we're summing on.
const { datasets: childDatasets, relationshipLevelsFound: relationshipLevelsFoundInDataset } =
this.statementCalculationCache.getFormulaParser().extractNodes({
context: errorContext,
formula: args.array,
parentIds: parentIdsOfChildren,
parentDatasetId,
currentObjectDefinition,
relationLevel,
plan: this.plan,
});
assert(
childDatasets.length + relationshipLevelsFoundInDataset.length,
new ConfigurationError(`${childComputedItem.function} array does not have a custom object definition`, {
...errorContext,
tokenTraces: childComputedItem.parentIds,
}),
);
if (childDatasets.length) {
const [childDataset] = childDatasets;
const customObjectDefinitionOfDataset = this.statementCalculationCache
.getDefinitions()
.getCustomObjectDefinitionByMachineName(childDataset.customObjectDefinition.machineName);
assert(
customObjectDefinitionOfDataset,
`customObjectDefinitionOfDataset not found for ${childDataset.id}`,
);
if ([DatasetType.metrics, DatasetType.quota].includes(childDataset.type)) {
// Add the virtual custom object definition into the list.
this.addCustomObjectDefinition(customObjectDefinitionOfDataset);
}
args.customObject = customObjectDefinitionOfDataset.machineName;
// First argument was escaped during parsing of the SUM, now is the good time
// to parse it and find its dependencies.
// TODO: check if it's still useful to escape the first parameter, eventually remove this since it'll be already save.
const isNewDataset = this.saveDataset(childDataset);
// Find filter dependencies.
if (isNewDataset) {
await this.findDependenciesOfComputedItem(
childDataset as FilterDataset,
childDataset.id,
customObjectDefinitionOfDataset,
);
}
// And now evaluate the second part of the formula in the context of this new dataset.
await this.findDependenciesOfComputedItem(
childComputedItem,
childDataset.id,
customObjectDefinitionOfDataset,
);
} else {
// Register the relation into the dataset and update the level.
this.addRelationsToFetchInDataset(parentDatasetId, relationshipLevelsFoundInDataset);
const newRelationLevel = FormulaParser.joinRelations(
relationLevel,
last(relationshipLevelsFoundInDataset) as string,
);
// We need to get the definition of the deepest relation level.
// If it's [a, a.b, a.b.c] we need just c.
const relationToFetch = last((last(relationshipLevelsFoundInDataset) as string).split('.'));
const relation = this.statementCalculationCache.getDefinitions().getRelationshipFromName(relationToFetch);
assert(relation, `In plan template, relation ${relationToFetch} not found`);
// It allows us to get the custom object definition of what we're descending in.
const customObjectDefinitionOfRelation = this.statementCalculationCache
.getDefinitions()
.getCustomObjectDefinitionByMachineName(relation.toDefinitionMachineName);
assert(
customObjectDefinitionOfRelation,
`In plan template, customObjectDefinitionOfRelation ${relation.toDefinitionMachineName} not found`,
);
args.customObject = customObjectDefinitionOfRelation.machineName;
// And now evaluate the second part of the formula in the context of this relation but staying in the same dataset.
await this.findDependenciesOfComputedItem(
childComputedItem,
parentDatasetId,
customObjectDefinitionOfRelation,
newRelationLevel,
);
}
}
}),
);
}
public hits = 0;
protected mergeParentIds(existingComputedItem: ComputedItem | Dataset, currentComputedItem: ComputedItem | Dataset) {
// Merge the ids from both the existing element and the newly discovered one.
existingComputedItem.parentIds = union(existingComputedItem.parentIds, currentComputedItem.parentIds);
// Propagate.
this.allElements
.filter((elt) => elt.parentIds.includes(currentComputedItem.id))
.forEach((elt) => {
elt.parentIds = union(elt.parentIds, currentComputedItem.parentIds);
});
}
protected saveDataset(dataset: Dataset): boolean {
const existingDataset = this.datasets.find((d) => d.id === dataset.id);
if (!existingDataset) {
this.allElements.push(dataset);
this.datasets.push(dataset);
return true;
}
this.hits++;
this.mergeParentIds(existingDataset, dataset);
return false;
}
protected saveGlobalComputedItem(computedItem: ComputedRule | ComputedVariable): boolean {
if (computedItem.type === ComputedItemTypes.VARIABLE && computedItem.variableType === VariableType.object) {
throw new Error(`Will not save a object variable ${computedItem.id} in global.`);
}
const existingItem = this.computedItems.find((i) => i.id === computedItem.id);
if (!existingItem) {
this.allElements.push(computedItem);
this.computedItems.push(computedItem);
return true;
}
this.hits++;
this.mergeParentIds(existingItem, computedItem);
return false;
}
protected saveOverrideConditionInDataset(datasetId: string | null, condition: AmaliaFormula) {
const dataset = this.datasets.find((d) => d.id === datasetId) as FilterDataset;
dataset.overrideCondition = condition;
}
protected saveComputedItemInDataset(datasetId: string | null, computedVariable: ComputedVariable): boolean {
if (computedVariable.variableType !== VariableType.object) {
throw new Error(`Will not save a non-object variable ${computedVariable.id} in a dataset.`);
}
const dataset = this.datasets.find((d) => d.id === datasetId);
if (!datasetId || !dataset) {
throw new Error(`Could not save result of ${computedVariable.variableMachineName} in a dataset`);
}
const { computedItems } = dataset;
// The dataset is now a child of this item, since it should be evaluated before it.
dataset.parentIds = union(dataset.parentIds, [computedVariable.id]);
const existingItem = computedItems.find((i) => i.id === computedVariable.id);
// Mutating the dataset in place to add computedItems or update parents.
if (!existingItem) {
this.allElements.push(computedVariable);
computedItems.push(computedVariable);
return true;
}
this.hits++;
this.mergeParentIds(existingItem, computedVariable);
return false;
}
protected addRelationsToFetchInDataset(datasetId: string | null, relationshipLevelsFounds: string[]) {
if (!relationshipLevelsFounds.length) {
return;
}
const datasetIndex = this.datasets.findIndex((d) => d.id === datasetId);
if (!datasetId || datasetIndex === -1) {
throw new Error('Could not add relations in a non-existing dataset.');
}
this.datasets[datasetIndex].relationMachineNames = union(
this.datasets[datasetIndex].relationMachineNames ?? [],
relationshipLevelsFounds,
);
}
// ======================= REFERENCE MAPS =======================
protected buildParentsGraph() {
this.parentsGraph = this.allElements.reduce<Record<string, string[]>>((acc, { id, parentIds }) => {
acc[id] = parentIds;
return acc;
}, {});
}
/**
* Returns the direct children of a computation item.
*
* Direct children are items that appears in the formula of an item.
* We mostly need it for the currencyFrom. For instance, in
* `opportunity.licenceAccelerator = opportunity.licence * 0.3`,
* "licence" is a direct child of "licenceAccelerator", which means
* "licenceAccelerator" will have the currency of "licence".
*
* @param computedItemId
* @private
*/
protected getDirectChildren(computedItemId: string) {
return computedItemId in this.directChildrenGraph ? this.directChildrenGraph[computedItemId] : [];
}
/**
* Loop on all variable that have a currency format to evaluate from which computed
* item they should grab their currency.
*/
protected buildCurrencyFrom() {
const allCurrencyItemIds = new Set(this.currencyItems.map((ci) => ci.id));
this.currencyItems.forEach((currencyItem) => {
// Currency of current computed item is a mix of the currency of its direct children.
// It means that it could be multiple, which means during evaluation, we should check
// that currency are the same (if not we have a heterogeneity issue).
const ids = [
// Get direct children of this item.
...this.getDirectChildren(currencyItem.id),
// And get direct children of the evaluations inside it.
...flatten((currencyItem.evaluations ?? []).map((e) => this.getDirectChildren(e.id))),
];
// And remove non-currency children.
currencyItem.currencyFrom = ids.filter((id) => allCurrencyItemIds.has(id));
});
}
/**
* Given the id of the item, find it in the template.
*
* TODO: not the most efficient way to do, will probably switch to hashmaps.
*
* @param id
* @param throwIfNotFound
*/
public getItemById(
id: string,
throwIfNotFound: boolean = true,
): {
computedItem?: ComputedItem;
dataset?: Dataset;
parentDatasetId?: string;
} {
const foundInRoot = this.computedItems.find((c) => c.id === id);
if (foundInRoot) {
return { computedItem: foundInRoot };
}
const foundDataset = this.datasets.find((d) => d.id === id);
if (foundDataset) {
return { dataset: foundDataset };
}
for (const dataset of this.datasets) {
for (const computedItem of dataset.computedItems) {
if (computedItem.id === id) {
return {
computedItem,
parentDatasetId: dataset.id,
};
}
}
}
if (throwIfNotFound) {
throw new Error('Computed item not found');
}
return {};
}
public getScopesToFetch() {
return this.scopesToFetch;
}
// ======================= TRAVERSE HELPERS =======================
/**
* Given the plan template and the list of items we've already calculated,
* fetch the next items that are "at the end of the graph" (which are the
* one that don't have any non-computed children).
*/
protected readonly getIdsOfNextItemsToCompute = (computedItemIds: string[]) => {
// Remove already computed items.
const nonComputedItems = omit(this.parentsGraph, computedItemIds);
// Case where we computed everything.
if (Object.keys(nonComputedItems).length === 0) {
return [];
}
// Build the list of all parentIds in the graph.
const allParentIds = flatten(Object.values(nonComputedItems));
// Childless items are the one that have an id that doesn't appear in parentIds of another item.
// It means that if we take the id of a ComputedItem, and we don't find it in the list of parentIds,
// bingo it's safe to compute.
const childrenToCompute = Object.keys(nonComputedItems).filter((itemId) => !allParentIds.includes(itemId));
// If we still have items to compute, but we cannot compute them because they are not "free leaves", then it
// means that there is a circular dependency somewhere in those items. Notify the users.
if (childrenToCompute.length === 0) {
throw new ConfigurationError(
`Circular dependency detected in the formulas of ${Object.keys(nonComputedItems).join(', ')}`,
);
}
return childrenToCompute;
};
public traversePlan = async (
callback?: ({
computedItem,
dataset,
parentDatasetId,
}: {
computedItem?: ComputedItem;
dataset?: Dataset;
parentDatasetId?: string;
}) => Promise<void>,
alreadyComputedItemIds?: string[],
) => {
const computedItemIds: string[] = alreadyComputedItemIds ?? [];
let nextItemsToComputeIds: string[] = [];
let turns = 0;
// Iterate on the list until everything is computed.
do {
if (turns++ > MAX_TURNS) {
throw new Error('Too many loops while computing items');
}
nextItemsToComputeIds = this.getIdsOfNextItemsToCompute(computedItemIds);
if (callback) {
for (const itemId of nextItemsToComputeIds) {
await callback(this.getItemById(itemId));
}
}
computedItemIds.push(...nextItemsToComputeIds);
} while (nextItemsToComputeIds.length > 0);
return computedItemIds;
};
// ======================= QUERY CONTAINERS =======================
public buildQueryContainers(defaultConnection: DataSource, dataConnection: DataSource, debugMode: boolean) {
const qcs = prepareQueryContainers(
defaultConnection,
dataConnection,
this.statementCalculationCache,
this.plan,
this.datasets,
this.filterDefinitions,
this.customObjectDefinitions,
this.relationshipsDefinition,
debugMode,
);
this.queryContainers.push(...qcs);
}
public getQueryContainer<T extends QueryContainer>(
type: PlanTemplateQueryContainer['type'],
key: PlanTemplateQueryContainer['key'],
) {
const qc = this.queryContainers.find((qc) => qc.key === key && qc.type === type)?.queryContainer;
assert(qc, `QueryContainer for ${type} - ${key} not found`);
return qc as T;
}
// ======================= DEHYDRATED =======================
/**
* Dehydrate the plan template into a plain object.
*
* Useful to store in the indexed plan template, for debug, for
* search operations in a plan, ...
*
* @param canSeeSqlRequests
* @param includeDefinitions
*/
public getDehydratedPlanTemplate({ canSeeSqlRequests }: { canSeeSqlRequests: boolean }): PlanTemplateDehydrated {
assert(this.plan, 'Cannot dehydrate a release plan template');
return {
metadata: this.metadata,
datasets: this.datasets,
computedItems: this.computedItems,
recursionLevel: this.recursionLevel,
// Don't show SQL queries to someone that cannot see them for security reasons.
queryContainers: canSeeSqlRequests
? this.queryContainers.map(
({ key, type, queryContainer }): PlanTemplateQueryContainerDehydrated => ({
key,
type,
queryContainer: queryContainer.formatDisplay(),
}),
)
: [],
definitions: {
...this.getDefinitions(),
plan: this.plan,
},
weight: this.getIndexedPlanWeight(),
};
}
private static isComputedFunctionResult(computedItem: ComputedItem): computedItem is ComputedFunctionResult {
return (
computedItem.type === ComputedItemTypes.FUNCTION_RESULT &&
['GETATINDEX', 'rowMarginalIndex', 'rowTiersIndex', 'SUM'].includes(computedItem.function)
);
}
}
|