All files / src/services trade-lane.service.ts

12.14% Statements 25/206
0% Branches 0/143
3.85% Functions 1/26
11.44% Lines 23/201

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 6901x 1x 1x   1x 1x 1x 1x 1x 1x   1x 1x     1x 17x       17x   17x   17x   17x   17x   17x   17x   17x   17x   17x                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      
import { bind, BindingScope } from '@loopback/core';
import { EntityNotFoundError, FilterBuilder, Options, repository, Where, IsolationLevel, AnyObject, } from '@loopback/repository';
import { HttpErrors, validateValueAgainstSchema } from '@loopback/rest';
 
import { TradeLaneDto, TradeLaneFlowDto, TradeLaneFlowJourneyPointDto, TradeLaneFlowPersonaDto } from '@logchain/dtos';
import { BaseResponses, Status, TradeLane, TradeLaneFlowJourneyPoint, TradeLaneFlowPersona } from '@logchain/models';
import { CompanyRepository, CountryRepository, FlowDefaultRepository, LocodeRepository, TradeLaneFlowJourneyPointRepository, TradeLaneFlowPersonaRepository, TradeLaneFlowRepository, TradeLaneRepository, TradeLaneViewRepository } from '@logchain/repositories';
import { DateUtils, ValidationError } from '@logchain/utils';
import { CSVParser, RecordsCreator, tradeLaneRowSchema, TradeLaneRow, UploadFileType, } from '@logchain/csv-parser';
import { BaseService } from '.';
import { TradeLaneView } from '@logchain/models/views';
import { Constants } from '@logchain/configs';
import _ from 'lodash';
 
@bind({ scope: BindingScope.TRANSIENT })
export class TradeLaneService extends BaseService<TradeLane> implements RecordsCreator {
  headers = ['name', 'description', 'product', 'pol_code', 'pod_code', 'reta_from', 'reta_to', 'equipment', 'provisions'];
 
  constructor(
    @repository(TradeLaneRepository)
    public tradeLaneRepo: TradeLaneRepository,
    @repository(TradeLaneViewRepository)
    public tradeLaneViewRepo: TradeLaneViewRepository,
    @repository(TradeLaneFlowRepository)
    public tradeLaneFlowRepo: TradeLaneFlowRepository,
    @repository(TradeLaneFlowPersonaRepository)
    public tradeLaneFlowPersonaRepo: TradeLaneFlowPersonaRepository,
    @repository(TradeLaneFlowJourneyPointRepository)
    public tradeLaneFlowJourneyPointRepo: TradeLaneFlowJourneyPointRepository,
    @repository(CountryRepository)
    public countryRepo: CountryRepository,
    @repository(LocodeRepository)
    public locodeRepository: LocodeRepository,
    @repository(FlowDefaultRepository)
    public flowDefaultRepo: FlowDefaultRepository,
    @repository(CompanyRepository)
    public comp_repo: CompanyRepository,
  ) {
    super();
  }
 
  /**
   * Validates reta
   * @param reta_from The reta from value
   * @param reta_to The reta to value
   */
  private validateReta(reta_from: number, reta_to: number) {
    // Value should be 0 <= reta_from <= reta_to value.
    if (reta_from <= 0 || reta_to <= 0 || reta_to < reta_from) {
      const err = new ValidationError('reta_from or reta_to is invalid');
      err.statusCode = 422;
      throw err;
    }
  }
 
  /**
   * Create a new trade lane
   * @param trade_lane The trade lane information
   */
  async create(trade_lane: TradeLaneDto, options?: Options): Promise<TradeLane> {
    const { reta_from, reta_to, pol_code, pod_code, name, product, equipment } = trade_lane;
    let { company_id } = trade_lane;
    
    // if company_id not exists, it should be the same with the company of current_user
    if (!company_id) {
      company_id = this.current_user.company_id;
      trade_lane.company_id = company_id;
    } else {
      // Validate company_id
      const company = await this.comp_repo.findOne({ where: { id: company_id, status: Status.Company.Active } });
      if (!company) {
        throw new HttpErrors.BadRequest(`Company not found with id: ${company_id}`);
      }
    }
 
    // validate reta
    this.validateReta(reta_from, reta_to);
 
    const [locodes, { count: existing }] = await Promise.all([
      this.locodeRepository.find({ where: { or: [{ code: pol_code, }, { code: pod_code, },], }, }, options),
      this.tradeLaneRepo.count({ name, product, equipment }, options),
    ]);
 
    if (existing) {
      throw new HttpErrors.BadRequest(`The trade lane name already exists: ${name} - ${product} - ${equipment}`);
    }
 
    // validate locode
    const pol = locodes.find(x => x.code === pol_code);
    const pod = locodes.find(x => x.code === pod_code);
    if (pol) {
      trade_lane.pol_name = pol.name;
      trade_lane.pol_country_id = pol.country_id;
    } else {
      throw new HttpErrors.BadRequest(
        `locode is not exists with code: ${pol_code}`,
      );
    }
 
    if (pod) {
      trade_lane.pod_name = pod.name;
      trade_lane.pod_country_id = pod.country_id;
    } else {
      throw new HttpErrors.BadRequest(
        `locode is not exists with code: ${pod_code}`,
      );
    }
 
    // create new trade lane
    const created_trade_lane = await this.tradeLaneRepo.create(trade_lane, options);
    created_trade_lane.activity = { 
      str: 'User {1} {2} the trade lane {3}', // User {1} {2} the trade lane {3}
      args: [
        Constants.AccessScope.Create,
        this.current_user.name,
        Constants.ActionLabel.Create,
        created_trade_lane.name
      ] 
    };
 
    return created_trade_lane;
  }
 
  /**
   * Copies the specified id.
   *
   * @param {number | string} id - The id to be copied.
   * @return {Promise<void>} A promise that resolves when the copy is complete.
   */
  async copy(id: number | string): Promise<AnyObject> {
    const trade_lane = await this.getByIdOrIdentifier(id);
    const new_name = `[Copy] ${trade_lane.name} - ${DateUtils.formatDateAndConvertTimeZone(new Date(), 'YYYY-MM-DD HH:mm:ss', this.current_user.timezone)}`;
    const trade_lane_flow = trade_lane.trade_lane_flow;
 
    // Copy trade-lane
    const new_trade_lane = await this.create({
      name: new_name,
      description: trade_lane.description,
      product: trade_lane.product,
      pol_code: trade_lane.pol_code,
      pod_code: trade_lane.pod_code,
      reta_from: trade_lane.reta_from,
      reta_to: trade_lane.reta_to,
      equipment: trade_lane.equipment,
      provisions: trade_lane.provisions,
      product_no: trade_lane.product_no,
      desired_temp: trade_lane.desired_temp,
      product_hazard_ids: trade_lane.product_hazard_ids,
      product_additional_information: trade_lane.product_additional_information,
      cargo_type: trade_lane.cargo_type,
      safety_data_sheet: (await this.duplicateS3Object(trade_lane.safety_data_sheet)).s3_uri,
      status: false,
    } as TradeLaneDto);
 
    const copied_activity = { 
      str: 'User {1} {2} the trade lane {3}', // User {1} {2} the trade lane {3}
      args: [
        Constants.AccessScope.Copy,
        this.current_user.name,
        Constants.ActionLabel.Copy,
        trade_lane.name,
      ],
    };
 
    if (!trade_lane_flow) {
      return { copied: { ...new_trade_lane, activity: copied_activity }, created: new_trade_lane };
    }
 
    // copy trade lane flow
    this.filter_builder = new FilterBuilder<TradeLane>();
    const new_trade_lane_flow = await this.upsertRefFlow(new_trade_lane.id, new TradeLaneFlowDto({
      personas: trade_lane_flow.personas.map( p => _.omit(p, 'id', 'trade_lane_flow_id')) as TradeLaneFlowPersona[],
      journey_points: trade_lane_flow.journey_points.map( jp => _.omit(jp, 'id', 'trade_lane_flow_id')) as TradeLaneFlowJourneyPoint[],
      flow_status: false,
    }));
 
    new_trade_lane_flow.activity = copied_activity;
 
    return { copied: new_trade_lane_flow, created: new_trade_lane };
  }
 
  /**
   * Update trade lane by id or identifier
   * @param id The id or identifier of trade lane
   * @param tradelane The new trade lane info
   * @returns Promise<void>
   */
  async updateByIdOrIdentifier(id: string | number, tradelane: TradeLaneDto) {
    this.addWhereIdOrIdentifier(id);
 
    // build where with current company of logged-in user
    this._addWhereCurrentCompany();
 
    const curr_inst = await this.tradeLaneRepo.findOne(
      this.filter_builder.build(),
    );
 
    if (!curr_inst) {
      throw new EntityNotFoundError(this.tradeLaneRepo.entityClass, id);
    }
 
    // eslint-disable-next-line prefer-const
    let { reta_from, reta_to, pod_code, pol_code } = tradelane;
    reta_from = reta_from || curr_inst.reta_from;
    reta_to = reta_to || curr_inst.reta_to;
 
    // validate reta
    this.validateReta(reta_from, reta_to);
 
    // ensure the pod active
    if (pod_code) {
      const pod = await this.locodeRepository.findOne({
        where: {
          code: pod_code,
        },
      });
      if (pod) {
        tradelane.pod_name = pod.name;
        tradelane.pod_country_id = pod.country_id;
      } else {
        throw new HttpErrors.BadRequest(
          `locode is not exists with code: ${pod_code}`,
        );
      }
    }
 
    // ensure the pol active
    if (pol_code) {
      const pol = await this.locodeRepository.findOne({
        where: {
          code: pol_code,
        },
      });
      if (pol) {
        tradelane.pol_name = pol.name;
        tradelane.pol_country_id = pol.country_id;
      } else {
        throw new HttpErrors.BadRequest(
          `locode is not exists with code: ${pol_code}`,
        );
      }
    }
 
    // update the tradelane.
    await this.tradeLaneRepo.updateAll(
      tradelane,
      this.filter_builder.build().where,
    );
 
    if (
      tradelane.safety_data_sheet &&
      tradelane.safety_data_sheet !== curr_inst.safety_data_sheet
    ) {
      super.cleanUpStorage(curr_inst.safety_data_sheet);
    }
 
    curr_inst.activity = { 
      str: 'User {1} {2} the trade lane {3}', // User {1} {2} the trade lane {3}
      args: [
        Constants.AccessScope.Update,
        this.current_user.name,
        Constants.ActionLabel.Update,
        curr_inst.name
      ] 
    };
 
    // return to write logs
    return curr_inst;
  }
 
  /**
   * Gets by id or identifier
   * @param id
   * @returns by id or identifier
   */
  async getByIdOrIdentifier(id: string | number): Promise<TradeLane> {
    this.addWhereIdOrIdentifier(id);
 
    // For public controller
    this._addWhereCurrentCompany();
 
    // add creator, modifier
    this._addIncludeCreator(this.filter_builder);
    this._addIncludeModifier(this.filter_builder);
 
    // add pol_country
    this._addIncludeCountry(this.filter_builder, 'pol_country');
 
    // add pod_country
    this._addIncludeCountry(this.filter_builder, 'pod_country');
 
    // add company
    this._addIncludeCompany(this.filter_builder);
 
    // get flows used by trade lane.
    this.filter_builder.include({
      relation: 'flows',
      scope: {
        fields: {
          id: true,
          trade_lane_id: true,
          name: true,
          status: true,
          stats: true,
        },
        order: ['created_date DESC'],
      },
    });
 
    // get trade_lane_flow used by trade lane.
    this.filter_builder.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'],
            },
          },
        ],
      },
    });
 
    // find tradeLane.
    const trade_lane = await this.tradeLaneRepo.findOne(
      this.filter_builder.build(), { maxDepthOfQuery: Number.MAX_SAFE_INTEGER },
    );
 
    if (!trade_lane) {
      throw new EntityNotFoundError(this.tradeLaneRepo.entityClass, id);
    }
 
    return trade_lane;
  }
 
  /**
   * Delete trade lane by id or identifier
   * @param id The trade lane id or identifier
   */
  async deleteByIdOrIdentifier(id: number | string) {
    this.addWhereIdOrIdentifier(id);
 
    // For public controller
    this._addWhereCurrentCompany();
 
    // get flows used by trade lane.
    this.filter_builder.include({
      relation: 'flows',
      scope: {
        fields: {
          id: true,
          trade_lane_id: true,
          name: true,
        },
      },
    });
 
    const trade_lane = await this.tradeLaneRepo.findOne(
      this.filter_builder.build(),
    );
 
    if (!trade_lane) {
      throw new EntityNotFoundError(this.tradeLaneRepo.entityClass, id);
    }
 
    if (trade_lane.status) {
      throw new HttpErrors.BadRequest("Don't allow delete active trade lane");
    }
 
    if (trade_lane?.flows?.length > 0) {
      throw new HttpErrors.BadRequest("Don't allow delete trade lane with flows");
    }
 
    await this.tradeLaneRepo.deleteAll(this.filter_builder.build().where);
 
    super.cleanUpStorage(trade_lane.safety_data_sheet);
 
    trade_lane.activity = { 
      str: 'User {1} {2} the trade lane {3}', // User {1} {2} the trade lane {3}
      args: [
        Constants.AccessScope.Delete,
        this.current_user.name,
        Constants.ActionLabel.Delete,
        trade_lane.name
      ] 
    };
 
    // return to write logs
    return trade_lane;
  }
 
  /**
   * Get array trade lane based on filter.
   * @param filter
   */
  async find(option: Options): Promise<BaseResponses<TradeLaneView>> {
    const filter_builder = new FilterBuilder<TradeLaneView>();
    filter_builder.filter = this.filter_builder.filter;
 
    // add creator, modifier
    this._addIncludeCreator(filter_builder);
    this._addIncludeModifier(filter_builder);
 
    // add pol_country
    this._addIncludeCountry(filter_builder, 'pol_country');
 
    // add pod_country
    this._addIncludeCountry(filter_builder, 'pod_country');
 
    this._addExcludeFields(filter_builder);
    
    this._addIncludeCompany(filter_builder);
 
    const tradelane_list = await this.tradeLaneViewRepo.fillRelation(
      filter_builder,
    );
 
    // implement default flow
    if (option.is_private) {
      const tradelane_ids = tradelane_list.data.map(x => x.id);
      if (tradelane_ids.length > 0) {
        const flow_list = await this.flowDefaultRepo.find({
          where: {
            trade_lane_id: {
              inq: tradelane_ids,
            },
          },
          fields: {
            id: true,
            trade_lane_id: true,
          },
        });
        tradelane_list.data.map(x => {
          x.default_flow = flow_list.filter(
            y => y.trade_lane_id === x.id,
          ).length;
        });
      }
    }
 
    return tradelane_list;
  }
 
  /**
   * Adds exclude fields
   * @param filterBuilder
   */
  private _addExcludeFields(filterBuilder: FilterBuilder) {
    filterBuilder.fields({
      created_date: false,
      created_by: false,
      modified_date: false,
      modified_by: false,
    });
  }
 
  /**
   * Builds the query for trade lane
   * @param q The query string.
   */
  async buildSearchQuery(q?: string) {
    if (!q) {
      return;
    }
 
    const ilike_value = this.buildILikeValue(q);
    // "FILTER: name OR product OR equipment Should be a LIKE search"
    this.filter_builder.impose({
      or: [
        {
          name: ilike_value,
        },
        {
          equipment: ilike_value,
        },
        {
          product: ilike_value,
        },
      ],
    });
  }
 
  /**
   * Builds the query country for trade lane.
   * @param country The country id.
   */
  async buildCountryQuery(country?: number) {
    if (!country) {
      return;
    }
 
    // FILTER: pol_country.id OR pod_country.id
    this.filter_builder.impose({
      or: [
        {
          pol_country_id: country,
        },
        {
          pod_country_id: country,
        },
      ],
    });
  }
 
  /**
   * Ensure get active record
   * @protected
   * @param filterBuilder The FilterBuilder
   * @param id The id or identifier
   */
  public ensureRightAccessRecord(): void {
    const _where: Where = {
      company_id: this.current_user.company_id
    };
 
    this.filter_builder.impose(_where);
  }
 
  /**
   * Validates the given row of TradeLane data in a CSV file.
   *
   * @param {TradeLaneRow} row - The row of TradeLane data to validate.
   * @return {Promise<void>} - A Promise that resolves when the validation is complete.
   */
  async validateRowsCsv(row: TradeLaneRow): Promise<void> {
    await validateValueAgainstSchema(row, tradeLaneRowSchema);
 
    try {
      row.reta_from = JSON.parse(row.reta_from);
    } catch (error) {
      throw new HttpErrors.BadRequest(`The reta_from should be an integer`);
    }
 
    try {
      row.reta_to = JSON.parse(row.reta_to);
    } catch (error) {
      throw new HttpErrors.BadRequest(`The reta_to should be an integer`);
    }
 
    row.status = true;
  }
 
  /**
   * Creates trade lane from csv files
   * @param [uploadedFiles]
   * @returns
   */
  async createTradeLaneFromCSV(uploadedFiles?: UploadFileType) {
    const csvParser = new CSVParser<TradeLaneRow>(this);
    const tx = await this.tradeLaneRepo.beginTransaction(IsolationLevel.SERIALIZABLE);
    try {
      const results = await csvParser.createRecordsFromCSV(uploadedFiles, { transaction: tx })
      await tx.commit();
      return results;
    } catch (error) {
      await tx.rollback();
      throw new HttpErrors.BadRequest(error.message);
    }
  }
  
  /**
   * Upsert sample flow data for trade-lane
   * @param  {number} id
   * @param  {TradeLaneFlowDto} payload
   */
  async upsertRefFlow(id: number, payload: TradeLaneFlowDto, options: Options = {}) {
    // Validate Personas
    const number_personas_limit = +(process.env.NUMBER_PERSONA_LIMIT ?? 0);
    if (payload.personas.length > number_personas_limit) {
      throw new HttpErrors.BadRequest(
        `Allowed limit for persona reached. Please remove some persona for the flow.`,
      );
    }
    // --------------------------------------------------
    const tradeLane = await this.getByIdOrIdentifier(id);
    
    const { personas = [], journey_points = [] } = payload;
 
    tradeLane.flow_status = payload.flow_status;
    
    await this.tradeLaneRepo.updateById(id, { flow_status: payload.flow_status });
 
    options.tx = await this.tradeLaneFlowRepo.beginTransaction(IsolationLevel.SERIALIZABLE);
    const tradeLaneFlow = await this.tradeLaneFlowRepo.upsertWithWhere(
      {
        trade_lane_id: tradeLane.id
      },
      {
        trade_lane_id: tradeLane.id,
      }, 
      options
    ) ?? await this.tradeLaneFlowRepo.findOne({ where: { trade_lane_id: tradeLane.id }}, options);
 
    // Update personas for trade-lane-flow
    if (tradeLaneFlow?.id) {
      let creator_personas: AnyObject[] = [];
      if (personas?.length) {
        // Validate creator of trade-lane of personas must have in access list
        creator_personas = personas.filter((persona: AnyObject) => {
          return persona.company_id === this.current_user.company_id;
        });
        
        const createdTradelanePersonas = payload.personas.map(persona => {
          return new TradeLaneFlowPersonaDto({
            trade_lane_flow_id: tradeLaneFlow.id,
            persona_id: persona.persona_id,
            company_id: persona.company_id,
            order: persona.order,
          });
        });
        await this.tradeLaneFlowPersonaRepo.deleteAll({trade_lane_flow_id: tradeLaneFlow.id}, options);
        tradeLaneFlow.personas = await this.tradeLaneFlowPersonaRepo.createAll(createdTradelanePersonas, options);
      }
      // -----------------------------------------------------------------------
 
      // Update journey_points for trade-lane-flow
      if (journey_points?.length) {
        await this.tradeLaneFlowJourneyPointRepo.deleteAll({trade_lane_flow_id: tradeLaneFlow.id}, options);
        tradeLaneFlow.journey_points = [];
        const createdJourneyPoints = payload.journey_points.map((journey_point) => {
          // ------------------------------------------
 
          // Validate creator of trade-lane of personas must have in access list
          if (journey_point.persona && creator_personas.length) {
            const persona_found = journey_point.personas.filter((persona: AnyObject) => {
              return persona.persona_id === creator_personas[0].persona_id && 
              persona.order === creator_personas[0].order;
            });
            if (!persona_found?.length) {
              throw new HttpErrors.BadRequest(`Creator of trade-lane is missing from access list.`);
            }
          }
          // ------------------------------------------
 
          return new TradeLaneFlowJourneyPointDto({
            trade_lane_flow_id: tradeLaneFlow.id,
            order: journey_point.order,
            persona: journey_point.persona ?? undefined,
            actor: !journey_point.persona ? journey_point.actor : undefined,
            validator: journey_point?.validator ?? undefined,
            name: journey_point.name ?? '',
            personas: journey_point.personas ?? [],
            actions: journey_point.actions ?? [],
            expected_date_info: journey_point.expected_date_info ?? undefined,
          });
        });
        if (createdJourneyPoints?.length) {
          tradeLaneFlow.journey_points = await this.tradeLaneFlowJourneyPointRepo.createAll(createdJourneyPoints, options);
        }
        tradeLane.trade_lane_flow = tradeLaneFlow;
        await this.tradeLaneRepo.updateById(tradeLane.id, { trade_lane_flow_id: tradeLaneFlow.id }, options);
      }
 
      try {
        await options.tx.commit();
      } catch (error) {
        await options.tx.rollback();
        if (error instanceof EntityNotFoundError || error instanceof HttpErrors.BadRequest || error instanceof HttpErrors.NotFound) {
          throw error;
        }
        throw new HttpErrors.InternalServerError('An error occurred when update flow of tradelane!');
      }
    }
 
    tradeLane.activity = { 
      str: 'User {1} {2} the trade lane {3}', // User {1} {2} the trade lane {3}
      args: [
        Constants.AccessScope.Update,
        this.current_user.name,
        Constants.ActionLabel.Update,
        tradeLane.name
      ] 
    };
 
    return tradeLane;
  }
}