Files
twotalesanimation 94792279c5 fix(status): reset review state on a new version, and derive shot status everywhere
Requesting changes on a shot and then re-rendering it through the render queue
left every layer of the app still showing the old verdict. Three independent
causes, all on the pipeline path.

finalizePreview inherited the superseded version's approvalStatus
unconditionally. The carry-over exists so a re-export of a signed-off shot does
not reappear as awaiting review, but it applied equally to NEEDS_CHANGES and
REJECTED, so the render queued to address a note arrived already wearing that
note and nothing registered that the work had been redone. carryApproval now
carries only APPROVED.

The pipeline never moved the task. One left on CHANGES by a review or a QC fail
stayed there through every re-render, with no way out but a manual kanban drag.
A genuinely new version now moves it to INTERNAL_REVIEW, as actions/versions.ts
and batch-upload already did. A replaced version is excluded: regeneratePreview
re-delivers the same version after a slate fix and is not a new submission.

The pipeline never called recalcShotStatus at all, so shot boards went stale the
moment a render changed a task. finalizePreview and the QC fail path both
recalculate now; the latter already documented the REVISIONS derivation it was
relying on and never triggering.

Shot.status is derived from tasks and approval flags, but six call sites wrote
it directly with the status they expected: internallyApproveShot,
shareWithClient, unshareFromClient, clientApproveShot, unapproveShot and the
client approve route. Rule 1 of the derivation is that any CHANGES task outranks
an approval, so a shot could be pushed past open rework and then snap back to
REVISIONS on the next unrelated recalc, which is close to unreportable as a bug.
They now set the approval inputs and let recalcShotStatus derive.
unshareFromClient additionally hardcoded READY_FOR_CLIENT even for a
client-approved shot. updateShotStatus keeps its direct write as the deliberate
manual override, now documented as transient for the same reason.

markShotForRevisions replaces the duplicated change-request logic. Both copies
marked all non-DONE tasks CHANGES, which matches nothing on the shot this is
most often called for: one out for client review precisely because all its tasks
are finished. The request then derived to INTERNAL_REVIEW and had no visible
effect anywhere. When nothing is picked up it now reopens the task behind the
shot's latest version, which is the deliverable the reviewer was looking at.

A client's shot-level change request also marks the versions and writes Approval
rows now. The dashboard counters, the version badges and the portal's own
filters all read Version.approvalStatus, so a shot-level verdict was invisible
everywhere those look.

clearStaleShotApproval covers the reverse case: uploading a new version onto an
approved shot moved the task to INTERNAL_REVIEW and changed nothing visible,
because the derivation short-circuits on shotApprovalStatus. The shot kept
reading COMPLETE while carrying work nobody had looked at. This is the one
user-visible behaviour change here, so watch the boards on a live show: an
approved shot now drops back to INTERNAL_REVIEW on a new upload. sharedWithClient
is deliberately left alone, since revoking client access stays a separate act.

submitApproval and unapproveVersion are transactional now. The verdict, the
version, the task and the derived shot status are one decision, and a failure
partway through left the three layers disagreeing with no way to tell which one
was right.

KanbanCard compared approvalStatus against "CHANGES_REQUESTED", which is not a
member of the enum, so the changes-requested icon never rendered at all.

Thirteen tests cover carryApproval, markShotForRevisions including the all-DONE
regression, and clearStaleShotApproval. What is not covered is the pipeline
transaction itself, which needs a database: queue a render against a shot in
REVISIONS and confirm the task and shot both move before trusting this on a
show.

Version.reviewStatus is still written nowhere while being published through
ext/shots/lookup and EXT_API_REFERENCE.md as a permanent "PENDING". Left alone
deliberately: removing a field from that contract could break the connector.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-31 18:17:04 +02:00

178 lines
6.6 KiB
TypeScript

import { Prisma, QCResult } from "@prisma/client";
import { z } from "zod";
import { db } from "@/lib/db";
import { PipelineError } from "./errors";
import { applyTransition } from "./transitions";
import { recalcShotStatus } from "@/lib/shot-status";
/**
* QC workflow (RenderPipeline2 §10) — technical/final-delivery QC on shots the
* client has usually already approved. One service, two front doors: the AE
* panel (API key) and the web QC page (session).
*
* PASS means "ready to upload" and nothing else: it never shares to the client
* portal, never changes approval state, never creates client-visible media
* (§10.0). FAIL does move the comp task to CHANGES — the shot genuinely needs
* rework, and the existing REVISIONS derivation should surface that.
*/
export const qcSubmitSchema = z.object({
result: z.enum(["PASS", "FAIL"]),
notes: z.string().max(4000).optional().nullable(),
/** Panel sends the artist's email; web callers pass the session user instead. */
reviewerEmail: z.string().email().optional().nullable(),
reviewerName: z.string().max(200).optional().nullable(),
});
export type QCSubmitInput = z.infer<typeof qcSubmitSchema>;
export interface QCActor {
source: "AE_PANEL" | "WEB";
userId?: string | null;
name?: string | null;
}
/** Statuses a QC decision can be recorded from. */
const QC_ELIGIBLE = ["READY_FOR_QC", "QC_FAILED", "READY_FOR_DELIVERY"] as const;
export async function submitQCReview(exportId: string, input: QCSubmitInput, actor: QCActor) {
const reviewer = input.reviewerEmail
? await db.user.findUnique({ where: { email: input.reviewerEmail }, select: { id: true, name: true } })
: null;
const reviewedById = actor.userId ?? reviewer?.id ?? null;
const reviewerName = actor.name ?? reviewer?.name ?? input.reviewerName ?? input.reviewerEmail ?? null;
return db.$transaction(async (tx) => {
const exportRow = await tx.export.findUnique({
where: { id: exportId },
include: { shot: { select: { shotCode: true } } },
});
if (!exportRow) throw new PipelineError(404, "Export not found");
if (!QC_ELIGIBLE.includes(exportRow.status as (typeof QC_ELIGIBLE)[number])) {
throw new PipelineError(
409,
`Export is ${exportRow.status} — QC can only be recorded on ${QC_ELIGIBLE.join(", ")}`
);
}
const result = input.result as QCResult;
const review = await tx.qCReview.create({
data: {
exportId,
result,
notes: input.notes?.trim() || null,
reviewedById,
reviewerName,
source: actor.source,
},
});
const who = reviewerName ?? "unknown reviewer";
let taskUpdated: { id: string; status: string } | null = null;
if (result === "PASS") {
// Re-passing an export that is already READY_FOR_DELIVERY is a no-op
// transition-wise; the QCReview row is still the record of the decision.
const updated =
exportRow.status === "READY_FOR_DELIVERY"
? exportRow
: await applyTransition(tx, exportRow, "READY_FOR_DELIVERY", {
type: "USER",
id: reviewedById,
note: `QC PASS by ${who}${input.notes ? ` — ${input.notes.slice(0, 200)}` : ""}`,
});
return {
export: { id: updated.id, status: updated.status },
review: { id: review.id, result, createdAt: review.createdAt },
task: null,
};
}
// FAIL — the shot needs rework, so the comp task goes back to CHANGES.
const updated =
exportRow.status === "QC_FAILED"
? exportRow
: await applyTransition(tx, exportRow, "QC_FAILED", {
type: "USER",
id: reviewedById,
note: `QC FAIL by ${who}${input.notes ? ` — ${input.notes.slice(0, 200)}` : ""}`,
});
if (exportRow.taskId) {
const task = await tx.task.findUnique({ where: { id: exportRow.taskId }, select: { id: true, status: true } });
if (task && task.status !== "CHANGES") {
await tx.task.update({ where: { id: task.id }, data: { status: "CHANGES" } });
taskUpdated = { id: task.id, status: "CHANGES" };
// Shot.status is derived from its tasks and does not recompute on its
// own, so without this the shot never actually reached REVISIONS.
await recalcShotStatus(exportRow.shotId, tx);
}
}
return {
export: { id: updated.id, status: updated.status },
review: { id: review.id, result, createdAt: review.createdAt },
task: taskUpdated,
};
});
}
export interface QCQueueFilter {
projectCode?: string | null;
projectId?: string | null;
episode?: string | null;
limit?: number;
}
/**
* E5 — everything waiting for a human. QC_FAILED is deliberately excluded: a
* failed export is the artist's problem until they queue a new version.
*/
export async function getQCQueue(filter: QCQueueFilter) {
const limit = Math.min(200, Math.max(1, filter.limit ?? 50));
const where: Prisma.ExportWhereInput = {
status: "READY_FOR_QC",
...(filter.projectId ? { projectId: filter.projectId } : {}),
...(filter.projectCode ? { shot: { project: { code: filter.projectCode } } } : {}),
...(filter.episode
? { shot: { ...(filter.projectCode ? { project: { code: filter.projectCode } } : {}), episode: filter.episode } }
: {}),
};
const rows = await db.export.findMany({
where,
orderBy: { statusChangedAt: "asc" }, // oldest first — nothing should sit in QC
take: limit,
include: {
shot: { select: { id: true, shotCode: true, episode: true, scene: true, project: { select: { code: true, name: true } } } },
validations: { where: { status: { in: ["FAIL", "WARN"] } }, select: { checkName: true, status: true, message: true } },
},
});
return {
queue: rows.map((e) => ({
exportId: e.id,
shotCode: e.shot.shotCode,
episode: e.shot.episode,
scene: e.shot.scene,
projectCode: e.shot.project.code,
versionString: e.versionString,
readySince: e.statusChangedAt,
// Everything the panel needs to import the actual EXRs for full-res QC
outputDir: e.outputDir,
outputPattern: e.outputPattern,
frameStart: e.frameStart,
frameEnd: e.frameEnd,
fps: e.fps,
deliveryMovPath: e.deliveryMovPath,
thumbnailUrl: e.thumbnailKey ? `/api/files/${e.thumbnailKey}` : null,
previewUrl: e.previewMovKey ? `/api/files/${e.previewMovKey}` : null,
// Warnings the automated pass raised — the human should look harder at these
warnings: e.validations.map((v) => ({ checkName: v.checkName, status: v.status, message: v.message })),
})),
};
}