"use client"; import { useState } from "react"; import { useQuery, useQueryClient } from "@tanstack/react-query"; import { Package, Plus, XCircle } from "lucide-react"; import { Button } from "@/components/ui/button"; import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog"; import { Input } from "@/components/ui/input"; import { useToast } from "@/components/ui/use-toast"; import { cn } from "@/lib/utils"; import { LogRequestDialog } from "@/components/delivery/LogRequestDialog"; import { DELIVERABLE_LABEL, LINE_STAGE_LABEL, type Deliverable, type RequestLineStage, } from "@/lib/render-pipeline/delivery-request-state"; interface RequestRow { id: string; requestNumber: number; projectId: string; projectCode: string; episode: string; deliverable: string; requestedBy: string; note: string | null; dueDate: string | null; createdAt: string; cancelReason: string | null; state: "OPEN" | "CLOSED" | "CANCELLED"; lineCount: number; deliveredCount: number; severity: "normal" | "warning" | "critical"; lines: { id: string; shotCode: string; clientCode: string | null; stage: RequestLineStage; readyExportId: string | null; }[]; } const SEVERITY_STYLES: Record = { normal: "bg-zinc-500/15 text-zinc-300 border-zinc-500/30", warning: "bg-amber-500/15 text-amber-400 border-amber-500/30", critical: "bg-red-500/15 text-red-400 border-red-500/30", }; const STAGE_STYLES: Record = { DELIVERED: "text-emerald-400", UPLOADED: "text-amber-400", BUILT: "text-amber-400", BUILDING: "text-blue-400", READY: "text-green-400", IN_QC: "text-zinc-400", NOT_READY: "text-zinc-500", }; function requestTitle(r: RequestRow): string { const what = DELIVERABLE_LABEL[r.deliverable as Deliverable] ?? r.deliverable; return r.episode ? `${what} for ${r.episode}` : `${what} · ${r.lineCount} shot${r.lineCount === 1 ? "" : "s"}`; } /** * What clients have asked for. An open request lists every shot with where it * stands, so "did 116 go out?" is answered by the page rather than by memory. */ export function RequestsPanel({ projectId, canBuild }: { projectId: string; canBuild: boolean }) { const { toast } = useToast(); const queryClient = useQueryClient(); const [logging, setLogging] = useState(false); const [cancelling, setCancelling] = useState(null); const [reason, setReason] = useState(""); const [busy, setBusy] = useState(false); const { data } = useQuery({ queryKey: ["delivery-requests", projectId], queryFn: async () => { const res = await fetch(`/api/delivery-requests${projectId ? `?projectId=${encodeURIComponent(projectId)}` : ""}`); if (!res.ok) throw new Error("Failed to load delivery requests"); return res.json() as Promise<{ requests: RequestRow[] }>; }, // Lines move as packages build and get shared on this same page. refetchInterval: 5000, }); const refresh = () => { queryClient.invalidateQueries({ queryKey: ["delivery-requests"] }); queryClient.invalidateQueries({ queryKey: ["delivery-packages"] }); queryClient.invalidateQueries({ queryKey: ["delivery-ready"] }); }; async function build(request: RequestRow) { const exportIds = request.lines.flatMap((l) => (l.readyExportId ? [l.readyExportId] : [])); if (!exportIds.length) return; setBusy(true); const res = await fetch("/api/deliveries", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ projectId: request.projectId, episode: request.episode || null, exportIds }), }); const body = await res.json().catch(() => ({})); setBusy(false); 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 for request #${request.requestNumber}`, }); } refresh(); } async function cancel() { if (!cancelling) return; setBusy(true); const res = await fetch(`/api/delivery-requests/${cancelling.id}/cancel`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ reason }), }); const body = await res.json().catch(() => ({})); setBusy(false); if (!res.ok) { toast({ title: "Not cancelled", description: body.error ?? res.statusText, variant: "destructive" }); return; } setCancelling(null); refresh(); } const requests = data?.requests ?? []; const open = requests.filter((r) => r.state === "OPEN"); const past = requests.filter((r) => r.state !== "OPEN"); return (
Delivery requests {canBuild && ( )}
{open.length === 0 &&
No open requests.
}
{open.map((r) => { const readyCount = r.lines.filter((l) => l.readyExportId).length; return (
Request #{r.requestNumber} {requestTitle(r)} {r.deliveredCount} of {r.lineCount} delivered {r.projectCode} · asked by {r.requestedBy} · {new Date(r.createdAt).toLocaleDateString()} {r.dueDate ? ` · due ${new Date(r.dueDate).toLocaleDateString()}` : ""} {canBuild && readyCount > 0 && ( )} {canBuild && ( )}
{r.note &&
{r.note}
}
{r.lines.map((line) => (
{line.shotCode} {line.clientCode && {line.clientCode}} {LINE_STAGE_LABEL[line.stage]}
))}
); })}
{past.length > 0 && (
Closed and cancelled ({past.length})
{past.map((r) => (
Request #{r.requestNumber} {requestTitle(r)} · {r.projectCode} · asked by {r.requestedBy} ·{" "} {r.state === "CANCELLED" ? ( cancelled — {r.cancelReason} ) : ( all {r.lineCount} delivered )}
))}
)} setLogging(false)} onLogged={refresh} defaultProjectId={projectId || undefined} /> {cancelling && ( !o && !busy && setCancelling(null)}> Cancel request #{cancelling.requestNumber} {cancelling.lineCount - cancelling.deliveredCount} of {cancelling.lineCount} shots have not been delivered. Cancelling removes the request from Awaiting delivery; it stays in the history with the reason. setReason(e.target.value)} autoFocus /> )}
); }