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 | 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x | import { FlowView } from '@logchain/models/views';
import { bind, /* inject, */ BindingScope, service } from '@loopback/core';
import {
AnyObject,
EntityNotFoundError,
FilterBuilder,
Options,
repository,
} from '@loopback/repository';
import { HttpErrors } from '@loopback/rest';
import { compact, isEmpty } from 'lodash';
import { BaseFlowService, DocumentService } from '.';
import { Constants } from '../configs';
import { FlowDefaultGroupDto, FlowDto, FlowJourneyPointDto, FlowPersonaDto } from '../dtos';
import { BaseResponses, Flow, FlowJourneyPoint, FlowPersona, FlowWithRelations, Status, TradeLaneFlowJourneyPoint, User } from '../models';
import {
CompanyPersonaRepository,
CompanyRepository,
FlowActionRepository,
FlowDefaultJourneyPointRepository,
FlowDefaultRepository,
FlowGroupRepository,
FlowJourneyPointRepository,
FlowPersonaRepository,
FlowReferenceRepository,
FlowViewRepository,
PersonaRepository,
RoleRightsRepository,
TradeLaneRepository,
} from '../repositories';
import { EntityNotActiveError } from '../repositories/errors';
import { FlowDiscussionRepository } from '../repositories/flow-discussion.repository';
import { FlowRepository } from '../repositories/flow.repository';
import _ from 'lodash';
import { NeededInfo } from '@logchain/types';
import { DateUtils } from '@logchain/utils';
import moment from 'moment';
import { FlowNotificationRepository } from '@logchain/repositories/flow-notification.repository';
@bind({ scope: BindingScope.TRANSIENT })
export class FlowService extends BaseFlowService<Flow> {
constructor(
/* ----- FLOW REPOSITORY ----- */
@repository(FlowRepository)
public flow_repo: FlowRepository,
@repository(FlowViewRepository)
public flowview_repo: FlowViewRepository,
@repository(FlowPersonaRepository)
public flow_persona_repo: FlowPersonaRepository,
@repository(FlowGroupRepository)
public flow_group_repo: FlowGroupRepository,
@repository(FlowActionRepository)
public flow_action_repo: FlowActionRepository,
@repository(FlowJourneyPointRepository)
public flow_journey_point_repo: FlowJourneyPointRepository,
@repository(FlowReferenceRepository)
public flow_journey_refer_repo: FlowReferenceRepository,
@repository(FlowDiscussionRepository)
public flow_discussion_repo: FlowDiscussionRepository,
/* ----- FLOW REPOSITORY ----- */
/* ----- FLOW DEFAULT REPOSITORY ----- */
@repository(FlowDefaultRepository)
public flow_default_repo: FlowDefaultRepository,
@repository(FlowDefaultJourneyPointRepository)
public flow_default_journey_point_repo: FlowDefaultJourneyPointRepository,
/* ----- FLOW DEFAULT REPOSITORY ----- */
/* ----- OTHER REPOSITORY ----- */
@repository(TradeLaneRepository)
public trade_repo: TradeLaneRepository,
@repository(PersonaRepository)
public persona_repo: PersonaRepository,
@repository(CompanyPersonaRepository)
public comp_persona_repo: CompanyPersonaRepository,
@repository(CompanyRepository)
public comp_repo: CompanyRepository,
@repository(RoleRightsRepository)
public role_right_repo: RoleRightsRepository,
@repository(FlowNotificationRepository)
public flow_notification_repo: FlowNotificationRepository,
) {
super(
/* ----- FLOW REPOSITORY ----- */
flow_repo,
flow_journey_point_repo,
flow_group_repo,
flow_persona_repo,
flow_journey_refer_repo,
flow_action_repo,
/* ----- FLOW REPOSITORY ----- */
persona_repo,
);
}
/**
* Ensure get right records.
*/
public ensureRightAccessRecord(): void {
this.filter_builder.impose({
company_id: this.current_user.company_id,
});
}
/**
* Validate the default flow information.
* @param flow_default_id The default flow id.
* @param trade_lane_id The trade lane id.
*/
private async _validateDefaultFlow(flow: FlowDto) {
const { trade_lane_id, flow_default_id } = flow;
if (flow_default_id) {
const default_flow = await this.flow_default_repo.findByIdWithActiveStatus(
flow_default_id,
);
if (trade_lane_id && default_flow.trade_lane_id !== trade_lane_id) {
throw new HttpErrors.BadRequest(
`Flow default ${flow_default_id} don's have the trade lane ${trade_lane_id}`,
);
}
flow.trade_lane_id = default_flow.trade_lane_id;
} else {
// validate trade lane info
await this.trade_repo.findByIdWithActiveStatus(trade_lane_id);
}
}
/**
* Creates a new the flow.
* @param flow The flow info.
* @returns Promise<Flow>
*/
async create(payload: FlowDto, options?: Options): Promise<Flow> {
// if default flow is provided. make sure is active
await this._validateDefaultFlow(payload);
// create new flow.
payload.step = Constants.FlowStep.One;
// force status to new
payload.status = Status.Flow.New;
payload.company_id = this.current_user.company_id;
// For created from XML.
this.flow_repo.current_user = this.current_user;
// Load information from trade lane
const curTradeLane = await this.trade_repo.findByIdWithActiveStatus(payload.trade_lane_id);
if (!curTradeLane) {
throw new HttpErrors.BadRequest(`Trade lane ${payload.trade_lane_id} not found!`);
}
payload.pol_code = curTradeLane.pol_code;
payload.pol_name = curTradeLane.pol_name;
payload.pol_country_id = curTradeLane.pol_country_id;
payload.pod_code = curTradeLane.pod_code;
payload.pod_name = curTradeLane.pod_name;
payload.pod_country_id = curTradeLane.pod_country_id;
// -------------------------------------------
// Validate invalid information from trade-lane
// 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);
}
// -------------------------------------------
const createdFlow = await this.flow_repo.create(payload);
const id = createdFlow.id;
const current_flow: FlowWithRelations = await this.getFlowById(createdFlow.id) as FlowWithRelations;
if (options?.trade_lane) {
current_flow.trade_lane = options.trade_lane;
}
if (current_flow.trade_lane?.flow_status && current_flow.trade_lane.trade_lane_flow) {
const trade_lane_flow_personas = current_flow.trade_lane.trade_lane_flow.personas;
let flow_persona_ids: number[] = [];
let flow_personas: FlowPersona[] = [];
if (current_flow.trade_lane.trade_lane_flow.personas) {
// Create flow_personas from current_flow step 2 but we don't have companies info yet.
const needed_info = options?.Unitkey ? { container_no: [options.Unitkey] } as NeededInfo : undefined;
const ref_personas = trade_lane_flow_personas.map((persona) => {
return new FlowPersona({
flow_id: id,
status: Status.FlowPersona.WaitToValidate,
company_id: persona.company_id,
persona_id: persona.persona_id,
order: persona.order,
needed_info: current_flow.company_id === persona.company_id ? needed_info : undefined,
});
});
flow_personas = await this.flow_persona_repo.createAll(ref_personas) ?? [];
flow_persona_ids = flow_personas.map(flow_persona => flow_persona.id) ?? [];
await this.flow_repo.updateById(id, {
step: Constants.FlowStep.Two,
})
// -----------------------------------------------------
}
// validate expected dates before processing journey points
const expected_dates_for_flow: AnyObject = {};
if (options?.xml) {
if (current_flow.trade_lane?.trade_lane_flow?.journey_points) {
for (const journey_point of current_flow.trade_lane?.trade_lane_flow?.journey_points) {
const parseExpectedDate: AnyObject = this.xmlService.parseExpectedDate(journey_point.expected_date_info, options as Options);
if (!parseExpectedDate) {
await this.deleteByIdOrIdentifier(id); // Rollback
throw new HttpErrors.BadRequest(this.xmlService.response1102(options));
}
expected_dates_for_flow[journey_point.expected_date_info.field_name] = parseExpectedDate['expected_date'];
}
}
}
// -----------------------------------------------------
// eslint-disable-next-line @typescript-eslint/no-misused-promises
setTimeout(async () => {
if (current_flow.trade_lane?.trade_lane_flow?.journey_points) {
// Create journey_points from current_flow step 3 but we only have persona without company
let journey_points = current_flow.trade_lane?.trade_lane_flow?.journey_points;
// We duplicate JP based on number of containers
const processedSteps = [];
for (const journey_point of journey_points) {
for (let iStep = 0; iStep < createdFlow.no_of_container; iStep++) {
const newJP = _.cloneDeep(journey_point);
newJP.container_order = iStep + 1;
processedSteps.push(newJP);
}
}
journey_points = processedSteps;
// eslint-disable-next-line @typescript-eslint/prefer-for-of
for (let index = 0; index < journey_points.length; index++) {
const journey_point = journey_points[index];
// Create new journey_point for draff case with location.
// Location
let location_selected: FlowPersona = {} as FlowPersona;
if (journey_point.persona) {
const location_index = trade_lane_flow_personas.findIndex(
persona => (
persona.persona_id === journey_point.persona.persona_id &&
persona.order === journey_point.persona.order
)
);
location_selected = flow_personas[location_index] ?? 0;
}
// Actor
let actor_selected: FlowPersona = {} as FlowPersona;
if (journey_point.actor) {
const location_index = trade_lane_flow_personas.findIndex(
persona => (
persona.persona_id === journey_point.actor.persona_id &&
persona.order === journey_point.actor.order
)
);
actor_selected = flow_personas[location_index] ?? 0;
}
// Validator
let validator_selected: FlowPersona = {} as FlowPersona;
if (journey_point.validator) {
const location_index = trade_lane_flow_personas.findIndex(
persona => (
persona.persona_id === journey_point.validator.persona_id &&
persona.order === journey_point.validator.order
)
);
validator_selected = flow_personas[location_index] ?? 0;
}
const interval_default = createdFlow.no_of_container === 1 ? 0 : Constants.DefaultContainerInterval;
if (journey_point?.expected_date_info?.field_name) {
if (options?.xml) {
const date_after_adjustment = DateUtils.adjustDays(
expected_dates_for_flow[journey_point.expected_date_info.field_name],
journey_point.expected_date_info.adjustment
);
journey_point.expected_date = date_after_adjustment;
} else if (createdFlow?.xml_expected_dates) {
// Process expected date from Web UI
journey_point.expected_date = createdFlow.xml_expected_dates[journey_point.expected_date_info.field_name] ?? undefined;
if (journey_point?.expected_date && journey_point?.expected_date_info?.adjustment) {
journey_point.expected_date = DateUtils.adjustDays(moment(journey_point.expected_date).toDate(), journey_point.expected_date_info.adjustment);
}
}
} else if (options?.xml) {
journey_point.expected_date = new Date();
}
// -------------------------------------
const createdJourneyPointIds = await this.upsertStep(id, {
steps: [
new FlowJourneyPointDto({
order: journey_point.order,
persona_id: journey_point.persona?.persona_id ?? 0, // Location
name: journey_point.name,
expected_date: journey_point?.expected_date ?? undefined,
flow_persona_id: location_selected?.id ?? actor_selected?.id ?? 0,
validator_is_required: validator_selected?.id ? true : false,
validator_flow_persona_id: validator_selected?.id ?? undefined,
container_order: journey_point?.container_order ?? undefined,
container_interval: journey_point?.container_interval ?? interval_default,
}),
]
}, options) ?? [];
// Create group for each journey_point
if (createdJourneyPointIds?.length) {
const checked_flow_persona_ids: number[] = [];
journey_point.personas.map((persona: AnyObject, pindex: number) => {
const location_index = trade_lane_flow_personas.findIndex(
persona1 => (
persona1.persona_id === persona.persona_id &&
persona1.order === persona.order
)
);
if (flow_persona_ids[location_index]) {
checked_flow_persona_ids.push(flow_persona_ids[location_index]);
}
});
await this.upsertGroup(id, { groups: [new FlowDefaultGroupDto({
flow_personas: checked_flow_persona_ids,
journey_points: [createdJourneyPointIds[0]],
name: ' ',
order: journey_point.order,
})]}, options);
// Create actions for each journey_point it's equivalent with accesses in step 3
const actor_id = location_selected?.id ?? actor_selected?.id;
journey_point.actions.map((action: AnyObject) => {
action.flow_persona_id = actor_id ?? 0;
action.container_order = journey_point.container_order ?? undefined;
action.form_data = { ...action.form_data };
if (options?.Unitkey) {
action.form_data = { container_no: options?.Unitkey, ...action.form_data };
}
if (Constants.forms_have_expected_weight.includes(action.form_id) && !isEmpty(options?.LoadWeight)) {
action.form_data = { ...action.form_data, expected_weight: parseFloat(options?.LoadWeight) };
}
if (options?.VesselData) {
action = this.setVesselDataToAction(action, options);
}
return action;
});
await this.upsertStepDetails(id, createdJourneyPointIds[0], {
actions: journey_point.actions,
});
// -----------------------------------------------------
}
};
// Update expected dates for flow
if (!isEmpty(expected_dates_for_flow)) {
await this.flow_repo.updateById(id, { xml_expected_dates: expected_dates_for_flow }, options);
}
// -----------------------------------------------------
}
}, 100);
}
current_flow.activity = {
str: 'User {1} {2} {3}', //User [First Name Last Name] [activity] [Flow Name]
args: [
'Create Flow',
current_flow?.creator?.name ?? '',
'created',
current_flow.name
]
};
return current_flow as Flow;
}
/**
* Creates a new the flow by external request.
* @param payload The flow info.
* @param options Additional data.
* @returns Promise<Flow>
*/
async createByExternal(payload: AnyObject, options?: Options) {
const selectedTradeLane = await this.trade_lane_repo.findOne({
where: { id: payload.trade_lane_id },
include: [
{
relation: 'trade_lane_flow',
scope: {
include: [
{
relation: 'personas'
},
{
relation: 'journey_points'
},
]
}
}
]
});
if (!selectedTradeLane) {
throw new EntityNotFoundError(this.trade_lane_repo.entityClass, payload.trade_lane_id);
}
let createdFlow: Flow = new Flow();
const personasByOrder: AnyObject = {};
const stepsByOrder: AnyObject = {};
// eslint-disable-next-line no-useless-catch
try {
if (selectedTradeLane.trade_lane_flow?.personas?.length) {
if (selectedTradeLane.trade_lane_flow?.journey_points?.length !== payload?.steps?.length) {
throw new HttpErrors.BadRequest(
`Invalid information: steps does not match.`,
);
}
if (payload?.steps?.length) {
payload.steps.map((step: AnyObject) => {
stepsByOrder[step.step_no] = step;
});
}
// We filter personas without company_id
const missingCompanyPersonas: AnyObject = {};
selectedTradeLane.trade_lane_flow.personas.map(persona => {
if (!persona.company_id) {
missingCompanyPersonas[persona.order] = persona;
}
});
// We fill missing information into steps
selectedTradeLane.trade_lane_flow?.journey_points.forEach(jp => {
jp.expected_date = stepsByOrder[jp.order]?.expected_date ?? '';
return jp;
});
if (!Object.keys(missingCompanyPersonas).length) {
// 1. Trade Lane selected has a complete flow (API specify expected date for all steps)
// Both personas & journey_points will get from trade-lane-flow
// But API will provide journey_points (only expected_date) to fill missing information
createdFlow = await this.create(new FlowDto({
trade_lane_id: payload.trade_lane_id,
name: payload.name,
description: payload.description,
}), {
trade_lane: selectedTradeLane,
...options
});
} else {
// 2. Trade Lane selected and some persona has no predefined companies
// API provide both personas (provide missing company_id) & journey_points (provide missing expected_date)
if (!payload?.personas?.length) {
throw new HttpErrors.BadRequest(
`Missing information: personas.`,
);
}
const objIdentifiers: AnyObject = {};
const objProvidedPersonas: AnyObject = {};
payload.personas.map((persona: AnyObject) => {
if (persona?.company_identifier) {
objIdentifiers[persona.company_identifier] = persona.order;
objProvidedPersonas[persona.order] = persona.company_identifier;
}
});
if (Object.keys(objProvidedPersonas).length !== Object.keys(missingCompanyPersonas).length) {
throw new HttpErrors.BadRequest(
`Invalid information: personas does not match.`,
);
}
const flow_companies = await this.comp_repo.find({
fields: ['id', 'identifier', 'name'],
where: {
identifier: { inq: Object.keys(objIdentifiers) }
}
});
const companies: AnyObject = {};
flow_companies.map(flow_company => {
companies[flow_company.identifier] = flow_company;
});
selectedTradeLane.trade_lane_flow.personas.forEach(persona => {
if (objProvidedPersonas[persona.order] && companies[objProvidedPersonas[persona.order]]) {
persona.company_id = companies[objProvidedPersonas[persona.order]].id;
}
return persona;
});
createdFlow = await this.create(new FlowDto({
trade_lane_id: payload.trade_lane_id,
name: payload.name,
description: payload.description,
}), {
trade_lane: selectedTradeLane,
...options
});
}
} else {
// 3. Flow created only copies the Trade Lane Product, POL and POD values
// API provide both personas & journey_points
if (!payload?.personas?.length) {
throw new HttpErrors.BadRequest(
`Missing information: personas.`,
);
}
if (!payload?.steps?.length) {
throw new HttpErrors.BadRequest(
`Missing information: steps.`,
);
}
// Do not allow mixed data (insert & update) in the body
const invalidPersonas = payload.personas.find(
(_persona: AnyObject) => _persona.order !== undefined
);
if (invalidPersonas) {
throw new HttpErrors.BadRequest(
`Invalid information: personas.`,
);
}
// Do not allow mixed data (insert & update) in the body
const invalidSteps = payload.steps.find(
(_step: AnyObject) => _step.step_no !== undefined
);
if (invalidSteps) {
throw new HttpErrors.BadRequest(
`Invalid information: steps.`,
);
}
// Limit number of personas for created flow.
const number_personas_limit = +(process.env.NUMBER_PERSONA_LIMIT ?? 0);
if (payload.personas.length > number_personas_limit) {
throw new HttpErrors.BadRequest(
`Allowed limit for persona reached. Please remove some persona for the flow.`,
);
}
// Number of expected_date provided must be equal to number of containers
for(const step of payload.steps) {
if (typeof(step.expected_date) === 'string') {
step.expected_date = [step.expected_date];
}
if (step.expected_date.length !== payload.no_of_container) {
throw new HttpErrors.BadRequest(
`Invalid information: expected_date does not match with number of containers. ${step.expected_date.length} - ${payload.no_of_container}`,
);
}
}
// Step1: Create basic flow
createdFlow = await this.create(new FlowDto({
trade_lane_id: payload.trade_lane_id,
name: payload.name,
description: payload.description,
no_of_container: payload.no_of_container ?? 1,
}), options);
// --------------------------
// Step2: Create flow personas
const objIdentifiers: AnyObject = {};
payload.personas.forEach((persona: AnyObject, index: number) => {
personasByOrder[index+1] = persona;
objIdentifiers[persona.company_identifier] = index+1;
});
const flow_companies = await this.comp_repo.find({
fields: ['id', 'identifier', 'name'],
where: {
identifier: { inq: Object.keys(objIdentifiers) }
}
});
const companiesByIdentifier: AnyObject = {};
flow_companies.map(flow_company => {
companiesByIdentifier[flow_company.identifier] = flow_company;
});
const ref_personas: FlowPersonaDto[] = payload.personas.map((persona: AnyObject) => {
return new FlowPersona({
flow_id: createdFlow.id,
status: Status.FlowPersona.WaitToValidate,
company_id: companiesByIdentifier[persona.company_identifier].id ?? 0,
persona_id: persona.persona_id,
order: persona.order,
});
});
const createdFlowPersonaIds = await this.upsertRefPersona(createdFlow.id, { ref_personas });
// --------------------------
// Step3: Create flow journey_points
// We duplicate JP based on number of containers
const processedSteps = [];
let journey_point_order = 0;
for (const journey_point of payload.steps) {
journey_point_order++;
// Process journey_point.expected_date based on number of containers
if (journey_point.container_interval && journey_point.expected_date.length > 1) {
journey_point.expected_date = journey_point.expected_date.map((date: string) => {
if (typeof journey_point.container_interval === 'string' || typeof journey_point.container_interval === 'number') {
return date + journey_point.container_interval;
} else {
// Handle the case when container_interval is of an incompatible type.
return date;
}
});
}
// -----------------------------------------------------------------
for (let iStep = 0; iStep < createdFlow.no_of_container; iStep++) {
const newJP = _.cloneDeep(journey_point);
newJP.order = journey_point_order;
newJP.container_order = iStep + 1;
newJP.expected_date = journey_point.expected_date[iStep] ?? '';
processedSteps.push(newJP);
}
}
payload.steps = processedSteps;
const flowPersonas = await this.flow_persona_repo.find({
fields: ['id', 'flow_id', 'company_id', 'persona_id'],
where: {
id: { inq: createdFlowPersonaIds }
}
});
// eslint-disable-next-line @typescript-eslint/prefer-for-of
const createdJourneyPoints: FlowJourneyPoint[] = [];
for (let index = 0; index < payload.steps.length; index++) {
const curStep = payload.steps[index];
const selectedPersona = flowPersonas.find(
flowPersona => (
flowPersona.persona_id === (curStep.location ?? 0) &&
flowPersona.company_id === (companiesByIdentifier[curStep.actor].id)
)
);
const createdJourneyPointIds = await this.upsertStep(createdFlow.id, {
steps: [
new FlowJourneyPointDto({
order: curStep.order,
persona_id: curStep.location ?? 0, // Location
flow_persona_id: selectedPersona?.id ?? 0, // Actor
name: curStep.name,
expected_date: curStep.expected_date ?? '',
}),
],
}) ?? null;
// Create group for each journey_point
const checked_flow_persona_ids: number[] = [];
// Add creator to access of all steps.
// eslint-disable-next-line no-unused-expressions
if(!curStep.access.includes(this.current_user.company_identifier)) {
curStep.access.push(this.current_user.company_identifier);
}
curStep.access.map((identifier: string) => {
flowPersonas.map(flowPersona => {
if (companiesByIdentifier[identifier] && flowPersona.company_id === (companiesByIdentifier[identifier].id)) {
checked_flow_persona_ids.push(flowPersona.id);
}
});
});
if (createdJourneyPointIds?.length) {
await this.upsertGroup(createdFlow.id, { groups: [new FlowDefaultGroupDto({
flow_personas: checked_flow_persona_ids,
journey_points: [createdJourneyPointIds[0]],
name: ' ',
order: curStep.order,
})]});
// Create actions for each journey_point it's equivalent with accesses in step 3
const actor_id = selectedPersona?.id ?? 0;
const toBeCreatedActions = curStep.actions.map((action: AnyObject) => {
action.flow_persona_id = actor_id;
action.title = action.form_name;
action.container_order = curStep.container_order ?? 0;
return {
flow_persona_id: actor_id,
form_id: action.form_id,
title: action.form_id === 0 ? action.form_name : undefined,
};
});
// Process ref_documents
const ref_document_ids: number[] = [];
if (createdJourneyPoints.length && curStep.ref_documents?.length) {
curStep.ref_documents.map((ref_document: AnyObject) => {
if (createdJourneyPoints.length) {
createdJourneyPoints.map(jp => {
if (jp.name === ref_document.step_name) {
jp.actions?.map(a => {
if (a.form_id === ref_document.form_id && a.title === ref_document.form_name) {
ref_document_ids.push(a.id);
}
});
}
});
}
});
}
// ----------------------
const safetyRef = await this.flow_journey_refer_repo.findOne({
where: {
flow_journey_point_id: createdJourneyPointIds[0],
}
});
if (safetyRef) {
ref_document_ids.push(safetyRef.flow_action_id);
}
await this.upsertStepDetails(createdFlow.id, createdJourneyPointIds[0], {
actions: toBeCreatedActions,
ref_documents: index === 0 ? undefined : ref_document_ids,
}, { forExternal: true });
createdJourneyPoints.push(await this.flow_journey_point_repo.findOne({
fields: ['id', 'name'],
where: {
id: createdJourneyPointIds[0] ?? 0,
},
include: [{ relation: 'actions' }],
}) as unknown as FlowJourneyPoint);
}
}
// --------------------------
}
// Validate all companies of flow must access to at least one journey_point
if (!this.current_user?.identifier) { // Only used for external API request
if (!await this.flow_repo.allCompaniesMustHaveAccessToStep(createdFlow.id)) {
throw new HttpErrors.BadRequest(
`All companies of flow must access to at least one step`,
);
}
}
// ------------------------
// Click on For validation
createdFlow = await this.activateFlowById(createdFlow.id, { forExternal: true });
createdFlow.status = Status.Flow.ForValidation;
// ------------------------
return createdFlow ? {
id: createdFlow.id,
name: createdFlow.name,
status: createdFlow.status,
status_name: new FlowDto(createdFlow as FlowDto).status_name(),
journey_points: createdFlow.journey_points,
} : null;
} catch (err) {
if (createdFlow?.id) {
await this.deleteByIdOrIdentifier(createdFlow.id);
}
throw err;
}
}
/**
* A function to add a container to a flow.
*
* @param {AnyObject} params - an object containing flow_id, container_no, and ram_order
* @return {Promise<void>} a promise that resolves when the container is added to the flow
*/
async addContainerToFlow(params: AnyObject): Promise<Flow | string> {
const { flow_id, container_no, ram_order = {} } = params;
const flow = await this.flow_repo.findOne({
where: { id: flow_id },
include: [
{
relation: 'trade_lane',
scope: {
fields: {
id: true,
name: true,
pol_code: true,
pod_code: true,
product: true,
company_id: true,
no_of_container: true,
trade_lane_flow_id: true,
},
include: [
{
relation: 'trade_lane_flow',
scope: {
fields: {
id: true,
trade_lane_id: true,
personas: true,
},
include: [
{
relation: 'personas',
scope: {
order: ['order ASC'],
},
},
{
relation: 'journey_points',
scope: {
order: ['order ASC'],
},
},
],
},
}
],
},
},
]
});
if (!flow) {
console.log('addContainerToFlow: Flow not found', flow_id);
return 'Flow not found';
}
// Append container to flows_persona
const flow_persona_owner = await this.flow_persona_repo.findOne({
where: {
flow_id,
company_id: flow.company_id,
persona_id: { inq: Constants.personas_can_create_flow },
},
});
if (!flow_persona_owner) {
console.log('No flow persona owner', flow_id);
return 'No flow persona owner';
}
// ----------------------------------
// Duplicate all steps that have locations (no need for no-location)
const expected_date_infos: AnyObject = {};
flow.trade_lane?.trade_lane_flow?.journey_points.map((jp: TradeLaneFlowJourneyPoint) => {
expected_date_infos[jp.order] = jp.expected_date_info;
});
const allStepsInFlow = await this.flow_journey_point_repo.find({
where: {
flow_id,
container_order: 1,
},
include: ['actions', 'ref_documents']
});
// Validation expected date
const expected_date_for_updates: AnyObject = {};
for(const step of allStepsInFlow) {
const result_expected_date = (expected_date_infos[step.order] ?
this.xmlService.parseExpectedDate(expected_date_infos[step.order], {...ram_order }) :
undefined) as AnyObject;
if (!result_expected_date) {
return this.xmlService.response1102(ram_order);
}
expected_date_for_updates[step.id] = result_expected_date;
}
// Increase number of containers in flow
flow.no_of_container = flow.no_of_container + 1;
await this.flow_repo.updateById(flow_id, { no_of_container: flow.no_of_container });
await this.flow_persona_repo.appendContainer(flow_persona_owner.id, container_no);
await this.flow_action_repo.appendContainerToBookingRef(flow_id, container_no, ram_order);
// Process steps (location)
for(const step of allStepsInFlow) {
const createdJourneyPointIds = await this.upsertStep(flow_id, { steps: [
{
order: step.order,
persona_id: step.persona_id,
name: step.name,
flow_persona_id: step.flow_persona_id,
container_order: flow.no_of_container,
container_interval: step.container_interval,
} as FlowJourneyPointDto
] }) ?? [];
const step_group = await this.flow_group_repo.findOne({
where: {
flow_id,
order: step.order,
},
});
await this.upsertGroup(flow_id, { groups: [new FlowDefaultGroupDto({
flow_personas: step_group?.flow_personas,
journey_points: [createdJourneyPointIds[0]],
name: ' ',
order: step.order,
})]});
const newActions = step.actions?.map((action) => {
let newAction: AnyObject = _.omit(_.cloneDeep(action), 'id', 'flow_journey_point_id');
if (Constants.forms_have_expected_weight.includes(newAction.form_id) && !isEmpty(ram_order?.LoadWeight)) {
const loadWeight = ram_order?.LoadWeight ? parseFloat(ram_order.LoadWeight) : undefined;
if (newAction.form_data) {
newAction.form_data.expected_weight = loadWeight;
} else {
newAction.form_data = ram_order?.LoadWeight ? { expected_weight: loadWeight } : {};
}
}
if (ram_order?.VesselData) {
newAction = this.setVesselDataToAction(newAction, ram_order) as AnyObject;
}
return newAction;
}) ?? [];
const expected_date_for_update = expected_date_for_updates[step.id]['expected_date'] ?? new Date();
const expected_date_adjust_for_update = expected_date_for_updates[step.id]['expected_date_adjustment'] ?? new Date();
await this.upsertStepDetails(flow_id, createdJourneyPointIds[0], {
actions: newActions,
ref_documents: step.ref_documents?.map((ref_doc) => ref_doc.flow_action_id) ?? [],
expected_date: expected_date_adjust_for_update,
});
if (expected_date_infos[step.order] && expected_date_for_update) {
flow.xml_expected_dates[expected_date_infos[step.order].field_name] = expected_date_for_update;
}
}
// Process vessel's steps (no location)
const vesselActions = await this.flow_action_repo.find({
where: {
flow_id,
form_id: { inq: Constants.forms_have_vessel_data },
},
});
for(const action of vesselActions) {
// Update form data
if (action.form_data) {
if (ram_order?.VesselData) {
action.form_data = this.setVesselDataToAction(action, ram_order).form_data;
await this.flow_action_repo.updateById(action.id, { form_data: action.form_data });
}
}
}
if (!isEmpty(flow.xml_expected_dates)) {
await this.flow_repo.updateById(flow_id, { xml_expected_dates: flow.xml_expected_dates });
}
// ----------------------------------
// Reset status validation of companies in flow
await this.flow_persona_repo.updateAll(
{ status: Status.FlowPersona.WaitToValidate },
{ flow_id },
);
// Fire trigger to re-update container_no of form_data
await this.flow_persona_repo.fireTriggerUpdateContainerNoForFormData(flow_id);
// ----------------------------------
return flow;
}
/**
* Updates the expected date for a container in a flow.
*
* @param {Flow} flow - The flow object.
* @param {number} container_number - The container number.
* @param {AnyObject} ram_order - The RAM order.
* @param {Options} [options] - Additional options.
* @returns {Promise<boolean>} - A promise that resolves to a boolean indicating the success of the operation.
*/
async updateExpectedDateByContainerNumber(flow: Flow, container_number: number, ram_order: AnyObject, options?: Options): Promise<boolean | string> {
const expected_date_infos: AnyObject = {};
flow.trade_lane?.trade_lane_flow?.journey_points.map((jp: TradeLaneFlowJourneyPoint) => {
expected_date_infos[jp.order] = jp.expected_date_info;
});
const allStepsInContainer = await this.flow_journey_point_repo.getStepsInContainer(flow.id, container_number) as FlowJourneyPoint[];
const toBeUpdatedSteps: AnyObject[] = [];
for(const step of allStepsInContainer) {
const result_expected_date = (expected_date_infos[step.order] ?
this.xmlService.parseExpectedDate(expected_date_infos[step.order], {...ram_order }):
undefined) as AnyObject;
if (!result_expected_date) {
return this.xmlService.response1102(ram_order);
} else {
if (typeof (result_expected_date) !== 'boolean') {
toBeUpdatedSteps.push({ expected_date: result_expected_date['expected_date_adjustment'] , step_id: step.id });
flow.xml_expected_dates[expected_date_infos[step.order].field_name] = result_expected_date['expected_date'];
}
}
}
// Check if expected date is higher than next step
for(let order = 0; order < toBeUpdatedSteps.length - 1; order++) {
if (moment(toBeUpdatedSteps[order].expected_date).isAfter(moment(toBeUpdatedSteps[order + 1].expected_date))) {
return this.xmlService.response1102(ram_order);
}
}
// Update expected dates
// eslint-disable-next-line @typescript-eslint/no-misused-promises
toBeUpdatedSteps.forEach(async (step: AnyObject) => {
await this.flow_journey_point_repo.updateById(step.step_id, { expected_date: step.expected_date });
});
// Update expected dates for flow
await this.flow_repo.updateById(flow.id, { xml_expected_dates: flow.xml_expected_dates });
return true;
}
/**
* Update flow information by id.
* @param id The flow id.
* @param flow The new information.
*/
async updateByIdOrIdentifier(id: number, payload: FlowDto, options: Options = {}): Promise<Flow> {
options.forUpdateReferences = false;
if (payload?.reference_1 !== undefined || payload?.reference_2 !== undefined || payload?.reference_3 !== undefined) {
// for update references we allow to update in any flow status but only three of those fields.
// #41542 - [Flow] Addition of internal reference fields
options.forUpdateReferences = true;
payload = new FlowDto({
id: payload.id,
reference_1: payload.reference_1,
reference_2: payload.reference_2,
reference_3: payload.reference_3,
});
}
const current_flow = await this.getFlowById(id, options);
payload.trade_lane_id = payload.trade_lane_id || current_flow.trade_lane_id;
payload.flow_default_id =
payload.flow_default_id || (current_flow as Flow).flow_default_id;
await this._validateDefaultFlow(payload);
// update the flow.
await this.flow_repo.updateById(id, payload);
// return to write logs
return current_flow as Flow;
}
/**
* Create or update a reference personas.
* @param id The ID of the flow.
* @param data The data.
*/
async upsertRefPersona(id: number, data: { ref_personas: FlowPersonaDto[] }) {
const { ref_personas } = data;
let company_identifiers = ref_personas.map(rp => {
rp.name = rp.company_name;
return rp.company_identifier;
});
let countFlowPersonas = 0;
const validatedActions: unknown[] = [];
company_identifiers = compact(company_identifiers);
if (company_identifiers.length) {
const mapping_personas = await this.comp_repo.getPersonasByIdOrIdentifier(
company_identifiers as string[],
);
ref_personas.forEach(rp => {
if (!rp.company_identifier) {
return; // next
}
if (!mapping_personas[rp.company_identifier]) {
throw new EntityNotFoundError(
this.comp_repo.entityClass,
rp.company_identifier,
);
}
if (
mapping_personas[rp.company_identifier].status !==
Status.Company.Active
) {
throw new EntityNotActiveError(
this.comp_repo.entityClass,
rp.company_identifier,
);
}
if (
!mapping_personas[rp.company_identifier].persona_ids.includes(
rp.persona_id,
)
) {
throw new HttpErrors.BadRequest(
`Company ${rp.company_identifier} don't have persona ${rp.persona_id}.`,
);
}
rp.name =
rp.company_name ?? mapping_personas[rp.company_identifier].name;
rp.company_id = mapping_personas[rp.company_identifier].id;
delete rp.company_name;
delete rp.company_identifier;
validatedActions.push(this.validateFlowPersona(rp.id, id, rp.persona_id));
if (!rp.id && !rp.deleted) {
countFlowPersonas = countFlowPersonas + 1;
}
});
}
const totalExistingFlowPersonas = (await this.flow_persona_repo.count({ flow_id: id })).count;
const number_personas_limit = +(process.env.NUMBER_PERSONA_LIMIT ?? 0);
if (countFlowPersonas + totalExistingFlowPersonas > number_personas_limit) {
throw new HttpErrors.BadRequest(
`Allowed limit for persona reached. Please remove some persona for the flow.`,
);
}
await Promise.all(validatedActions);
return this.populateFlowData(id, ref_personas, this.flow_persona_repo);
}
/**
* @param {number} id Flow Persona Id
* @param {number} flow_id Flow Id
* @param {number} persona_id Persona Id
*/
async validateFlowPersona(id: number, flow_id: number, persona_id: number) {
// In this function we need to check one flow just have only one shipper or consignee
if (Constants.doNotDuplicatedPersonas.includes(persona_id)) {
const where: AnyObject = {
flow_id,
persona_id,
};
if (id) {
where['id'] = { neq: id };
}
const existingFlowPersona = await this.flow_persona_repo.findOne({ where });
if (existingFlowPersona) {
const persona = await this.persona_repo.findById(persona_id);
throw new HttpErrors.BadRequest(
`Flow ${flow_id} have more than one ${persona.title}.`,
);
}
}
}
/**
* Get list flow based on filter.
* @param options The options.
*/
async find(options: Options): Promise<BaseResponses<FlowView>> {
this.addExtraFilter();
const filter_builder = new FilterBuilder<FlowView>();
filter_builder.filter = this.filter_builder.filter;
return this.flowview_repo.fillRelation(filter_builder);
}
/**
* Get flow by id or identifier.
* @param id The flow id.
* @param options The options.
*/
async getByIdOrIdentifier(id: number, options: Options): Promise<Flow> {
// only get histories for step 2 UI.
if (options?.step === Constants.FlowStep.Two) {
this.addExtraFilterForHistories();
}
const current_flow = await super.getByIdOrIdentifier(id, options);
return current_flow;
}
/**
* Add extra filter for histories and relations
*/
addExtraFilterForHistories() {
this.filter_builder.include({
relation: 'histories',
scope: {
order: ['created_date DESC'],
include: [
{
relation: 'company',
scope: {
fields: {
id: true,
name: true,
},
},
},
],
},
});
}
/**
* Delete the flow with id.
* @param id The flow id.
* @param options The options.
*/
async deleteByIdOrIdentifier(id: number | string, options?: Options) {
this.addWhereIdOrIdentifier(id);
this._addIncludeCreator(this.filter_builder);
const current_flow = await this.flow_repo.findOne(
this.filter_builder.build(),
);
if (!current_flow) {
throw new EntityNotFoundError(this.flow_repo.entityClass, id);
}
// Any New/InProgress/Inactive can be deleted
if (
![Status.Flow.New, Status.Flow.InProgress, Status.Flow.Inactive].includes(
current_flow.status,
)
) {
throw new HttpErrors.BadRequest(
`Only allow delete New or InProgress or Inactive flow!`,
);
}
await this.flow_repo.deleteById(current_flow.id);
current_flow.activity = {
str: 'User {1} {2} {3}', //User [First Name Last Name] [activity] [Flow Name]
args: [
'Delete Flow',
current_flow?.creator?.name ?? '',
'deleted',
current_flow.name
]
};
return current_flow;
}
/**
* Activate the flow by id.
* @param id The flow id.
* @param options The options.
*/
async activateFlowById(id: number, options?: Options) {
const current_flow = await super.activateFlowById(id, options);
await this.sendNotifications(current_flow, {
template: Constants.Email.InviteCompanyToValidateTheFlow,
key: Constants.Notification.FlowActivated,
step1: true, // First sending to Shipper or Logistics Service Provider
});
return current_flow;
}
/**
*Get company from user id
* @param id
*/
async getCompanyFromCreatorId(id: number) {
const filter_builder = new FilterBuilder<User>();
this.buildExtraFilterGetCompany(filter_builder);
const creator = await this.user_repo.findById(id, filter_builder.build());
return creator.company;
}
/**
* Build addtional relations
* @param {FilterBuilder<User>} filter_builder
*/
buildExtraFilterGetCompany(filter_builder: FilterBuilder<User>) {
filter_builder.include({
relation: 'company',
scope: {
fields: {
id: true,
name: true,
},
},
});
}
/**
* Add extra filter
* @param {Options} options?
*/
addExtraFilter(options?: Options) {
super.addExtraFilter(options);
if (
options?.step === Constants.FlowStep.Two ||
options?.step === Constants.FlowStep.Four
) {
this.filter_builder.include({
relation: 'personas',
scope: {
fields: {
id: true,
name: true,
persona_id: true,
company_id: true,
flow_id: true,
status: true,
validated_date: true,
},
order: ['order ASC', 'id ASC'],
include: [
{
relation: 'persona',
},
{
relation: 'company',
scope: {
fields: {
id: true,
name: true,
identifier: true,
privacy_status: true,
},
},
},
],
},
});
}
}
/**
* Sends mail to all companies using the provided id and options.
*
* @param {number} id - the id used to identify the companies
* @param {AnyObject} options - the options object containing template, key, and cancellation flag
* @return {Promise<void>} a Promise that resolves when the mail is sent to all companies
*/
async sendMailToAllCompanies(id: number, options: AnyObject = {}): Promise<void> {
const flow = await this.flow_repo.findByIdWithActiveStatus(id, { fields: ['id', 'name', 'cancelled_reason'] });
await this.sendNotifications(flow as Flow, options);
}
/**
* Sets vessel data to the given action object based on the form ID and form data.
*
* @param {AnyObject} action - The action object to set vessel data to.
* @param {AnyObject} [options] - Optional options object.
* @param {AnyObject} [options.VesselData] - Optional vessel data object.
* @return {AnyObject} The modified action object with vessel data set.
*/
setVesselDataToAction(action: AnyObject, options?: AnyObject): AnyObject {
let key = '';
if (action.form_id === Constants.Form.VesselArrival && action?.form_data?.origin && action?.form_data?.arrival) {
key = action?.form_data?.origin + '_' + action?.form_data?.arrival;
} else if (action.form_id === Constants.Form.VesselDeparture && action?.form_data?.departure && action?.form_data?.destination) {
key = action?.form_data?.departure + '_' + action?.form_data?.destination;
}
if (options?.VesselData[key] && options?.VesselData[key]['Vessel_BookingRef']) {
for(const container_no of Object.keys(options?.VesselData[key]['Vessel_BookingRef'])) {
if (!action?.form_data) {
action.form_data = {};
}
if (!action?.form_data?.vessel_booking_ref) {
action.form_data.vessel_booking_ref = {};
}
action.form_data.vessel_booking_ref[container_no] = options.VesselData[key]['Vessel_BookingRef'][container_no] ?? '';
}
}
if (options?.VesselData[key]) {
action.form_data = { ...action.form_data, origin: options?.VesselData[key]['LoadG4code_UN'] ?? '' };
action.form_data = { ...action.form_data, arrival: options?.VesselData[key]['UnLoadG4code_UN'] ?? '' };
action.form_data = { ...action.form_data, vessel_voyage: options?.VesselData[key]['VesselVoyage'] ?? '' };
action.form_data = { ...action.form_data, vessel_carrier_name: options?.VesselData[key]['VesselCarrier_Name'] ?? '' };
action.form_data = { ...action.form_data, vessel_booking_ref: action.form_data.vessel_booking_ref ?? '' };
}
return action;
}
/**
* Toggle flow notification
* @param id The flow id.
* @param options The options.
*/
async toggleFlowNotification(id: number, options?: Options) {
const currentFlow = await this.flow_repo.findById(id, {
fields: ['id'],
}, options);
if (!currentFlow) {
throw new EntityNotFoundError(this.flow_repo.entityClass, id);
}
// Toggle flow notification
const currentFlowNotification = await this.flow_notification_repo.findOne({
where: {
flow_id: currentFlow.id,
created_by: this.current_user.id,
}
}, options);
if (currentFlowNotification) {
await this.flow_notification_repo.deleteById(currentFlowNotification.id, options);
} else {
await this.flow_notification_repo.create({
flow_id: currentFlow.id,
created_by: this.current_user.id,
}, options);
}
return true;
}
}
|