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:
@@ -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 })
|
||||
}
|
||||
|
||||
@@ -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 } from '@/lib/db/with-user'
|
||||
import { writeAuditLog } from '@/lib/db/audit'
|
||||
import { incidents, sites, zones } from '@/lib/db/schema'
|
||||
import { eq, desc } from 'drizzle-orm'
|
||||
import { rowsToCsv } from '@/lib/csv'
|
||||
|
||||
export async function GET(request: NextRequest) {
|
||||
@@ -20,53 +23,53 @@ export async function GET(request: NextRequest) {
|
||||
return NextResponse.json({ error: 'Forbidden' }, { status: 403 })
|
||||
}
|
||||
|
||||
const supabase = await createClient()
|
||||
|
||||
const { data: incidents } = await supabase
|
||||
.from('incidents')
|
||||
.select(`
|
||||
reference_no, incident_type, status, severity, reported_at, closed_at,
|
||||
injury_involved, medical_status, lost_days,
|
||||
sites (name), zones (name)
|
||||
`)
|
||||
.order('reported_at', { ascending: false })
|
||||
const rows = await withUser(session.sub, async tx =>
|
||||
tx.select({
|
||||
referenceNo: incidents.referenceNo,
|
||||
incidentType: incidents.incidentType,
|
||||
status: incidents.status,
|
||||
severity: incidents.severity,
|
||||
reportedAt: incidents.reportedAt,
|
||||
closedAt: incidents.closedAt,
|
||||
injuryInvolved: incidents.injuryInvolved,
|
||||
medicalStatus: incidents.medicalStatus,
|
||||
lostDays: incidents.lostDays,
|
||||
siteName: sites.name,
|
||||
zoneName: zones.name,
|
||||
})
|
||||
.from(incidents)
|
||||
.leftJoin(sites, eq(incidents.siteId, sites.id))
|
||||
.leftJoin(zones, eq(incidents.zoneId, zones.id))
|
||||
.orderBy(desc(incidents.reportedAt))
|
||||
.limit(10000)
|
||||
|
||||
const rows = incidents ?? []
|
||||
)
|
||||
|
||||
const headers = [
|
||||
'Reference', 'Type', 'Status', 'Severity', 'Site', 'Zone',
|
||||
'Reported At', 'Closed At', 'Injury Involved', 'Medical Status', 'Lost Days',
|
||||
]
|
||||
|
||||
const csvRows = rows.map(inc => {
|
||||
const siteName = (inc.sites as unknown as { name: string } | null)?.name ?? ''
|
||||
const zoneName = (inc.zones as unknown as { name: string } | null)?.name ?? ''
|
||||
return [
|
||||
inc.reference_no ?? '',
|
||||
inc.incident_type,
|
||||
inc.status,
|
||||
String(inc.severity ?? ''),
|
||||
siteName,
|
||||
zoneName,
|
||||
inc.reported_at ? new Date(inc.reported_at as string).toISOString().split('T')[0] : '',
|
||||
inc.closed_at ? new Date(inc.closed_at as string).toISOString().split('T')[0] : '',
|
||||
inc.injury_involved ? 'Yes' : 'No',
|
||||
inc.medical_status ?? '',
|
||||
String(inc.lost_days ?? ''),
|
||||
]
|
||||
})
|
||||
const csvRows = rows.map(inc => [
|
||||
inc.referenceNo ?? '',
|
||||
inc.incidentType,
|
||||
inc.status,
|
||||
String(inc.severity ?? ''),
|
||||
inc.siteName ?? '',
|
||||
inc.zoneName ?? '',
|
||||
inc.reportedAt ? new Date(inc.reportedAt).toISOString().split('T')[0] : '',
|
||||
inc.closedAt ? new Date(inc.closedAt).toISOString().split('T')[0] : '',
|
||||
inc.injuryInvolved ? 'Yes' : 'No',
|
||||
inc.medicalStatus ?? '',
|
||||
String(inc.lostDays ?? ''),
|
||||
])
|
||||
|
||||
const csv = rowsToCsv(headers, csvRows)
|
||||
const safeRole = role.replace(/[^a-z0-9]/gi, '')
|
||||
const filename = `incidents-${safeRole}-${new Date().toISOString().split('T')[0]}.csv`
|
||||
|
||||
await supabase.rpc('write_audit_log', {
|
||||
p_table_name: 'incidents',
|
||||
p_record_id: session.sub,
|
||||
p_action: 'export_csv',
|
||||
p_new_value: { role, row_count: rows.length } as never,
|
||||
})
|
||||
await withUser(session.sub, async tx =>
|
||||
writeAuditLog(tx, 'incidents', session.sub, 'export_csv', { role, row_count: rows.length })
|
||||
)
|
||||
|
||||
return new NextResponse(csv, {
|
||||
status: 200,
|
||||
|
||||
@@ -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 }))
|
||||
|
||||
Reference in New Issue
Block a user