All files / src/services cargo.service.ts

13.66% Statements 22/161
0% Branches 0/210
5.56% Functions 1/18
12.74% Lines 20/157

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 5501x 1x             1x 1x 1x 1x                   1x   1x 1x 1x   1x     1x       2x   2x   2x   2x   2x   2x   2x   2x                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          
import { bind, BindingScope, service } from '@loopback/core';
import {
  EntityNotFoundError,
  FilterBuilder,
  Options,
  OrClause,
  repository,
} from '@loopback/repository';
import { HttpErrors } from '@loopback/rest';
import { FilesMappingDto, CargoDto } from '../dtos';
import { BaseResponses, Cargo, CargoWithRelations, Status } from '../models';
import {
  CompanyRepository,
  FilesMappingRepository,
  FlowJourneyPointRepository,
  CargoRepository,
  CargoViewRepository,
  UserViewRepository,
  CargoOverrideRepository,
} from '../repositories';
import { AnyObject, PdfTemplate } from '../types';
import { BaseService } from './base.service';
import { VerificationView, CargoView, CargoViewWithRelations } from '@logchain/models/views';
import { Constants } from '@logchain/configs';
import _ from 'lodash';
import { FlowService } from './flow.service';
@bind({ scope: BindingScope.TRANSIENT })
export class CargoService extends BaseService<Cargo> {
 
  @service(FlowService)
  public flowService: FlowService;
 
  constructor(
    @repository(CargoRepository)
    public cargo_repo: CargoRepository,
    @repository(CargoOverrideRepository)
    public cargo_override_repo: CargoOverrideRepository,
    @repository(CargoViewRepository)
    public cargo_view_repo: CargoViewRepository,
    @repository(FilesMappingRepository)
    public files_mapping_repo: FilesMappingRepository,
    @repository(CompanyRepository)
    public comp_repo: CompanyRepository,
    @repository(UserViewRepository)
    public userRepository: UserViewRepository,
    @repository(FlowJourneyPointRepository)
    public flowJourneyPointRepository: FlowJourneyPointRepository,
  ) {
    super();
  }
 
  /**
   * Make sure we got the right access.
   */
  public ensureRightAccessRecord(): void {
    this.filter_builder.impose({
      company_id: this.current_user.company_id,
      hidden: false,
    } as unknown as OrClause<Cargo>);
  }
 
  /**
   * Make sure we got the right user access.
   */
  public ensureUserAccessRecord(): void {
    const where = this.filter_builder.filter.where as AnyObject;
 
    if (where?.category_ids === undefined) {
      this.filter_builder.impose({
        granted_users: {
          contains: [this.current_user.id],
        },
      } as AnyObject);
    }
  }
 
  /**
   * Get array Cargo based on filter.
   * @param filter
   */
  async find(): Promise<BaseResponses<CargoViewWithRelations>> {
    this.ensureUserAccessRecord();
    const filter_builder = new FilterBuilder<CargoView>();
    filter_builder.filter = this.filter_builder.filter;
    this.addExtraFilter(filter_builder);
    this._addExcludeFields(filter_builder);
    return this.cargo_view_repo.fillRelation(filter_builder);
  }
 
  /**
   * update Cargo based on filter.
   * @param id
   *  Cargo
   */
  async updateByIdOrIdentifier(
    id: number,
    cargo: CargoDto,
    options: Options = {}
  ): Promise<CargoWithRelations> {
    this.addWhereIdOrIdentifier(id);
    this._addIncludeCompany(this.filter_builder);
    
    // Get instance of Cargo
    const current_cargo = await this.cargo_repo.findOne(
      this.filter_builder.build(),
    );
    if (!current_cargo) {
      throw new EntityNotFoundError(this.cargo_repo.entityClass, id);
    }
    const cargoDto = new CargoDto(current_cargo as unknown as CargoDto);
    
    // Can not switch status back to New
    if (
      cargo.status === Status.Cargo.New &&
      current_cargo.status !== Status.Cargo.New
    ) {
      throw new HttpErrors.BadRequest(
        `Can not change status to new ${cargo.status}`,
      );
    } else if ([Status.Cargo.Cancelled, Status.Cargo.Completed].includes(current_cargo.status)) {
      throw new HttpErrors.BadRequest(`This action was completed.`,);
    }
 
    // For external request
    if (options?.type_id) {
      const submittedType = (options?.type_id === Constants.Form.CargoCollection) 
      ? Constants.CargoActionType.CargoCollection 
      : Constants.CargoActionType.CargoDelivery;
      if (current_cargo.action_type !== submittedType) {
        throw new HttpErrors.BadRequest('Invalid Parameters: type_id.');
      }
    }
 
    if (Constants.cargoFinishedStatuses.includes(cargo.status)) {
      if (!cargo?.attachments?.length && !current_cargo?.documents?.length) {
        // Validate cargo in case this form is not attachment form
        if (!cargo.containers?.length) {
          throw new HttpErrors.BadRequest('Missing Parameters: containers.');
        }
 
        // We need to make sure all submitted containers are allowed (not completed and cancelled)
        const allowed_containers = await this.cargo_repo.getDefaultContainers(
          current_cargo.flow_id, current_cargo.action_type, current_cargo.journey_point_id
        );
        const submitted_valid_containers = cargo.containers.filter((container: AnyObject) => {
          return allowed_containers.includes(container.container_no);
        });
 
        if (submitted_valid_containers.length !== cargo.containers.length) {
          throw new HttpErrors.BadRequest('Invalid Parameters: containers.');
        }
      }
    }
    
    // Create override record
    if (options?.oldDocument) {
      const overriden_cargo = await this.cargo_override_repo.create({ 
        original_id: current_cargo.id, 
        ..._.omit(options.oldDocument, ['id', 'created_date', 'updated_date']),
      });
      // Transfer old attachments
      await this.transferOldAttachments(
        current_cargo.id, 
        overriden_cargo.id, 
        this.cargo_repo.getPostgresTableName(), 
        'Cargo'
      );
      // -------------------------------
    }
 
    // For external request
    if (cargo.attachments && typeof(cargo.attachments) === 'string') {
      // For external request user provide base64 content
      const buf = Buffer.from(cargo.attachments as unknown as string, 'base64')
      cargo.attachments = [`documents/cargoes/${cargoDto.company.identifier}/${cargoDto.id}.pdf`];
      const param = {
        Key: cargo.attachments[0],
        Body: buf,
        ContentEncoding: 'base64',
        ContentType: 'application/pdf',
        ServerSideEncryption: 'AES256',
      };
      await this.s3_service.putObject(param);
    }
 
    // Process form upload
    const { attachments = [] } = cargo;
    if (attachments.length) {
      for (const attachment of attachments as unknown as AnyObject[]) {
        let uri = '';
        if (typeof(attachment) !== 'string') {
          uri = attachment.uri;
        } else {
          uri = attachment;
        }
        const metadata = await this.s3_service.getObjectMetadata(uri);
        if (metadata) {
          const e_tag = metadata.ETag?.slice(1, -1);
          await this.files_mapping_repo.upsertWithWhere(
            {
              hash: e_tag,
              external_id: id,
            },
            {
              table_name: this.cargo_repo.getPostgresTableName(),
              field_name: `Cargo`,
              uri: uri,
              version: metadata.VersionId,
              external_id: id,
              hash: e_tag,
              last_update_date: metadata.LastModified,
              added_reason: attachment.reason ?? '',
            },
          );
        }
      }
    } else {
      // Delete old attachments
      await this.deleteOldAttachments(this.cargo_repo.getPostgresTableName(), id);
    }
 
    if ([...Constants.cargoFinishedStatuses, Status.Cargo.InProgress].includes(cargo.status)) {
      cargo.system_actual_date = new Date();
    }
 
    // Update Cargo after finished all validation above
    await this.cargo_repo.updateById(id, cargo);
 
    cargoDto.status = cargo.status;
    // Generate the pdf for the cargo.
    if (
      current_cargo.status !== cargo.status &&
      Constants.cargoFinishedStatuses.includes(cargo.status)
    ) {
      options.forPDFCreation = true; // This flag is used to create pdf with seperate file_mappings
      const newest_cargo = await this.getByIdOrIdentifier(current_cargo.id, options) as unknown as CargoDto;
      // Push pdf of overriden action to the last page of overriding action
      if (options?.oldDocument) {
        const files = options?.forAdditional ? newest_cargo.additional_documents : newest_cargo.documents;
        files.unshift(new FilesMappingDto({ uri: options?.oldDocument.uri }));
      }
      const data: PdfTemplate = {
        content: { 
          ...newest_cargo, 
          timezone: newest_cargo?.company?.timezone ?? '', 
          validator_id: await this.getValidatorFromStep(newest_cargo.journey_point_id)
        },
        model_name: this.cargo_repo.getPostgresTableName(),
      };
      await this.generatePdf(data);
 
      // Create new action date for remaining container
      // #42870 - [Bug][Cargo Form] There is not a new record created after the action was completed on the form
      if (!current_cargo.override_by_id 
        && newest_cargo.cancelled_action !== Status.ActionAfterCancelled.NewAction 
        && newest_cargo.allowed_containers?.length
        && !options?.oldDocument
      ) {
        const oldDocument = await this.cargo_repo.findById(newest_cargo.id);
        const createdParam = new CargoDto(_.omit(
            oldDocument,
            'id',
            'containers',
            'is_pdf_created',
            'uri',
            'version',
            'hash',
            'blockchain_tx',
            'pdf_attempt',
            'created_date',
            'modified_date'
          ) as unknown as CargoDto);
        createdParam.containers = newest_cargo.allowed_containers?.map(container_no => {
          return {
            container_no,
            seal_no: '',
            tare_mass: '',
            total_gross: '',
          }
        }) ?? [];
        await this.cargo_repo.create({ 
          ...createdParam,
          status: Status.Cargo.New,
          created_date: new Date(),
        });
      }
      // ------------------------------------------------------
    }
    const action = Constants.CargoTypeText[cargoDto?.action_type ?? 0] ?? '';
    current_cargo.activity = { 
      str: '{0} is {1} for {2}', 
      args: [
        current_cargo.override_by_id ? action + ' overridden' : action,
        (cargoDto.status_name() as string).toLowerCase(),
        cargoDto.company?.name ?? ''
      ] 
    };
 
    return current_cargo;
  }
 
  /**
   * Get Cargo by id or identifier
   * @param id The user id
   * @param filter The filter
   * @returns Promise<Cargo | null>
   */
  async getByIdOrIdentifier(id: number, options?: Options): Promise<CargoViewWithRelations> {
    this.addWhereIdOrIdentifier(id);
    // Load relation for Cargo
    this.addExtraFilter(this.filter_builder);
    this.addExtraCompanyFilter(this.filter_builder);
 
    const filter_builder = new FilterBuilder<CargoView>();
    filter_builder.filter = this.filter_builder.filter;
 
    const cargo = await this.cargo_view_repo.findOne(
      filter_builder.build(),
      {
        get_reference: true,
      },
    );
 
    if (!cargo) {
      throw new EntityNotFoundError(this.cargo_view_repo.entityClass, id);
    }
 
    // Get default container list for cargo form
    cargo.allowed_containers = await this.cargo_repo.getDefaultContainers(cargo.flow_id, cargo.action_type, cargo.journey_point_id);
    if (cargo.containers?.length && cargo.allowed_containers?.length) {
      const selected_containers = cargo.containers.map((container: AnyObject) => {
        return container.container_no;
      });
      cargo.allowed_containers = cargo.allowed_containers.filter((c: string) => !selected_containers.includes(c));
    }
    // ------------------------------------------
 
    // Get all documents by flow_action_id
    const all_documents = await this.cargo_repo.find({
      fields: ['id'],
      where: {
        flow_action_id: cargo.flow_action_id,
      }
    });
 
    // Init default data
    cargo.documents = [];
    cargo.additional_documents = [];
 
    if (all_documents?.length) {
      let document_ids = all_documents.map((d) => d.id);
      if (options?.forPDFCreation) {
        document_ids = [id];
      }
      const documents = await this.files_mapping_repo.find({
        where: {
          external_id: { inq: document_ids },
          table_name: this.cargo_repo.getPostgresTableName(),
        },
        fields: {
          external_id: false,
          table_name: false,
        },
        order: ['last_update_date DESC'],
      });
      if (documents?.length) {
        documents.map((d) => {
          if (!d.added_reason) {
            cargo.documents.push(d);
          } else {
            cargo.additional_documents.push(d);
          }
        });
      }
    }
 
    // Fetch verification information
    cargo.verification = await this.verification_view_repo.findOne({
      where: {
        external_id: cargo.id,
        table_name: this.cargo_repo.getPostgresTableName(),
        is_actor: false,
      },
    }) as VerificationView;
 
    return cargo;
  }
 
  /**
   * Validates the given ID and payload.
   *
   * @param {number} id - The ID to validate.
   * @param {AnyObject} payload - The payload to validate.
   * @throws {EntityNotFoundError} If the old document is not found.
   * @return {Promise<any>} The result of the function.
   */
  async validate(id: number, payload: AnyObject, options?: Options): Promise<AnyObject> {
    const oldOriginalDocument = await this.cargo_repo.findById(id);
    if (!oldOriginalDocument || ![Status.Cargo.Completed, Status.Cargo.Cancelled].includes(oldOriginalDocument.status)) {
      throw new EntityNotFoundError(this.cargo_repo.entityClass, id);
    }
    const oldDocument = await this.cargo_repo.findOne({
      where: {
        flow_action_id: oldOriginalDocument.flow_action_id,
        status: { nin: [Status.Cargo.New, Status.Cargo.InProgress] },
      },
      order: ['id DESC'],
      limit: 1,
    });
    if (!oldDocument) {
      throw new EntityNotFoundError(this.cargo_repo.entityClass, id);
    }
    const createdParam = new CargoDto(_.omit(oldDocument, 'id') as unknown as CargoDto);
    const newDocument = await this.cargo_repo.create({ 
      ...createdParam,
      status: Status.Document.New,
      created_date: new Date(),
      hidden: true,
    });
 
    const updatedParams = {
      attachments: payload.documents,
      status: oldDocument.status,
    } as CargoDto;
 
    return this.updateByIdOrIdentifier(newDocument.id, updatedParams, {
      oldDocument: oldDocument as unknown as CargoDto,
      forAdditional: true,
      ...options,
    });
  }
 
  /**
   * Overrides an existing record with the provided payload.
   *
   * @param {number} id - The ID of the entry record to override.
   * @return {Promise<CargoDto>} A promise that resolves to the newly created entry record.
   * @throws {EntityNotFoundError} If the old document is not found.
   */
  async override(id: number, payload: CargoDto): Promise<AnyObject> {
    // Validate override document is valid for overriding
    const oldDocument = await this.cargo_repo.findById(id);
 
    // Make sure old document exists
    if (!oldDocument) {
      throw new EntityNotFoundError(this.cargo_repo.entityClass, id);
    }
    // ---------------------------------------
 
    // Make sure overrided action must be completed
    if (Constants.loadingFinishedStatuses.includes(oldDocument.status) === false) {
      throw new HttpErrors.BadRequest('Action was not completed yet.');
    }
    // ---------------------------------------
 
    // Make sure overrided action don't have modification about form type (form to attachment or vice versa)
    if (oldDocument.form_type !== payload.form_type) {
      throw new HttpErrors.BadRequest('The action can not be changed from form to attachment or vice versa.');
    }
    // ---------------------------------------
 
    // Mapping from old document to override document
    const createdParam = new CargoDto(oldDocument as unknown as CargoDto);
    Object.assign(createdParam, payload);
    createdParam.status = oldDocument.status;
    createdParam.created_date = new Date();
    createdParam.modified_date = new Date();
    // Mark this action was overriden by current user
    createdParam.override_by_id = this.current_user.id;
    // ---------------------------------------    
 
    // Reset status to in progress
    await this.cargo_repo.updateById(oldDocument.id, { status: Status.Cargo.InProgress });
    const newAction = await this.updateByIdOrIdentifier(oldDocument.id, createdParam, { oldDocument });
    // ---------------------------------------
 
    return newAction;
  }
 
  /**
   * Add extra filter for Cargo
   * @param filterBuilder The filter builder instance
   * @param options The options
   * @return Filter
   */
  addExtraFilter(filterBuilder: FilterBuilder, options?: Options) {
    super._addIncludeModifier(filterBuilder);
  }
 
  /**
   * Add extra filter for Cargo company
   * @param filterBuilder The filter builder instance
   * @param options The options
   * @return Filter
   */
  addExtraCompanyFilter(filterBuilder: FilterBuilder, options?: Options) {
    super._addIncludeModifier(filterBuilder);
    filterBuilder.include({
      relation: 'company',
      scope: {
        fields: {
          id: true,
          identifier: true,
          name: true,
          timezone: true,
        },
      },
    });
  }
 
  /**
   * Builds the query for cargo
   * @param q The query string.
   */
  async buildSearchQuery(q?: string) {
    if (!q) {
      return;
    }
    const ilike_value = this.buildILikeValue(q);
    const or_clause: OrClause<CargoView> = {
      or: [
        {
          flow_id: ilike_value as unknown as number,
        },
        {
          flow_name: ilike_value,
        },
        {
          container_no: ilike_value,
        },
        {
          product_no: ilike_value,
        },
      ],
    };
    this.filter_builder.impose(or_clause);
  }
 
  /**
   * Add extra filter (excluded) on fields
   * @param  {FilterBuilder} filterBuilder
   */
  private _addExcludeFields(filterBuilder: FilterBuilder) {
    filterBuilder.fields({
      remarks: false,
      created_date: false,
    });
  }
}