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>
58 lines
2.1 KiB
TypeScript
58 lines
2.1 KiB
TypeScript
export const dynamic = 'force-dynamic'
|
|
|
|
import { NextRequest, NextResponse } from 'next/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'
|
|
|
|
export async function GET(
|
|
_request: NextRequest,
|
|
{ params }: { params: Promise<{ id: string }> }
|
|
) {
|
|
const { id } = await params
|
|
const session = await getSession()
|
|
if (!session) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
|
if (!['hse', 'admin'].includes(session.role))
|
|
return NextResponse.json({ error: 'Forbidden' }, { status: 403 })
|
|
|
|
const googleAiKey = await getApiKey('GOOGLE_AI_API_KEY')
|
|
|
|
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[]
|
|
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 })
|
|
}
|
|
}
|
|
|
|
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 ?? [])
|
|
}
|