Skip to content
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1,054 changes: 473 additions & 581 deletions prisma/schema.prisma

Large diffs are not rendered by default.

6 changes: 4 additions & 2 deletions prisma/seed.ts
Original file line number Diff line number Diff line change
Expand Up @@ -305,8 +305,10 @@ async function main() {
verdictScoreB: 55,
moreResponsibleRole: "ROLE_B",
issueSummary: "연락 빈도 차이",
reasoning: "상호 소통 부족",
advice: "기대치를 공유하세요",
aFault: "연락 빈도에 대한 기대치를 먼저 공유하지 않은 점",
bFault: "상대방의 소통 요구를 충분히 수용하지 않은 점",
aSuggestedLine: "앞으로 서로 기대하는 연락 주기를 함께 정해보면 어떨까요?",
bSuggestedLine: "내가 바빴더라도 짧게라도 먼저 연락할게요.",
resultConflictGroupId: groups[0].id,
resultConflictDetailId: details[0].id,
resultCardId: card.id,
Expand Down
34 changes: 13 additions & 21 deletions src/app/(page)/disputes/[id]/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,8 @@ import Tabs from '@/components/ui/Tabs'
import Spinner from '@/components/ui/Spinner'
import StatusBadge from '@/components/ui/StatusBadge'
import CategoryIcon from '@/components/ui/CategoryIcon'
import type { DisputeDto } from '@/types/dispute'
import { useDispute, useRequestJudgment } from '@/domains/dispute/dispute.hooks'
import { useToastStore } from '@/stores/toastStore'
import styles from './DisputePage.module.scss'

const COMPLETED_STATUSES = ['judged', 'closed'] as const
Expand All @@ -28,34 +29,25 @@ export default function DisputePage({ params }: { params: Promise<{ id: string }
const { id } = React.use(params)
const router = useRouter()

const [dispute, setDispute] = React.useState<DisputeDto | null>(null)
const [fetchLoading, setFetchLoading] = React.useState(true)
const { data: dispute, isLoading: fetchLoading } = useDispute(id)
const { mutate: requestJudgment, isPending: isJudging } = useRequestJudgment(id)
const showToast = useToastStore((s) => s.show)

const [activeTab, setActiveTab] = React.useState('statement')
const [showSoloModal, setShowSoloModal] = React.useState(false)
const [isJudging, setIsJudging] = React.useState(false)

React.useEffect(() => {
fetch(`/api/disputes/${id}`)
.then((r) => r.json())
.then((json) => { if (json.success) setDispute(json.data) })
.finally(() => setFetchLoading(false))
}, [id])

const isCompleted = dispute !== null && (COMPLETED_STATUSES as readonly string[]).includes(dispute.status)
const isCompleted = dispute !== undefined && (COMPLETED_STATUSES as readonly string[]).includes(dispute.status)
const canJudge = dispute?.status === 'waiting_opponent' || dispute?.status === 'both_submitted'
const isSolo = dispute !== null && dispute.participants.length === 1
const isSolo = dispute !== undefined && dispute.participants.length === 1
const roleAStatement = dispute?.statements?.find((s) => s.role === 'role_a')
const roleBStatement = dispute?.statements?.find((s) => s.role === 'role_b')

const runJudge = async () => {
const runJudge = () => {
setShowSoloModal(false)
setIsJudging(true)
try {
await fetch(`/api/disputes/${id}/judge`, { method: 'POST' })
router.refresh()
} catch {
setIsJudging(false)
}
requestJudgment(undefined, {
onError: (error) => showToast(error instanceof Error ? error.message : 'AI 판결 요청에 실패했습니다.'),
onSuccess: () => router.refresh(),
})
}

if (fetchLoading) return null
Expand Down
110 changes: 67 additions & 43 deletions src/app/api/disputes/[id]/judge/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,11 @@ import type { DisputeStatus } from '@prisma/client'
import { authOptions } from '@/lib/auth'
import { prisma } from '@/lib/db'
import { getSessionUserId } from '@/lib/auth/session'
import { generateAiJudgment } from '@/lib/ai/judgment'
import { toAiJudgmentDto } from '@/domains/judgement/judgment.mapper'
import type { ApiResponse } from '@/types/common'
import type { AiJudgmentDto } from '@/types/judgment'

// TODO: src/lib/ai 구현 후 import 추가
// import { generateAiJudgment } from '@/lib/ai/judgment'

// POST /api/disputes/:id/judge
// AI 판결 요청. both_submitted 상태일 때만 가능. 중복 요청 방지 (멱등성)
export async function POST(
Expand Down Expand Up @@ -128,49 +126,75 @@ export async function POST(
statusSetToJudging = true

try {
// DB에서 갈등 유형 마스터 데이터 조회 (AI 프롬프트에 전달)
const conflictTypeDetails = await prisma.conflictTypeDetail.findMany({
select: { id: true, detailCode: true, displayName: true, groupId: true },
})

const statementA = dispute.statements.find((s) => s.role === 'ROLE_A' && s.submittedAt)?.content
const statementB = dispute.statements.find((s) => s.role === 'ROLE_B' && s.submittedAt)?.content

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 },
)
Comment on lines +133 to +142

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

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
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/app/api/disputes/`[id]/judge/route.ts around lines 134 - 143, The code
validates that statementA exists but does not validate that statementB exists,
which can cause duo dispute cases to be incorrectly processed as solo cases when
passed to generateAiJudgment. After the existing check for missing statementA,
add a similar validation check for statementB to ensure both statements are
present before proceeding. When statementB is missing, update the dispute status
back to the previousStatus, set statusSetToJudging to false, and return an error
response with an appropriate error code and message for the B-side statement not
found condition.

}

// AI 판결 생성
// TODO: src/lib/ai/judgment.ts 구현 후 아래 로직으로 교체
//
// const aiResult = await generateAiJudgment({
// disputeId: id,
// categoryGroup: dispute.categoryGroup,
// statements: dispute.statements.map((s) => ({
// role: s.role,
// content: s.content,
// })),
// })
//
// const judgment = await prisma.$transaction(async (tx) => {
// const resultCard = await tx.judgmentResultCard.create({ data: { ... } })
// const created = await tx.aiJudgment.create({
// data: {
// disputeId: id,
// ...aiResult,
// resultCardId: resultCard.id,
// },
// })
// await tx.dispute.update({ where: { id }, data: { status: 'JUDGED' } })
// return tx.aiJudgment.findUniqueOrThrow({
// where: { id: created.id },
// include: { resultConflictGroup: true, resultConflictDetail: true, resultCard: true, aiNotice: true },
// })
// })
//
// return NextResponse.json<ApiResponse<AiJudgmentDto>>({ success: true, data: toAiJudgmentDto(judgment) })

// AI 모듈 미구현 — 상태 원복 후 503 반환
await prisma.dispute.update({
where: { id },
data: { status: previousStatus },
const aiResult = await generateAiJudgment({
categoryGroup: dispute.categoryGroup,
statementA,
statementB,
conflictTypes: conflictTypeDetails.map((d) => ({ code: d.detailCode, name: d.displayName })),
})

// AI가 반환한 code로 ConflictTypeDetail 매핑
const matchedDetail = conflictTypeDetails.find((d) => d.detailCode === aiResult.conflictTypeCode)
if (!matchedDetail) {
throw new Error(`JSON: unknown conflictTypeCode ${aiResult.conflictTypeCode}`)
}

const judgment = await prisma.$transaction(async (tx) => {
const resultCard = await tx.judgmentResultCard.create({
data: {
cardTitle: aiResult.summary.slice(0, 50),
cardSummary: aiResult.summary,
imageStatus: 'PENDING',
shareEnabled: false,
},
})

const created = await tx.aiJudgment.create({
data: {
disputeId: id,
verdictScoreA: aiResult.scoreA,
verdictScoreB: aiResult.scoreB,
moreResponsibleRole: aiResult.moreResponsibleRole ?? undefined,
issueSummary: aiResult.summary,
aFault: aiResult.aFault,
bFault: aiResult.bFault,
aSuggestedLine: aiResult.aSuggestedLine,
bSuggestedLine: aiResult.bSuggestedLine,
resultConflictDetailId: matchedDetail.id,
resultConflictGroupId: matchedDetail.groupId,
resultCardId: resultCard.id,
modelName: aiResult.modelName,
},
})

await tx.dispute.update({ where: { id }, data: { status: 'JUDGED' } })

return tx.aiJudgment.findUniqueOrThrow({
where: { id: created.id },
include: { resultConflictGroup: true, resultConflictDetail: true, resultCard: true, aiNotice: true },
})
})

statusSetToJudging = false
return NextResponse.json<ApiResponse>(
{
success: false,
error: { code: 'AI_NOT_IMPLEMENTED', message: 'AI 판결 모듈이 아직 준비되지 않았습니다.' },
},
{ status: 503 },
)
return NextResponse.json<ApiResponse<AiJudgmentDto>>({ success: true, data: toAiJudgmentDto(judgment) })
} catch (aiError) {
// AI 요청 실패 시 상태 원복
await prisma.dispute
Expand Down
92 changes: 92 additions & 0 deletions src/app/api/disputes/[id]/statements/submit/route.ts
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 },
})
Comment thread
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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major | 🏗️ Heavy lift

멱등성과 상태 전이를 같은 트랜잭션에서 실제 제출 수 기준으로 계산해야 합니다.

Line 50의 선조회(statement.submittedAt)는 동시 요청에서 TOCTOU가 발생하고, Line 62-64의 role 기반 상태 결정은 실제 양측 제출 여부와 불일치할 수 있습니다. 결과적으로 both_submitted가 조기 기록되어 후속 판결 흐름에서 불일치 상태를 만들 수 있습니다.

수정 제안 (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 Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/app/api/disputes/`[id]/statements/submit/route.ts around lines 49 - 74,
The idempotency check on statement.submittedAt at line 50 occurs outside the
transaction, creating a race condition with concurrent requests. Additionally,
the newDisputeStatus determination at lines 62-64 uses only participant.role to
decide between WAITING_OPPONENT and BOTH_SUBMITTED, but this should instead be
based on the actual count of submitted statements in the database. Move the
idempotency logic inside the transaction and replace the role-based status
assignment with logic that counts how many dispute statements have been
submitted (submittedAt is not null) for the given disputeId, setting the status
to BOTH_SUBMITTED only when both participants have actually submitted their
statements. This ensures the state transition reflects actual submission counts
rather than role assumptions.

Source: 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 },
)
}
}
50 changes: 50 additions & 0 deletions src/app/api/users/me/route.ts
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 },
)
}
}
2 changes: 2 additions & 0 deletions src/app/layout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import type { Metadata } from 'next';
import localFont from 'next/font/local';
import AuthProvider from '@/components/providers/AuthProvider';
import QueryProvider from '@/components/providers/QueryProvider';
import Toast from '@/components/feedback/Toast';
import './globals.scss';

const pretendard = localFont({
Expand All @@ -27,6 +28,7 @@ export default function RootLayout({
<AuthProvider>
<QueryProvider>
<main className="container">{children}</main>
<Toast />
</QueryProvider>
</AuthProvider>
</body>
Expand Down
39 changes: 39 additions & 0 deletions src/domains/dispute/dispute.api.ts
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
Comment thread
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 판결 요청 실패')
}
Loading