All files / src/services external.service.ts

15.64% Statements 43/275
0% Branches 0/266
4.76% Functions 1/21
15.36% Lines 41/267

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 7781x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x   1x 1x 1x     1x     1x   1x   1x   1x   1x   1x   1x   1x   1x   1x   1x   1x   1x   1x   1x   1x   1x   1x   1x   1x   1x   1x                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              
import { bind, BindingScope, service } from '@loopback/core';
import { CompanyRepository, FlowActionRepository, FlowJourneyPointRepository, FlowRepository, RamOrderRepository, TradeLaneRepository } from '@logchain/repositories';
import { AnyObject, Options, repository } from '@loopback/repository';
import { FlowService } from './flow.service';
import { LoadingService } from './loading.service';
import { Constants } from '@logchain/configs';
import { EntryRecordDto, FlowDto, LiftDto, LoadingDto, OnLoadingDto, RamOrderDto, WeighbridgeDto } from '@logchain/dtos';
import { Flow, RamOrder, RamOrderRelations, Status, TradeLane } from '@logchain/models';
import { HttpErrors } from '@loopback/rest';
import { BaseService } from './base.service';
import { BolService, DGDService, DocumentService, EirService, EntryRecordService, FlowJourneyService, LiftService, OnLoadingService, TransportService, VesselService, WeighbridgeService } from '.';
import { FTPService } from './ftp.service';
import * as fs from 'fs';
import * as xml2js from 'xml2js';
import { FtpConfigs } from '@logchain/configs/ftp-configs';
import sftp from 'ssh2-sftp-client';
import { RAM_ORDER, RAM_ORDER_MSGTYPE_ENUM } from '@logchain/types';
import { StringUtils } from '@logchain/utils';
import { CargoService } from './cargo.service';
 
@bind({ scope: BindingScope.TRANSIENT })
export class ExternalService extends BaseService<Flow> {
  constructor(
    @service(FTPService)
    public ftpService: FTPService,
    @service(FlowService)
    public flowService: FlowService,
    @service(EntryRecordService)
    public entryRecordService: EntryRecordService,
    @service(LoadingService)
    public loadingService: LoadingService,
    @service(WeighbridgeService)
    public weighbridgeService: WeighbridgeService,
    @service(LiftService)
    public liftService: LiftService,
    @service(OnLoadingService)
    public onLoadingService: OnLoadingService,
    @service(DocumentService)
    public documentService: DocumentService,
    @service(EirService)
    public eirService: EirService,
    @service(BolService)
    public bolService: BolService,
    @service(VesselService)
    public vesselService: VesselService,
    @service(CargoService)
    public cargoService: CargoService,
    @service(DGDService)
    public dgdService: DGDService,
    @service(TransportService)
    public transportService: TransportService,
    @service(FlowJourneyService)
    public flowJourneyService: FlowJourneyService,
    @repository(CompanyRepository)
    public comp_repo: CompanyRepository,
    @repository(FlowRepository)
    public flow_repo: FlowRepository,
    @repository(FlowJourneyPointRepository)
    public flow_journey_point_repo: FlowJourneyPointRepository,
    @repository(FlowActionRepository)
    public flow_action_repo: FlowActionRepository,
    @repository(RamOrderRepository)
    public ram_order_repo: RamOrderRepository,
    @repository(TradeLaneRepository)
    public trade_lane_repo: TradeLaneRepository,
  ) {
    super();
  }
  
  /**
   * Update all action's data in one function
   * @param  {number} id id of action
   * @param  {number} type_id type of action
   * @param  {AnyObject} payload data to be updated
   * @param  {Options={}} options optional variables to pass to this function
   */
  async updateAction(id: number, type_id: number, payload: AnyObject, options: Options = {}) {
    // Init default values here
    payload.type = payload?.attachments ? Constants.WeighbridgeType.Attachment : Constants.WeighbridgeType.Form;
    // -----------------------
 
    // Common validation here
    if (payload?.status === Status.Loading.Cancelled && (!payload?.cancelled_action || !payload?.cancelled_reason)) {
      throw new HttpErrors.BadRequest('Required Parameters: cancelled_action, cancelled_reason.');
    } else if (payload?.type === Constants.WeighbridgeType.Attachment && !payload?.attachments) {
      throw new HttpErrors.BadRequest('Required Parameters: attachments.');
    } else if ([Constants.Form.GateIn, Constants.Form.GateOut].includes(type_id)) {
      if (payload.type && payload.type !== Constants.EntryRecordMethod.Attachment) {
        throw new HttpErrors.BadRequest('Invalid Parameters: type. GateIn or GateOut only support attachments');
      }
    } else {
      if (payload.status === undefined) {
        throw new HttpErrors.BadRequest('Required Parameters: status.');
      }
    }
    // -----------------------
 
    // Common conversion here
    // -----------------------
 
    // Common mapping here
    if ([Constants.Form.GateIn, Constants.Form.GateOut].includes(type_id)) {
      // Mapping from general endpoint to local endpoint
      payload.remark = payload.remarks ?? ''; delete payload.remarks;
      payload.method = payload?.type ?? Constants.EntryRecordMethod.Attachment; // Form vs Attachment => Allowed: Attachment
      payload.type = (type_id === Constants.Form.GateIn ? 0 : 1); // Entry Record accept type_id as type "Gate-In or Gate-Out"
      payload.checklists = payload.attachments; // Entry Record accept checklists as attachments
      delete payload.attachments;
    }
    // -----------------------
 
    switch (type_id) {
      case Constants.Form.LiftOn:
      case Constants.Form.LiftOff:
        return this.liftService.updateByIdOrIdentifier(id, new LiftDto(payload), { type_id });
 
      case Constants.Form.GateIn:
      case Constants.Form.GateOut:
        return this.entryRecordService.createGate(id, new EntryRecordDto(payload));
      
      case Constants.Form.WeighbridgeEntry:
      case Constants.Form.WeighbridgeExit:
        return this.weighbridgeService.updateByIdOrIdentifier(id, new WeighbridgeDto(payload), { type_id });
 
      case Constants.Form.LoadChemical:
      case Constants.Form.UnloadChemical:
        return this.loadingService.updateByIdOrIdentifier(id, new LoadingDto(payload), { type_id });
      
      case Constants.Form.OnLoading:
      case Constants.Form.OffLoading:
        return this.onLoadingService.updateByIdOrIdentifier(id, new OnLoadingDto(payload), { type_id });
 
      case Constants.Form.EIR:
        throw new HttpErrors.BadRequest('Un-Supported');
      case Constants.Form.ReheatTank:
        throw new HttpErrors.BadRequest('Un-Supported');
      case Constants.Form.BOL:
        throw new HttpErrors.BadRequest('Un-Supported');
      case Constants.Form.VesselArrival:
      case Constants.Form.VesselDeparture:
        throw new HttpErrors.BadRequest('Un-Supported');
      case Constants.Form.CargoCollection:
      case Constants.Form.CargoDelivery:
        throw new HttpErrors.BadRequest('Un-Supported');
      default:
        throw new HttpErrors.BadRequest('Un-Supported');
    }
  }
 
  /**
   * A function that generates actions from an FTP XML. It connects to the FTP server, retrieves XML files, 
   * parses and processes them, and then uploads the modified files back to the FTP server. 
   *
   * @return {Promise<void>} 
   */
  async generateActionsFromFTP_XML(): Promise<void> {
    let remoteFromXmlFilePath = '';
    let new_ram_order: (RamOrder & RamOrderRelations) | null = { id: 0 } as RamOrder;
    let cur_ram_order: (RamOrder & RamOrderRelations) | null = { id: 0 } as RamOrder;
    try {
      await this.ftpService.connect();
      let files = await this.ftpService.listFiles(FtpConfigs.fromDir);
      if (!files?.length) {
        return;
      } else if (files?.length && files?.length > 1) {
        files.sort((a, b) => a.modifyTime - b.modifyTime);
        files = files.slice(0, 1);
      }
      
      const file: sftp.FileInfo = files[0];
      
      remoteFromXmlFilePath = `${FtpConfigs.fromDir}/${file.name}`;
      const localXmlFilePath = `/tmp/${file.name}`;
 
      await this.ftpService.downloadFile(remoteFromXmlFilePath, localXmlFilePath);
      console.log(`Downloaded ${file.name}`);
 
      const xmlData = fs.readFileSync(localXmlFilePath, 'utf-8');
 
      // Back up file to S3
      const pdfKey = Constants.sutton_xml_path + file.name;
      const param = {
        Key: pdfKey,
        Body: xmlData,
        ContentEncoding: 'base64',
        ContentType: 'application/xml',
        ServerSideEncryption: 'AES256',
      };
      await this.s3_service.putObject(param);
      // -----------------------------------
 
      if (file.name === '.' || file.name === '..' || !file.name.endsWith('.xml')) {
        console.log(`Skipping ${file.name}`);
        throw new Error('File not found or not an XML file');
      }
 
      let result: AnyObject = {};
      try {
        result = await this.parseXmlToObject(xmlData);
      } catch (error) {
        // Because we want to ignore xml files that cannot be parsed
        // Delete XML file and stop here then move to next file
        console.log(`Skipping ${file.name} can not parse XML content.`, error);
        throw new Error(`Server could not process the XML due to a perceived client error (this can be from anything like wrong XML format, invalid request framing, …)`);
      }
      if (result['DSET']?.['tt-edi-ord']?.length > 0) {
        let content = '';
        const ram_order = this.xmlService.getRAM_Order(result);
        // Validate required parameters
        if (!ram_order?.MsgType || !ram_order?.Outgoing_Docid || !ram_order?.Consignment_num || !ram_order?.Unitkey) {
          console.log('Missing required parameters', JSON.stringify(ram_order));
          content = this.xmlService.response400(ram_order, 'Missing required parameters');
        } else {
          if (ram_order.Unitkey === 'UNALLOCATED') {
            ram_order.Unitkey = ram_order.Unitkey + StringUtils.randomstring(5);
          }
 
          // Check Outgoing_DocId is processed yet
          cur_ram_order = await this.ram_order_repo.findOne({
            where: {
              outgoing_docid: ram_order.Outgoing_Docid
            },
            order: ['id DESC']
          });
 
          // Mark this ram_order as New
          new_ram_order = await this.ram_order_repo.create(new RamOrderDto({
            msg_type: ram_order.MsgType,
            outgoing_docid: ram_order.Outgoing_Docid,
            consignment_num: ram_order.Consignment_num,
            unitkey: ram_order.Unitkey,
            status: Status.RamOrderStatus.New,
          }));
 
          if (cur_ram_order?.status === Status.RamOrderStatus.Completed) {
            content = this.xmlService.response1001(ram_order);
          } else {
            // Mark this ram_order as InProgress
            await this.ram_order_repo.updateById(new_ram_order.id, { status: Status.RamOrderStatus.InProgress });
 
            switch (ram_order.MsgType) {
              case RAM_ORDER_MSGTYPE_ENUM.NEW:
                content = await this.createOrder(ram_order);
                break;
              case RAM_ORDER_MSGTYPE_ENUM.UPDATE:
                content = await this.updateOrder(ram_order);
                break;
              case RAM_ORDER_MSGTYPE_ENUM.CANCEL:
                content = await this.cancelOrder(ram_order);
                break;
            }
          }
        
          // Mark this ram_order as Completed
          await this.ram_order_repo.updateById(new_ram_order.id, { status: Status.RamOrderStatus.Completed, xml_response: content });
        }
 
        const remoteToXmlFilePath = `${FtpConfigs.toDir}/${file.name}`;
        fs.writeFileSync(localXmlFilePath, content);
 
        await this.ftpService.uploadFile(localXmlFilePath, remoteToXmlFilePath);
        console.log(`Uploaded ${file.name}`);
 
        await this.ftpService.deleteFile(remoteFromXmlFilePath);
        console.log(`Removed ${file.name} from ${FtpConfigs.fromDir}`);
      }
 
      // eslint-disable-next-line @typescript-eslint/no-misused-promises
      setTimeout(async () => {
        await this.ftpService.disconnect();
      }, 10000);
 
      // eslint-disable-next-line @typescript-eslint/no-misused-promises
      process.on('unhandledRejection', async (reason, promise) => {
        console.error('Unhandled Rejection at:', promise, 'reason:', reason);
        if (new_ram_order?.id) {
          await this.ram_order_repo.updateById(
            new_ram_order.id, 
            { 
              status: Status.RamOrderStatus.Completed, 
              xml_response: this.xmlService.response400(new_ram_order, JSON.stringify(reason))
            }
          );
        }
        if (remoteFromXmlFilePath !== '') {
          await this.ftpService.deleteFile(remoteFromXmlFilePath);
          console.log(`Removed ${remoteFromXmlFilePath}`);
        }
      });
    } catch (error) {
      console.log(error);
      if (new_ram_order?.id) {
        await this.ram_order_repo.updateById(
          new_ram_order.id, 
          { 
            status: Status.RamOrderStatus.Completed, 
            xml_response: this.xmlService.response400(new_ram_order, error.message) 
          }
        );
      }
      if (remoteFromXmlFilePath !== '') {
        await this.ftpService.deleteFile(remoteFromXmlFilePath);
        console.log(`Removed ${remoteFromXmlFilePath}`);
      }
    } finally {
      // await this.ftpService.disconnect();
    }
  }
 
  /**
   * Asynchronously create new order.
   *
   * @param {AnyObject} ram_order - the RAM order
   * @return {Promise<string>} a promise that resolves to the creation status
   */
  async createOrder(ram_order: RAM_ORDER): Promise<string> {
    if (ram_order.LoadWeight && isNaN(Number(ram_order.LoadWeight))) {
      return this.xmlService.response1101(ram_order);
    }
    // Check Consignment_num (flow_id) is created yet
    const curFlow = await this.flow_repo.findOne({
      where: {
        consignment_num: ram_order.Consignment_num,
      },
      include: [
        {
          relation: 'trade_lane',
          scope: {
            fields: {
              id: true,
              name: true,
              pol_code: true,
              pod_code: true,
              product: true,
            },
            include: [{
              relation: 'trade_lane_flow',
              scope: {
                include: [{
                  relation: 'journey_points',
                  scope: {
                    order: ['order ASC']
                  }
                }]
              }
            }]
          }
        }
      ]
    });
    if (!curFlow) {
      // Consigment number is not created yet
      return this.createFlowFromConsignmentNum(ram_order);
    }
    // Consigment number is created
    return this.addContainerToFlowFromConsignmentNum(ram_order, curFlow);
  }
 
  /**
   * Asynchronously updates an existing order.
   *
   * @param {AnyObject} ram_order - the RAM order
   * @return {Promise<string>} a promise that resolves to the update status
   */
  async updateOrder(ram_order: RAM_ORDER): Promise<string> {
    // Check Consignment_num (flow_id) is created yet
    const curFlow = await this.flow_repo.findOne({
      where: {
        consignment_num: ram_order.Consignment_num,
        live_status: { nin: [Status.LiveStatus.Completed, Status.LiveStatus.Rejected] }
      },
      include: [
        {
          relation: 'trade_lane',
          scope: {
            fields: {
              id: true,
              name: true,
              pol_code: true,
              pod_code: true,
              product: true,
              company_id: true,
              no_of_container: true,
              trade_lane_flow_id: true,
            },
            include: [
              {
                relation: 'trade_lane_flow',
                scope: {
                  fields: {
                    id: true,
                    trade_lane_id: true,
                    personas: true,
                  },
                  include: [
                    {
                      relation: 'personas',
                      scope: {
                        order: ['order ASC'],
                      },
                    },
                    {
                      relation: 'journey_points',
                      scope: {
                        order: ['order ASC'],
                      },
                    },
                  ],
                },
              }
            ],
          },
        },
      ]
    });
    
    if (!curFlow) {
      return this.xmlService.response1002(ram_order);
    }
 
    // Check Unitkey (container_no) is existed yet
    const containers = await this.flow_persona_repo1.getAllContainersByFlowId(curFlow.id);
    if (!containers.includes(ram_order.Unitkey)) {
      return this.xmlService.response1003(ram_order, Constants.response1009_for_update_xml);
    }
 
    // Check allowed attributes to update
    if (!ram_order?.LoadWeight) {
      return this.xmlService.response1009(ram_order);
    } else if (isNaN(Number(ram_order.LoadWeight))) {
      return this.xmlService.response1101(ram_order);
    }
 
    // Validate the VesselData
    const missingFields = this.validateVesselInformation(ram_order, curFlow.trade_lane);
    if (missingFields.length !== 0) {
      return this.xmlService.response1103(ram_order, missingFields.join(', '));
    }
    // --------------------------------------
 
    const container_number = containers.findIndex((container: string) => container === ram_order.Unitkey) + 1;
 
    if ([Status.Flow.New, Status.Flow.ForValidation, Status.Flow.Live].includes(curFlow.status)) {
      // Update data for specific container
      const result = await this.flowService.updateExpectedDateByContainerNumber(curFlow, container_number, ram_order);
      if (typeof(result) === 'string') { // Make sure expected_date available in XML file
        return result;
      }
 
      if (ram_order.LoadWeight) {
        await this.flow_action_repo.updateFormDataByContainerNumber(curFlow.id, container_number, ram_order);
      }
 
      // Update data for vessels form
      const allVesselActions = await this.flow_action_repo.find({
        where: {
          flow_id: curFlow.id,
          form_id: { inq: [Constants.Form.VesselArrival, Constants.Form.VesselDeparture] }
        },
      });
      
      for(const action of allVesselActions) {
        const updatedAction = this.flowService.setVesselDataToAction(action, ram_order);
        await this.flow_action_repo.updateById(action.id, { form_data: updatedAction.form_data });
      }
      // --------------------------------
 
      if (curFlow.status === Status.Flow.ForValidation) {
        // Send notifications to validated-companies to validate again
        const validatedCompanies = await this.flow_persona_repo1.find({
          fields: ['id', 'company_id'],
          where: {
            flow_id: curFlow.id,
            status: Status.FlowPersona.Validated
          }
        });
        // Force validated companies must validate again
        await this.flow_persona_repo1.updateAll({
          status: Status.FlowPersona.WaitToValidate
        }, {
          flow_id: curFlow.id,
          status: Status.FlowPersona.Validated
        });
        const validatedCompanyIds = validatedCompanies.map((company: AnyObject) => company.company_id);
        await this.flowService.sendNotifications(curFlow, { 
          template: Constants.Email.InformCompanyAfterFlowContainersAreUpdated,
          key: Constants.Notification.FlowIsUpdated,
          company_ids: validatedCompanyIds,
          container_name: ram_order.Unitkey,
        });
      }
  
      if (curFlow.status === Status.Flow.Live) {
        // Send notifications to affected companies (open actions companies)
        const openActions = await this.flow_action_repo.find({
          fields: ['id', 'company_id'],
          where: {
            flow_id: curFlow.id,
            status: Status.FlowAction.New
          }
        });
        const openActionCompanyIds = openActions.map((action: AnyObject) => action.company_id);
        await this.flowService.sendNotifications(curFlow, { 
          template: Constants.Email.InformCompanyAfterFlowIsUpdated,
          key: Constants.Notification.FlowIsUpdated,
          company_ids: openActionCompanyIds,
          container_name: ram_order.Unitkey,
        });
      }
 
      return this.xmlService.response200(ram_order);
    } else {
      return this.xmlService.response1002(ram_order);
    }
  }
 
  /**
   * Asynchronously cancels an existing order.
   *
   * @param {AnyObject} ram_order - the RAM order
   * @return {Promise<string>} a promise that resolves to the cancellation status
   */
  async cancelOrder(ram_order: RAM_ORDER): Promise<string> {
    // Check Consignment_num (flow_id) is created yet
    const curFlow = await this.flow_repo.findOne({
      where: {
        consignment_num: ram_order.Consignment_num,
        live_status: { nin: [Status.LiveStatus.Completed, Status.LiveStatus.Rejected] }
      }
    });
    if (!curFlow) {
      return this.xmlService.response1002(ram_order);
    }
 
    // Check Unitkey (container_no) is cancelled yet
    const containers = await this.flow_persona_repo1.getAllContainersByFlowId(curFlow.id);
    if (!containers.includes(ram_order.Unitkey)) {
      return this.xmlService.response1003(ram_order);
    }
 
    const container_number = containers.findIndex((container: string) => container === ram_order.Unitkey);
 
    const flow_company = await this.comp_repo.findById(curFlow.company_id);
    let template = '';
 
    switch(curFlow.status) {
      case Status.Flow.New:
        if (containers.length === 1) { // if we have only one container left
          await this.flow_repo.updateById(curFlow.id, { status: Status.Flow.Inactive, cancelled_reason: 'Order was cancelled' });
        } else {
          // Remove current container out of flow
          await this.flow_journey_point_repo.deleteByFlowIdAndContainerNumber(curFlow.id, container_number + 1);
        }
        return this.xmlService.response200(ram_order);
      case Status.Flow.ForValidation:
        if (containers.length === 1) { // if we have only one container left
          await this.flow_repo.updateById(curFlow.id, { status: Status.Flow.Rejected, cancelled_reason: 'Order was cancelled' });
          template = Constants.Email.InformCompanyAfterFlowForValidationHasBeenRejected;
        } else {
          // Remove current container out of flow
          await this.flow_journey_point_repo.deleteByFlowIdAndContainerNumber(curFlow.id, container_number + 1);
          template = Constants.Email.InformCompanyAfterFlowContainersAreDeleted;
        }
        // Send mail to all companies of flow
        await this.flowService.sendNotifications(curFlow, { 
          template,
          key: Constants.Notification.FlowValidationIsRejected,
          flow_company_name: flow_company.name,
          container_name: ram_order.Unitkey,
        })
 
        return this.xmlService.response200(ram_order);
      case Status.Flow.Live:
        // Cancel container as it was doing on the web
        await this.flowJourneyService.cancelContainerNo(curFlow.id, { containers: [ram_order.Unitkey], cancelled_reason: 'Order was cancelled' });
        return this.xmlService.response200(ram_order);
      default:
        return this.xmlService.response1002(ram_order);
    }
  }
 
  /**
   * Asynchronously parses XML data to an object.
   *
   * @param {string} xmlData - the XML data to be parsed
   * @return {Promise<AnyObject>} a promise that resolves to the parsed object
   */
  async parseXmlToObject(xmlData: string): Promise<AnyObject> {
    return new Promise((resolve, reject) => {
      xml2js.parseString(xmlData, (error, result) => {
        if (error) {
          reject(error);
        } else {
          resolve(result);
        }
      });
    });
  }
 
  /**
   * A description of the entire function.
   *
   * @param {RAM_ORDER} ram_order - the RAM_ORDER parameter
   * @return {Promise<void>} a Promise that resolves to void
   */
  async createFlowFromConsignmentNum(ram_order: RAM_ORDER): Promise<string> {
    // Is there a trade-lane for the record ?
    const foundTradeLane = await this.trade_lane_repo.find({
      where: {
        pol_code: ram_order.POL,
        pod_code: ram_order.POD,
        product: ram_order.ProductId
      },
      include: [{
        relation: 'trade_lane_flow',
        scope: {
          include: [{
            relation: 'journey_points',
            scope: {
              order: ['order ASC']
            }
          }]
        }
      }]
    });
    if (!foundTradeLane || foundTradeLane.length === 0) {
      // 1011: Invalid Trade Lane
      return this.xmlService.response1011(ram_order);
    }
 
    if (foundTradeLane.length > 1) {
      // 1012: Many Trade Lanes
      return this.xmlService.response1012(ram_order);
    }
 
    // Validate the VesselData
    const missingFields = this.validateVesselInformation(ram_order, foundTradeLane[0]);
    if (missingFields.length !== 0) {
      return this.xmlService.response1103(ram_order, missingFields.join(', '));
    }
    // --------------------------------------
 
    // Get the lowest order of tt-edi-vessel tag in XML
    const tt_edi_ord = ram_order.xml['DSET']['tt-edi-ord'][0];
    let lowest_tt_edi_vessel = undefined;
    let minestSeqNo = Number.MAX_SAFE_INTEGER;
    for (const item of tt_edi_ord['tt-edi-vessel']) {
      if (item['SeqNo'] && +item['SeqNo'] < minestSeqNo) {
        minestSeqNo = +item['SeqNo'];
        lowest_tt_edi_vessel = item;
      }
    }
    if (!lowest_tt_edi_vessel) {
      return this.xmlService.response1105(ram_order);
    } else if (!lowest_tt_edi_vessel['Vessel_BookingRef'] || !lowest_tt_edi_vessel['Vessel_BookingRef'][0]) {
      return this.xmlService.response1105(ram_order);
    }
    // --------------------------------------
 
    // Create flow from trade-lane
    try {
      await this.flowService.create(new FlowDto({
        trade_lane_id: foundTradeLane[0].id,
        consignment_num: ram_order.Consignment_num,
        name: `${lowest_tt_edi_vessel['Vessel_BookingRef'][0]}/${ram_order.Jobno}/${ram_order.Consignment_num}: ${ram_order.POL} - ${ram_order.POD}`,
      }), ram_order);
    } catch (error) {
      return error.message;
    }
 
    return this.xmlService.response200(ram_order);
  }
 
  /**
   * A description of the entire function.
   *
   * @param {RAM_ORDER} ram_order - description of parameter
   * @param {Flow} curFlow - description of parameter
   * @return {Promise<any>} description of return value
   */
  async addContainerToFlowFromConsignmentNum(ram_order: RAM_ORDER,  curFlow: Flow): Promise<string> {
    // Validate the VesselData
    const missingFields = this.validateVesselInformation(ram_order, curFlow.trade_lane);
    if (missingFields.length !== 0) {
      return this.xmlService.response1103(ram_order, missingFields.join(', '));
    }
    // --------------------------------------
 
    // Is the Unitkey already existing on the flow ?
    const containers = await this.flow_persona_repo1.getAllContainersByFlowId(curFlow.id);
    if (containers.includes(ram_order.Unitkey)) {
      return this.xmlService.response1003(ram_order, 'Container No already exist in the flow and cannot be added');
    }
    // --------------------------------------
    
    if (curFlow.status === Status.Flow.New) {
      // Add this container to current flow
      const result = await this.flowService.addContainerToFlow({
        flow_id: curFlow.id,
        container_no: ram_order.Unitkey,
        ram_order,
      });
 
      if (typeof(result) === 'string') {
        return result;
      }
 
      // Send mail to all companies of flow
      const flow_company = await this.comp_repo.findById(curFlow.company_id);
      await this.flowService.sendMailToAllCompanies(curFlow.id, { 
        template: Constants.Email.InformCompanyAfterFlowContainersAreAdded,
        flow_company_name: flow_company.name,
        container_name: ram_order.Unitkey,
      });
 
      return this.xmlService.response200(ram_order);
    } else {
      // Is this flow for validation ?
      if (curFlow.status !== Status.Flow.ForValidation) {
        return this.xmlService.response1011(ram_order);
      }
 
      // Add this container to current flow
      const result = await this.flowService.addContainerToFlow({
        flow_id: curFlow.id,
        container_no: ram_order.Unitkey,
        ram_order,
      });
 
      if (typeof(result) === 'string') {
        return result;
      }
 
      // Send mail to all companies of flow
      const flow_company = await this.comp_repo.findById(curFlow.company_id);
      await this.flowService.sendMailToAllCompanies(curFlow.id, { 
        template: Constants.Email.InformCompanyAfterFlowContainersAreAdded,
        flow_company_name: flow_company.name,
        container_name: ram_order.Unitkey,
      });
 
      return this.xmlService.response200(ram_order);
    }
  }
 
  /**
   * Validates the vessel information from the given RAM order and trade lane.
   *
   * @param {RAM_ORDER} ram_order - The RAM order object containing vessel data.
   * @param {TradeLane} trade_lane - The trade lane object containing journey points.
   * @return {AnyObject} An empty object if the validation is successful, otherwise throws an error.
   */
  validateVesselInformation(ram_order: RAM_ORDER, trade_lane: TradeLane): string[] {
    const missingFields: string[] = [];
    const journeyPoints = trade_lane?.trade_lane_flow?.journey_points;
    if (journeyPoints && ram_order?.VesselData) {
      // Compare arrival and departure code from actions of journey points (trade-lane-flow) to get correct vessel information from XML object
      journeyPoints.map((journeyPoint: AnyObject) => {
        journeyPoint.actions.map((action: AnyObject) => {
          if (action.form_id === Constants.Form.VesselArrival) {
            const vesselKey = action.form_data.origin + '_' + action.form_data.arrival;
            if (!ram_order.VesselData?.[vesselKey]) {
              missingFields.push(vesselKey);
            }
          } else if (action.form_id === Constants.Form.VesselDeparture) {
            const vesselKey = action.form_data.departure + '_' + action.form_data.destination;
            if (!ram_order.VesselData?.[vesselKey]) {
              missingFields.push(vesselKey);
            }
          }
        });
      });
    }
 
    return missingFields;
  }
}