All files / lib/api api.ts

92% Statements 23/25
83.33% Branches 10/12
100% Functions 7/7
91.66% Lines 22/24

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                    7x     2x               4x   4x 1x 1x     3x         2x 1x 1x     1x         1x         1x         2x 1x 1x     1x         2x 1x 1x     1x 1x    
import type {
  ApiEnvelope,
  CustomerFilters,
  CustomersResponse,
  JiraDeliveryResponse,
  Metric,
  RevenuePoint,
} from "@/types/dashboard";
import {queryCustomers} from "@/lib/customer-query/customer-query";
 
const isStaticDataMode = () => process.env.NEXT_PUBLIC_DATA_MODE === "static";
 
function createEnvelope<T>(data: T): ApiEnvelope<T> {
  return {
    data,
    updatedAt: new Date().toISOString(),
  };
}
 
// Centralize API error handling so TanStack Query can expose consistent error states.
async function fetchJson<T>(url: string): Promise<T> {
  const response = await fetch(url);
 
  if (!response.ok) {
    const message = await response.text();
    throw new Error(message || `Request failed with status ${response.status}`);
  }
 
  return await response.json() as Promise<T>;
}
 
/** Fetch KPI metrics for the executive overview cards. */
export async function fetchMetrics() {
  if (isStaticDataMode()) {
    const {metrics} = await import("@/lib/mock-data/mock-data");
    return createEnvelope(metrics);
  }
 
  return fetchJson<ApiEnvelope<Metric[]>>("/api/metrics");
}
 
/** Fetch monthly revenue points for the composition chart. */
export async function fetchRevenue() {
  Iif (isStaticDataMode()) {
    const {revenue} = await import("@/lib/mock-data/mock-data");
    return createEnvelope(revenue);
  }
 
  return fetchJson<ApiEnvelope<RevenuePoint[]>>("/api/revenue");
}
 
/** Fetch Jira-like delivery KPI signals for manager execution analysis. */
export async function fetchDelivery() {
  if (isStaticDataMode()) {
    const {jiraDelivery} = await import("@/lib/mock-data/mock-data");
    return createEnvelope(jiraDelivery);
  }
 
  return fetchJson<ApiEnvelope<JiraDeliveryResponse>>("/api/delivery");
}
 
/** Fetch paginated and filtered customer accounts for the customer table. */
export async function fetchCustomers(filters: CustomerFilters) {
  if (isStaticDataMode()) {
    const {customers} = await import("@/lib/mock-data/mock-data");
    return queryCustomers(customers, filters);
  }
 
  const response = await fetchJson<CustomersResponse>("/api/customers");
  return queryCustomers(response.data, filters);
}