All files / src/repositories/scan shipment.repository.ts

7.29% Statements 7/96
0% Branches 0/93
0% Functions 0/20
5.62% Lines 5/89

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 3111x 1x 1x   1x     1x                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              
import {inject} from '@loopback/core';
import {BaseCrudRepository} from '../base-crud.repository.base';
import {LogChainDataSource} from '../../datasources';
 
import {Shipment, ShipmentRelations} from '../../models/scan/shipment.model';
import {PmoStatusValueMap} from '@logchain/types';
 
export class ShipmentRepository extends BaseCrudRepository<Shipment, typeof Shipment.prototype.id, ShipmentRelations> {
  private buildSortClause(
    sort: Array<string> | undefined,
    sortableFields: {[key: string]: string},
    fallback: string,
  ): string {
    if (!sort?.length) {
      return fallback;
    }
 
    const parsedSort = sort
      .map(item => {
        const trimmed = `${item ?? ''}`.trim();
        if (!trimmed) {
          return null;
        }
 
        const [fieldRaw, directionRaw] = trimmed.split(/\s+/);
        const fieldKey = (fieldRaw ?? '').toLowerCase();
        const field = sortableFields[fieldKey];
        if (!field) {
          return null;
        }
 
        const direction = `${directionRaw ?? 'ASC'}`.toUpperCase() === 'DESC' ? 'DESC' : 'ASC';
        return `${field} ${direction}`;
      })
      .filter((item): item is string => !!item);
 
    return parsedSort.length ? parsedSort.join(', ') : fallback;
  }
 
  constructor(@inject('datasources.logchain') dataSource: LogChainDataSource) {
    super(Shipment, dataSource);
  }
 
  async findByShippingNo(shippingNo: string): Promise<Shipment[]> {
    const result = await this.execute(`SELECT * FROM scan.shipment WHERE shipping_no = $1`, [shippingNo]);
 
    return result as Shipment[];
  }
 
  private buildShipmentSearchConditions(params: {
    q?: string;
    status?: string;
    fromDate?: string;
    toDate?: string;
    emptyOnly?: boolean;
  }) {
    const {q, status, fromDate, toDate, emptyOnly = false} = params;
 
    const conditions: string[] = [];
    const queryParams: any[] = [];
    let idx = 1;
 
    if (q?.trim()) {
      conditions.push(`
        (
          b.shipping_no ILIKE $${idx}
          OR b.temporary_no ILIKE $${idx}
          OR p.code ILIKE $${idx}
        )
      `);
      queryParams.push(`%${q.trim()}%`);
      idx++;
    }
 
    const ALLOWED_STATUSES = ['Pickup', 'Packed', 'Picked', 'Rejected'];
    if (status?.trim()) {
      conditions.push(`te.step_code = $${idx}`);
      queryParams.push(status.trim());
      idx++;
    } else {
      conditions.push(`te.step_code = ANY($${idx}::text[])`);
      queryParams.push(ALLOWED_STATUSES);
      idx++;
    }
 
    //fromDate and toDate are expected to be in ISO format (e.g., '2024-01-01' or '2024-01-01T00:00:00Z')
    if (fromDate) {
      conditions.push(`te.event_time >= $${idx}::timestamp`);
      queryParams.push(fromDate);
      idx++;
    }
 
    if (toDate) {
      // Inclusive end-of-day for date-only inputs.
      conditions.push(`te.event_time < ($${idx}::timestamp + interval '1 day')`);
      queryParams.push(toDate);
      idx++;
    }
 
    if (emptyOnly) {
      //Update the condition to only return shipments that do not shipment no or empty shipment no
      conditions.push(`(b.shipping_no IS NULL OR b.shipping_no = '')`);
    }
 
    return {
      conditions,
      queryParams,
      idx,
    };
  }
 
  private async enrichShipmentData(data: any[]) {
    if (!data.length) {
      return data;
    }
    const temporaryNos = [...new Set(data.map(x => x.temporary_no).filter(Boolean))];
    let boxesResult: any[] = [];
    if (temporaryNos.length) {
      boxesResult = (await this.execute(
        `
      SELECT
        b.*,
        d.display_text as dimension_name,
        d.length,
        d.width,
        d.height
      FROM box b
      LEFT JOIN dimension d
        ON d.id = b.dimension_id
      WHERE b.temporary_no = ANY($1)
      `,
        [temporaryNos],
      )) as any[];
    }
    const boxIds = [...new Set(boxesResult.map(x => Number(x.id)))];
    let pmosResult: any[] = [];
 
    if (boxIds.length) {
      pmosResult = (await this.execute(
        `SELECT
        p.id,
        p.code,
        p.eq_no,
        p.po,
        p.status,
        p.box_id,
        p.shipment_id,
        p.updated_at
      FROM pmo p
      WHERE p.box_id = ANY($1)
      `,
        [boxIds],
      )) as any[];
    }
    boxesResult.forEach(box => {
      box.pmos = pmosResult.filter(p => Number(p.box_id) === Number(box.id));
      box.pmo_codes = box.pmos.map((p: any) => p.code);
    });
    data.forEach((shipment: any) => {
      shipment.total_weight = boxesResult
        .filter((box: any) => box.temporary_no === shipment.temporary_no)
        .reduce((sum: number, box: any) => sum + (box.weight ?? 0), 0);
      shipment.boxes = boxesResult.filter(
        (box: any) =>
          box.temporary_no === shipment.temporary_no && (box.shipping_no ?? '') === (shipment.shipping_no ?? ''),
      );
      //shipment.pmos = pmosResult.filter((pmo: any) => pmo.temporary_no === shipment.temporary_no);
      shipment.pmos = shipment.boxes.flatMap((box: any) => box.pmos || []);
    });
    return data;
  }
 
  async searchShipmentPaging(params: {
    q?: string;
    status?: string;
    fromDate?: string;
    toDate?: string;
    emptyOnly?: boolean;
    sort?: Array<string>;
    page: number;
    limit: number;
  }) {
    const {q, status, fromDate, toDate, emptyOnly = false, sort, page, limit} = params;
 
    const {
      conditions,
      queryParams,
      idx: startIdx,
    } = this.buildShipmentSearchConditions({
      q,
      status,
      fromDate,
      toDate,
      emptyOnly,
    });
 
    let idx = startIdx;
    const whereClause = conditions.length ? `WHERE ${conditions.join(' AND ')}` : '';
    const orderByClause = this.buildSortClause(
      sort,
      {
        id: 'b.id',
        shipping_no: 'b.shipping_no',
        temporary_no: 'b.temporary_no',
      },
      'te.event_time DESC',
    );
    const offset = (page - 1) * limit;
    const data = (await this.execute(
      `SELECT DISTINCT b.temporary_no, b.shipping_no, te.step_code AS status, te.event_time AS last_update, te.user_name AS last_updated_by
FROM box b INNER JOIN pmo p ON b.id = p.box_id LEFT join (SELECT DISTINCT ON (temporary_no) *
FROM timeline_event where temporary_no is not null 
ORDER BY temporary_no, id DESC) te on b.temporary_no = te.temporary_no  
      ${whereClause}
      ORDER BY ${orderByClause}
      LIMIT $${idx++} OFFSET $${idx++}
      `,
      [...queryParams, limit, offset],
    )) as any[];
    await this.enrichShipmentData(data);
    const totalResult = (await this.execute(
      `SELECT COUNT(*) AS total
      FROM (SELECT DISTINCT b.temporary_no, te.step_code AS status, te.event_time AS lastUpdate, te.user_name AS lastUpdatedBy
FROM box b INNER JOIN pmo p ON b.id = p.box_id LEFT join (SELECT DISTINCT ON (temporary_no) *
FROM timeline_event where temporary_no is not null 
ORDER BY temporary_no, id DESC) te on b.temporary_no = te.temporary_no 
        ${whereClause}
      ) filtered
      `,
      queryParams,
    )) as any[];
    const total = Number(totalResult?.[0]?.total ?? 0);
    return {
      data,
      total,
      page,
      limit,
      has_more: page * limit < total,
    };
  }
 
  async searchShipmentAllForExport(params: {
    q?: string;
    status?: string;
    fromDate?: string;
    toDate?: string;
    emptyOnly?: boolean;
  }) {
    const {q, status, fromDate, toDate, emptyOnly = false} = params;
 
    const {
      conditions,
      queryParams,
      idx: startIdx,
    } = this.buildShipmentSearchConditions({
      q,
      status,
      fromDate,
      toDate,
      emptyOnly,
    });
 
    const whereClause = conditions.length ? `WHERE ${conditions.join(' AND ')}` : '';
    const orderByClause = 'b.temporary_no DESC';
    return (await this.execute(
      `
      SELECT
        b.id AS box_id,
        b.shipping_no,
        b.temporary_no,
        te.step_code AS status,
        COALESCE(d.display_text, '') AS dimensions,
        COALESCE(b.weight, 0) AS total_weight,
        STRING_AGG(DISTINCT NULLIF(TRIM(p.po), ''), ', ') AS po_numbers,
        STRING_AGG(DISTINCT 'PMO ' || p.code, ', ') AS pmo_codes,
        te.event_time AS "lastUpdate",
        te.user_name AS "lastUpdateBy"
      FROM box b
      INNER JOIN pmo p ON b.id = p.box_id
      LEFT JOIN dimension d ON b.dimension_id = d.id
      LEFT JOIN (
        SELECT DISTINCT ON (temporary_no) *
        FROM timeline_event
        WHERE temporary_no IS NOT NULL
        ORDER BY temporary_no, id DESC
      ) te ON b.temporary_no = te.temporary_no
      ${whereClause}
      GROUP BY
        b.id,
        b.shipping_no,
        b.temporary_no,
        d.display_text,
        b.weight,
        te.step_code,
        te.event_time,
        te.user_name
      ORDER BY ${orderByClause}
      `,
      queryParams,
    )) as any[];
  }
 
  async generateTemporaryNo(): Promise<string> {
    const result = await this.execute(`
    SELECT generate_temporary_unique_no() AS temporary_no
  `);
 
    return result?.[0]?.temporary_no;
  }
}