All files / src/api/analytics priceTrend.ts

100% Statements 48/48
90% Branches 9/10
100% Functions 1/1
100% Lines 48/48

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 481x 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 5x 5x 4x 4x 4x 4x 5x 2x 3x 3x 2x 2x 2x 5x 1x 1x 5x
/**
* @file priceTrend.ts
* @module api/analytics/priceTrend
*
* @summary
* Price trend time series for a given item within an optional date/supplier window.
* Provides function to fetch historical price points.
* @enterprise
* - Resilient data fetching with graceful error handling
* - TypeDoc documentation for price trend analytics function
*/
import http from '../httpClient';
import { asNumber, paramClean } from './util';
import type { AnalyticsParams } from './validation';
import type { PricePoint } from './types';
 
// Tolerant DTO (local)
type BackendPriceTrendDTO = { timestamp?: string; price?: unknown };
 
/** Fetch an item's price trend in a time window. 
 * Returns array of {date, price}. Empty array on errors.
 * @example
 * ```typescript
 * const points = await getPriceTrend('ITEM-123', {
 *   from: '2025-09-01',
 *  to: '2025-11-30',
 *  supplierId: 'SUP-001'
 * });
 * return <LineChart data={points} />;
 * ```
*/
export async function getPriceTrend(itemId: string, p?: AnalyticsParams): Promise<PricePoint[]> {
    if (!itemId) return [];
    try {
        const { data } = await http.get<unknown>('/api/analytics/price-trend', {
            params: { itemId, ...paramClean(p) },
        });
        if (!Array.isArray(data)) return [];
        const rows = (data as BackendPriceTrendDTO[]).map((d) => ({
            date: String(d.timestamp ?? ''),
            price: asNumber(d.price),
        }));
        rows.sort((a, b) => a.date.localeCompare(b.date));
        return rows;
    } catch {
        return [];
    }
}