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
+15 -11
View File
@@ -1,8 +1,10 @@
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 } from '@/lib/db/with-user'
import { incidents, sites } from '@/lib/db/schema'
import { eq } from 'drizzle-orm'
export async function GET() {
const session = await getSession()
@@ -10,28 +12,30 @@ export async function GET() {
if (!['hse', 'admin', 'management'].includes(session.role))
return NextResponse.json({ error: 'Forbidden' }, { status: 403 })
const supabase = await createClient()
const { data: incidents, error } = await supabase
.from('incidents')
.select('id, status, incident_type, sites (name)')
const rows = await withUser(session.sub, async tx =>
tx.select({
id: incidents.id,
status: incidents.status,
incidentType: incidents.incidentType,
siteName: sites.name,
})
.from(incidents)
.leftJoin(sites, eq(incidents.siteId, sites.id))
.limit(10000)
)
if (error) return NextResponse.json({ error: 'Failed to fetch stats' }, { status: 500 })
const rows = incidents ?? []
const total = rows.length
const closed = rows.filter(r => r.status === 'closed').length
const open = total - closed
const by_type: Record<string, number> = {}
for (const r of rows) {
by_type[r.incident_type] = (by_type[r.incident_type] ?? 0) + 1
by_type[r.incidentType] = (by_type[r.incidentType] ?? 0) + 1
}
const siteMap: Record<string, number> = {}
for (const r of rows) {
const name = (r.sites as unknown as { name: string } | null)?.name ?? 'Unknown'
const name = r.siteName ?? 'Unknown'
siteMap[name] = (siteMap[name] ?? 0) + 1
}
const by_site = Object.entries(siteMap).map(([name, count]) => ({ name, count }))