feat(kiosk): implement kiosk report submission functionality with offline support test(outbox): add tests for outbox functionality including report submission and error handling feat(outbox): create outbox management for queued reports with IndexedDB persistence feat(uuid): add UUID generation utility for client IDs feat(qr): implement QR code generation for reporting links by site and area feat(kiosk): create Kiosk page for reporting incidents without an account
292 lines
14 KiB
TypeScript
292 lines
14 KiB
TypeScript
import { and, asc, count, desc, eq, ilike, or, type SQL } from 'drizzle-orm'
|
|
import { Hono } from 'hono'
|
|
import { bodyLimit } from 'hono/body-limit'
|
|
import { z } from 'zod'
|
|
import type { Comment, TimelineEntry } from '../../shared/api-types.ts'
|
|
import { hasRole } from '../../shared/enums.ts'
|
|
import {
|
|
commentSchema,
|
|
createActionSchema,
|
|
createIncidentSchema,
|
|
incidentListQuery,
|
|
investigationSchema,
|
|
rootCauseSchema,
|
|
transitionSchema,
|
|
updateIncidentSchema,
|
|
type IncidentListQuery,
|
|
} from '../../shared/schemas.ts'
|
|
import { transitionBlocker, transitions } from '../../shared/workflow.ts'
|
|
import { requireAuth, requireRole } from '../auth/middleware.ts'
|
|
import type { SessionUser } from '../auth/sessions.ts'
|
|
import type { Db } from '../db/client.ts'
|
|
import { auditLog, comments, correctiveActions, incidents, investigations, rootCauses, users } from '../db/schema.ts'
|
|
import { diff } from '../lib/audit.ts'
|
|
import { toCsv } from '../lib/csv.ts'
|
|
import { saveAttachment } from '../lib/attachments.ts'
|
|
import { iso } from '../lib/dates.ts'
|
|
import { currentUser, fail, validate, type AppEnv } from '../lib/http.ts'
|
|
import { assertActiveUser, auditIncident, findIncident, loadDetail, selectIncidents, toAttachment, toIncident, visibleTo } from '../lib/incidents.ts'
|
|
import { assertLocation, fileReport, parseOccurredAt } from '../lib/reporting.ts'
|
|
|
|
const numberParam = z.object({ number: z.coerce.number().int().positive() })
|
|
|
|
const EXPORT_LIMIT = 10_000
|
|
|
|
const escapeLike = (value: string) => value.replace(/[\\%_]/g, '\\$&')
|
|
|
|
function listFilter(db: Db, user: SessionUser, { q, type, severity, status, siteId }: Omit<IncidentListQuery, 'page' | 'pageSize'>) {
|
|
let search: SQL | undefined
|
|
if (q) {
|
|
const pattern = `%${escapeLike(q)}%`
|
|
const number = /^(?:inc-?)?(\d+)$/i.exec(q)?.[1]
|
|
search = or(
|
|
ilike(incidents.title, pattern),
|
|
ilike(incidents.description, pattern),
|
|
ilike(incidents.locationDetail, pattern),
|
|
number ? eq(incidents.number, Number(number)) : undefined,
|
|
)
|
|
}
|
|
return and(
|
|
visibleTo(db, user),
|
|
search,
|
|
type ? eq(incidents.type, type) : undefined,
|
|
severity ? eq(incidents.severity, severity) : undefined,
|
|
status ? eq(incidents.status, status) : undefined,
|
|
siteId ? eq(incidents.siteId, siteId) : undefined,
|
|
)
|
|
}
|
|
|
|
/** Creates the incident's investigation if it doesn't exist yet and returns its id. */
|
|
async function ensureInvestigation(db: Db, incidentId: string): Promise<string> {
|
|
await db.insert(investigations).values({ incidentId }).onConflictDoNothing({ target: investigations.incidentId })
|
|
const [row] = await db.select({ id: investigations.id }).from(investigations).where(eq(investigations.incidentId, incidentId))
|
|
return row.id
|
|
}
|
|
|
|
export const incidentRoutes = new Hono<AppEnv>()
|
|
.get('/', requireAuth, validate('query', incidentListQuery), async (c) => {
|
|
const me = currentUser(c)
|
|
const { page, pageSize, ...filters } = c.req.valid('query')
|
|
const db = c.get('db')
|
|
const where = listFilter(db, me, filters)
|
|
const [{ total }] = await db.select({ total: count() }).from(incidents).where(where)
|
|
const rows = await selectIncidents(db)
|
|
.where(where)
|
|
.orderBy(desc(incidents.occurredAt), desc(incidents.number))
|
|
.limit(pageSize)
|
|
.offset((page - 1) * pageSize)
|
|
return c.json({ items: rows.map(toIncident), page, pageSize, total })
|
|
})
|
|
|
|
.get('/export', requireAuth, validate('query', incidentListQuery.omit({ page: true, pageSize: true })), async (c) => {
|
|
const me = currentUser(c)
|
|
const db = c.get('db')
|
|
const rows = await selectIncidents(db)
|
|
.where(listFilter(db, me, c.req.valid('query')))
|
|
.orderBy(desc(incidents.occurredAt), desc(incidents.number))
|
|
.limit(EXPORT_LIMIT)
|
|
const csv = toCsv(
|
|
['Reference', 'Title', 'Type', 'Severity', 'Status', 'Occurred at', 'Reported at', 'Closed at', 'Site', 'Area', 'Location detail', 'Reporter', 'Description', 'Immediate action'],
|
|
rows.map(toIncident).map((i) => [
|
|
i.reference,
|
|
i.title,
|
|
i.type,
|
|
i.severity,
|
|
i.status,
|
|
i.occurredAt,
|
|
i.reportedAt,
|
|
i.closedAt,
|
|
i.site.name,
|
|
i.area?.name,
|
|
i.locationDetail,
|
|
i.anonymous ? 'Anonymous' : (i.reporter?.name ?? i.reporterName ?? (i.kiosk ? `Reporting link: ${i.kiosk.name}` : null)),
|
|
i.description,
|
|
i.immediateAction,
|
|
]),
|
|
)
|
|
const date = new Date().toISOString().slice(0, 10)
|
|
return c.body(csv, 200, { 'Content-Type': 'text/csv; charset=utf-8', 'Content-Disposition': `attachment; filename="incidents-${date}.csv"` })
|
|
})
|
|
|
|
.post('/', requireAuth, validate('json', createIncidentSchema), async (c) => {
|
|
const me = currentUser(c)
|
|
const input = c.req.valid('json')
|
|
const db = c.get('db')
|
|
const { id, created } = await fileReport(db, c.get('notifier'), { ...input, organizationId: me.organizationId, reporter: me })
|
|
const [row] = await selectIncidents(db).where(eq(incidents.id, id))
|
|
return c.json({ incident: toIncident(row) }, created ? 201 : 200)
|
|
})
|
|
|
|
.get('/:number', requireAuth, validate('param', numberParam), async (c) => {
|
|
return c.json({ incident: await loadDetail(c.get('db'), currentUser(c), c.req.valid('param').number) })
|
|
})
|
|
|
|
.patch('/:number', requireRole('supervisor'), validate('param', numberParam), validate('json', updateIncidentSchema), async (c) => {
|
|
const me = currentUser(c)
|
|
const db = c.get('db')
|
|
const { incident } = await findIncident(db, me, c.req.valid('param').number)
|
|
const { occurredAt, ...input } = c.req.valid('json')
|
|
|
|
const siteId = input.siteId ?? incident.siteId
|
|
let areaId = input.areaId !== undefined ? input.areaId : incident.areaId
|
|
if (input.siteId && input.siteId !== incident.siteId && input.areaId === undefined) areaId = null // moving site clears the old area
|
|
if (input.siteId !== undefined || input.areaId !== undefined) await assertLocation(db, me.organizationId, siteId, areaId)
|
|
|
|
const update = { ...input, areaId, occurredAt: occurredAt ? parseOccurredAt(occurredAt) : undefined }
|
|
const changes = diff(incident, update)
|
|
if (Object.keys(changes).length > 0) {
|
|
await db.update(incidents).set(update).where(eq(incidents.id, incident.id))
|
|
await auditIncident(db, me, me.organizationId, incident.id, 'update', changes)
|
|
}
|
|
return c.json({ incident: await loadDetail(db, me, incident.number) })
|
|
})
|
|
|
|
.post('/:number/transitions', requireAuth, validate('param', numberParam), validate('json', transitionSchema), async (c) => {
|
|
const me = currentUser(c)
|
|
const db = c.get('db')
|
|
const { to, note } = c.req.valid('json')
|
|
const detail = await loadDetail(db, me, c.req.valid('param').number)
|
|
|
|
const rule = transitions.find((t) => t.from === detail.status && t.to === to)
|
|
if (!rule) throw fail(409, `An incident in "${detail.status}" can't move to "${to}"`)
|
|
if (!hasRole(me.role, rule.minRole)) throw fail(403, 'You do not have permission to do that')
|
|
const blocker = transitionBlocker(rule, {
|
|
severity: detail.severity,
|
|
rootCauseCount: detail.rootCauses.length,
|
|
actionStatuses: detail.actions.map((action) => action.status),
|
|
})
|
|
if (blocker) throw fail(409, blocker)
|
|
|
|
// Conditional update guards against two people moving the same incident at once.
|
|
const moved = await db
|
|
.update(incidents)
|
|
.set({ status: to, closedAt: to === 'closed' ? new Date() : null })
|
|
.where(and(eq(incidents.id, detail.id), eq(incidents.status, detail.status)))
|
|
.returning({ id: incidents.id })
|
|
if (moved.length === 0) throw fail(409, 'This incident was just changed by someone else. Reload and try again.')
|
|
|
|
await auditIncident(db, me, me.organizationId, detail.id, 'status', { status: [detail.status, to], ...(note ? { note } : {}) })
|
|
if (note) await db.insert(comments).values({ incidentId: detail.id, authorId: me.id, body: note })
|
|
return c.json({ incident: await loadDetail(db, me, detail.number) })
|
|
})
|
|
|
|
.get('/:number/comments', requireAuth, validate('param', numberParam), async (c) => {
|
|
const db = c.get('db')
|
|
const { incident } = await findIncident(db, currentUser(c), c.req.valid('param').number)
|
|
const rows = await db
|
|
.select({ comment: comments, authorName: users.name })
|
|
.from(comments)
|
|
.leftJoin(users, eq(users.id, comments.authorId))
|
|
.where(eq(comments.incidentId, incident.id))
|
|
.orderBy(asc(comments.createdAt))
|
|
const result: Comment[] = rows.map(({ comment, authorName }) => ({
|
|
id: comment.id,
|
|
author: comment.authorId ? { id: comment.authorId, name: authorName ?? '' } : null,
|
|
body: comment.body,
|
|
createdAt: iso(comment.createdAt),
|
|
}))
|
|
return c.json({ comments: result })
|
|
})
|
|
|
|
.post('/:number/comments', requireAuth, validate('param', numberParam), validate('json', commentSchema), async (c) => {
|
|
const me = currentUser(c)
|
|
const db = c.get('db')
|
|
const { incident } = await findIncident(db, me, c.req.valid('param').number)
|
|
const [comment] = await db.insert(comments).values({ incidentId: incident.id, authorId: me.id, body: c.req.valid('json').body }).returning()
|
|
const result: Comment = { id: comment.id, author: { id: me.id, name: me.name }, body: comment.body, createdAt: iso(comment.createdAt) }
|
|
return c.json({ comment: result }, 201)
|
|
})
|
|
|
|
.get('/:number/timeline', requireAuth, validate('param', numberParam), async (c) => {
|
|
const me = currentUser(c)
|
|
const db = c.get('db')
|
|
const { incident } = await findIncident(db, me, c.req.valid('param').number)
|
|
const rows = await db
|
|
.select({ entry: auditLog, actorName: users.name })
|
|
.from(auditLog)
|
|
.leftJoin(users, eq(users.id, auditLog.actorId))
|
|
.where(and(eq(auditLog.organizationId, me.organizationId), eq(auditLog.entityType, 'incident'), eq(auditLog.entityId, incident.id)))
|
|
.orderBy(asc(auditLog.id))
|
|
const timeline: TimelineEntry[] = rows.map(({ entry, actorName }) => ({
|
|
id: entry.id,
|
|
at: iso(entry.createdAt),
|
|
actor: entry.actorId ? { id: entry.actorId, name: actorName ?? '' } : null,
|
|
action: entry.action,
|
|
changes: (entry.changes as Record<string, unknown> | null) ?? null,
|
|
}))
|
|
return c.json({ timeline })
|
|
})
|
|
|
|
.put('/:number/investigation', requireRole('supervisor'), validate('param', numberParam), validate('json', investigationSchema), async (c) => {
|
|
const me = currentUser(c)
|
|
const db = c.get('db')
|
|
const { incident } = await findIncident(db, me, c.req.valid('param').number)
|
|
const { completed, ...input } = c.req.valid('json')
|
|
if (input.leadId) await assertActiveUser(db, me.organizationId, input.leadId)
|
|
|
|
const investigationId = await ensureInvestigation(db, incident.id)
|
|
const [current] = await db.select().from(investigations).where(eq(investigations.id, investigationId))
|
|
const update = { ...input, completedAt: completed === undefined ? undefined : completed ? (current.completedAt ?? new Date()) : null }
|
|
const changes = diff(current, update)
|
|
if (Object.keys(changes).length > 0) {
|
|
await db.update(investigations).set(update).where(eq(investigations.id, investigationId))
|
|
await auditIncident(db, me, me.organizationId, incident.id, 'investigation.update', changes)
|
|
}
|
|
return c.json({ incident: await loadDetail(db, me, incident.number) })
|
|
})
|
|
|
|
.post('/:number/root-causes', requireRole('supervisor'), validate('param', numberParam), validate('json', rootCauseSchema), async (c) => {
|
|
const me = currentUser(c)
|
|
const db = c.get('db')
|
|
const { incident } = await findIncident(db, me, c.req.valid('param').number)
|
|
const input = c.req.valid('json')
|
|
const investigationId = await ensureInvestigation(db, incident.id)
|
|
await db.insert(rootCauses).values({ ...input, investigationId })
|
|
await auditIncident(db, me, me.organizationId, incident.id, 'root_cause.add', { category: input.category, description: input.description })
|
|
return c.json({ incident: await loadDetail(db, me, incident.number) }, 201)
|
|
})
|
|
|
|
.post('/:number/actions', requireRole('supervisor'), validate('param', numberParam), validate('json', createActionSchema), async (c) => {
|
|
const me = currentUser(c)
|
|
const db = c.get('db')
|
|
const { incident } = await findIncident(db, me, c.req.valid('param').number)
|
|
if (incident.status === 'closed') throw fail(409, 'Reopen the incident before adding actions')
|
|
const input = c.req.valid('json')
|
|
if (input.assigneeId) await assertActiveUser(db, me.organizationId, input.assigneeId)
|
|
if (input.rootCauseId) {
|
|
const [cause] = await db
|
|
.select({ id: rootCauses.id })
|
|
.from(rootCauses)
|
|
.innerJoin(investigations, eq(investigations.id, rootCauses.investigationId))
|
|
.where(and(eq(rootCauses.id, input.rootCauseId), eq(investigations.incidentId, incident.id)))
|
|
if (!cause) throw fail(400, 'Root cause must belong to this incident')
|
|
}
|
|
|
|
const [action] = await db
|
|
.insert(correctiveActions)
|
|
.values({ ...input, incidentId: incident.id })
|
|
.returning()
|
|
await auditIncident(db, me, me.organizationId, incident.id, 'action.add', { actionId: action.id, title: action.title, assigneeId: action.assigneeId, dueDate: action.dueDate })
|
|
if (action.assigneeId && action.assigneeId !== me.id) c.get('notifier').actionAssigned(action.id, me.name)
|
|
return c.json({ incident: await loadDetail(db, me, incident.number) }, 201)
|
|
})
|
|
|
|
.post(
|
|
'/:number/attachments',
|
|
requireAuth,
|
|
validate('param', numberParam),
|
|
// Reject oversized bodies before reading them into memory
|
|
async (c, next) => bodyLimit({ maxSize: c.get('config').maxUploadBytes + 64 * 1024, onError: (c) => c.json({ error: 'File is too large' }, 413) })(c, next),
|
|
async (c) => {
|
|
const me = currentUser(c)
|
|
const db = c.get('db')
|
|
const config = c.get('config')
|
|
const { incident } = await findIncident(db, me, c.req.valid('param').number)
|
|
|
|
const body = await c.req.parseBody()
|
|
const row = await saveAttachment({ db, storage: c.get('storage'), config }, incident.id, body.file, me.id)
|
|
await auditIncident(db, me, me.organizationId, incident.id, 'attachment.add', { attachmentId: row.id, fileName: row.fileName })
|
|
return c.json({ attachment: toAttachment(row, me.name) }, 201)
|
|
},
|
|
)
|