diff --git a/src/app/api/statistics/categories/route.ts b/src/app/api/statistics/categories/route.ts new file mode 100644 index 0000000..e507919 --- /dev/null +++ b/src/app/api/statistics/categories/route.ts @@ -0,0 +1,68 @@ +import { NextResponse } from 'next/server' +import { getServerSession } from 'next-auth' +import { authOptions } from '@/lib/auth' +import { getSessionUserId } from '@/lib/auth/session' +import { prisma } from '@/lib/db' +import type { ApiResponse } from '@/types/common' + +// 하루에 한 번 재계산 (홈 화면 통계는 실시간 불필요) +export const revalidate = 86400 + +const ALL_CATEGORIES = ['ROMANCE', 'FAMILY', 'FRIEND', 'WORK'] as const + +// GET /api/statistics/categories +// 판결 완료 사건 기준 카테고리별(연애/가족/친구/직장) count 반환 +// 비율 계산은 프론트 훅(useStatistics)에서 처리 +export async function GET() { + const session = await getServerSession(authOptions) + const userId = getSessionUserId(session) + if (!userId) { + return NextResponse.json( + { success: false, error: { code: 'UNAUTHORIZED', message: '로그인이 필요합니다.' } }, + { status: 401 }, + ) + } + + try { + const grouped = await prisma.dispute.groupBy({ + by: ['categoryGroup'], + where: { + status: 'JUDGED', + deletedAt: null, + anonymizedAt: null, + }, + _count: { id: true }, + }) + + const total = grouped.reduce((sum, g) => sum + g._count.id, 0) + const countMap = new Map(grouped.map((g) => [g.categoryGroup, g._count.id])) + + // 4개 카테고리 모두 항상 포함 (데이터 없는 카테고리는 count 0) + const items = ALL_CATEGORIES.map((category) => ({ + category, + count: countMap.get(category) ?? 0, + })) + + return NextResponse.json>({ + success: true, + data: { items, total }, + }) + } catch (error) { + const message = error instanceof Error ? error.message : String(error) + const isTimeout = /timeout|timed out/i.test(message) + + console.error('[statistics/categories] api error', { isTimeout, message }) + + if (isTimeout) { + return NextResponse.json( + { success: false, error: { code: 'TIMEOUT', message: '요청 처리 시간이 초과되었습니다.' } }, + { status: 504 }, + ) + } + + return NextResponse.json( + { success: false, error: { code: 'INTERNAL_SERVER_ERROR', message: '서버 오류가 발생했습니다.' } }, + { status: 500 }, + ) + } +} diff --git a/src/hooks/useStatistics.ts b/src/hooks/useStatistics.ts new file mode 100644 index 0000000..d3748c0 --- /dev/null +++ b/src/hooks/useStatistics.ts @@ -0,0 +1,37 @@ +'use client' + +import { useQuery } from '@tanstack/react-query' + +type CategoryItem = { + category: 'ROMANCE' | 'FAMILY' | 'FRIEND' | 'WORK' + count: number +} + +export type CategoryStat = CategoryItem & { + percentage: number +} + +async function fetchCategoryStats() { + const res = await fetch('/api/statistics/categories') + if (!res.ok) throw new Error('통계 데이터를 불러오지 못했습니다.') + const json = await res.json() + return json.data as { items: CategoryItem[]; total: number } +} + +export function useStatistics() { + return useQuery({ + queryKey: ['statistics', 'categories'], + queryFn: async () => { + const { items, total } = await fetchCategoryStats() + + // 카테고리별 비율 계산 (소수점 1자리) + const stats: CategoryStat[] = items.map((item) => ({ + ...item, + percentage: total > 0 ? Math.round((item.count / total) * 1000) / 10 : 0, + })) + + return { items: stats, total } + }, + staleTime: 1000 * 60 * 60 * 24, // 서버 revalidate(86400s)와 맞춤 + }) +}