All files / app/detail/hooks useAIReport.ts

100% Statements 24/24
83.33% Branches 5/6
100% Functions 3/3
100% Lines 24/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 73 74 75 76 77 78 79 80 81 82 83                                                        18x 18x 18x 18x         18x 8x 2x 2x     6x 6x 6x     6x   5x   5x   4x 3x   1x     2x 2x 2x   6x             18x 7x     18x                
/**
 * useAIReport Hook
 */
 
import { useEffect, useState } from 'react';
 
import { aiReportService, type AIReportData } from '@/src/services/api';
 
interface UseAIReportReturn {
  /** AI 报告数据 */
  report: AIReportData | null;
  /** 是否存在报告 */
  hasReport: boolean;
  /** 是否正在加载 */
  isLoading: boolean;
  /** 错误信息 */
  error: string | null;
  /** 重新加载报告 */
  refetch: () => Promise<void>;
}
 
/**
 * AI 报告 Hook
 *
 * @param catfoodId - 猫粮 ID
 * @returns AI 报告状态和方法
 */
export function useAIReport(catfoodId: number | null): UseAIReportReturn {
  const [report, setReport] = useState<AIReportData | null>(null);
  const [hasReport, setHasReport] = useState(false);
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
 
  /**
   * 加载 AI 报告
   */
  const loadReport = async () => {
    if (!catfoodId) {
      setHasReport(false);
      return;
    }
 
    try {
      setIsLoading(true);
      setError(null);
 
      // 先检查报告是否存在
      const checkResult = await aiReportService.checkReportExists(catfoodId);
 
      setHasReport(checkResult.exists);
 
      if (checkResult.exists) {
        // 获取报告详情
        const reportData = await aiReportService.getReport(catfoodId);
        setReport(reportData);
      } else {
        setReport(null);
      }
    } catch (err: any) {
      setError(err.message || '加载失败');
      setHasReport(false);
      setReport(null);
    } finally {
      setIsLoading(false);
    }
  };
 
  /**
   * 当 catfoodId 变化时重新加载
   */
  useEffect(() => {
    loadReport();
  }, [catfoodId]);
 
  return {
    report,
    hasReport,
    isLoading,
    error,
    refetch: loadReport,
  };
}