"use client"; import { useState } from "react"; import Link from "next/link"; import { useQuery, useQueryClient } from "@tanstack/react-query"; import { ArrowLeft, Package, CheckCircle2, XCircle, RefreshCw, Upload } from "lucide-react"; import { Button } from "@/components/ui/button"; import { useToast } from "@/components/ui/use-toast"; import { cn } from "@/lib/utils"; import { handoffStage } from "@/lib/render-pipeline/delivery-handoff"; import { DELIVERY_STATUS_STYLES, statusLabel } from "../status-colors"; import { RecordShareDialog, RecordUploadDialog } from "./HandoffDialogs"; import { RequestsPanel } from "./RequestsPanel"; interface ReadyExport { exportId: string; shotCode: string; episode: string; versionString: string; fileCount: number | null; totalBytes: number | null; deliveryMovPath: string | null; hasChecksum: boolean; qc: { result: string; reviewer: string | null; at: string } | null; } interface ReadyResponse { episodes: { episode: string; count: number; exports: ReadyExport[] }[]; } interface PackageRow { id: string; packageNumber: number; name: string; kind: "EXR_DELIVERY" | "MOV_REVIEW"; episode: string; status: string; rootPath: string | null; errorMessage: string | null; projectName: string; projectCode: string; createdAt: string; builtAt: string | null; uploadUrl: string | null; uploadedAt: string | null; uploadedByName: string | null; sharedWith: string | null; sharedNote: string | null; deliveredAt: string | null; deliveredByName: string | null; itemCount: number; verifiedCount: number; exrFileCount: number; movCount: number; totalBytes: number; items: { id: string; shotCode: string; clientCode: string | null; versionString: string; status: string; fileCount: number | null; linkMode: string | null; errorMessage: string | null; }[]; } interface ProjectOption { id: string; name: string; code: string; } function formatBytes(bytes: number | null): string { if (bytes == null) return "—"; const gb = bytes / 1_073_741_824; return gb >= 1 ? `${gb.toFixed(1)} GB` : `${(bytes / 1_048_576).toFixed(0)} MB`; } export function DeliveriesClient({ canBuild }: { canBuild: boolean }) { const { toast } = useToast(); const queryClient = useQueryClient(); const [projectId, setProjectId] = useState(""); const [episode, setEpisode] = useState(""); const [building, setBuilding] = useState(false); // Tracked as exclusions so every ready shot — including one that passes QC // while the page is open — starts selected. const [deselected, setDeselected] = useState>(() => new Set()); const [handoff, setHandoff] = useState<{ step: "upload" | "share"; packageId: string } | null>(null); const { data: projects } = useQuery({ queryKey: ["pipeline-projects"], queryFn: async () => { const res = await fetch("/api/projects"); if (!res.ok) throw new Error("Failed to load projects"); const body = await res.json(); return (body.projects ?? body) as ProjectOption[]; }, }); const { data: ready, isLoading: readyLoading } = useQuery({ queryKey: ["delivery-ready", projectId], queryFn: async () => { const res = await fetch(`/api/deliveries/ready?projectId=${encodeURIComponent(projectId)}`); if (!res.ok) throw new Error((await res.json().catch(() => ({})))?.error ?? "Failed to load ready exports"); return res.json() as Promise; }, enabled: Boolean(projectId), }); const { data: packages } = useQuery({ queryKey: ["delivery-packages", projectId], queryFn: async () => { const res = await fetch(`/api/deliveries${projectId ? `?projectId=${encodeURIComponent(projectId)}` : ""}`); if (!res.ok) throw new Error("Failed to load packages"); return res.json() as Promise<{ packages: PackageRow[] }>; }, // A build is a queued job like any other — poll while one is in flight. refetchInterval: 5000, }); function toggleExport(exportId: string, selected: boolean) { setDeselected((prev) => { const next = new Set(prev); if (selected) next.delete(exportId); else next.add(exportId); return next; }); } function setEpisodeSelected(exportIds: string[], selected: boolean) { setDeselected((prev) => { const next = new Set(prev); for (const id of exportIds) { if (selected) next.delete(id); else next.add(id); } return next; }); } async function build(ep: string, exportIds: string[]) { if (!projectId || exportIds.length === 0) return; setBuilding(true); try { // Always send the explicit list: the package holds exactly the shots // ticked on screen, never one that turned ready since the page loaded. const res = await fetch("/api/deliveries", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ projectId, episode: ep || null, exportIds }), }); const body = await res.json().catch(() => ({})); if (!res.ok) { toast({ title: "Build failed", description: body.error ?? res.statusText, variant: "destructive" }); } else { toast({ title: `Package #${body.package.packageNumber} queued`, description: `${body.package.itemCount} shots → ${body.package.rootPath}`, }); queryClient.invalidateQueries({ queryKey: ["delivery-packages"] }); queryClient.invalidateQueries({ queryKey: ["delivery-ready"] }); } } finally { setBuilding(false); } } function refreshPackages() { queryClient.invalidateQueries({ queryKey: ["delivery-packages"] }); queryClient.invalidateQueries({ queryKey: ["delivery-ready"] }); } async function cancelPackage(id: string) { const res = await fetch(`/api/deliveries/${id}/cancel`, { method: "POST" }); const body = await res.json().catch(() => ({})); if (!res.ok) { toast({ title: "Cancel failed", description: body.error ?? res.statusText, variant: "destructive" }); } refreshPackages(); } // Looked up from the live list so the dialog never acts on a stale row. const handoffPackage = handoff ? packages?.packages.find((p) => p.id === handoff.packageId) : undefined; const episodes = ready?.episodes ?? []; const shown = episode ? episodes.filter((e) => e.episode === episode) : episodes; return (

Delivery packages

{/* Picker */}
{episodes.length > 0 && ( )}
{/* Ready to build */} {projectId && (
Ready for delivery
{readyLoading &&
Loading…
} {!readyLoading && shown.length === 0 && (
Nothing has passed QC yet. Exports appear here once QC passes them.
)} {shown.map((ep) => { const allIds = ep.exports.map((x) => x.exportId); const selectedIds = allIds.filter((id) => !deselected.has(id)); const allSelected = selectedIds.length === allIds.length; const selectedExports = ep.exports.filter((x) => !deselected.has(x.exportId)); const missingChecksum = selectedExports.filter((x) => !x.hasChecksum).length; return (
{ep.episode ? `Episode ${ep.episode}` : "No episode"} {canBuild ? `Selected: ${selectedIds.length} of ${ep.count} shots` : `Ready: ${ep.count} shots`} {canBuild && selectedIds.length > 0 && ( {formatBytes(selectedExports.reduce((sum, x) => sum + (x.totalBytes ?? 0), 0))} )} {missingChecksum > 0 && ( {missingChecksum} without a validation checksum )}
{canBuild && ( )}
{ep.exports.map((x) => { const selected = !deselected.has(x.exportId); return (
{canBuild && ( toggleExport(x.exportId, e.target.checked)} aria-label={`Include ${x.shotCode} in the package`} /> )} {x.shotCode} {x.versionString} {x.fileCount ?? "?"} frames {formatBytes(x.totalBytes)} {!x.deliveryMovPath && no MOV}
); })}
); })}
)} {/* History — packages are permanent (§11.5) */}
Packages
{(packages?.packages ?? []).map((p) => { const stage = handoffStage(p); return (
#{p.packageNumber} {p.name} {p.kind === "MOV_REVIEW" && ( MOV review )} {stage === "AWAITING_UPLOAD" ? "BUILT — NOT UPLOADED" : stage === "AWAITING_SHARE" ? "UPLOADED — LINK NOT SHARED" : statusLabel(p.status)} {p.episode ? `episode ${p.episode} · ` : ""} {p.verifiedCount}/{p.itemCount} shots {new Date(p.createdAt).toLocaleDateString()} {p.status === "BUILDING" && } {canBuild && stage === "AWAITING_UPLOAD" && ( )} {canBuild && stage === "AWAITING_SHARE" && ( )} {canBuild && ["QUEUED", "FAILED", "DRAFT"].includes(p.status) && ( )}
{p.rootPath &&
{p.rootPath}
} {p.errorMessage &&
{p.errorMessage}
} {p.uploadedAt && p.uploadUrl && (
Uploaded {new Date(p.uploadedAt).toLocaleString()} {p.uploadedByName ? ` by ${p.uploadedByName}` : ""} —{" "} {p.uploadUrl} {canBuild && stage === "AWAITING_SHARE" && ( )}
)} {p.deliveredAt && (
{p.sharedWith ? `Link shared with ${p.sharedWith} ${new Date(p.deliveredAt).toLocaleString()}` : `Delivered ${new Date(p.deliveredAt).toLocaleString()} — before uploads and shares were recorded`} {p.deliveredByName ? ` by ${p.deliveredByName}` : ""} {p.sharedNote ? ` — ${p.sharedNote}` : ""}
)}
{p.items.map((item) => (
{item.status === "VERIFIED" ? "✓" : item.status === "FAILED" ? "✕" : "·"} {item.shotCode} {item.versionString} {p.kind === "EXR_DELIVERY" && item.fileCount != null && ( {item.fileCount}f )} {item.linkMode && {item.linkMode}} {item.errorMessage && {item.errorMessage}}
))}
); })} {(packages?.packages ?? []).length === 0 && (
No packages built yet
)}
{handoff?.step === "upload" && handoffPackage && ( setHandoff(null)} onSaved={refreshPackages} /> )} {handoff?.step === "share" && handoffPackage?.uploadUrl && ( setHandoff(null)} onSaved={refreshPackages} /> )}
); }