feat(db): phase 4 group 3 — incident routes to Drizzle

Convert all 11 incident API routes from Supabase PostgREST to Drizzle
ORM with withUser/asAdmin/writeAuditLog patterns and RLS enforcement.
Only uploadEvidenceFile retains supabase client (Phase 5 storage work).

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
2026-07-23 16:57:01 +08:00
co-authored by Claude Sonnet 4.6
parent d234ebf916
commit 98f5c4e421
11 changed files with 482 additions and 431 deletions
+20 -16
View File
@@ -1,8 +1,11 @@
export const dynamic = 'force-dynamic'
import { NextRequest, NextResponse } from 'next/server'
import { createClient } from '@/lib/supabase/server'
import { getSession } from '@/lib/auth/get-session'
import { withUser, asAdmin } from '@/lib/db/with-user'
import { writeAuditLog } from '@/lib/db/audit'
import { auditLog } from '@/lib/db/schema'
import { eq, and, gte, sql } from 'drizzle-orm'
import { createDeepSeekClient } from '@/lib/claude/client'
import { getApiKey } from '@/lib/settings'
@@ -10,16 +13,17 @@ export async function POST(request: NextRequest) {
const session = await getSession()
if (!session) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
const supabase = await createClient()
const since = new Date(Date.now() - 60_000).toISOString()
const { count: recentCount } = await supabase
.from('audit_log')
.select('id', { count: 'exact', head: true })
.eq('changed_by', session.sub)
.eq('action', 'ai_quality_check')
.gte('changed_at', since)
if ((recentCount ?? 0) > 0)
// Rate limit
const since = new Date(Date.now() - 60_000)
const [rateRow] = await asAdmin(db =>
db.select({ cnt: sql<number>`count(*)` }).from(auditLog)
.where(and(
eq(auditLog.changedBy, session.sub),
eq(auditLog.action, 'ai_quality_check'),
gte(auditLog.changedAt, since),
))
)
if (Number(rateRow?.cnt ?? 0) > 0)
return NextResponse.json({ error: 'Rate limited — please wait 60 seconds' }, { status: 429 })
const deepseekKey = await getApiKey('DEEPSEEK_API_KEY')
@@ -92,11 +96,11 @@ Score 110 based on: specificity (location, time, persons involved), completen
return NextResponse.json({ error: 'AI returned unexpected structure' }, { status: 500 })
}
await supabase.rpc('write_audit_log', {
p_table_name: 'incidents',
p_record_id: session.sub,
p_action: 'ai_quality_check',
p_new_value: { score: input.score, passes: input.passes, model: 'deepseek-chat' } as never,
// audit write uses session.sub as a pseudo record-id (no incident_id at this stage)
await withUser(session.sub, async tx => {
await writeAuditLog(tx, 'incidents', session.sub, 'ai_quality_check', {
score: input.score, passes: input.passes, model: 'deepseek-chat',
})
})
return NextResponse.json(input)