From 670e5f8348078fbecade5698161ccdf8a5292360 Mon Sep 17 00:00:00 2001 From: bigben-7 Date: Fri, 20 Nov 2026 07:49:23 +0100 Subject: [PATCH] Real upload progress, Socket.IO document status, remove unused document components --- .../(protected)/documents/[id]/page.tsx | 49 ++--- .../documents/[id]/verify/page.tsx | 167 +++++++----------- .../(protected)/documents/upload/page.tsx | 63 ++++--- .../components/documents/DocumentHeader.tsx | 33 ---- .../components/documents/DocumentMetadata.tsx | 62 ------- .../documents/EmptyAnalysisState.tsx | 9 - .../components/documents/ReportLinkCard.tsx | 18 -- frontend/components/documents/RiskSummary.tsx | 78 -------- .../components/documents/StatusTimeline.tsx | 52 ------ .../documents/VerificationNotice.tsx | 11 -- .../documents/VerifyOnStellarButton.tsx | 27 --- frontend/components/ui/ReferenceCard.tsx | 21 --- .../ui/__tests__/reference-card.test.tsx | 61 ------- frontend/hooks/useDocument.ts | 25 --- frontend/hooks/useDocumentStatusSocket.ts | 57 ++++++ frontend/hooks/useVerifyDocument.ts | 14 -- frontend/lib/__tests__/upload-xhr.test.ts | 72 ++++++++ frontend/lib/upload-xhr.ts | 70 ++++++++ frontend/messages/en.json | 3 +- frontend/messages/es.json | 3 +- frontend/messages/fr.json | 3 +- frontend/package.json | 1 + frontend/src/components/upload/DropZone.tsx | 71 -------- frontend/src/hooks/useDocumentStatusSocket.ts | 41 ----- frontend/src/lib/upload-progress.ts | 46 ----- 25 files changed, 324 insertions(+), 733 deletions(-) delete mode 100644 frontend/components/documents/DocumentHeader.tsx delete mode 100644 frontend/components/documents/DocumentMetadata.tsx delete mode 100644 frontend/components/documents/EmptyAnalysisState.tsx delete mode 100644 frontend/components/documents/ReportLinkCard.tsx delete mode 100644 frontend/components/documents/RiskSummary.tsx delete mode 100644 frontend/components/documents/StatusTimeline.tsx delete mode 100644 frontend/components/documents/VerificationNotice.tsx delete mode 100644 frontend/components/documents/VerifyOnStellarButton.tsx delete mode 100644 frontend/components/ui/ReferenceCard.tsx delete mode 100644 frontend/components/ui/__tests__/reference-card.test.tsx delete mode 100644 frontend/hooks/useDocument.ts create mode 100644 frontend/hooks/useDocumentStatusSocket.ts delete mode 100644 frontend/hooks/useVerifyDocument.ts create mode 100644 frontend/lib/__tests__/upload-xhr.test.ts create mode 100644 frontend/lib/upload-xhr.ts delete mode 100644 frontend/src/components/upload/DropZone.tsx delete mode 100644 frontend/src/hooks/useDocumentStatusSocket.ts delete mode 100644 frontend/src/lib/upload-progress.ts diff --git a/frontend/app/[locale]/(protected)/documents/[id]/page.tsx b/frontend/app/[locale]/(protected)/documents/[id]/page.tsx index b023f76c..4fd48c19 100644 --- a/frontend/app/[locale]/(protected)/documents/[id]/page.tsx +++ b/frontend/app/[locale]/(protected)/documents/[id]/page.tsx @@ -1,5 +1,6 @@ "use client"; +import { useDocumentStatusSocket } from "@/hooks/useDocumentStatusSocket"; import React, { useCallback, useEffect, useRef, useState } from "react"; import { useParams } from "next/navigation"; import { useTranslations } from "next-intl"; @@ -20,7 +21,6 @@ import { // Configuration // ───────────────────────────────────────────────────────────────────────────── -const WS_BASE = (process.env.NEXT_PUBLIC_WS_URL ?? "ws://localhost:3001").replace(/^http/, "ws"); // ───────────────────────────────────────────────────────────────────────────── // Types @@ -277,34 +277,6 @@ export default function DocumentDetailPage() { const [savingLocation, setSavingLocation] = useState(false); const [locationError, setLocationError] = useState(null); - // ── WebSocket for real-time status updates (FE-06) ────────────────────── - const wsRef = useRef(null); - - const setupWebSocket = useCallback(() => { - if (!docId || typeof window === "undefined") return; - const ws = new WebSocket(`${WS_BASE}/documents/${docId}/status`); - wsRef.current = ws; - - ws.onmessage = (event) => { - try { - const payload = JSON.parse(event.data) as { status?: DocumentStatus }; - if (payload.status) { - setDoc((prev) => prev ? { ...prev, status: payload.status as DocumentStatus } : prev); - } - } catch { - // malformed message — ignore - } - }; - - ws.onerror = () => ws.close(); - ws.onclose = () => { - // Reconnect after 5 s (simple back-off) - setTimeout(setupWebSocket, 5000); - }; - - return () => ws.close(); - }, [docId]); - // ── Fetch document + risk data ───────────────────────────────────────── const fetchData = useCallback(async () => { if (!docId) return; @@ -336,13 +308,18 @@ export default function DocumentDetailPage() { fetchData(); }, [fetchData]); - useEffect(() => { - const cleanup = setupWebSocket(); - return () => { - cleanup?.(); - wsRef.current?.close(); - }; - }, [setupWebSocket]); + // ── Live status updates over Socket.IO (#1643) ────────────────────────── + // The detail page updates without a reload when the backend moves the + // document through PENDING -> ANALYZING -> VERIFIED/FLAGGED, and refetches + // the risk data on every change. + useDocumentStatusSocket(docId, { + onStatus: (event) => { + setDoc((prev) => + prev ? { ...prev, status: event.status.toUpperCase() as DocumentStatus } : prev, + ); + void fetchData(); + }, + }); // ── Verify on Stellar ────────────────────────────────────────────────── async function handleVerify() { diff --git a/frontend/app/[locale]/(protected)/documents/[id]/verify/page.tsx b/frontend/app/[locale]/(protected)/documents/[id]/verify/page.tsx index e3170cb1..971cd0e5 100644 --- a/frontend/app/[locale]/(protected)/documents/[id]/verify/page.tsx +++ b/frontend/app/[locale]/(protected)/documents/[id]/verify/page.tsx @@ -8,14 +8,7 @@ import { useDateFormatting } from "@/i18n/formatting"; import { ApiError, request } from "@/lib/api-client"; import { apiUrl } from "@/lib/api-config"; import { stellarTxUrl } from "@/lib/stellar"; - -// ───────────────────────────────────────────────────────────────────────────── -// Configuration -// ───────────────────────────────────────────────────────────────────────────── - -const WS_BASE = ( - process.env.NEXT_PUBLIC_WS_URL ?? "ws://localhost:3001" -).replace(/^http/, "ws"); +import { useDocumentStatusSocket } from "@/hooks/useDocumentStatusSocket"; // ───────────────────────────────────────────────────────────────────────────── // Types @@ -54,24 +47,6 @@ function truncateHash(hash: string, chars = 10): string { // Sub-components // ───────────────────────────────────────────────────────────────────────────── -/** Thin animated progress bar. */ -function ProgressBar({ value }: { value: number }) { - return ( -
-
-
- ); -} - /** Copyable text field. */ function CopyField({ label, @@ -203,13 +178,7 @@ function PreVerification({ // Processing state // ───────────────────────────────────────────────────────────────────────────── -function ProcessingView({ - progress, - statusMsg, -}: { - progress: number; - statusMsg: string; -}) { +function ProcessingView({ statusMsg }: { statusMsg: string }) { return (
{statusMsg}

- -

{progress}%

+ {/* Indeterminate: the job reports no percentage, so none is faked. */} +
); @@ -433,13 +407,13 @@ export default function VerifyPage() { const [viewState, setViewState] = useState("pre"); const [anchoring, setAnchoring] = useState(false); const [anchorError, setAnchorError] = useState(null); - const [progress, setProgress] = useState(0); const [statusMsg, setStatusMsg] = useState(() => t("submitting")); const [verification, setVerification] = useState( null, ); - const wsRef = useRef(null); + const pollTimer = useRef | null>(null); + const finished = useRef(false); // ── Fetch document metadata ──────────────────────────────────────────── useEffect(() => { @@ -464,34 +438,6 @@ export default function VerifyPage() { .finally(() => setPageLoading(false)); }, [docId, router, t]); - // ── WebSocket progress handler ───────────────────────────────────────── - const connectProgressWs = useCallback(() => { - if (!docId || typeof window === "undefined") return; - const ws = new WebSocket(`${WS_BASE}/documents/${docId}/verify/progress`); - wsRef.current = ws; - - ws.onmessage = (event) => { - try { - const payload = JSON.parse(event.data) as { - progress?: number; - message?: string; - status?: string; - }; - if (payload.progress !== undefined) setProgress(payload.progress); - if (payload.message) setStatusMsg(payload.message); - if (payload.status === "VERIFIED") { - ws.close(); - // Fetch final verification record - fetchVerification(); - } - } catch { - // ignore malformed messages - } - }; - - ws.onerror = () => ws.close(); - }, [docId]); // eslint-disable-line react-hooks/exhaustive-deps - // ── Fetch verification record after anchoring ────────────────────────── const fetchVerification = useCallback(async () => { if (!docId) return; @@ -513,50 +459,64 @@ export default function VerifyPage() { }, [docId, t]); // ── Anchor handler ───────────────────────────────────────────────────── + // Completion comes from the Socket.IO event below; polling with backoff is + // only the fallback, so the page reflects the real job outcome however long + // anchoring takes. + const finishVerification = useCallback(async () => { + if (finished.current) return; + finished.current = true; + if (pollTimer.current) clearTimeout(pollTimer.current); + await fetchVerification(); + }, [fetchVerification]); + + const startPolling = useCallback(() => { + if (!docId) return; + let attempt = 0; + const MAX_ATTEMPTS = 12; + const poll = async () => { + if (finished.current) return; + attempt += 1; + try { + const data = await request( + documentPath(docId, "/verification"), + ); + if (data?.transactionHash) { + finished.current = true; + setVerification(data); + setViewState("post"); + return; + } + } catch { + // Not anchored yet (404) or a transient error: keep waiting. + } + if (attempt >= MAX_ATTEMPTS) { + setStatusMsg(t("stillProcessing")); + return; + } + pollTimer.current = setTimeout(poll, Math.min(2000 * 2 ** (attempt - 1), 30000)); + }; + pollTimer.current = setTimeout(poll, 2000); + }, [docId, t]); + + useDocumentStatusSocket(viewState === "processing" ? docId : null, { + onVerification: (event) => { + if (event.status === "confirmed" || event.status === "failed") { + void finishVerification(); + } + }, + }); + async function handleAnchor() { if (!docId) return; setAnchoring(true); setAnchorError(null); - setProgress(0); setStatusMsg(t("submitting")); + finished.current = false; try { await request(documentPath(docId, "/verify"), { method: "POST" }); - - // Switch to processing view and open WS for real-time updates setViewState("processing"); - connectProgressWs(); - - // Simulate progress advancement when WS is unavailable - const interval = setInterval(() => { - setProgress((prev) => { - if (prev >= 90) { - clearInterval(interval); - return prev; - } - return prev + 10; - }); - }, 800); - - // Poll for completion (fallback when WS is not available) - const poll = async () => { - await new Promise((r) => setTimeout(r, 8000)); - const data = await request( - documentPath(docId, "/verification"), - ); - clearInterval(interval); - setProgress(100); - setVerification(data); - setViewState("post"); - wsRef.current?.close(); - }; - - poll().catch(() => { - // WS/poll failed — move to post with partial info - clearInterval(interval); - setProgress(100); - fetchVerification(); - }); + startPolling(); } catch { setAnchorError(t("anchorError")); setAnchoring(false); @@ -565,7 +525,10 @@ export default function VerifyPage() { // ── Cleanup ──────────────────────────────────────────────────────────── useEffect(() => { - return () => wsRef.current?.close(); + return () => { + finished.current = true; + if (pollTimer.current) clearTimeout(pollTimer.current); + }; }, []); // ── Render ───────────────────────────────────────────────────────────── @@ -650,7 +613,7 @@ export default function VerifyPage() { /> )} {viewState === "processing" && ( - + )} {viewState === "post" && verification && ( diff --git a/frontend/app/[locale]/(protected)/documents/upload/page.tsx b/frontend/app/[locale]/(protected)/documents/upload/page.tsx index 0a2d1d83..5a25fd14 100644 --- a/frontend/app/[locale]/(protected)/documents/upload/page.tsx +++ b/frontend/app/[locale]/(protected)/documents/upload/page.tsx @@ -2,7 +2,12 @@ import React, { useState, useRef } from "react"; import { useRouter } from "next/navigation"; -import { request } from "@/lib/api-client"; +import { getAccessToken } from "@/lib/session"; +import { + UploadAbortedError, + uploadWithProgress, + type UploadHandle, +} from "@/lib/upload-xhr"; import { apiUrl } from "@/lib/api-config"; import { documentUploadConstraints, @@ -25,6 +30,7 @@ export default function DocumentUploadPage() { const [error, setError] = useState(""); const [uploading, setUploading] = useState(false); const [progress, setProgress] = useState(0); + const uploadRef = useRef | null>(null); const [isDragOver, setIsDragOver] = useState(false); function validateFile(file: File): string | null { @@ -130,7 +136,7 @@ export default function DocumentUploadPage() { } setUploading(true); - setProgress(10); + setProgress(0); setError(""); try { @@ -142,26 +148,27 @@ export default function DocumentUploadPage() { formData.append("longitude", longitude.trim()); } - // Simulated upload progress - const interval = setInterval(() => { - setProgress((prev) => (prev >= 90 ? prev : prev + 20)); - }, 200); - - try { - const data = await request<{ id?: string; documentId?: string }>( - apiUrl("/documents/upload"), - { method: "POST", body: formData }, - ); - setProgress(100); - const docId = data?.id ?? data?.documentId ?? "new-doc-id"; - setTimeout(() => { - router.push(`/documents/${docId}`); - }, 500); - } finally { - clearInterval(interval); - } - } catch { - setError("Failed to upload document. Please try again."); + // Real progress (bytes sent), cancellable (#1641). + const upload = uploadWithProgress<{ id?: string; documentId?: string }>( + apiUrl("/documents/upload"), + formData, + { token: getAccessToken(), onProgress: setProgress }, + ); + uploadRef.current = upload; + const data = await upload.promise; + uploadRef.current = null; + const docId = data?.id ?? data?.documentId ?? "new-doc-id"; + setTimeout(() => { + router.push(`/documents/${docId}`); + }, 500); + } catch (err) { + uploadRef.current = null; + setError( + err instanceof UploadAbortedError + ? "Upload cancelled." + : "Failed to upload document. Please try again.", + ); + setProgress(0); } finally { setUploading(false); } @@ -290,6 +297,10 @@ export default function DocumentUploadPage() {
@@ -300,7 +311,13 @@ export default function DocumentUploadPage() {
- - ); -} \ No newline at end of file diff --git a/frontend/components/documents/RiskSummary.tsx b/frontend/components/documents/RiskSummary.tsx deleted file mode 100644 index bce03acb..00000000 --- a/frontend/components/documents/RiskSummary.tsx +++ /dev/null @@ -1,78 +0,0 @@ -'use client'; - -interface RiskSummaryProps { - score: number | null; - flags: string[] | null; -} - -export function RiskSummary({ score, flags }: RiskSummaryProps) { - if (score === null) { - return ( -
-

Risk analysis not yet available.

-
- ); - } - - const getRiskColor = (score: number) => { - if (score < 30) return { stroke: '#22c55e', text: 'text-green-600', label: 'Low Risk' }; - if (score < 60) return { stroke: '#f59e0b', text: 'text-amber-500', label: 'Medium Risk' }; - return { stroke: '#ef4444', text: 'text-red-600', label: 'High Risk' }; - }; - - const { stroke, text, label } = getRiskColor(score); - const R = 52; - const circumference = 2 * Math.PI * R; - const offset = circumference - (score / 100) * circumference; - - return ( -
-

Risk Analysis

-
-
- - - - - {score} - - - / 100 - - -

{label}

-
-
- {flags?.map((flag) => ( -
-
- {flag} - ✗ -
-
- ))} - {(!flags || flags.length === 0) && ( -
-
- No risk flags detected - ✓ -
-
- )} -
-
-
- ); -} \ No newline at end of file diff --git a/frontend/components/documents/StatusTimeline.tsx b/frontend/components/documents/StatusTimeline.tsx deleted file mode 100644 index d17f644e..00000000 --- a/frontend/components/documents/StatusTimeline.tsx +++ /dev/null @@ -1,52 +0,0 @@ -'use client'; - -interface StatusTimelineProps { - currentStatus: string; - events: Array<{ status: string; timestamp: string; description?: string }>; -} - -const STATUS_ORDER = ['PENDING', 'ANALYZING', 'VERIFIED']; - -export function StatusTimeline({ currentStatus, events }: StatusTimelineProps) { - const steps = STATUS_ORDER; - const isFinalStatus = ['VERIFIED', 'FLAGGED', 'REJECTED'].includes(currentStatus); - const currentIdx = steps.indexOf( - currentStatus === 'FLAGGED' || currentStatus === 'REJECTED' ? 'VERIFIED' : currentStatus - ); - - return ( -
-

Status Timeline

-
    - {steps.map((step, i) => { - const done = i < currentIdx || (isFinalStatus && step === 'VERIFIED'); - const active = - i === currentIdx || - ((currentStatus === 'FLAGGED' || currentStatus === 'REJECTED') && step === 'VERIFIED'); - const label = step === 'VERIFIED' - ? currentStatus === 'FLAGGED' - ? 'FLAGGED' - : currentStatus === 'REJECTED' - ? 'REVOKED' - : 'VERIFIED' - : step; - - return ( -
  1. - - {done ? '✓' : i + 1} - -

    - {label} -

    -
  2. - ); - })} -
-
- ); -} \ No newline at end of file diff --git a/frontend/components/documents/VerificationNotice.tsx b/frontend/components/documents/VerificationNotice.tsx deleted file mode 100644 index 5bf4cb19..00000000 --- a/frontend/components/documents/VerificationNotice.tsx +++ /dev/null @@ -1,11 +0,0 @@ -'use client'; - -interface VerificationNoticeProps { - message: string; -} - -export function VerificationNotice({ message }: VerificationNoticeProps) { - return ( -

{message}

- ); -} \ No newline at end of file diff --git a/frontend/components/documents/VerifyOnStellarButton.tsx b/frontend/components/documents/VerifyOnStellarButton.tsx deleted file mode 100644 index 7d5aa862..00000000 --- a/frontend/components/documents/VerifyOnStellarButton.tsx +++ /dev/null @@ -1,27 +0,0 @@ -'use client'; - -import { Button } from '@/components/ui/button'; - -interface VerifyOnStellarButtonProps { - loading?: boolean; - disabled?: boolean; - onVerify?: () => void; -} - -export function VerifyOnStellarButton({ loading, disabled, onVerify }: VerifyOnStellarButtonProps) { - return ( - - ); -} \ No newline at end of file diff --git a/frontend/components/ui/ReferenceCard.tsx b/frontend/components/ui/ReferenceCard.tsx deleted file mode 100644 index e33387f7..00000000 --- a/frontend/components/ui/ReferenceCard.tsx +++ /dev/null @@ -1,21 +0,0 @@ -import React from 'react'; - -interface ReferenceCardProps { - title: string; - description?: string; - children?: React.ReactNode; -} - -export const ReferenceCard: React.FC = ({ - title, - description, - children, -}) => { - return ( -
-

{title}

- {description &&

{description}

} - {children &&
{children}
} -
- ); -}; diff --git a/frontend/components/ui/__tests__/reference-card.test.tsx b/frontend/components/ui/__tests__/reference-card.test.tsx deleted file mode 100644 index 1925cb30..00000000 --- a/frontend/components/ui/__tests__/reference-card.test.tsx +++ /dev/null @@ -1,61 +0,0 @@ -import React from "react"; -import { render, screen } from "@testing-library/react"; -import { ReferenceCard } from "../ReferenceCard"; - -describe("ReferenceCard", () => { - it("renders its title", () => { - render(); - - expect(screen.getByRole("heading", { name: "Land registry reference" })).toBeInTheDocument(); - }); - - it("renders the optional description when provided", () => { - render( - , - ); - - expect(screen.getByText("Details from the authoritative registry")).toBeInTheDocument(); - }); - - it("renders children in the content area", () => { - render( - - Open document - , - ); - - expect(screen.getByRole("link", { name: "Open document" })).toHaveAttribute( - "href", - "/documents/123", - ); - expect(screen.getByRole("link", { name: "Open document" }).parentElement).toHaveClass( - "mt-4", - ); - }); - - it("uses theme-aware card colors", () => { - const { container } = render( - , - ); - - expect(container.firstElementChild).toHaveClass( - "bg-card", - "text-card-foreground", - "border-border", - ); - expect(screen.getByText("Registry details")).toHaveClass( - "text-muted-foreground", - ); - }); - - it("omits optional description and content wrappers when values are absent", () => { - const { container } = render(); - - expect(screen.queryByText("Details from the authoritative registry")).not.toBeInTheDocument(); - expect(container.querySelector(".mt-1")).not.toBeInTheDocument(); - expect(container.querySelector(".mt-4")).not.toBeInTheDocument(); - }); -}); diff --git a/frontend/hooks/useDocument.ts b/frontend/hooks/useDocument.ts deleted file mode 100644 index 90bd775a..00000000 --- a/frontend/hooks/useDocument.ts +++ /dev/null @@ -1,25 +0,0 @@ -'use client'; - -import { useQuery } from '@tanstack/react-query'; -import { request } from '@/lib/api-client'; -import { apiUrl } from '@/lib/api-config'; - -interface DocumentDetail { - id: string; - title: string; - fileHash: string; - status: string; - riskScore: number | null; - riskFlags: string[] | null; - createdAt: string; - updatedAt: string; - timeline: Array<{ status: string; timestamp: string; description?: string }>; -} - -export function useDocument(documentId: string) { - return useQuery({ - queryKey: ['document', documentId], - queryFn: () => request(apiUrl(`/documents/${documentId}`)), - enabled: !!documentId, - }); -} \ No newline at end of file diff --git a/frontend/hooks/useDocumentStatusSocket.ts b/frontend/hooks/useDocumentStatusSocket.ts new file mode 100644 index 00000000..54aa3180 --- /dev/null +++ b/frontend/hooks/useDocumentStatusSocket.ts @@ -0,0 +1,57 @@ +/** + * Live document updates over the backend's Socket.IO `/documents` namespace + * (#1642, #1643). + * + * Auth is the httpOnly cookie (`withCredentials`). After connecting the hook + * emits `subscribe:document` for the document, then forwards the server's + * `document:status-changed` and `verification:status-changed` events. The + * connection is closed on unmount or when the document id changes. + */ +import { useEffect, useRef } from "react"; +import { io, type Socket } from "socket.io-client"; +import { getApiOrigin } from "@/lib/api-config"; + +export interface DocumentStatusEvent { + documentId: string; + status: string; + previousStatus?: string | null; + timestamp?: string; +} + +export interface DocumentStatusHandlers { + onStatus?: (event: DocumentStatusEvent) => void; + onVerification?: (event: DocumentStatusEvent) => void; +} + +export function useDocumentStatusSocket( + documentId: string | null | undefined, + handlers: DocumentStatusHandlers, + baseUrl: string | null = getApiOrigin(), +): void { + const handlersRef = useRef(handlers); + handlersRef.current = handlers; + + useEffect(() => { + if (!documentId || !baseUrl) return; + + const socket: Socket = io(`${baseUrl}/documents`, { + transports: ["websocket"], + withCredentials: true, + }); + socket.on("connect", () => { + socket.emit("subscribe:document", { documentId }); + }); + socket.on("document:status-changed", (event: DocumentStatusEvent) => + handlersRef.current.onStatus?.(event), + ); + socket.on("verification:status-changed", (event: DocumentStatusEvent) => + handlersRef.current.onVerification?.(event), + ); + + return () => { + socket.emit("unsubscribe:document", { documentId }); + socket.off(); + socket.disconnect(); + }; + }, [documentId, baseUrl]); +} diff --git a/frontend/hooks/useVerifyDocument.ts b/frontend/hooks/useVerifyDocument.ts deleted file mode 100644 index 92f0f5d6..00000000 --- a/frontend/hooks/useVerifyDocument.ts +++ /dev/null @@ -1,14 +0,0 @@ -'use client'; - -import { useMutation } from '@tanstack/react-query'; -import { request } from '@/lib/api-client'; -import { apiUrl } from '@/lib/api-config'; - -export function useVerifyDocument(documentId: string) { - return useMutation({ - mutationFn: () => - request(apiUrl(`/documents/${documentId}/verify`), { - method: 'POST', - }), - }); -} \ No newline at end of file diff --git a/frontend/lib/__tests__/upload-xhr.test.ts b/frontend/lib/__tests__/upload-xhr.test.ts new file mode 100644 index 00000000..65ed186c --- /dev/null +++ b/frontend/lib/__tests__/upload-xhr.test.ts @@ -0,0 +1,72 @@ +import { UploadAbortedError, UploadHttpError, uploadWithProgress } from "../upload-xhr"; + +class FakeXhr { + static last: FakeXhr; + upload: { onprogress: ((e: Partial) => void) | null } = { onprogress: null }; + onload: (() => void) | null = null; + onerror: (() => void) | null = null; + onabort: (() => void) | null = null; + status = 0; + responseText = ""; + withCredentials = false; + headers: Record = {}; + method = ""; + url = ""; + constructor() { + FakeXhr.last = this; + } + open(method: string, url: string) { + this.method = method; + this.url = url; + } + setRequestHeader(name: string, value: string) { + this.headers[name] = value; + } + send() {} + abort() { + this.onabort?.(); + } +} + +describe("uploadWithProgress", () => { + const original = global.XMLHttpRequest; + beforeEach(() => { + (global as unknown as { XMLHttpRequest: unknown }).XMLHttpRequest = FakeXhr; + }); + afterEach(() => { + global.XMLHttpRequest = original; + }); + + it("reports bytes sent, capped at 99 until the server answers", async () => { + const seen: number[] = []; + const { promise } = uploadWithProgress("/u", new FormData(), { + onProgress: (p) => seen.push(p), + token: "tok", + }); + const xhr = FakeXhr.last; + expect(xhr.withCredentials).toBe(true); + expect(xhr.headers.Authorization).toBe("Bearer tok"); + + xhr.upload.onprogress?.({ lengthComputable: true, loaded: 25, total: 100 }); + xhr.upload.onprogress?.({ lengthComputable: true, loaded: 100, total: 100 }); + xhr.status = 202; + xhr.responseText = '{"id":"d1"}'; + xhr.onload?.(); + + await expect(promise).resolves.toEqual({ id: "d1" }); + expect(seen).toEqual([25, 99, 100]); + }); + + it("rejects with the status on a non-2xx response", async () => { + const { promise } = uploadWithProgress("/u", new FormData()); + FakeXhr.last.status = 413; + FakeXhr.last.onload?.(); + await expect(promise).rejects.toBeInstanceOf(UploadHttpError); + }); + + it("abort() cancels the request", async () => { + const { promise, abort } = uploadWithProgress("/u", new FormData()); + abort(); + await expect(promise).rejects.toBeInstanceOf(UploadAbortedError); + }); +}); diff --git a/frontend/lib/upload-xhr.ts b/frontend/lib/upload-xhr.ts new file mode 100644 index 00000000..bd8ef2d8 --- /dev/null +++ b/frontend/lib/upload-xhr.ts @@ -0,0 +1,70 @@ +/** + * Multipart upload with real progress and cancellation (#1641). + * + * `fetch` cannot report upload progress, so this uses XMLHttpRequest and + * `upload.onprogress`. The percentage is bytes sent over bytes total, capped at + * 99 until the server has answered, so the bar never claims "done" early. + */ +export interface UploadHandle { + promise: Promise; + /** Aborts the request; the promise rejects with an `UploadAbortedError`. */ + abort: () => void; +} + +export class UploadAbortedError extends Error { + constructor() { + super("Upload cancelled"); + this.name = "UploadAbortedError"; + } +} + +export class UploadHttpError extends Error { + constructor(public readonly status: number) { + super(`Upload failed with status ${status}`); + this.name = "UploadHttpError"; + } +} + +export function uploadWithProgress( + url: string, + body: FormData, + options: { + token?: string | null; + onProgress?: (percent: number) => void; + } = {}, +): UploadHandle { + const xhr = new XMLHttpRequest(); + + const promise = new Promise((resolve, reject) => { + xhr.open("POST", url); + xhr.withCredentials = true; + if (options.token) { + xhr.setRequestHeader("Authorization", `Bearer ${options.token}`); + } + + xhr.upload.onprogress = (event: ProgressEvent) => { + if (!event.lengthComputable || event.total === 0) return; + const percent = Math.floor((event.loaded / event.total) * 100); + options.onProgress?.(Math.min(percent, 99)); + }; + + xhr.onload = () => { + if (xhr.status >= 200 && xhr.status < 300) { + options.onProgress?.(100); + try { + resolve((xhr.responseText ? JSON.parse(xhr.responseText) : undefined) as T); + } catch { + resolve(undefined as T); + } + } else { + reject(new UploadHttpError(xhr.status)); + } + }; + xhr.onerror = () => reject(new Error("Network error during upload")); + xhr.onabort = () => reject(new UploadAbortedError()); + + xhr.send(body); + }); + + return { promise, abort: () => xhr.abort() }; +} diff --git a/frontend/messages/en.json b/frontend/messages/en.json index d33ab086..5e1079dd 100644 --- a/frontend/messages/en.json +++ b/frontend/messages/en.json @@ -417,7 +417,8 @@ "qrPending": "QR code available after server-side generation (BE-85)", "downloadCertificate": "Download Verification Certificate", "backToDocument": "Back to Document" - } + }, + "stillProcessing": "Still processing. This can take a few minutes; the page will update when anchoring finishes." }, "map": { "title": "Document Map", diff --git a/frontend/messages/es.json b/frontend/messages/es.json index d8f0bea1..de092e83 100644 --- a/frontend/messages/es.json +++ b/frontend/messages/es.json @@ -417,7 +417,8 @@ "qrPending": "Código QR disponible tras la generación en el servidor (BE-85)", "downloadCertificate": "Descargar certificado de verificación", "backToDocument": "Volver al documento" - } + }, + "stillProcessing": "Procesando todavía. Puede tardar unos minutos; la página se actualizará cuando termine el anclaje." }, "map": { "title": "Mapa de documentos", diff --git a/frontend/messages/fr.json b/frontend/messages/fr.json index 2ac5c436..1d84f817 100644 --- a/frontend/messages/fr.json +++ b/frontend/messages/fr.json @@ -417,7 +417,8 @@ "qrPending": "Code QR disponible après génération côté serveur (BE-85)", "downloadCertificate": "Télécharger le certificat de vérification", "backToDocument": "Retour au document" - } + }, + "stillProcessing": "Traitement en cours. Cela peut prendre quelques minutes ; la page se mettra à jour à la fin de l'ancrage." }, "map": { "title": "Carte des documents", diff --git a/frontend/package.json b/frontend/package.json index fd711c49..06874405 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -35,6 +35,7 @@ "react-dom": "19.1.0", "react-hook-form": "^7.74.0", "react-leaflet": "^5.0.0", + "socket.io-client": "^4.8.1", "tailwind-merge": "^3.3.1", "zod": "^4.3.6" }, diff --git a/frontend/src/components/upload/DropZone.tsx b/frontend/src/components/upload/DropZone.tsx deleted file mode 100644 index f555b28e..00000000 --- a/frontend/src/components/upload/DropZone.tsx +++ /dev/null @@ -1,71 +0,0 @@ -/** - * Accessible upload drop zone (#1513, #1512). - * - * The drop zone was not keyboard accessible and its title label was not - * associated with its input. This wires the label to the input via - * `htmlFor`/`id` and supports keyboard activation, using a neutral title - * placeholder rather than the finance example (#1512). - */ -import * as React from "react"; - -export interface DropZoneProps { - id?: string; - label?: string; - accept?: string; - onFile: (file: File) => void; -} - -export function DropZone({ - id = "upload-file", - label = "Choose a document to upload", - accept, - onFile, -}: DropZoneProps): React.ReactElement { - const inputRef = React.useRef(null); - const labelId = `${id}-label`; - - return ( -
- -
inputRef.current?.click()} - onKeyDown={(event) => { - if (event.key === "Enter" || event.key === " ") { - event.preventDefault(); - inputRef.current?.click(); - } - }} - onDrop={(event) => { - event.preventDefault(); - const file = event.dataTransfer.files?.[0]; - if (file) { - onFile(file); - } - }} - onDragOver={(event) => event.preventDefault()} - > - Drag and drop, or press Enter to browse -
- { - const file = event.target.files?.[0]; - if (file) { - onFile(file); - } - }} - /> -
- ); -} - -export default DropZone; diff --git a/frontend/src/hooks/useDocumentStatusSocket.ts b/frontend/src/hooks/useDocumentStatusSocket.ts deleted file mode 100644 index 67eb8e2d..00000000 --- a/frontend/src/hooks/useDocumentStatusSocket.ts +++ /dev/null @@ -1,41 +0,0 @@ -/** - * Document status socket hook (#1502, #1503). - * - * The document page opened a raw WebSocket to `/documents/:id/status`, but the - * backend serves a Socket.IO namespace, and its manual reconnect loop kept - * running after the page was closed. This hook connects through Socket.IO and - * tears the connection down on unmount. - */ -import { useEffect, useRef } from "react"; -import { io, type Socket } from "socket.io-client"; - -export interface DocumentStatusEvent { - documentId: string; - status: string; -} - -export function useDocumentStatusSocket( - documentId: string, - onStatus: (event: DocumentStatusEvent) => void, - baseUrl: string = process.env.NEXT_PUBLIC_API_URL ?? "", -): void { - const handlerRef = useRef(onStatus); - handlerRef.current = onStatus; - - useEffect(() => { - if (!documentId) { - return; - } - const socket: Socket = io(`${baseUrl}/documents`, { - transports: ["websocket"], - withCredentials: true, - }); - socket.on("status", (event: DocumentStatusEvent) => - handlerRef.current(event), - ); - return () => { - socket.off("status"); - socket.disconnect(); - }; - }, [documentId, baseUrl]); -} diff --git a/frontend/src/lib/upload-progress.ts b/frontend/src/lib/upload-progress.ts deleted file mode 100644 index 96d16f5f..00000000 --- a/frontend/src/lib/upload-progress.ts +++ /dev/null @@ -1,46 +0,0 @@ -/** - * Upload progress tracking that cleans up after itself (#1511). - * - * The upload page faked progress and leaked its `setInterval` on errors. This - * tracker owns its timer and guarantees it is cleared on completion or failure. - */ -export interface ProgressTracker { - set(value: number): void; - done(): void; - fail(): void; -} - -export function createProgressTracker( - onProgress: (value: number) => void, - intervalMs = 250, - schedule: (fn: () => void, ms: number) => ReturnType = - setInterval, - clear: (handle: ReturnType) => void = clearInterval, -): ProgressTracker { - let value = 0; - let handle: ReturnType | null = schedule(() => { - value = Math.min(value + 5, 95); - onProgress(value); - }, intervalMs); - - const stop = (): void => { - if (handle !== null) { - clear(handle); - handle = null; - } - }; - - return { - set(next: number): void { - value = Math.min(Math.max(next, 0), 100); - onProgress(value); - }, - done(): void { - stop(); - onProgress(100); - }, - fail(): void { - stop(); - }, - }; -}