diff --git a/app/api/contracts/[id]/workspace/files/[fileId]/route.ts b/app/api/contracts/[id]/workspace/files/[fileId]/route.ts new file mode 100644 index 0000000..c9ff2b5 --- /dev/null +++ b/app/api/contracts/[id]/workspace/files/[fileId]/route.ts @@ -0,0 +1,99 @@ +export const dynamic = 'force-dynamic' + +import { NextRequest, NextResponse } from 'next/server' +import { withAuthCtx } from '@/lib/auth/middleware' +import { sql } from '@/lib/db' +import { readEncryptedFile } from '@/lib/security/fileEncryption' + +interface RouteContext { + params: Promise<{ id: string; fileId: string }> +} + +type Row = Record + +/** + * GET /api/contracts/:id/workspace/files/:fileId + * + * Streams the decrypted file to the authenticated user. Supply ?preview=1 + * for an inline Content-Disposition (in-browser preview). + */ +export const GET = withAuthCtx(async (request: NextRequest, auth, context) => { + const { id: contractId, fileId } = await context.params + const preview = request.nextUrl.searchParams.get('preview') === '1' + + try { + // Resolve requesting user + const userRows = (await sql` + SELECT id FROM users WHERE wallet_address = ${auth.walletAddress} LIMIT 1 + `) as unknown as Row[] + const user = userRows[0] + if (!user) { + return NextResponse.json( + { error: 'User not found', code: 'USER_NOT_FOUND' }, + { status: 404 }, + ) + } + + // Fetch the deliverable and verify it belongs to this contract + const deliverableRows = (await sql` + SELECT + md.id, + md.original_filename, + md.mime_type, + md.file_size, + md.file_path, + md.encryption_iv, + md.encryption_key_id, + c.client_id, + c.freelancer_id + FROM milestone_deliverables md + JOIN milestones m ON m.id = md.milestone_id + JOIN contracts c ON c.id = m.contract_id + WHERE md.id = ${fileId} + AND c.id = ${contractId} + AND md.is_removed = FALSE + LIMIT 1 + `) as unknown as Row[] + const deliverable = deliverableRows[0] + + if (!deliverable) { + return NextResponse.json( + { error: 'File not found', code: 'FILE_NOT_FOUND' }, + { status: 404 }, + ) + } + + if (deliverable.client_id !== user.id && deliverable.freelancer_id !== user.id) { + return NextResponse.json( + { error: 'Access denied', code: 'FORBIDDEN' }, + { status: 403 }, + ) + } + + const plaintext = await readEncryptedFile( + deliverable.file_path as string, + deliverable.encryption_iv as string, + (deliverable.encryption_key_id as string | undefined) ?? 'primary', + ) + + const disposition = preview + ? `inline; filename="${deliverable.original_filename}"` + : `attachment; filename="${deliverable.original_filename}"` + + return new NextResponse(new Uint8Array(plaintext), { + status: 200, + headers: { + 'Content-Type': deliverable.mime_type as string, + 'Content-Disposition': disposition, + 'Content-Length': String(plaintext.length), + 'Cache-Control': 'private, no-store', + }, + }) + } catch (err) { + console.error('[workspace-file] Error serving file:', err) + return NextResponse.json( + { error: 'Failed to retrieve file', code: 'FILE_DOWNLOAD_FAILED' }, + { status: 500 }, + ) + } +}) diff --git a/app/api/contracts/[id]/workspace/route.ts b/app/api/contracts/[id]/workspace/route.ts new file mode 100644 index 0000000..dcae14f --- /dev/null +++ b/app/api/contracts/[id]/workspace/route.ts @@ -0,0 +1,222 @@ +export const dynamic = 'force-dynamic' + +import { NextRequest, NextResponse } from 'next/server' +import { withAuthCtx } from '@/lib/auth/middleware' +import { sql } from '@/lib/db' + +interface RouteContext { + params: Promise<{ id: string }> +} + +type Row = Record + +/** + * GET /api/contracts/:id/workspace + * + * Returns all milestones for the contract, each with their deliverable files + * and submission history entries. Access is restricted to the contract's + * client and freelancer. + */ +export const GET = withAuthCtx(async (request: NextRequest, auth, context) => { + const { id: contractId } = await context.params + + try { + // Resolve requesting user + const userRows = (await sql` + SELECT id FROM users WHERE wallet_address = ${auth.walletAddress} LIMIT 1 + `) as unknown as Row[] + const user = userRows[0] + if (!user) { + return NextResponse.json( + { error: 'User not found', code: 'USER_NOT_FOUND' }, + { status: 404 }, + ) + } + + // Fetch the contract and verify access + const contractRows = (await sql` + SELECT + c.id, + c.status, + c.client_id, + c.freelancer_id, + c.total_amount, + c.currency, + p.title AS project_title, + client_u.display_name AS client_name, + client_u.username AS client_username, + free_u.display_name AS freelancer_name, + free_u.username AS freelancer_username + FROM contracts c + JOIN projects p ON p.id = c.project_id + JOIN users client_u ON client_u.id = c.client_id + LEFT JOIN users free_u ON free_u.id = c.freelancer_id + WHERE c.id = ${contractId} + LIMIT 1 + `) as unknown as Row[] + const contract = contractRows[0] + + if (!contract) { + return NextResponse.json( + { error: 'Contract not found', code: 'CONTRACT_NOT_FOUND' }, + { status: 404 }, + ) + } + + if (contract.client_id !== user.id && contract.freelancer_id !== user.id) { + return NextResponse.json( + { error: 'Access denied', code: 'FORBIDDEN' }, + { status: 403 }, + ) + } + + // Fetch milestones for this contract + const milestones = (await sql` + SELECT + id, + title, + description, + status, + sort_order, + due_date, + amount, + currency, + submitted_at, + approved_at + FROM milestones + WHERE contract_id = ${contractId} + ORDER BY sort_order ASC, created_at ASC + `) as unknown as Row[] + + if (milestones.length === 0) { + return NextResponse.json({ + contract: { + id: contract.id, + status: contract.status, + project_title: contract.project_title, + total_amount: contract.total_amount, + currency: contract.currency, + client: { name: contract.client_name, username: contract.client_username }, + freelancer: { name: contract.freelancer_name, username: contract.freelancer_username }, + }, + milestones: [], + total_files: 0, + }) + } + + const milestoneIds = milestones.map((m) => m.id as string) + + // Fetch all (non-removed) deliverables across those milestones in one query + const deliverables = (await sql` + SELECT + md.id, + md.milestone_id, + md.original_filename, + md.mime_type, + md.file_size, + md.created_at, + md.uploader_id, + u.display_name AS uploader_display_name, + u.username AS uploader_username + FROM milestone_deliverables md + JOIN users u ON u.id = md.uploader_id + WHERE md.milestone_id = ANY(${milestoneIds}::uuid[]) + AND md.is_removed = FALSE + ORDER BY md.milestone_id, md.created_at ASC + `) as unknown as Row[] + + // Group deliverables by milestone + const deliverablesByMilestone: Record = {} + for (const d of deliverables) { + const mid = d.milestone_id as string + if (!deliverablesByMilestone[mid]) deliverablesByMilestone[mid] = [] + deliverablesByMilestone[mid].push(d) + } + + // Fetch submission history for version tracking + const historyRows = (await sql` + SELECT + h.id, + h.milestone_id, + h.submission_type, + h.deliverable_notes, + h.deliverable_links, + h.feedback, + h.revision_notes, + h.created_at, + submitter.display_name AS submitter_name, + submitter.username AS submitter_username + FROM milestone_submission_history h + LEFT JOIN users submitter ON submitter.id = h.submitted_by + WHERE h.milestone_id = ANY(${milestoneIds}::uuid[]) + ORDER BY h.milestone_id, h.created_at DESC + `) as unknown as Row[] + + // Group history by milestone + const historyByMilestone: Record = {} + for (const h of historyRows) { + const mid = h.milestone_id as string + if (!historyByMilestone[mid]) historyByMilestone[mid] = [] + historyByMilestone[mid].push(h) + } + + // Assemble response + const result = milestones.map((m) => ({ + id: m.id, + title: m.title, + description: m.description, + status: m.status, + sort_order: m.sort_order, + due_date: m.due_date, + amount: m.amount, + currency: m.currency, + submitted_at: m.submitted_at, + approved_at: m.approved_at, + files: (deliverablesByMilestone[m.id as string] ?? []).map((d) => ({ + id: d.id, + original_filename: d.original_filename, + mime_type: d.mime_type, + file_size: d.file_size, + created_at: d.created_at, + uploader: { + id: d.uploader_id, + display_name: d.uploader_display_name, + username: d.uploader_username, + }, + })), + submission_history: (historyByMilestone[m.id as string] ?? []).map((h) => ({ + id: h.id, + submission_type: h.submission_type, + deliverable_notes: h.deliverable_notes, + deliverable_links: h.deliverable_links, + feedback: h.feedback, + revision_notes: h.revision_notes, + created_at: h.created_at, + submitter: { + display_name: h.submitter_name, + username: h.submitter_username, + }, + })), + })) + + return NextResponse.json({ + contract: { + id: contract.id, + status: contract.status, + project_title: contract.project_title, + total_amount: contract.total_amount, + currency: contract.currency, + client: { name: contract.client_name, username: contract.client_username }, + freelancer: { name: contract.freelancer_name, username: contract.freelancer_username }, + }, + milestones: result, + total_files: deliverables.length, + }) + } catch (err) { + console.error('[workspace] Error fetching workspace data:', err) + return NextResponse.json( + { error: 'Failed to load workspace', code: 'WORKSPACE_FETCH_FAILED' }, + { status: 500 }, + ) + } +}) diff --git a/app/dashboard/contracts/[id]/page.tsx b/app/dashboard/contracts/[id]/page.tsx index 947c0da..9524aa9 100644 --- a/app/dashboard/contracts/[id]/page.tsx +++ b/app/dashboard/contracts/[id]/page.tsx @@ -3,7 +3,7 @@ import { useEffect, useState } from "react"; import { useParams } from "next/navigation"; import Link from "next/link"; -import { ArrowLeft, Loader2, AlertCircle, Star, ShieldCheck, Wallet, User } from "lucide-react"; +import { ArrowLeft, Loader2, AlertCircle, Star, ShieldCheck, Wallet, User, FolderOpen } from "lucide-react"; import { Button } from "@/components/ui/button"; import { Badge } from "@/components/ui/badge"; import { Card } from "@/components/ui/card"; @@ -175,6 +175,12 @@ export default function ContractDetailPage() { {statusCfg.label} + + + {/* Parties */} diff --git a/app/dashboard/contracts/[id]/workspace/page.tsx b/app/dashboard/contracts/[id]/workspace/page.tsx new file mode 100644 index 0000000..f5c8345 --- /dev/null +++ b/app/dashboard/contracts/[id]/workspace/page.tsx @@ -0,0 +1,579 @@ +"use client" + +import * as React from "react" +import { useParams } from "next/navigation" +import Link from "next/link" +import { format } from "date-fns" +import { + ArrowLeft, + Loader2, + AlertCircle, + FolderOpen, + Filter, + FileSearch, + ChevronDown, + ChevronUp, + CheckCircle2, + Clock, + AlertTriangle, + History, + FileText, + Link as LinkIcon, + HardDrive, +} from "lucide-react" +import { Button } from "@/components/ui/button" +import { Badge } from "@/components/ui/badge" +import { Card } from "@/components/ui/card" +import { + Collapsible, + CollapsibleContent, + CollapsibleTrigger, +} from "@/components/ui/collapsible" +import { + Select, + SelectContent, + SelectItem, + SelectTrigger, + SelectValue, +} from "@/components/ui/select" +import { + ScrollArea, +} from "@/components/ui/scroll-area" +import { WorkspaceFileCard, type WorkspaceFile } from "@/components/dashboard/workspace-file-card" + +// ─── Types ───────────────────────────────────────────────────────────────── + +interface SubmissionHistoryEntry { + id: string + submission_type: "submitted" | "approved" | "rejected" | "revision_requested" + deliverable_notes: string | null + deliverable_links: string[] | null + feedback: string | null + revision_notes: string | null + created_at: string + submitter: { + display_name: string | null + username: string | null + } +} + +interface MilestoneWithFiles { + id: string + title: string + description: string | null + status: string + sort_order: number + due_date: string | null + amount: string + currency: string + submitted_at: string | null + approved_at: string | null + files: WorkspaceFile[] + submission_history: SubmissionHistoryEntry[] +} + +interface WorkspaceData { + contract: { + id: string + status: string + project_title: string + total_amount: string + currency: string + client: { name: string | null; username: string } + freelancer: { name: string | null; username: string } | null + } + milestones: MilestoneWithFiles[] + total_files: number +} + +// ─── Helpers ─────────────────────────────────────────────────────────────── + +function getAuthHeaders(): Record { + const token = + typeof window !== "undefined" + ? localStorage.getItem("tc_dev_access_token") + : null + return token ? { Authorization: `Bearer ${token}` } : {} +} + +function getAuthToken(): string | null { + if (typeof window === "undefined") return null + return localStorage.getItem("tc_dev_access_token") +} + +function formatBytes(bytes: number): string { + if (bytes < 1024) return `${bytes} B` + if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB` + return `${(bytes / (1024 * 1024)).toFixed(2)} MB` +} + +const milestoneStatusConfig: Record< + string, + { label: string; color: string; icon: React.ElementType } +> = { + pending: { + label: "Pending", + color: "bg-muted text-muted-foreground border-muted", + icon: Clock, + }, + in_progress: { + label: "In Progress", + color: "bg-blue-500/10 text-blue-500 border-blue-500/20", + icon: Clock, + }, + submitted: { + label: "Awaiting Review", + color: "bg-amber-500/10 text-amber-500 border-amber-500/20", + icon: AlertTriangle, + }, + approved: { + label: "Approved", + color: "bg-green-500/10 text-green-500 border-green-500/20", + icon: CheckCircle2, + }, + rejected: { + label: "Rejected", + color: "bg-destructive/10 text-destructive border-destructive/20", + icon: AlertCircle, + }, + paid: { + label: "Paid", + color: "bg-emerald-500/10 text-emerald-500 border-emerald-500/20", + icon: CheckCircle2, + }, +} + +const historyTypeConfig: Record< + string, + { label: string; color: string; icon: React.ElementType } +> = { + submitted: { label: "Submitted", color: "text-blue-500", icon: FileText }, + approved: { label: "Approved", color: "text-green-500", icon: CheckCircle2 }, + rejected: { label: "Rejected", color: "text-destructive", icon: AlertCircle }, + revision_requested: { + label: "Revision Requested", + color: "text-amber-500", + icon: AlertTriangle, + }, +} + +// ─── Submission History Panel ────────────────────────────────────────────── + +function SubmissionHistory({ + history, +}: { + history: SubmissionHistoryEntry[] +}) { + const [open, setOpen] = React.useState(false) + + if (history.length === 0) return null + + return ( + + + + + + + +
+ {history.map((entry, idx) => { + const cfg = historyTypeConfig[entry.submission_type] ?? historyTypeConfig.submitted + const Icon = cfg.icon + const isLatest = idx === 0 + return ( +
+
+ +
+
+
+ + {cfg.label} + + {isLatest && ( + + Latest + + )} + + {format(new Date(entry.created_at), "MMM d, yyyy 'at' h:mm a")} + +
+

+ by{" "} + {entry.submitter.display_name ?? + `@${entry.submitter.username ?? "unknown"}`} +

+ {entry.deliverable_notes && ( +

+ {entry.deliverable_notes} +

+ )} + {entry.deliverable_links && entry.deliverable_links.length > 0 && ( +
+ {entry.deliverable_links.map((link, i) => ( + + + Link {i + 1} + + ))} +
+ )} + {entry.revision_notes && ( +

+ + Revision:{" "} + + {entry.revision_notes} +

+ )} + {entry.feedback && ( +

+ Feedback: + {entry.feedback} +

+ )} +
+
+ ) + })} +
+
+
+
+ ) +} + +// ─── Milestone Section ──────────────────────────────────────────────────── + +function MilestoneSection({ + milestone, + contractId, + authToken, + defaultOpen, +}: { + milestone: MilestoneWithFiles + contractId: string + authToken: string | null + defaultOpen: boolean +}) { + const [open, setOpen] = React.useState(defaultOpen) + const cfg = milestoneStatusConfig[milestone.status] ?? milestoneStatusConfig.pending + const StatusIcon = cfg.icon + + return ( + + + +
+
+ {/* Number badge */} +
+ {milestone.sort_order + 1} +
+ +
+
+

{milestone.title}

+ + + {cfg.label} + +
+
+ + {parseFloat(milestone.amount).toLocaleString()} {milestone.currency} + + {milestone.due_date && ( + Due {format(new Date(milestone.due_date), "MMM d, yyyy")} + )} + + + {milestone.files.length}{" "} + {milestone.files.length === 1 ? "file" : "files"} + +
+
+
+ +
+ {open ? ( + + ) : ( + + )} +
+
+
+ + +
+ {/* Description */} + {milestone.description && ( +

{milestone.description}

+ )} + + {/* Files */} + {milestone.files.length === 0 ? ( +
+ +

No files uploaded for this milestone.

+
+ ) : ( +
+ {milestone.files.map((file) => ( + + ))} +
+ )} + + {/* Version / submission history */} + +
+
+
+
+ ) +} + +// ─── Page ────────────────────────────────────────────────────────────────── + +export default function WorkspacePage() { + const { id: contractId } = useParams<{ id: string }>() + const [data, setData] = React.useState(null) + const [loading, setLoading] = React.useState(true) + const [error, setError] = React.useState(null) + const [filterMilestone, setFilterMilestone] = React.useState("all") + const [authToken] = React.useState(getAuthToken) + + React.useEffect(() => { + if (!contractId) return + ;(async () => { + try { + const res = await fetch(`/api/contracts/${contractId}/workspace`, { + headers: getAuthHeaders(), + credentials: "include", + }) + if (res.status === 403) { + setError("You don't have permission to access this workspace.") + return + } + if (res.status === 404) { + setError("Contract not found.") + return + } + if (!res.ok) { + setError("Failed to load workspace data.") + return + } + const json = await res.json() + setData(json) + } catch { + setError("An unexpected error occurred while loading the workspace.") + } finally { + setLoading(false) + } + })() + }, [contractId]) + + if (loading) { + return ( +
+ + Loading workspace… +
+ ) + } + + if (error || !data) { + return ( +
+ +

+ {error ?? "Workspace could not be loaded."} +

+ + + +
+ ) + } + + const { contract, milestones, total_files } = data + + // Filtered + sorted milestones + const visibleMilestones = + filterMilestone === "all" + ? milestones + : milestones.filter((m) => m.id === filterMilestone) + + // Summary stats + const totalSize = milestones + .flatMap((m) => m.files) + .reduce((sum, f) => sum + (f.file_size ?? 0), 0) + + const milestonesWithFiles = milestones.filter((m) => m.files.length > 0).length + + return ( +
+ {/* ── Header ── */} +
+ + + +
+
+

Project Workspace

+ + {contract.status.replace("_", " ")} + +
+

+ {contract.project_title} +

+
+
+ + {/* ── Summary cards ── */} +
+ +

Total Files

+

{total_files}

+
+ +

Total Size

+

{formatBytes(totalSize)}

+
+ +

Milestones

+

+ {milestonesWithFiles}/{milestones.length} +

+

with files

+
+ +

Contract Value

+

+ {parseFloat(contract.total_amount).toLocaleString()}{" "} + + {contract.currency} + +

+
+
+ + {/* ── Filter ── */} + {milestones.length > 1 && ( +
+ + + {filterMilestone !== "all" && ( + + )} +
+ )} + + {/* ── Milestone sections ── */} + {milestones.length === 0 ? ( +
+ +

No milestones yet

+

+ Milestones and their files will appear here once they are created for this contract. +

+
+ ) : visibleMilestones.length === 0 ? ( +
+ +

No milestones match the current filter.

+ +
+ ) : ( +
+ {visibleMilestones.map((milestone, idx) => ( + + ))} +
+ )} +
+ ) +} diff --git a/components/dashboard/sidebar.tsx b/components/dashboard/sidebar.tsx index dd0e797..9ba88c3 100644 --- a/components/dashboard/sidebar.tsx +++ b/components/dashboard/sidebar.tsx @@ -14,6 +14,7 @@ import { MessageSquare, Banknote, ShieldCheck, + FolderOpen, } from 'lucide-react' import { Button } from '@/components/ui/button' import { cn } from '@/lib/utils' @@ -34,6 +35,11 @@ const navItems = [ href: '/dashboard/projects', icon: FileText, }, + { + label: 'Workspace', + href: '/dashboard/contracts', + icon: FolderOpen, + }, { label: 'Disputes', href: '/dashboard/disputes', diff --git a/components/dashboard/workspace-file-card.tsx b/components/dashboard/workspace-file-card.tsx new file mode 100644 index 0000000..2443be4 --- /dev/null +++ b/components/dashboard/workspace-file-card.tsx @@ -0,0 +1,341 @@ +"use client" + +import * as React from "react" +import { format } from "date-fns" +import { + FileText, + FileImage, + FileVideo, + FileCode, + File, + Download, + Eye, + Clock, + User, + HardDrive, + X, + Loader2, + AlertCircle, +} from "lucide-react" +import { Button } from "@/components/ui/button" +import { Badge } from "@/components/ui/badge" +import { + Dialog, + DialogContent, + DialogHeader, + DialogTitle, +} from "@/components/ui/dialog" +import { toast } from "sonner" + +export interface WorkspaceFile { + id: string + original_filename: string + mime_type: string + file_size: number + created_at: string + uploader: { + id: string + display_name: string | null + username: string + } +} + +interface WorkspaceFileCardProps { + file: WorkspaceFile + contractId: string + /** Pass token for download/preview requests */ + authToken: string | null +} + +// ─── Helpers ────────────────────────────────────────────────────────────── + +function formatBytes(bytes: number): string { + if (bytes < 1024) return `${bytes} B` + if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB` + return `${(bytes / (1024 * 1024)).toFixed(2)} MB` +} + +function fileTypeLabel(mime: string): string { + if (mime.startsWith("image/")) return mime.replace("image/", "").toUpperCase() + if (mime === "application/pdf") return "PDF" + if (mime.startsWith("video/")) return mime.replace("video/", "").toUpperCase() + if (mime.startsWith("text/")) return mime.replace("text/", "").toUpperCase() + if (mime.includes("spreadsheet") || mime.includes("excel")) return "XLSX" + if (mime.includes("wordprocessingml") || mime.includes("msword")) return "DOCX" + if (mime.includes("zip")) return "ZIP" + const ext = mime.split("/")[1]?.toUpperCase() + return ext ?? "FILE" +} + +function FileIcon({ mime, className }: { mime: string; className?: string }) { + if (mime.startsWith("image/")) return + if (mime.startsWith("video/")) return + if (mime.startsWith("text/") || mime.includes("json") || mime.includes("javascript")) + return + return +} + +function isPreviewable(mime: string): boolean { + return ( + mime.startsWith("image/") || + mime === "application/pdf" || + mime.startsWith("text/") + ) +} + +function fileTypeColor(mime: string): string { + if (mime.startsWith("image/")) return "bg-blue-500/10 text-blue-500 border-blue-500/20" + if (mime === "application/pdf") return "bg-red-500/10 text-red-500 border-red-500/20" + if (mime.startsWith("video/")) return "bg-purple-500/10 text-purple-500 border-purple-500/20" + if (mime.startsWith("text/")) return "bg-green-500/10 text-green-500 border-green-500/20" + return "bg-muted text-muted-foreground border-border/40" +} + +// ─── Preview Dialog ──────────────────────────────────────────────────────── + +interface PreviewDialogProps { + open: boolean + onOpenChange: (open: boolean) => void + file: WorkspaceFile + contractId: string + authToken: string | null +} + +function PreviewDialog({ open, onOpenChange, file, contractId, authToken }: PreviewDialogProps) { + const [previewUrl, setPreviewUrl] = React.useState(null) + const [loading, setLoading] = React.useState(false) + const [error, setError] = React.useState(null) + + React.useEffect(() => { + if (!open) { + // Revoke the object URL when dialog closes to free memory + if (previewUrl) URL.revokeObjectURL(previewUrl) + setPreviewUrl(null) + setError(null) + return + } + + let cancelled = false + setLoading(true) + setError(null) + + const headers: HeadersInit = {} + if (authToken) headers["Authorization"] = `Bearer ${authToken}` + + fetch( + `/api/contracts/${contractId}/workspace/files/${file.id}?preview=1`, + { headers, credentials: "include" }, + ) + .then(async (res) => { + if (!res.ok) { + const data = await res.json().catch(() => ({})) + throw new Error(data.error ?? "Failed to load preview") + } + return res.blob() + }) + .then((blob) => { + if (cancelled) return + setPreviewUrl(URL.createObjectURL(blob)) + }) + .catch((err) => { + if (cancelled) return + setError(err instanceof Error ? err.message : "Preview unavailable") + }) + .finally(() => { + if (!cancelled) setLoading(false) + }) + + return () => { + cancelled = true + } + }, [open, file.id, contractId, authToken, previewUrl]) + + return ( + + + + + + {file.original_filename} + + + +
+ {loading && ( +
+ +
+ )} + + {error && !loading && ( +
+ +

{error}

+
+ )} + + {previewUrl && !loading && ( + <> + {file.mime_type.startsWith("image/") && ( + // eslint-disable-next-line @next/next/no-img-element + {file.original_filename} + )} + {file.mime_type === "application/pdf" && ( +