All files / src/services flow-validation.service.ts

8.04% Statements 34/423
0% Branches 0/677
2% Functions 1/50
7.8% Lines 32/410

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  1x 1x             1x         1x 1x   1x 1x 1x                             1x 1x   1x 1x     1x 17x         17x   17x   17x   17x   17x   17x   17x   17x   17x   17x   17x   17x     17x   17x       17x   17x   17x   17x                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  
import { FlowView } from '@logchain/models/views';
import { bind, /* inject, */ BindingScope, service } from '@loopback/core';
import {
  EntityNotFoundError,
  FilterBuilder,
  IsolationLevel,
  Options,
  repository,
} from '@loopback/repository';
import {
  HttpErrors,
  SchemaObject,
  validateValueAgainstSchema,
} from '@loopback/rest';
import { compact, isEmpty, omit, remove, uniq } from 'lodash';
import { BaseFlowService, CategoryService, DocumentService } from '.';
import { CreateFlowRequest } from '../components/fabric/types';
import { Constants } from '../configs';
import { BaseResponses, Company, Flow, FlowAction, FlowJourneyPoint, FlowPersona, Status } from '../models';
import {
  CategoryRepository,
  CompanyLocationRepository,
  CompanyPersonaRepository,
  DocumentRepository,
  FlowActionRepository,
  FlowCategoryRepository,
  FlowGroupRepository,
  FlowJourneyPointRepository,
  FlowPersonaRepository,
  FlowReferenceRepository,
  FlowViewRepository,
  PersonaRepository,
  VerificationRepository,
} from '../repositories';
import { FlowDiscussionRepository } from '../repositories/flow-discussion.repository';
import { FlowRepository } from '../repositories/flow.repository';
import { AnyObject, Identifier, NeededInfo } from '../types';
import { DocumentDto, FlowDto, FlowJourneyPointDto } from '@logchain/dtos';
import { StringUtils } from '@logchain/utils';
 
@bind({ scope: BindingScope.TRANSIENT })
export class FlowValidationService extends BaseFlowService<Flow> {
  where_clause = '';
  flow_personas: FlowPersona[];
  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,
    @repository(VerificationRepository)
    public validation_repo: VerificationRepository,
    @repository(DocumentRepository)
    public document_repo: DocumentRepository,
    @repository(CategoryRepository)
    public category_repo: CategoryRepository,
    @repository(FlowCategoryRepository)
    public flow_category_repo: FlowCategoryRepository,
    /* ----- FLOW REPOSITORY ----- */
    @service()
    public document_service: DocumentService,
    @service()
    public category_service: CategoryService,
 
    /* ----- OTHER REPOSITORY ----- */
    @repository(PersonaRepository)
    public persona_repo: PersonaRepository,
    @repository(CompanyLocationRepository)
    public comp_location_repo: CompanyLocationRepository,
    @repository(CompanyPersonaRepository)
    public comp_persona_repo: CompanyPersonaRepository,
  ) /* ----- OTHER REPOSITORY ----- */ {
    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.
   */
  async ensureRightAccessRecord(): Promise<void> {
    const filter = this.filter_builder.build();
    const filter_persona = new FilterBuilder<FlowPersona>({
      fields: ['id', 'flow_id', 'company_id', 'validated_date', 'status'],
      where: {
        company_id: this.current_user.company_id,
      },
    });
 
    if ((filter as AnyObject)?.where?.actual_date) {
      filter_persona.impose({
        validated_date: (filter as AnyObject)?.where?.actual_date,
      });
 
      delete (filter as AnyObject)?.where?.actual_date;
    }
 
    if ((filter as AnyObject)?.where?.status) {
      filter_persona.impose({
        status: (filter as AnyObject)?.where?.status,
      });
 
      delete (filter as AnyObject)?.where?.status;
    }
 
    this.flow_personas = await this.flow_persona_repo.find(
      filter_persona.build(),
    );
 
    const flow_ids = this.flow_personas.map(persona => persona.flow_id);
    this.filter_builder.impose({
      id: {
        inq: flow_ids,
      },
      status: {
        inq: [
          Status.Flow.ForValidation,
          Status.Flow.Validated,
          Status.Flow.Rejected,
          Status.Flow.Live,
        ],
      },
    });
  }
 
  /**
   * Get list flow for validation based on filter.
   * @param options The options.
   */
  async find(options?: Options): Promise<BaseResponses<FlowView>> {
    const filter_builder = new FilterBuilder<FlowView>();
    filter_builder.filter = this.filter_builder.filter ?? {};
    filter_builder.include({
      relation: 'trade_lane',
      scope: {
        fields: ['id', 'name', 'description', 'pol_code', 'pod_code'],
      },
    });
    filter_builder.include({
      relation: 'company',
      scope: {
        fields: ['id', 'identifier', 'name'],
      },
    });
    // This is stupid but our db structure can not solve this problem so we need to do like this.
    const status_order = filter_builder.filter.order?.find(value => value.includes('status_name')) ?? undefined;
    if (status_order) {
      const [, direction] = status_order.split(' ');
      filter_builder.filter.order = [`persona_statuses.${this.current_user.company_id} ${direction}`];
    }
    // ------------------------------
 
    const resl = await this.flowview_repo.findWithPaging(
      filter_builder.build(),
    );
 
    // This is stupid but our db structure can not solve this problem so we need to do like this.
    resl.data.every(flow => {
      flow.status = flow.persona_statuses[this.current_user.company_id.toString()];
      flow.status_name = new FlowDto({status: flow.status}).status_name() ?? '';
      return flow;
    });
    // ------------------------------
 
    return resl;
  }
 
  /**
   * Get flow by id or identifier.
   * @param id The flow id.
   * @param options The options.
   */
  async getByIdOrIdentifier(id: number, options: Options) {
    // Process load data for flow owner and step owner
    // If current_user is flow owner and not validated yet we process it as normal
    // If current_user is flow owner and already validated the flow we swap the company between flow owner and step owner and continue as normal
    if (options?.flow_persona_id) { // In case validate for other company
      const curFlow = await this.flow_repo.findById(id);
      const flow_persona_owner = await this.flow_persona_repo.findOne({
        where: { flow_id: id, company_id: curFlow.company_id },
      });
      if (!flow_persona_owner) {
        throw new HttpErrors.BadRequest(`Flow owner not found! Flow id: ${id}`);
      }
      const step_persona_owner = await this.flow_persona_repo.findById(options?.flow_persona_id);
      if (!step_persona_owner) {
        throw new HttpErrors.BadRequest(`Step owner not found! flow_persona_id: ${options?.flow_persona_id}`);
      }
      // If current company is not step owner we need to check if it is flow owner
      if (this.current_user.company_id !== step_persona_owner?.company_id) {
        if (this.current_user.company_id === flow_persona_owner?.company_id) {
          // Switch company to be validated for current user.
          const toBeValidatedCompany = await this.comp_repo.findById(step_persona_owner.company_id);
          if (!toBeValidatedCompany) {
            throw new EntityNotFoundError(this.comp_repo.entityClass, step_persona_owner.company_id);
          }
          await this._swapCompany(toBeValidatedCompany);
        }
      }
    }
    // If current company is not both step owner and flow owner we will return null data.
    // -----------------------------------------------
    const stmt: {
      sql: string;
      params: number[];
    } = {
      sql: '',
      params: [id, this.current_user.company_id],
    };
 
    if (!options.step || options.step === Constants.FlowValidationUIStep.One) {
      stmt.sql = 'SELECT get_flow_validation_by_id($1, $2) as data;';
      
      const flow = await this.flow_repo.execute(stmt.sql, stmt.params);
      if (!flow?.length || !flow[0].data || !flow[0].data.journey_points) {
        throw new EntityNotFoundError(this.flow_repo.entityClass, id);
      }
 
      // Skip step-0
      if (flow[0].data?.journey_points?.length) {
        flow[0].data.journey_points = flow[0].data.journey_points.filter((jp: FlowJourneyPoint) => jp.order !== 0 );
      }
 
      // Get all categories of current company
      flow[0].data.categories = await this.category_repo.find({
        fields: ['id', 'name'],
        where: {
          company_id: this.current_user.company_id,
          status: Status.Category.Active,
        },
      });
 
      // Get all categories of flow
      flow[0].data.available_categories = await this.category_service.getAvailable(id);
 
      return flow[0].data;
    }
 
    if (options.step === Constants.FlowValidationUIStep.Two) {
      stmt.sql = 'SELECT get_detail_flow_validation_by_id($1, $2, $3)  as data;';
      stmt.params.push(options.step_id);
      
      const flow = await this.flow_repo.execute(stmt.sql, stmt.params);
      if (!flow?.length || !flow[0].data || !flow[0].data.journey_points) {
        throw new EntityNotFoundError(this.flow_repo.entityClass, id);
      }
 
      // Skip step-0
      if (flow[0].data?.journey_points?.length) {
        flow[0].data.journey_points = flow[0].data.journey_points.filter((jp: FlowJourneyPoint) => jp.order !== 0 );
      }
 
      flow[0].data.journey_points = await this.validateStepData(id, flow[0].data.journey_points);
 
      return flow[0].data;
    }
 
    if (options.step === Constants.FlowValidationUIStep.Three) {
      const flow = await this.flow_repo.findById(id);
      const flow_persona = await this.flow_persona_repo.findOne({
        where: {
          flow_id: flow.id,
          company_id: this.current_user.company_id,
        },
      });
      const histories = await this.flow_discussion_repo.findOne({
        where: {
          flow_id: flow.id,
          company_id: this.current_user.company_id,
        },
        order: ['created_date DESC'],
      });
      const res = (await this.flow_repo.execute(
        'SELECT get_journey_points_can_access($1, $2) as journey_points',
        [id, this.current_user.company_id],
      )) as {
        journey_points: AnyObject[];
      }[];
 
      // Throw error if can not get journey points
      if (!res.length || !res[0].journey_points) {
        throw new HttpErrors.BadRequest('Can not get journey points!');
      }
 
      let journey_points = await this.validateStepData(id, res[0].journey_points);
 
      // Skip step-0
      journey_points = journey_points.filter((jp: AnyObject) => jp.order !== 0 );
 
      const resFlowCompanies = await this.flow_repo.execute(
        'SELECT get_companies_by_flow_id($1) as companies',
        [id],
      ) as {
        companies: AnyObject[];
      }[];
 
      return {
        id: flow.id,
        name: flow.name,
        status: flow?.status,
        validate_status: flow_persona?.status,
        description: flow.description,
        remarks: histories ? histories.comment : '',
        companies: resFlowCompanies[0].companies,
        journey_points,
      };
    }
  }
  
  /**
   * Check if all steps of flow were finished input data or not
   * @param  {number} id
   * @param  {AnyObject[]} journey_points
   */
  async validateStepData(id: number, journey_points: AnyObject[]) {
    for (const journey_point of journey_points) {
      const resl = (await this.flow_repo.execute(
        'SELECT get_action_to_update($1, $2, $3) as actions',
        [id, journey_point.id, this.current_user.company_id],
      )) as {
        actions: FlowAction[];
      }[];
 
      if (!resl?.length || !resl[0].actions.length) {
        throw new HttpErrors.BadRequest(
          `Can't not update the action. Not Match Condition`,
        );
      }
 
      const actions = resl[0].actions;
      journey_point.status = true;
      for (const action of actions) {
        if (action.readonly) {
          continue;
        }
        // build schema based on needed_info
        const { schema, omit_fields } = this._buildSchema(
          action.needed_info,
          true,
        );
        try {
          // validate input
          await validateValueAgainstSchema(
            omit(action.form_data, omit_fields),
            schema,
          );
        } catch (error) {
          console.log(error.details);
          journey_point.status = false;
          break;
        }
      }
      if (journey_point?.persona?.id) {
        journey_point.locations = await this.comp_location_repo.getLocationsByCompanyId(
          journey_point.company_id,
          journey_point?.persona?.id ?? 0,
        );
        // Only check this if current user is step owner
        if (journey_point.accesses?.length && journey_point.company_id === this.current_user.company_id) {
          // If current location of journey point is not in activated locations => invalid step
          journey_point.status = journey_point.status && (journey_point.locations.filter(
            (location: AnyObject) => location.id === journey_point?.location_data?.id,
          ).length > 0);
        }
      }
    }
 
    return journey_points;
  }
 
  /**
   * Updates the flow information globally. Updates possible are:
   * - Validate or Reject a flow
   * - Give remarks to a flow
   * @param id The flow id
   * @param options The options.
   */
  async updateById(id: number, data: AnyObject) {
    const tx = await this.flow_repo.beginTransaction(
      IsolationLevel.SERIALIZABLE,
    );
 
    try {
      if (data?.flow_persona_id) {
        // Flow owner validate for Logistic Provider
        const curFlow = await this.flow_repo.findOne({
          where: { id },
          include: [{ relation: 'personas' }],
        });
        // Check flow exist
        if (!curFlow) {
          throw new EntityNotFoundError(this.flow_repo.entityClass, id);
        }
        
        // Check right access of current user for this flow. It must be flow owner
        if (curFlow?.company_id !== this.current_user.company_id) {
          throw new HttpErrors.Forbidden('You don\'t have right access');
        }
    
        // Check flow persona exist
        const flow_persona = curFlow?.personas?.find((p) => p.id === data.flow_persona_id);
        if (!flow_persona) {
          throw new EntityNotFoundError(this.flow_persona_repo.entityClass, data.flow_persona_id);
        }
        if (!Constants.personas_allowed_validated_by_flow_owner.includes(flow_persona.persona_id)) {
          throw new HttpErrors.Forbidden('You don\'t have right access');
        }
    
        // Switch company for current user.
        const toBeValidatedCompany = await this.comp_repo.findOne({
          where: { id: flow_persona.company_id },
        });
        if (!toBeValidatedCompany) {
          throw new EntityNotFoundError(this.comp_repo.entityClass, flow_persona.company_id);
        }
    
        await this._swapCompany(toBeValidatedCompany);
      }
 
      if (data?.needed_info?.container_no) {
        // Validate duplicates.
        if (data?.needed_info?.container_no.length > new Set(data?.needed_info?.container_no).size) {
          console.log('Duplicated container number', data?.needed_info?.container_no);
          throw new HttpErrors.BadRequest(Constants.error_message_duplicated_container_no);
        }
      }
 
      if (data?.category_ids) {
        // Validate categories
        const categories = await this.category_repo.find({
          where: {
            id: {
              inq: data?.category_ids,
            },
          },
        });
        if (data?.category_ids.length !== categories.length) {
          throw new HttpErrors.BadRequest('Invalid category_ids');
        }
      }
 
      const stmt: {
        sql: string;
        params: number[];
      } = {
        sql: 'SELECT get_flow_validation_by_id($1, $2) as data',
        params: [id, this.current_user.company_id],
      };
 
      // Get Flow Information
      const resl = await this.flow_repo.execute(stmt.sql, stmt.params);
      if (!resl?.length) {
        throw new EntityNotFoundError(this.flow_repo.entityClass, id);
      }
 
      const flow = resl[0].data;
      if (!(flow.company_id === this.current_user.company_id && data.status === Status.Flow.Rejected)) {
        // We only allow the flow owner to reject the flow after it already validated the flow
        if (flow.status !== Status.Flow.ForValidation) {
          throw new HttpErrors.BadRequest(
            `Status of the flow invalid: Current status is ${Constants.flow_status_text[flow.status ?? 0]}`,
          );
        }
 
        if (flow.validate_status === Status.FlowPersona.Validated) {
          throw new HttpErrors.BadRequest(`You already validated the flow!`);
        }
      } else {
        if (flow.status === Status.Flow.Rejected) {
          throw new HttpErrors.BadRequest(`You already rejected the flow!`);
        }
      }
 
      // #33516 - [FlowValidation] Support properly rejection of a Flow
      if (data.status === Status.Flow.Rejected && !data.remarks) {
        throw new HttpErrors.BadRequest(`Missing parametes: remarks`);
      }
 
      // This block is used for validation order on validating and sending notifications
      const options: AnyObject = {};
      const flow_personas_current = await this.flow_persona_repo.find({
        fields: ['persona_id'],
        where: {
          flow_id: id,
          company_id: this.current_user.company_id ?? 0,
        }
      }) as FlowPersona[];
      
      options.step1_personas_sent = Constants.PersonasForSendingStep1;
      options.step2_personas_sent = Constants.PersonasForSendingStep2.map(((pid: number) => {
        if (!options.step1_personas_sent.includes(pid)) {
          return pid;
        }
      }));
 
      options.current_persona_ids_step1 = [];
      options.current_persona_ids_step2 = [];
      options.current_persona_ids_step3 = [];
      flow_personas_current.map(fp => {
        if (options.step1_personas_sent.includes(fp.persona_id)) {
          options.current_persona_ids_step1.push(fp.persona_id);
        }
        if (options.step2_personas_sent.includes(fp.persona_id)) {
          options.current_persona_ids_step2.push(fp.persona_id);
        }
        if (Constants.PersonasForSendingStep3.includes(fp.persona_id)) {
          options.current_persona_ids_step3.push(fp.persona_id);
        }
      });
      // ----------------------------------------------------------------------------------
      if (data.status === Status.Flow.Validated) {
        const { journey_points } = await this.getByIdOrIdentifier(id, {
          step: Constants.FlowValidationUIStep.Three,
        });
        let not_complete = true;
        if (options.current_persona_ids_step3.length === 0) {
          not_complete = journey_points.some((jp: { status: boolean, company_id: number }) => {
            // If current company is not trucking companies we only check owned steps.
            if (jp.company_id === this.current_user.company_id) {
              return !jp.status;
            }
          });
        } else {
          not_complete = journey_points.some((jp: { status: boolean }) => {
            // If current company is trucking companies we should check all steps that it joined.
            return !jp.status;
          });
        }
        if (not_complete) {
          throw new HttpErrors.BadRequest(
            `Can not validate: Not completed yet`,
          );
        }
        await this._ensurePersonaValidationOrder(id, options);
      }
 
      const tmp: {
        needed_info?: AnyObject;
        status?: number;
        validator_id?: number;
        validated_date?: Date;
      } = {};
      if (data.needed_info) {
        await this.ensureDataCorrectBasedOnCompanyPersona(
          flow,
          data.needed_info,
        );
        tmp.needed_info = data.needed_info;
      }
 
      if (data.status) {
        tmp.status = data.status;
        tmp.validator_id = this.current_user.id;
        tmp.validated_date = new Date();
      }
 
      if (!isEmpty(tmp)) {
        let toBeUpdatedFlowPersonas = await this.flow_persona_repo.find({
          where: {
            flow_id: id,
            company_id: this.current_user.company_id,
            status: {
              inq: [
                Status.FlowPersona.WaitToValidate,
                Status.FlowPersona.Rejected,
              ],
            },
          }
        });
        const step2ToBeUpdatedFlowPersonas = toBeUpdatedFlowPersonas.filter(
          flow_persona => {
            return !Constants.PersonasForSendingStep3.includes(flow_persona.persona_id);
          }
        );
 
        toBeUpdatedFlowPersonas = step2ToBeUpdatedFlowPersonas.length ? step2ToBeUpdatedFlowPersonas : toBeUpdatedFlowPersonas;
        
        toBeUpdatedFlowPersonas.map(async flow_persona => {
          const { count } = await this.flow_persona_repo.updateAll(tmp, { id: flow_persona.id }, { transaction: tx });
          
          if (count === 0) {
            throw new HttpErrors.BadRequest(
              `Validate flow failed: Not found persona match condition`,
            );
          }
        });
      }
 
      if (data.remarks || data.status) {
        await this.flow_discussion_repo.create(
          {
            flow_id: id,
            comment: data.remarks,
            status: data.status,
            company_id: this.current_user.company_id,
          },
          {
            transaction: tx,
          },
        );
      }
 
      if (data?.category_ids) {
        await this.flow_category_repo.upsertWithWhere(
          {
            flow_id: id,
            company_id: this.current_user.company_id,
          },
          {
            flow_id: id,
            company_id: this.current_user.company_id,
            category_ids: data.category_ids,
          },
          {
            transaction: tx,
          },
        );
      }
 
      if (data.status === Status.Flow.Validated) {
        // eslint-disable-next-line @typescript-eslint/no-misused-promises
        setTimeout(async () => {
          // Check current company if which step it belong to ?
          await this._sendNotificationStep2(id, flow, options);
          // ---------------------------------------------------------------------------- 
          const {
            count: exists_not_complete,
          } = await this.flow_persona_repo.count({
            flow_id: id,
            status: {
              inq: [
                Status.FlowPersona.WaitToValidate,
                Status.FlowPersona.Rejected,
              ],
            },
          });
 
          if (exists_not_complete) {
            return;
          }
 
          // Create last step (Addendum) to track changes on flow after validated.
          await this._createAddendumStep(id);
          // --------------------------------------------------------------------
 
          const sql = `SELECT * FROM get_full_flow_for_blockchain_creation($1) as data;`;
          const params = await this.flow_repo.execute(sql, [id]);
          try {
            await this.cc_service.invoke(
              'CreateFlow',
              params[0].data as CreateFlowRequest,
            );
          } catch(err) {
            await this.flow_repo.updateById(id, { status: Status.Flow.ForValidation });
            return false;
          }
          await this.flow_repo.updateById(id, { status: Status.Flow.Live });
          await this.flow_persona_repo.updateAll(
            { status: Status.Flow.Live },
            { flow_id: id },
          );
          await this.sendNotifications(flow, {
            template: Constants.Email.InformCompanyAfterFlowIsLive,
            key: Constants.Notification.FlowIsLive,
          });
 
          // Generate PDF for step-0
          const step_0_journey = params[0]?.data['journeys'].find((journey: FlowJourneyPoint) => journey.name === 'Safety Data Sheet') ?? {};
          const step_0_action_id = (step_0_journey?.['actions']) ? step_0_journey['actions'][0]['stepId'] as number : 0;
          const step_0_document = await this.document_repo.findOne({
            fields: ['id', 'flow_action_id'],
            where: {
              flow_action_id: step_0_action_id
            }
          }); 
          if (step_0_document?.id) {
            await this.document_service.updateByIdOrIdentifier(step_0_document?.id ?? 0, new DocumentDto({
              status: Status.Document.Completed,
              readonly: true, // This is mark it not to be showed in the list
              documents: [flow?.trade_lane?.safety_data_sheet ?? ''],
            }), { ignoredCompany: true });
          }
          // -----------------------
          // Fire trigger to re-update container_no of form_data
          await this.flow_persona_repo.fireTriggerUpdateContainerNoForFormData(id);
          // ----------------------------------
        }, 1000);
      } else if (data.status === Status.Flow.Rejected) {
        // #33516 - [FlowValidation] Support properly rejection of a Flow
        // eslint-disable-next-line @typescript-eslint/no-misused-promises
        setTimeout(async () => {
          // ---------------------------------------------------------------------------- 
          await this.flow_repo.updateById(id, { status: Status.Flow.Rejected });
          await this.flow_persona_repo.updateAll(
            { status: Status.Flow.Rejected }, 
            { flow_id: id, status: { nin: [Status.Flow.Validated] } }
          );
          const tmpFlow = await this.flow_repo.findByIdWithActiveStatus(id, {
            fields: ['id', 'name', 'company_id'],
            include: [
              { relation: 'company', scope: { fields: ['id', 'name'] } }
            ]
          }) as FlowDto;
          await this.sendNotifications(tmpFlow, {
            template: Constants.Email.InformCompanyAfterFlowValidationIsRejected,
            key: Constants.Notification.FlowIsCompleted,
            forCancellation: true,
            flow_company_name: tmpFlow?.company?.name ?? ''
          });
          // -----------------------
        }, 1000);
      }
 
      await tx.commit();
    } catch (error) {
      await tx.rollback();
      throw error;
    }
  }
 
  /**
   * Validate flow as other company
   * - Validate or Reject a flow
   * - Give remarks to a flow
   * @param id The flow id
   * @param options The options.
   */
  async validateFlowAsOther(id: number, flow_persona_id: number, data: AnyObject) {
    const flow = await this.flow_repo.findOne({
      where: { id },
      include: [{ relation: 'personas' }],
    });
    // Check flow exist
    if (!flow) {
      throw new EntityNotFoundError(this.flow_repo.entityClass, id);
    }
    // Check flow is for validation
    if(flow.status !== Status.Flow.ForValidation) {
      throw new HttpErrors.BadRequest('Flow is not for validation');
    }
    // Check right access of current user for this flow. It must be flow owner
    if (flow?.company_id !== this.current_user.company_id) {
      throw new HttpErrors.Forbidden('You don\'t have right access');
    }
 
    // Check flow persona exist
    const flow_persona = flow?.personas?.find((p) => p.id === flow_persona_id);
    if (!flow_persona) {
      throw new EntityNotFoundError(this.flow_persona_repo.entityClass, flow_persona_id);
    }
    if (!Constants.personas_allowed_validated_by_flow_owner.includes(flow_persona.persona_id)) {
      throw new HttpErrors.Forbidden('You don\'t have right access');
    }
 
    // Switch company for current user.
    const flow_company_name = this.current_user.company_name;
    const toBeValidatedCompany = await this.comp_repo.findOne({
      where: { id: flow_persona.company_id },
    });
    if (!toBeValidatedCompany) {
      throw new EntityNotFoundError(this.comp_repo.entityClass, flow_persona.company_id);
    }
 
    await this._swapCompany(toBeValidatedCompany);
    await this.ensureRightAccessRecord();
 
    // Send notification to the neededToBeValidated company
    await this.sendNotifications(flow as FlowDto, {
      template: Constants.Email.InformCompanyAfterFlowIsValidated,
      key: Constants.Notification.FlowIsValidated,
      company_ids: [toBeValidatedCompany.id],
      flow_company_name,
    });
 
    const remarks = data?.remarks ? data.remarks : StringUtils.format(Constants.remarks_behalf_of_the_validation, flow.name, flow_company_name);
 
    // Update flow
    return this.updateById(id, {remarks, ...data});
  }
 
  /**
   * Update info for the action in each journey points.
   * @param id The flow id.
   * @param step_id The action id.
   * @param data The data to update.
   */
  async updateStepDetails(id: number, step_id: number, data: {location_id: number, actions: AnyObject[]}) {
    // Process swapping between flow-owner and step owner
    const curStep = await this.flow_journey_point_repo.findOne({
      where: { id: step_id },
      include: [{ relation: 'flow_persona' }],
    });
    if(!curStep) {
      throw new EntityNotFoundError(this.flow_journey_point_repo.entityClass, step_id);
    }
    const curFlow = await this.flow_repo.findById(id);
    const curTruckingCompanies = await this.flow_persona_repo.find({
      where: { flow_id: id, persona_id: { inq: [Constants.Persona.TruckingCompany, Constants.Persona.Carrier]}},
      fields: ['company_id'],
    });
    const isTruckingCompany = curTruckingCompanies?.find((c) => c.company_id === this.current_user.company_id);
    // Only 3 company types can update steps
    // 1. Flow owner
    // 2. Step owner
    // 3. Trucking companies (only steps with location)
    if(curStep?.flow_persona.company_id !== this.current_user.company_id && !isTruckingCompany) {
      if (curFlow.company_id === this.current_user.company_id) {
        const toBeValidatedCompany = await this.comp_repo.findOne({
          where: { id: curStep.flow_persona.company_id },
        });
        if (!toBeValidatedCompany) {
          throw new EntityNotFoundError(this.comp_repo.entityClass, curStep.flow_persona.company_id);
        }
        // Switch company to be validated for current user.
        await this._swapCompany(toBeValidatedCompany);
      } else {
        throw new HttpErrors.Forbidden('You don\'t have right to update this step');
      }
    }
    // -------------------------------------
 
    const resl = (await this.flow_repo.execute(
      'SELECT flow_persona_id, get_action_to_update($1, $2, $3) as actions FROM flows_journey_point WHERE id = $2',
      [id, step_id, this.current_user.company_id],
    )) as {
      flow_persona_id: number,
      actions: FlowAction[];
    }[];
 
    if (!resl?.length || !resl[0].actions.length) {
      throw new HttpErrors.BadRequest(
        `Can't not update the action. Not Match Condition`,
      );
    }
 
    const actions = resl[0].actions;
    const tx = await this.flow_action_repo.beginTransaction(
      IsolationLevel.SERIALIZABLE,
    );
    try {
      await this.ensureDataCorrectBasedOnFormType(id, {
        location_id: data?.location_id ?? 0,
        flow_persona_id: resl[0].flow_persona_id,
      }, actions, data.actions, {
        transaction: tx,
      });
      await tx.commit();
    } catch (error) {
      await tx.rollback();
      throw error;
    }
  }
 
  /**
   * Validates if a container number exists on other flows.
   *
   * @param {number} id - The ID of the flow.
   * @param {string} container_no - The container number to check.
   * @return {Promise<string>} A promise that resolves to a string containing the IDs of the flows that have the same container number.
   */
  async validateContainerNoExistOnOtherFlows(id: number, container_no: string): Promise<AnyObject> {
    return this.flow_persona_repo.getFlowIdsWhichHaveSameContainerNo(id, container_no);
  }
 
  /**
   * Ensure the data is correct based on form id.
   * @param form_id The form id.
   * @param data The data.
   */
  async ensureDataCorrectBasedOnFormType(
    flow_id: number,
    locationToBeUpdated: { location_id: number, flow_persona_id: number },
    actions: FlowAction[],
    actions_input: AnyObject[],
    options?: Options,
  ) {
    const action_mapping: AnyObject = {};
    actions.forEach((current: AnyObject) => {
      action_mapping[current.id] = current;
    });
 
    const resl = (await this.flow_repo.execute(
      'SELECT get_companies_by_flow_id($1) as companies',
      [flow_id],
    )) as {
      companies: { identifier: string; persona_id: number; name: string }[];
    }[];
    if (!resl?.length) {
      throw new HttpErrors.BadRequest('Can not get companies for the flow!');
    }
 
    const companies = resl[0].companies;
    const p_tasks: Promise<void>[] = [];
    actions_input.forEach((action, idx) => {
      // don't update incase don't have any information
      if (isEmpty(omit(action, 'id'))) {
        return;
      }
 
      p_tasks[idx] = (async action_input => {
        const action_db = action_mapping[action.id];
        if (!action_db) {
          throw new HttpErrors.BadRequest(`Invalid action id: ${action.id}`);
        }
 
        // if action no need to provide any information
        const allowed_updates = action_db.needed_info.some(
          (info: AnyObject) => {
            return !info.readonly;
          },
        );
        if (!allowed_updates) {
          return;
        }
 
        if (action_input.company_other_type) {
          action_input.company_other_type = +action_input.company_other_type;
        }
 
        // build schema based on needed_info
        const { schema, omit_fields } = this._buildSchema(action_db.needed_info);
 
        // validate input
        await validateValueAgainstSchema(
          omit(action_input, omit_fields),
          schema,
        );
 
        // company other must exists in the flow.
        if (action_input.company_other) {
          this._ensureCompanyJoinedToFlow(
            companies,
            action_input.company_other,
          );
        }
 
        // delivered company must exist in the flow with TruckingCompany persona
        if (action_input.delivered_company) {
          this._ensureCompanyJoinedToFlowWithSpecificPersona(
            companies,
            action_input.delivered_company,
          );
        }
 
        // trucking company must exist in the flow with TruckingCompany persona
        if (action_input.trucking_company) {
          this._ensureCompanyJoinedToFlowWithSpecificPersona(
            companies,
            action_input.trucking_company,
          );
        }
 
        // customer company must exist in the flow
        if (action_input.customer) {
          this._ensureCompanyJoinedToFlow(companies, action_input.customer);
        }
 
        // received company must exist in the flow
        if (action_input.received_company) {
          this._ensureCompanyJoinedToFlow(
            companies,
            action_input.received_company,
          );
        }
 
        const { actor } = action_input;
        const user_mapping = await this.ensureUserBelongToCompany(
          [actor],
          this.current_user.company_id,
          options,
        );
 
        const tmp: AnyObject = {};
        if (user_mapping[actor]) {
          tmp['actor_id'] = user_mapping[actor];
        }
 
        if (!isEmpty(omit(action_input, omit_fields))) {
          tmp['form_data'] = omit(action_input, omit_fields);
        }
 
        await this.flow_action_repo.updateById(action.id, tmp, options);
      })(action);
    });
 
    if (locationToBeUpdated?.location_id) {
      p_tasks.push(this.flow_persona_repo.updateNeedInfo(locationToBeUpdated.flow_persona_id, {
        location: locationToBeUpdated.location_id,
      }, options));
    }
 
    return Promise.all(p_tasks);
  }
 
  /**
   * Ensure the identifiers is belong to the company.
   * @param identifiers The array of identifiers.
   * @param company_id The company id.
   */
  async ensureUserBelongToCompany(
    identifiers: Identifier[],
    company_id: number,
    options?: Options,
  ) {
    identifiers = identifiers.flat();
    const users = await this.user_repo.find(
      {
        fields: ['id', 'identifier', 'company_id', 'status'],
        where: {
          status: Status.User.Active,
          company_id,
          identifier: {
            inq: identifiers,
          },
        },
      },
      options,
    );
 
    const mapping: AnyObject = {};
    users.forEach(u => {
      remove(identifiers, ele => {
        mapping[`${u.identifier}`] = u.id;
        return ele === u.identifier;
      });
    });
 
    identifiers = compact(identifiers);
    if (identifiers.length) {
      throw new HttpErrors.NotFound(
        `${this.user_repo.entityClass.modelName
        } not exists with identifiers: ${uniq(identifiers)}`,
      );
    }
 
    return mapping;
  }
 
  /**
   * Ensure the data is correct based on form id.
   * @param form_id The form id.
   * @param data The data.
   */
  async ensureDataCorrectBasedOnCompanyPersona(
    flow: AnyObject,
    needed_info: NeededInfo,
  ) {
    if (!flow.needed_info) {
      return;
    }
 
    const { schema, omit_fields } = this._buildSchema(
      flow.needed_info,
    );
 
    await validateValueAgainstSchema(
      omit(needed_info, omit_fields),
      schema,
    );
 
    if (needed_info.location) {
      const exists = await this.comp_location_repo.existsWithCompany(
        this.current_user.company_id,
        needed_info.location,
      );
 
      if (!exists) {
        throw new EntityNotFoundError(
          this.comp_location_repo.entityClass,
          needed_info.location,
        );
      }
    }
 
    if (needed_info.delivered_by) {
      const { count } = await this.user_repo.count({
        company_id: this.current_user.company_id,
        identifier: needed_info.delivered_by,
      });
 
      if (!count) {
        throw new EntityNotFoundError(
          this.user_repo.entityClass,
          needed_info.delivered_by,
        );
      }
    }
  }
 
  /**
   * Ensure company joined to the flow.
   * @param companies The companies array.
   * @param identifier The identifier of company
   */
  private _ensureCompanyJoinedToFlow(
    companies: { identifier: string; persona_id: number; name: string }[],
    identifier: string,
  ) {
    const found = companies.find(company => {
      return company.identifier === identifier;
    });
 
    if (!found) {
      throw new HttpErrors.BadRequest(
        `Company with identifier ${identifier} must exists in the flows`,
      );
    }
  }
  
  /**
   * Make sure each company persona must validate flow in a corrent order.
   * @param  {number} id
   * @param  {Options} options
   */
  private async _ensurePersonaValidationOrder(id: number, options?: Options ) {
    // Count all personas in flow
    const {
      count: step1_invalidated_count,
    } = await this.flow_persona_repo.count({
      flow_id: id,
      persona_id: { inq: options?.step1_personas_sent ?? [] },
      status: { inq: [Status.FlowPersona.WaitToValidate, Status.FlowPersona.Rejected] },
    });
    const {
      count: step2_invalidated_count,
    } = await this.flow_persona_repo.count({
      flow_id: id,
      persona_id: { inq: options?.step2_personas_sent ?? []},
      status: { inq: [Status.FlowPersona.WaitToValidate, Status.FlowPersona.Rejected] },
    });
 
    // Count all personas in flow for current company
    const {
      count: step1_invalidated_count_for_current,
    } = await this.flow_persona_repo.count({
      flow_id: id,
      persona_id: { inq: options?.current_persona_ids_step1 ?? [] },
      status: { inq: [Status.FlowPersona.WaitToValidate, Status.FlowPersona.Rejected] },
    });
    const {
      count: step2_invalidated_count_for_current,
    } = await this.flow_persona_repo.count({
      flow_id: id,
      persona_id: { inq: options?.current_persona_ids_step2 ?? [] },
      status: { inq: [Status.FlowPersona.WaitToValidate, Status.FlowPersona.Rejected] },
    });
 
    if (step1_invalidated_count) {
      const persona_texts = options?.step1_personas_sent.map((pid: number) => Constants.PersonaLabel[pid]);
      if (!step1_invalidated_count_for_current) {
        throw new HttpErrors.BadRequest(
          `Can not validate: Please wait for ${persona_texts.join(', ')} finish their validation first`,
        );
      }
    } else if (step2_invalidated_count) {
      const persona_texts = options?.step2_personas_sent.map((pid: number) => Constants.PersonaLabel[pid]);
      if (!step2_invalidated_count_for_current) {
        throw new HttpErrors.BadRequest(
          `Can not validate: Please wait for ${persona_texts.join(', ')} finish their validation first`,
        );
      }
    }
  }
 
  /**
   * Ensure company joined to the flow with specified persona id.
   * @param companies The companies array.
   * @param identifier The identifier of company
   * @param persona_id The persona id.
   */
  private _ensureCompanyJoinedToFlowWithSpecificPersona(
    companies: { identifier: string; persona_id: number; name: string }[],
    identifier: string,
  ) {
    const found = companies.find(company => {
      return (
        company.identifier === identifier && Constants.TruckingPersonas.includes(company.persona_id)
      );
    });
 
    if (!found) {
      throw new HttpErrors.BadRequest(
        `Company with identifier ${identifier} dose must exists in the flows with persona is Trucking Company`,
      );
    }
  }
  
  /**
   * Build Schema
   * @param  {AnyObject} needed_info
   * @param  {} additional_properties=false
   */
  private _buildSchema(needed_info: AnyObject, additional_properties = false) {
    const properties: SchemaObject = {};
    const omit_fields: string[] = ['id'];
    const needed_info_schema: SchemaObject = {
      properties: properties,
      required: [],
      additionalProperties: additional_properties,
    };
 
    needed_info.forEach(
      (i: {
        key: string;
        type: string;
        required?: boolean;
        readonly: boolean;
      }) => {
        properties[`${i.key}`] = { type: i.type };
        if (i.required) {
          needed_info_schema.required?.push(i.key);
        }
 
        if (i.readonly) {
          omit_fields.push(i.key);
        }
      },
    );
    return { schema: needed_info_schema, omit_fields };
  }
  
  /**
   * Send notification to companies in step 2
   * @param {number} id
   * @param {Flow} flow
   */
  private async _sendNotificationStep2(id: number, flow: Flow, options?: Options) {
    const whereStep1 = { persona_id: { inq: options?.step1_personas_sent ?? [] } };
    const whereStep2 = { persona_id: { inq: options?.step2_personas_sent ?? [] } };
 
    /**
      Line1: Shipper or Logistics Service Provider
      Line2: Agent, Bulk Storage Terminal, Consignee, ISO Tank Depot, Port, Railhead, Shipping Line
      Line3: Carrier, Trucking
      - Line1 & Line2 can validate same time only Line3 must be validate in another time.
      - Ex: A company with personas Shipper, Agent and Trucking, that company will validate for the first time for Shipper and Agent
      - Then go out and come back to validate for Trucking persona.
    */
    if (options?.current_persona_ids_step1?.length) {
      const {
        count: step1_invalidated_count,
      } = await this.flow_persona_repo.count({
        flow_id: id,
        ...whereStep1,
        status: { inq: [Status.FlowPersona.WaitToValidate, Status.FlowPersona.Rejected] },
      });
      const step2_persona_ids = options?.step2_personas_sent.map((p_id: number) => {
        // We don't send again to personas already validated in Line1
        if (!options?.step1_personas_sent.includes(p_id)) {
          return p_id;
        }
      });
      if (step1_invalidated_count === 0) {
        await this.sendNotifications(flow, {
          template: Constants.Email.InviteCompanyToValidateTheFlow,
          key: Constants.Notification.FlowActivated,
          step2: true,
          personasForSendingStep2: step2_persona_ids,
        });
      }
    } else if (options?.current_persona_ids_step2?.length) {
      const {
        count: step2_invalidated_count,
      } = await this.flow_persona_repo.count({
        flow_id: id,
        ...whereStep2,
        status: { inq: [Status.FlowPersona.WaitToValidate, Status.FlowPersona.Rejected] },
      });
      if (step2_invalidated_count === 0) {
        await this.sendNotifications(flow, {
          template: Constants.Email.InviteCompanyToValidateTheFlow,
          key: Constants.Notification.FlowActivated,
          step3: true, // Third sending to Trucking Companies
          personasForSendingStep3: Constants.PersonasForSendingStep3,
        });
      }
    }
  }
 
  /**
   * Creates an addendum step for a given flow ID.
   *
   * @param {number} id - The ID of the step.
   * @return {Promise<void>} - A promise that resolves when the step is created.
   */
  private async _createAddendumStep(id: number): Promise<void> {
    const step0 = await this.flow_journey_point_repo.findOne({
      fields: ['id', 'persona_id', 'flow_persona_id'],
      where: { name: Constants.safety_data_sheet_label, flow_id: id }
    });
    const group0 = await this.flow_group_repo.findOne({
      fields: ['flow_personas','journey_points'],
      where: { name: Constants.safety_data_sheet_label, flow_id: id }
    });
    const step_n = await this.flow_journey_point_repo.findOne({
      fields: ['id', 'order', 'expected_date'],
      where: { flow_id: id },
      order: ['order DESC'],
    });
    const order = step_n?.order ? step_n.order + 1 : 0;
    const lastStep = {
      name: Constants.addendum_label,
      expected_date: step_n?.expected_date,
      persona_id: step0?.persona_id,
      flow_persona_id: step0?.flow_persona_id,
      groups: [{
        name: Constants.addendum_label,
        flow_personas: group0?.flow_personas,
        journey_points: group0?.journey_points,
        order: order,
      }],
      actions: [{
        form_id: 0,
        flow_persona_id: step0?.flow_persona_id,
        title: Constants.update_expected_dates_label,
        status: Status.FlowAction.Completed,
      },
      {
        form_id: 0,
        flow_persona_id: step0?.flow_persona_id,
        title: Constants.update_container_no_label,
        status: Status.FlowAction.Completed,
      },
      {
        form_id: 0,
        flow_persona_id: step0?.flow_persona_id,
        title: Constants.cancel_container_no_label,
        status: Status.FlowAction.Completed,
      }],
      order: order,
    } as FlowJourneyPointDto;
    await this.upsertStep(id, { steps: [lastStep] });
  }
 
  
  /**
   * Swap the current user's company with the provided company.
   *
   * @param {Company} toBeValidatedCompany - The company to be validated and swapped with the current user's company.
   * @return {void} This function does not return any value.
   */
  private async _swapCompany(toBeValidatedCompany: Company): Promise<void> {
    if (!toBeValidatedCompany) {
      return
    }
    this.current_user.company_id = toBeValidatedCompany.id;
    this.current_user.company_identifier = toBeValidatedCompany.identifier;
    this.current_user.company_name = toBeValidatedCompany.name;
    this.current_user.company_personas = await this.comp_persona_repo.find({
      where: { company_id: toBeValidatedCompany.id },
    });
  }
}