feat(db): phase 4 group 5 — dashboard/reports/settings/notifications/users routes to Drizzle

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
2026-07-23 17:13:51 +08:00
co-authored by Claude Sonnet 4.6
parent 853675118d
commit c2db693d9f
7 changed files with 273 additions and 151 deletions
+38 -29
View File
@@ -1,8 +1,11 @@
export const dynamic = 'force-dynamic'
import { 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 { incidents, sites, zones, auditLog } from '@/lib/db/schema'
import { eq, and, gte, desc } from 'drizzle-orm'
import { createDeepSeekClient } from '@/lib/claude/client'
import { getApiKey } from '@/lib/settings'
@@ -24,27 +27,33 @@ export async function POST() {
if (!['hse', 'admin', 'management'].includes(session.role))
return NextResponse.json({ error: 'Forbidden' }, { status: 403 })
const supabase = await createClient()
const now = new Date()
const ninetyDaysAgo = new Date(now)
ninetyDaysAgo.setDate(now.getDate() - 90)
const midpoint = new Date(now)
midpoint.setDate(now.getDate() - 45)
const { data: incidents } = await supabase
.from('incidents')
.select('incident_type, severity, reported_at, zones (name), sites (name)')
.gte('reported_at', ninetyDaysAgo.toISOString())
const rows = await withUser(session.sub, async tx =>
tx.select({
incidentType: incidents.incidentType,
severity: incidents.severity,
reportedAt: incidents.reportedAt,
zoneName: zones.name,
siteName: sites.name,
})
.from(incidents)
.leftJoin(zones, eq(incidents.zoneId, zones.id))
.leftJoin(sites, eq(incidents.siteId, sites.id))
.where(gte(incidents.reportedAt, ninetyDaysAgo))
)
const rows = incidents ?? []
if (rows.length === 0)
return NextResponse.json({ flags: [], summary: 'No incidents in the last 90 days.' })
const zoneMap = new Map<string, ZoneAggregate & { severitySum: number; severityCount: number }>()
for (const r of rows) {
const zone = (r.zones as unknown as { name: string } | null)?.name ?? 'Unknown zone'
const site = (r.sites as unknown as { name: string } | null)?.name ?? 'Unknown site'
const zone = r.zoneName ?? 'Unknown zone'
const site = r.siteName ?? 'Unknown site'
const key = `${site}|${zone}`
let agg = zoneMap.get(key)
if (!agg) {
@@ -55,14 +64,14 @@ export async function POST() {
zoneMap.set(key, agg)
}
agg.total++
if (r.incident_type === 'near_miss') agg.near_miss++
if (r.incident_type === 'hazard') agg.hazard++
if (r.incident_type === 'injury') agg.injury++
if (r.incidentType === 'near_miss') agg.near_miss++
if (r.incidentType === 'hazard') agg.hazard++
if (r.incidentType === 'injury') agg.injury++
if (typeof r.severity === 'number') {
agg.severitySum += r.severity
agg.severityCount++
}
if (new Date(r.reported_at as string) < midpoint) agg.first_half++
if (r.reportedAt && new Date(r.reportedAt) < midpoint) agg.first_half++
else agg.second_half++
}
@@ -79,16 +88,18 @@ export async function POST() {
}))
// Rate limit: 1 AI call per 60s per user (checked via audit_log)
const { data: lastCall } = await supabase
.from('audit_log')
.select('changed_at')
.eq('changed_by', session.sub)
.eq('action', 'ai_risk_flags')
.order('changed_at', { ascending: false })
.limit(1)
.single()
const [lastCall] = await asAdmin(db =>
db.select({ changedAt: auditLog.changedAt })
.from(auditLog)
.where(and(
eq(auditLog.changedBy, session.sub),
eq(auditLog.action, 'ai_risk_flags'),
))
.orderBy(desc(auditLog.changedAt))
.limit(1)
)
if (lastCall && Date.now() - new Date(lastCall.changed_at).getTime() < 60_000) {
if (lastCall && Date.now() - new Date(lastCall.changedAt!).getTime() < 60_000) {
return NextResponse.json({ error: 'Rate limit: wait 60 seconds between AI requests' }, { status: 429 })
}
@@ -164,12 +175,10 @@ ${JSON.stringify(aggregates, null, 2)}
typeof (f as Record<string, unknown>).recommended_action === 'string',
)
await supabase.rpc('write_audit_log', {
p_table_name: 'incidents',
p_record_id: session.sub,
p_action: 'ai_risk_flags',
p_new_value: { flags, summary: input.summary, model: 'deepseek-chat' } as never,
})
await withUser(session.sub, async tx =>
writeAuditLog(tx, 'incidents', session.sub, 'ai_risk_flags',
{ flags, summary: input.summary, model: 'deepseek-chat' })
)
return NextResponse.json({ flags, summary: input.summary })
}