Repository navigation
feat: AI 판결 스키마 분리 및 판결 로직 구현 #70
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
Changes from 3 commits
1f931fd
c1a7c93
69bd306
5f32f01
a8bc195
2706c8e
b3eaa7b
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Large diffs are not rendered by default.
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,92 @@ | ||
| import { NextRequest, NextResponse } from 'next/server' | ||
| import { getServerSession } from 'next-auth' | ||
| import { authOptions } from '@/lib/auth' | ||
| import { prisma } from '@/lib/db' | ||
| import { getSessionUserId } from '@/lib/auth/session' | ||
| import type { ApiResponse } from '@/types/common' | ||
| import type { DisputeStatus, StatementSubmitResponse } from '@/types/dispute' | ||
|
|
||
| // POST /api/disputes/:id/statements/submit | ||
| // 진술 최종 제출. submittedAt 설정 후 dispute 상태 업데이트. 멱등성 보장. | ||
| export async function POST( | ||
| _request: NextRequest, | ||
| { params }: { params: Promise<{ id: string }> }, | ||
| ) { | ||
| const session = await getServerSession(authOptions) | ||
| const userId = getSessionUserId(session) | ||
|
|
||
| if (!userId) { | ||
| return NextResponse.json<ApiResponse>( | ||
| { success: false, error: { code: 'UNAUTHORIZED', message: '로그인이 필요합니다.' } }, | ||
| { status: 401 }, | ||
| ) | ||
| } | ||
|
|
||
| const { id: disputeId } = await params | ||
|
|
||
| try { | ||
| const participant = await prisma.disputeParticipant.findFirst({ | ||
| where: { disputeId, userId }, | ||
| include: { statements: true }, | ||
| }) | ||
|
coderabbitai[bot] marked this conversation as resolved.
Resolved
|
||
|
|
||
| if (!participant) { | ||
| return NextResponse.json<ApiResponse>( | ||
| { success: false, error: { code: 'FORBIDDEN', message: '해당 사건의 참여자가 아닙니다.' } }, | ||
| { status: 403 }, | ||
| ) | ||
| } | ||
|
|
||
| const statement = participant.statements[0] ?? null | ||
|
|
||
| if (!statement) { | ||
| return NextResponse.json<ApiResponse>( | ||
| { success: false, error: { code: 'NOT_FOUND', message: '제출할 진술이 없습니다.' } }, | ||
| { status: 404 }, | ||
| ) | ||
| } | ||
|
|
||
| // 이미 제출된 경우 멱등성 처리 | ||
| if (statement.submittedAt) { | ||
| const dispute = await prisma.dispute.findUniqueOrThrow({ where: { id: disputeId } }) | ||
| return NextResponse.json<ApiResponse<StatementSubmitResponse>>({ | ||
| success: true, | ||
| data: { | ||
| id: statement.id, | ||
| submittedAt: statement.submittedAt.toISOString(), | ||
| disputeStatus: dispute.status.toLowerCase() as DisputeStatus, | ||
| }, | ||
| }) | ||
| } | ||
|
|
||
| const newDisputeStatus = | ||
| participant.role === 'ROLE_A' ? ('WAITING_OPPONENT' as const) : ('BOTH_SUBMITTED' as const) | ||
|
|
||
| const [updatedStatement, updatedDispute] = await prisma.$transaction([ | ||
| prisma.disputeStatement.update({ | ||
| where: { id: statement.id }, | ||
| data: { submittedAt: new Date() }, | ||
| }), | ||
| prisma.dispute.update({ | ||
| where: { id: disputeId }, | ||
| data: { status: newDisputeStatus }, | ||
| }), | ||
| ]) | ||
|
Comment on lines
+82
to
+107
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 멱등성과 상태 전이를 같은 트랜잭션에서 실제 제출 수 기준으로 계산해야 합니다. Line 50의 선조회( 수정 제안 (interactive transaction + 조건부 업데이트)- // 이미 제출된 경우 멱등성 처리
- if (statement.submittedAt) {
- const dispute = await prisma.dispute.findUniqueOrThrow({ where: { id: disputeId } })
- return NextResponse.json<ApiResponse<StatementSubmitResponse>>({
- success: true,
- data: {
- id: statement.id,
- submittedAt: statement.submittedAt.toISOString(),
- disputeStatus: dispute.status.toLowerCase() as DisputeStatus,
- },
- })
- }
-
- const newDisputeStatus =
- participant.role === 'ROLE_A' ? ('WAITING_OPPONENT' as const) : ('BOTH_SUBMITTED' as const)
-
- const [updatedStatement, updatedDispute] = await prisma.$transaction([
- prisma.disputeStatement.update({
- where: { id: statement.id },
- data: { submittedAt: new Date() },
- }),
- prisma.dispute.update({
- where: { id: disputeId },
- data: { status: newDisputeStatus },
- }),
- ])
+ const now = new Date()
+ const result = await prisma.$transaction(async (tx) => {
+ // 멱등성: 아직 제출되지 않은 경우에만 갱신
+ const updated = await tx.disputeStatement.updateMany({
+ where: { id: statement.id, submittedAt: null },
+ data: { submittedAt: now },
+ })
+
+ const currentStatement = await tx.disputeStatement.findUniqueOrThrow({
+ where: { id: statement.id },
+ select: { id: true, submittedAt: true },
+ })
+
+ // 중복 요청이면 현재 분쟁 상태 그대로 반환
+ if (updated.count === 0) {
+ const currentDispute = await tx.dispute.findUniqueOrThrow({
+ where: { id: disputeId },
+ select: { status: true },
+ })
+ return { statement: currentStatement, dispute: currentDispute }
+ }
+
+ // 실제 제출 수 기준으로 상태 계산
+ const submittedCount = await tx.disputeStatement.count({
+ where: { disputeId, submittedAt: { not: null } },
+ })
+ const nextStatus = submittedCount >= 2 ? 'BOTH_SUBMITTED' : 'WAITING_OPPONENT'
+
+ const currentDispute = await tx.dispute.update({
+ where: { id: disputeId },
+ data: { status: nextStatus },
+ select: { status: true },
+ })
+ return { statement: currentStatement, dispute: currentDispute }
+ })
@@
- id: updatedStatement.id,
- submittedAt: updatedStatement.submittedAt!.toISOString(),
- disputeStatus: updatedDispute.status.toLowerCase() as DisputeStatus,
+ id: result.statement.id,
+ submittedAt: result.statement.submittedAt!.toISOString(),
+ disputeStatus: result.dispute.status.toLowerCase() as DisputeStatus,
},
})As per coding guidelines, "AI judgment request, statement completion, invitation participation, and deletion/anonymization requests must implement idempotency to prevent duplicate processing." 🤖 Prompt for AI AgentsSource: Coding guidelines |
||
|
|
||
| return NextResponse.json<ApiResponse<StatementSubmitResponse>>({ | ||
| success: true, | ||
| data: { | ||
| id: updatedStatement.id, | ||
| submittedAt: updatedStatement.submittedAt!.toISOString(), | ||
| disputeStatus: updatedDispute.status.toLowerCase() as DisputeStatus, | ||
| }, | ||
| }) | ||
| } catch (error) { | ||
| const message = error instanceof Error ? error.message : String(error) | ||
| console.error('[disputes/statements/submit] api error', { message }) | ||
| return NextResponse.json<ApiResponse>( | ||
| { success: false, error: { code: 'INTERNAL_SERVER_ERROR', message: '서버 오류가 발생했습니다.' } }, | ||
| { status: 500 }, | ||
| ) | ||
| } | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,50 @@ | ||
| import { NextResponse } from 'next/server' | ||
| import { getServerSession } from 'next-auth' | ||
| import { authOptions } from '@/lib/auth' | ||
| import { prisma } from '@/lib/db' | ||
| import { getSessionUserId } from '@/lib/auth/session' | ||
| import type { ApiResponse } from '@/types/common' | ||
|
|
||
| interface UserMeDto { | ||
| id: string | ||
| nickname: string | null | ||
| mbti: string | null | ||
| } | ||
|
|
||
| export async function GET() { | ||
| const session = await getServerSession(authOptions) | ||
| const userId = getSessionUserId(session) | ||
|
|
||
| if (!userId) { | ||
| return NextResponse.json<ApiResponse>( | ||
| { success: false, error: { code: 'UNAUTHORIZED', message: '로그인이 필요합니다.' } }, | ||
| { status: 401 }, | ||
| ) | ||
| } | ||
|
|
||
| try { | ||
| const user = await prisma.user.findUnique({ | ||
| where: { id: userId }, | ||
| select: { id: true, nickname: true, mbti: true }, | ||
| }) | ||
|
|
||
| if (!user) { | ||
| return NextResponse.json<ApiResponse>( | ||
| { success: false, error: { code: 'USER_NOT_FOUND', message: '사용자를 찾을 수 없습니다.' } }, | ||
| { status: 404 }, | ||
| ) | ||
| } | ||
|
|
||
| return NextResponse.json<ApiResponse<UserMeDto>>({ | ||
| success: true, | ||
| data: { id: user.id, nickname: user.nickname, mbti: user.mbti }, | ||
| }) | ||
| } catch (error) { | ||
| const message = error instanceof Error ? error.message : String(error) | ||
| console.error('[users/me] api error', { message }) | ||
| return NextResponse.json<ApiResponse>( | ||
| { success: false, error: { code: 'INTERNAL_SERVER_ERROR', message: '서버 오류가 발생했습니다.' } }, | ||
| { status: 500 }, | ||
| ) | ||
| } | ||
| } |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,39 @@ | ||
| import type { ApiResponse } from '@/types/common' | ||
| import type { | ||
| DisputeDto, | ||
| DisputeStatementDto, | ||
| StatementSubmitResponse, | ||
| } from '@/types/dispute' | ||
|
|
||
| export async function fetchDispute(disputeId: string): Promise<DisputeDto> { | ||
| const res = await fetch(`/api/disputes/${disputeId}`) | ||
| const json: ApiResponse<DisputeDto> = await res.json() | ||
| if (!json.success || !json.data) throw new Error(json.error?.message ?? '사건 조회 실패') | ||
| return json.data | ||
|
coderabbitai[bot] marked this conversation as resolved.
Resolved
|
||
| } | ||
|
|
||
| export async function saveStatement(disputeId: string, content: string): Promise<DisputeStatementDto> { | ||
| const res = await fetch(`/api/disputes/${disputeId}/statements`, { | ||
| method: 'POST', | ||
| headers: { 'Content-Type': 'application/json' }, | ||
| body: JSON.stringify({ content }), | ||
| }) | ||
| const json: ApiResponse<DisputeStatementDto> = await res.json() | ||
| if (!json.success || !json.data) throw new Error(json.error?.message ?? '진술 저장 실패') | ||
| return json.data | ||
| } | ||
|
|
||
| export async function submitStatement(disputeId: string): Promise<StatementSubmitResponse> { | ||
| const res = await fetch(`/api/disputes/${disputeId}/statements/submit`, { | ||
| method: 'POST', | ||
| }) | ||
| const json: ApiResponse<StatementSubmitResponse> = await res.json() | ||
| if (!json.success || !json.data) throw new Error(json.error?.message ?? '진술 제출 실패') | ||
| return json.data | ||
| } | ||
|
|
||
| export async function requestJudgment(disputeId: string): Promise<void> { | ||
| const res = await fetch(`/api/disputes/${disputeId}/judge`, { method: 'POST' }) | ||
| const json: ApiResponse = await res.json() | ||
| if (!json.success) throw new Error(json.error?.message ?? 'AI 판결 요청 실패') | ||
| } | ||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
2인 판결에서 B측 진술 누락 검증이 빠져 있습니다.
Line 134-143은
statementA만 검증하고statementB는 검증하지 않습니다. 이 상태로generateAiJudgment에 넘기면 duo 사건이어도 단독 분기 처리될 수 있어 결과가 왜곡됩니다.예시 수정안
if (!statementA) { await prisma.dispute.update({ where: { id }, data: { status: previousStatus } }) statusSetToJudging = false return NextResponse.json<ApiResponse>( { success: false, error: { code: 'STATEMENT_NOT_FOUND', message: 'A측 진술을 찾을 수 없습니다.' } }, { status: 422 }, ) } + if (!isSolo && !statementB) { + await prisma.dispute.update({ where: { id }, data: { status: previousStatus } }) + statusSetToJudging = false + return NextResponse.json<ApiResponse>( + { success: false, error: { code: 'STATEMENT_NOT_FOUND', message: 'B측 진술을 찾을 수 없습니다.' } }, + { status: 422 }, + ) + }🤖 Prompt for AI Agents