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:
@@ -1,8 +1,10 @@
|
||||
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 { incidents } from '@/lib/db/schema'
|
||||
import { eq, sql } from 'drizzle-orm'
|
||||
import { embedText } from '@/lib/claude/embed'
|
||||
import { getApiKey } from '@/lib/settings'
|
||||
|
||||
@@ -16,42 +18,39 @@ export async function GET(
|
||||
if (!['hse', 'admin'].includes(session.role))
|
||||
return NextResponse.json({ error: 'Forbidden' }, { status: 403 })
|
||||
|
||||
const supabase = await createClient()
|
||||
|
||||
const googleAiKey = await getApiKey('GOOGLE_AI_API_KEY')
|
||||
|
||||
const { data: incident } = await supabase
|
||||
.from('incidents')
|
||||
.select('id, description, embedding, status')
|
||||
.eq('id', id)
|
||||
.single()
|
||||
if (!incident) return NextResponse.json({ error: 'Not found' }, { status: 404 })
|
||||
|
||||
const inc = incident as { id: string; description: string; embedding: string | null; status: string }
|
||||
const [incidentRow] = await withUser(session.sub, async tx =>
|
||||
tx.select({ id: incidents.id, description: incidents.description, embedding: incidents.embedding, status: incidents.status })
|
||||
.from(incidents).where(eq(incidents.id, id)).limit(1)
|
||||
)
|
||||
if (!incidentRow) return NextResponse.json({ error: 'Not found' }, { status: 404 })
|
||||
|
||||
let embeddingVec: number[]
|
||||
try {
|
||||
if (inc.embedding) {
|
||||
embeddingVec = JSON.parse(inc.embedding) as number[]
|
||||
} else {
|
||||
embeddingVec = await embedText(inc.description, googleAiKey)
|
||||
// Closed incidents are locked at the DB level — the trigger would reject
|
||||
// this backfill. The vector still serves the similarity query below.
|
||||
if (inc.status !== 'closed') {
|
||||
const { error: persistError } = await supabase.from('incidents').update({
|
||||
embedding: `[${embeddingVec.join(',')}]` as unknown as string,
|
||||
}).eq('id', id)
|
||||
if (persistError) console.error('embedding backfill error:', persistError)
|
||||
if (incidentRow.embedding) {
|
||||
// pg driver may return the vector as a string — parse if needed
|
||||
const raw = incidentRow.embedding
|
||||
embeddingVec = typeof raw === 'string' ? (JSON.parse(raw) as number[]) : (raw as number[])
|
||||
} else {
|
||||
try {
|
||||
embeddingVec = await embedText(incidentRow.description, googleAiKey)
|
||||
if (incidentRow.status !== 'closed') {
|
||||
const embStr = `[${embeddingVec.join(',')}]`
|
||||
await asAdmin(db =>
|
||||
db.execute(sql`UPDATE incidents SET embedding = ${embStr}::vector(768) WHERE id = ${id}::uuid`)
|
||||
)
|
||||
}
|
||||
} catch {
|
||||
return NextResponse.json({ error: 'Embedding service unavailable' }, { status: 503 })
|
||||
}
|
||||
} catch {
|
||||
return NextResponse.json({ error: 'Embedding service unavailable' }, { status: 503 })
|
||||
}
|
||||
|
||||
const { data: similar } = await supabase.rpc('match_incidents', {
|
||||
query_embedding: `[${embeddingVec.join(',')}]`,
|
||||
exclude_id: id,
|
||||
match_count: 5,
|
||||
const embStr = `[${embeddingVec.join(',')}]`
|
||||
const similar = await withUser(session.sub, async tx => {
|
||||
const result = await tx.execute(
|
||||
sql`SELECT * FROM match_incidents(${embStr}::vector(768), ${id}::uuid, ${5})`
|
||||
)
|
||||
return result.rows
|
||||
})
|
||||
|
||||
return NextResponse.json(similar ?? [])
|
||||
|
||||
Reference in New Issue
Block a user