"use client"; import { useState } from "react"; import Link from "next/link"; import { useQuery, useQueryClient } from "@tanstack/react-query"; import { ArrowLeft, Package, CheckCircle2, XCircle, RefreshCw } from "lucide-react"; import { Button } from "@/components/ui/button"; import { useToast } from "@/components/ui/use-toast"; import { cn } from "@/lib/utils"; import { DELIVERY_STATUS_STYLES, statusLabel } from "../status-colors"; 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; createdAt: string; builtAt: string | null; deliveredAt: string | null; itemCount: number; verifiedCount: number; items: { id: string; shotCode: string; 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); 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, }); async function build(ep: string) { if (!projectId) return; setBuilding(true); try { const res = await fetch("/api/deliveries", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ projectId, episode: ep || null }), }); 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); } } async function packageAction(id: string, verb: "delivered" | "cancel") { const res = await fetch(`/api/deliveries/${id}/${verb}`, { method: "POST" }); const body = await res.json().catch(() => ({})); if (!res.ok) { toast({ title: `${verb} failed`, description: body.error ?? res.statusText, variant: "destructive" }); } queryClient.invalidateQueries({ queryKey: ["delivery-packages"] }); queryClient.invalidateQueries({ queryKey: ["delivery-ready"] }); } 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) => (
{ep.episode ? `Episode ${ep.episode}` : "No episode"} Ready: {ep.count} shots {ep.exports.some((x) => !x.hasChecksum) && ( {ep.exports.filter((x) => !x.hasChecksum).length} without a validation checksum )}
{canBuild && ( )}
{ep.exports.map((x) => (
{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) => (
#{p.packageNumber} {p.name} {p.kind === "MOV_REVIEW" && ( MOV review )} {statusLabel(p.status)} {p.episode ? `episode ${p.episode} · ` : ""} {p.verifiedCount}/{p.itemCount} shots {new Date(p.createdAt).toLocaleDateString()} {p.status === "BUILDING" && } {canBuild && p.status === "READY" && p.kind === "EXR_DELIVERY" && ( )} {canBuild && ["QUEUED", "FAILED", "DRAFT"].includes(p.status) && ( )}
{p.rootPath &&
{p.rootPath}
} {p.errorMessage &&
{p.errorMessage}
} {p.deliveredAt && (
Delivered {new Date(p.deliveredAt).toLocaleString()}
)}
{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
)}
); }