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 | 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x | import {bind, BindingScope, inject, service} from '@loopback/core';
import {AnyObject, repository} from '@loopback/repository';
import {HttpErrors} from '@loopback/rest';
import {BaseService} from '../base.service';
import {Pmo} from '../../models/scan/pmo.model';
import {PmoRepository} from '../../repositories/scan/pmo.repository';
import {TimelineEventRepository} from '@logchain/repositories/scan/timeline-event.repository';
import {AttachmentType, PmoStatus, RecipientNotification, TimelineStep} from '@logchain/types';
import {TimelineService} from './timeline.service';
import {AdditionalInformationService} from './additional-information.service';
import {ShipmentRepository} from '@logchain/repositories/scan/shipment.repository';
import {BoxRepository} from '@logchain/repositories/scan/box.repository';
import {DimensionRepository} from '@logchain/repositories/scan/dimension.repository';
import {RejectPmoRepository} from '@logchain/repositories/scan/reject-pmo.repository';
import {EmailConfigRepository} from '@logchain/repositories/scan/email-config.repository';
import {BrevoService} from '@logchain/services/scan/brevo.service';
import {BoxService} from './box.service';
import {AttachmentService} from './attachment.service';
import {NotificationService} from '../notification.service';
import {
getNotificationLink,
getRejectNotificationTemplate,
getStatusUpdateNotificationTemplate,
} from '@logchain/utils/notification.helper';
import {DateUtils} from '@logchain/utils';
import {Constants} from '@logchain/configs';
import {UserRepository} from '@logchain/repositories';
import {SecurityBindings, UserProfile} from '@loopback/security';
@bind({scope: BindingScope.TRANSIENT})
export class PmoService extends BaseService<Pmo> {
private static readonly PMO_CODE_PATTERN = /^\d{8}$/;
constructor(
@repository(PmoRepository)
public pmoRepo: PmoRepository,
@repository(TimelineEventRepository)
public timelineRepo: TimelineEventRepository,
@service(TimelineService)
private timelineService: TimelineService,
@service(AdditionalInformationService)
private additionalInformationService: AdditionalInformationService,
@repository(ShipmentRepository)
public shipmentRepo: ShipmentRepository,
@repository(BoxRepository)
public boxRepo: BoxRepository,
@repository(DimensionRepository)
public dimensionRepo: DimensionRepository,
@repository(RejectPmoRepository)
public rejectPmoRepo: RejectPmoRepository,
@repository(EmailConfigRepository)
private emailConfigRepository: EmailConfigRepository,
@service(BrevoService)
private brevoService: BrevoService,
@service(BoxService)
private boxService: BoxService,
@service(AttachmentService)
private attachmentService: AttachmentService,
@service(NotificationService)
private notificationService: NotificationService,
@repository(UserRepository)
public userRepo: UserRepository,
@inject(SecurityBindings.USER, {optional: true})
private currentUser: UserProfile,
) {
super();
}
/**
* GETY ALL PMO (with filter)
*/
async getAllPmo(params: {
q?: string;
type?: string;
status?: number;
showDrop?: boolean;
page?: number;
limit?: number;
sortBy?: string;
sortOrder?: string;
}) {
const {q, type, status, showDrop, page = 1, limit = 20} = params;
return this.pmoRepo.findAllWithShipmentPaging({
q,
type,
status,
showDrop,
page,
limit,
});
}
/**
* Scan PMO / EQ / Shipment
*/
async findByScan(code: string, type: string) {
let result = await this.pmoRepo.findByScan(code, type);
/*
* AUTO-CREATE PMO:
*/
if ((!result || result.length === 0) && type === 'pmo' && PmoService.PMO_CODE_PATTERN.test(code)) {
await this.autoCreatePmoByCode(code);
result = await this.pmoRepo.findByScan(code, type);
}
/*
* PMO IDS
*/
const pmoIds = result.map(x => Number(x.id)).filter(x => !isNaN(x));
let additionalStatus = 0;
if (result?.length > 0) {
additionalStatus = result[0].status;
}
let additionalInformations: any = [];
if (pmoIds.length > 0 && additionalStatus) {
additionalInformations = await this.additionalInformationService.findByPMOIdsAndStatus(pmoIds, additionalStatus);
}
/*
* MERGE
*/
return result.map(item => ({
...item,
shippingNo: item.shipping_no,
temporaryNo: item.temporary_no,
additional_informations: additionalInformations.filter((x: any) => Number(x.pmo_id) === Number(item.id)),
}));
}
/**
* - code -> field `code`
* - code -> field `order_no`
* - status -> PmoStatus.NEW (
*/
private async autoCreatePmoByCode(code: string): Promise<Pmo> {
const existing = await this.pmoRepo.findOne({where: {code}});
if (existing) return existing;
try {
return await this.pmoRepo.create({
code,
order_no: Number(code),
status: PmoStatus.NEW,
created_at: new Date(),
updated_at: new Date(),
});
} catch (e) {
const existedAfterRace = await this.pmoRepo.findOne({where: {code}});
if (existedAfterRace) return existedAfterRace;
throw e;
}
}
/**
* Build timeline note
*/
async buildTimelineNote(action: TimelineStep, pmo: any, currentStatus: number): Promise<string> {
switch (action) {
case TimelineStep.PACKING: {
if (!pmo.shipment_id) {
return 'Packing completed';
}
const shipment = await this.shipmentRepo.findById(Number(pmo.shipment_id));
return shipment?.temporary_no ? `Packing completed (Temp No. ${shipment.temporary_no})` : 'Packing completed';
}
case TimelineStep.PICKED: {
if (!pmo.shipment_id) {
return 'Picked Up completed';
}
const shipment = await this.shipmentRepo.findById(Number(pmo.shipment_id));
return shipment?.shipping_no
? `Picked Up completed (Shipment No. ${shipment.shipping_no})`
: 'Picked Up completed';
}
default:
return `${action} completed`;
}
}
/**
* Map status
*/
mapAction(status: number): TimelineStep {
switch (status) {
case 1:
return TimelineStep.DROPPED;
case 2:
return TimelineStep.RECEIVED;
case 3:
return TimelineStep.PACKING;
case 4:
return TimelineStep.PACKED;
case 5:
return TimelineStep.PICKUP;
case 6:
return TimelineStep.PICKED;
case 7:
return TimelineStep.COMPLETE;
case 8:
return TimelineStep.REJECT;
default:
return TimelineStep.DROPPED;
}
}
mapStatusLabel(status: number): string {
const map: Record<number, string> = {
[PmoStatus.NEW]: 'Drop',
[PmoStatus.DROPPED]: 'Receive',
[PmoStatus.RECEIVED]: 'Packing',
[PmoStatus.PACKING]: 'Packed',
[PmoStatus.PACKED]: 'Pickup',
[PmoStatus.PICKUP]: 'Picked Up',
[PmoStatus.COMPLETED]: 'Completed',
[PmoStatus.REJECTED]: 'Rejected',
};
return map[status] ?? `Unknown (${status})`;
}
/**
* mixed status
*/
resolveEffectiveStatus(pmos: Pmo[]): number {
const statuses = [...new Set(pmos.map(p => p.status))];
const EARLY_STATUSES = new Set([PmoStatus.NEW, PmoStatus.DROPPED, PmoStatus.RECEIVED]);
const allEarly = statuses.every(s => EARLY_STATUSES.has(s));
if (statuses.length === 1) {
return statuses[0];
}
if (allEarly) {
return Math.max(...statuses);
}
throw new HttpErrors.BadRequest('PMOs has mixed actions, please only select records with similar actions');
}
/**
* Update status + timeline
*/
async updateStatus(
ids: number[],
nextStatus: number,
statusMap: Map<number, number>,
additional_information?: string | null,
temporaryNo?: string,
pmoTemporaryNos?: {pmoId: number; temporaryNo: string}[],
) {
const pmos = await this.pmoRepo.find({
where: {id: {inq: ids}},
});
if (!pmos.length) {
throw new HttpErrors.NotFound('PMO not found');
}
const rejectedPmos = pmos.filter(p => p.status === PmoStatus.REJECTED);
if (rejectedPmos.length > 0) {
const error = new HttpErrors.Conflict(
`PMO(s) ${rejectedPmos.map(p => p.code).join(', ')} has been rejected and must be removed before proceeding`,
);
(error as any).code = 'PMO_ALREADY_REJECTED';
(error as any).rejectedPmos = rejectedPmos.map(p => ({id: p.id, code: p.code}));
throw error;
}
const conflicted = pmos.filter(pmo => {
const expectedStatus = statusMap.get(Number(pmo.id));
return expectedStatus !== undefined && pmo.status !== expectedStatus;
});
if (conflicted.length > 0) {
const error = new HttpErrors.Conflict('Status of PMO(s) has been updated');
(error as any).conflictedPmos = conflicted.map(p => ({
id: p.id,
code: p.code,
currentStatus: p.status,
expectedStatus: statusMap.get(Number(p.id)),
}));
throw error;
}
this.resolveEffectiveStatus(pmos);
const currentStatus = nextStatus - 1;
if (!this.isValidFlow(currentStatus, nextStatus)) {
if (currentStatus === nextStatus) {
throw new HttpErrors.BadRequest(
`PMO is already in "${this.mapStatusLabel(currentStatus)}" status, cannot transition to the same status`,
);
}
throw new HttpErrors.BadRequest(
`Invalid flow from ${this.mapStatusLabel(currentStatus)} to ${this.mapStatusLabel(nextStatus)}`,
);
}
const action = this.mapAction(currentStatus);
const nextAction = this.mapAction(nextStatus);
const emailConfig = await this.emailConfigRepository.findByActionAndReasonCode(action, 'update');
const emailLog = {
action: action,
reasonCode: 'update',
config: emailConfig,
};
const tempNoMap = new Map<number, string>();
if (pmoTemporaryNos?.length) {
pmoTemporaryNos.forEach(({pmoId, temporaryNo: t}) => {
tempNoMap.set(Number(pmoId), t);
});
}
const pmoAttachments: {pmo: Pmo; attachments: any[]}[] = new Array(pmos.length);
const currentUser = this.timelineService.getCurrentUserName();
const sortedPmos = [...pmos].sort((a, b) => a.status - b.status);
for (const [index, p] of sortedPmos.entries()) {
await this.pmoRepo.updateById(p.id, {
status: nextStatus,
action: nextAction,
});
const resolvedTempNo = tempNoMap.get(Number(p.id)) ?? temporaryNo;
const note = await this.buildTimelineNote(action, p, currentStatus);
const latestInfoRows = await this.additionalInformationService.additionalInformationRepo.find({
where: {pmo_id: p.id, status: currentStatus},
order: ['updated_at DESC'],
limit: 1,
});
const additionalInfo = latestInfoRows[0]?.information?.trim() ?? '';
for (let step = p.status; step < nextStatus; step++) {
const stepAction = this.mapAction(step);
const isLastStep = step === nextStatus - 1;
const stepNote = await this.buildTimelineNote(stepAction, p, step);
await this.timelineService.createEvent({
pmoId: p.id,
stepCode: stepAction,
userName: this.timelineService.getCurrentUserName(),
note: stepNote,
additionalInformation: isLastStep ? additional_information : null,
temporaryNo: resolvedTempNo,
});
}
const attachments = await this.attachmentService.findDirectByPmoIdAndType(
p.id,
action as unknown as AttachmentType,
);
pmoAttachments[index] = {pmo: p, attachments};
const notificationTemplate = getStatusUpdateNotificationTemplate(nextStatus);
if (notificationTemplate) {
const link = getNotificationLink(nextStatus, p.id);
const dateStr = DateUtils.formatDateAndConvertTimeZone(new Date(), 'DD MM YYYY HH:mm', 'Asia/Singapore');
const recipients = await this.buildRecipientsForPmos([p], {
link,
date: dateStr,
droppedBy: currentUser,
receivedBy: currentUser,
packingBy: currentUser,
packedBy: currentUser,
pickUpBy: currentUser,
pickedBy: currentUser,
});
await this.notificationService.sendBulkNotifications(notificationTemplate, recipients);
if (nextStatus === PmoStatus.COMPLETED) {
await this.notificationService.sendBulkNotifications(Constants.Notification.Completed, recipients);
}
}
}
const updatedPmos = await this.pmoRepo.find({where: {id: {inq: ids}}});
const shipmentIdsToCheck = [
...new Set(updatedPmos.map(p => p.shipment_id).filter((id): id is number => id != null)),
];
const boxIdsToCheck = [...new Set(updatedPmos.map(p => p.box_id).filter((id): id is number => id != null))];
if (shipmentIdsToCheck.length > 0 || boxIdsToCheck.length > 0) {
const orConditions: any[] = [];
if (shipmentIdsToCheck.length > 0) {
orConditions.push({shipment_id: {inq: shipmentIdsToCheck}});
}
if (boxIdsToCheck.length > 0) {
orConditions.push({box_id: {inq: boxIdsToCheck}});
}
const siblingPmos = await this.pmoRepo.find({
where: {
and: [{id: {nin: ids}}, {status: currentStatus}, {or: orConditions}],
},
});
if (siblingPmos.length > 0) {
await Promise.all(
siblingPmos.map(p =>
this.pmoRepo.updateById(p.id, {
shipment_id: null as any,
box_id: null,
updated_at: new Date(),
}),
),
);
}
}
const globalSeenGroupUids = new Set<string>();
const deduplicatedPmoAttachments = pmoAttachments.map(item => {
const uniqueAttachments = (item.attachments ?? []).filter((att: any) => {
if (att.group_uid) {
if (globalSeenGroupUids.has(att.group_uid)) return false;
globalSeenGroupUids.add(att.group_uid);
}
return true;
});
return {...item, attachments: uniqueAttachments};
});
await this.brevoService.sendNotificationEmail(emailConfig!, 'update', {pmo_list: deduplicatedPmoAttachments});
if (nextAction === TimelineStep.COMPLETE) {
const emailConfig1 = await this.emailConfigRepository.findByActionAndReasonCode(nextAction, 'update');
await this.brevoService.sendNotificationEmail(emailConfig1!, 'update', {pmo_list: deduplicatedPmoAttachments});
}
return {
success: true,
total: pmos.length,
action,
emailLog,
};
}
/**
* Flow rule
*/
isValidFlow(current: number, next: number): boolean {
const flow: Record<number, number[]> = {
1: [2, 3, 4],
2: [3, 4],
3: [4],
4: [5],
5: [6],
6: [7],
7: [],
8: [],
};
return flow[current]?.includes(next);
}
/**
* Manual update fields
*/
async manualUpdate(id: number, data: Record<string, any>) {
const allowedFields = ['po', 'trent_type', 'esn', 'part_no', 'part_desc', 'serial_no', 'qty', 'dropped_by'];
const payload: Record<string, any> = {};
Object.keys(data).forEach(key => {
if (allowedFields.includes(key)) {
payload[key] = data[key];
}
});
if (Object.keys(payload).length === 0) {
throw new HttpErrors.BadRequest('No valid fields to update');
}
payload.updated_at = new Date();
await this.pmoRepo.updateById(id, payload);
return {
success: true,
};
}
async manualUpdateBatch(
items: {
id: number;
data: Record<string, any>;
}[],
) {
await Promise.all(items.map(item => this.manualUpdate(item.id, item.data)));
return {
success: true,
total: items.length,
};
}
async rejectPMO(data: {
ids: number[];
updateStatus: number;
pmos: Array<{id: number; currentStatus: number}>;
statusMap: Map<number, number>;
reasonCode: string;
reasonLabel: string;
notificationText: string;
note?: string;
temporaryNo?: string;
}) {
const pmos = await this.pmoRepo.find({
where: {
id: {
inq: data.ids,
},
},
});
if (!pmos.length) {
throw new HttpErrors.NotFound('PMO not found');
}
const conflicted = pmos.filter(pmo => {
const expectedStatus = data.statusMap.get(Number(pmo.id));
return expectedStatus !== undefined && pmo.status !== expectedStatus;
});
if (conflicted.length > 0) {
const error = new HttpErrors.Conflict('Status of PMO(s) has been updated');
(error as any).conflictedPmos = conflicted.map(p => ({
id: p.id,
code: p.code,
currentStatus: p.status,
expectedStatus: data.statusMap.get(Number(p.id)),
}));
throw error;
}
this.resolveEffectiveStatus(pmos);
const currentStatus = this.mapAction(pmos[0].status);
const currentUser = this.timelineService.getCurrentUserName();
const nextAction = this.mapAction(data.updateStatus);
const emailConfig = await this.emailConfigRepository.findByActionAndReasonCode(currentStatus, data.reasonCode);
const emailLog = {
action: currentStatus,
reasonCode: data.reasonCode,
config: emailConfig,
};
await Promise.all(
pmos.map(async pmo => {
const payload: any = {
status: data.updateStatus,
action: nextAction,
};
/*
* reject => clear shipment/box
*/
if (Number(data.updateStatus) !== 8) {
payload.shipment_id = null;
payload.box_id = null;
}
await this.pmoRepo.updateById(pmo.id, payload);
/*
* save reject history
*/
await this.rejectPmoRepo.create({
pmo_id: pmo.id,
from_status: pmo.status,
update_status: data.updateStatus,
reason_code: data.reasonCode,
reason_label: data.reasonLabel,
reject_note: data.note,
rejected_by: currentUser,
created_at: new Date(),
});
/*
* timeline
*/
await this.timelineService.createEvent({
pmoId: pmo.id,
stepCode: TimelineStep.REJECT,
userName: currentUser,
additionalInformation: data.note?.trim() ?? '',
note: `Reason Reject: ${data.reasonLabel}`,
temporaryNo: data.temporaryNo ?? (null as any),
});
const rejectTemplate = getRejectNotificationTemplate(pmo.status);
if (rejectTemplate) {
const link = getNotificationLink(data.updateStatus, pmo.id);
const dateStr = DateUtils.formatDateAndConvertTimeZone(new Date(), 'DD MM YYYY HH:mm', 'Asia/Singapore');
const recipients = await this.buildRecipientsForPmos([pmo], {
link,
date: dateStr,
rejectedBy: currentUser,
notificationText: data.notificationText,
note: data.note ?? '',
});
await this.notificationService.sendBulkNotifications(rejectTemplate, recipients);
}
}),
);
/* send notification email */
await this.brevoService.sendNotificationEmail(emailConfig!, 'reject', {pmos: pmos, remarks: data.note ?? ''});
return {
success: true,
emailLog,
};
}
private async buildRecipientsForPmos(pmos: Pmo[], replacementData: AnyObject): Promise<RecipientNotification[]> {
if (!this.currentUser?.sub) {
return [];
}
return pmos.map(pmo => ({
sub: this.currentUser.sub,
language: (this.currentUser.settings as any)?.language ?? 'en',
settings: this.currentUser.settings,
replacement_data: {
...replacementData,
pmoNo: pmo.code,
},
}));
}
async unlinkPmo(id: number, temporaryNo?: string) {
const pmo = await this.pmoRepo.findById(id);
if (!pmo) throw new HttpErrors.NotFound('PMO not found');
const wasAssigned = pmo.shipment_id != null && pmo.box_id != null;
let resolvedTemporaryNo: string | null = temporaryNo ?? null;
if (!resolvedTemporaryNo && pmo.shipment_id) {
const shipment = await this.shipmentRepo.findById(Number(pmo.shipment_id));
resolvedTemporaryNo = shipment.temporary_no ?? null;
}
await this.pmoRepo.updateById(id, {
box_id: null,
shipment_id: null as any,
updated_at: new Date(),
});
if (wasAssigned) {
await this.timelineService.createEvent({
pmoId: id,
stepCode: this.mapAction(pmo.status),
userName: this.timelineService.getCurrentUserName(),
note: 'Removed from Box',
temporaryNo: resolvedTemporaryNo ?? (null as any),
isRemovedFromBox: true,
});
}
return {success: true};
}
}
|