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

13.62% Statements 41/301
0% Branches 0/342
2.44% Functions 1/41
13.59% Lines 39/287

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 9631x 1x 1x 1x 1x 1x 1x                                 1x 1x   1x 1x 1x 1x 1x 1x 1x   1x     1x                     1x 19x         19x   19x   19x   19x   19x   19x   19x   19x   19x   19x   19x     19x         19x   19x   19x   19x   19x   19x   19x                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        
import {Constants} from '@logchain/configs';
import {bind, /* inject, */ BindingScope, service} from '@loopback/core';
import {AnyObject, EntityNotFoundError, Filter, FilterBuilder, Options, OrClause, repository} from '@loopback/repository';
import {isEmpty} from 'lodash';
import {BaseFlowService, DocumentService} from '.';
import {BaseResponses, Flow, FlowPersona, ReportMaster, Status} from '../models';
import {
  CategoryRepository,
  CompanyLocationRepository,
  DocumentRepository,
  FlowActionNotificationRepository,
  FlowActionRepository,
  FlowCategoryRepository,
  FlowGroupRepository,
  FlowJourneyPointRepository,
  FlowPersonaRepository,
  FlowReferenceRepository,
  FlowViewRepository,
  PersonaRepository,
  ReportMasterRepository,
  ReportViewRepository,
  SearchViewRepository,
} from '../repositories';
import {FlowDiscussionRepository} from '../repositories/flow-discussion.repository';
import {FlowRepository} from '../repositories/flow.repository';
import {FlowView, ReportView, SearchView} from '@logchain/models/views';
import { DocumentDto } from '@logchain/dtos';
import { DateUtils, StringUtils } from '@logchain/utils';
import handlebars from 'handlebars';
import moment from 'moment-timezone';
import path from 'path';
import * as fs from 'fs';
import { HttpErrors } from '@loopback/rest';
import { ReplyMessage } from '@logchain/types';
import ExcelJS from 'exceljs';
 
// Helper function to format date
handlebars.registerHelper('formatDate', function (dateString: string, format: string | undefined, timeZone: string) {
  try {
    if (isEmpty(dateString)) return '';
    const date = moment.tz(dateString, timeZone);
    return date.format(format);
  } catch (err) {
    return '';
  }
});
 
@bind({scope: BindingScope.TRANSIENT})
export class FlowJourneyService extends BaseFlowService<Flow> {
  where_clause = '';
  flow_personas: FlowPersona[];
  constructor(
    /* ----- FLOW REPOSITORY ----- */
    @repository(FlowRepository)
    public flow_repo: FlowRepository,
    @repository(FlowViewRepository)
    public flowview_repo: FlowViewRepository,
    @repository(SearchViewRepository)
    public searchview_repo: SearchViewRepository,
    @repository(ReportViewRepository)
    public reportview_repo: ReportViewRepository,
    @repository(ReportMasterRepository)
    public report_master_repo: ReportMasterRepository,
    @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 ----- */
    @service()
    public document_service: DocumentService,
 
 
    /* ----- OTHER REPOSITORY ----- */
    @repository(DocumentRepository)
    public document_repo: DocumentRepository,
    @repository(PersonaRepository)
    public persona_repo: PersonaRepository,
    @repository(CompanyLocationRepository)
    public comp_location_repo: CompanyLocationRepository,
    @repository(FlowActionNotificationRepository)
    public flow_action_notification_repo: FlowActionNotificationRepository,
    @repository(CategoryRepository)
    public category_repo: CategoryRepository,
    @repository(FlowCategoryRepository)
    public flow_category_repo: FlowCategoryRepository,
  ) /* ----- 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_persona = new FilterBuilder<FlowPersona>({
      fields: ['id', 'flow_id', 'company_id', 'validated_date', 'status'],
      where: {
        company_id: this.current_user.company_id,
      },
    });
 
    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.Validated, Status.Flow.Live],
      },
    });
  }
 
  /**
   * Search flow action data based on filter.
   * @param options The options.
   */
  async search(options: Options = {}): Promise<BaseResponses<SearchView>> {
 
    // Get list of public flows
    const filter = this.filter_builder.build();
    const flows = await this.flow_repo.find({ fields: ['id'], where: filter.where });
    const flowIds = flows.map((rec: AnyObject) => rec.id);
 
    // Build search filter based on submitted filter
    this.filter_builder.filter.where = {};
    const filter_builder = new FilterBuilder<SearchView>(this.filter_builder.filter as Filter<SearchView>);
 
    // Search only on public flows
    filter_builder.impose({ flow_id: { inq: flowIds }});
 
    // Includes user filter condition
    if (!isEmpty(options.where)) {
      filter_builder.impose(options.where);
    }
 
    return this.searchview_repo.fillRelation(filter_builder, options);
  }
 
  /**
   * Show report about journey of each container.
   * @param options The options.
   */
  async report(options: Options = {}): Promise<BaseResponses<ReportView>> {
 
    // Get list of public flows
    const filter = this.filter_builder.build();
    const flows = await this.flow_repo.find({ fields: ['id'], where: filter.where });
    const flowIds = flows.map((rec: AnyObject) => rec.id);
 
    // Build search filter based on submitted filter
    this.filter_builder.filter.where = {};
    const filter_builder = new FilterBuilder<ReportView>(this.filter_builder.filter as Filter<ReportView>);
 
    // Search only on public flows
    filter_builder.impose({ flow_id: { inq: flowIds }});
 
    // Includes user filter condition
    if (!isEmpty(options.where)) {
      filter_builder.impose(options.where);
    }
 
    return this.reportview_repo.fillRelation(filter_builder, options);
  }
 
  /**
   * Export report as PDF
   * @param options The options.
   */
  async reportPDF(options: Options = {}) {
    const { res } = options;
    options.res = undefined;
    try {
      const user = await this.user_repo.findById(this.current_user.id);
      const filePath = path.join(__dirname, '..', 'components', 'aws', 'pdf-templates', user.language, 'PDF01.html');
      const source = fs.readFileSync(filePath, 'utf-8');
      const result = await this.report(options);
      const period = options?.where?.and ?? [];
      let from_date = undefined, to_date = undefined;
      period.forEach((condition: AnyObject) => {
        if (condition.expected_start) {
          from_date = condition.expected_start.gte.toISOString();
        }
        if (condition.expected_end) {
          to_date = condition.expected_end.lte.toISOString();
        }
      });
      // Process data for filter
      const filter = {
        status: Constants.report_filter_live_status_text[options?.where?.status] ?? undefined,
        from_date,
        to_date,
        container_no: options?.where?.container_no?.ilike.replace(/%/g,"") ?? undefined,
        flow_id: options?.where?.flow_id?.ilike.replace(/%/g,"") ?? undefined,
        flow_name: options?.where?.flow_name?.ilike.replace(/%/g,"") ?? undefined,
        reference_1: options?.where?.flow_reference_1?.ilike.replace(/%/g,"") ?? undefined,
        reference_2: options?.where?.flow_reference_2?.ilike.replace(/%/g,"") ?? undefined,
        reference_3: options?.where?.flow_reference_3?.ilike.replace(/%/g,"") ?? undefined,
      };
      // -----------------------
      const htmlContent = handlebars.compile(source)({
        s3BaseURL: process.env.AWS_BUCKET_NAME + '.s3.amazonaws.com',
        steps: result.data,
        filter,
        timezone: this.current_user.timezone,
      });
 
      // Configuration for html-pdf
      const pdfBuffer = await StringUtils.convertToPDF(htmlContent, this.current_user.timezone);
 
      // Set headers for PDF response
      res.setHeader('Content-Type', 'application/pdf');
      res.setHeader('Content-Disposition', 'inline; filename=output_html_pdf.pdf');
      res.send(pdfBuffer);
    } catch (error) {
      console.error('Error generating PDF:', error);
      res.status(500).send('Internal Server Error');
    }
  }
 
  /**
   * Show report-master about journey of each container.
   * @param options The options.
   */
  async reportMaster(options: Options = {}): Promise<BaseResponses<ReportMaster>> {
 
    // Get list of public flows
    const filter = this.filter_builder.build();
    const flows = await this.flow_repo.find({ fields: ['id'], where: filter.where });
    const flowIds = flows.map((rec: AnyObject) => rec.id);
 
    // Build search filter based on submitted filter
    this.filter_builder.filter.where = {};
    const filter_builder = new FilterBuilder<ReportMaster>(this.filter_builder.filter as Filter<ReportMaster>);
 
    // Search only on public flows
    filter_builder.impose({ flow_id: { inq: flowIds }});
 
    // Includes user filter condition
    if (!isEmpty(options.where)) {
      filter_builder.impose(options.where);
    }
 
    return this.report_master_repo.fillRelation(filter_builder, options);
  }
 
  /**
   * Export report-master as XLSX
   * @param options The options.
   */
  async reportMasterXLS(options: Options = {}) {
    const { res } = options;
    options.res = undefined;
    const reportMasterData = await this.reportMaster(options);
    const workbook = new ExcelJS.Workbook();
    const worksheet = workbook.addWorksheet('Report Master');
 
    // Define columns
    worksheet.columns = [
        { header: 'Job No', key: 'job_no'},
        { header: 'Cargo No', key: 'container_no' },
        { header: 'Shipping Line', key: 'pol_shipping' },
        { header: 'Booking Ref', key: 'pol_booking' },
        { header: 'Voyage', key: 'pol_voyage' },
        { header: 'POL', key: 'pol_code' },
        { header: 'POL Sailing Date', key: 'pol_etd' },
        { header: 'Trans Port', key: 'trans_code' },
        { header: 'Trans ETA', key: 'trans_eta' },
        { header: 'Trans Time', key: 'trans_time' },
        { header: 'Trans ETD', key: 'trans_etd' },
        { header: 'Trans Shipping Line', key: 'trans_shipping' },
        { header: 'Trans Voyage', key: 'trans_voyage' },
        { header: 'Trans Booking Ref', key: 'trans_booking' },
        { header: 'Consignee', key: 'consignee' },
        { header: 'POD', key: 'pod_code' },
        { header: 'POD Arrival Date', key: 'pod_eta' },
        { header: 'Final Transit Time', key: 'final_transit_time' },
        { header: 'Laden Status', key: 'flow_status_name' },
        { header: 'Comments', key: 'comments' },
    ];
 
    // Add rows
    reportMasterData.data.map((rec: AnyObject) => {
      worksheet.addRow(rec);
    });
 
    // Write to file
    const xlsBuffer = await workbook.xlsx.writeBuffer();
    console.log(`File saved as report_master_${Date.now()}.xlsx`);
 
    // Set headers for PDF response
    res.setHeader('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
    res.setHeader('Content-Disposition', `inline; filename=report_master_${Date.now()}.xlsx`);
    res.send(xlsBuffer);
  }
 
  /**
   * Precomputes the master report with the provided options.
   * @param options The options.
   */
  async precomputeReportMaster(options: Options = {}) {
    await this.flow_base_repo.precomputeReportMaster(options);
  }
 
  /**
   * 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, options);
  }
 
  /**
   * Get list flow for validation based on filter.
   * @param options The options.
   */
  async getJourneyDetailsByFlowId(id: number, step_id?: number, options?: Options) {
    const sql = `SELECT get_journey_details($1, $2, $3, $4) as data;`;
    const resl = await this.flow_repo.execute(sql, [id, this.current_user.company_id, step_id, this.current_user.id], options);
 
    if (!resl || !resl.length || isEmpty(resl[0].data.journey_points)) {
      throw new EntityNotFoundError(this.flow_repo.entityClass, id);
    }
 
    return resl[0].data;
  }
 
  /**
   * Cancel an open flow
   * @param  {number} id
   * @param  {AnyObject} payload
   */
  async cancelFlowById(id: number, payload: AnyObject) {
    // Only update cancelled_reason because we need to keep action's status "open" to find users for sending
    // If we update action to closed here we can not find users of company which are having open actions
    await this.flow_repo.updateById(id, payload);
 
    const flow = await this.flow_repo.findByIdWithActiveStatus(id, {fields: ['id', 'name', 'cancelled_reason']});
 
    await this.sendNotifications(flow, {
      template: Constants.Email.InformCompanyAfterFlowIsRejected,
      key: Constants.Notification.FlowIsCancelled,
      forCancellation: true,
    });
 
    // This update will trigger in database that update all actions and action's data to cancel
    // We just do this update after sending notifications to users of companies of open actions
    await this.flow_repo.updateById(id, {live_status: Status.LiveStatus.Rejected});
  }
  
  /**
   * Update expected dates of action's data of flow.
   *
   * @param {number} id - The ID of flow to be updated.
   * @param {AnyObject} payload - The payload to update.
   * @throws {EntityNotFoundError} If the old flow is not found.
   */
  async updateExpectedDates(id: number, payload: AnyObject) {
    const flow = await this.flow_repo.findById(id);
    if (isEmpty(flow)) {
      throw new EntityNotFoundError('Flow', 'ID');
    }
 
    const step_addendum_action = await this.flow_action_repo.findOne({
      fields: ['id'],
      where: {
        flow_id: id,
        title: Constants.update_expected_dates_label
      }
    });
    if (!step_addendum_action) {
      throw new EntityNotFoundError(this.flow_action_repo.entityClass, id);
    }
 
    try {
      await this.upsertStep(id, { steps: payload.steps });
      // eslint-disable-next-line @typescript-eslint/no-misused-promises
      setTimeout(async () => {
        const step_n_document = await this.document_repo.create({
          flow_id: id,
          company_id: this.current_user.company_id,
          name: Constants.update_expected_dates_label,
          reason_for_updating: payload.reason,
          expected_date: new Date(),
          flow_action_id: step_addendum_action.id,
          status: Status.Document.New,
          readonly: true,
          pdf_attempt: 0,
        });
        // Get all id of steps from payload.steps
        const updated_step_ids = payload.steps.map((step: AnyObject) => step.id);
 
        // Aggregate data for steps
        const arrExpectedDatesGroupByStepName = await this.flow_journey_point_repo.getExpectedDatesByStepName(id, updated_step_ids) as AnyObject;
        const arrExpectedDatesGroupByActionName = await this.flow_journey_point_repo.getExpectedDatesByActionName(id, updated_step_ids) as AnyObject;
        // -------------------------
        await this.document_service.updateByIdOrIdentifier(step_n_document?.id ?? 0, new DocumentDto({
          status: Status.Document.Completed,
          readonly: true, // This is mark it not to be showed in the list
          documents: payload?.uri ? [payload.uri] : [],
        }), { ignoredCompany: true, steps: arrExpectedDatesGroupByStepName, forUpdateAddendum: true });
        // -------------------------------------------------------------
 
        // Send notifications to all companies that still have open actions.
        // Query to get all company_id with actions are still open.
        const companies_has_open_actions = await this.flow_action_repo.find({
          fields: ['company_id'],
          where: {
            status: Status.FlowAction.New,
            flow_id: id,
          },
        });
        if (companies_has_open_actions?.length) {
          const companies_has_open_actions_ids = companies_has_open_actions.map((item) => item.company_id);
          const trucking_company = await this.flow_persona_repo.findOne(
            {
              fields: ['id', 'company_id'],
              where: { flow_id: id, persona_id: { inq: [Constants.Persona.TruckingCompany] } },
            }
          );
          companies_has_open_actions_ids.push(trucking_company?.company_id ?? 0);
          const records = await this.user_view_repo.find({
            fields: ['contact_email', 'language', 'name', 'company_name'],
            where: { company_id: { inq: companies_has_open_actions_ids }, status: Status.User.Active },
          });
          const recepients = [];
          const headers = ['Cargo Number', 'Step Name', 'Action Name', 'New Expected Date'];
          const actions: AnyObject[] = [];
          arrExpectedDatesGroupByActionName.map((step: AnyObject) => {
            return step.expected_dates.map((action: AnyObject) => {
              actions.push({
                container_no: action.container_no,
                step_name: step.name,
                action_name: action.action_name,
                expected_date: DateUtils.formatDateAndConvertTimeZone(action.expected_date, 'DD/MM/YY HH:mm', action.timezone),
              });
            });
          });
          for(const record of records) {
            recepients.push({
              email: record.contact_email,
              language: record.language,
              replacement_data: {
                name: flow.name,
                username: record.name,
                company_name: record.company_name,
                reason_for_update: payload.reason,
                list_actions_text: this.ses_service.generateTemplateTableText(actions, headers),
                list_actions_html: this.ses_service.generateTemplateTableHTML(actions, headers),
                show_limit_message: actions?.length > Constants.MaxItemsForActionListInEmail ? true : false
              }
            });
          }
          await Promise.all([
            this.ses_service.sendBulkTemplatedEmail(Constants.Email.InformCompanyAfterFlowExpectedDatesIsUpdated, recepients),
            this.sendNotifications(flow, {
              key: Constants.Notification.FlowExpectedDatesIsUpdated,
              company_ids: companies_has_open_actions_ids,
            })
          ]);
        }
        // -------------------------------------------------------------
      }, 1000);
    } catch (error) {
      console.error(error);
      throw error;
    }
  }
  
  /**
   * Update container_no of action's data of flow.
   *
   * @param {number} id - The ID of flow to be updated.
   * @param {AnyObject} payload - The payload to update.
   * @throws {EntityNotFoundError} If the old flow is not found.
   */
  async updateContainerNo(id: number, payload: AnyObject) {
    const flow = await this.flow_repo.findOne({
      fields: ['id', 'personas', 'name'],
      where: {
        id
      },
      include: [
        {
          relation: 'personas',
          scope: {
            fields: ['id', 'needed_info', 'flow_id'],
            where: {
              'needed_info.container_no': {
                neq: null
              }
            }
          },
        }
      ]
    });
    if (isEmpty(flow)) {
      console.log('Flow not found for update_container_no action');
      throw new EntityNotFoundError(this.flow_repo.entityClass, id);
    }
 
    // Get action of addendum step.
    const step_addendum_action = await this.flow_action_repo.findOne({
      fields: ['id'],
      where: {
        flow_id: id,
        title: Constants.update_container_no_label
      }
    });
    if (!step_addendum_action) {
      console.log('Addendum step not found for update_container_no action');
      throw new EntityNotFoundError(this.flow_action_repo.entityClass, id);
    }
 
    // Get persona that contains needed info.
    const persona = flow?.personas[0];
    if (!persona) {
      console.log('Persona not found for update_container_no action');
      throw new EntityNotFoundError(this.persona_repo.entityClass, id);
    }
 
    try {
      // Update needed_info.container_no
      const needed_info = JSON.parse(JSON.stringify(persona.needed_info));
      payload.containers.map((container: string, index: number) => {
        if (!needed_info.container_no) {
          needed_info.container_no = [];
        }
        if (container !== null) {
          needed_info.container_no[index] = container;
        }
      });
      // Validate duplicates.
      if (needed_info.container_no.length > new Set(needed_info.container_no).size) {
        console.log('Duplicated container number', needed_info.container_no);
        throw new HttpErrors.BadRequest(Constants.error_message_duplicated_container_no);
      }
      await this.flow_persona_repo.updateById(persona.id, {needed_info});
      // ------------------------------------
 
      // eslint-disable-next-line @typescript-eslint/no-misused-promises
      setTimeout(async () => {
        // Create document for addendum step's action (update_container_no).
        const step_n_document = await this.document_repo.create({
          flow_id: id,
          company_id: this.current_user.company_id,
          name: Constants.update_container_no_label,
          reason_for_updating: payload.reason,
          expected_date: new Date(),
          flow_action_id: step_addendum_action.id,
          status: Status.Document.New,
          readonly: true,
          pdf_attempt: 0,
        });
        // -------------------------
 
        const arrOldAndNewContainerNo = payload.containers.map((container: string, index: number) => {
          if (container !== null) {
            return {
              oldContainerNo: persona.needed_info.container_no[index],
              newContainerNo: container
            };
          }
        });
 
        // Generate PDF for addendum step.
        await this.document_service.updateByIdOrIdentifier(step_n_document?.id ?? 0, new DocumentDto({
          status: Status.Document.Completed,
          readonly: true, // This is mark it not to be showed in the list
          documents: payload?.uri ? [payload.uri] : [],
        }), { ignoredCompany: true, containers: arrOldAndNewContainerNo, forUpdateAddendum: true });
        // -------------------------------------------------------------
 
        // Send notifications to all companies that still have open actions.
        // Query to get all company_id with actions are still open.
        const companies_has_open_actions = await this.flow_action_repo.find({
          fields: ['company_id'],
          where: {
            status: Status.FlowAction.New,
            flow_id: id,
          },
        });
        if (companies_has_open_actions?.length) {
          const companies_has_open_actions_ids = companies_has_open_actions.map((item) => item.company_id);
          const records = await this.user_view_repo.find({
            fields: ['contact_email', 'language', 'name', 'company_name'],
            where: { company_id: { inq: companies_has_open_actions_ids }, status: Status.User.Active },
          });
          const recepients = [];
          const headers = ['Old Cargo Number', 'New Cargo number'];
          for(const record of records) {
            recepients.push({
              email: record.contact_email,
              language: record.language,
              replacement_data: {
                name: flow.name,
                username: record.name,
                company_name: record.company_name,
                reason_for_update: payload.reason,
                list_actions_text: this.ses_service.generateTemplateTableText(arrOldAndNewContainerNo, headers),
                list_actions_html: this.ses_service.generateTemplateTableHTML(arrOldAndNewContainerNo, headers),
                show_limit_message: arrOldAndNewContainerNo?.length > Constants.MaxItemsForActionListInEmail ? true : false
              }
            });
          }
          await this.ses_service.sendBulkTemplatedEmail(Constants.Email.InformCompanyAfterFlowContainerNoIsUpdated, recepients);
        }
        // -------------------------------------------------------------
      }, 1000);
    } catch (error) {
      console.error(error);
      throw error;
    }
  }
 
  /**
   * Cancels a container with the specified ID.
   *
   * @param {number} id - The ID of the container to cancel.
   * @param {AnyObject} payload - The payload containing additional information.
   * @throws {EntityNotFoundError} If the flow with the specified ID is not found.
   */
  async cancelContainerNo(id: number, payload: AnyObject) {
    const flow = await this.flow_repo.findOne({
      fields: ['id', 'personas', 'name', 'status', 'company_id'],
      where: {
        id
      },
      include: [
        {
          relation: 'personas',
          scope: {
            fields: ['id', 'needed_info', 'flow_id', 'name', 'company_id', 'persona_id'],
            include: [{
              relation: 'persona',
              scope: {
                fields: ['id', 'title']
              }
            }]
          },
        }
      ]
    }) ?? {} as Flow;
    if (isEmpty(flow)) {
      throw new EntityNotFoundError(this.flow_repo.entityClass, id);
    }
 
    // If journey record is still on status Open or In Transit we can cancel it
    if ([Status.LiveStatus.Rejected, Status.LiveStatus.Completed].includes(flow.status)) {
      throw new HttpErrors.BadRequest('Flow is already comleted or rejected');
    }
 
    // If company of the logged user is the creator of the flow record
    if (this.current_user.company_id !== flow.company_id) {
      throw new HttpErrors.BadRequest('You are not owner of this flow');
    }
 
    // Get addendum step's "cancel container action"
    const step_addendum_action = await this.flow_action_repo.findOne({
      fields: ['id'],
      where: {
        flow_id: id,
        title: Constants.cancel_container_no_label
      }
    });
    if (!step_addendum_action) {
      throw new EntityNotFoundError(this.flow_action_repo.entityClass, id);
    }
 
    // Check if containers are not filled
    if (!payload.containers) {
      throw new HttpErrors.BadRequest('Missing "containers" in payload');
    }
 
    // Get persona that contains needed info.
    const flow_persona_has_container_no = flow?.personas.find((item) => item.needed_info?.container_no);
    if (!flow_persona_has_container_no) {
      throw new EntityNotFoundError(this.persona_repo.entityClass, id);
    }
    if (typeof flow_persona_has_container_no.needed_info.container_no === 'string') {
      flow_persona_has_container_no.needed_info.container_no = [flow_persona_has_container_no.needed_info.container_no];
    }
    // Validate container_no is exists in our db
    const isExists = payload.containers.find((container_no: string) => flow_persona_has_container_no.needed_info.container_no.includes(container_no));
    if (!isExists) {
      throw new HttpErrors.BadRequest('Invalid containers in payload');
    }
    
    const container_status: AnyObject = {};
    // Cancel submitted containers of flow by cancel all actions of that container
    const container_orders = flow_persona_has_container_no.needed_info.container_no.map((item: string, index: number) => {
      if (payload.containers.includes(item)) {
        container_status[index] = Status.Container.Cancelled;
        return index + 1;
      }
      return 0;
    });
    // Check if all containers are filled we will reject the flow
    if (payload.containers.length === flow_persona_has_container_no.needed_info.container_no.length) {
      await this.flow_journey_point_repo.updateContainerStatus(id, container_status);
      await this.checkAndNotifyUsersWhenFlowCompeted({ flow_id: id } as ReplyMessage);
      return this.cancelFlowById(id, { cancelled_reason: payload.reason });
    } else {
      // Update status of actions
      await this.flow_journey_point_repo.updateContainerStatus(id, container_status);
      await this.flow_action_repo.cancelActionsByContainerOrders(id, container_orders);
    }
    // ------------------------------------
 
    // Check if all containers of flow were cancelled so we need to reject the flow
    const result = await this.flow_action_repo.getTotalAndCancelledActionsByFlowId(id);
    if (result.total_actions === result.cancelled_actions) {
      return this.cancelFlowById(id, { cancelled_reason: payload.reason });
    }
 
    // eslint-disable-next-line @typescript-eslint/no-misused-promises
    setTimeout(async () => {
      // Create document for addendum step's action (cancel_container_no).
      const step_n_document = await this.document_repo.create({
        flow_id: id,
        company_id: this.current_user.company_id,
        name: Constants.cancel_container_no_label,
        cancelled_action: Status.ActionAfterCancelled.ContinueFlow,
        reason_for_updating: payload.reason,
        expected_date: new Date(),
        flow_action_id: step_addendum_action.id,
        status: Status.Document.New,
        readonly: true,
        pdf_attempt: 0,
      });
      // -------------------------
      
      // Generate PDF for addendum step.
      await this.document_service.updateByIdOrIdentifier(step_n_document?.id ?? 0, new DocumentDto({
        status: Status.Document.Completed,
        readonly: true, // This is mark it not to be showed in the list
        documents: payload?.uri ? [payload.uri] : [],
      }), { ignoredCompany: true, cancelled_containers: payload.containers.join(', '), forUpdateAddendum: true });
      // -------------------------------------------------------------
 
      // Send notifications to all companies that still have cancelled actions.
      // Query to get all company_id with actions are still open.
      const cancelled_actions = await this.flow_action_repo.getCancelledActionsByFlowIdAndContainers(id, payload.containers);
      if (cancelled_actions?.length) {
        const companies_has_open_actions_ids = cancelled_actions.map((item: AnyObject) => item.company_id);
        const trucking_company = await this.flow_persona_repo.findOne(
          {
            fields: ['id', 'company_id'],
            where: { flow_id: id, persona_id: { inq: [Constants.Persona.TruckingCompany] } },
          }
        );
        companies_has_open_actions_ids.push(trucking_company?.company_id ?? 0);
        const records = await this.user_view_repo.find({
          fields: ['contact_email', 'language', 'name', 'company_name', 'company_id'],
          where: { company_id: { inq: companies_has_open_actions_ids }, status: Status.User.Active },
        });
        
        // Group personas by company_id
        const company_persona_names: {[property: number]: string[];} = {};
        flow.personas.map((flow_persona: AnyObject) => {
          if (company_persona_names[flow_persona.company_id]) {
            company_persona_names[flow_persona.company_id].push(flow_persona.persona.title);
          } else {
            company_persona_names[flow_persona.company_id] = [flow_persona.persona.title];
          }
        });
 
        // Group actions by company_id
        const cancelled_actions_names: {[property: number]: string[];} = {};
        cancelled_actions.map((action: AnyObject) => {
          const action_name = action.action_name;
          if (!action_name) {
            return;
          }
          if (cancelled_actions_names[action.company_id]) {
            if (!cancelled_actions_names[action.company_id].includes(action_name)) {
              cancelled_actions_names[action.company_id].push(action_name);
            }
          } else {
            cancelled_actions_names[action.company_id] = [action_name ?? ''];
          }
        });
 
        const recepients = [];
        for(const record of records) {
          recepients.push({
            email: record.contact_email,
            language: record.language,
            replacement_data: {
              flow_id: flow.id,
              name: flow.name,
              username: record.name,
              company_name: record.company_name,
              company_persona_names: company_persona_names[record.company_id]?.join(', '),
              container_numbers: payload.containers.join(', '),
              container_numbers_break_by_line: payload.containers.join('<br/>\r\n'),
              action_names: cancelled_actions_names[record.company_id]?.join('<br/>\r\n') ?? '',
              cancelled_reason: payload?.reason ?? '',
            }
          });
        }
        await Promise.all([
          this.ses_service.sendBulkTemplatedEmail(Constants.Email.InformCompanyAfterFlowContainersAreRejected, recepients),
          this.sendNotifications(flow, {
            key: Constants.Notification.FlowContainersAreCancelled,
            company_ids: companies_has_open_actions_ids,
          })
        ]);
      }
      // -------------------------------------------------------------
    }, 1000);
 
    return flow;
  }
 
  /**
   * Builds the query for loading
   * @param q The query string.
   */
  async buildSearchQuery(q?: string) {
    if (!q) {
      return;
    }
 
    // FILTER:
    // OR flow_id should be a LIKE search
    const ilike_value = this.buildILikeValue(q);
    const or_clause: OrClause<FlowView> = 
    {
      or: [
        {
          id: ilike_value as unknown as number,
        },
        {
          name: ilike_value,
        },
        {
          pod_code: ilike_value,
        },
        {
          pol_code: ilike_value,
        },
      ],
    };
 
    const allowed_personas_to_search_with_reference = this.current_user.company_personas.filter((item: { persona_id: number }) => {
      return Constants.personas_can_create_flow.includes(item.persona_id);
    });
    if (allowed_personas_to_search_with_reference?.length) {
      or_clause.or.push(
        {
          reference_1: ilike_value,
        },
        {
          reference_2: ilike_value,
        },
        {
          reference_3: ilike_value,
        },
      );
    }
    this.filter_builder.impose(or_clause);
  }
 
  /**
   * Toggle flow action notification
   * @param id The flow action id.
   * @param options The options.
   */
  async toggleFlowActionNotification(id: number, options?: Options) {
    const currentFlowAction = await this.flow_action_repo.findById(id, {
      fields: ['id'],
    }, options);
 
    if (!currentFlowAction) {
      throw new EntityNotFoundError(this.flow_action_repo.entityClass, id);
    }
 
    // Toggle flow notification
    const currentFlowActionNotification = await this.flow_action_notification_repo.findOne({
      where: {
        flow_action_id: currentFlowAction.id,
        created_by: this.current_user.id,
      }
    }, options);
    
    if (currentFlowActionNotification) {
      await this.flow_action_notification_repo.deleteById(currentFlowActionNotification.id, options);
    } else {
      await this.flow_action_notification_repo.create({
        flow_action_id: currentFlowAction.id,
        created_by: this.current_user.id,
      }, options);
    }
 
    return true;
  }
 
  async updateCategories(id: number, payload: { category_ids: number[]; }) {
    // Check valid category_ids format
    if (!payload.category_ids || !Array.isArray(payload.category_ids)) {
      throw new HttpErrors.BadRequest('Invalid category_ids');
    }
    if (payload.category_ids.length === 0) {
      throw new HttpErrors.BadRequest('Empty category_ids');
    }
 
    // Check if all category_ids are exists
    const categories = await this.category_repo.find({
      fields: ['id'],
      where: {
        id: { inq: payload.category_ids }
      }
    });
    if (payload.category_ids.length !== categories.length) {
      throw new HttpErrors.BadRequest('Invalid category_ids');
    }
 
    // Check if flow exists
    const flow = await this.flow_repo.findById(id, {
      fields: ['id'],
    });
    if (!flow) {
      throw new EntityNotFoundError(this.flow_repo.entityClass, id);
    }
 
    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: payload.category_ids,
    },
  );
 
    return true;
  }
}