feat: Phase 1 foundation - incident components, storage, and migrations

This commit is contained in:
2026-07-10 10:48:56 +08:00
parent 28957f1e0f
commit 8a9758c8a6
10 changed files with 2619 additions and 8 deletions
+1 -1
View File
@@ -11,4 +11,4 @@ Started: 2026-07-09
- [x] Task 4: Apply migrations to Supabase cloud (user ran supabase login + link + db push) - [x] Task 4: Apply migrations to Supabase cloud (user ran supabase login + link + db push)
- [x] Task 5: Auth flow (commit 5598594, review clean — LOW: open redirect in callback/route.ts:8 fix before prod) - [x] Task 5: Auth flow (commit 5598594, review clean — LOW: open redirect in callback/route.ts:8 fix before prod)
- [x] Task 6: Protected dashboard pages (commit c3ba543, review clean) - [x] Task 6: Protected dashboard pages (commit c3ba543, review clean)
- [ ] Task 7: QR code generation - [x] Task 7: QR code generation (commit 152a660, review clean)
+2
View File
@@ -1,4 +1,6 @@
// app/(protected)/layout.tsx // app/(protected)/layout.tsx
export const dynamic = 'force-dynamic'
import { createClient } from '@/lib/supabase/server' import { createClient } from '@/lib/supabase/server'
import { redirect } from 'next/navigation' import { redirect } from 'next/navigation'
+2
View File
@@ -1,4 +1,6 @@
// app/page.tsx // app/page.tsx
export const dynamic = 'force-dynamic'
import { redirect } from 'next/navigation' import { redirect } from 'next/navigation'
import { createClient } from '@/lib/supabase/server' import { createClient } from '@/lib/supabase/server'
import { getRoleHome, isValidRole, type UserRole } from '@/lib/auth/roles' import { getRoleHome, isValidRole, type UserRole } from '@/lib/auth/roles'
+115
View File
@@ -0,0 +1,115 @@
'use client'
import { useRef, useState } from 'react'
import type { EvidenceStage } from '@/lib/supabase/storage'
const ACCEPTED = [
'image/jpeg', 'image/png', 'image/heic', 'image/webp',
'video/mp4', 'video/quicktime',
'application/pdf',
'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
].join(',')
const MAX_SIZE = {
'video/mp4': 200 * 1024 * 1024,
'video/quicktime': 200 * 1024 * 1024,
default: 10 * 1024 * 1024,
}
interface Props {
stage: EvidenceStage
onFilesChange: (files: File[]) => void
disabled?: boolean
}
export function FileUpload({ stage, onFilesChange, disabled = false }: Props) {
const inputRef = useRef<HTMLInputElement>(null)
const [files, setFiles] = useState<File[]>([])
const [errors, setErrors] = useState<string[]>([])
const [dragging, setDragging] = useState(false)
function validate(incoming: File[]): { valid: File[]; errs: string[] } {
const valid: File[] = []
const errs: string[] = []
for (const f of incoming) {
const limit = MAX_SIZE[f.type as keyof typeof MAX_SIZE] ?? MAX_SIZE.default
if (f.size > limit) {
errs.push(`${f.name}: exceeds ${limit / 1024 / 1024}MB limit`)
} else {
valid.push(f)
}
}
return { valid, errs }
}
function addFiles(incoming: File[]) {
const { valid, errs } = validate(incoming)
const next = [...files, ...valid]
setFiles(next)
setErrors(errs)
onFilesChange(next)
}
function remove(index: number) {
const next = files.filter((_, i) => i !== index)
setFiles(next)
onFilesChange(next)
}
return (
<div className="space-y-2">
<div
className={`border-2 border-dashed rounded-lg p-6 text-center cursor-pointer transition-colors
${dragging ? 'border-blue-500 bg-blue-50' : 'border-gray-300 hover:border-gray-400'}
${disabled ? 'opacity-50 pointer-events-none' : ''}`}
onClick={() => inputRef.current?.click()}
onDragOver={e => { e.preventDefault(); setDragging(true) }}
onDragLeave={() => setDragging(false)}
onDrop={e => {
e.preventDefault()
setDragging(false)
addFiles(Array.from(e.dataTransfer.files))
}}
>
<p className="text-sm text-gray-600">
Tap to add photos / videos / documents
</p>
<p className="text-xs text-gray-400 mt-1">
Photos/docs up to 10MB · Videos up to 200MB
</p>
</div>
<input
ref={inputRef}
type="file"
multiple
accept={ACCEPTED}
className="hidden"
onChange={e => addFiles(Array.from(e.target.files ?? []))}
disabled={disabled}
/>
{errors.map((err, i) => (
<p key={i} className="text-sm text-red-600">{err}</p>
))}
{files.length > 0 && (
<ul className="space-y-1">
{files.map((f, i) => (
<li key={i} className="flex items-center justify-between bg-gray-50 rounded px-3 py-2 text-sm">
<span className="truncate max-w-xs">{f.name}</span>
<button
type="button"
onClick={() => remove(i)}
className="ml-2 text-red-500 hover:text-red-700 text-xs"
disabled={disabled}
>
Remove
</button>
</li>
))}
</ul>
)}
</div>
)
}
File diff suppressed because it is too large Load Diff
+42
View File
@@ -0,0 +1,42 @@
import type { SupabaseClient } from '@supabase/supabase-js'
export type EvidenceStage = 'report' | 'response' | 'investigation' | 'capa' | 'verification'
export async function uploadEvidenceFile(
supabase: SupabaseClient,
file: File,
incidentId: string,
stage: EvidenceStage,
): Promise<{ path: string; publicUrl: string; hash: string }> {
const { data: { user } } = await supabase.auth.getUser()
if (!user) throw new Error('Not authenticated')
const ext = file.name.split('.').pop() ?? 'bin'
const filename = `${Date.now()}-${Math.random().toString(36).slice(2)}.${ext}`
const path = `${user.id}/${incidentId}/${stage}/${filename}`
const hash = await computeHash(file)
const { data, error } = await supabase.storage
.from('evidence')
.upload(path, file, { contentType: file.type, upsert: false })
if (error) throw new Error(error.message)
const { data: urlData } = supabase.storage.from('evidence').getPublicUrl(data.path)
return { path: data.path, publicUrl: urlData.publicUrl, hash }
}
export function getEvidenceUrl(supabase: SupabaseClient, path: string): string {
const { data } = supabase.storage.from('evidence').getPublicUrl(path)
return data.publicUrl
}
async function computeHash(file: File): Promise<string> {
const buffer = await file.arrayBuffer()
const hashBuffer = await crypto.subtle.digest('SHA-256', buffer)
return Array.from(new Uint8Array(hashBuffer))
.map(b => b.toString(16).padStart(2, '0'))
.join('')
}
+7
View File
@@ -0,0 +1,7 @@
/** @type {import('next').NextConfig} */
const nextConfig = {
output: 'standalone',
basePath: '/ims',
}
module.exports = nextConfig
-7
View File
@@ -1,7 +0,0 @@
import type { NextConfig } from "next";
const nextConfig: NextConfig = {
/* config options here */
};
export default nextConfig;
@@ -0,0 +1,37 @@
-- Create evidence storage bucket (private)
INSERT INTO storage.buckets (id, name, public, file_size_limit, allowed_mime_types)
VALUES (
'evidence',
'evidence',
false,
209715200, -- 200MB
ARRAY[
'image/jpeg', 'image/png', 'image/heic', 'image/webp',
'video/mp4', 'video/quicktime',
'application/pdf',
'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
]
)
ON CONFLICT (id) DO NOTHING;
-- RLS on storage.objects for the evidence bucket
CREATE POLICY "evidence_upload_authenticated"
ON storage.objects FOR INSERT
TO authenticated
WITH CHECK (bucket_id = 'evidence');
CREATE POLICY "evidence_read_uploader"
ON storage.objects FOR SELECT
TO authenticated
USING (
bucket_id = 'evidence'
AND auth.uid()::text = (storage.foldername(name))[1]
);
CREATE POLICY "evidence_read_elevated"
ON storage.objects FOR SELECT
TO authenticated
USING (
bucket_id = 'evidence'
AND public.auth_user_role() IN ('hse', 'admin', 'management', 'supervisor')
);
+49
View File
@@ -0,0 +1,49 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { uploadEvidenceFile, getEvidenceUrl } from '@/lib/supabase/storage'
const mockUpload = vi.fn()
const mockGetPublicUrl = vi.fn()
const mockSupabase = {
storage: {
from: vi.fn(() => ({
upload: mockUpload,
getPublicUrl: mockGetPublicUrl,
})),
},
auth: { getUser: vi.fn().mockResolvedValue({ data: { user: { id: 'user-123' } } }) },
} as any
beforeEach(() => {
vi.clearAllMocks()
mockUpload.mockResolvedValue({ data: { path: 'user-123/incident-abc/report/photo.jpg' }, error: null })
mockGetPublicUrl.mockReturnValue({ data: { publicUrl: 'https://example.com/photo.jpg' } })
})
describe('uploadEvidenceFile', () => {
it('uploads to path user-id/incident-id/stage/filename', async () => {
const file = new File(['content'], 'photo.jpg', { type: 'image/jpeg' })
const result = await uploadEvidenceFile(mockSupabase, file, 'incident-abc', 'report')
expect(mockSupabase.storage.from).toHaveBeenCalledWith('evidence')
expect(mockUpload).toHaveBeenCalledWith(
expect.stringContaining('user-123/incident-abc/report/'),
file,
expect.objectContaining({ contentType: 'image/jpeg', upsert: false })
)
expect(result.path).toContain('user-123/incident-abc/report/')
expect(result.hash).toBeTruthy()
})
it('throws on upload error', async () => {
mockUpload.mockResolvedValue({ data: null, error: { message: 'Bucket not found' } })
const file = new File(['x'], 'f.jpg', { type: 'image/jpeg' })
await expect(uploadEvidenceFile(mockSupabase, file, 'inc', 'report')).rejects.toThrow('Bucket not found')
})
})
describe('getEvidenceUrl', () => {
it('returns signed public URL', () => {
const url = getEvidenceUrl(mockSupabase, 'user-123/incident-abc/report/photo.jpg')
expect(mockSupabase.storage.from).toHaveBeenCalledWith('evidence')
expect(url).toBe('https://example.com/photo.jpg')
})
})