import { useEffect } from 'react'; import { useQuery } from '@tanstack/react-query'; import { PLAN_LIMITS } from '@cra-compliance/types'; import type { DashboardStats, PlanLimits } from '@cra-compliance/types'; import type { ReadinessLine } from '@cra-compliance/shared'; import { externalApiFetch, getStoredPlan, markPlanStored, setServicePlan, toPlan, useConfig, wpApiFetch } from './useApi'; /** /api/dashboard. `readiness_lines` is optional: older API versions do not send it. */ export type AccountStats = DashboardStats & { readiness_lines?: ReadinessLine[] }; export function useDashboardStats() { const config = useConfig(); return useQuery({ queryKey: ['dashboard'], enabled: config.connected, queryFn: async () => (await externalApiFetch<{ data: AccountStats }>('/api/dashboard')).data, staleTime: 5 * 60 * 1000, refetchInterval: 5 * 60 * 1000, retry: 1, }); } /** * Limits as the service sends them, on top of the table bundled with the * plugin. The service sends "unlimited" as null (JSON has no Infinity). */ function mergeLimits(bundled: PlanLimits, live: unknown): PlanLimits { if (!live || typeof live !== 'object') return bundled; const merged: Record = { ...bundled }; for (const [key, fallback] of Object.entries(bundled)) { const value = (live as Record)[key]; if (value === null && typeof fallback === 'number') merged[key] = Infinity; else if (value !== null && typeof value === typeof fallback) merged[key] = value; } return merged as unknown as PlanLimits; } /** * What the account's plan allows today. The service is the source: it knows * about upgrades, downgrades and team plans. The table bundled with the plugin * is only used until the first answer arrives, or when the service is down. */ export function useLimits(): PlanLimits { const config = useConfig(); const stats = useDashboardStats(); return mergeLimits(PLAN_LIMITS[config.plan], stats.data?.limits); } /** * Keep the plan in step with the account. The plan saved with the API key is a * copy from the day the key was entered, so it goes out of date on an upgrade. * Each time the service reports the plan, use it and save it for the next page * load. */ export function usePlanSync() { const stats = useDashboardStats(); const reported = stats.data?.plan; useEffect(() => { if (!reported) return; const plan = toPlan(reported); setServicePlan(plan); if (plan === getStoredPlan()) return; wpApiFetch('settings', { method: 'POST', body: JSON.stringify({ plan }) }) .then(() => markPlanStored(plan)) .catch(() => { /* Saved on a later load. This session already uses the reported plan. */ }); }, [reported]); }