Files
vfxreview/actions/approvals.ts
T
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

216 lines
6.9 KiB
TypeScript

"use server";
import { auth } from "@/auth";
import { db } from "@/lib/db";
import { revalidatePath } from "next/cache";
import { z } from "zod";
import { ApprovalStatus } from "@prisma/client";
import { recalcShotStatus, clearStaleShotApproval } from "@/lib/shot-status";
import { notifyApprovalChange } from "@/lib/notifications";
import { slackNotifyApproval } from "@/lib/slack";
import { versionLabel } from "@/lib/utils";
import { createDisplayEvent } from "@/lib/display-events";
const approvalSchema = z.object({
versionId: z.string().cuid(),
status: z.nativeEnum(ApprovalStatus),
notes: z.string().optional(),
});
export async function submitApproval(data: z.infer<typeof approvalSchema>) {
const session = await auth();
if (!session?.user) throw new Error("Unauthorized");
const parsed = approvalSchema.parse(data);
// Only supervisors, producers, admins, and clients can approve
const allowedRoles = ["ADMIN", "PRODUCER", "SUPERVISOR", "CLIENT"];
if (!allowedRoles.includes(session.user.role)) {
throw new Error("Insufficient permissions to review versions");
}
// The verdict, the version, the task and the derived shot status are one
// decision and are written as one: a failure partway through used to leave the
// three layers disagreeing, with no way to tell which one was right.
const { approval, version } = await db.$transaction(async (tx) => {
const approval = await tx.approval.create({
data: {
versionId: parsed.versionId,
userId: session.user.id,
status: parsed.status,
notes: parsed.notes,
},
});
await tx.version.update({
where: { id: parsed.versionId },
data: { approvalStatus: parsed.status },
});
// Load version + task + shot + project for downstream effects
const version = await tx.version.findUnique({
where: { id: parsed.versionId },
include: {
task: {
include: {
shot: true,
project: true,
},
},
},
});
if (!version) throw new Error("Version not found");
// Update task status based on approval result
if (version.task && parsed.status !== "PENDING_REVIEW") {
if (parsed.status === "APPROVED") {
await tx.task.update({
where: { id: version.task.id },
data: { status: "DONE" },
});
} else if (parsed.status === "REJECTED" || parsed.status === "NEEDS_CHANGES") {
await tx.task.update({
where: { id: version.task.id },
data: { status: "CHANGES" },
});
}
// Recalculate shot status from updated task states
if (version.task.shot) {
await recalcShotStatus(version.task.shot.id, tx);
}
}
return { approval, version };
});
// Notifications
const reviewer = await db.user.findUnique({ where: { id: session.user.id } });
const reviewerName = reviewer?.name ?? "Reviewer";
if (version.task && parsed.status !== "PENDING_REVIEW") {
const contextCode = version.task.shot?.shotCode ?? null;
await notifyApprovalChange({
artistId: version.task.assignedArtistId ?? version.artistId,
shotCode: contextCode ?? version.task.title,
versionId: parsed.versionId,
status: parsed.status as "APPROVED" | "REJECTED" | "NEEDS_CHANGES",
reviewerName,
});
// Slack
if (version.task.project.slackWebhook) {
const appUrl = process.env.NEXT_PUBLIC_APP_URL ?? "http://localhost:3000";
await slackNotifyApproval(version.task.project.slackWebhook, {
shotCode: contextCode ?? version.task.title,
versionLabel: versionLabel(version.versionNumber),
status: parsed.status as "APPROVED" | "REJECTED" | "NEEDS_CHANGES",
reviewerName,
projectName: version.task.project.name,
reviewUrl: `${appUrl}/review/${parsed.versionId}`,
});
}
}
// Display board event
const contextCode = version.task?.shot?.shotCode ?? version.task?.title ?? null;
if (contextCode && parsed.status !== "PENDING_REVIEW") {
const displayType =
parsed.status === "APPROVED" ? "APPROVED" :
parsed.status === "NEEDS_CHANGES" ? "CHANGES" : "REJECTED";
await createDisplayEvent(displayType, contextCode, reviewerName);
}
revalidatePath(`/review/${parsed.versionId}`);
if (version.task) {
revalidatePath(`/tasks/${version.task.id}`);
revalidatePath(`/projects/${version.task.projectId}`);
}
return { success: true, approval };
}
export async function getApprovalHistory(versionId: string) {
const session = await auth();
if (!session?.user) throw new Error("Unauthorized");
return db.approval.findMany({
where: { versionId },
include: {
user: { select: { id: true, name: true, email: true, image: true, role: true } },
},
orderBy: { createdAt: "desc" },
});
}
/**
* Resets an approved version back to PENDING_REVIEW and the associated task
* back to INTERNAL_REVIEW. Recalculates shot status.
* Only ADMIN, PRODUCER, SUPERVISOR can unapprove.
*/
export async function unapproveVersion(versionId: string) {
const session = await auth();
if (!session?.user) throw new Error("Unauthorized");
const allowedRoles = ["ADMIN", "PRODUCER", "SUPERVISOR"];
if (!allowedRoles.includes(session.user.role)) {
throw new Error("Insufficient permissions to unapprove versions");
}
const version = await db.version.findUnique({
where: { id: versionId },
include: {
task: {
include: { shot: true },
},
},
});
if (!version) throw new Error("Version not found");
if (version.approvalStatus !== "APPROVED") {
throw new Error("Only approved versions can be unapproved");
}
// One decision, one write — same reasoning as submitApproval.
await db.$transaction(async (tx) => {
// Create an audit record for the unapproval
await tx.approval.create({
data: {
versionId,
userId: session.user.id,
status: "PENDING_REVIEW",
notes: "Approval undone",
},
});
// Reset version approval status
await tx.version.update({
where: { id: versionId },
data: { approvalStatus: "PENDING_REVIEW" },
});
// Reset task back to INTERNAL_REVIEW if it was moved to DONE
if (version.task && version.task.status === "DONE") {
await tx.task.update({
where: { id: version.task.id },
data: { status: "INTERNAL_REVIEW" },
});
}
// Undoing a version approval also invalidates any shot-level sign-off that
// rested on it, otherwise the shot keeps reading COMPLETE / READY_FOR_CLIENT.
if (version.task?.shot) {
await clearStaleShotApproval(tx, version.task.shot.id);
await recalcShotStatus(version.task.shot.id, tx);
}
});
revalidatePath(`/review/${versionId}`);
if (version.task) {
revalidatePath(`/tasks/${version.task.id}`);
revalidatePath(`/projects/${version.task.projectId}`);
}
return { success: true };
}