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:
@@ -1,6 +1,7 @@
|
||||
import { db } from "@/lib/db";
|
||||
import { getConfigNumber } from "@/lib/render-pipeline/config";
|
||||
import { listMachines } from "@/lib/render-pipeline/machines";
|
||||
import { handoffStage, type HandoffStage } from "@/lib/render-pipeline/delivery-handoff";
|
||||
import type { ExportStatus, Prisma } from "@prisma/client";
|
||||
|
||||
/**
|
||||
@@ -596,6 +597,72 @@ export async function getRecentDeliveries(limit = 5): Promise<DeliverySummary[]>
|
||||
});
|
||||
}
|
||||
|
||||
export interface AwaitingDelivery {
|
||||
id: string;
|
||||
packageNumber: number;
|
||||
name: string;
|
||||
projectCode: string;
|
||||
episode: string;
|
||||
itemCount: number;
|
||||
stage: HandoffStage;
|
||||
/** When the folder was ready to go — the clock the client is waiting on. */
|
||||
builtAt: Date;
|
||||
severity: "normal" | "warning" | "critical";
|
||||
}
|
||||
|
||||
/**
|
||||
* Built packages the client does not have yet.
|
||||
*
|
||||
* A READY package is the easiest thing in the pipeline to believe is done: the
|
||||
* folder exists and every file verified, but nothing has left the building.
|
||||
* It stays listed until the upload location and the person it was shared with
|
||||
* are both on record, and gets louder the longer that takes.
|
||||
*/
|
||||
export async function getAwaitingDelivery(): Promise<AwaitingDelivery[]> {
|
||||
const rows = await db.deliveryPackage.findMany({
|
||||
where: {
|
||||
kind: "EXR_DELIVERY",
|
||||
status: "READY",
|
||||
project: { status: { in: ["ACTIVE", "ON_HOLD"] } },
|
||||
},
|
||||
orderBy: { builtAt: "asc" },
|
||||
select: {
|
||||
id: true,
|
||||
packageNumber: true,
|
||||
name: true,
|
||||
kind: true,
|
||||
status: true,
|
||||
episode: true,
|
||||
createdAt: true,
|
||||
builtAt: true,
|
||||
uploadedAt: true,
|
||||
project: { select: { code: true } },
|
||||
_count: { select: { items: true } },
|
||||
},
|
||||
});
|
||||
|
||||
const day = 24 * 3600_000;
|
||||
return rows.flatMap((row) => {
|
||||
const stage = handoffStage(row);
|
||||
if (!stage) return [];
|
||||
const builtAt = row.builtAt ?? row.createdAt;
|
||||
const age = Date.now() - builtAt.getTime();
|
||||
return [
|
||||
{
|
||||
id: row.id,
|
||||
packageNumber: row.packageNumber,
|
||||
name: row.name,
|
||||
projectCode: row.project.code,
|
||||
episode: row.episode,
|
||||
itemCount: row._count.items,
|
||||
stage,
|
||||
builtAt,
|
||||
severity: age >= 2 * day ? "critical" : age >= day ? "warning" : "normal",
|
||||
},
|
||||
];
|
||||
});
|
||||
}
|
||||
|
||||
export interface CourtSide {
|
||||
count: number;
|
||||
items: { id: string; shotCode: string; label: string; href: string }[];
|
||||
|
||||
@@ -5,6 +5,7 @@ import { PipelineError } from "./errors";
|
||||
import { applyTransition } from "./transitions";
|
||||
import { getConfigNumber, getConfigValue } from "./config";
|
||||
import { clientShotCode } from "@/lib/shot-code";
|
||||
import type { RecordShareInput, RecordUploadInput } from "./delivery-handoff";
|
||||
|
||||
/**
|
||||
* Delivery builder (RenderPipeline2 §11). The web app decides *what* goes in a
|
||||
@@ -640,11 +641,33 @@ export async function listDeliveryPackages(filter: {
|
||||
},
|
||||
orderBy: { createdAt: "desc" },
|
||||
include: {
|
||||
items: { select: { id: true, shotCode: true, versionString: true, status: true, fileCount: true, linkMode: true, errorMessage: true } },
|
||||
items: {
|
||||
select: {
|
||||
id: true,
|
||||
shotCode: true,
|
||||
clientCode: true,
|
||||
versionString: true,
|
||||
status: true,
|
||||
fileCount: true,
|
||||
totalBytes: true,
|
||||
movPath: true,
|
||||
linkMode: true,
|
||||
errorMessage: true,
|
||||
},
|
||||
},
|
||||
project: { select: { id: true, name: true, code: true } },
|
||||
},
|
||||
});
|
||||
|
||||
// Who recorded each handoff step — the ids are plain columns, not relations.
|
||||
const userIds = [
|
||||
...new Set(packages.flatMap((p) => [p.uploadedById, p.deliveredById]).filter((id): id is string => !!id)),
|
||||
];
|
||||
const users = userIds.length
|
||||
? await db.user.findMany({ where: { id: { in: userIds } }, select: { id: true, name: true, email: true } })
|
||||
: [];
|
||||
const userName = new Map(users.map((u) => [u.id, u.name ?? u.email]));
|
||||
|
||||
return {
|
||||
packages: packages.map((p) => ({
|
||||
id: p.id,
|
||||
@@ -659,30 +682,71 @@ export async function listDeliveryPackages(filter: {
|
||||
projectCode: p.project.code,
|
||||
createdAt: p.createdAt,
|
||||
builtAt: p.builtAt,
|
||||
uploadUrl: p.uploadUrl,
|
||||
uploadedAt: p.uploadedAt,
|
||||
uploadedByName: p.uploadedById ? (userName.get(p.uploadedById) ?? null) : null,
|
||||
sharedWith: p.sharedWith,
|
||||
sharedNote: p.sharedNote,
|
||||
deliveredAt: p.deliveredAt,
|
||||
deliveredByName: p.deliveredById ? (userName.get(p.deliveredById) ?? null) : null,
|
||||
itemCount: p.items.length,
|
||||
verifiedCount: p.items.filter((i) => i.status === "VERIFIED").length,
|
||||
items: p.items,
|
||||
// What the upload should contain, for the person comparing it against
|
||||
// the client's portal.
|
||||
exrFileCount: p.items.reduce((sum, i) => sum + (i.fileCount ?? 0), 0),
|
||||
movCount: p.items.filter((i) => i.movPath).length,
|
||||
totalBytes: p.items.reduce((sum, i) => sum + Number(i.totalBytes ?? 0), 0),
|
||||
items: p.items.map(({ totalBytes: _bytes, movPath: _mov, ...item }) => item),
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
/** E19 — the human uploaded the folder to the client and is confirming it. */
|
||||
export async function markDelivered(packageId: string, userId: string) {
|
||||
function assertHandoffAllowed(pkg: { kind: DeliveryKind; status: DeliveryStatus }, verb: string) {
|
||||
if (pkg.kind !== "EXR_DELIVERY") {
|
||||
throw new PipelineError(
|
||||
409,
|
||||
"A MOV review package is shared for review, not delivered — it has no delivered state"
|
||||
);
|
||||
}
|
||||
if (pkg.status !== "READY") {
|
||||
throw new PipelineError(409, `Package is ${pkg.status} — only a READY package can be ${verb}`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Step one of the handoff: the folder is on the client's portal, and this is
|
||||
* where. Repeatable while the package is READY, so a wrong link can be
|
||||
* corrected before it is shared.
|
||||
*/
|
||||
export async function markUploaded(packageId: string, input: RecordUploadInput, userId: string) {
|
||||
return db.$transaction(async (tx) => {
|
||||
const pkg = await tx.deliveryPackage.findUnique({ where: { id: packageId } });
|
||||
if (!pkg) throw new PipelineError(404, "Delivery package not found");
|
||||
assertHandoffAllowed(pkg, "recorded as uploaded");
|
||||
|
||||
const updated = await tx.deliveryPackage.update({
|
||||
where: { id: pkg.id },
|
||||
data: { uploadUrl: input.uploadUrl, uploadedAt: new Date(), uploadedById: userId },
|
||||
});
|
||||
return { package: { id: updated.id, status: updated.status, uploadUrl: updated.uploadUrl } };
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* E19 — step two: the link was sent to a named person, which is what makes the
|
||||
* package DELIVERED. Refused until the upload location is on record, so
|
||||
* "delivered" always has somewhere to point.
|
||||
*/
|
||||
export async function markDelivered(packageId: string, input: RecordShareInput, userId: string) {
|
||||
return db.$transaction(async (tx) => {
|
||||
const pkg = await tx.deliveryPackage.findUnique({ where: { id: packageId }, include: { items: true } });
|
||||
if (!pkg) throw new PipelineError(404, "Delivery package not found");
|
||||
if (pkg.status === "DELIVERED") {
|
||||
return { package: { id: pkg.id, status: pkg.status }, alreadyApplied: true };
|
||||
}
|
||||
if (pkg.status !== "READY") {
|
||||
throw new PipelineError(409, `Package is ${pkg.status} — only a READY package can be marked delivered`);
|
||||
}
|
||||
if (pkg.kind !== "EXR_DELIVERY") {
|
||||
throw new PipelineError(
|
||||
409,
|
||||
"A MOV review package is shared for review, not delivered — it has no delivered state"
|
||||
);
|
||||
assertHandoffAllowed(pkg, "marked delivered");
|
||||
if (!pkg.uploadedAt || !pkg.uploadUrl) {
|
||||
throw new PipelineError(409, "Record where the package was uploaded before marking it delivered");
|
||||
}
|
||||
|
||||
for (const item of pkg.items) {
|
||||
@@ -698,7 +762,13 @@ export async function markDelivered(packageId: string, userId: string) {
|
||||
|
||||
const updated = await tx.deliveryPackage.update({
|
||||
where: { id: pkg.id },
|
||||
data: { status: "DELIVERED", deliveredAt: new Date(), deliveredById: userId },
|
||||
data: {
|
||||
status: "DELIVERED",
|
||||
sharedWith: input.sharedWith,
|
||||
sharedNote: input.note || null,
|
||||
deliveredAt: new Date(),
|
||||
deliveredById: userId,
|
||||
},
|
||||
});
|
||||
return { package: { id: updated.id, status: updated.status }, alreadyApplied: false };
|
||||
});
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { buildShareMessage, handoffStage, recordShareSchema, recordUploadSchema } from "./delivery-handoff";
|
||||
|
||||
describe("handoffStage", () => {
|
||||
const ready = { kind: "EXR_DELIVERY", status: "READY", uploadedAt: null };
|
||||
|
||||
it("waits on the upload first, then on the share", () => {
|
||||
expect(handoffStage(ready)).toBe("AWAITING_UPLOAD");
|
||||
expect(handoffStage({ ...ready, uploadedAt: new Date() })).toBe("AWAITING_SHARE");
|
||||
});
|
||||
|
||||
it("waits on nothing before the build or after delivery", () => {
|
||||
expect(handoffStage({ ...ready, status: "BUILDING" })).toBeNull();
|
||||
expect(handoffStage({ ...ready, status: "FAILED" })).toBeNull();
|
||||
expect(handoffStage({ ...ready, status: "DELIVERED", uploadedAt: new Date() })).toBeNull();
|
||||
});
|
||||
|
||||
it("never asks for a review package to be delivered", () => {
|
||||
expect(handoffStage({ ...ready, kind: "MOV_REVIEW" })).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("recordUploadSchema", () => {
|
||||
const url = "https://contenthub.example.com/folders/abc";
|
||||
|
||||
it("accepts a link with the contents confirmed", () => {
|
||||
expect(recordUploadSchema.safeParse({ uploadUrl: url, contentsConfirmed: true }).success).toBe(true);
|
||||
});
|
||||
|
||||
it("refuses an unconfirmed upload", () => {
|
||||
expect(recordUploadSchema.safeParse({ uploadUrl: url, contentsConfirmed: false }).success).toBe(false);
|
||||
expect(recordUploadSchema.safeParse({ uploadUrl: url }).success).toBe(false);
|
||||
});
|
||||
|
||||
it("refuses anything that is not a web link", () => {
|
||||
for (const uploadUrl of ["", "uploaded", "//SAN/DELIVERY/ACME/101", "javascript:alert(1)"]) {
|
||||
expect(recordUploadSchema.safeParse({ uploadUrl, contentsConfirmed: true }).success).toBe(false);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("recordShareSchema", () => {
|
||||
it("needs a recipient", () => {
|
||||
expect(recordShareSchema.safeParse({ sharedWith: " " }).success).toBe(false);
|
||||
expect(recordShareSchema.safeParse({ sharedWith: "Sam (post super)" }).success).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("buildShareMessage", () => {
|
||||
it("lists the packaged versions under the client's own shot codes", () => {
|
||||
const message = buildShareMessage({
|
||||
projectCode: "UNG",
|
||||
episode: "116",
|
||||
name: "20260930_Delivery",
|
||||
uploadUrl: "https://contenthub.example.com/folders/abc",
|
||||
items: [
|
||||
{ shotCode: "UNG_116_020", clientCode: null, versionString: "v002" },
|
||||
{ shotCode: "UNG_116_010", clientCode: "116_A_0010", versionString: "v004" },
|
||||
],
|
||||
});
|
||||
expect(message).toBe(
|
||||
[
|
||||
"Delivery: UNG · episode 116 · 20260930_Delivery",
|
||||
"2 shots",
|
||||
"https://contenthub.example.com/folders/abc",
|
||||
"",
|
||||
"116_A_0010 v004",
|
||||
"UNG_116_020 v002",
|
||||
].join("\n")
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,73 @@
|
||||
import { z } from "zod";
|
||||
import { clientShotCode } from "@/lib/shot-code";
|
||||
|
||||
/**
|
||||
* The handoff after a package is built: upload it, then share the link.
|
||||
*
|
||||
* Kept free of database imports so the deliveries page can use the same stage
|
||||
* logic and share message the server does.
|
||||
*/
|
||||
|
||||
export type HandoffStage = "AWAITING_UPLOAD" | "AWAITING_SHARE";
|
||||
|
||||
/**
|
||||
* What a built EXR package is still waiting on, or null when it is waiting on
|
||||
* nothing — not built yet, already delivered, or a review (which has no
|
||||
* delivered state at all).
|
||||
*/
|
||||
export function handoffStage(pkg: {
|
||||
kind: string;
|
||||
status: string;
|
||||
uploadedAt: Date | string | null;
|
||||
}): HandoffStage | null {
|
||||
if (pkg.kind !== "EXR_DELIVERY" || pkg.status !== "READY") return null;
|
||||
return pkg.uploadedAt ? "AWAITING_SHARE" : "AWAITING_UPLOAD";
|
||||
}
|
||||
|
||||
export const recordUploadSchema = z.object({
|
||||
uploadUrl: z
|
||||
.string()
|
||||
.trim()
|
||||
.max(2000)
|
||||
.url("Paste the full link to the upload folder")
|
||||
.refine((value) => /^https?:\/\//i.test(value), "The upload link must start with http:// or https://"),
|
||||
/** The person looked at the upload and its contents match the package. */
|
||||
contentsConfirmed: z.literal(true, {
|
||||
errorMap: () => ({ message: "Confirm the uploaded files match the package" }),
|
||||
}),
|
||||
});
|
||||
|
||||
export type RecordUploadInput = z.infer<typeof recordUploadSchema>;
|
||||
|
||||
export const recordShareSchema = z.object({
|
||||
sharedWith: z.string().trim().min(1, "Say who the link was sent to").max(200),
|
||||
note: z.string().trim().max(1000).optional().nullable(),
|
||||
});
|
||||
|
||||
export type RecordShareInput = z.infer<typeof recordShareSchema>;
|
||||
|
||||
/**
|
||||
* The message sent to the client with the link. Generated rather than typed so
|
||||
* the shots and versions the client is told about are the ones in the package.
|
||||
*/
|
||||
export function buildShareMessage(pkg: {
|
||||
projectCode: string;
|
||||
episode: string;
|
||||
name: string;
|
||||
uploadUrl: string;
|
||||
items: { shotCode: string; clientCode?: string | null; versionString: string }[];
|
||||
}): string {
|
||||
const shots = pkg.items
|
||||
.map((item) => `${clientShotCode(item)} ${item.versionString}`)
|
||||
.sort((a, b) => a.localeCompare(b));
|
||||
const heading = [pkg.projectCode, pkg.episode ? `episode ${pkg.episode}` : "", pkg.name]
|
||||
.filter(Boolean)
|
||||
.join(" · ");
|
||||
return [
|
||||
`Delivery: ${heading}`,
|
||||
`${shots.length} shot${shots.length === 1 ? "" : "s"}`,
|
||||
pkg.uploadUrl,
|
||||
"",
|
||||
...shots,
|
||||
].join("\n");
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
createRequestSchema,
|
||||
matchShotCodes,
|
||||
parseShotCodes,
|
||||
resolveLineStage,
|
||||
waitingSeverity,
|
||||
} from "./delivery-request-state";
|
||||
|
||||
describe("parseShotCodes", () => {
|
||||
it("takes codes out of a pasted message whatever separates them", () => {
|
||||
expect(parseShotCodes("UNG_116_010, UNG_116_020\nUNG_116_030; 116-A-0040")).toEqual([
|
||||
"UNG_116_010",
|
||||
"UNG_116_020",
|
||||
"UNG_116_030",
|
||||
"116-A-0040",
|
||||
]);
|
||||
});
|
||||
|
||||
it("drops repeats regardless of case", () => {
|
||||
expect(parseShotCodes("ung_116_010 UNG_116_010")).toEqual(["ung_116_010"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("matchShotCodes", () => {
|
||||
const shots = [
|
||||
{ id: "a", shotCode: "UNG_116_010", clientCode: "116_A_0010" },
|
||||
{ id: "b", shotCode: "UNG_116_020", clientCode: null },
|
||||
];
|
||||
|
||||
it("matches our code or the client's, in any case", () => {
|
||||
const { matched, unmatched } = matchShotCodes(["116_a_0010", "ung_116_020"], shots);
|
||||
expect(matched.map((s) => s.id)).toEqual(["a", "b"]);
|
||||
expect(unmatched).toEqual([]);
|
||||
});
|
||||
|
||||
it("reports what it could not match instead of dropping it", () => {
|
||||
expect(matchShotCodes(["UNG_116_010", "UNG_116_999"], shots).unmatched).toEqual(["UNG_116_999"]);
|
||||
});
|
||||
|
||||
it("counts a shot once when both of its codes are given", () => {
|
||||
expect(matchShotCodes(["UNG_116_010", "116_A_0010"], shots).matched).toHaveLength(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveLineStage", () => {
|
||||
const logged = new Date("2026-09-30T14:00:00Z");
|
||||
const before = new Date("2026-09-20T10:00:00Z");
|
||||
const after = new Date("2026-10-01T10:00:00Z");
|
||||
const base = {
|
||||
requestCreatedAt: logged,
|
||||
packages: [],
|
||||
manual: { deliveredAt: null, url: null, sharedWith: null },
|
||||
exportStatuses: [],
|
||||
};
|
||||
|
||||
it("walks a shot from not ready through to delivered", () => {
|
||||
expect(resolveLineStage(base)).toBe("NOT_READY");
|
||||
expect(resolveLineStage({ ...base, exportStatuses: ["READY_FOR_QC"] })).toBe("IN_QC");
|
||||
expect(resolveLineStage({ ...base, exportStatuses: ["READY_FOR_QC", "READY_FOR_DELIVERY"] })).toBe("READY");
|
||||
const pkg = { status: "BUILDING", uploadedAt: null, deliveredAt: null };
|
||||
expect(resolveLineStage({ ...base, packages: [pkg] })).toBe("BUILDING");
|
||||
expect(resolveLineStage({ ...base, packages: [{ ...pkg, status: "READY" }] })).toBe("BUILT");
|
||||
expect(resolveLineStage({ ...base, packages: [{ ...pkg, status: "READY", uploadedAt: after }] })).toBe("UPLOADED");
|
||||
expect(
|
||||
resolveLineStage({ ...base, packages: [{ status: "DELIVERED", uploadedAt: after, deliveredAt: after }] })
|
||||
).toBe("DELIVERED");
|
||||
});
|
||||
|
||||
it("does not let a delivery from before the request close it", () => {
|
||||
expect(
|
||||
resolveLineStage({ ...base, packages: [{ status: "DELIVERED", uploadedAt: before, deliveredAt: before }] })
|
||||
).toBe("NOT_READY");
|
||||
});
|
||||
|
||||
it("closes on a manual delivery only with a link and a recipient", () => {
|
||||
const sameDay = new Date("2026-09-30T12:00:00Z");
|
||||
const manual = { deliveredAt: sameDay, url: "https://x.example/f", sharedWith: "Sam" };
|
||||
expect(resolveLineStage({ ...base, manual })).toBe("DELIVERED");
|
||||
expect(resolveLineStage({ ...base, manual: { ...manual, url: null } })).toBe("NOT_READY");
|
||||
expect(resolveLineStage({ ...base, manual: { ...manual, sharedWith: null } })).toBe("NOT_READY");
|
||||
expect(resolveLineStage({ ...base, manual: { ...manual, deliveredAt: before } })).toBe("NOT_READY");
|
||||
});
|
||||
});
|
||||
|
||||
describe("waitingSeverity", () => {
|
||||
const now = new Date("2026-09-30T12:00:00Z").getTime();
|
||||
const hoursAgo = (h: number) => new Date(now - h * 3600_000);
|
||||
|
||||
it("escalates with age", () => {
|
||||
expect(waitingSeverity(hoursAgo(2), null, now)).toBe("normal");
|
||||
expect(waitingSeverity(hoursAgo(30), null, now)).toBe("warning");
|
||||
expect(waitingSeverity(hoursAgo(50), null, now)).toBe("critical");
|
||||
});
|
||||
|
||||
it("is critical once past the due date, however new", () => {
|
||||
expect(waitingSeverity(hoursAgo(2), hoursAgo(1), now)).toBe("critical");
|
||||
});
|
||||
});
|
||||
|
||||
describe("createRequestSchema", () => {
|
||||
const base = { projectId: "p", deliverable: "EXR", requestedBy: "Sam" };
|
||||
|
||||
it("needs exactly one way of naming the shots", () => {
|
||||
expect(createRequestSchema.safeParse(base).success).toBe(false);
|
||||
expect(createRequestSchema.safeParse({ ...base, episode: "116" }).success).toBe(true);
|
||||
expect(createRequestSchema.safeParse({ ...base, episode: "116", shotCodes: "UNG_116_010" }).success).toBe(false);
|
||||
});
|
||||
|
||||
it("needs to know who asked", () => {
|
||||
expect(createRequestSchema.safeParse({ ...base, episode: "116", requestedBy: " " }).success).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,163 @@
|
||||
import { z } from "zod";
|
||||
|
||||
/**
|
||||
* Delivery request rules with no database behind them, shared by the server
|
||||
* and the pages that show requests.
|
||||
*/
|
||||
|
||||
export const DELIVERABLES = ["EXR", "MOV", "EXR_AND_MOV"] as const;
|
||||
export type Deliverable = (typeof DELIVERABLES)[number];
|
||||
|
||||
export const DELIVERABLE_LABEL: Record<Deliverable, string> = {
|
||||
EXR: "EXRs",
|
||||
MOV: "MOVs",
|
||||
EXR_AND_MOV: "EXRs + MOVs",
|
||||
};
|
||||
|
||||
/** Where one requested shot stands, from furthest along to not started. */
|
||||
export type RequestLineStage =
|
||||
| "DELIVERED"
|
||||
| "UPLOADED"
|
||||
| "BUILT"
|
||||
| "BUILDING"
|
||||
| "READY"
|
||||
| "IN_QC"
|
||||
| "NOT_READY";
|
||||
|
||||
export const LINE_STAGE_LABEL: Record<RequestLineStage, string> = {
|
||||
DELIVERED: "delivered",
|
||||
UPLOADED: "uploaded, link not shared",
|
||||
BUILT: "built, not uploaded",
|
||||
BUILDING: "package building",
|
||||
READY: "ready to package",
|
||||
IN_QC: "in QC",
|
||||
NOT_READY: "not through QC",
|
||||
};
|
||||
|
||||
export const createRequestSchema = z
|
||||
.object({
|
||||
projectId: z.string().min(1),
|
||||
/** Exactly one of these three says which shots were asked for. */
|
||||
episode: z.string().trim().min(1).max(50).optional().nullable(),
|
||||
shotIds: z.array(z.string().min(1)).min(1).max(1000).optional().nullable(),
|
||||
shotCodes: z.string().trim().min(1).max(20000).optional().nullable(),
|
||||
deliverable: z.enum(DELIVERABLES),
|
||||
requestedBy: z.string().trim().min(1, "Say who asked for it").max(200),
|
||||
dueDate: z.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional().nullable(),
|
||||
note: z.string().trim().max(2000).optional().nullable(),
|
||||
})
|
||||
.refine((v) => [v.episode, v.shotIds, v.shotCodes].filter(Boolean).length === 1, {
|
||||
message: "Choose an episode, a shot selection or a list of shot codes",
|
||||
});
|
||||
|
||||
export type CreateRequestInput = z.infer<typeof createRequestSchema>;
|
||||
|
||||
export const cancelRequestSchema = z.object({
|
||||
reason: z.string().trim().min(1, "Say why the request is being cancelled").max(500),
|
||||
});
|
||||
|
||||
/**
|
||||
* Shot codes out of a pasted message: split on anything that is not part of a
|
||||
* code, so "116_010, 116_020\n116_030" and a column copied from a sheet both
|
||||
* work. Order is kept and repeats dropped.
|
||||
*/
|
||||
export function parseShotCodes(text: string): string[] {
|
||||
const seen = new Set<string>();
|
||||
const codes: string[] = [];
|
||||
for (const raw of text.split(/[^A-Za-z0-9_\-.]+/)) {
|
||||
const code = raw.trim();
|
||||
const key = code.toLowerCase();
|
||||
if (!code || seen.has(key)) continue;
|
||||
seen.add(key);
|
||||
codes.push(code);
|
||||
}
|
||||
return codes;
|
||||
}
|
||||
|
||||
/**
|
||||
* Pasted codes against a project's shots. The client writes their own codes
|
||||
* and we write ours, so either matches; anything that matches neither is
|
||||
* returned rather than dropped, because a silently skipped shot is exactly the
|
||||
* kind of miss a request exists to prevent.
|
||||
*/
|
||||
export function matchShotCodes<T extends { shotCode: string; clientCode?: string | null }>(
|
||||
codes: string[],
|
||||
shots: T[]
|
||||
): { matched: T[]; unmatched: string[] } {
|
||||
const byCode = new Map<string, T>();
|
||||
for (const shot of shots) {
|
||||
byCode.set(shot.shotCode.toLowerCase(), shot);
|
||||
const alias = shot.clientCode?.trim().toLowerCase();
|
||||
if (alias && !byCode.has(alias)) byCode.set(alias, shot);
|
||||
}
|
||||
const matched = new Set<T>();
|
||||
const unmatched: string[] = [];
|
||||
for (const code of codes) {
|
||||
const shot = byCode.get(code.toLowerCase());
|
||||
if (shot) matched.add(shot);
|
||||
else unmatched.push(code);
|
||||
}
|
||||
return { matched: [...matched], unmatched };
|
||||
}
|
||||
|
||||
/**
|
||||
* Where a requested shot stands. Only a delivery made after the request was
|
||||
* logged closes the line — a client asking again for something already sent
|
||||
* is asking for it to be sent again.
|
||||
*/
|
||||
export function resolveLineStage(input: {
|
||||
requestCreatedAt: Date;
|
||||
/** EXR delivery packages containing the shot. */
|
||||
packages: { status: string; uploadedAt: Date | null; deliveredAt: Date | null }[];
|
||||
manual: { deliveredAt: Date | null; url: string | null; sharedWith: string | null };
|
||||
/** Statuses of the shot's exports. */
|
||||
exportStatuses: string[];
|
||||
}): RequestLineStage {
|
||||
const { requestCreatedAt, packages, manual, exportStatuses } = input;
|
||||
if (
|
||||
packages.some((p) => p.status === "DELIVERED" && p.deliveredAt && p.deliveredAt >= requestCreatedAt)
|
||||
) {
|
||||
return "DELIVERED";
|
||||
}
|
||||
if (
|
||||
manual.deliveredAt &&
|
||||
manual.url &&
|
||||
manual.sharedWith &&
|
||||
manualDeliveryCounts(manual.deliveredAt, requestCreatedAt)
|
||||
) {
|
||||
return "DELIVERED";
|
||||
}
|
||||
const ready = packages.filter((p) => p.status === "READY");
|
||||
if (ready.some((p) => p.uploadedAt)) return "UPLOADED";
|
||||
if (ready.length) return "BUILT";
|
||||
if (packages.some((p) => p.status === "QUEUED" || p.status === "BUILDING")) return "BUILDING";
|
||||
if (exportStatuses.includes("READY_FOR_DELIVERY")) return "READY";
|
||||
if (exportStatuses.includes("READY_FOR_QC")) return "IN_QC";
|
||||
return "NOT_READY";
|
||||
}
|
||||
|
||||
const DAY_MS = 24 * 3600_000;
|
||||
|
||||
/** Past its due date or two days old is critical; a day old is a warning. */
|
||||
export function waitingSeverity(
|
||||
since: Date,
|
||||
dueDate: Date | null,
|
||||
now = Date.now()
|
||||
): "normal" | "warning" | "critical" {
|
||||
if (dueDate && dueDate.getTime() < now) return "critical";
|
||||
const age = now - since.getTime();
|
||||
return age >= 2 * DAY_MS ? "critical" : age >= DAY_MS ? "warning" : "normal";
|
||||
}
|
||||
|
||||
/**
|
||||
* A manual delivery is recorded as a calendar day (noon UTC), so it counts for
|
||||
* a request logged any time that same day.
|
||||
*/
|
||||
export function manualDeliveryCounts(manualDeliveredAt: Date, requestCreatedAt: Date): boolean {
|
||||
const dayStart = Date.UTC(
|
||||
requestCreatedAt.getUTCFullYear(),
|
||||
requestCreatedAt.getUTCMonth(),
|
||||
requestCreatedAt.getUTCDate()
|
||||
);
|
||||
return manualDeliveredAt.getTime() >= dayStart;
|
||||
}
|
||||
@@ -0,0 +1,256 @@
|
||||
import { db } from "@/lib/db";
|
||||
import { PipelineError } from "./errors";
|
||||
import {
|
||||
matchShotCodes,
|
||||
parseShotCodes,
|
||||
resolveLineStage,
|
||||
waitingSeverity,
|
||||
type CreateRequestInput,
|
||||
type RequestLineStage,
|
||||
} from "./delivery-request-state";
|
||||
|
||||
/**
|
||||
* Delivery requests: what a client asked for, held open until it has gone out.
|
||||
*
|
||||
* A request stores only the ask and its shot list. Whether each shot has been
|
||||
* delivered is read from the packages and manual deliveries themselves, so a
|
||||
* request cannot say "done" when the delivery record does not.
|
||||
*/
|
||||
|
||||
export async function createDeliveryRequest(input: CreateRequestInput, userId: string) {
|
||||
const project = await db.project.findUnique({ where: { id: input.projectId }, select: { id: true } });
|
||||
if (!project) throw new PipelineError(404, "Project not found");
|
||||
|
||||
const select = { id: true, shotCode: true, clientCode: true } as const;
|
||||
let shots: { id: string; shotCode: string; clientCode: string | null }[];
|
||||
|
||||
if (input.episode) {
|
||||
// Snapshot: the request is for the shots in the episode today. A shot
|
||||
// added to the episode later is a new ask, not a silent change to this one.
|
||||
shots = await db.shot.findMany({ where: { projectId: project.id, episode: input.episode }, select });
|
||||
if (!shots.length) throw new PipelineError(422, `No shots in episode ${input.episode}`);
|
||||
} else if (input.shotIds) {
|
||||
const ids = [...new Set(input.shotIds)];
|
||||
shots = await db.shot.findMany({ where: { projectId: project.id, id: { in: ids } }, select });
|
||||
if (shots.length !== ids.length) {
|
||||
throw new PipelineError(422, "Some of the selected shots are not in this project");
|
||||
}
|
||||
} else {
|
||||
const codes = parseShotCodes(input.shotCodes ?? "");
|
||||
const all = await db.shot.findMany({ where: { projectId: project.id }, select });
|
||||
const { matched, unmatched } = matchShotCodes(codes, all);
|
||||
if (unmatched.length) {
|
||||
throw new PipelineError(
|
||||
422,
|
||||
`${unmatched.length} code${unmatched.length === 1 ? "" : "s"} did not match a shot: ${unmatched.slice(0, 10).join(", ")}${unmatched.length > 10 ? "…" : ""}`,
|
||||
{ unmatched }
|
||||
);
|
||||
}
|
||||
shots = matched;
|
||||
if (!shots.length) throw new PipelineError(422, "No shot codes found in the text");
|
||||
}
|
||||
|
||||
return db.$transaction(async (tx) => {
|
||||
const last = await tx.deliveryRequest.aggregate({
|
||||
where: { projectId: project.id },
|
||||
_max: { requestNumber: true },
|
||||
});
|
||||
const request = await tx.deliveryRequest.create({
|
||||
data: {
|
||||
projectId: project.id,
|
||||
requestNumber: (last._max.requestNumber ?? 0) + 1,
|
||||
episode: input.episode ?? "",
|
||||
deliverable: input.deliverable,
|
||||
requestedBy: input.requestedBy,
|
||||
note: input.note || null,
|
||||
// Noon UTC so the calendar day survives any timezone it is shown in.
|
||||
dueDate: input.dueDate ? new Date(`${input.dueDate}T12:00:00.000Z`) : null,
|
||||
createdById: userId,
|
||||
lines: {
|
||||
create: shots.map((s) => ({ shotId: s.id, shotCode: s.shotCode, clientCode: s.clientCode })),
|
||||
},
|
||||
},
|
||||
});
|
||||
return { request: { id: request.id, requestNumber: request.requestNumber, lineCount: shots.length } };
|
||||
});
|
||||
}
|
||||
|
||||
export async function cancelDeliveryRequest(requestId: string, reason: string, userId: string) {
|
||||
const request = await db.deliveryRequest.findUnique({ where: { id: requestId } });
|
||||
if (!request) throw new PipelineError(404, "Delivery request not found");
|
||||
if (request.cancelledAt) return { request: { id: request.id }, alreadyApplied: true };
|
||||
await db.deliveryRequest.update({
|
||||
where: { id: request.id },
|
||||
data: { cancelledAt: new Date(), cancelledById: userId, cancelReason: reason },
|
||||
});
|
||||
return { request: { id: request.id }, alreadyApplied: false };
|
||||
}
|
||||
|
||||
export interface DeliveryRequestLineView {
|
||||
id: string;
|
||||
shotId: string;
|
||||
shotCode: string;
|
||||
clientCode: string | null;
|
||||
stage: RequestLineStage;
|
||||
/** The export to package when the stage is READY. */
|
||||
readyExportId: string | null;
|
||||
}
|
||||
|
||||
export interface DeliveryRequestView {
|
||||
id: string;
|
||||
requestNumber: number;
|
||||
projectId: string;
|
||||
projectCode: string;
|
||||
episode: string;
|
||||
deliverable: string;
|
||||
requestedBy: string;
|
||||
note: string | null;
|
||||
dueDate: Date | null;
|
||||
createdAt: Date;
|
||||
cancelledAt: Date | null;
|
||||
cancelReason: string | null;
|
||||
state: "OPEN" | "CLOSED" | "CANCELLED";
|
||||
lineCount: number;
|
||||
deliveredCount: number;
|
||||
severity: "normal" | "warning" | "critical";
|
||||
lines: DeliveryRequestLineView[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Requests with each line's stage worked out from the delivery record.
|
||||
* `openOnly` is what the dashboard wants; the deliveries page takes the recent
|
||||
* history too.
|
||||
*/
|
||||
export async function listDeliveryRequests(
|
||||
filter: { projectId?: string; openOnly?: boolean } = {}
|
||||
): Promise<DeliveryRequestView[]> {
|
||||
const requests = await db.deliveryRequest.findMany({
|
||||
where: {
|
||||
...(filter.projectId ? { projectId: filter.projectId } : {}),
|
||||
...(filter.openOnly ? { cancelledAt: null } : {}),
|
||||
project: { status: { in: ["ACTIVE", "ON_HOLD"] } },
|
||||
},
|
||||
orderBy: { createdAt: "desc" },
|
||||
take: 200,
|
||||
include: {
|
||||
project: { select: { code: true } },
|
||||
lines: { orderBy: { shotCode: "asc" } },
|
||||
},
|
||||
});
|
||||
if (!requests.length) return [];
|
||||
|
||||
const shotIds = [...new Set(requests.flatMap((r) => r.lines.map((l) => l.shotId)))];
|
||||
const [items, shots, exports] = await Promise.all([
|
||||
db.deliveryItem.findMany({
|
||||
where: {
|
||||
shotId: { in: shotIds },
|
||||
package: { kind: "EXR_DELIVERY", status: { in: ["QUEUED", "BUILDING", "READY", "DELIVERED"] } },
|
||||
},
|
||||
select: { shotId: true, package: { select: { status: true, uploadedAt: true, deliveredAt: true } } },
|
||||
}),
|
||||
db.shot.findMany({
|
||||
where: { id: { in: shotIds } },
|
||||
select: { id: true, manualDeliveredAt: true, manualDeliveryUrl: true, manualDeliverySharedWith: true },
|
||||
}),
|
||||
db.export.findMany({
|
||||
where: { shotId: { in: shotIds }, status: { in: ["READY_FOR_DELIVERY", "READY_FOR_QC"] } },
|
||||
orderBy: { versionNumber: "desc" },
|
||||
select: { id: true, shotId: true, status: true },
|
||||
}),
|
||||
]);
|
||||
|
||||
const packagesByShot = new Map<string, (typeof items)[number]["package"][]>();
|
||||
for (const item of items) {
|
||||
if (!packagesByShot.has(item.shotId)) packagesByShot.set(item.shotId, []);
|
||||
packagesByShot.get(item.shotId)!.push(item.package);
|
||||
}
|
||||
const shotById = new Map(shots.map((s) => [s.id, s]));
|
||||
const exportsByShot = new Map<string, typeof exports>();
|
||||
for (const row of exports) {
|
||||
if (!exportsByShot.has(row.shotId)) exportsByShot.set(row.shotId, []);
|
||||
exportsByShot.get(row.shotId)!.push(row);
|
||||
}
|
||||
|
||||
const views = requests.map((request): DeliveryRequestView => {
|
||||
const lines = request.lines.map((line): DeliveryRequestLineView => {
|
||||
const shot = shotById.get(line.shotId);
|
||||
const shotExports = exportsByShot.get(line.shotId) ?? [];
|
||||
const stage = resolveLineStage({
|
||||
requestCreatedAt: request.createdAt,
|
||||
packages: packagesByShot.get(line.shotId) ?? [],
|
||||
manual: {
|
||||
deliveredAt: shot?.manualDeliveredAt ?? null,
|
||||
url: shot?.manualDeliveryUrl ?? null,
|
||||
sharedWith: shot?.manualDeliverySharedWith ?? null,
|
||||
},
|
||||
exportStatuses: shotExports.map((e) => e.status),
|
||||
});
|
||||
return {
|
||||
id: line.id,
|
||||
shotId: line.shotId,
|
||||
shotCode: line.shotCode,
|
||||
clientCode: line.clientCode,
|
||||
stage,
|
||||
// Newest first, so this is the version a build would take.
|
||||
readyExportId:
|
||||
stage === "READY" ? (shotExports.find((e) => e.status === "READY_FOR_DELIVERY")?.id ?? null) : null,
|
||||
};
|
||||
});
|
||||
const deliveredCount = lines.filter((l) => l.stage === "DELIVERED").length;
|
||||
const state = request.cancelledAt ? "CANCELLED" : deliveredCount === lines.length ? "CLOSED" : "OPEN";
|
||||
return {
|
||||
id: request.id,
|
||||
requestNumber: request.requestNumber,
|
||||
projectId: request.projectId,
|
||||
projectCode: request.project.code,
|
||||
episode: request.episode,
|
||||
deliverable: request.deliverable,
|
||||
requestedBy: request.requestedBy,
|
||||
note: request.note,
|
||||
dueDate: request.dueDate,
|
||||
createdAt: request.createdAt,
|
||||
cancelledAt: request.cancelledAt,
|
||||
cancelReason: request.cancelReason,
|
||||
state,
|
||||
lineCount: lines.length,
|
||||
deliveredCount,
|
||||
severity: state === "OPEN" ? waitingSeverity(request.createdAt, request.dueDate) : "normal",
|
||||
lines,
|
||||
};
|
||||
});
|
||||
|
||||
return filter.openOnly ? views.filter((v) => v.state === "OPEN") : views;
|
||||
}
|
||||
|
||||
/** Episodes a request can be logged against, with how many shots each holds. */
|
||||
export async function getRequestOptions(projectId: string) {
|
||||
const groups = await db.shot.groupBy({
|
||||
by: ["episode"],
|
||||
where: { projectId, episode: { not: null } },
|
||||
_count: { _all: true },
|
||||
});
|
||||
return {
|
||||
episodes: groups
|
||||
.filter((g) => g.episode)
|
||||
.map((g) => ({ episode: g.episode as string, shotCount: g._count._all }))
|
||||
.sort((a, b) => a.episode.localeCompare(b.episode)),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* How many of these shots are still owed on a request. A manual delivery of
|
||||
* such a shot has to carry the upload link and recipient, or the request it
|
||||
* answers would stay open with nothing to say why.
|
||||
*/
|
||||
export async function countShotsOnOpenRequests(shotIds: string[]): Promise<number> {
|
||||
if (!shotIds.length) return 0;
|
||||
const open = await listDeliveryRequests({ openOnly: true });
|
||||
const wanted = new Set(shotIds);
|
||||
const owed = new Set<string>();
|
||||
for (const request of open) {
|
||||
for (const line of request.lines) {
|
||||
if (line.stage !== "DELIVERED" && wanted.has(line.shotId)) owed.add(line.shotId);
|
||||
}
|
||||
}
|
||||
return owed.size;
|
||||
}
|
||||
Reference in New Issue
Block a user