feat(deliveries): delivery requests and upload/share evidence
Deploy / deploy (push) Successful in 5m17s

A built package used to become DELIVERED on one click with nothing behind
it, and nothing recorded what a client had asked for.

- Marking delivered is now two recorded steps: Record upload (the link on
  the client's portal, contents confirmed) then Share link (who it was sent
  to). The second is refused until the first is on record.
- Delivery requests log a client's ask by episode, pasted shot codes or a
  Shot Status selection. A line closes only when its shot goes out with
  evidence after the request was logged; a request can otherwise only be
  cancelled with a reason.
- Delivered Outside Pipeline takes an upload link and recipient, required
  for shots on an open request.
- The dashboard gains an Awaiting delivery section listing open requests
  and built packages the client does not have yet.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
twotalesanimation
2026-09-30 14:21:24 +02:00
parent 326d8cbefa
commit f30acef101
25 changed files with 2241 additions and 52 deletions
+31 -1
View File
@@ -5,12 +5,15 @@ import { BlockedQueue } from "@/components/dashboard/BlockedQueue";
import { FarmStrip } from "@/components/dashboard/FarmStrip";
import { DeliveryCountdown } from "@/components/dashboard/DeliveryCountdown";
import { QcQueue } from "@/components/dashboard/QcQueue";
import { AwaitingDelivery } from "@/components/dashboard/AwaitingDelivery";
import { LogRequestButton } from "@/components/dashboard/LogRequestButton";
import { RecentDeliveries } from "@/components/dashboard/RecentDeliveries";
import { WhoseCourt } from "@/components/dashboard/WhoseCourt";
import { ShotQueue } from "@/components/dashboard/ShotQueue";
import { TaskWidgets } from "@/components/dashboard/TaskWidgets";
import { ScheduleWidgets } from "@/components/dashboard/ScheduleWidgets";
import {
getAwaitingDelivery,
getBlockedExports,
getDeliveryCountdown,
getFarmStatus,
@@ -20,6 +23,7 @@ import {
getRecentDeliveries,
getWhoseCourt,
} from "@/lib/dashboard/ops";
import { listDeliveryRequests } from "@/lib/render-pipeline/delivery-requests";
import type { DashboardStats } from "@/types";
export const metadata = { title: "Dashboard" };
@@ -37,7 +41,7 @@ async function getDashboardData(userId: string, role: string) {
const isClient = role === "CLIENT";
// Producers see the floor; an artist sees the failures that are theirs.
const [counts, blocked, farm, episodes, qcQueue, qcStaleHours, deliveries, court] =
const [counts, blocked, farm, episodes, qcQueue, qcStaleHours, deliveries, awaitingDelivery, openRequests, court] =
await Promise.all([
getOpsCounts(isArtist ? userId : undefined),
getBlockedExports(isArtist ? { artistId: userId } : {}),
@@ -46,6 +50,8 @@ async function getDashboardData(userId: string, role: string) {
isArtist || isClient ? [] : getQcQueue(),
getQcStaleHours(),
isArtist || isClient ? [] : getRecentDeliveries(),
isArtist || isClient ? [] : getAwaitingDelivery(),
isArtist || isClient ? [] : listDeliveryRequests({ openOnly: true }),
isArtist || isClient ? null : getWhoseCourt(),
]);
@@ -128,6 +134,8 @@ async function getDashboardData(userId: string, role: string) {
qcQueue,
qcStaleHours,
deliveries,
awaitingDelivery,
openRequests,
court,
shots,
myTasks,
@@ -152,6 +160,8 @@ export default async function DashboardPage() {
qcQueue,
qcStaleHours,
deliveries,
awaitingDelivery,
openRequests,
court,
shots,
myTasks,
@@ -171,6 +181,26 @@ export default async function DashboardPage() {
{!isClient && <StatsCards stats={stats} />}
{/* Rows only clear by being dealt with; the heading stays so there is
always somewhere to log what a client just asked for. */}
{!isClient && !isArtistRole && (
<div className="space-y-3">
<div className="flex items-center justify-between gap-3">
<h2
className={
openRequests.length + awaitingDelivery.length > 0
? "text-sm font-semibold text-amber-400 uppercase tracking-wide"
: "text-sm font-semibold text-muted-foreground uppercase tracking-wide"
}
>
Awaiting delivery
</h2>
{canSeeSchedule && <LogRequestButton />}
</div>
<AwaitingDelivery requests={openRequests} packages={awaitingDelivery} />
</div>
)}
{!isClient && (
<div className="space-y-3">
<h2 className="text-sm font-semibold text-muted-foreground uppercase tracking-wide">
@@ -3,11 +3,14 @@
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 { 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;
@@ -35,14 +38,25 @@ interface PackageRow {
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;
@@ -69,6 +83,7 @@ export function DeliveriesClient({ canBuild }: { canBuild: boolean }) {
const [projectId, setProjectId] = useState<string>("");
const [episode, setEpisode] = useState<string>("");
const [building, setBuilding] = useState(false);
const [handoff, setHandoff] = useState<{ step: "upload" | "share"; packageId: string } | null>(null);
const { data: projects } = useQuery({
queryKey: ["pipeline-projects"],
@@ -126,16 +141,23 @@ export function DeliveriesClient({ canBuild }: { canBuild: boolean }) {
}
}
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" });
}
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;
@@ -183,6 +205,8 @@ export function DeliveriesClient({ canBuild }: { canBuild: boolean }) {
)}
</div>
<RequestsPanel projectId={projectId} canBuild={canBuild} />
{/* Ready to build */}
{projectId && (
<div className="rounded-lg border border-zinc-800 bg-zinc-900/40">
@@ -238,7 +262,9 @@ export function DeliveriesClient({ canBuild }: { canBuild: boolean }) {
<div className="rounded-lg border border-zinc-800 bg-zinc-900/40">
<div className="px-4 py-2.5 border-b border-zinc-800 text-sm font-medium text-white">Packages</div>
<div className="divide-y divide-zinc-800/60">
{(packages?.packages ?? []).map((p) => (
{(packages?.packages ?? []).map((p) => {
const stage = handoffStage(p);
return (
<details key={p.id} className="group">
<summary className="flex items-center gap-3 px-4 py-3 cursor-pointer hover:bg-zinc-900/60 flex-wrap">
<span className="text-sm text-white font-medium">#{p.packageNumber}</span>
@@ -251,10 +277,16 @@ export function DeliveriesClient({ canBuild }: { canBuild: boolean }) {
<span
className={cn(
"rounded-full border px-2 py-0.5 text-xs",
DELIVERY_STATUS_STYLES[p.status] ?? ""
// Built is not delivered: a package still owed to the
// client must not read as a green "READY".
stage ? "bg-amber-500/15 text-amber-400 border-amber-500/30" : (DELIVERY_STATUS_STYLES[p.status] ?? "")
)}
>
{statusLabel(p.status)}
{stage === "AWAITING_UPLOAD"
? "BUILT — NOT UPLOADED"
: stage === "AWAITING_SHARE"
? "UPLOADED — LINK NOT SHARED"
: statusLabel(p.status)}
</span>
<span className="text-xs text-zinc-500">
{p.episode ? `episode ${p.episode} · ` : ""}
@@ -263,17 +295,30 @@ export function DeliveriesClient({ canBuild }: { canBuild: boolean }) {
<span className="text-xs text-zinc-600">{new Date(p.createdAt).toLocaleDateString()}</span>
{p.status === "BUILDING" && <RefreshCw className="h-3.5 w-3.5 text-blue-400 animate-spin" />}
<span className="ml-auto flex items-center gap-2">
{canBuild && p.status === "READY" && p.kind === "EXR_DELIVERY" && (
{canBuild && stage === "AWAITING_UPLOAD" && (
<Button
size="sm"
variant="outline"
onClick={(e) => {
e.preventDefault();
packageAction(p.id, "delivered");
setHandoff({ step: "upload", packageId: p.id });
}}
>
<Upload className="h-4 w-4 mr-2 text-amber-400" />
Record upload
</Button>
)}
{canBuild && stage === "AWAITING_SHARE" && (
<Button
size="sm"
variant="outline"
onClick={(e) => {
e.preventDefault();
setHandoff({ step: "share", packageId: p.id });
}}
>
<CheckCircle2 className="h-4 w-4 mr-2 text-emerald-400" />
Mark delivered
Share link
</Button>
)}
{canBuild && ["QUEUED", "FAILED", "DRAFT"].includes(p.status) && (
@@ -282,7 +327,7 @@ export function DeliveriesClient({ canBuild }: { canBuild: boolean }) {
variant="outline"
onClick={(e) => {
e.preventDefault();
packageAction(p.id, "cancel");
cancelPackage(p.id);
}}
>
<XCircle className="h-4 w-4 mr-2 text-red-400" />
@@ -294,9 +339,31 @@ export function DeliveriesClient({ canBuild }: { canBuild: boolean }) {
<div className="px-4 pb-4 space-y-2">
{p.rootPath && <div className="text-xs text-zinc-500 break-all">{p.rootPath}</div>}
{p.errorMessage && <div className="text-xs text-red-400">{p.errorMessage}</div>}
{p.uploadedAt && p.uploadUrl && (
<div className="text-xs text-zinc-400 break-all">
Uploaded {new Date(p.uploadedAt).toLocaleString()}
{p.uploadedByName ? ` by ${p.uploadedByName}` : ""} —{" "}
<a href={p.uploadUrl} target="_blank" rel="noreferrer" className="text-sky-400 hover:underline">
{p.uploadUrl}
</a>
{canBuild && stage === "AWAITING_SHARE" && (
<button
type="button"
className="ml-2 text-zinc-500 hover:text-white underline"
onClick={() => setHandoff({ step: "upload", packageId: p.id })}
>
change
</button>
)}
</div>
)}
{p.deliveredAt && (
<div className="text-xs text-emerald-400">
Delivered {new Date(p.deliveredAt).toLocaleString()}
{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}` : ""}
</div>
)}
<div className="grid sm:grid-cols-2 lg:grid-cols-3 gap-x-6 gap-y-1">
@@ -325,12 +392,24 @@ export function DeliveriesClient({ canBuild }: { canBuild: boolean }) {
</div>
</div>
</details>
))}
);
})}
{(packages?.packages ?? []).length === 0 && (
<div className="p-4 text-sm text-zinc-500">No packages built yet</div>
)}
</div>
</div>
{handoff?.step === "upload" && handoffPackage && (
<RecordUploadDialog pkg={handoffPackage} onClose={() => setHandoff(null)} onSaved={refreshPackages} />
)}
{handoff?.step === "share" && handoffPackage?.uploadUrl && (
<RecordShareDialog
pkg={{ ...handoffPackage, uploadUrl: handoffPackage.uploadUrl }}
onClose={() => setHandoff(null)}
onSaved={refreshPackages}
/>
)}
</div>
);
}
@@ -0,0 +1,218 @@
"use client";
import { useState } from "react";
import { Copy } 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 { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { useToast } from "@/components/ui/use-toast";
import { buildShareMessage } from "@/lib/render-pipeline/delivery-handoff";
export interface HandoffPackage {
id: string;
packageNumber: number;
name: string;
projectCode: string;
episode: string;
rootPath: string | null;
uploadUrl: string | null;
itemCount: number;
exrFileCount: number;
movCount: number;
totalBytes: number;
items: { shotCode: string; clientCode: string | null; versionString: string }[];
}
function formatSize(bytes: number): string {
if (!bytes) return "size unknown";
const gb = bytes / 1_073_741_824;
return gb >= 1 ? `${gb.toFixed(1)} GB` : `${(bytes / 1_048_576).toFixed(0)} MB`;
}
async function post(path: string, body: unknown): Promise<string | null> {
const res = await fetch(path, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(body),
});
if (res.ok) return null;
const data = await res.json().catch(() => ({}));
return data.error ?? res.statusText;
}
/** Step one: where the folder now lives on the client's side. */
export function RecordUploadDialog({
pkg,
onClose,
onSaved,
}: {
pkg: HandoffPackage;
onClose: () => void;
onSaved: () => void;
}) {
const { toast } = useToast();
const [uploadUrl, setUploadUrl] = useState(pkg.uploadUrl ?? "");
const [confirmed, setConfirmed] = useState(false);
const [saving, setSaving] = useState(false);
async function save() {
setSaving(true);
const error = await post(`/api/deliveries/${pkg.id}/uploaded`, { uploadUrl, contentsConfirmed: confirmed });
setSaving(false);
if (error) {
toast({ title: "Upload not recorded", description: error, variant: "destructive" });
return;
}
onSaved();
onClose();
}
return (
<Dialog open onOpenChange={(open) => !open && onClose()}>
<DialogContent>
<DialogHeader>
<DialogTitle>
Record upload — #{pkg.packageNumber} {pkg.name}
</DialogTitle>
<DialogDescription>
Paste the link to the folder on the client&apos;s portal. The package stays on the dashboard as
awaiting delivery until the link has also been shared.
</DialogDescription>
</DialogHeader>
<div className="space-y-4">
<div className="rounded-md border border-zinc-800 bg-zinc-900/60 p-3 text-xs text-zinc-400 space-y-1">
<div className="text-zinc-200">
The upload should contain {pkg.itemCount} shot{pkg.itemCount === 1 ? "" : "s"} · {pkg.exrFileCount} EXR
frames · {pkg.movCount} MOV{pkg.movCount === 1 ? "" : "s"} · {formatSize(pkg.totalBytes)}
</div>
{pkg.rootPath && <div className="break-all">Source: {pkg.rootPath}</div>}
</div>
<div className="space-y-1.5">
<Label htmlFor="upload-url">Upload link</Label>
<Input
id="upload-url"
type="url"
placeholder="https://…"
value={uploadUrl}
onChange={(e) => setUploadUrl(e.target.value)}
autoFocus
/>
</div>
<label className="flex items-start gap-2 text-sm text-zinc-300">
<input
type="checkbox"
className="mt-1"
checked={confirmed}
onChange={(e) => setConfirmed(e.target.checked)}
/>
<span>I opened this link and the upload has finished and matches the counts above.</span>
</label>
</div>
<DialogFooter>
<Button variant="outline" onClick={onClose}>
Cancel
</Button>
<Button onClick={save} disabled={saving || !uploadUrl.trim() || !confirmed}>
Record upload
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
);
}
/** Step two: the link went to a person. This is what makes it delivered. */
export function RecordShareDialog({
pkg,
onClose,
onSaved,
}: {
pkg: HandoffPackage & { uploadUrl: string };
onClose: () => void;
onSaved: () => void;
}) {
const { toast } = useToast();
const [sharedWith, setSharedWith] = useState("");
const [note, setNote] = useState("");
const [saving, setSaving] = useState(false);
const message = buildShareMessage(pkg);
async function copy() {
try {
await navigator.clipboard.writeText(message);
toast({ title: "Message copied" });
} catch {
toast({ title: "Could not copy", description: "Select the text and copy it by hand.", variant: "destructive" });
}
}
async function save() {
setSaving(true);
const error = await post(`/api/deliveries/${pkg.id}/delivered`, { sharedWith, note: note || null });
setSaving(false);
if (error) {
toast({ title: "Not marked delivered", description: error, variant: "destructive" });
return;
}
onSaved();
onClose();
}
return (
<Dialog open onOpenChange={(open) => !open && onClose()}>
<DialogContent>
<DialogHeader>
<DialogTitle>
Share link — #{pkg.packageNumber} {pkg.name}
</DialogTitle>
<DialogDescription>
Send this message to the client, then record who it went to. That marks the package delivered.
</DialogDescription>
</DialogHeader>
<div className="space-y-4">
<div className="space-y-1.5">
<div className="flex items-center justify-between">
<Label htmlFor="share-message">Message</Label>
<Button size="sm" variant="outline" onClick={copy}>
<Copy className="h-3.5 w-3.5 mr-2" />
Copy message
</Button>
</div>
<Textarea id="share-message" readOnly value={message} rows={8} className="font-mono text-xs" />
</div>
<div className="space-y-1.5">
<Label htmlFor="shared-with">Sent to</Label>
<Input
id="shared-with"
placeholder="Name, and where — e.g. Sam, production WhatsApp group"
value={sharedWith}
onChange={(e) => setSharedWith(e.target.value)}
/>
</div>
<div className="space-y-1.5">
<Label htmlFor="share-note">Note (optional)</Label>
<Input id="share-note" value={note} onChange={(e) => setNote(e.target.value)} />
</div>
</div>
<DialogFooter>
<Button variant="outline" onClick={onClose}>
Cancel
</Button>
<Button onClick={save} disabled={saving || !sharedWith.trim()}>
Link sent — mark delivered
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
);
}
@@ -0,0 +1,273 @@
"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<RequestRow["severity"], string> = {
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<RequestLineStage, string> = {
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<RequestRow | null>(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 (
<div className="rounded-lg border border-zinc-800 bg-zinc-900/40">
<div className="flex items-center justify-between gap-3 px-4 py-2.5 border-b border-zinc-800">
<span className="text-sm font-medium text-white">Delivery requests</span>
{canBuild && (
<Button size="sm" variant="outline" onClick={() => setLogging(true)}>
<Plus className="h-3.5 w-3.5 mr-1.5" />
Log request
</Button>
)}
</div>
{open.length === 0 && <div className="p-4 text-sm text-zinc-500">No open requests.</div>}
<div className="divide-y divide-zinc-800/60">
{open.map((r) => {
const readyCount = r.lines.filter((l) => l.readyExportId).length;
return (
<details key={r.id} open className="group">
<summary className="flex items-center gap-3 px-4 py-3 cursor-pointer hover:bg-zinc-900/60 flex-wrap">
<span className="text-sm text-white font-medium">Request #{r.requestNumber}</span>
<span className="text-sm text-zinc-300">{requestTitle(r)}</span>
<span className={cn("rounded-full border px-2 py-0.5 text-xs", SEVERITY_STYLES[r.severity])}>
{r.deliveredCount} of {r.lineCount} delivered
</span>
<span className="text-xs text-zinc-500">
{r.projectCode} · asked by {r.requestedBy} · {new Date(r.createdAt).toLocaleDateString()}
{r.dueDate ? ` · due ${new Date(r.dueDate).toLocaleDateString()}` : ""}
</span>
<span className="ml-auto flex items-center gap-2">
{canBuild && readyCount > 0 && (
<Button
size="sm"
disabled={busy}
onClick={(e) => {
e.preventDefault();
build(r);
}}
>
<Package className="h-4 w-4 mr-2" />
Build {readyCount} ready
</Button>
)}
{canBuild && (
<Button
size="sm"
variant="outline"
onClick={(e) => {
e.preventDefault();
setReason("");
setCancelling(r);
}}
>
<XCircle className="h-4 w-4 mr-2 text-red-400" />
Cancel request
</Button>
)}
</span>
</summary>
<div className="px-4 pb-4 space-y-2">
{r.note && <div className="text-xs text-zinc-400">{r.note}</div>}
<div className="grid sm:grid-cols-2 lg:grid-cols-3 gap-x-6 gap-y-1">
{r.lines.map((line) => (
<div key={line.id} className="flex items-center gap-2 text-xs">
<span className="text-zinc-300">{line.shotCode}</span>
{line.clientCode && <span className="text-zinc-600">{line.clientCode}</span>}
<span className={STAGE_STYLES[line.stage]}>{LINE_STAGE_LABEL[line.stage]}</span>
</div>
))}
</div>
</div>
</details>
);
})}
</div>
{past.length > 0 && (
<details className="border-t border-zinc-800">
<summary className="px-4 py-2.5 cursor-pointer text-xs text-zinc-500 hover:text-zinc-300">
Closed and cancelled ({past.length})
</summary>
<div className="px-4 pb-3 space-y-1">
{past.map((r) => (
<div key={r.id} className="text-xs text-zinc-500">
<span className="text-zinc-300">Request #{r.requestNumber}</span> {requestTitle(r)} · {r.projectCode} ·
asked by {r.requestedBy} ·{" "}
{r.state === "CANCELLED" ? (
<span className="text-zinc-400">cancelled — {r.cancelReason}</span>
) : (
<span className="text-emerald-400">all {r.lineCount} delivered</span>
)}
</div>
))}
</div>
</details>
)}
<LogRequestDialog
open={logging}
onClose={() => setLogging(false)}
onLogged={refresh}
defaultProjectId={projectId || undefined}
/>
{cancelling && (
<Dialog open onOpenChange={(o) => !o && !busy && setCancelling(null)}>
<DialogContent>
<DialogHeader>
<DialogTitle>Cancel request #{cancelling.requestNumber}</DialogTitle>
<DialogDescription>
{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.
</DialogDescription>
</DialogHeader>
<Input
aria-label="Reason"
placeholder="Why — e.g. client no longer needs 116"
value={reason}
onChange={(e) => setReason(e.target.value)}
autoFocus
/>
<DialogFooter>
<Button variant="outline" onClick={() => setCancelling(null)} disabled={busy}>
Keep request
</Button>
<Button variant="destructive" onClick={cancel} disabled={busy || !reason.trim()}>
Cancel request
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
)}
</div>
);
}
@@ -35,6 +35,7 @@ import { cn, getInitials } from "@/lib/utils";
import { updateShotNotes, bulkUpdateDueDates, bulkAssignArtist, bulkDeleteShots, bulkSetManualDelivery, toggleKeyShot, toggleScaledShot } from "@/actions/shots";
import { previewMovReview, buildMovReview } from "@/actions/deliveries";
import { useToast } from "@/components/ui/use-toast";
import { LogRequestDialog } from "@/components/delivery/LogRequestDialog";
import {
Film,
Clock,
@@ -55,6 +56,7 @@ import {
Scaling,
UserPlus,
PackageCheck,
ClipboardList,
} from "lucide-react";
import { format } from "date-fns";
import { shotThumbnail } from "@/lib/shot-thumbnail";
@@ -373,11 +375,17 @@ function ManualDeliveryDialog({
}: {
open: boolean;
onClose: () => void;
onApply: (deliveredOn: string | null, note: string) => Promise<void>;
onApply: (
deliveredOn: string | null,
note: string,
evidence: { uploadUrl: string; sharedWith: string },
) => Promise<void>;
count: number;
}) {
const [date, setDate] = useState("");
const [note, setNote] = useState("");
const [uploadUrl, setUploadUrl] = useState("");
const [sharedWith, setSharedWith] = useState("");
const [clearing, setClearing] = useState(false);
const [isPending, startTransition] = useTransition();
@@ -385,6 +393,8 @@ function ManualDeliveryDialog({
if (open) {
setDate("");
setNote("");
setUploadUrl("");
setSharedWith("");
setClearing(false);
}
}, [open]);
@@ -392,7 +402,7 @@ function ManualDeliveryDialog({
const handleApply = () => {
if (!clearing && !date) return;
startTransition(async () => {
await onApply(clearing ? null : date, note);
await onApply(clearing ? null : date, note, { uploadUrl, sharedWith });
});
};
@@ -444,6 +454,30 @@ function ManualDeliveryDialog({
className="w-full rounded-md border border-zinc-700 bg-zinc-900 px-3 py-2 text-sm text-zinc-100 [color-scheme:dark] focus:border-zinc-500 focus:outline-none focus:ring-1 focus:ring-zinc-500"
/>
</div>
<div className="space-y-1.5">
<label className="text-xs font-medium text-zinc-400">Upload link</label>
<input
type="url"
value={uploadUrl}
onChange={(e) => setUploadUrl(e.target.value)}
placeholder="https://…"
className="w-full rounded-md border border-zinc-700 bg-zinc-900 px-3 py-2 text-sm text-zinc-100 placeholder:text-zinc-600 focus:border-zinc-500 focus:outline-none focus:ring-1 focus:ring-zinc-500"
/>
</div>
<div className="space-y-1.5">
<label className="text-xs font-medium text-zinc-400">Link sent to</label>
<input
type="text"
value={sharedWith}
onChange={(e) => setSharedWith(e.target.value)}
placeholder="Name, and where it was sent"
className="w-full rounded-md border border-zinc-700 bg-zinc-900 px-3 py-2 text-sm text-zinc-100 placeholder:text-zinc-600 focus:border-zinc-500 focus:outline-none focus:ring-1 focus:ring-zinc-500"
/>
<p className="text-xs text-zinc-500">
Both are needed for shots on an open delivery request; a backfill of old deliveries can leave
them blank.
</p>
</div>
<div className="space-y-1.5">
<label className="text-xs font-medium text-zinc-400">Note (optional)</label>
<Textarea
@@ -1086,6 +1120,7 @@ export function ShotStatusClient({
const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
const [movReviewDialogOpen, setMovReviewDialogOpen] = useState(false);
const [manualDeliveryDialogOpen, setManualDeliveryDialogOpen] = useState(false);
const [requestDialogOpen, setRequestDialogOpen] = useState(false);
const toggleEpisode = (ep: string) =>
setExpandedEpisodes((prev) => {
@@ -1185,10 +1220,19 @@ export function ShotStatusClient({
}
};
const handleManualDelivery = async (deliveredOn: string | null, note: string) => {
const handleManualDelivery = async (
deliveredOn: string | null,
note: string,
evidence: { uploadUrl: string; sharedWith: string },
) => {
try {
const result = await bulkSetManualDelivery([...selectedIds], deliveredOn, note);
const n = `${result.updated} shot${result.updated !== 1 ? "s" : ""}`;
const result = await bulkSetManualDelivery([...selectedIds], deliveredOn, note, evidence);
if (!result.success) {
// The dialog stays open so the missing link and recipient can be added.
toast({ title: "Not marked delivered", description: result.error, variant: "destructive" });
return;
}
const n =`${result.updated} shot${result.updated !== 1 ? "s" : ""}`;
toast({ title: deliveredOn ? `${n} marked delivered` : `Manual delivery cleared on ${n}` });
setManualDeliveryDialogOpen(false);
clearSelection();
@@ -1384,6 +1428,10 @@ export function ShotStatusClient({
<Clapperboard className="h-3.5 w-3.5 mr-2" />
Build MOV Review Package
</DropdownMenuItem>
<DropdownMenuItem onClick={() => setRequestDialogOpen(true)}>
<ClipboardList className="h-3.5 w-3.5 mr-2" />
Log Delivery Request
</DropdownMenuItem>
<DropdownMenuItem onClick={() => setManualDeliveryDialogOpen(true)}>
<PackageCheck className="h-3.5 w-3.5 mr-2" />
Delivered Outside Pipeline
@@ -1610,6 +1658,16 @@ export function ShotStatusClient({
count={selectionCount}
/>
{/* A client asked for the selected shots */}
{selectedProjectId && (
<LogRequestDialog
open={requestDialogOpen}
onClose={() => setRequestDialogOpen(false)}
onLogged={clearSelection}
preset={{ projectId: selectedProjectId, shotIds: [...selectedIds] }}
/>
)}
{/* Bulk delete dialog */}
<BulkDeleteDialog
open={deleteDialogOpen}
@@ -2,20 +2,30 @@ import { NextRequest, NextResponse } from "next/server";
import { toErrorResponse } from "@/lib/render-pipeline/errors";
import { requirePipelineAdmin } from "@/lib/render-pipeline/session-auth";
import { markDelivered } from "@/lib/render-pipeline/deliveries";
import { recordShareSchema } from "@/lib/render-pipeline/delivery-handoff";
// ── POST /api/deliveries/{id}/delivered (E19) ────────────────────────────────
//
// The folder has been uploaded to the client. Moves every packaged export to
// DELIVERED — the end of the pipeline.
// The upload link has been sent to the client. Takes who it was sent to, and
// moves every packaged export to DELIVERED — the end of the pipeline.
export async function POST(
_req: NextRequest,
req: NextRequest,
{ params }: { params: Promise<{ packageId: string }> }
) {
try {
const user = await requirePipelineAdmin();
const { packageId } = await params;
const result = await markDelivered(packageId, user.id);
const parsed = recordShareSchema.safeParse(await req.json().catch(() => null));
if (!parsed.success) {
return NextResponse.json(
{ error: parsed.error.issues[0]?.message ?? "Invalid request", details: parsed.error.issues },
{ status: 422 }
);
}
const result = await markDelivered(packageId, parsed.data, user.id);
return NextResponse.json(result);
} catch (err) {
const { body, status } = toErrorResponse(err);
@@ -0,0 +1,34 @@
import { NextRequest, NextResponse } from "next/server";
import { toErrorResponse } from "@/lib/render-pipeline/errors";
import { requirePipelineAdmin } from "@/lib/render-pipeline/session-auth";
import { markUploaded } from "@/lib/render-pipeline/deliveries";
import { recordUploadSchema } from "@/lib/render-pipeline/delivery-handoff";
// ── POST /api/deliveries/{id}/uploaded ───────────────────────────────────────
//
// The folder is on the client's portal. Records where, so the package shows as
// waiting to be shared rather than waiting to be uploaded.
export async function POST(
req: NextRequest,
{ params }: { params: Promise<{ packageId: string }> }
) {
try {
const user = await requirePipelineAdmin();
const { packageId } = await params;
const parsed = recordUploadSchema.safeParse(await req.json().catch(() => null));
if (!parsed.success) {
return NextResponse.json(
{ error: parsed.error.issues[0]?.message ?? "Invalid request", details: parsed.error.issues },
{ status: 422 }
);
}
const result = await markUploaded(packageId, parsed.data, user.id);
return NextResponse.json(result);
} catch (err) {
const { body, status } = toErrorResponse(err);
return NextResponse.json(body, { status });
}
}
@@ -0,0 +1,34 @@
import { NextRequest, NextResponse } from "next/server";
import { toErrorResponse } from "@/lib/render-pipeline/errors";
import { requirePipelineAdmin } from "@/lib/render-pipeline/session-auth";
import { cancelDeliveryRequest } from "@/lib/render-pipeline/delivery-requests";
import { cancelRequestSchema } from "@/lib/render-pipeline/delivery-request-state";
// ── POST /api/delivery-requests/{id}/cancel ──────────────────────────────────
//
// The only way a request leaves the awaiting list without being delivered, and
// it has to say why.
export async function POST(
req: NextRequest,
{ params }: { params: Promise<{ requestId: string }> }
) {
try {
const user = await requirePipelineAdmin();
const { requestId } = await params;
const parsed = cancelRequestSchema.safeParse(await req.json().catch(() => null));
if (!parsed.success) {
return NextResponse.json(
{ error: parsed.error.issues[0]?.message ?? "Invalid request", details: parsed.error.issues },
{ status: 422 }
);
}
const result = await cancelDeliveryRequest(requestId, parsed.data.reason, user.id);
return NextResponse.json(result);
} catch (err) {
const { body, status } = toErrorResponse(err);
return NextResponse.json(body, { status });
}
}
@@ -0,0 +1,22 @@
import { NextRequest, NextResponse } from "next/server";
import { toErrorResponse } from "@/lib/render-pipeline/errors";
import { requirePipelineUser } from "@/lib/render-pipeline/session-auth";
import { getRequestOptions } from "@/lib/render-pipeline/delivery-requests";
// ── GET /api/delivery-requests/options?projectId= ────────────────────────────
//
// The episodes a request can be logged against.
export async function GET(req: NextRequest) {
try {
await requirePipelineUser();
const projectId = new URL(req.url).searchParams.get("projectId");
if (!projectId) {
return NextResponse.json({ error: "projectId is required" }, { status: 400 });
}
return NextResponse.json(await getRequestOptions(projectId));
} catch (err) {
const { body, status } = toErrorResponse(err);
return NextResponse.json(body, { status });
}
}
+44
View File
@@ -0,0 +1,44 @@
import { NextRequest, NextResponse } from "next/server";
import { toErrorResponse } from "@/lib/render-pipeline/errors";
import { requirePipelineAdmin, requirePipelineUser } from "@/lib/render-pipeline/session-auth";
import { createDeliveryRequest, listDeliveryRequests } from "@/lib/render-pipeline/delivery-requests";
import { createRequestSchema } from "@/lib/render-pipeline/delivery-request-state";
// ── GET /api/delivery-requests · POST /api/delivery-requests ─────────────────
//
// What clients have asked for, and how much of each ask has gone out.
export async function GET(req: NextRequest) {
try {
await requirePipelineUser();
const { searchParams } = new URL(req.url);
const requests = await listDeliveryRequests({
projectId: searchParams.get("projectId") ?? undefined,
openOnly: searchParams.get("open") === "1",
});
return NextResponse.json({ requests });
} catch (err) {
const { body, status } = toErrorResponse(err);
return NextResponse.json(body, { status });
}
}
export async function POST(req: NextRequest) {
try {
const user = await requirePipelineAdmin();
const parsed = createRequestSchema.safeParse(await req.json().catch(() => null));
if (!parsed.success) {
return NextResponse.json(
{ error: parsed.error.issues[0]?.message ?? "Invalid request", details: parsed.error.issues },
{ status: 422 }
);
}
const result = await createDeliveryRequest(parsed.data, user.id);
return NextResponse.json(result, { status: 201 });
} catch (err) {
const { body, status } = toErrorResponse(err);
return NextResponse.json(body, { status });
}
}