fix(capa): handle network errors, keep form locked after submit, extend tests
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -61,7 +61,7 @@ export default async function CapaDetailPage({ params }: Props) {
|
|||||||
if (!capa) notFound()
|
if (!capa) notFound()
|
||||||
|
|
||||||
const photos = await asAdmin(db =>
|
const photos = await asAdmin(db =>
|
||||||
db.select({ id: evidenceFiles.id, fileUrl: evidenceFiles.fileUrl, fileType: evidenceFiles.fileType })
|
db.select({ id: evidenceFiles.id, fileUrl: evidenceFiles.fileUrl })
|
||||||
.from(evidenceFiles)
|
.from(evidenceFiles)
|
||||||
.where(and(eq(evidenceFiles.capaId, id), eq(evidenceFiles.deleted, false)))
|
.where(and(eq(evidenceFiles.capaId, id), eq(evidenceFiles.deleted, false)))
|
||||||
.orderBy(asc(evidenceFiles.uploadedAt))
|
.orderBy(asc(evidenceFiles.uploadedAt))
|
||||||
@@ -122,11 +122,11 @@ export default async function CapaDetailPage({ params }: Props) {
|
|||||||
)}
|
)}
|
||||||
{photos.length > 0 && (
|
{photos.length > 0 && (
|
||||||
<ul className="grid grid-cols-2 gap-2 sm:grid-cols-3">
|
<ul className="grid grid-cols-2 gap-2 sm:grid-cols-3">
|
||||||
{photos.map(p => (
|
{photos.map((p, i) => (
|
||||||
<li key={p.id}>
|
<li key={p.id}>
|
||||||
<a href={p.fileUrl} target="_blank" rel="noreferrer" className="block overflow-hidden rounded-md shadow-card">
|
<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 */}
|
{/* eslint-disable-next-line @next/next/no-img-element */}
|
||||||
<img src={p.fileUrl} alt="CAPA completion evidence" className="aspect-square w-full object-cover" />
|
<img src={p.fileUrl} alt={`CAPA completion evidence ${i + 1} of ${photos.length}`} className="aspect-square w-full object-cover" />
|
||||||
</a>
|
</a>
|
||||||
</li>
|
</li>
|
||||||
))}
|
))}
|
||||||
|
|||||||
@@ -38,12 +38,15 @@ export function SubmitVerificationForm({ capaId }: Props) {
|
|||||||
if (!res.ok) {
|
if (!res.ok) {
|
||||||
const data = await res.json().catch(() => ({}))
|
const data = await res.json().catch(() => ({}))
|
||||||
setError(Array.isArray(data.details) ? data.details.join('. ') : (data.error ?? 'Submit failed. Please try again.'))
|
setError(Array.isArray(data.details) ? data.details.join('. ') : (data.error ?? 'Submit failed. Please try again.'))
|
||||||
|
setLoading(false)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
router.refresh()
|
router.refresh()
|
||||||
} finally {
|
return
|
||||||
setLoading(false)
|
} catch {
|
||||||
|
setError('Network error. Please try again.')
|
||||||
}
|
}
|
||||||
|
setLoading(false)
|
||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
|
|||||||
@@ -1,11 +1,26 @@
|
|||||||
import { describe, it, expect, vi } from 'vitest'
|
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||||
import { render, screen, fireEvent } from '@testing-library/react'
|
import { render, screen, fireEvent, waitFor } from '@testing-library/react'
|
||||||
import { SubmitVerificationForm } from '@/components/capa/submit-verification-form'
|
import { SubmitVerificationForm } from '@/components/capa/submit-verification-form'
|
||||||
|
|
||||||
|
const { refresh } = vi.hoisted(() => ({ refresh: vi.fn() }))
|
||||||
vi.mock('next/navigation', () => ({
|
vi.mock('next/navigation', () => ({
|
||||||
useRouter: () => ({ refresh: vi.fn() }),
|
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() {
|
function button() {
|
||||||
return screen.getByRole('button', { name: 'Submit for Verification' }) as HTMLButtonElement
|
return screen.getByRole('button', { name: 'Submit for Verification' }) as HTMLButtonElement
|
||||||
}
|
}
|
||||||
@@ -24,4 +39,53 @@ describe('SubmitVerificationForm', () => {
|
|||||||
expect(button().disabled).toBe(false)
|
expect(button().disabled).toBe(false)
|
||||||
expect(screen.getByText('proof.jpg')).toBeTruthy()
|
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()
|
||||||
|
})
|
||||||
})
|
})
|
||||||
|
|||||||
Reference in New Issue
Block a user