All files / src/api/inventory rowNormalizers.ts

100% Statements 74/74
100% Branches 12/12
100% Functions 1/1
100% Lines 74/74

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 751x 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 1x 1x 1x 1x 1x 6x 3x 3x 3x 3x 3x 6x 2x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x  
/**
 * @file rowNormalizers.ts
 * @module api/inventory/rowNormalizers
 *
 * @summary
 * DTO normalization for inventory list rows.
 * Converts raw API responses to strongly-typed InventoryRow shapes.
 * Maps backend fields (id, quantity, minimumQuantity) → frontend fields (itemId, onHand, minQty).
 *
 * @enterprise
 * - Single responsibility: DTO → InventoryRow transformation
 * - Handles backend field name mappings transparently
 * - Type-safe with full TypeScript support
 * - Reusable for both single rows and batch operations
 */
 
import type { InventoryRow } from './types';
import { pickString, pickNumber } from './utils';
 
/**
 * Normalize a raw API response object into a strongly-typed InventoryRow.
 * Maps backend fields:
 *  - id → itemId
 *  - quantity → onHand
 *  - minimumQuantity → minQty
 *  - createdAt → updatedAt
 *
 * @param raw - Raw DTO from API response
 * @returns InventoryRow with all fields safely extracted and coerced, or null if invalid
 *
 * @example
 * ```typescript
 * const rows = response.content
 *   .map(toInventoryRow)
 *   .filter((r): r is InventoryRow => r !== null);
 * ```
 */
export const toInventoryRow = (raw: unknown): InventoryRow | null => {
  if (typeof raw !== 'object' || raw === null) return null;
 
  const r = raw as Record<string, unknown>;
 
  // ID is required
  const id = pickString(r, 'id');
  if (!id) return null;
 
  const name = pickString(r, 'name') ?? '—';
  const code = pickString(r, 'code') ?? null;
 
  const supplierIdStr = pickString(r, 'supplierId');
  const supplierId: string | number | null = supplierIdStr ?? null;
 
  const supplierName = pickString(r, 'supplierName') ?? null;
 
  // quantity → onHand
  const onHand = pickNumber(r, 'quantity') ?? 0;
 
  // minimumQuantity → minQty
  const minQty = pickNumber(r, 'minimumQuantity') ?? null;
 
  // createdAt → updatedAt (for display)
  const updatedAt = pickString(r, 'createdAt') ?? null;
 
  return {
    id,
    name,
    code,
    supplierId,
    supplierName,
    onHand,
    minQty,
    updatedAt,
  };
};