All files / src/hooks useCohortAnalysis.ts

0% Statements 0/90
100% Branches 0/0
0% Functions 0/1
0% Lines 0/90

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 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91                                                                                                                                                                                     
/**
 * useCohortAnalysis Hook
 *
 * Fetches customer cohort analysis data for retention visualization.
 */

"use client";

import { useState, useEffect, useCallback } from "react";

export interface CohortData {
  cohort: string;
  size: number;
  retention: number[];
  revenue: number[];
  orders: number[];
  averageOrderValue: number;
  customerLifetimeValue: number;
}

export interface CohortAnalysisResult {
  cohorts: CohortData[];
  totalUsers: number;
  averageRetention: number[];
  averageCLV: number;
}

interface UseCohortAnalysisResult {
  data: CohortAnalysisResult | null;
  isLoading: boolean;
  error: Error | null;
  months: number;
  setMonths: (months: number) => void;
  refetch: () => Promise<void>;
}

const emptyResult: CohortAnalysisResult = {
  cohorts: [],
  totalUsers: 0,
  averageRetention: [],
  averageCLV: 0,
};

export function useCohortAnalysis(initialMonths: number = 6): UseCohortAnalysisResult {
  const [data, setData] = useState<CohortAnalysisResult | null>(null);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<Error | null>(null);
  const [months, setMonths] = useState(initialMonths);

  const fetchCohorts = useCallback(async () => {
    try {
      setIsLoading(true);
      setError(null);

      const response = await fetch(`/api/admin/analytics/cohorts?months=${months}`);

      if (!response.ok) {
        throw new Error(`Failed to fetch cohort data: ${response.status}`);
      }

      const result = await response.json();

      if (result.success && result.data) {
        setData(result.data);
      } else {
        setData(emptyResult);
      }
    } catch (err) {
      setError(err instanceof Error ? err : new Error("Unknown error"));
      setData(emptyResult);
    } finally {
      setIsLoading(false);
    }
  }, [months]);

  useEffect(() => {
    fetchCohorts();
  }, [fetchCohorts]);

  return {
    data,
    isLoading,
    error,
    months,
    setMonths,
    refetch: fetchCohorts,
  };
}

export default useCohortAnalysis;