diff --git a/app/(protected)/hse/capa/[id]/page.tsx b/app/(protected)/hse/capa/[id]/page.tsx index e086cb4..d2086f1 100644 --- a/app/(protected)/hse/capa/[id]/page.tsx +++ b/app/(protected)/hse/capa/[id]/page.tsx @@ -5,8 +5,8 @@ import Link from 'next/link' import { ArrowLeft } from 'lucide-react' import { asAdmin } from '@/lib/db/with-user' import { getSession } from '@/lib/auth/get-session' -import { capaActions, incidents, users } from '@/lib/db/schema' -import { eq } from 'drizzle-orm' +import { capaActions, evidenceFiles, incidents, users } from '@/lib/db/schema' +import { eq, and, asc } from 'drizzle-orm' import { aliasedTable } from 'drizzle-orm' import { VerifyForm } from '@/components/capa/verify-form' import { CloseCapaButton } from '@/components/capa/close-capa-button' @@ -60,6 +60,13 @@ export default async function CapaDetailPage({ params }: Props) { 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 status = capa.status const today = new Date().toISOString().slice(0, 10) @@ -102,7 +109,7 @@ export default async function CapaDetailPage({ params }: Props) { {isHse && status === 'pending_verification' && } {isHse && status === 'verified' && } - {(capa.ownerNotes || capa.completedAt) && ( + {(capa.ownerNotes || capa.completedAt || photos.length > 0) && (

Completion report

{capa.completedAt && ( @@ -113,6 +120,18 @@ export default async function CapaDetailPage({ params }: Props) { {capa.ownerNotes && (

{capa.ownerNotes}

)} + {photos.length > 0 && ( + + )}
)} diff --git a/app/api/capa/[id]/route.ts b/app/api/capa/[id]/route.ts index a9ae2ed..e148f11 100644 --- a/app/api/capa/[id]/route.ts +++ b/app/api/capa/[id]/route.ts @@ -105,6 +105,13 @@ export async function PATCH( 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'] if (body.status && privilegedStatuses.includes(body.status) && !['hse', 'admin'].includes(role)) { 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 ('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 (body.status === 'pending_verification') updateSet.completedAt = new Date() // Build audit new/old value from original snake_case body keys for consistency const auditNew: Record = {} for (const key of allowed) { 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 => { let oldNotes: string | null = null diff --git a/app/api/capa/[id]/submit/route.ts b/app/api/capa/[id]/submit/route.ts new file mode 100644 index 0000000..c1a236a --- /dev/null +++ b/app/api/capa/[id]/submit/route.ts @@ -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 }) +} diff --git a/app/report/page.tsx b/app/report/page.tsx index 5dab647..f3c0f67 100644 --- a/app/report/page.tsx +++ b/app/report/page.tsx @@ -3,8 +3,9 @@ export const dynamic = 'force-dynamic' import { redirect } from 'next/navigation' import { asAdmin } from '@/lib/db/with-user' import { getSession } from '@/lib/auth/get-session' -import { zones, sites, trucks } from '@/lib/db/schema' -import { eq, asc } from 'drizzle-orm' +import { zones, sites, trucks, users } from '@/lib/db/schema' +import { eq, asc, and } from 'drizzle-orm' +import { groupSites } from '@/lib/report/zones' import { ReportForm } from '@/components/incidents/report-form' import { LanguageSwitcher } from '@/components/language-switcher' import { OfflineSync } from '@/components/incidents/offline-sync' @@ -55,6 +56,26 @@ export default async function ReportPage({ searchParams }: Props) { 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 (
@@ -62,18 +83,18 @@ export default async function ReportPage({ searchParams }: Props) {

{/* will be translated via ReportForm */}Report an Incident

- {zoneName ? ( + {zoneName && (

{siteName ?? 'Unknown Site'} — {zoneName}

- ) : ( -

No zone detected — zone will not be recorded

)} diff --git a/components/capa/capa-owner-actions.tsx b/components/capa/capa-owner-actions.tsx index e2d33ed..4e70872 100644 --- a/components/capa/capa-owner-actions.tsx +++ b/components/capa/capa-owner-actions.tsx @@ -3,6 +3,7 @@ import { useState } from 'react' import { useRouter } from 'next/navigation' import { Button } from '@/components/ui/button' +import { SubmitVerificationForm } from '@/components/capa/submit-verification-form' interface Props { capaId: string @@ -41,11 +42,7 @@ export function CapaOwnerActions({ capaId, currentStatus }: Props) { } if (currentStatus === 'in_progress') { - return ( - - ) + return } return null diff --git a/components/capa/submit-verification-form.tsx b/components/capa/submit-verification-form.tsx new file mode 100644 index 0000000..6fa10f0 --- /dev/null +++ b/components/capa/submit-verification-form.tsx @@ -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([]) + const [loading, setLoading] = useState(false) + const [error, setError] = useState(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 ( +
+
+

Proof of completion

+

Describe what was done and attach 1 to {MAX_CAPA_PHOTOS} photos as evidence.

+
+ + +