Merge feat/zone-capa-proof: zone picker, CAPA completion proof, test-data cleanup

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-15 11:07:32 +08:00
co-authored by Claude Sonnet 5.5
23 changed files with 800 additions and 27 deletions
+22 -3
View File
@@ -5,8 +5,8 @@ import Link from 'next/link'
import { ArrowLeft } from 'lucide-react' import { ArrowLeft } from 'lucide-react'
import { asAdmin } from '@/lib/db/with-user' import { asAdmin } from '@/lib/db/with-user'
import { getSession } from '@/lib/auth/get-session' import { getSession } from '@/lib/auth/get-session'
import { capaActions, incidents, users } from '@/lib/db/schema' import { capaActions, evidenceFiles, incidents, users } from '@/lib/db/schema'
import { eq } from 'drizzle-orm' import { eq, and, asc } from 'drizzle-orm'
import { aliasedTable } from 'drizzle-orm' import { aliasedTable } from 'drizzle-orm'
import { VerifyForm } from '@/components/capa/verify-form' import { VerifyForm } from '@/components/capa/verify-form'
import { CloseCapaButton } from '@/components/capa/close-capa-button' import { CloseCapaButton } from '@/components/capa/close-capa-button'
@@ -60,6 +60,13 @@ export default async function CapaDetailPage({ params }: Props) {
if (!capa) notFound() if (!capa) notFound()
const photos = await asAdmin(db =>
db.select({ id: evidenceFiles.id, fileUrl: evidenceFiles.fileUrl })
.from(evidenceFiles)
.where(and(eq(evidenceFiles.capaId, id), eq(evidenceFiles.deleted, false)))
.orderBy(asc(evidenceFiles.uploadedAt))
)
const isHse = session && ['hse', 'admin'].includes(session.role) const isHse = session && ['hse', 'admin'].includes(session.role)
const status = capa.status const status = capa.status
const today = new Date().toISOString().slice(0, 10) const today = new Date().toISOString().slice(0, 10)
@@ -102,7 +109,7 @@ export default async function CapaDetailPage({ params }: Props) {
{isHse && status === 'pending_verification' && <VerifyForm capaId={id} />} {isHse && status === 'pending_verification' && <VerifyForm capaId={id} />}
{isHse && status === 'verified' && <CloseCapaButton capaId={id} />} {isHse && status === 'verified' && <CloseCapaButton capaId={id} />}
{(capa.ownerNotes || capa.completedAt) && ( {(capa.ownerNotes || capa.completedAt || photos.length > 0) && (
<section className="space-y-2 rounded-xl bg-surface p-5 shadow-card"> <section className="space-y-2 rounded-xl bg-surface p-5 shadow-card">
<h2 className="text-sm font-semibold">Completion report</h2> <h2 className="text-sm font-semibold">Completion report</h2>
{capa.completedAt && ( {capa.completedAt && (
@@ -113,6 +120,18 @@ export default async function CapaDetailPage({ params }: Props) {
{capa.ownerNotes && ( {capa.ownerNotes && (
<p className="whitespace-pre-wrap text-[13px] text-ink-3">{capa.ownerNotes}</p> <p className="whitespace-pre-wrap text-[13px] text-ink-3">{capa.ownerNotes}</p>
)} )}
{photos.length > 0 && (
<ul className="grid grid-cols-2 gap-2 sm:grid-cols-3">
{photos.map((p, i) => (
<li key={p.id}>
<a href={p.fileUrl} target="_blank" rel="noreferrer" className="block overflow-hidden rounded-md shadow-card">
{/* eslint-disable-next-line @next/next/no-img-element */}
<img src={p.fileUrl} alt={`CAPA completion evidence ${i + 1} of ${photos.length}`} className="aspect-square w-full object-cover" />
</a>
</li>
))}
</ul>
)}
</section> </section>
)} )}
</div> </div>
+7 -2
View File
@@ -105,6 +105,13 @@ export async function PATCH(
const body = await request.json() const body = await request.json()
if (body.status === 'pending_verification') {
return NextResponse.json(
{ error: 'Use POST /api/capa/[id]/submit to submit for verification' },
{ status: 403 },
)
}
const privilegedStatuses = ['verified', 'reopened', 'closed'] const privilegedStatuses = ['verified', 'reopened', 'closed']
if (body.status && privilegedStatuses.includes(body.status) && !['hse', 'admin'].includes(role)) { if (body.status && privilegedStatuses.includes(body.status) && !['hse', 'admin'].includes(role)) {
return NextResponse.json({ error: 'Forbidden' }, { status: 403 }) return NextResponse.json({ error: 'Forbidden' }, { status: 403 })
@@ -122,14 +129,12 @@ export async function PATCH(
if ('department' in body && allowed.includes('department')) updateSet.department = body.department if ('department' in body && allowed.includes('department')) updateSet.department = body.department
if ('root_cause_ref' in body && allowed.includes('root_cause_ref')) updateSet.rootCauseRef = body.root_cause_ref if ('root_cause_ref' in body && allowed.includes('root_cause_ref')) updateSet.rootCauseRef = body.root_cause_ref
if ('owner_notes' in body && allowed.includes('owner_notes')) updateSet.ownerNotes = body.owner_notes if ('owner_notes' in body && allowed.includes('owner_notes')) updateSet.ownerNotes = body.owner_notes
if (body.status === 'pending_verification') updateSet.completedAt = new Date()
// Build audit new/old value from original snake_case body keys for consistency // Build audit new/old value from original snake_case body keys for consistency
const auditNew: Record<string, unknown> = {} const auditNew: Record<string, unknown> = {}
for (const key of allowed) { for (const key of allowed) {
if (key in body) auditNew[key] = body[key] if (key in body) auditNew[key] = body[key]
} }
if (body.status === 'pending_verification') auditNew.completed_at = updateSet.completedAt?.toISOString()
await withUser(session.sub, async tx => { await withUser(session.sub, async tx => {
let oldNotes: string | null = null let oldNotes: string | null = null
+98
View File
@@ -0,0 +1,98 @@
export const dynamic = 'force-dynamic'
import { NextRequest, NextResponse } from 'next/server'
import { and, eq } from 'drizzle-orm'
import { getSession } from '@/lib/auth/get-session'
import { withUser } from '@/lib/db/with-user'
import { writeAuditLog } from '@/lib/db/audit'
import { capaActions, evidenceFiles } from '@/lib/db/schema'
import { uploadEvidenceFile } from '@/lib/storage/evidence'
import { validateCapaSubmission } from '@/lib/capa/submit-validation'
class StatusConflict extends Error {}
export async function POST(
request: NextRequest,
{ params }: { params: Promise<{ id: string }> }
) {
const { id } = await params
const session = await getSession()
if (!session) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
const [capa] = await withUser(session.sub, async tx =>
tx.select({
incidentId: capaActions.incidentId,
ownerUserId: capaActions.ownerUserId,
status: capaActions.status,
}).from(capaActions).where(eq(capaActions.id, id)).limit(1)
)
if (!capa) return NextResponse.json({ error: 'Not found' }, { status: 404 })
const isElevated = ['hse', 'admin'].includes(session.role)
if (capa.ownerUserId !== session.sub && !isElevated)
return NextResponse.json({ error: 'Forbidden' }, { status: 403 })
if (capa.status !== 'in_progress')
return NextResponse.json({ error: 'CAPA must be in_progress' }, { status: 409 })
const form = await request.formData()
const files = form.getAll('files').filter((f): f is File => f instanceof File)
const check = validateCapaSubmission(String(form.get('note') ?? ''), files)
if (!check.ok)
return NextResponse.json({ error: 'Validation failed', details: check.errors }, { status: 422 })
const uploaded: Array<{ publicUrl: string; hash: string; type: string }> = []
try {
for (const file of files) {
const { publicUrl, hash } = await uploadEvidenceFile(file, capa.incidentId, 'capa', session.sub)
uploaded.push({ publicUrl, hash, type: file.type })
}
} catch (err) {
return NextResponse.json(
{ error: 'Photo upload failed', details: [err instanceof Error ? err.message : 'unknown error'] },
{ status: 422 },
)
}
const completedAt = new Date()
try {
await withUser(session.sub, async tx => {
const updated = await tx.update(capaActions).set({
status: 'pending_verification',
ownerNotes: check.note,
completedAt,
}).where(and(eq(capaActions.id, id), eq(capaActions.status, 'in_progress')))
.returning({ id: capaActions.id })
if (updated.length === 0) throw new StatusConflict()
const rows = await tx.insert(evidenceFiles).values(
uploaded.map(u => ({
incidentId: capa.incidentId,
capaId: id,
stage: 'capa' as const,
fileUrl: u.publicUrl,
fileType: u.type,
fileHash: u.hash,
uploadedBy: session.sub,
}))
).returning({ id: evidenceFiles.id })
await writeAuditLog(
tx, 'capa_actions', id, 'submitted_for_verification',
{
status: 'pending_verification',
owner_notes: check.note,
completed_at: completedAt.toISOString(),
evidence_file_ids: rows.map(r => r.id),
},
{ status: 'in_progress' },
)
})
} catch (err) {
if (err instanceof StatusConflict)
return NextResponse.json({ error: 'CAPA must be in_progress' }, { status: 409 })
throw err
}
return NextResponse.json({ ok: true })
}
+27 -6
View File
@@ -3,8 +3,9 @@ export const dynamic = 'force-dynamic'
import { redirect } from 'next/navigation' import { redirect } from 'next/navigation'
import { asAdmin } from '@/lib/db/with-user' import { asAdmin } from '@/lib/db/with-user'
import { getSession } from '@/lib/auth/get-session' import { getSession } from '@/lib/auth/get-session'
import { zones, sites, trucks } from '@/lib/db/schema' import { zones, sites, trucks, users } from '@/lib/db/schema'
import { eq, asc } from 'drizzle-orm' import { eq, asc, and } from 'drizzle-orm'
import { groupSites } from '@/lib/report/zones'
import { ReportForm } from '@/components/incidents/report-form' import { ReportForm } from '@/components/incidents/report-form'
import { LanguageSwitcher } from '@/components/language-switcher' import { LanguageSwitcher } from '@/components/language-switcher'
import { OfflineSync } from '@/components/incidents/offline-sync' import { OfflineSync } from '@/components/incidents/offline-sync'
@@ -55,6 +56,26 @@ export default async function ReportPage({ searchParams }: Props) {
carrier: t.carrier ?? null, carrier: t.carrier ?? null,
})) }))
const zoneRows = await asAdmin(db =>
db.select({
siteId: sites.id,
siteName: sites.name,
zoneId: zones.id,
zoneName: zones.name,
token: zones.qrCodeToken,
})
.from(zones)
.innerJoin(sites, eq(zones.siteId, sites.id))
.where(and(eq(zones.active, true), eq(sites.active, true)))
.orderBy(asc(sites.name), asc(zones.name))
)
const siteOptions = groupSites(zoneRows)
const [me] = await asAdmin(db =>
db.select({ siteId: users.siteId }).from(users).where(eq(users.id, session.sub)).limit(1)
)
const defaultSiteId = me?.siteId ?? ''
return ( return (
<main className="min-h-screen bg-gray-50 py-6 px-4 max-w-lg mx-auto"> <main className="min-h-screen bg-gray-50 py-6 px-4 max-w-lg mx-auto">
<div className="mb-6"> <div className="mb-6">
@@ -62,18 +83,18 @@ export default async function ReportPage({ searchParams }: Props) {
<h1 className="text-2xl font-bold text-gray-900">{/* will be translated via ReportForm */}Report an Incident</h1> <h1 className="text-2xl font-bold text-gray-900">{/* will be translated via ReportForm */}Report an Incident</h1>
<LanguageSwitcher /> <LanguageSwitcher />
</div> </div>
{zoneName ? ( {zoneName && (
<p className="text-sm text-gray-600 mt-1"> <p className="text-sm text-gray-600 mt-1">
{siteName ?? 'Unknown Site'} — {zoneName} {siteName ?? 'Unknown Site'} — {zoneName}
</p> </p>
) : (
<p className="text-sm text-accent-700 mt-1">No zone detected — zone will not be recorded</p>
)} )}
</div> </div>
<ReportForm <ReportForm
zoneToken={zone ?? null} zoneToken={zoneName ? (zone ?? null) : null}
zoneName={zoneName} zoneName={zoneName}
siteName={siteName} siteName={siteName}
sites={siteOptions}
defaultSiteId={defaultSiteId}
trucks={truckList} trucks={truckList}
initialTruckId={truck_id ?? null} initialTruckId={truck_id ?? null}
/> />
+2 -5
View File
@@ -3,6 +3,7 @@
import { useState } from 'react' import { useState } from 'react'
import { useRouter } from 'next/navigation' import { useRouter } from 'next/navigation'
import { Button } from '@/components/ui/button' import { Button } from '@/components/ui/button'
import { SubmitVerificationForm } from '@/components/capa/submit-verification-form'
interface Props { interface Props {
capaId: string capaId: string
@@ -41,11 +42,7 @@ export function CapaOwnerActions({ capaId, currentStatus }: Props) {
} }
if (currentStatus === 'in_progress') { if (currentStatus === 'in_progress') {
return ( return <SubmitVerificationForm capaId={capaId} />
<Button onClick={() => updateStatus('pending_verification')} disabled={loading}>
{loading ? '…' : 'Submit for Verification'}
</Button>
)
} }
return null return null
@@ -0,0 +1,108 @@
'use client'
import { useState } from 'react'
import { useRouter } from 'next/navigation'
import { X } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { Field, Textarea } from '@/components/ui/field'
import { MAX_CAPA_PHOTOS, validateCapaSubmission } from '@/lib/capa/submit-validation'
interface Props {
capaId: string
}
export function SubmitVerificationForm({ capaId }: Props) {
const router = useRouter()
const [note, setNote] = useState('')
const [files, setFiles] = useState<File[]>([])
const [loading, setLoading] = useState(false)
const [error, setError] = useState<string | null>(null)
const check = validateCapaSubmission(note, files)
function addFiles(list: FileList | null) {
if (!list) return
setFiles(prev => [...prev, ...Array.from(list)].slice(0, MAX_CAPA_PHOTOS))
}
async function handleSubmit(e: React.FormEvent) {
e.preventDefault()
if (!check.ok) return
setLoading(true)
setError(null)
try {
const fd = new FormData()
fd.append('note', check.note)
files.forEach(f => fd.append('files', f))
const res = await fetch(`/api/capa/${capaId}/submit`, { method: 'POST', body: fd })
if (!res.ok) {
const data = await res.json().catch(() => ({}))
setError(Array.isArray(data.details) ? data.details.join('. ') : (data.error ?? 'Submit failed. Please try again.'))
setLoading(false)
return
}
router.refresh()
return
} catch {
setError('Network error. Please try again.')
}
setLoading(false)
}
return (
<form onSubmit={handleSubmit} className="space-y-3 rounded-xl bg-surface p-5 shadow-card">
<div>
<h2 className="text-sm font-semibold">Proof of completion</h2>
<p className="text-xs text-muted">Describe what was done and attach 1 to {MAX_CAPA_PHOTOS} photos as evidence.</p>
</div>
<Field label="Completion note" htmlFor={`note-${capaId}`}>
<Textarea
id={`note-${capaId}`}
value={note}
onChange={e => setNote(e.target.value)}
rows={3}
placeholder="What action was carried out?"
disabled={loading}
/>
</Field>
<Field label="Photos" htmlFor={`photos-${capaId}`}>
<input
id={`photos-${capaId}`}
type="file"
accept="image/*"
multiple
disabled={loading || files.length >= MAX_CAPA_PHOTOS}
onChange={e => { addFiles(e.target.files); e.target.value = '' }}
className="block w-full text-[13px] text-ink"
/>
</Field>
{files.length > 0 && (
<ul className="space-y-1">
{files.map((f, i) => (
<li key={`${f.name}-${i}`} className="flex items-center justify-between gap-2 text-[13px]">
<span className="truncate">{f.name}</span>
<button
type="button"
aria-label={`Remove ${f.name}`}
onClick={() => setFiles(prev => prev.filter((_, j) => j !== i))}
disabled={loading}
className="text-muted hover:text-ink"
>
<X size={14} strokeWidth={2} aria-hidden />
</button>
</li>
))}
</ul>
)}
{error && <p role="alert" className="text-xs text-danger">{error}</p>}
<Button type="submit" disabled={!check.ok || loading}>
{loading ? 'Submitting…' : 'Submit for Verification'}
</Button>
</form>
)
}
+47 -4
View File
@@ -5,16 +5,19 @@ import { useRouter } from 'next/navigation'
import { FileUpload } from '@/components/incidents/file-upload' import { FileUpload } from '@/components/incidents/file-upload'
import type { IncidentType, MedicalStatus } from '@/lib/incidents/validate' import type { IncidentType, MedicalStatus } from '@/lib/incidents/validate'
import { useTranslations } from '@/lib/i18n/context' import { useTranslations } from '@/lib/i18n/context'
import { zonesForSite, resolveZoneToken, type SiteOption } from '@/lib/report/zones'
interface Props { interface Props {
zoneToken: string | null zoneToken: string | null
zoneName: string | null zoneName: string | null
siteName: string | null siteName: string | null
sites: SiteOption[]
defaultSiteId: string
trucks: Array<{ id: string; truck_no: string; carrier: string | null }> trucks: Array<{ id: string; truck_no: string; carrier: string | null }>
initialTruckId?: string | null initialTruckId?: string | null
} }
export function ReportForm({ zoneToken, trucks, initialTruckId }: Props) { export function ReportForm({ zoneToken, sites, defaultSiteId, trucks, initialTruckId }: Props) {
const router = useRouter() const router = useRouter()
const t = useTranslations('ReportForm') const t = useTranslations('ReportForm')
const itLabels = useTranslations('IncidentType') const itLabels = useTranslations('IncidentType')
@@ -52,6 +55,12 @@ export function ReportForm({ zoneToken, trucks, initialTruckId }: Props) {
} | null>(null) } | null>(null)
const [overrideQuality, setOverrideQuality] = useState(false) const [overrideQuality, setOverrideQuality] = useState(false)
const [siteId, setSiteId] = useState(
sites.some(s => s.id === defaultSiteId) ? defaultSiteId : (sites.length === 1 ? sites[0].id : '')
)
const [zoneId, setZoneId] = useState('')
const effectiveZoneToken = resolveZoneToken({ zoneToken, sites, zoneId })
const [form, setForm] = useState({ const [form, setForm] = useState({
incident_type: (initialTruckId ? 'transport' : '') as IncidentType | '', incident_type: (initialTruckId ? 'transport' : '') as IncidentType | '',
description: '', description: '',
@@ -113,7 +122,7 @@ export function ReportForm({ zoneToken, trucks, initialTruckId }: Props) {
try { try {
const { addPendingReport } = await import('@/lib/offline/db') const { addPendingReport } = await import('@/lib/offline/db')
await addPendingReport({ await addPendingReport({
zone_token: zoneToken ?? '', zone_token: effectiveZoneToken ?? '',
incident_type: form.incident_type as IncidentType, incident_type: form.incident_type as IncidentType,
description: form.description, description: form.description,
injury_involved: form.injury_involved, injury_involved: form.injury_involved,
@@ -162,7 +171,7 @@ export function ReportForm({ zoneToken, trucks, initialTruckId }: Props) {
try { try {
const fd = new FormData() const fd = new FormData()
if (zoneToken) fd.append('zone_token', zoneToken) if (effectiveZoneToken) fd.append('zone_token', effectiveZoneToken)
fd.append('incident_type', form.incident_type) fd.append('incident_type', form.incident_type)
fd.append('description', form.description) fd.append('description', form.description)
fd.append('injury_involved', String(form.injury_involved)) fd.append('injury_involved', String(form.injury_involved))
@@ -225,6 +234,40 @@ export function ReportForm({ zoneToken, trucks, initialTruckId }: Props) {
</div> </div>
)} )}
{!zoneToken && (
<div className="grid grid-cols-2 gap-3">
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">
{t.siteLabel} <span className="text-red-500">*</span>
</label>
<select
required
className="w-full border border-divider px-3 py-2.5 text-sm focus:outline-none focus:ring-2 focus:ring-accent"
value={siteId}
onChange={e => { setSiteId(e.target.value); setZoneId('') }}
>
<option value="">{t.sitePlaceholder}</option>
{sites.map(s => <option key={s.id} value={s.id}>{s.name}</option>)}
</select>
</div>
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">
{t.zoneLabel} <span className="text-red-500">*</span>
</label>
<select
required
disabled={!siteId}
className="w-full border border-divider px-3 py-2.5 text-sm focus:outline-none focus:ring-2 focus:ring-accent disabled:opacity-50"
value={zoneId}
onChange={e => setZoneId(e.target.value)}
>
<option value="">{t.zonePlaceholder}</option>
{zonesForSite(sites, siteId).map(z => <option key={z.id} value={z.id}>{z.name}</option>)}
</select>
</div>
</div>
)}
<div> <div>
<label className="block text-sm font-medium text-gray-700 mb-1"> <label className="block text-sm font-medium text-gray-700 mb-1">
{t.incidentTypeLabel} <span className="text-red-500">*</span> {t.incidentTypeLabel} <span className="text-red-500">*</span>
@@ -382,7 +425,7 @@ export function ReportForm({ zoneToken, trucks, initialTruckId }: Props) {
<button <button
type="submit" type="submit"
disabled={submitting || !form.incident_type || (form.incident_type === 'transport' && !form.truck_id)} disabled={submitting || !effectiveZoneToken || !form.incident_type || (form.incident_type === 'transport' && !form.truck_id)}
className="w-full bg-accent text-white py-3 font-medium text-sm className="w-full bg-accent text-white py-3 font-medium text-sm
hover:bg-accent-600 disabled:opacity-50 disabled:cursor-not-allowed transition-colors" hover:bg-accent-600 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
> >
+5
View File
@@ -0,0 +1,5 @@
-- Apply by hand on the server DB with the owner's go-ahead. Not run by deploy.
BEGIN;
ALTER TABLE evidence_files ADD COLUMN IF NOT EXISTS capa_id UUID REFERENCES capa_actions(id) ON DELETE RESTRICT;
CREATE INDEX IF NOT EXISTS evidence_files_capa_id_idx ON evidence_files(capa_id);
COMMIT;
+67
View File
@@ -0,0 +1,67 @@
-- One-off: delete ALL incidents (and children) and every user with role <> 'admin'.
-- Usage: psql -p 5433 -d ims -v mode=dryrun -f cleanup-test-data.sql (counts only)
-- psql -p 5433 -d ims -v mode=run -f cleanup-test-data.sql (deletes, one transaction)
-- Evidence files on disk are NOT touched (5-year retention).
\set ON_ERROR_STOP on
\if :{?mode}
\else
\echo 'Set -v mode=dryrun or -v mode=run'
\quit
\endif
BEGIN;
\echo '--- admins kept ---'
SELECT id, name, email FROM users WHERE role = 'admin' ORDER BY email;
\echo '--- row counts to delete ---'
SELECT 'incidents' AS tbl, count(*) FROM incidents
UNION ALL SELECT 'evidence_files', count(*) FROM evidence_files
UNION ALL SELECT 'investigations', count(*) FROM investigations
UNION ALL SELECT 'capa_actions', count(*) FROM capa_actions
UNION ALL SELECT 'dosh_reports', count(*) FROM dosh_reports
UNION ALL SELECT 'incident_addenda', count(*) FROM incident_addenda
UNION ALL SELECT 'notifications_log', count(*) FROM notifications_log
UNION ALL SELECT 'audit_log (all)', count(*) FROM audit_log
UNION ALL SELECT 'users (non-admin)', count(*) FROM users WHERE role <> 'admin';
SELECT (:'mode' = 'run') AS do_delete \gset
\if :do_delete
-- Closed incidents are locked by triggers; disable them for this transaction only.
ALTER TABLE incidents DISABLE TRIGGER incidents_closed_lock_delete;
ALTER TABLE incidents DISABLE TRIGGER incidents_closed_lock_update;
DELETE FROM notifications_log;
DELETE FROM incident_addenda;
DELETE FROM dosh_reports;
DELETE FROM evidence_files;
DELETE FROM capa_actions;
DELETE FROM investigations;
DELETE FROM incidents;
-- audit_log: remove rows about deleted incident-side tables and about non-admin users.
DELETE FROM audit_log
WHERE table_name IN ('incidents','evidence_files','investigations','capa_actions','dosh_reports','incident_addenda')
OR changed_by IN (SELECT id FROM users WHERE role <> 'admin')
OR (table_name = 'users' AND record_id IN (SELECT id FROM users WHERE role <> 'admin'));
UPDATE app_settings SET updated_by = NULL
WHERE updated_by IN (SELECT id FROM users WHERE role <> 'admin');
DELETE FROM password_reset_tokens WHERE user_id IN (SELECT id FROM users WHERE role <> 'admin');
DELETE FROM users WHERE role <> 'admin';
ALTER TABLE incidents ENABLE TRIGGER incidents_closed_lock_delete;
ALTER TABLE incidents ENABLE TRIGGER incidents_closed_lock_update;
\echo '--- after ---'
SELECT 'incidents' AS tbl, count(*) FROM incidents
UNION ALL SELECT 'users', count(*) FROM users
UNION ALL SELECT 'admins', count(*) FROM users WHERE role = 'admin';
COMMIT;
\else
ROLLBACK;
\echo 'dry run: nothing changed'
\endif
+3
View File
@@ -197,6 +197,9 @@ CREATE INDEX capa_actions_owner_idx ON capa_actions(owner_user_id);
CREATE INDEX capa_actions_status_idx ON capa_actions(status); CREATE INDEX capa_actions_status_idx ON capa_actions(status);
CREATE INDEX capa_actions_due_date_idx ON capa_actions(due_date); CREATE INDEX capa_actions_due_date_idx ON capa_actions(due_date);
ALTER TABLE evidence_files ADD COLUMN capa_id UUID REFERENCES capa_actions(id) ON DELETE RESTRICT;
CREATE INDEX evidence_files_capa_id_idx ON evidence_files(capa_id);
CREATE TABLE dosh_reports ( CREATE TABLE dosh_reports (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(), id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
incident_id UUID NOT NULL REFERENCES incidents(id) ON DELETE RESTRICT, incident_id UUID NOT NULL REFERENCES incidents(id) ON DELETE RESTRICT,
+24
View File
@@ -0,0 +1,24 @@
# Cleanup: delete test incidents and non-admin users
Owner go-ahead required before step 4. Never run during business hours without telling HSE.
1. **Backup** (on the server, `ssh -p 9321 setia@175.136.239.121`):
```bash
D=$(date +%Y%m%d-%H%M)
pg_dump -p 5433 -Fc ims > /srv/apps/ims/backups/ims-pre-cleanup-$D.dump
tar -czf /srv/apps/ims/backups/evidence-pre-cleanup-$D.tgz /var/lib/ims-evidence
ls -lh /srv/apps/ims/backups/*pre-cleanup-$D*
```
Create `/srv/apps/ims/backups` first if missing. Both files must be non-empty.
2. **Upload** `db/ops/cleanup-test-data.sql` to `/srv/apps/ims/backups/` (not into `app/`).
3. **Dry run.** Use a DB role that owns the tables and bypasses RLS (superuser, or the owner role with BYPASSRLS). The tables have FORCE RLS and no DELETE policies, so as `app_user` or a plain owner the counts can read 0 and deletes silently remove nothing. Check first: `psql -p 5433 -d ims -Atc "select rolsuper or rolbypassrls from pg_roles where rolname = current_user"` must print `t`. Then:
```bash
psql -p 5433 -d ims -v mode=dryrun -f /srv/apps/ims/backups/cleanup-test-data.sql
```
Send the admins list and the row counts to the owner. If incidents or users show 0 when the app shows rows, you are on the wrong role: stop. Mention that audit_log rows written by non-admin users about other tables (zones, trucks, settings) are also removed. Stop here until they confirm.
4. **Run** after explicit confirmation:
```bash
psql -p 5433 -d ims -v ON_ERROR_STOP=1 -v mode=run -f /srv/apps/ims/backups/cleanup-test-data.sql
```
5. **Verify**: `systemctl is-active ims` is `active`; log in as an admin at https://ims.setia.com.my/login; Incidents page is empty; Users page lists only admins.
6. **Rollback** (only if wrong): `pg_restore -p 5433 -d ims --clean --if-exists <dump>`; evidence files were never touched.
@@ -32,17 +32,16 @@ Making zone optional; a "General" zone per site.
- Allowed: CAPA owner, or hse/admin. Status must be `in_progress`; otherwise 409. - Allowed: CAPA owner, or hse/admin. Status must be `in_progress`; otherwise 409.
- Validates note non-empty and 1 to 5 image files; otherwise 422. - Validates note non-empty and 1 to 5 image files; otherwise 422.
- In one `withUser` transaction: store files via `lib/storage/evidence.ts`, insert `evidence_files` rows (`stage = 'capa'`, `capa_id` set, hash recorded), set `owner_notes`, `completed_at`, `status = 'pending_verification'`, and write `audit_log` (include file ids and the note). - In one `withUser` transaction: store files via `lib/storage/evidence.ts`, insert `evidence_files` rows (`stage = 'capa'`, `capa_id` set, hash recorded), set `owner_notes`, `completed_at`, `status = 'pending_verification'`, and write `audit_log` (include file ids and the note).
- Existing in-app notification to HSE on submission is kept.
- `PATCH /api/capa/[id]` rejects `status: 'pending_verification'` with 403 for everyone (the new endpoint is the only path). Owner `in_progress` transition is unchanged. - `PATCH /api/capa/[id]` rejects `status: 'pending_verification'` with 403 for everyone (the new endpoint is the only path). Owner `in_progress` transition is unchanged.
- CAPA detail page: "Completion report" section shows the note and a photo gallery (signed `/api/evidence/...` URLs) so HSE sees proof when verifying or reopening. - CAPA detail page: "Completion report" section shows the note and a photo gallery (signed `/api/evidence/...` URLs) so HSE sees proof when verifying or reopening.
- Evidence rows are never hard-deleted (5-year retention). - Evidence rows are never hard-deleted (5-year retention).
### Schema change (manual, needs owner go-ahead) ### Schema change (manual, needs owner go-ahead)
```sql ```sql
ALTER TABLE evidence_files ADD COLUMN capa_id uuid REFERENCES capa_actions(id); ALTER TABLE evidence_files ADD COLUMN IF NOT EXISTS capa_id UUID REFERENCES capa_actions(id) ON DELETE RESTRICT;
CREATE INDEX evidence_files_capa_id_idx ON evidence_files(capa_id); CREATE INDEX IF NOT EXISTS evidence_files_capa_id_idx ON evidence_files(capa_id);
``` ```
The `evidence_stage` enum already has `capa`; no enum change. Update `db/schema.sql`, `lib/db/schema.ts`, and check the `evidence_*` RLS policies in `db/rls.sql` cover CAPA owners (insert) and hse/admin (read); add a read policy for the CAPA owner if missing. The `evidence_stage` enum already has `capa`; no enum change. Update `db/schema.sql`, `lib/db/schema.ts`, no RLS change: the PIC is the uploader and already reads own rows.
### Out of scope ### Out of scope
Photos on "Mark In Progress"; HSE-side evidence upload; video. Photos on "Mark In Progress"; HSE-side evidence upload; video.
+18
View File
@@ -0,0 +1,18 @@
export const MAX_CAPA_PHOTOS = 5
export type CapaSubmissionResult =
| { ok: true; note: string }
| { ok: false; errors: string[] }
export function validateCapaSubmission(
note: string,
files: ReadonlyArray<{ type: string }>,
): CapaSubmissionResult {
const errors: string[] = []
const trimmed = note.trim()
if (!trimmed) errors.push('Completion note is required')
if (files.length < 1) errors.push('At least 1 photo is required')
if (files.length > MAX_CAPA_PHOTOS) errors.push(`At most ${MAX_CAPA_PHOTOS} photos are allowed`)
if (files.some(f => !f.type.startsWith('image/'))) errors.push('Only image files are allowed')
return errors.length ? { ok: false, errors } : { ok: true, note: trimmed }
}
+2
View File
@@ -10,6 +10,7 @@ import {
date, date,
jsonb, jsonb,
customType, customType,
type AnyPgColumn,
} from 'drizzle-orm/pg-core' } from 'drizzle-orm/pg-core'
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
@@ -145,6 +146,7 @@ export const evidenceFiles = pgTable('evidence_files', {
uploadedBy: uuid('uploaded_by').notNull().references(() => users.id), uploadedBy: uuid('uploaded_by').notNull().references(() => users.id),
uploadedAt: timestamp('uploaded_at', { withTimezone: true }).notNull().defaultNow(), uploadedAt: timestamp('uploaded_at', { withTimezone: true }).notNull().defaultNow(),
deleted: boolean('deleted').notNull().default(false), deleted: boolean('deleted').notNull().default(false),
capaId: uuid('capa_id').references((): AnyPgColumn => capaActions.id),
}) })
export const investigations = pgTable('investigations', { export const investigations = pgTable('investigations', {
+33
View File
@@ -0,0 +1,33 @@
export type ZoneOption = { id: string; name: string; qr_code_token: string }
export type SiteOption = { id: string; name: string; zones: ZoneOption[] }
export type ZoneRow = { siteId: string; siteName: string; zoneId: string; zoneName: string; token: string }
export function groupSites(rows: ZoneRow[]): SiteOption[] {
const bySite = new Map<string, SiteOption>()
for (const r of rows) {
let site = bySite.get(r.siteId)
if (!site) {
site = { id: r.siteId, name: r.siteName, zones: [] }
bySite.set(r.siteId, site)
}
site.zones.push({ id: r.zoneId, name: r.zoneName, qr_code_token: r.token })
}
return [...bySite.values()]
}
export function zonesForSite(sites: SiteOption[], siteId: string): ZoneOption[] {
return sites.find(s => s.id === siteId)?.zones ?? []
}
export function resolveZoneToken(args: {
zoneToken: string | null
sites: SiteOption[]
zoneId: string
}): string | null {
if (args.zoneToken) return args.zoneToken
for (const site of args.sites) {
const zone = site.zones.find(z => z.id === args.zoneId)
if (zone) return zone.qr_code_token
}
return null
}
+5 -1
View File
@@ -18,7 +18,11 @@
"savedOffline": "Report saved. It will be submitted automatically when you're back online.", "savedOffline": "Report saved. It will be submitted automatically when you're back online.",
"offlineBanner": "You're offline. Your report will be saved and submitted when you reconnect.", "offlineBanner": "You're offline. Your report will be saved and submitted when you reconnect.",
"truckLabel": "Truck", "truckLabel": "Truck",
"truckPlaceholder": "Select truck…" "truckPlaceholder": "Select truck…",
"siteLabel": "Site",
"sitePlaceholder": "Select site…",
"zoneLabel": "Zone",
"zonePlaceholder": "Select zone…"
}, },
"IncidentType": { "IncidentType": {
"injury": "Injury / Medical", "injury": "Injury / Medical",
+5 -1
View File
@@ -18,7 +18,11 @@
"savedOffline": "Laporan disimpan. Ia akan dihantar secara automatik apabila anda dalam talian semula.", "savedOffline": "Laporan disimpan. Ia akan dihantar secara automatik apabila anda dalam talian semula.",
"offlineBanner": "Anda tiada sambungan. Laporan anda akan disimpan dan dihantar apabila disambungkan semula.", "offlineBanner": "Anda tiada sambungan. Laporan anda akan disimpan dan dihantar apabila disambungkan semula.",
"truckLabel": "Trak", "truckLabel": "Trak",
"truckPlaceholder": "Pilih trak…" "truckPlaceholder": "Pilih trak…",
"siteLabel": "Tapak",
"sitePlaceholder": "Pilih tapak…",
"zoneLabel": "Zon",
"zonePlaceholder": "Pilih zon…"
}, },
"IncidentType": { "IncidentType": {
"injury": "Kecederaan / Perubatan", "injury": "Kecederaan / Perubatan",
+5 -1
View File
@@ -18,7 +18,11 @@
"savedOffline": "报告已保存。当您重新联网时将自动提交。", "savedOffline": "报告已保存。当您重新联网时将自动提交。",
"offlineBanner": "您处于离线状态。您的报告将在重新联网时自动提交。", "offlineBanner": "您处于离线状态。您的报告将在重新联网时自动提交。",
"truckLabel": "货车", "truckLabel": "货车",
"truckPlaceholder": "选择货车…" "truckPlaceholder": "选择货车…",
"siteLabel": "场地",
"sitePlaceholder": "选择场地…",
"zoneLabel": "区域",
"zonePlaceholder": "选择区域…"
}, },
"IncidentType": { "IncidentType": {
"injury": "受伤/医疗", "injury": "受伤/医疗",
+35
View File
@@ -0,0 +1,35 @@
// @vitest-environment node
import { describe, it, expect, vi } from 'vitest'
vi.mock('@/lib/auth/get-session', () => ({
getSession: async () => ({ sub: 'owner-1', role: 'capa_owner' }),
}))
vi.mock('@/lib/db/audit', () => ({ writeAuditLog: vi.fn() }))
vi.mock('@/lib/db/with-user', () => ({
withUser: async (_id: string, fn: (tx: unknown) => unknown) =>
fn({
select: () => ({ from: () => ({ where: () => ({ limit: async () => [{ ownerUserId: 'owner-1', status: 'in_progress' }] }) }) }),
update: () => ({ set: () => ({ where: async () => undefined }) }),
}),
}))
import { PATCH } from '@/app/api/capa/[id]/route'
const ctx = { params: Promise.resolve({ id: 'capa-1' }) }
const patch = (body: unknown) =>
new Request('http://localhost/api/capa/capa-1', {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
})
describe('PATCH /api/capa/[id]', () => {
it('rejects pending_verification (must use /submit)', async () => {
const res = await PATCH(patch({ status: 'pending_verification' }) as never, ctx)
expect(res.status).toBe(403)
})
it('still allows in_progress', async () => {
const res = await PATCH(patch({ status: 'in_progress' }) as never, ctx)
expect(res.status).toBe(200)
})
})
+117
View File
@@ -0,0 +1,117 @@
// @vitest-environment node
import { describe, it, expect, vi, beforeEach } from 'vitest'
const h = vi.hoisted(() => ({
session: null as null | { sub: string; role: string },
capa: null as null | { incidentId: string; ownerUserId: string; status: string },
updates: [] as unknown[],
inserts: [] as unknown[],
updateRows: [{ id: 'capa-1' }] as unknown[],
}))
vi.mock('@/lib/auth/get-session', () => ({ getSession: async () => h.session }))
vi.mock('@/lib/db/audit', () => ({ writeAuditLog: vi.fn() }))
vi.mock('@/lib/storage/evidence', () => ({
uploadEvidenceFile: vi.fn(async () => ({ path: 'p', publicUrl: '/api/evidence/p?token=t', hash: 'h' })),
}))
vi.mock('@/lib/db/with-user', () => ({
withUser: async (_id: string, fn: (tx: unknown) => unknown) => {
const tx = {
select: () => ({ from: () => ({ where: () => ({ limit: async () => (h.capa ? [h.capa] : []) }) }) }),
insert: () => ({ values: (v: unknown) => { h.inserts.push(v); return { returning: async () => [{ id: 'ev-1' }] } } }),
update: () => ({ set: (v: unknown) => { h.updates.push(v); return { where: () => ({ returning: async () => h.updateRows }) } } }),
}
return fn(tx)
},
}))
import { writeAuditLog } from '@/lib/db/audit'
import { uploadEvidenceFile } from '@/lib/storage/evidence'
import { POST } from '@/app/api/capa/[id]/submit/route'
function req(note: string | null, fileCount: number) {
const fd = new FormData()
if (note !== null) fd.append('note', note)
for (let i = 0; i < fileCount; i++) fd.append('files', new File(['x'], `p${i}.jpg`, { type: 'image/jpeg' }))
return new Request('http://localhost/api/capa/capa-1/submit', { method: 'POST', body: fd })
}
const ctx = { params: Promise.resolve({ id: 'capa-1' }) }
beforeEach(() => {
h.session = { sub: 'owner-1', role: 'capa_owner' }
h.capa = { incidentId: 'inc-1', ownerUserId: 'owner-1', status: 'in_progress' }
h.updates = []
h.inserts = []
h.updateRows = [{ id: 'capa-1' }]
vi.mocked(writeAuditLog).mockClear()
})
describe('POST /api/capa/[id]/submit', () => {
it('401 without a session', async () => {
h.session = null
expect((await POST(req('done', 1) as never, ctx)).status).toBe(401)
})
it('404 when the CAPA does not exist', async () => {
h.capa = null
expect((await POST(req('done', 1) as never, ctx)).status).toBe(404)
})
it('403 for a user who is neither owner nor hse/admin', async () => {
h.session = { sub: 'other', role: 'reporter' }
expect((await POST(req('done', 1) as never, ctx)).status).toBe(403)
})
it('409 when status is not in_progress', async () => {
h.capa!.status = 'open'
expect((await POST(req('done', 1) as never, ctx)).status).toBe(409)
})
it('422 when no photo is attached', async () => {
const res = await POST(req('done', 0) as never, ctx)
expect(res.status).toBe(422)
expect((await res.json()).details).toContain('At least 1 photo is required')
})
it('422 when the note is empty', async () => {
expect((await POST(req(' ', 1) as never, ctx)).status).toBe(422)
})
it('stores evidence, sets status and audits on success', async () => {
const res = await POST(req(' fixed the rack ', 2) as never, ctx)
expect(res.status).toBe(200)
expect(h.inserts[0]).toEqual([
expect.objectContaining({ incidentId: 'inc-1', capaId: 'capa-1', stage: 'capa', uploadedBy: 'owner-1' }),
expect.objectContaining({ incidentId: 'inc-1', capaId: 'capa-1', stage: 'capa', uploadedBy: 'owner-1' }),
])
expect(h.updates[0]).toEqual(
expect.objectContaining({ status: 'pending_verification', ownerNotes: 'fixed the rack', completedAt: expect.any(Date) }),
)
expect(writeAuditLog).toHaveBeenCalledWith(
expect.anything(), 'capa_actions', 'capa-1', 'submitted_for_verification',
expect.objectContaining({ status: 'pending_verification' }),
expect.objectContaining({ status: 'in_progress' }),
)
})
it('409 on a lost race: no evidence insert, no audit', async () => {
h.updateRows = []
const res = await POST(req('done', 1) as never, ctx)
expect(res.status).toBe(409)
expect(h.inserts).toHaveLength(0)
expect(writeAuditLog).not.toHaveBeenCalled()
})
it('422 with details and no DB writes when upload fails', async () => {
vi.mocked(uploadEvidenceFile).mockRejectedValueOnce(new Error('disk full'))
const res = await POST(req('done', 1) as never, ctx)
expect(res.status).toBe(422)
expect((await res.json()).details).toContain('disk full')
expect(h.inserts).toHaveLength(0)
expect(h.updates).toHaveLength(0)
expect(writeAuditLog).not.toHaveBeenCalled()
})
it('200 for an hse non-owner, evidence uploadedBy is the hse user', async () => {
h.session = { sub: 'hse-1', role: 'hse' }
const res = await POST(req('done', 1) as never, ctx)
expect(res.status).toBe(200)
expect(h.inserts[0]).toEqual([expect.objectContaining({ uploadedBy: 'hse-1' })])
})
it('422 for 6 files at route level', async () => {
const res = await POST(req('done', 6) as never, ctx)
expect(res.status).toBe(422)
expect((await res.json()).details).toContain('At most 5 photos are allowed')
})
})
@@ -0,0 +1,91 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { render, screen, fireEvent, waitFor } from '@testing-library/react'
import { SubmitVerificationForm } from '@/components/capa/submit-verification-form'
const { refresh } = vi.hoisted(() => ({ refresh: vi.fn() }))
vi.mock('next/navigation', () => ({
useRouter: () => ({ refresh }),
}))
const fetchMock = vi.fn()
beforeEach(() => {
refresh.mockClear()
fetchMock.mockReset()
vi.stubGlobal('fetch', fetchMock)
})
function fill(container: HTMLElement, names: string[] = ['proof.jpg']) {
fireEvent.change(screen.getByLabelText('Completion note'), { target: { value: 'Rack fixed' } })
const input = container.querySelector('input[type="file"]') as HTMLInputElement
const files = names.map(n => new File(['x'], n, { type: 'image/jpeg' }))
fireEvent.change(input, { target: { files } })
}
function button() {
return screen.getByRole('button', { name: 'Submit for Verification' }) as HTMLButtonElement
}
describe('SubmitVerificationForm', () => {
it('is disabled until a note and a photo are provided', () => {
const { container } = render(<SubmitVerificationForm capaId="abc" />)
expect(button().disabled).toBe(true)
fireEvent.change(screen.getByLabelText('Completion note'), { target: { value: 'Rack fixed' } })
expect(button().disabled).toBe(true)
const input = container.querySelector('input[type="file"]') as HTMLInputElement
const file = new File(['x'], 'proof.jpg', { type: 'image/jpeg' })
fireEvent.change(input, { target: { files: [file] } })
expect(button().disabled).toBe(false)
expect(screen.getByText('proof.jpg')).toBeTruthy()
})
it('posts FormData on success, refreshes and stays disabled', async () => {
fetchMock.mockResolvedValue({ ok: true, json: async () => ({ ok: true }) })
const { container } = render(<SubmitVerificationForm capaId="abc" />)
fill(container)
fireEvent.click(button())
await waitFor(() => expect(refresh).toHaveBeenCalledTimes(1))
const [url, init] = fetchMock.mock.calls[0]
expect(url).toBe('/api/capa/abc/submit')
expect(init.method).toBe('POST')
const fd = init.body as FormData
expect(fd.get('note')).toBe('Rack fixed')
expect((fd.getAll('files') as File[]).map(f => f.name)).toEqual(['proof.jpg'])
expect((screen.getByRole('button', { name: 'Submitting…' }) as HTMLButtonElement).disabled).toBe(true)
})
it('shows server details and re-enables on 422', async () => {
fetchMock.mockResolvedValue({ ok: false, json: async () => ({ error: 'bad', details: ['Note too short', 'Bad photo'] }) })
const { container } = render(<SubmitVerificationForm capaId="abc" />)
fill(container)
fireEvent.click(button())
expect((await screen.findByRole('alert')).textContent).toBe('Note too short. Bad photo')
expect(button().disabled).toBe(false)
expect(refresh).not.toHaveBeenCalled()
})
it('shows a network error and re-enables when fetch rejects', async () => {
fetchMock.mockRejectedValue(new Error('offline'))
const { container } = render(<SubmitVerificationForm capaId="abc" />)
fill(container)
fireEvent.click(button())
expect((await screen.findByRole('alert')).textContent).toBe('Network error. Please try again.')
expect(button().disabled).toBe(false)
})
it('disables submit again after removing the only file', () => {
const { container } = render(<SubmitVerificationForm capaId="abc" />)
fill(container)
expect(button().disabled).toBe(false)
fireEvent.click(screen.getByLabelText('Remove proof.jpg'))
expect(button().disabled).toBe(true)
})
it('caps the list at 5 photos', () => {
const { container } = render(<SubmitVerificationForm capaId="abc" />)
fill(container, ['1.jpg', '2.jpg', '3.jpg', '4.jpg', '5.jpg', '6.jpg'])
expect(screen.getAllByText(/^\d\.jpg$/)).toHaveLength(5)
expect(screen.queryByText('6.jpg')).toBeNull()
})
})
+30
View File
@@ -0,0 +1,30 @@
import { describe, it, expect } from 'vitest'
import { validateCapaSubmission, MAX_CAPA_PHOTOS } from '@/lib/capa/submit-validation'
const img = { type: 'image/jpeg' }
describe('validateCapaSubmission', () => {
it('accepts a note with 1 image and trims the note', () => {
expect(validateCapaSubmission(' done ', [img])).toEqual({ ok: true, note: 'done' })
})
it('rejects an empty or whitespace note', () => {
const r = validateCapaSubmission(' ', [img])
expect(r.ok).toBe(false)
if (!r.ok) expect(r.errors).toContain('Completion note is required')
})
it('rejects zero files', () => {
const r = validateCapaSubmission('done', [])
expect(r.ok).toBe(false)
if (!r.ok) expect(r.errors).toContain('At least 1 photo is required')
})
it('rejects more than the max', () => {
const r = validateCapaSubmission('done', Array(MAX_CAPA_PHOTOS + 1).fill(img))
expect(r.ok).toBe(false)
if (!r.ok) expect(r.errors).toContain(`At most ${MAX_CAPA_PHOTOS} photos are allowed`)
})
it('rejects non-image files', () => {
const r = validateCapaSubmission('done', [{ type: 'application/pdf' }])
expect(r.ok).toBe(false)
if (!r.ok) expect(r.errors).toContain('Only image files are allowed')
})
})
+46
View File
@@ -0,0 +1,46 @@
import { describe, it, expect } from 'vitest'
import { groupSites, zonesForSite, resolveZoneToken, type ZoneRow } from '@/lib/report/zones'
const rows: ZoneRow[] = [
{ siteId: 's1', siteName: 'SC1', zoneId: 'z1', zoneName: 'Dock A', token: 'tok-a' },
{ siteId: 's1', siteName: 'SC1', zoneId: 'z2', zoneName: 'Dock B', token: 'tok-b' },
{ siteId: 's2', siteName: 'SC2', zoneId: 'z3', zoneName: 'Cold Room', token: 'tok-c' },
]
describe('groupSites', () => {
it('groups zone rows under their site, keeping order', () => {
const sites = groupSites(rows)
expect(sites.map(s => s.name)).toEqual(['SC1', 'SC2'])
expect(sites[0].zones.map(z => z.name)).toEqual(['Dock A', 'Dock B'])
expect(sites[1].zones[0]).toEqual({ id: 'z3', name: 'Cold Room', qr_code_token: 'tok-c' })
})
it('returns [] for no rows', () => {
expect(groupSites([])).toEqual([])
})
})
describe('zonesForSite', () => {
const sites = groupSites(rows)
it('returns the zones of the given site', () => {
expect(zonesForSite(sites, 's2').map(z => z.id)).toEqual(['z3'])
})
it('returns [] for an unknown or empty site id', () => {
expect(zonesForSite(sites, 'nope')).toEqual([])
expect(zonesForSite(sites, '')).toEqual([])
})
})
describe('resolveZoneToken', () => {
const sites = groupSites(rows)
it('prefers the QR token', () => {
expect(resolveZoneToken({ zoneToken: 'qr-1', sites, zoneId: 'z1' })).toBe('qr-1')
})
it('falls back to the selected zone token', () => {
expect(resolveZoneToken({ zoneToken: null, sites, zoneId: 'z2' })).toBe('tok-b')
})
it('returns null when nothing is chosen or the zone is unknown', () => {
expect(resolveZoneToken({ zoneToken: null, sites, zoneId: '' })).toBeNull()
expect(resolveZoneToken({ zoneToken: null, sites, zoneId: 'zz' })).toBeNull()
})
})