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 | 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x | import {
bind, BindingScope, inject, service,
} from '@loopback/core';
import { AnyObject, DataObject, Options, repository } from '@loopback/repository';
import { CompleteMultipartUploadOutput } from 'aws-sdk/clients/s3';
import { FlowService, FTPService, NotificationService, XMLService } from '.';
import { AwsS3Service, AwsServiceBindings, AwsSesService, AwsSqsService } from '@logchain/components/aws';
import { CCService, FabricServiceBindings } from '@logchain/components/fabric';
import { Constants, LogChainConfigs } from '@logchain/configs';
import { Status, User, Verification } from '@logchain/models';
import {
CompanyRepository,
FlowActionRepository, FlowJourneyPointRepository, FlowPersonaRepository, FlowRepository, FormRepository, UserRepository, UserViewRepository, VerificationRepository,
VerificationViewRepository,
} from '@logchain/repositories';
import { PdfTemplate, ReplyMessage, RetryReplyMessage } from '@logchain/types';
import { DateUtils } from '@logchain/utils/date';
import { PerformStepRequest } from '@logchain/components/fabric/types';
import { v4 as uuidv4 } from 'uuid';
import { FtpConfigs } from '@logchain/configs/ftp-configs';
import * as fs from 'fs';
import { VerificationView } from '@logchain/models/views';
@bind({ scope: BindingScope.SINGLETON })
export class MessageService {
@inject(FabricServiceBindings.CC_SERVICE)
public cc_service: CCService;
@service()
public notification_service: NotificationService;
@inject(AwsServiceBindings.SES_SERVICE)
public ses_service: AwsSesService;
@inject(AwsServiceBindings.S3_SERVICE)
public s3_service: AwsS3Service;
@inject(AwsServiceBindings.SQS_SERVICE)
public producer: AwsSqsService;
@service(XMLService)
public xmlService: XMLService;
@service(FlowService)
public flowService: FlowService;
constructor(
@repository(VerificationRepository)
public verification_repo: VerificationRepository,
@repository(VerificationViewRepository)
public verification_view_repo: VerificationViewRepository,
@repository(FlowActionRepository)
public flow_action_repo: FlowActionRepository,
@repository(FlowPersonaRepository)
public flow_persona_repo: FlowPersonaRepository,
@repository(FlowJourneyPointRepository)
public flow_journey_point_repo: FlowJourneyPointRepository,
@repository(CompanyRepository)
public company_repo: CompanyRepository,
@repository(UserRepository)
public user_repo: UserRepository,
@repository(UserViewRepository)
public user_view_repo: UserViewRepository,
@repository(FormRepository)
public form_repo: FormRepository,
@repository(FlowRepository)
public flow_repo: FlowRepository,
@service(FTPService)
public ftpService: FTPService,
) { }
/**
* @method
* @description Update data after creating pdf.
* @name handleReplyMsg
* @param {ReplyMessage | null} msg
* @return {Promise<void>}
*/
public async handleReplyMsg(reply_msg: AnyObject): Promise<void> {
if (!reply_msg || !reply_msg?.message?.Body) {
console.log('No messages to handle.', reply_msg);
return;
}
const msg = JSON.parse(reply_msg.message.Body);
try {
if (msg.content?.retry) {
const { pdf_attempt = 0 } = await this._getAttemptCreations(msg.content.id, msg.model_name);
if (pdf_attempt >= LogChainConfigs.MaxPdfAttempts) {
// Send mail to admin list
const recepients = LogChainConfigs.supportEmails.map((email) => {
return { contact_email: email, language: 'en' } as User;
});
const flow_id = msg.content.flow_id ?? msg.content.entry.flow_id;
const flow = await this.flow_repo.findById(flow_id);
await this.ses_service.sendTemplatedEmail(
Constants.Email.InformSupportTeamAfterPDFGenerationFailed,
recepients,
{
username: 'Support team',
name: flow.name,
flow_id: flow.id,
}
);
await this._incrementAttemptCreations(msg.content.id, msg.model_name);
// -----------------------
throw Error('pdf_attempt limit reached!!!');
} else {
await this._sendRetryMessage(msg);
}
} else {
msg.metadata.ETag = msg.metadata.ETag?.replace(/"/g, '');
await this._verifyJourneyOnBlockchain(msg);
await this.flowService.checkAndNotifyUsersWhenFlowCompeted(msg);
}
} catch(error) {
console.log(error);
if (reply_msg?.message?.ReceiptHandle) {
this.producer.deleteMessage({
QueueUrl: process.env.AWS_REPLY_QUEUE_URL as string,
ReceiptHandle: reply_msg?.message?.ReceiptHandle
}, console.log);
}
}
}
/**
* Send message to lambda function generate pdf.
* @param msg The message from sqs.
*/
async sendMessage(msg: PdfTemplate): Promise<void> {
const data: PdfTemplate = {
content: msg.content,
model_name: msg.model_name,
};
const res = await this.producer.send({
id: uuidv4(),
groupId: 'pdf-generator',
deduplicationId: uuidv4(),
body: JSON.stringify(data),
});
console.log('Send message to SQS Successful', res.length ? res[0]?.Id : '');
}
/**
* Send retry message to lambda function generate pdf.
* @param msg The message from sqs.
*/
private async _sendRetryMessage(msg: RetryReplyMessage): Promise<void> {
// Clear flag
delete msg.content.retry;
const data: PdfTemplate = {
content: msg.content,
model_name: msg.model_name,
};
const res = await this.producer.send({
id: uuidv4(),
groupId: 'pdf-generator',
deduplicationId: uuidv4(),
body: JSON.stringify(data),
});
// Update pdf_attempt
await this._incrementAttemptCreations(msg.content.id, msg.model_name);
console.log('Send message to SQS Successful', res.length ? res[0]?.Id : '');
}
/**
* Verify journey on the blockchain network.
* @param msg The message from sqs.
*/
private async _verifyJourneyOnBlockchain(msg: ReplyMessage): Promise<void> {
const { table_name, metadata } = msg;
const params: PerformStepRequest = {
flowId: msg.flow_id,
actionId: msg.flow_action_id,
hash: metadata.ETag,
uri: metadata.Key,
version: metadata.VersionId,
};
let blockchain_tx = '';
let validated_blockchain_tx = '';
// PDF come from override
// - Verification created => (status: 0) => update previous verification (hash only) (don't update transaction id)
// - Verification completed => (status: 1) => create new verification (don't update transaction id)
// PDF come from validation
// - Verification completed => (status: 1) => Update transaction id
// Get old verification record.(only for the case verfication was created before)
const oldVerificationValidator = await this.verification_repo.findOne({
where: {
is_actor: false,
external_id: msg.id,
table_name: msg.table_name,
},
order: ['id DESC'],
});
if (!msg?.validator_company_id || msg?.call_from_validation) {
// In case pdf no-need-validator or pdf-created-from-verification-completed.
// Invoke chaincode function to submit hash of the documents.
blockchain_tx = await this.cc_service.invoke('PerformStep', params);
if (oldVerificationValidator && oldVerificationValidator?.status !== Status.Verification.ForValidation) {
validated_blockchain_tx = await this.cc_service.invoke('ValidateStep', {
actionId: oldVerificationValidator.flow_action_id,
hash: metadata.ETag,
approve: !(oldVerificationValidator.status - 1),
});
}
}
// Update blockchain transaction to database.
await this._updateBlockchainTx2Documents(
msg.id,
table_name,
metadata,
blockchain_tx,
);
const oldVerificationActor = await this.verification_repo.findOne({
where: {
is_actor: true,
external_id: msg.id,
table_name: msg.table_name,
},
order: ['id DESC'],
});
if (oldVerificationActor) {
await this.verification_repo.updateById(oldVerificationActor?.id ?? 0, {
blockchain_tx: blockchain_tx,
uri: metadata.Key,
version: metadata.VersionId,
hash: metadata.ETag,
});
}
// Create verification record if this is pdf process come from completed an action.
if (!msg?.call_from_validation) {
await this._createVerificationRecords(msg, blockchain_tx, oldVerificationActor ?? undefined);
} else {
if (oldVerificationValidator) {
await this.verification_repo.updateAll(
{
verification_id: oldVerificationValidator?.verification_id ?? oldVerificationActor?.verification_id,
status: oldVerificationValidator.status,
cancelled_reason: oldVerificationValidator.status === Status.Verification.Rejected ? oldVerificationValidator.cancelled_reason : undefined,
blockchain_tx: validated_blockchain_tx,
uri: metadata.Key,
version: metadata.VersionId,
hash: metadata.ETag,
},
{
external_id: oldVerificationValidator.external_id,
table_name: oldVerificationValidator.table_name,
is_actor: false,
},
);
}
}
// We send file to Sutton when record was created on blockchain.
if (!msg?.validator_company_id || (oldVerificationValidator?.status !== Status.Verification.ForValidation)) {
await this._sendPDFFileToSutton(msg, blockchain_tx);
}
}
/**
* Sends the PDF file to Sutton.
*
* @param {ReplyMessage} msg - The message containing the PDF file information.
* @param {string} blockchain_tx - The blockchain transaction ID.
* @return {Promise<void>} - A promise that resolves when the PDF file is sent successfully.
*/
private async _sendPDFFileToSutton(msg: ReplyMessage, blockchain_tx: string): Promise<void> {
/**
Everytime a LIVE flow receives a document a file will be created on Sutton's `DOCUMENTS` folder. Each document will create 2 files
1 XML file containing the information of the record
1 PDF file which is the actual file generated by LogChain. The generated file will have a file name of [TransactionId].pdf
**/
// Check flow status to see if it's a live flow
const flow = await this.flow_repo.findOne({
where: {
id: msg.flow_id,
},
});
if (!flow || flow.status !== Status.Flow.Live) {
console.log('Flow is not live. Cannot send PDF file to Sutton', msg.flow_id);
return;
}
if (!flow?.consignment_num) {
console.log('Flow is not belong to Sutton. Cannot send PDF file to Sutton', msg.flow_id);
return;
}
const suttonData: AnyObject = {};
const flowPersonas = await this.flow_persona_repo.find({
where: {
flow_id: msg.flow_id,
persona_id: { inq: Constants.personas_can_create_flow },
},
});
if (!flowPersonas?.length) {
console.log('FlowPersona was not found. Cannot send PDF file to Sutton', msg.flow_id);
return;
}
let container_no_list: string[] = [];
flowPersonas.map(persona => {
if (persona?.needed_info?.container_no) {
container_no_list = persona.needed_info.container_no as string[];
}
});
const curStep = await this.flow_journey_point_repo.findOne({
where: { id: msg.journey_point_id },
});
if (!curStep) {
console.log('Can not find flow journey point. Cannot send PDF file to Sutton', msg.journey_point_id);
return;
}
const curContainerNo = curStep.container_order ? container_no_list[curStep.container_order - 1] : container_no_list.join(',');
const curAction = await this.flow_action_repo.findOne({
fields: ['form_id', 'company_id'],
where: { id: msg.flow_action_id },
});
if (!curAction) {
console.log('Can not find flow action. Cannot send PDF file to Sutton', msg.flow_action_id);
return;
}
if ([Constants.safety_data_sheet_label, Constants.addendum_label].includes(curStep.name)) {
return;
}
suttonData.FileType = curAction.form_id;
const curActionData = await this.flow_action_repo.execute(
`SELECT status FROM actions_data_view WHERE document_name = '${msg.table_name}' AND id = ${msg.id}`,
);
if (!curActionData?.length) {
console.log('Can not find action data. Cannot send PDF file to Sutton', msg.table_name, msg.id);
return;
}
suttonData.FileTypeStatus = curActionData[0]?.status ?? 0;
const verificationActor = await this.company_repo.findById(curAction.company_id);
suttonData.DocumentActor = verificationActor.name ?? '';
const verificationValidator = await this.verification_view_repo.findOne({
fields: ['status', 'verification_name'],
where: {
flow_id: msg.flow_id,
flow_journey_point_id: msg.journey_point_id,
flow_action_id: msg.flow_action_id,
is_actor: false,
},
}) as VerificationView;
suttonData.ValidationStatus = verificationValidator ? verificationValidator.status : Status.Verification.ValidationNotNeeded;
const key = (msg?.metadata?.Key ?? '') ?? { body: Buffer.from('') };
const response = await this.s3_service.getBufferObjectFromS3(key);
// Send PDF file to Sutton
if (response?.body) {
try {
await this.ftpService.connect();
const remoteFromXmlFilePath = `${FtpConfigs.toDirDocuments}/${blockchain_tx}.xml`;
const remoteFromPdfFilePath = `${FtpConfigs.toDirDocuments}/${blockchain_tx}.pdf`;
const localXmlFilePath = `/tmp/${blockchain_tx}.xml`;
const localPdfFilePath = `/tmp/${blockchain_tx}.pdf`;
fs.writeFileSync(localXmlFilePath, this.xmlService.generateXMLForPDFDocument({
TransactionId: blockchain_tx,
Consignment_num: flow.consignment_num,
Unitkey: curContainerNo,
File: {
FileDate: DateUtils.formatDate(new Date(), 'yyyy-MM-DD hh:mm:ss.sss ZD'),
FileType: suttonData.FileType, // FormID
FileTypeName: Constants.FormLabel[suttonData.FileType] ?? 'Unknown', // Form Name
FileTypeStatus: suttonData.FileTypeStatus, // 0,1,2,3
FileTypeStatusName: Constants.action_data_status_text[suttonData.FileTypeStatus] ?? 'Unknown', // New, In Progress, Completed, Rejected
ValidationStatus: suttonData.ValidationStatus,
ValidationStatusName: Constants.validation_status_text[suttonData.ValidationStatus] ?? '',
FlowStep: flow.stats.steps,
FlowStepName: flow.name,
DocumentActor: suttonData.DocumentActor,
},
}));
fs.writeFileSync(localPdfFilePath, response.body as Buffer);
await this.ftpService.uploadFile(localXmlFilePath, remoteFromXmlFilePath);
await this.ftpService.uploadFile(localPdfFilePath, remoteFromPdfFilePath);
// eslint-disable-next-line @typescript-eslint/no-misused-promises
setTimeout(async () => {
await this.ftpService.disconnect();
}, 10000);
} catch (error) {
console.log(error);
} finally {
await this.ftpService.disconnect();
}
}
}
/**
* Create verification records
* @param msg The message from sqs.
* @param blockchain_tx The blockchain transaction.
*/
private async _createVerificationRecords(
msg: ReplyMessage,
blockchain_tx: string,
oldVerificationActor?: Verification,
) {
const action = await this.flow_action_repo.findOne({
where: {
id: msg.flow_action_id,
flow_id: msg.flow_id,
},
});
if (!action) {
console.log(
`Action not found with id ${msg.flow_action_id} of flow ${msg.flow_id}`,
);
return;
}
// Get overriden document to choose template and clear old verification
let overridenDocument: AnyObject[] = [];
try {
const sql = `SELECT * FROM ${msg.table_name} WHERE id = ${msg.id} AND override_by_id IS NOT NULL`;
overridenDocument = await this.verification_repo.execute(sql) as AnyObject[];
} catch (error) {
console.log('Error while getting overriden document');
}
if (overridenDocument?.length && msg?.validator_company_id) {
oldVerificationActor = undefined;
}
const verification = {
flow_id: msg.flow_id,
flow_journey_point_id: action.flow_journey_point_id,
flow_action_id: msg.flow_action_id,
form_id: action.form_id,
};
// create verification records for actor
const bulk_data: DataObject<Verification>[] = [];
if (!oldVerificationActor) {
bulk_data.push(
{
...verification,
blockchain_tx,
verification_id: msg.actor_id,
status: Status.Verification.Validated, // auto validated for actor
is_actor: true,
external_id: msg.id,
table_name: msg.table_name,
hash: msg.metadata.ETag,
uri: msg.metadata.Key,
version: msg.metadata.VersionId,
},
);
}
// create verification records for validator
const open_actions = await this.flow_action_repo.findOne({
where: {
id: msg.flow_action_id,
flow_id: msg.flow_id,
status: Status.FlowAction.New,
},
});
// We should not create new verification in case the actor submit cancelled and create new action
if (msg.validator_company_id && !open_actions) {
bulk_data.push({
...verification,
verification_company_id: msg.validator_company_id,
status: Status.Verification.ForValidation,
is_actor: false,
external_id: msg.id,
table_name: msg.table_name,
hash: msg.metadata.ETag,
uri: msg.metadata.Key,
version: msg.metadata.VersionId,
});
// In case additional document was created, we should update old verification record to skip validation
if (overridenDocument.length === 0) {
await this.verification_repo.updateAll(
{
verification_company_id: msg.validator_company_id,
status: Status.Verification.Skipped,
},
{
flow_action_id: msg.flow_action_id,
table_name: msg.table_name,
is_actor: false,
status: Status.Verification.ForValidation,
});
}
}
let createdVerifications: Verification[] = [];
if (oldVerificationActor) {
createdVerifications.push(oldVerificationActor);
}
// Create new verification
if (bulk_data?.length) {
const newVerifications = await this.verification_repo.createAll(bulk_data);
if (createdVerifications.length === 0) {
// In case there is no actor verification, we just add all new verifications.
createdVerifications = newVerifications;
} else {
// In case there is old verification, we just add verification validator only
createdVerifications.push(newVerifications[0]);
}
}
// -----------------------------------------
// Update all old verification records to latest information
if (overridenDocument.length > 0 && blockchain_tx !== '') {
await this.verification_repo.updateAll(
{
verification_company_id: msg.validator_company_id,
status: Status.Verification.ForValidation,
blockchain_tx: createdVerifications[0].blockchain_tx,
},
{
external_id: msg.id,
table_name: msg.table_name,
is_actor: false,
});
}
// -----------------------------------------
// Send notification to users of validator company
if (msg.validator_company_id) {
const alert = createdVerifications.find(a => {
return a.verification_company_id === msg.validator_company_id;
});
if (!alert) {
return;
}
// Send email and notification to validator
let template = Constants.Email.InformUserAfterCompletedDocumentRecord;
let key = Constants.Notification.VerificationsAction;
if (overridenDocument.length > 0) {
template = Constants.Email.EM102;
key = Constants.Notification.EM102;
}
const recepients = await this.user_repo.find({
where: {
company_id: msg.validator_company_id,
status: Status.User.Active,
}
});
const tasks: AnyObject[] = [];
recepients.forEach(receipient => {
tasks.push(
this._sendNotificationToVerification(
alert.id,
receipient.id,
action.form_id,
action.title,
overridenDocument ?
{
template,
key,
flow_id: msg.flow_id,
}
: undefined
),
);
});
await Promise.all(tasks);
console.log('Notification sent to users of validator company');
} else if (overridenDocument.length > 0) {
// Send alerts to companies access to this step
const curFlow = await this.flow_repo.findById(msg.flow_id);
const actor = await this.user_view_repo.findById(msg.actor_id);
const companyIdsInStep = await this.flow_journey_point_repo.getCompanyIdsInStep(msg.journey_point_id);
const feature_name = action?.title ?? (await this.form_repo.findById(action.form_id))?.name ?? '';
await this.flowService.sendNotifications(curFlow, {
template: Constants.Email.EM101,
key: Constants.Notification.EM101,
company_ids: companyIdsInStep,
feature_name: feature_name,
feature_id: msg.id,
actor_name: actor.name ?? '',
link: this._buildHrefForFlow(msg.flow_id),
});
}
// -----------------------------------------
}
/**
* Update S3 Info and Blockchain transaction to the Documents.
* @param table_name The table_name to update.
* @param id The id.
* @param metadata The metadata from S3
* @param blockchain_tx The blockchain transaction.
*/
private async _updateBlockchainTx2Documents(
id: number,
table_name: string,
metadata: CompleteMultipartUploadOutput,
blockchain_tx: string,
) {
const sql = `
UPDATE ${table_name}
SET is_pdf_created = true,
uri = $1,
version = $2,
hash = $3,
blockchain_tx = $4
WHERE id = $5`;
await this.verification_repo.execute(sql, [
metadata.Key,
metadata.VersionId,
metadata.ETag,
blockchain_tx,
id,
]);
}
/**
* Increment pdf_attempt
* @param id the id of the documents.
* @param table_name The table name.
*/
private async _incrementAttemptCreations(id: number, table_name: string) {
const sql = `
UPDATE ${table_name}
SET pdf_attempt = pdf_attempt + 1
WHERE id = $1`;
return this.verification_repo.execute(sql, [id]);
}
/**
* Get pdf_attempt
* @param id the id of the documents.
* @param table_name The table name.
*/
private async _getAttemptCreations(id: number, table_name: string) {
const sql = `SELECT pdf_attempt FROM ${table_name} WHERE id = $1`;
const results = await this.verification_repo.execute(sql, [id]);
return results?.length ? results[0] : { pdf_attempt: 0 };
}
/**
* Send notifications to the user who need to verify the document.
* @param verification_id The verification id.
*/
private async _sendNotificationToVerification(
id: number,
verification_id?: number,
form_id?: number,
form_title?: string,
options: Options = {},
): Promise<void> {
if (verification_id === undefined || form_id === undefined) {
return;
}
let form_name = form_title;
if (form_id) {
const form = await this.form_repo.findById(form_id);
form_name = form.name;
}
const recipients = await this.user_view_repo.findById(verification_id, {
include: [
{
relation: 'company',
scope: {
fields: {
id: true,
timezone: true,
},
},
},
],
});
if (recipients.status !== Status.User.Active) {
console.log('User is not active');
return;
}
const p_tasks = [];
p_tasks[0] = this.ses_service.sendTemplatedEmail(
options?.template ?? Constants.Email.InformUserAfterCompletedDocumentRecord,
recipients,
{
username: recipients.name,
feature_id: options?.feature_id ?? id,
feature_name: options?.feature_name ?? form_name,
actor_name: options?.actor_name ?? recipients.name,
created_date: DateUtils.formatDateWithTimeZone(
new Date(),
recipients.company?.timezone,
),
},
);
p_tasks[1] = this.notification_service.sendBulkNotifications(
options?.key ?? Constants.Notification.VerificationsAction,
[
{
sub: recipients.sub,
settings: recipients.settings,
language: recipients.language,
replacement_data: {
feature_id: options?.feature_id ?? id,
feature_name: options?.feature_name ?? form_name,
actor_name: options?.actor_name ?? form_name,
link: this._buildHrefForAlert(id),
created_date: DateUtils.formatDateWithTimeZone(
new Date(),
recipients.company?.timezone,
),
},
},
],
);
const res = await Promise.allSettled(p_tasks);
const rejectedResults = res.filter(i => {
return i.status === 'rejected';
});
if (rejectedResults.length) {
console.log(
'[ERROR] - _sendNotificationToVerification: ',
rejectedResults,
);
}
}
/**
* Build href link for the alerts.
* @param id The alert.
* @return The link of alert.
*/
private _buildHrefForAlert(id: number): string {
return `alerts/alert-detail/${id}`;
}
/**
* Build href link for the flow.
* @param id The flow id.
* @param key The template.
* @return The link of flow.
*/
private _buildHrefForFlow(id: number): string {
return `physical-transport/journey-detail/${id}`;
}
}
|