All files / src/api/suppliers supplierNormalizers.ts

100% Statements 59/59
100% Branches 18/18
100% Functions 1/1
100% Lines 59/59

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 601x 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 1x 1x 1x 1x 1x 1x 1x 12x 8x 8x 8x 8x 12x 12x 4x 4x 4x 12x 6x 6x 6x 12x 5x 5x 5x 5x 12x 12x 12x 12x 12x 12x 12x  
/**
 * @file supplierNormalizers.ts
 * @module api/suppliers/normalizers
 *
 * @summary
 * DTO normalization for supplier list rows.
 * Converts raw API responses to strongly-typed SupplierRow shapes.
 *
 * @enterprise
 * - Single responsibility: DTO → SupplierRow transformation
 * - Flexible field extraction with safe fallbacks
 * - Type-safe with full TypeScript support
 * - Reusable for both single rows and batch operations
 */
 
import type { SupplierRow } from './types';
import { pickString, pickNumber } from '../inventory/utils';
 
/**
 * Normalize a raw API response object into a strongly-typed SupplierRow.
 * Safely handles missing/misnamed fields from backend with intelligent fallbacks.
 *
 * @param raw - Raw DTO from API response
 * @returns SupplierRow with all fields safely extracted and coerced, or null if invalid
 *
 * @example
 * ```typescript
 * const rows = response.content
 *   .map(toSupplierRow)
 *   .filter((r): r is SupplierRow => r !== null);
 * ```
 */
export const toSupplierRow = (raw: unknown): SupplierRow | null => {
  if (typeof raw !== 'object' || raw === null) return null;
 
  const r = raw as Record<string, unknown>;
 
  // ID is required - try both string and number
  let id: string | null = pickString(r, 'id') ?? null;
  if (!id) {
    const numId = pickNumber(r, 'id');
    id = numId ? String(numId) : null;
  }
  if (!id) return null;
 
  // Name is required
  const name = pickString(r, 'name');
  if (!name) return null;
 
  return {
    id,
    name,
    contactName: pickString(r, 'contactName') ?? null,
    phone: pickString(r, 'phone') ?? null,
    email: pickString(r, 'email') ?? null,
    createdBy: pickString(r, 'createdBy') ?? null,
    createdAt: pickString(r, 'createdAt') ?? null,
  };
};