feat(deliveries): delivery requests and upload/share evidence
Deploy / deploy (push) Successful in 5m17s
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:
@@ -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'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>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user