import { and, asc, desc, eq, ilike, inArray, or, sql, aliasedTable } from 'drizzle-orm' import { asAdmin } from '@/lib/db/with-user' import { incidents, sites, trucks, users, zones } from '@/lib/db/schema' import { OPEN_STATUSES, PAGE_SIZE, type ListParams } from './list-params' import type { Incident, SiteOption, TruckOption } from './types' export interface IncidentListData { incidents: Incident[] total: number counts: { all: number; open: number; closed: number } sites: SiteOption[] trucks: TruckOption[] } export async function loadIncidentList(p: ListParams): Promise { const reporter = aliasedTable(users, 'reporter') const base = [] if (p.q) base.push(or(ilike(incidents.referenceNo, `%${p.q}%`), ilike(incidents.description, `%${p.q}%`))) if (p.type) base.push(eq(incidents.incidentType, p.type as never)) if (p.siteId) base.push(eq(incidents.siteId, p.siteId)) if (p.truckId) base.push(eq(incidents.truckId, p.truckId)) const scoped = [...base] if (p.status) scoped.push(eq(incidents.status, p.status as never)) if (p.view === 'open') scoped.push(inArray(incidents.status, [...OPEN_STATUSES] as never)) if (p.view === 'closed') scoped.push(eq(incidents.status, 'closed' as never)) const where = scoped.length ? and(...scoped) : undefined const baseWhere = base.length ? and(...base) : undefined const sortColumn = { reported_at: incidents.reportedAt, reference_no: incidents.referenceNo, status: incidents.status }[p.sort] const orderBy = p.dir === 'asc' ? asc(sortColumn) : desc(sortColumn) const [[countRow], rows, statusCounts, siteRows, truckRows] = await Promise.all([ asAdmin(db => db.select({ count: sql`count(*)` }).from(incidents).where(where)), asAdmin(db => db.select({ id: incidents.id, referenceNo: incidents.referenceNo, incidentType: incidents.incidentType, status: incidents.status, severity: incidents.severity, reportedAt: incidents.reportedAt, siteName: sites.name, zoneName: zones.name, reporterName: reporter.name, truckNo: trucks.truckNo, }) .from(incidents) .leftJoin(sites, eq(incidents.siteId, sites.id)) .leftJoin(zones, eq(incidents.zoneId, zones.id)) .leftJoin(reporter, eq(incidents.reportedBy, reporter.id)) .leftJoin(trucks, eq(incidents.truckId, trucks.id)) .where(where) .orderBy(orderBy) .limit(PAGE_SIZE) .offset((p.page - 1) * PAGE_SIZE) ), asAdmin(db => db.select({ status: incidents.status, count: sql`count(*)` }) .from(incidents) .where(baseWhere) .groupBy(incidents.status) ), asAdmin(db => db.select({ id: sites.id, name: sites.name }).from(sites).orderBy(asc(sites.name))), asAdmin(db => db.select({ id: trucks.id, truckNo: trucks.truckNo }) .from(trucks) .where(eq(trucks.active, true)) .orderBy(asc(trucks.truckNo)) ), ]) const byStatus = new Map(statusCounts.map(r => [r.status as string, Number(r.count)])) const all = [...byStatus.values()].reduce((a, b) => a + b, 0) const open = OPEN_STATUSES.reduce((sum, s) => sum + (byStatus.get(s) ?? 0), 0) return { incidents: rows.map(r => ({ id: r.id, reference_no: r.referenceNo, incident_type: r.incidentType, status: r.status, severity: r.severity, reported_at: r.reportedAt.toISOString(), sites: r.siteName ? { name: r.siteName } : null, zones: r.zoneName ? { name: r.zoneName } : null, trucks: r.truckNo ? { truck_no: r.truckNo } : null, reporter: r.reporterName ? { name: r.reporterName } : null, })), total: Number(countRow?.count ?? 0), counts: { all, open, closed: byStatus.get('closed') ?? 0 }, sites: siteRows.map(s => ({ id: s.id, name: s.name })), trucks: truckRows.map(t => ({ id: t.id, truck_no: t.truckNo })), } }