All files / src/api/analytics frequency.ts

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

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 551x 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 6x 6x 6x 6x 5x 5x 5x 5x 6x 3x 3x 3x 3x 8x 8x 8x 8x 8x 8x 3x 3x 3x 6x 1x 1x 6x  
/**
* @file frequency.ts
* @module api/analytics/frequency
*
* @summary
* Supplier-scoped item update frequency (top N items by change count).
* Fetches and normalizes item update frequency data.
* @enterprise
* - Resilient data fetching with graceful error handling
* - Flexible field recognition for robust parsing
* - TypeDoc documentation for item frequency analytics function
*/
 
import http from '../httpClient';
import { isArrayOfRecords, pickNumber, pickString } from './util';
 
 
export type ItemUpdateFrequencyPoint = { id: string; name: string; updates: number };
 
/**
 * GET /api/analytics/item-update-frequency?supplierId=...&limit=N
 * Accepts either:
 *   - { id, name, updates } or
 *   - { itemId?, itemName, updates|updateCount|count }
 *
 * If no id is present, uses the name as a stable id.
 */
export async function getItemUpdateFrequency(
  supplierId: string,
  limit = 10
): Promise<ItemUpdateFrequencyPoint[]> {
  if (!supplierId) return [];
  try {
    const { data } = await http.get<unknown>('/api/analytics/item-update-frequency', {
      params: { supplierId, limit }
    });
    if (!isArrayOfRecords(data)) return [];
 
    // Parse and normalize records
    return (data as Array<Record<string, unknown>>)
      .map((r) => {
        // tolerant name/id picking
        const name = pickString(r, ['name', 'itemName']);
        if (!name) return null;
        const id = pickString(r, ['id', 'itemId', 'sku', 'code']) || name;
        const updates = pickNumber(r, ['updates', 'updateCount', 'updatesCount', 'count', 'changes']);
        return { id, name, updates } as ItemUpdateFrequencyPoint;
      })
      .filter((x): x is ItemUpdateFrequencyPoint => x !== null)
      .slice(0, limit);
  } catch {
    return [];
  }
}