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

9.92% Statements 13/131
0% Branches 0/105
0% Functions 0/13
8.59% Lines 11/128

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 4451x 1x           1x 1x 1x 1x 1x     1x   1x     1x     1x                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            
import { bind, /* inject, */ BindingScope, service } from '@loopback/core';
import {
  EntityNotFoundError,
  FilterBuilder,
  Options,
  repository,
} from '@loopback/repository';
import { HttpErrors } from '@loopback/rest';
import { isEmpty } from 'lodash';
import { BaseService, ExternalService, FlowService, MessageService } from '.';
import { BaseResponses, Status, Verification } from '../models';
import { FormRepository, VerificationRepository, VerificationViewRepository } from '../repositories';
import { AnyObject, PdfTemplate, RecipientNotification, ReplyMessage } from '../types';
import { VerificationView } from '@logchain/models/views/verification.view';
import { Constants } from '@logchain/configs';
import { UserView } from '@logchain/models/views';
import { FilesMappingDto } from '@logchain/dtos';
 
@bind({ scope: BindingScope.TRANSIENT })
export class FlowAlertService extends BaseService<Verification> {
 
  @service(FlowService)
  public flowService: FlowService;
 
  public table2services: AnyObject = {};
 
  constructor(
    @service(ExternalService)
    public externalService: ExternalService,
    @repository(VerificationRepository)
    public verification_repo: VerificationRepository,
    @repository(VerificationViewRepository)
    public verification_view_repo: VerificationViewRepository,
    @repository(FormRepository)
    public form_repo: FormRepository,
    @service(MessageService)
    public messageService: MessageService
  ) {
    super();
    this.table2services = {
      'entry_records': this.externalService.entryRecordService,
      'documents': this.externalService.documentService,
      'loadings': this.externalService.loadingService,
      'onloadings': this.externalService.onLoadingService,
      'lifts': this.externalService.liftService,
      'weighbridges': this.externalService.weighbridgeService,
      'eirs': this.externalService.eirService,
      'bols': this.externalService.bolService,
      'transports': this.externalService.transportService,
      'vessels': this.externalService.vesselService,
      'cargoes': this.externalService.cargoService,
      'dgds': this.externalService.dgdService,
    };
  }
 
  /**
   * Builds the query for alerts
   * @param q The query string.
   */
  async buildSearchQuery(q?: string) {
    if (!q) {
      return;
    }
 
    const ilike_value = this.buildILikeValue(q);
    const forms = await this.form_repo.find({
      fields: ['id', 'name'],
      where: {
        name: ilike_value,
      },
    });
    const form_ids = forms.map(f => {
      return f.id;
    });
 
    this.filter_builder.impose({
      or: [
        {
          form_id: {
            inq: form_ids,
          },
        },
      ],
    });
  }
 
  /**
   * Ensure get right records.
   */
  async ensureRightAccessRecord(): Promise<void> {
    this.filter_builder.impose({
      or: [
        {
          verification_id: this.current_user.id
        },
        {
          verification_company_id: this.current_user.company_id
        },
      ],
      is_actor: false,
    });
  }
 
  /**
   * Get list alert for current user.
   * @param options The options.
   */
  async find(options?: Options): Promise<BaseResponses<VerificationView>> {
    const filter_builder = new FilterBuilder<VerificationView>();
    filter_builder.filter = this.filter_builder.filter;
 
    return this.verification_view_repo.findWithPaging(filter_builder.build());
  }
 
  /**
   * Validated or Rejected the documents.
   * @param id The id of Verification
   * @param verification The verification information
   */
  async updateByIdOrIdentifier(
    id: number,
    data: Partial<Verification> & { status: number },
  ): Promise<Verification> {
    try {
      this.addWhereIdOrIdentifier(id);
      const verification = await this.verification_repo.findOne(
        this.filter_builder.build(),
      );
 
      // validate status of verification
      if (!verification) {
        throw new EntityNotFoundError(this.verification_repo.entityClass, id);
      }
 
      if (verification.status !== Status.Verification.ForValidation) {
        throw new HttpErrors.BadRequest(
          `You already Validated or Rejected, Current status: ${verification.status}`,
        );
      }
 
      // Update status for verification
      await this.verification_repo.updateAll(
        {
          verification_id: this.current_user.id,
          status: data.status,
          cancelled_reason: data.status === Status.Verification.Rejected ? data.cancelled_reason : undefined,
        },
        {
          external_id: verification.external_id,
          table_name: verification.table_name,
          is_actor: false,
        },
      );
 
      // Create new action when verification was rejected
      // int_flow_action_id int4, str_table_name text, int_form_id int4, int_external_id int4
      if (data.status === Status.Verification.Rejected) {
        await this.verification_repo.execute('SELECT cancel_flow_action_when_verification_was_rejected($1, $2, $3, $4);', [
          verification.flow_action_id,
          verification.table_name,
          verification.form_id,
          verification.external_id,
        ]);
      }
      // -----------------------------------------
 
      // Send mail to actor to confirm that the documents have been validated or rejected by validator
      const actor_verification = await this.verification_repo.findOne({
        where: {
          flow_action_id: verification.flow_action_id,
          is_actor: true,
        },
      });
 
      if (!actor_verification) {
        throw new HttpErrors.BadRequest(`Not found actor verification on flow ${verification.flow_id}`);
      }
 
      const validator_verification = await this.verification_repo.findById(
        verification.id,
      );
 
      if (!validator_verification) {
        throw new HttpErrors.BadRequest(`Not found validator verification on flow ${verification.flow_id}`);
      }
      // -----------------------------------------
 
      // Send message to generate pdf
      const actor = await this.user_view_repo.findById(actor_verification.verification_id);
      const param: PdfTemplate = {
        content: {
          ...(await this._getContentModel(verification, actor)),
          timezone: this.current_user.timezone,
          validator_id: this.current_user.company_id,
          call_from_validation: true,
        },
        model_name: verification.table_name
      };
      const validator_id = actor_verification.verification_company_id;
      const validator_name = (await this.user_view_repo.findById(this.current_user.id)).name;
      const validator_date = new Date();
      const action_author = actor.name;
      const action_date = actor_verification.created_date;
      await this.generatePdf(param, { action_author, action_date, validating_status: data.status, validator_id, validator_name, validator_date });
      // -----------------------------------------
 
      let overridenDocument = null;
      try {
        const overrideSQL = `SELECT * FROM ${verification.table_name} WHERE id = ${verification.external_id} AND override_by_id IS NOT NULL`;
        overridenDocument = (await this.verification_repo.execute(overrideSQL))?.[0];
      } catch (error) {
        overridenDocument = null;
        console.log('Error while getting overriden document');
      }
      const tasks = [
        !overridenDocument && (await this._sendEmailToVerification(validator_verification)),
        !overridenDocument && (await this._sendNotificationToActor(actor_verification, validator_verification)),
        await this.flowService.checkAndNotifyUsersWhenFlowCompeted({ flow_id: verification.flow_id } as ReplyMessage),
        overridenDocument && (await this._sendEmailAndNotificationForOverridenDocument(actor_verification, validator_verification)),
      ];
      await Promise.all(tasks.filter(t => !!t));
 
      return verification;
    } catch (error) {
      throw new HttpErrors.BadRequest(error.message);
    }
  }
 
  /**
   * Gets by id or identifier
   * @param id The id of transports
   * @returns Promise<Transport>
   */
  async getByIdOrIdentifier(id: string | number): Promise<AnyObject> {
    this.addWhereIdOrIdentifier(id);
    this.filter_builder.include({
      relation: 'form',
    });
 
    const verification = await this.verification_view_repo.findOne(
      this.filter_builder.build(),
    );
 
    if (!verification) {
      throw new EntityNotFoundError(this.verification_repo.entityClass, id);
    }
 
    const sql = `SELECT build_action_for_journey($1, $2, $3, $4) as data;`;
    const resl = await this.verification_repo.execute(sql, [
      verification.flow_action_id,
      verification.form_id,
      verification.actions_name,
      verification.external_id,
    ]);
 
    if (!resl || !resl.length || isEmpty(resl[0].data)) {
      throw new EntityNotFoundError(this.verification_repo.entityClass, id);
    }
 
    const data = resl[0].data;
    const { consensus, ...documents } = data.documents[0];
    return {
      id: verification.id,
      status: verification.status,
      name: data.name,
      consensus,
      documents,
    };
  }
 
  /**
   * Sends an email to the user for document verification.
   *
   * @param {Verification} actor_verification - The verification performed by the actor.
   * @param {Verification} validator_verification - The verification to be sent in the email.
   * @param {Options} [options] - Optional parameters for the function.
   * @return {Promise<void>} A promise that resolves when the email is sent successfully.
   */
  private async _sendEmailToVerification(
    validator_verification: Verification,
    options?: Options
  ): Promise<void> {
    const { verification_id, form_id } = validator_verification;
    if (isNaN(verification_id) || isNaN(form_id)) {
      return;
    }
 
    const action = await this.flow_action_repo_base.findById(validator_verification.flow_action_id);
    let form_name = action.title;
    if (form_id !== 0) {
      const form = await this.form_repo.findById(form_id);
      form_name = form.name;
    }
 
    const company_ids = [validator_verification.verification_company_id];
    const emailTemplate = validator_verification.status === Status.Verification.Validated
      ? Constants.Email.InformUserAfterApprovedDocument
      : Constants.Email.InformUserAfterRejectedDocument;
 
    await this.flowService.sendMailToAllCompanies(validator_verification.flow_id, {
      template: emailTemplate,
      company_ids,
      feature_id: validator_verification.external_id,
      feature_name: form_name,
      cancelled_reason: validator_verification?.cancelled_reason ?? '',
      rejected_reason: validator_verification?.cancelled_reason ?? '',
    });
  }
 
  /**
   * Sends a notification to the actor regarding the validation of a document.
   *
   * @param {Verification} actor_verification - The verification performed by the actor.
   * @param {Verification} validator_verification - The verification performed by the validator.
   * @return {Promise<void>} A promise that resolves when the notification is sent successfully.
   */
  private async _sendNotificationToActor(
    actor_verification: Verification,
    validator_verification: Verification,
    options?: Options
  ): Promise<void> {
    const action = await this.flow_action_repo_base.findById(actor_verification.flow_action_id);
    let form_name = action.title;
    if (actor_verification.form_id !== 0) {
      const form = await this.form_repo.findById(actor_verification.form_id);
      form_name = form.name;
    }
 
    const validator = await this.user_view_repo.findById(validator_verification.verification_id);
    const actor = await this.user_view_repo.findById(actor_verification.verification_id);
    const template = validator_verification.status === Status.Verification.Validated
      ? Constants.Notification.VerificationsValidated
      : Constants.Notification.VerificationsRejected;
    const identities: RecipientNotification[] = [];
    const link = this._buildHrefForFlow(validator_verification.external_id, validator_verification.table_name);
    identities.push({
      sub: actor.sub,
      settings: actor.settings,
      language: actor.language,
      replacement_data: {
        form_name,
        feature_id: validator_verification.external_id,
        feature_name: form_name,
        link,
        validator_name: validator.name,
        rejection_reason: validator_verification?.cancelled_reason ?? '',
      },
    });
 
    // Send notification
    await this.notification_service.sendBulkNotifications(template, identities);
  }
 
  /**
   * Sends an email to the user for document verification.
   *
   * @param {Verification} actor_verification - The verification performed by the actor.
   * @param {Verification} validator_verification - The verification to be sent in the email.
   * @param {Options} [options] - Optional parameters for the function.
   * @return {Promise<void>} A promise that resolves when the email is sent successfully.
   */
  private async _sendEmailAndNotificationForOverridenDocument(
    actor_verification: Verification,
    validator_verification: Verification,
    options?: Options
  ): Promise<void> {
    const { verification_id, form_id } = validator_verification;
    if (isNaN(verification_id) || isNaN(form_id)) {
      return;
    }
 
    const action = await this.flow_action_repo_base.findById(validator_verification.flow_action_id);
    let form_name = action.title;
    if (form_id !== 0) {
      const form = await this.form_repo.findById(form_id);
      form_name = form.name;
    }
 
    let company_ids = [];
    if (validator_verification.status === Status.Verification.Validated) {
      company_ids = await this.flow_journey_point_repo2.getCompanyIdsInStep(validator_verification.flow_journey_point_id);
    } else {
      const actor = await this.user_view_repo.findById(actor_verification.verification_id);
      company_ids = [actor.company_id];
    }
    const emailTemplate = validator_verification.status === Status.Verification.Validated
      ? Constants.Email.EM101
      : Constants.Email.EM103;
    const notificationTemplate = validator_verification.status === Status.Verification.Validated
      ? Constants.Notification.EM101
      : Constants.Notification.EM103;
 
    await this.flowService.sendMailToAllCompanies(validator_verification.flow_id, {
      template: emailTemplate,
      key: notificationTemplate,
      company_ids,
      feature_id: validator_verification.external_id,
      feature_name: form_name,
      cancelled_reason: validator_verification?.cancelled_reason ?? '',
      rejected_reason: validator_verification?.cancelled_reason ?? '',
    });
  }
 
  /**
   * Builds an href for a flow based on the provided id and table.
   *
   * @param {number} id - The id of the flow.
   * @param {string} table - The table name to use for building the href.
   * @return {string} The built href or an empty string if the table is not found.
   */
  private _buildHrefForFlow(id: number, table: string): string {
    if (Constants.table2links[table]) {
      return Constants.table2links[table].replace('{id}', id.toString());
    }
 
    return '';
  }
 
  /**
   * Retrieves the content model for a given verification.
   *
   * @param {Verification} verification - The verification object containing the flow action ID.
   * @return {Promise<AnyObject>} The content model associated with the flow action.
   */
  private async _getContentModel(verification: Verification, actor: UserView): Promise<AnyObject> {
    const currentCompanyId = this.current_user.company_id;
    const serviceObj = this.table2services[verification.table_name];
    // Swap between actor and validator to get action data
    serviceObj.current_user.company_id = actor.company_id;
    const objContent = await serviceObj.getByIdOrIdentifier(verification.external_id);
    serviceObj.current_user.company_id = currentCompanyId;
 
    // Push old document to list uri of new document (only for the case override)
    if (objContent?.override_by_id) {
      if (verification.table_name === this.entry_record_repo.getPostgresTableName()) {
        objContent.checklists = [...objContent.checklists, new FilesMappingDto({ uri: objContent.uri })];
      } else {
        objContent.documents = [...objContent.documents, new FilesMappingDto({ uri: objContent.uri })];
      }
    }
 
    return objContent;
  }
}