Repository navigation
feat: 통계 API 구현 (GET /api/statistics/categories) #44
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 27 commits
Commits
Show all changes
28 commits
Select commit
Hold shift + click to select a range
811cedd
feat: 사건조회 페이지 판결,유형 tab 공통 컴포넌트 생성
wjdalss21 a2f5ff4
feat: 사건 관련 페이지의 진행 상태 컴포넌트
wjdalss21 f42f802
Merge remote-tracking branch 'origin/dev' into feature/common-compone…
wjdalss21 5da994c
fix: StatusBadge CSS 변수 하드코딩 제거 및 Tab className trailing space 수정
wjdalss21 3ede2bc
fix: StatusBadge 크기 조정 및 .playwright-mcp gitignore 추가
wjdalss21 e08c74c
feat: CategoryFilter 공통 컴포넌트 생성
wjdalss21 f46d301
fix: Tab 라벨 폰트 스타일 명시
wjdalss21 e04b9eb
chore: @mui/icons-material 패키지 추가
wjdalss21 37c7652
Merge remote-tracking branch 'origin/dev' into feature/common-compone…
wjdalss21 d9fc1a5
feat: CategoryFilter 스타일 및 single 모드 적용
wjdalss21 b29f0c9
feat: CategoryIcon 컴포넌트 생성 및 CategoryFilter 아이콘 매핑 분리
wjdalss21 56dedb9
fix: 카테고리 타입을 DB CategoryGroup 기준으로 통일
wjdalss21 d5af9ee
Update src/components/ui/CategoryIcon.tsx
wjdalss21 f3f035c
fix: CategoryIcon 중복 import 제거 및 CategoryFilter discriminated union 타…
wjdalss21 1c33fb9
fix: CaseCard 카테고리 아이콘을 제목 왼쪽 인라인으로 이동
wjdalss21 3971ae4
docs: 공통 컴포넌트 테스트 스크린샷 추가
wjdalss21 f46ef9e
Merge remote-tracking branch 'origin/dev' into feature/common-compone…
wjdalss21 65c4d25
Merge remote-tracking branch 'origin/dev' into feature/common-compone…
wjdalss21 81e184b
fix: CaseCard titleRow flex 축소 보완 (min-width: 0, flex: 1)
wjdalss21 8d94d2f
Merge remote-tracking branch 'origin/dev' into feature/common-compone…
wjdalss21 45a8ea6
Merge remote-tracking branch 'origin/dev' into feature/common-compone…
wjdalss21 d159a19
feat: 통계 도메인 서비스 레이어 생성 (statisticsService.ts)
wjdalss21 d57ce7e
feat: 통계 API Route Handler 생성 (GET /api/v1/statistics/top-types)
wjdalss21 7a0974b
fix: statistics top-types 인증 제거 (메인 페이지 공개 접근 허용)
wjdalss21 d2e5efb
fix: statistics top-types 에러 핸들링 보완
wjdalss21 2aa6931
Merge remote-tracking branch 'origin/dev' into feature/create-api-jm
wjdalss21 945a54c
refactor: 통계 API 카테고리 기준으로 재설계
wjdalss21 83a705d
fix: 통계 API 서버 측 세션 인증 추가
wjdalss21 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,56 @@ | ||
| import { NextResponse } from 'next/server' | ||
| 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() { | ||
| 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<ApiResponse<{ items: typeof items; total: number }>>({ | ||
| 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<ApiResponse>( | ||
| { success: false, error: { code: 'TIMEOUT', message: '요청 처리 시간이 초과되었습니다.' } }, | ||
| { status: 504 }, | ||
| ) | ||
| } | ||
|
|
||
| return NextResponse.json<ApiResponse>( | ||
| { success: false, error: { code: 'INTERNAL_SERVER_ERROR', message: '서버 오류가 발생했습니다.' } }, | ||
| { status: 500 }, | ||
| ) | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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)와 맞춤 | ||
| }) | ||
| } |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.