All files / src/services/scan timeline.service.ts

5.16% Statements 18/349
0% Branches 0/348
0% Functions 0/37
4.85% Lines 16/330

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 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 8871x   1x   1x   1x   1x 1x   1x 1x 1x 1x 1x 1x 1x 1x         1x   1x                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          
import {bind, BindingScope, inject, service} from '@loopback/core';
 
import {repository} from '@loopback/repository';
 
import {HttpErrors} from '@loopback/rest';
 
import {TimelineEventRepository} from '@logchain/repositories/scan/timeline-event.repository';
 
import {AttachmentType, TimelineStep} from '@logchain/types';
import {SecurityBindings} from '@loopback/security';
import {UserProfile} from '@logchain/components/aws';
import {AttachmentService} from './attachment.service';
import {AttachmentRepository} from '@logchain/repositories/scan/attachment.repository';
import {AdditionalInformationRepository} from '@logchain/repositories/scan/additional-information.repository';
import {RejectPmoRepository} from '@logchain/repositories/scan/reject-pmo.repository';
import {mapAttachmentType, toUTCString} from '@logchain/utils/scan';
import {ShipmentRepository} from '@logchain/repositories/scan/shipment.repository';
import {PmoRepository} from '@logchain/repositories';
import {SlaConfigService} from './sla-config.service';
 
@bind({
  scope: BindingScope.TRANSIENT,
})
export class TimelineService {
  @inject(SecurityBindings.USER, {optional: true})
  public current_user: UserProfile;
 
  constructor(
    @repository(TimelineEventRepository)
    public timelineRepo: TimelineEventRepository,
 
    @service(AttachmentService)
    public attachmentService: AttachmentService,
 
    @repository(AttachmentRepository)
    public attachmentRepo: AttachmentRepository,
 
    @repository(AdditionalInformationRepository)
    public additionalInformationRepo: AdditionalInformationRepository,
 
    @repository(RejectPmoRepository)
    public rejectPmoRepo: RejectPmoRepository,
 
    @repository(PmoRepository)
    private pmoRepo: PmoRepository,
 
    @repository(ShipmentRepository)
    private shipmentRepo: ShipmentRepository,
 
    @service(SlaConfigService)
    private slaConfigService: SlaConfigService,
  ) {}
 
  getCurrentUserName(): string {
    return this.current_user?.name || this.current_user?.email || 'System';
  }
 
  /**
   * Get timeline by PMO
   */
  async findByPmoId(pmoId: number) {
    if (!pmoId) {
      throw new HttpErrors.BadRequest('PMO is required');
    }
 
    const events = await this.timelineRepo.find({
      where: {pmoId},
      order: ['event_time ASC'],
    });
    const result = await Promise.all(
      events.map(async (event, index) => {
        const attachmentType = mapAttachmentType(event.step_code);
        let attachments: any[] = [];
        if (attachmentType) {
          const prevSameStepEvent = events
            .slice(0, index)
            .reverse()
            .find(e => e.step_code === event.step_code);
 
          const fromTime = prevSameStepEvent?.event_time ?? null;
          const toTime = event.event_time;
 
          const where: any = {
            pmo_id: pmoId,
            type: attachmentType,
          };
 
          if (fromTime && toTime) {
            where.and = [{created_at: {gt: fromTime}}, {created_at: {lte: toTime}}];
          } else if (fromTime) {
            where.created_at = {gt: fromTime};
          } else {
            where.created_at = {lte: toTime};
          }
          const rows = await this.attachmentRepo.find({
            where,
            order: ['created_at DESC'],
          });
          attachments = await Promise.all(
            rows.map(async item => ({
              ...item,
              signed_url: await this.attachmentService.generateSignedUrl(item.file_url!),
            })),
          );
        }
 
        return {
          ...event,
          additional_information: (event.additional_information ?? '').trim(),
          attachments,
        };
      }),
    );
 
    return result;
  }
 
  /**
   * Create timeline event
   */
  async createEvent(data: {
    pmoId: number;
    stepCode: TimelineStep;
    userName?: string;
    note?: string;
    temporaryNo?: string;
    metadata?: object;
    additionalInformation?: string | null;
    isRemovedFromBox?: boolean;
  }) {
    let resolvedTemporaryNo = data.temporaryNo ?? null;
 
    if (!resolvedTemporaryNo && data.pmoId) {
      try {
        const pmo = await this.pmoRepo.findById(data.pmoId);
        if (pmo?.shipment_id) {
          const shipment = await this.shipmentRepo.findById(Number(pmo.shipment_id));
          resolvedTemporaryNo = shipment?.temporary_no ?? null;
        }
      } catch (e) {
        // Ignore error if PMO or Shipment not found, just proceed with null temporary number
      }
    }
 
    return this.timelineRepo.create({
      pmoId: data.pmoId,
      step_code: data.stepCode,
      user_name: data.userName,
      note: data.note,
      temporary_no: resolvedTemporaryNo ?? (null as any),
      metadata: data.metadata,
      additional_information: data.additionalInformation ?? '',
      // event_time: new Date(),
      is_removed_from_box: data.isRemovedFromBox ?? null,
    });
  }
  async getTimelineDetail(pmoId: number, status: TimelineStep) {
    const rows = await this.timelineRepo.find({
      where: {
        pmoId,
        step_code: status,
      },
      order: ['event_time DESC'],
      limit: 1,
    });
 
    const item = rows[0];
 
    if (!item) {
      return null;
    }
 
    return {
      pmo_id: item.pmoId,
 
      dropped_by: status === TimelineStep.DROPPED ? item.user_name : null,
 
      dropped_date: status === TimelineStep.DROPPED ? item.event_time : null,
 
      received_by: status === TimelineStep.RECEIVED ? item.user_name : null,
 
      received_date: status === TimelineStep.RECEIVED ? item.event_time : null,
 
      packing_by: status === TimelineStep.PACKING ? item.user_name : null,
 
      packing_date: status === TimelineStep.PACKING ? item.event_time : null,
 
      packed_by: status === TimelineStep.PACKED ? item.user_name : null,
 
      packed_date: status === TimelineStep.PACKED ? item.event_time : null,
 
      pickup_by: status === TimelineStep.PICKUP ? item.user_name : null,
 
      pickup_date: status === TimelineStep.PICKUP ? item.event_time : null,
 
      picked_by: status === TimelineStep.PICKED ? item.user_name : null,
 
      picked_date: status === TimelineStep.PICKED ? item.event_time : null,
 
      rejected_by: status === TimelineStep.REJECT ? item.user_name : null,
 
      rejected_date: status === TimelineStep.REJECT ? item.event_time : null,
    };
  }
 
  async getTimelineSummary(pmoIds: number[]) {
    if (!pmoIds?.length) {
      throw new HttpErrors.BadRequest('PMO ids is required');
    }
 
    /*
     * LOAD ALL TIMELINES
     */
    const rows = await this.timelineRepo.find({
      where: {
        pmoId: {
          inq: pmoIds.map(x => Number(x)),
        },
      },
 
      order: ['event_time ASC'],
    });
 
    /*
     * GROUP RESULT
     */
    const result: Record<number, any> = {};
 
    rows.forEach(item => {
      const pmoId = Number(item.pmoId);
 
      if (!result[pmoId]) {
        result[pmoId] = {
          pmo_id: pmoId,
 
          dropped_by: null,
          dropped_date: null,
 
          received_by: null,
          received_date: null,
 
          packing_by: null,
          packing_date: null,
 
          packed_by: null,
          packed_date: null,
 
          pickup_by: null,
          pickup_date: null,
 
          picked_by: null,
          picked_date: null,
 
          rejected_by: null,
          rejected_date: null,
        };
      }
 
      switch (item.step_code) {
        case TimelineStep.DROPPED:
          result[pmoId].dropped_by = item.user_name;
          result[pmoId].dropped_date = item.event_time;
          break;
 
        case TimelineStep.RECEIVED:
          result[pmoId].received_by = item.user_name;
          result[pmoId].received_date = item.event_time;
          break;
 
        case TimelineStep.PACKING:
          result[pmoId].packing_by = item.user_name;
          result[pmoId].packing_date = item.event_time;
          break;
 
        case TimelineStep.PACKED:
          result[pmoId].packed_by = item.user_name;
          result[pmoId].packed_date = item.event_time;
          break;
 
        case TimelineStep.PICKUP:
          result[pmoId].pickup_by = item.user_name;
          result[pmoId].pickup_date = item.event_time;
          break;
 
        case TimelineStep.PICKED:
          result[pmoId].picked_by = item.user_name;
          result[pmoId].picked_date = item.event_time;
          break;
 
        case TimelineStep.REJECT:
          result[pmoId].rejected_by = item.user_name;
          result[pmoId].rejected_date = item.event_time;
          break;
      }
    });
 
    return result;
  }
 
  async findByPmoIds(pmoIds: number[]) {
    if (!pmoIds?.length) {
      throw new HttpErrors.BadRequest('Not found PMO');
    }
 
    const allEvents = await this.timelineRepo.find({
      where: {
        pmoId: {inq: pmoIds.map(x => Number(x))},
      },
      order: ['event_time ASC'],
    });
 
    if (!allEvents.length) return [];
 
    const pmoCycleMap = new Map<number, number>();
 
    const eventsWithCycle = allEvents.map(event => {
      const pmoId = Number(event.pmoId);
      if (!pmoCycleMap.has(pmoId)) pmoCycleMap.set(pmoId, 0);
 
      const cycle = pmoCycleMap.get(pmoId)!;
      const eventWithCycle = {...event, _cycle: cycle};
 
      if (event.step_code === TimelineStep.REJECT) {
        pmoCycleMap.set(pmoId, cycle + 1);
      }
 
      return eventWithCycle;
    });
 
    const grouped = new Map<
      string,
      {
        events: any[];
        pmoIds: Set<number>;
        tempNo: string | null;
        firstTime: Date;
      }
    >();
    for (const event of eventsWithCycle) {
      const tempNo = event.temporary_no?.trim() ?? null;
      const cycle = event._cycle;
 
      let groupKey: string;
      if (tempNo) {
        groupKey = `${event.step_code}__${tempNo}__cycle${cycle}`;
      } else {
        groupKey = `${event.step_code}__nott__cycle${cycle}__pmo${event.pmoId}`;
      }
 
      if (!grouped.has(groupKey)) {
        grouped.set(groupKey, {
          events: [],
          pmoIds: new Set(),
          tempNo,
          firstTime: new Date(event.event_time!),
        });
      }
 
      const g = grouped.get(groupKey)!;
      g.events.push(event);
      g.pmoIds.add(Number(event.pmoId));
    }
 
    const sortedGroups = Array.from(grouped.entries()).sort((a, b) => {
      return a[1].firstTime.getTime() - b[1].firstTime.getTime();
    });
 
    const eventsByPmo = new Map<number, typeof allEvents>();
    for (const event of allEvents) {
      const pid = Number(event.pmoId);
      if (!eventsByPmo.has(pid)) eventsByPmo.set(pid, []);
      eventsByPmo.get(pid)!.push(event);
    }
 
    const result = await Promise.all(
      sortedGroups.map(async ([_key, group]) => {
        const rep = group.events[0];
 
        const attachments: any[] = [];
        for (const event of group.events) {
          const attachmentType = mapAttachmentType(event.step_code);
          if (!attachmentType) continue;
 
          const pmoId = Number(event.pmoId);
          const pmoEvents = eventsByPmo.get(pmoId) ?? [];
          const eventIndex = pmoEvents.findIndex(e => e.id === event.id);
 
          const prevSameStepEvent = pmoEvents
            .slice(0, eventIndex)
            .reverse()
            .find(e => e.step_code === event.step_code);
 
          const fromTime = prevSameStepEvent?.event_time ?? null;
          const toTime = event.event_time;
 
          const where: any = {
            pmo_id: pmoId,
            type: attachmentType,
          };
 
          const fromISO = toUTCString(fromTime);
          const toISO = toUTCString(toTime);
 
          if (fromISO && toISO) {
            where.and = [{created_at: {gt: fromISO}}, {created_at: {lte: toISO}}];
          } else if (fromISO) {
            where.created_at = {gt: fromISO};
          } else if (toISO) {
            where.created_at = {lte: toISO};
          }
          const rows = await this.attachmentRepo.find({
            where,
            order: ['created_at DESC'],
          });
          const signed = await Promise.all(
            rows.map(async item => ({
              ...item,
              signed_url: await this.attachmentService.generateSignedUrl(item.file_url!),
            })),
          );
          attachments.push(...signed);
        }
 
        const removedPmoIds = new Set<number>();
        const normalPmoIds = new Set<number>();
 
        for (const event of group.events) {
          const pid = Number(event.pmoId);
          if (event.is_removed_from_box) {
            removedPmoIds.add(pid);
          } else {
            normalPmoIds.add(pid);
          }
        }
 
        return {
          step_code: rep.step_code,
          temporary_no: rep.temporary_no ?? null,
          user_name: rep.user_name,
          note: rep.note,
          event_time: rep.event_time,
          additional_information: (rep.additional_information ?? '').trim(),
          pmo_ids: Array.from(group.pmoIds),
          removed_pmo_ids: Array.from(removedPmoIds),
          attachments,
          is_removed_from_box: rep.is_removed_from_box ?? null,
        };
      }),
    );
 
    return result;
  }
 
  async getAllTimeLine(pmoIds: number[]) {
    if (!pmoIds?.length) {
      throw new HttpErrors.BadRequest('Not found PMO');
    }
 
    const eventsFromPmoIds = await this.timelineRepo.find({
      where: {pmoId: {inq: pmoIds.map(x => Number(x))}},
      order: ['event_time ASC'],
    });
 
    const temporaryNosFromEvents = [
      ...new Set(eventsFromPmoIds.map(e => e.temporary_no?.trim()).filter((t): t is string => t != null && t !== '')),
    ];
 
    let eventsFromTemporaryNos: any[] = [];
    if (temporaryNosFromEvents.length > 0) {
      eventsFromTemporaryNos = await this.timelineRepo.find({
        where: {temporary_no: {inq: temporaryNosFromEvents}},
        order: ['event_time ASC'],
      });
    }
 
    const eventMap = new Map<number, any>();
    for (const e of [...eventsFromPmoIds, ...eventsFromTemporaryNos]) {
      eventMap.set(Number(e.id), e);
    }
    const allEvents = Array.from(eventMap.values()).sort(
      (a, b) => new Date(a.event_time!).getTime() - new Date(b.event_time!).getTime(),
    );
 
    if (!allEvents.length) return [];
 
    const allPmoIdsInEvents = [...new Set(allEvents.map(e => Number(e.pmoId)))];
    const allPmosInEvents = await this.pmoRepo.find({
      where: {id: {inq: allPmoIdsInEvents}},
    });
    const pmoCodeMap = new Map<number, string>(allPmosInEvents.map(p => [Number(p.id), p.code]));
 
    type Group = {
      stepCode: string;
      tempNo: string | null;
      events: any[];
      pmoIds: Set<number>;
      firstTime: Date;
    };
 
    const rejectedSessionMap = new Map<string, number>();
 
    const rejectedLastWasRejected = new Map<string, boolean>();
 
    const nonRejectedGroupMap = new Map<string, Group>();
 
    const rejectedGroupMap = new Map<string, Group>();
 
    const groups: Group[] = [];
 
    const prevStepPerTempNo = new Map<string, string>();
 
    for (const event of allEvents) {
      const tempNo = event.temporary_no?.trim() || null;
 
      if (!tempNo) {
        groups.push({
          stepCode: event.step_code,
          tempNo: null,
          events: [event],
          pmoIds: new Set([Number(event.pmoId)]),
          firstTime: new Date(event.event_time!),
        });
        continue;
      }
 
      if (event.step_code === TimelineStep.REJECT) {
        const baseKey = `Rejected__${tempNo}`;
        const prevStep = prevStepPerTempNo.get(tempNo);
 
        if (!rejectedSessionMap.has(baseKey)) {
          rejectedSessionMap.set(baseKey, 0);
        } else if (prevStep !== TimelineStep.REJECT) {
          rejectedSessionMap.set(baseKey, rejectedSessionMap.get(baseKey)! + 1);
        }
 
        const session = rejectedSessionMap.get(baseKey)!;
        const groupKey = `${baseKey}__s${session}`;
 
        if (!rejectedGroupMap.has(groupKey)) {
          const g: Group = {
            stepCode: event.step_code,
            tempNo,
            events: [],
            pmoIds: new Set(),
            firstTime: new Date(event.event_time!),
          };
          rejectedGroupMap.set(groupKey, g);
          groups.push(g);
        }
 
        const g = rejectedGroupMap.get(groupKey)!;
        g.events.push(event);
        g.pmoIds.add(Number(event.pmoId));
      } else {
        const groupKey = `${event.step_code}__${tempNo}`;
 
        if (!nonRejectedGroupMap.has(groupKey)) {
          const g: Group = {
            stepCode: event.step_code,
            tempNo,
            events: [],
            pmoIds: new Set(),
            firstTime: new Date(event.event_time!),
          };
          nonRejectedGroupMap.set(groupKey, g);
          groups.push(g);
        }
 
        const g = nonRejectedGroupMap.get(groupKey)!;
        g.events.push(event);
        g.pmoIds.add(Number(event.pmoId));
      }
 
      prevStepPerTempNo.set(tempNo, event.step_code);
    }
 
    groups.sort((a, b) => a.firstTime.getTime() - b.firstTime.getTime());
 
    const eventsByPmo = new Map<number, any[]>();
    for (const event of allEvents) {
      const pid = Number(event.pmoId);
      if (!eventsByPmo.has(pid)) eventsByPmo.set(pid, []);
      eventsByPmo.get(pid)!.push(event);
    }
 
    type AttachmentQuery = {
      pmoId: number;
      type: AttachmentType;
      fromISO: string | null;
      toISO: string | null;
    };
 
    const attachmentQueries: AttachmentQuery[] = [];
    const attachmentResultMap = new Map<string, any[]>();
 
    for (const group of groups) {
      for (const event of group.events) {
        const attachmentType = mapAttachmentType(event.step_code);
        if (!attachmentType) continue;
 
        const pmoId = Number(event.pmoId);
        const pmoEvents = eventsByPmo.get(pmoId) ?? [];
        const eventIndex = pmoEvents.findIndex(e => e.id === event.id);
 
        const prevSameStepEvent = pmoEvents
          .slice(0, eventIndex)
          .reverse()
          .find(e => e.step_code === event.step_code);
 
        const fromISO = toUTCString(prevSameStepEvent?.event_time ?? null);
        const toISO = toUTCString(event.event_time);
 
        const queryKey = `${pmoId}__${attachmentType}__${toISO ?? ''}`;
        if (!attachmentResultMap.has(queryKey)) {
          attachmentResultMap.set(queryKey, []);
          attachmentQueries.push({pmoId, type: attachmentType, fromISO, toISO});
        }
      }
    }
 
    await Promise.all(
      attachmentQueries.map(async ({pmoId, type, fromISO, toISO}) => {
        const where: any = {pmo_id: pmoId, type};
        if (fromISO && toISO) {
          where.and = [{created_at: {gt: fromISO}}, {created_at: {lte: toISO}}];
        } else if (fromISO) {
          where.created_at = {gt: fromISO};
        } else if (toISO) {
          where.created_at = {lte: toISO};
        }
 
        const rows = await this.attachmentRepo.find({where, order: ['created_at DESC']});
        const signed = await Promise.all(
          rows.map(async item => ({
            ...item,
            signed_url: await this.attachmentService.generateSignedUrl(item.file_url!),
          })),
        );
 
        const queryKey = `${pmoId}__${type}__${toISO ?? ''}`;
        attachmentResultMap.set(queryKey, signed);
      }),
    );
 
    // ── BUILD RESULT ──
    const result = groups.map(group => {
      const rep = group.events[0];
 
      const attachments: any[] = [];
      const seenGroupUids = new Set<string>();
 
      for (const event of group.events) {
        const attachmentType = mapAttachmentType(event.step_code);
        if (!attachmentType) continue;
 
        const pmoId = Number(event.pmoId);
        const toISO = toUTCString(event.event_time);
        const queryKey = `${pmoId}__${attachmentType}__${toISO ?? ''}`;
        const rows = attachmentResultMap.get(queryKey) ?? [];
 
        for (const att of rows) {
          if (att.group_uid) {
            if (seenGroupUids.has(att.group_uid)) continue;
            seenGroupUids.add(att.group_uid);
          }
          attachments.push(att);
        }
      }
 
      const pmoEventMap = new Map<number, {hasNormal: boolean; hasRemoved: boolean}>();
      for (const event of group.events) {
        const pid = Number(event.pmoId);
        if (!pmoEventMap.has(pid)) {
          pmoEventMap.set(pid, {hasNormal: false, hasRemoved: false});
        }
        const entry = pmoEventMap.get(pid)!;
        if (event.is_removed_from_box) {
          entry.hasRemoved = true;
        } else {
          entry.hasNormal = true;
        }
      }
 
      const normalPmoCodes: string[] = [];
      const removedPmoCodes: string[] = [];
      for (const [pid, flags] of pmoEventMap.entries()) {
        const code = pmoCodeMap.get(pid) ?? String(pid);
        if (flags.hasNormal) {
          normalPmoCodes.push(code);
        } else {
          removedPmoCodes.push(code);
        }
      }
 
      return {
        step_code: rep.step_code,
        temporary_no: rep.temporary_no ?? null,
        shipping_no: rep.shipping_no ?? null,
        user_name: rep.user_name,
        note: rep.note,
        event_time: rep.event_time,
        additional_information: (rep.additional_information ?? '').trim(),
        pmo_codes: normalPmoCodes,
        removed_pmo_codes: removedPmoCodes,
        attachments,
        is_removed_from_box: rep.is_removed_from_box ?? null,
      };
    });
 
    return result;
  }
 
  // ========================
  // SLA CALCULATION METHODS
  // ========================
 
  /**
   * Get timeline with SLA deadline for Packing stage
   *
   * Integrated with PMO/Shipment to display Estimated Time
   * based on the forwarder's SLA configuration
   */
  async getTimelineWithSlaDeadline(pmoId: number, forwarder?: string) {
    if (!pmoId) {
      throw new HttpErrors.BadRequest('PMO ID is required');
    }
 
    // Get timeline events
    const events = await this.timelineRepo.find({
      where: {pmoId},
      order: ['event_time ASC'],
    });
 
    if (!events.length) {
      return null;
    }
 
    // Find the Packing event
    const dropppedEvent = events.find(e => e.step_code === TimelineStep.DROPPED);
 
    if (!dropppedEvent) {
      // No packing event, return timeline as is
      return {
        timeline: await this.findByPmoId(pmoId),
        sla_deadline: null,
        sla_config: null,
      };
    }
 
    // Get PMO to get forwarder info
    const pmo = await this.pmoRepo.findById(pmoId);
    const providerName = forwarder ?? pmo?.forwarder;
 
    if (!providerName) {
      return {
        timeline: await this.findByPmoId(pmoId),
        sla_deadline: null,
        sla_config: null,
        warning: 'No forwarder specified for SLA calculation',
      };
    }
 
    try {
      // Calculate SLA deadline
      const slaResult = await this.slaConfigService.calculateSlaDeadline({
        provider: providerName,
        startDateTime: dropppedEvent.event_time ?? new Date(),
        countryCode: pmo?.country_code, // If available
      });
      if (!slaResult) {
        return {
          timeline: await this.findByPmoId(pmoId),
          sla_deadline: null,
          sla_config: null,
        };
      }
      // Get SLA config
      const slaConfig = await this.slaConfigService.getSlaConfig(providerName, pmo?.country_code);
 
      // Get remaining time
      const remainingTime = this.slaConfigService.getRemainingTime(slaResult.deadline);
 
      return {
        timeline: await this.findByPmoId(pmoId),
        sla_deadline: {
          ...slaResult,
          remaining_time: remainingTime,
          is_overdue: remainingTime.isOverdue,
          status: remainingTime.isOverdue
            ? 'OVERDUE'
            : remainingTime.days === 0
            ? 'TODAY'
            : remainingTime.days === 1
            ? 'TOMORROW'
            : 'PENDING',
        },
        sla_config: slaConfig,
      };
    } catch (error) {
      return {
        timeline: await this.findByPmoId(pmoId),
        sla_deadline: null,
        sla_config: null,
        error: (error as any).message,
      };
    }
  }
 
  /**
   * Get timeline summary with SLA for multiple PMOs
   */
  async getTimelineSummaryWithSla(pmoIds: number[], forwarder?: string) {
    if (!pmoIds?.length) {
      throw new HttpErrors.BadRequest('PMO ids is required');
    }
 
    const summary = await this.getTimelineSummary(pmoIds);
    const slaMap = new Map<number, any>();
 
    // Get all PMOs to get forwarder info
    const pmos = await this.pmoRepo.find({
      where: {id: {inq: pmoIds}},
    });
    const pmoForwarderMap = new Map(pmos.map(p => [p.id, p.forwarder]));
 
    // Calculate SLA for each PMO
    for (const pmoId of pmoIds) {
      try {
        const result = await this.getTimelineWithSlaDeadline(pmoId, forwarder);
        if (result?.sla_deadline) {
          slaMap.set(pmoId, result.sla_deadline);
        }
      } catch (error) {
        // Skip if SLA calculation fails
        console.warn(`SLA calculation failed for PMO ${pmoId}:`, (error as any).message);
      }
    }
 
    // Merge SLA info into summary
    const result: Record<number, any> = {};
    for (const [pmoId, summaryData] of Object.entries(summary)) {
      const id = Number(pmoId);
      result[id] = {
        ...summaryData,
        sla_deadline: slaMap.get(id) || null,
        forwarder: pmoForwarderMap.get(id) ?? null,
      };
    }
 
    return result;
  }
 
  /**
   * Get SLA status for a specific timeline event
   */
  async getEventSlaStatus(eventId: number) {
    const event = await this.timelineRepo.findById(eventId);
 
    if (!event) {
      throw new HttpErrors.NotFound(`Timeline event ${eventId} not found`);
    }
 
    const slaDeadline = (event.metadata as any)?.sla_deadline;
 
    if (!slaDeadline) {
      return {
        has_sla: false,
        event_id: eventId,
        step_code: event.step_code,
      };
    }
 
    const deadline = new Date(slaDeadline);
    const remaining = this.slaConfigService.getRemainingTime(deadline);
 
    return {
      has_sla: true,
      event_id: eventId,
      step_code: event.step_code,
      sla_deadline: deadline,
      remaining_time: remaining,
      is_overdue: remaining.isOverdue,
      sla_config: (event.metadata as any)?.sla_config,
    };
  }
}