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 | 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 98x 1x 1x 1x 98x 98x 98x 98x 98x 98x 98x 98x 98x 81x | import {bind, /* inject, */ BindingScope} from '@loopback/core';
import {
EntityNotFoundError,
Filter,
FilterBuilder,
IsolationLevel,
Options,
repository,
Where,
} from '@loopback/repository';
import {HttpErrors} from '@loopback/rest';
import {compact, remove, uniq} from 'lodash';
import {Constants, Module} from '../configs';
// Inline type to avoid importing from internal @loopback/filter path
interface InclusionScope { fields?: object; order?: string[]; where?: object; include?: InclusionFilter[]; }
type InclusionFilter = string | Inclusion;
interface Inclusion { relation: string; scope?: InclusionScope; }
import {
FlowActionDto,
FlowDefaultActionDto,
FlowDefaultGroupDto,
FlowDefaultJourneyPointDto,
FlowDefaultPersonaDto,
FlowDefaultReferenceDto,
FlowDto,
FlowJourneyPointDto,
FlowPersonaDto,
UserDto,
} from '../dtos';
import {
BaseEntity,
Flow,
FlowDefault,
FlowDefaultAction,
FlowDefaultJourneyPoint,
FlowDefaultReference,
FlowJourneyPoint,
FlowPersona,
FlowReference,
RoleRights,
Status,
TradeLane,
} from '../models';
import {
BaseCrudRepository,
CompanyPersonaRepository,
FlowActionRepository,
FlowDefaultGroupRepository,
FlowDefaultJourneyPointRepository,
FlowDefaultPersonaRepository,
FlowDefaultReferenceRepository,
FlowDefaultRepository,
FlowGroupRepository,
FlowJourneyPointRepository,
FlowPersonaRepository,
FlowReferenceRepository,
FormRepository,
PersonaRepository,
RoleRightsRepository,
TradeLaneRepository,
} from '../repositories';
import {FlowDefaultActionRepository} from '../repositories/flow-default-action.repository';
import {FlowRepository} from '../repositories/flow.repository';
import {Action, AnyObject, Documents, GroupDetail, RecipientNotification, ReplyMessage} from '../types';
import {BaseService} from './base.service';
import _ from 'lodash';
import { DateUtils } from '@logchain/utils';
type FlowRepo = FlowDefaultRepository | FlowRepository;
type FlowJourneyPointRepo =
| FlowDefaultJourneyPointRepository
| FlowJourneyPointRepository;
type FlowGroupRepo = FlowDefaultGroupRepository | FlowGroupRepository;
type FlowPersonaRepo = FlowDefaultPersonaRepository | FlowPersonaRepository;
type FlowActionRepo = FlowDefaultActionRepository | FlowActionRepository;
type FlowReferenceRepo =
| FlowDefaultReferenceRepository
| FlowReferenceRepository;
type FlowData =
| FlowDefaultJourneyPointDto
| FlowDefaultGroupDto
| FlowDefaultPersonaDto
| FlowDefaultActionDto
| FlowDefaultReferenceDto
| FlowJourneyPointDto
| FlowReference
| FlowPersonaDto;
@bind({scope: BindingScope.TRANSIENT})
export class BaseFlowService<M extends BaseEntity> extends BaseService<M> {
is_default_flow = true;
@repository(TradeLaneRepository)
public trade_lane_repo: TradeLaneRepository;
@repository(FormRepository)
public form_repo: FormRepository;
@repository(RoleRightsRepository)
public role_right_repo: RoleRightsRepository;
constructor(
@repository(BaseCrudRepository)
public flow_repo: FlowRepo,
@repository(BaseCrudRepository)
public flow_journey_point_repo: FlowJourneyPointRepo,
@repository(BaseCrudRepository)
public flow_group_repo: FlowGroupRepo,
@repository(BaseCrudRepository)
public flow_persona_repo: FlowPersonaRepo,
@repository(BaseCrudRepository)
public flow_refer_repo: FlowReferenceRepo,
@repository(BaseCrudRepository)
public flow_action_repo: FlowActionRepo,
@repository(PersonaRepository)
public persona_repo: PersonaRepository,
) {
super();
if (flow_repo instanceof FlowRepository) {
this.is_default_flow = false;
}
}
/**
* Get flow by id or identifier.
* @param id The flow id.
* @param options The options.
*/
async getByIdOrIdentifier(id: number, options: Options): Promise<M> {
this.addWhereIdOrIdentifier(id);
// add include to get more data.
this.addExtraFilter(options);
const current_flow = await this.flow_repo.findOne(
this.filter_builder.build() as AnyObject,
);
if (!current_flow) {
throw new EntityNotFoundError(this.flow_repo.entityClass, id);
}
current_flow.steps_state = await this.getStepsUIStatus(current_flow.id);
if (options?.step === Constants.FlowStep.One) {
const unique_persona = await this.flow_persona_repo.groupingPersonaByFlowId(
id,
);
current_flow.unique_persona = unique_persona;
}
if (options?.step > Constants.FlowStep.Two) {
if (current_flow.journey_points?.length) {
const promises = current_flow.journey_points.map(async (journeypoint: AnyObject) => {
const source = await this.getStepDetails(id, journeypoint.id);
journeypoint.allowed_actions = await this.getActionForJourneyPoint(id, journeypoint.id);
journeypoint.allowed_documents = await this.getDocumentForJourneyPoint( id, journeypoint.id);
return Object.assign(journeypoint, source);
});
await Promise.all(promises);
}
current_flow.personas = await this.getUniquePersonas(id);
}
return (current_flow as unknown) as M;
}
/**
* Get flow by flow id.
* @param id The flow id
* @param options The options
*/
async getFlowById(id: number, options?: Options) {
this.addWhereIdOrIdentifier(id);
this.filter_builder.include({
relation: 'trade_lane',
scope: {
include: [{
relation: 'trade_lane_flow',
scope: {
include: [{
relation: 'personas',
scope: {
order: ['order ASC']
}
},{
relation: 'journey_points',
scope: {
order: ['order ASC']
}
}]
}
}]
}
});
this.filter_builder.include({
relation: 'creator',
scope: {
fields: {
id: true,
name: true,
},
},
});
const flow = await this.flow_repo.findOne(
this.filter_builder.build() as AnyObject
);
if (!flow) {
throw new EntityNotFoundError(this.flow_repo.entityClass, id);
}
// can not update ForValidation/Validated/Live for Flow.
if (
!options?.forUpdateReferences &&
!options?.forFleetUpdate &&
!this.is_default_flow &&
[
Status.Flow.ForValidation,
Status.Flow.Validated,
Status.Flow.Live,
].includes(flow.status)
) {
throw new HttpErrors.BadRequest(
`Can not update the flow. Current status is: ${flow.status}`,
);
}
return flow;
}
/**
* Creates or update a journey for the flow.
* @param id The flow id.
* @param data The journey points information.
* @param options Params for other options.
*/
async upsertStep(id: number, data: {steps: FlowJourneyPointDto[]}, options: Options = {}) {
const flow = await this.flow_repo.findById(id) as Flow;
if (!flow) {
throw new EntityNotFoundError(this.flow_repo.entityClass, id);
}
const { steps } = data;
const persona_ids: number[] = [];
const actor_persona: {id?: number; persona_id: number}[] = [];
const jp_ids: number[] = [];
steps.forEach(({id: jp_id, persona_id, flow_persona_id}) => {
jp_ids.push(jp_id);
// only check if persona_id != 0. 0 is for documents.
if (persona_id !== 0 && typeof(flow_persona_id) !== 'undefined') {
persona_ids.push(persona_id);
actor_persona.push({
id: flow_persona_id,
persona_id,
});
}
});
if (this.is_default_flow) {
// ensure all persona id is exists.
await this.ensurePersonasExists(
id,
compact(persona_ids),
this.flow_persona_repo,
);
} else {
await this.ensureActorPersonasExistsWithMatchedPersona(id, actor_persona);
}
// ensure all journey points belong to the flow
await this.ensureJourneyBelongToFlow(id, compact(jp_ids));
return this.populateFlowData(id, steps, this.flow_journey_point_repo, undefined, options);
}
/**
* Ensure all personas is exists.
* @param persona_ids The persona array id.
*/
protected async ensurePersonasExists(
id: number,
persona_ids: number[],
repo: PersonaRepository | CompanyPersonaRepository | FlowPersonaRepo = this
.persona_repo, // by default, it will be PersonaRepository
) {
let where: AnyObject = {
id: {inq: persona_ids},
};
if (repo instanceof FlowDefaultPersonaRepository) {
where = {
id: {inq: persona_ids},
flow_default_id: id,
};
}
const personas = await repo.find({
where: where,
});
personas.forEach((persona: {id: number}) => {
remove(persona_ids, ele => {
return ele === persona.id;
});
});
persona_ids = compact(persona_ids);
if (persona_ids.length) {
throw new HttpErrors.BadRequest(
`${repo.entityClass.modelName} not exists with id: ${uniq(
persona_ids,
)}`,
);
}
return personas;
}
/**
* Ensure all personas is exists.
* @param flow_persona_ids The persona array id.
*/
protected async ensureActorPersonasExistsWithMatchedPersona(
id: number,
flow_persona_ids: {id?: number; persona_id: number}[],
) {
const where: AnyObject = {
flow_id: id,
};
if (flow_persona_ids.length) {
where.or = [];
for (const iterator of flow_persona_ids) {
where.or.push(iterator);
}
}
const personas = await this.flow_persona_repo.find({
where: where,
});
personas.forEach((persona: {id: number; persona_id: number}) => {
remove(flow_persona_ids, ele => {
return ele.id === persona.id && ele.persona_id === persona.persona_id;
});
});
const persona_ids = compact(flow_persona_ids.map(r => r.id));
if (persona_ids.length) {
throw new HttpErrors.BadRequest(
`${
this.flow_persona_repo.entityClass.modelName
} not exists with id: ${uniq(persona_ids)}`,
);
}
return personas;
}
/**
* Populate data for steps or groups.
* @param id The flow id.
* @param arr_data The array of steps or groups
* @param repo The repository.
*/
async populateFlowData(
id: number,
arr_data: FlowData[],
repo:
| FlowJourneyPointRepo
| FlowGroupRepo
| FlowPersonaRepo
| FlowActionRepo
| FlowReferenceRepo,
step_id?: number,
options: Options = {},
) {
const tx = options?.tx ?? await repo.beginTransaction(IsolationLevel.SERIALIZABLE);
try {
const flow = await this.flow_repo.findOne({
where: {id},
fields: ['id', 'step'],
});
if (!flow) {
throw new EntityNotFoundError(this.flow_repo.entityClass, id);
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const p_tasks: any[] = [];
const arr_data_details = _.cloneDeep(arr_data);
// eslint-disable-next-line @typescript-eslint/no-explicit-any
arr_data.forEach((data: any, idx: number) => {
// For FlowJourneyPointRepository
data = _.omit(data, ['actions', 'ref_documents', 'groups']);
// delete a step/group by id
if (data.delete) {
p_tasks[idx] = repo.deleteById(data.id, {
transaction: tx,
flow_id: id,
journey_point_id: step_id,
});
// Delete FlowGroup also when JP was deleted.
if (data.group_id) {
if (repo instanceof FlowJourneyPointRepository || repo instanceof FlowDefaultJourneyPointRepository) {
p_tasks[idx] = this.flow_group_repo.deleteById(data.group_id, {
transaction: tx,
flow_id: id,
journey_point_id: step_id,
});
}
}
return;
}
// update a step/group by id
if (data.id) {
p_tasks[idx] = repo.updateById(data.id, data, {
transaction: tx,
});
return;
}
delete data.delete;
// in case create for the default flow.
data.flow_default_id = flow.id;
if (!this.is_default_flow) {
// in case create for the flow.
data.flow_id = flow.id;
delete data.flow_default_id;
}
// create new step/group
if (
repo instanceof FlowDefaultReferenceRepository ||
repo instanceof FlowReferenceRepository
) {
// for reference documents. don't create new
p_tasks[idx] = repo.findOrCreate(data, data, {
transaction: tx,
});
return;
}
p_tasks[idx] = repo.create(data, {
transaction: tx,
});
});
// update stats
const result = await Promise.all(p_tasks);
// update stats
await this.flow_repo.updateById(
id,
{
step: flow.getNextStep(),
},
{
transaction: tx,
},
);
await tx.commit();
// map result
if (result) {
const upsertParams: AnyObject[] = [];
const results = arr_data_details.map(
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(s: {delete?: boolean; id?: number}, idx: number, data_details: any) => {
const data_detail = data_details[idx];
if (s.delete) {
return !result[idx]; // deleteById return undefined
}
// Create/update step detail
const journey_point_id = s.id ?? result[idx].id;
if (data_detail?.actions || data_detail?.ref_documents || data_detail?.expected_date || data_detail?.groups) {
upsertParams.push({
flow_id: id,
journey_point_id,
data_detail: {
actions: data_detail?.actions ?? [],
ref_documents: data_detail?.ref_documents ?? [],
expected_date: data_detail?.expected_date ?? '',
},
groups: data_detail?.groups ?? [],
});
}
if (s.id) {
return s.id;
}
return result[idx].id;
},
);
if (upsertParams.length) {
for(const param of upsertParams) {
if (param.data_detail.actions.length || param.data_detail.ref_documents.length || !_.isEmpty(param.data_detail.expected_date)) {
await this.upsertStepDetails(param.flow_id, param.journey_point_id, {
actions: param.data_detail.actions,
ref_documents: param.data_detail.ref_documents,
expected_date: param.data_detail.expected_date,
});
}
if (param.groups.length) {
param.groups.map((g: AnyObject) => {
g.journey_points = [param.journey_point_id];
return g;
});
await this.upsertGroup(param.flow_id, { groups: [param.groups[0]] });
}
}
}
return results;
}
} catch (error) {
console.log(error);
if (tx.isActive()) {
await tx.rollback();
}
throw error;
}
}
/**
* Build where clause based on the flow type.
* @param flow the flow information
*/
private buildWhereClauseBasedOnFlow(flow_id: number) {
// in case of the default flow.
if (this.is_default_flow) {
return {
flow_default_id: flow_id,
};
}
// in case of the flow
return {
flow_id: flow_id,
};
}
/**
* Create or update a group for the flow.
* @param id The flow default id.
* @param data The flow group info.
*/
async upsertGroup(id: number, data: {groups: FlowDefaultGroupDto[]}, options: Options = {}) {
const {groups} = data;
const persona_ids: number[][] = [];
const journey_points_ids: number[][] = [];
groups.map(group => {
persona_ids.push(group.flow_personas);
journey_points_ids.push(group.journey_points);
});
// ensure all persona id is exists.
await this.ensurePersonasExists(
id,
persona_ids.flat(),
this.flow_persona_repo,
);
// ensure all journey point is belong to the flow.
await this.ensureJourneyBelongToFlow(id, journey_points_ids.flat());
await this.populateFlowData(id, groups, this.flow_group_repo);
// return groups details after added.
return this.flow_group_repo.findGroupsByFlowId(id);
}
/**
* Ensure all journey point belong to the flow.
* @param id The flow id.
* @param journey_points_ids The journey points array id.
*/
private async ensureJourneyBelongToFlow(
id: number,
journey_points_ids: number[],
options: Options = {}
) {
const journey_points = await this.flow_journey_point_repo.find({
fields: {
id: true,
flow_default_id: true,
},
where: {
flow_default_id: id,
id: {inq: journey_points_ids},
},
}, options);
journey_points.forEach((jp: {id: number}) => {
remove(journey_points_ids, ele => {
return ele === jp.id;
});
});
journey_points_ids = compact(journey_points_ids);
if (journey_points_ids.length) {
throw new HttpErrors.BadRequest(
`Steps ${journey_points_ids} not exists or not belong to the flow ${id}`,
);
}
}
/**
* Create or update a reference personas.
* @param id The ID of the flow.
* @param data The data.
*/
async upsertRefPersona(
id: number,
data: {ref_personas: (FlowDefaultPersonaDto | FlowPersonaDto)[]},
// eslint-disable-next-line @typescript-eslint/no-explicit-any
): Promise<any[] | undefined> {
throw new Error('Method not implemented.');
}
/**
* Create or update step details.
* @param id The flow id.
* @param step_id The step id.
* @param data The data to update.
*/
async upsertStepDetails(
id: number,
step_id: number,
data: {
actions?: AnyObject[];
ref_documents?: number[];
expected_date?: Date;
}, options: Options = {}
) {
const {actions = [], ref_documents, expected_date} = data;
const persona_ids: number[] = [];
const form_ids: number[] = [];
const delete_actions: number[] = [];
const where = this.buildWhereClauseBasedOnFlow(id);
const step = await this.flow_journey_point_repo.findOne({
where: {
id: step_id,
...where,
},
}) as FlowJourneyPoint;
if (!step) {
throw new EntityNotFoundError(
this.flow_journey_point_repo.entityClass,
step_id,
);
}
// Validate expected_date
if (options?.forExternal) {
if (!await this.flow_repo.validateExpectedDate(id, step, expected_date ?? '')) {
throw new HttpErrors.BadRequest(
`Expected date should be a date and time that is greater than or equal the previous step`,
);
}
}
// ------------------------
actions.map(action => {
if (this.is_default_flow) {
action.flow_default_journey_point_id = step_id;
} else {
action.flow_journey_point_id = step_id;
}
persona_ids.push(action.flow_persona_id);
form_ids.push(action.form_id);
if (action.delete) {
delete_actions.push(action.id);
}
action.container_order = step.container_order;
});
// ensure all persona id is exists.
await this.ensurePersonasExists(
id,
[...persona_ids.flat()],
this.flow_persona_repo,
);
// ensure all form id is exists.
await this.ensureFormExists(form_ids);
let result_ref_docs;
// ensure all documents is exists.
if (ref_documents?.length) {
const documents = await this._ensureRefDocumentsExists(ref_documents);
result_ref_docs = await this.populateFlowData(
id,
(documents as Array<FlowDefaultAction | FlowDefault>).map(
(ref: {id: number}) => {
ref_documents.push(ref.id);
if (this.is_default_flow) {
return new FlowDefaultReferenceDto({
flow_default_id: id,
flow_default_journey_point_id: step_id,
flow_default_action_id: ref.id,
});
} else {
return new FlowReference({
flow_id: id,
flow_journey_point_id: step_id,
flow_action_id: ref.id,
});
}
},
),
this.flow_refer_repo,
);
}
if (ref_documents) {
let ref_where_delete:
| Where<FlowReference>
| Where<FlowDefaultReference> = {
flow_id: id,
flow_journey_point_id: step_id,
flow_action_id: {
nin: ref_documents,
},
};
if (this.is_default_flow) {
ref_where_delete = {
flow_default_id: id,
flow_default_journey_point_id: step_id,
flow_default_action_id: {
nin: ref_documents,
},
};
}
await this.flow_refer_repo.deleteAll(ref_where_delete);
}
const result_action = await this.populateFlowData(
id,
actions as FlowData[],
this.flow_action_repo,
step_id,
);
if (expected_date) {
await this.flow_journey_point_repo.updateById(step_id, {expected_date});
}
return {
actions: result_action,
ref_documents: result_ref_docs,
};
}
/**
* Ensure all form is exists.
* @param form_ids The forms array id.
*/
private async ensureFormExists(form_ids: number[]) {
const forms = await this.form_repo.find({
fields: {
id: true,
name: true,
},
where: {
id: {
inq: form_ids,
},
},
});
forms.forEach((form: {id: number}) => {
remove(form_ids, id => {
return id === form.id;
});
});
form_ids = compact(form_ids);
if (form_ids.length) {
throw new HttpErrors.BadRequest(
`${this.form_repo.entityClass.modelName} not exists with id: ${form_ids}`,
);
}
return forms;
}
/**
* Ensure all ref documents is exists.
* @param ref_documents The documents array id.
*/
private async _ensureRefDocumentsExists(ref_documents: number[]) {
const documents = await this.flow_action_repo.find({
fields: {
id: true,
},
where: {
id: {
inq: ref_documents,
},
},
});
documents.forEach((doc: {id: number}) => {
remove(ref_documents, ele => {
return ele === doc.id;
});
});
ref_documents = compact(ref_documents);
if (ref_documents.length) {
throw new HttpErrors.BadRequest(
`${this.flow_action_repo.entityClass.modelName} not exists with id: ${ref_documents}`,
);
}
return documents;
}
/**
* Builds the query for trade lane
* @param q The query string.
*/
async buildSearchQuery(q?: string) {
if (!q) {
return;
}
const ilike_value = this.buildILikeValue(q);
const filter = new FilterBuilder<TradeLane>();
filter.fields({
id: true,
status: true,
pol_country_id: true,
pod_country_id: true,
});
filter.where({
status: true,
or: [
{
pol_code: ilike_value,
},
{
pod_code: ilike_value,
},
],
});
const trade_lanes = await this.trade_lane_repo.find(filter.build());
const trade_lane_ids = trade_lanes.map(trade_lane => {
return trade_lane.id;
});
// FILTER: name OR description Should be a LIKE search
(this.filter_builder as FilterBuilder<{
name: string;
reference_1: string;
reference_2: string;
reference_3: string;
description: string;
trade_lane_id: number;
}>).impose({
or: [
{
trade_lane_id: {
inq: trade_lane_ids,
},
},
{
name: ilike_value,
},
{
reference_1: ilike_value,
},
{
reference_2: ilike_value,
},
{
reference_3: ilike_value,
},
{
description: ilike_value,
},
],
});
}
/**
* Builds the query country for the flow
* @param country The country id.
*/
async buildCountryQuery(country?: number) {
if (!country) {
return;
}
const filter = new FilterBuilder<TradeLane>();
filter.fields({
id: true,
status: true,
pol_country_id: true,
pod_country_id: true,
});
filter.where({
status: true,
or: [
{
pol_country_id: country,
},
{
pod_country_id: country,
},
],
});
const trade_lanes = await this.trade_lane_repo.find(filter.build());
const trade_lane_ids = trade_lanes.map(trade_lane => {
return trade_lane.id;
});
// FILTER: pol_country.id OR pod_country.id
(this.filter_builder as FilterBuilder<{
trade_lane_id: number;
}>).impose({
trade_lane_id: {
inq: trade_lane_ids,
},
});
}
/**
* Get step details.
* @param id The flow id.
* @param step_id The step id.
* @param options The options.
*/
async getStepDetails(id: number, step_id?: number, options?: Options) {
const filter = new FilterBuilder<FlowDefaultJourneyPoint>();
filter.where({
flow_default_id: id,
});
// get first step
if (!step_id) {
filter.order(['order ASC']);
} else {
// get exactly step
filter.impose({id: step_id});
}
const step = await this.flow_journey_point_repo.findOne(
filter.build() as Filter<FlowDefaultJourneyPoint> &
Filter<FlowJourneyPoint>,
);
if (!step) {
throw new EntityNotFoundError(
this.flow_journey_point_repo.entityClass,
step_id,
);
}
step.groups = await this.getGroupsWithStatusByJourneyId(id, step_id);
step.actions = await this.flow_action_repo.findActionsByJourneyId(id, step.id);
step.ref_documents = await this.flow_refer_repo.findRefDocumentsByJourneyId(id, step.id);
return step;
}
/**
* Add extra filter. Depend on the step we limit query to DB.
* @param options The options.
*/
addExtraFilter(options?: Options) {
// Get info for step 1
if (!options?.step || [Constants.FlowStep.One, Constants.FlowStep.Three].includes(options?.step)) {
this.filter_builder.include({
relation: 'trade_lane',
scope: {
fields: {
id: true,
name: true,
pol_code: true,
pod_code: true,
product: true,
product_no: true,
desired_temp: true,
},
},
});
}
// I allow get journey_points at step 2, step 3 of default flow.
if (options?.step > Constants.FlowStep.Two) {
const base_included: Inclusion = {
relation: 'journey_points',
scope: {
fields: {
id: true,
name: true,
order: true,
persona_id: true,
flow_default_id: true, // for default flow
flow_id: true, // for flow
flow_persona_id: true, // for flow
validator_is_required: true, // for flow
validator_flow_persona_id: true, // for flow
},
where: { order: { neq: 0 }, name: { neq: Constants.addendum_label } },
order: ['order ASC'],
include: [
{
relation: 'persona',
scope: {
fields: ['id', 'title', 'color'],
order: ['title ASC'],
},
},
],
},
};
if (!this.is_default_flow) {
base_included.scope?.include?.push({
relation: 'flow_persona',
scope: {
fields: ['id', 'name'],
order: ['name ASC'],
},
});
base_included.scope?.include?.push({
relation: 'validator_flow_persona',
scope: {
fields: ['id', 'name'],
order: ['name ASC'],
},
});
}
this.filter_builder.include(base_included);
}
}
/**
* Get groups info by id.
* @param flow_id The flow id.
* @param group_id The group id.
*/
public async getGroupInfoById(flow_id: number, group_id?: number) {
if (!group_id) {
const where_clause = this.buildWhereClauseBasedOnFlow(flow_id);
const first_group = await this.flow_group_repo.findOne({
where: where_clause,
order: ['order ASC'],
});
if (!first_group) {
return [];
}
group_id = first_group.id;
}
const sql = `SELECT * FROM get_groups_info_by_id($1, $2, $3);`;
const group_info = await this.flow_group_repo.execute(sql, [
this.is_default_flow,
flow_id,
group_id,
]);
return group_info[0] as GroupDetail;
}
/**
* Get allowed actions for journey point based on current personas.
* @param flow_id The flow id.
* @param journey_point_id The journey point id.
*/
public async getActionForJourneyPoint(
flow_id: number,
journey_point_id: number,
) {
const sql = `SELECT * FROM get_actions_for_journey_point($1, $2, $3);`;
const resl = await this.flow_group_repo.execute(sql, [
this.is_default_flow,
flow_id,
journey_point_id,
]);
return resl as Action[];
}
/**
* Get all documents and forms allowed to add as a reference documents for current journey point.
* @param flow_id The flow id.
* @param journey_point_id The journey point id.
*/
public async getDocumentForJourneyPoint(
flow_id: number,
journey_point_id: number,
) {
const sql = `SELECT * FROM get_documents_for_journey_point($1, $2, $3);`;
const resl = await this.flow_group_repo.execute(sql, [
this.is_default_flow,
flow_id,
journey_point_id,
]);
return resl as Documents[];
}
/**
* Get all groups with status Completed or Incomplete
* @param flow_id The flow id.
*/
public async getGroupsWithStatus(flow_id: number) {
const sql = `SELECT * FROM get_groups_with_status ( $1, $2 );`;
const resl = await this.flow_group_repo.execute(sql, [
this.is_default_flow,
flow_id,
]);
return resl as FlowDefaultGroupDto[];
}
/**
* Get all groups with status Completed or Incomplete
* @param flow_id The flow id.
*/
public async getGroupsWithStatusByJourneyId(flow_id: number, step_id?: number) {
const sql = `
SELECT fg.*, group_status.status,
json_agg(json_build_object(
'id', fp.id,
'name',
CASE
WHEN fp.name IS NOT NULL THEN
fp.name
ELSE comp.name
END,
'icon', get_icon_name(p.title),
'persona_title', p.title,
'persona_id', p.id
)
) as company_personas
FROM get_groups_with_status ( $1, $2 ) as group_status
LEFT JOIN flows_group as fg ON fg."id" = group_status.id
LEFT JOIN flows_persona as fp ON fp.id = ANY(fg.flow_personas)
LEFT JOIN companies as comp ON fp.company_id =comp.id
LEFT JOIN personas as p ON fp.persona_id = p.id
WHERE $3=ANY(fg.journey_points) AND fg.flow_id=$2
GROUP BY fg.id, group_status.status
ORDER BY fg."order"`;
const resl = await this.flow_group_repo.execute(sql, [
this.is_default_flow,
flow_id,
step_id
]);
return resl as FlowDefaultGroupDto[];
}
/**
* Get unique personas
* @param flow_id The flow id.
*/
public async getUniquePersonas(flow_id: number) {
const sql = `SELECT * FROM get_unique_personas($1, $2);`;
const resl = await this.flow_group_repo.execute(sql, [
this.is_default_flow,
flow_id,
]);
return resl as FlowDefaultPersonaDto[];
}
/**
* Get Steps UI status
* @param flow_id The flow id.
*/
public async getStepsUIStatus(flow_id: number) {
const sql = `SELECT * FROM get_step_ui_status($1, $2);`;
const resl = await this.flow_group_repo.execute(sql, [
this.is_default_flow,
flow_id,
]);
if (!resl?.length) {
return [];
} else {
const results = resl[0].steps_status as boolean[];
const statuses = [
results[0],
results[1],
results[2] && results[3] && results[4],
results[5]
];
if (typeof(results[6]) !== 'undefined') {
statuses.push(results[6]);
}
return statuses;
}
}
/**
* Activate the flow by id.
* @param id The flow id.
* @param options The options.
*/
async activateFlowById(id: number, options?: Options): Promise<M> {
this.addWhereIdOrIdentifier(id);
if (options?.forExternal) {
this.filter_builder.include({
relation: 'journey_points',
scope: {
fields: ['id', 'name', 'flow_id', 'order'],
order: ['order ASC'],
include: [
{
relation: 'actions',
scope: {
fields: ['id', 'flow_journey_point_id', 'form_id', 'title'],
},
},
],
},
});
}
const current_flow = await this.flow_repo.findOne(
this.filter_builder.build() as AnyObject,
);
if (!current_flow) {
throw new EntityNotFoundError(this.flow_repo.entityClass, id);
}
// Validate invalid information from trade-lane
const curTradeLane = await this.trade_lane_repo.findByIdWithActiveStatus(current_flow.trade_lane_id);
if (!curTradeLane) {
throw new HttpErrors.BadRequest(`Trade lane ${current_flow.trade_lane_id} not found!`);
}
// Check valid Safety Data Sheet from trade-lane
if (!curTradeLane.safety_data_sheet) {
throw new HttpErrors.BadRequest(`Safety Data Sheet is required!`);
} else {
const url = curTradeLane.safety_data_sheet;
if (url.includes('null')) {
throw new HttpErrors.BadRequest(`Invalid Safety Data Sheet URL!`);
}
await this.ensureS3ObjectExists(url);
}
// -------------------------------------------
await this.ensureFlowCanBeActivated(current_flow);
await this.removeDuplicatedForNoLocationSteps(current_flow);
await this.flow_repo.updateById(id, {
status: this.is_default_flow
? Status.FlowDefault.Active
: Status.Flow.ForValidation,
step: current_flow.getNextStep(),
});
return (current_flow as unknown) as M;
}
/**
* Ensure the flow can be activated
* @param flow The flow instance
*/
async ensureFlowCanBeActivated(flow: {
id: number;
status: number;
}): Promise<void> {
let statuses = [
Status.Flow.ForValidation,
Status.Flow.Validated,
Status.Flow.Rejected,
Status.Flow.Live,
];
if (this.is_default_flow) {
statuses = [Status.FlowDefault.Active];
}
if (statuses.includes(flow.status)) {
throw new HttpErrors.BadRequest(
`Status flow invalid: Current status is ${flow.status}`,
);
}
const groups = await this.getGroupsWithStatus(flow.id);
if (!groups?.length) {
throw new HttpErrors.BadRequest(
`Need to define groups before activate the flow!`,
);
}
const has_invalid = groups.filter(g => {
return !g.status;
});
if (has_invalid?.length) {
throw new HttpErrors.BadRequest(
`All Steps should at least be accessible by 1 group: ${has_invalid.map(
g => {
return g.name;
},
)}`,
);
}
const personas = await this.getUniquePersonas(flow.id);
const has_invalid_persona = personas.filter(p => {
return !p.groups;
});
if (has_invalid_persona?.length) {
throw new HttpErrors.BadRequest(
`Company ${has_invalid_persona.map(
p => {
return p.name;
},
)} with persona ${has_invalid_persona.map(
p => {
return p.icon.replace('-icon', '').toUpperCase();
},
)} should have access to at least 1 step.`,
);
}
}
/**
* Removes duplicated no location steps from a given flow.
*
* @param {Flow} flow - The flow object from which to remove duplicated steps.
* @return {Promise<void>} A promise that resolves when the duplicated steps have been removed.
*/
async removeDuplicatedForNoLocationSteps(flow: AnyObject): Promise<void> {
await this.flow_repo.removeDuplicatedForNoLocationSteps(flow.id);
}
/**
* Send notifications to the user who can received the notification.
* @param flow The flow instance
* @param options The options
*/
async sendNotifications(flow: Flow, options?: Options) {
const p_tasks: AnyObject[] = [];
const company_ids: number[] = [];
const role_ids: number[] = [];
const company_persona_names: {[property: number]: string[];} = {};
const action_names: {[property: number]: string[];} = {};
if (options?.forCancellation) {
// Filter users by open actions
p_tasks[0] = this.flow_action_repo.find({
fields: ['id', 'flow_id', 'company_id', 'form_id', 'form'],
include:[{
relation: 'form',
scope: {
fields: {
id: true,
name: true,
},
},
}],
where: {
flow_id: flow.id,
status: Status.FlowAction.New,
},
} as AnyObject);
// Filter users by personas
p_tasks[1] = this.flow_persona_repo.find({
fields: ['id', 'flow_id', 'company_id', 'persona_id', 'persona'],
include:[{
relation: 'persona',
scope: {
fields: {
id: true,
title: true,
},
},
}],
where: {
flow_id: flow.id,
},
} as AnyObject);
// Filter users by roles_right
p_tasks[2] = this.role_right_repo.find({
where: {
feature_id: +Module.PhysicalTransport.JourneyMgmt,
allow_retrieve: Constants.Access.Allowed,
},
});
const [actions, personas, validate_roles] = await Promise.all(p_tasks);
actions.map((action: FlowActionDto) => {
if (!action?.form?.name) {
return;
}
company_ids.push(action.company_id);
if (!action_names[action.company_id]) {
action_names[action.company_id] = [];
}
if (!action_names[action.company_id].includes(action.form.name)) {
action_names[action.company_id].push(action?.form?.name ?? '');
}
});
personas.map((per: FlowPersona) => {
if (!company_persona_names[per.company_id]) {
company_persona_names[per.company_id] = [];
}
company_persona_names[per.company_id].push(per.persona.title ?? '');
});
validate_roles.map((role: RoleRights) => {
role_ids.push(role.role_id);
});
} else {
// Filter users by personas
if (options?.company_ids?.length) {
p_tasks[0] = this.flow_persona_repo.find({
fields: ['id', 'flow_id', 'company_id', 'name', 'persona_id'],
include:[{
relation: 'persona',
scope: {
fields: {
id: true,
title: true,
},
},
}],
where: {
flow_id: flow.id,
company_id: { inq: options.company_ids },
},
} as AnyObject);
} else {
p_tasks[0] = this.flow_persona_repo.find({
fields: ['id', 'flow_id', 'company_id', 'name', 'persona_id'],
include:[{
relation: 'persona',
scope: {
fields: {
id: true,
title: true,
},
},
}],
where: {
flow_id: flow.id,
},
} as AnyObject);
}
p_tasks[1] = this.role_right_repo.find({
where: {
feature_id: +Module.Compliance.FlowValidation,
allow_validate: Constants.Access.Allowed,
},
});
const [personas, validate_roles] = await Promise.all(p_tasks);
if (options?.key === Constants.Notification.FlowActivated) {
// For the case notification be sent to companies that need to validate the flow.
personas.map((per: FlowPersona) => {
if (options?.step1 && Constants.PersonasForSendingStep1.includes(per.persona_id)) {
// Line 1: Shipper and Logistics Service Provider
company_ids.push(per.company_id);
} if (options?.step2) {
// Line 2: The rest remaining personas except Trucking and Carrier
const personasForSendingStep2 = options?.PersonasForSendingStep2 ?? Constants.PersonasForSendingStep2;
if (personasForSendingStep2.includes(per.persona_id)) {
// Personas in line 2 must be accessible by at least one step (journey_point).
// This is validated by flow management we don't need to check it here
company_ids.push(per.company_id);
}
} if (options?.step3) {
// Line 3: Trucking and Carrier personas
const personasForSendingStep3 = options?.PersonasForSendingStep3 ?? Constants.PersonasForSendingStep3;
if (personasForSendingStep3.includes(per.persona_id)) {
company_ids.push(per.company_id);
}
}
});
} else {
// For other cases.
personas.map((per: FlowPersona) => {
company_ids.push(per.company_id);
if (!company_persona_names[per.company_id]) {
company_persona_names[per.company_id] = [];
}
company_persona_names[per.company_id].push(per.persona.title ?? '');
});
}
validate_roles.map((role: RoleRights) => {
role_ids.push(role.role_id);
});
}
// find the user who can receive the notifications.
const users = await this.user_view_repo.find({
fields: [
'name',
'sub',
'company_id',
'status',
'settings',
'contact_email',
'language',
],
where: {
status: Status.User.Active,
role_id: {
inq: role_ids,
},
company_id: {
inq: company_ids,
},
id: {
nin: options?.excluded_user_ids ?? [0],
}
},
include: [
{
relation: 'company',
scope: {
fields: ['id', 'name']
}
}
]
}) as unknown as UserDto[];
if (!users?.length) {
console.log('not found users');
return;
}
// build notification
const identities: RecipientNotification[] = [];
const link = this._buildHrefForFlow(flow.id, options?.key);
const recipients = users.map((item: UserDto) => {
identities.push({
sub: item.sub,
settings: item.settings,
language: item.language,
replacement_data: {
name: flow.name,
link: options?.link ?? link,
company_name: item?.company?.name ?? '',
container_name: options?.container_name ?? '',
feature_name: options?.feature_name ?? '',
feature_id: options?.feature_id ?? '',
flow_id: flow.id,
action_name: options?.action_name ?? '',
record_name: options?.record_name ?? '',
actor_name: options?.actor_name ?? '',
actor_company_name: options?.actor_company_name ?? '',
},
});
return {
email: item.contact_email,
language: item.language,
replacement_data: {
flow_id: flow.id,
feature_name: options?.feature_name ?? '',
action_name: options?.action_name ?? '',
record_name: options?.record_name ?? '',
feature_id: options?.feature_id ?? '',
username: item.name,
link: options?.link ?? link,
name: flow.name,
company_name: item?.company?.name ?? '',
company_persona_names: company_persona_names[item.company_id]?.join(', ') ?? [],
action_names: action_names[item.company_id]?.join('<br/>\r\n') ?? [],
cancelled_reason: flow.cancelled_reason ?? '',
step_name: options?.step_name ?? '',
reason_for_change: options?.reason_for_change ?? '',
vehicle_no: options?.vehicle_no ?? '',
delivered_by: options?.delivered_by ?? '',
delivery_note: options?.delivery_note ?? '',
flow_company_name: options?.flow_company_name ?? '',
container_name: options?.container_name ?? '',
rejected_reason: options?.rejected_reason ?? '',
actor_name: options?.actor_name ?? '',
actor_company_name: options?.actor_company_name ?? '',
validator_name: options?.validator_name ?? this.current_user?.name ?? '',
validator_date: options?.validator_date ?? DateUtils.formatDateWithTimeZone(
new Date(),
item.company?.timezone,
),
created_date: options?.created_date ?? DateUtils.formatDateWithTimeZone(
new Date(),
item.company?.timezone,
),
},
};
});
console.log('recipients', recipients.map(r => r.email));
p_tasks.length = 0;
if (options?.template) {
p_tasks[0] = this.ses_service.sendBulkTemplatedEmail(
options?.template,
recipients,
);
}
if (options?.key) {
p_tasks[1] = this.notification_service.sendBulkNotifications(
options?.key,
identities,
);
}
await Promise.allSettled(p_tasks);
}
/**
* Build href link for the flow.
* @param id The flow id.
* @param key The template.
* @return The link of flow.
*/
private _buildHrefForFlow(id: number, key: string, options?: AnyObject): string {
if ([Constants.Notification.FlowActivated, Constants.Notification.FlowIsValidated].includes(key)) {
return `compliance/flows-validate/step1?id=${id}`;
} else if ([Constants.Notification.EM121].includes(key)) {
return `physical-transport/journey-detail/${id}?journey_id=${options?.journey_point_id ?? 0}&action_id=${options?.flow_action_id ?? 0}&expand_doc=true`;
} else if ([Constants.Notification.EM102].includes(key)) {
return `alerts/alert-detail/${id}`;
} else if ([Constants.Notification.FlowExpectedDatesIsUpdated].includes(key)) {
return `physical-transport/journey-detail/${id}?step=addendum`;
} else {
return `physical-transport/journey-detail/${id}`;
}
}
/**
* Checks if the flow action is completed and notifies users if it is.
*
* @param {ReplyMessage} msg - The message containing the flow ID.
* @return {Promise<void>} A promise that resolves when the notification is sent.
*/
async checkAndNotifyUsersWhenFlowActionCompeted(msg: ReplyMessage, flow: FlowDto, options: Options = {}): Promise<void> {
const flowAction = await this.flow_action_repo_base.findOne({
where: {
id: msg.flow_action_id,
} as AnyObject,
include: [
{
relation: 'form',
scope: {
fields: {
id: true,
name: true,
},
},
},
],
}) as FlowActionDto;
if (!flowAction || Constants.systemActions.includes(flowAction.title)) {
console.log('Flow action not found', msg.flow_action_id);
return;
}
if (![Status.FlowAction.Completed].includes(flowAction.status)) {
console.log('Flow action is not completed', msg.flow_action_id);
return;
}
let recepientCompanyIds: number[] = options?.validatedCompanyIds ?? [];
if (!options?.validatedCompanyIds?.length) {
const validatedPersonas = await this.flow_persona_repo.find({
where: {
flow_id: msg.flow_id,
} as AnyObject,
}) as unknown as FlowPersonaDto[];
recepientCompanyIds = validatedPersonas.map(
flowPersona => flowPersona.company_id,
);
}
if (msg.id && recepientCompanyIds.length) {
let recordName = msg.id.toString();
let actionData: AnyObject = {};
try { // #54117
const sql = `SELECT * FROM ${msg.table_name} WHERE id = ${msg.id}`;
const actionDatas = await this.flow_action_repo.execute(sql) as AnyObject[];
if (actionDatas?.length) {
actionData = actionDatas[0];
}
console.log('actionData', actionData);
recordName = actionData?.name ?? actionData?.id ?? '';
} catch (error) {
console.log('Error while getting action data', error);
}
// Exclude user list from the notification (by id)
const excludedUserIds = await this.user_repo.getExcludedUsersBySettingsFromReceivingNotifications(msg.flow_id, msg.flow_action_id);
// -----------------------------------------------
let neeedToBeSentNotification = (actionData?.status === Status.Document.Completed);
if (msg.table_name === this.entry_record_repo.getPostgresTableName()) {
neeedToBeSentNotification = ([Status.Entries.EntryApproved, Status.Entries.ExitCompleted].includes(actionData.status));
}
if (neeedToBeSentNotification) { // Only send notification for actions with status completed
const actor = await this.user_view_repo.findOne({
where: {
id: msg.actor_id,
},
include: ['company'],
});
console.log(actor);
await this.sendNotifications(flow, {
template: Constants.Email.EM121,
key: Constants.Notification.EM121,
company_ids: recepientCompanyIds,
excluded_user_ids: excludedUserIds,
action_name: Constants.FormLabel[flowAction.form_id] ?? '',
actor_name: actor?.name,
actor_company_name: actor?.company?.name ?? '',
record_name: recordName ?? '',
link: this._buildHrefForFlow(flow.id, Constants.Notification.EM121, msg),
});
}
}
}
/**
* Checks if the flow is completed and notifies users if it is.
*
* @param {ReplyMessage} msg - The message containing the flow ID.
* @return {Promise<void>} A promise that resolves when the notification is sent.
*/
async checkAndNotifyUsersWhenFlowCompeted(msg: ReplyMessage): Promise<void> {
const flow = await this.flow_repo.findById(msg.flow_id) as FlowDto;
const validatedPersonas = await this.flow_persona_repo.find({
where: {
flow_id: msg.flow_id,
} as AnyObject,
}) as unknown as FlowPersonaDto[];
const validatedCompanyIds = validatedPersonas.map(
flowPersona => flowPersona.company_id,
);
if (msg?.id && validatedCompanyIds.length) {
await this.checkAndNotifyUsersWhenFlowActionCompeted(msg, flow, { validatedCompanyIds });
}
if (![Status.Flow.Rejected, Status.Flow.Live].includes(flow.status) ||
![Status.LiveStatus.Rejected, Status.LiveStatus.Completed].includes(flow.live_status)) {
console.log('Flow is not completed');
return;
}
await this.sendNotifications(flow, {
template: Constants.Email.InformCompanyAfterFlowIsCompleted,
key: Constants.Notification.FlowIsCompleted,
company_ids: validatedCompanyIds,
});
}
/**
* Reset filter for current service.
* @return void()
*/
resetFilterBuilder() {
this.filter_builder = new FilterBuilder<M>();
}
}
|