Compare commits
6 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 269a5cbfda | |||
| 59af7959e6 | |||
| a6ee1917e7 | |||
| 28e8c47907 | |||
| 94792279c5 | |||
| 93137cdcd2 |
@@ -1292,6 +1292,11 @@ The panel keeps all existing capabilities (episode/shot discovery, overlays, pic
|
||||
| Latest Export + QC status | new E2 `exports/latest` — e.g. `v004 — READY_FOR_QC`, `v004 — RENDERING 42% (ETA 1:36 on RENDER-01)`, `v003 — QC FAILED: "grain mismatch"` |
|
||||
|
||||
While an export is active the panel polls E2 every 15 s to live-update the header.
|
||||
The poll stops when the export leaves an active status, and also when the panel is
|
||||
closed or reloaded — `app.scheduleTask` outlives the panel instance that armed it,
|
||||
so the task id is kept in ExtendScript global scope where the next instance can
|
||||
still cancel it. The export is unaffected either way: it runs on the farm, and the
|
||||
header picks its status back up on the next Refresh.
|
||||
|
||||
### 12.2 Buttons and their API calls
|
||||
|
||||
|
||||
+282
-18
@@ -32,7 +32,7 @@ var SETTINGS_KEY = "cfg";
|
||||
// Bump on every change deployed to a workstation. The panel reports this to
|
||||
// the server on load, so Pipeline → Machines shows which version each machine
|
||||
// is actually running and flags the ones left behind.
|
||||
var PANEL_VERSION = "2.5.0";
|
||||
var PANEL_VERSION = "2.6.2";
|
||||
|
||||
(function VFXReviewConnector(thisObj) {
|
||||
var uiState = {
|
||||
@@ -65,7 +65,6 @@ var PANEL_VERSION = "2.5.0";
|
||||
|
||||
var pipelineState = {
|
||||
pollShotCode: null,
|
||||
pollTaskId: 0,
|
||||
prefilledShotCode: null
|
||||
};
|
||||
|
||||
@@ -958,17 +957,29 @@ var PANEL_VERSION = "2.5.0";
|
||||
}
|
||||
}
|
||||
|
||||
// Assigning displayStartFrame on a version of AE that does not have the
|
||||
// property is ignored silently rather than throwing, which is one of the
|
||||
// ways a comp ends up back at 00:00:00:00. Read the value back and fall
|
||||
// through to displayStartTime when it did not take, and tell the caller
|
||||
// whether anything stuck.
|
||||
function setCompStartFrame(comp, frameNumber) {
|
||||
var wanted = Math.round(frameNumber);
|
||||
|
||||
try {
|
||||
comp.displayStartFrame = frameNumber;
|
||||
return;
|
||||
if (Math.round(comp.displayStartFrame) === wanted) {
|
||||
return true;
|
||||
}
|
||||
} catch (frameError) {
|
||||
}
|
||||
|
||||
try {
|
||||
comp.displayStartTime = frameNumber / comp.frameRate;
|
||||
return Math.round(comp.displayStartTime * comp.frameRate) === wanted;
|
||||
} catch (timeError) {
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
function deselectAllProjectItems() {
|
||||
@@ -1051,13 +1062,220 @@ var PANEL_VERSION = "2.5.0";
|
||||
return frames;
|
||||
}
|
||||
|
||||
// The plate's own start timecode: AE metadata when we can read it,
|
||||
// otherwise the API's source clip timecode less the handle frames — the
|
||||
// same convention the Set Start Timecode button uses.
|
||||
// The first file of an imported sequence: the frame whose header carries the
|
||||
// plate's start timecode. importEXRSequence sorts before importing, so this
|
||||
// is the sequence's first frame and not an arbitrary one.
|
||||
function getFootageFirstFile(footageItem) {
|
||||
try {
|
||||
if (footageItem && footageItem.mainSource && footageItem.mainSource.file) {
|
||||
return footageItem.mainSource.file;
|
||||
}
|
||||
} catch (fileError) {
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
function readUInt32LE(buf, offset) {
|
||||
return (buf.charCodeAt(offset) & 0xFF) +
|
||||
(buf.charCodeAt(offset + 1) & 0xFF) * 256 +
|
||||
(buf.charCodeAt(offset + 2) & 0xFF) * 65536 +
|
||||
(buf.charCodeAt(offset + 3) & 0xFF) * 16777216;
|
||||
}
|
||||
|
||||
function readInt32LE(buf, offset) {
|
||||
var value = readUInt32LE(buf, offset);
|
||||
|
||||
return value >= 2147483648 ? value - 4294967296 : value;
|
||||
}
|
||||
|
||||
// A null-terminated header string. Returns null when the terminator is not
|
||||
// found within a sane distance, which means the bytes are not a header we
|
||||
// understand and parsing should stop rather than guess.
|
||||
function readExrString(buf, offset) {
|
||||
var end = offset;
|
||||
var limit = Math.min(buf.length, offset + 256);
|
||||
|
||||
while (end < limit && buf.charCodeAt(end) !== 0) {
|
||||
end += 1;
|
||||
}
|
||||
|
||||
if (end >= limit) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return buf.substring(offset, end);
|
||||
}
|
||||
|
||||
function pad2(value) {
|
||||
return (value < 10 ? "0" : "") + value;
|
||||
}
|
||||
|
||||
function makeTimecode(hours, minutes, seconds, frames, dropFrame) {
|
||||
if (hours > 23 || minutes > 59 || seconds > 59) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
hours: hours,
|
||||
minutes: minutes,
|
||||
seconds: seconds,
|
||||
frames: frames,
|
||||
dropFrame: dropFrame,
|
||||
text: pad2(hours) + ":" + pad2(minutes) + ":" + pad2(seconds) +
|
||||
(dropFrame ? ";" : ":") + pad2(frames)
|
||||
};
|
||||
}
|
||||
|
||||
// SMPTE 12M as stored in the EXR timeCode attribute: BCD-packed, which is
|
||||
// why the raw value reads back as its own hex digits (0x18585712 is
|
||||
// 18:58:57:12). Every field sits inside a single byte, so the nibbles can be
|
||||
// picked off per byte and never touch the sign bit.
|
||||
function decodePackedTimecode(buf, offset) {
|
||||
var b0 = buf.charCodeAt(offset) & 0xFF; // frames, drop-frame flag
|
||||
var b1 = buf.charCodeAt(offset + 1) & 0xFF; // seconds
|
||||
var b2 = buf.charCodeAt(offset + 2) & 0xFF; // minutes
|
||||
var b3 = buf.charCodeAt(offset + 3) & 0xFF; // hours
|
||||
|
||||
return makeTimecode(
|
||||
(b3 & 0x0F) + ((b3 >> 4) & 0x03) * 10,
|
||||
(b2 & 0x0F) + ((b2 >> 4) & 0x07) * 10,
|
||||
(b1 & 0x0F) + ((b1 >> 4) & 0x07) * 10,
|
||||
(b0 & 0x0F) + ((b0 >> 4) & 0x03) * 10,
|
||||
((b0 >> 6) & 0x01) === 1);
|
||||
}
|
||||
|
||||
function parseTimecodeText(text) {
|
||||
var parts = String(text).split(/[:;]/);
|
||||
|
||||
if (parts.length < 4) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return makeTimecode(
|
||||
parseInt(parts[0], 10) || 0,
|
||||
parseInt(parts[1], 10) || 0,
|
||||
parseInt(parts[2], 10) || 0,
|
||||
parseInt(parts[3], 10) || 0,
|
||||
String(text).indexOf(";") !== -1);
|
||||
}
|
||||
|
||||
// Reads the plate's timecode straight out of the OpenEXR header, the way the
|
||||
// worker's ExrHeader.cs does, so the panel anchors comps on exactly the
|
||||
// value validation later checks them against. Header layout is
|
||||
// magic(4) version(4) then attributes as `name\0 type\0 int32 size data`,
|
||||
// terminated by an empty name — one short read, no pixel decode.
|
||||
//
|
||||
// Returns null when the file is unreadable or carries no timecode at all.
|
||||
function readExrTimecode(file) {
|
||||
var EXR_HEADER_BYTES = 65536;
|
||||
var EXR_MAGIC = 20000630;
|
||||
var buf = null;
|
||||
var opened = false;
|
||||
var pos = 8;
|
||||
var packed = null;
|
||||
var text = null;
|
||||
var name;
|
||||
var type;
|
||||
var size;
|
||||
|
||||
if (!file || !file.exists) {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
file.encoding = "BINARY";
|
||||
opened = file.open("r");
|
||||
if (opened) {
|
||||
buf = file.read(EXR_HEADER_BYTES);
|
||||
}
|
||||
} catch (readError) {
|
||||
buf = null;
|
||||
}
|
||||
|
||||
try {
|
||||
if (opened) {
|
||||
file.close();
|
||||
}
|
||||
} catch (closeError) {
|
||||
}
|
||||
|
||||
if (!buf || buf.length < 16 || readUInt32LE(buf, 0) !== EXR_MAGIC) {
|
||||
return null;
|
||||
}
|
||||
|
||||
while (pos < buf.length) {
|
||||
name = readExrString(buf, pos);
|
||||
if (name === null) {
|
||||
break;
|
||||
}
|
||||
pos += name.length + 1;
|
||||
if (name.length === 0) {
|
||||
break; // an empty name ends the header
|
||||
}
|
||||
|
||||
type = readExrString(buf, pos);
|
||||
if (type === null) {
|
||||
break;
|
||||
}
|
||||
pos += type.length + 1;
|
||||
|
||||
if (pos + 4 > buf.length) {
|
||||
break;
|
||||
}
|
||||
size = readInt32LE(buf, pos);
|
||||
pos += 4;
|
||||
if (size < 0 || pos + size > buf.length) {
|
||||
break;
|
||||
}
|
||||
|
||||
if (name === "timeCode" && size >= 8) {
|
||||
packed = decodePackedTimecode(buf, pos);
|
||||
} else if (name === "timeCodeString" && size >= 11) {
|
||||
text = parseTimecodeText(buf.substr(pos, size).replace(/\0+$/, ""));
|
||||
}
|
||||
|
||||
pos += size;
|
||||
}
|
||||
|
||||
// The packed attribute is the authoritative one; timeCodeString is a
|
||||
// convenience copy that some writers emit and others omit.
|
||||
return packed || text;
|
||||
}
|
||||
|
||||
// Non-drop frame count, mirroring Timecode.ToFrames in the worker. The show
|
||||
// rate is the authority — a plate's own rate is whatever happens to be on
|
||||
// disk, and plates are conformed to the show rate on import.
|
||||
function timecodeToFrames(tc, fps) {
|
||||
var rate = Math.round(resolveFps(fps));
|
||||
|
||||
return ((tc.hours * 60 + tc.minutes) * 60 + tc.seconds) * rate + tc.frames;
|
||||
}
|
||||
|
||||
// The plate's own start timecode, ranked the way validation ranks it
|
||||
// (RenderPipeline2 §8.1a): the EXR header's embedded timecode first, then
|
||||
// AE's own read of the footage metadata, and only then the API's source clip
|
||||
// timecode less the handle frames — the convention the Set Start Timecode
|
||||
// button uses. The API value is the editorial in-point and sits a
|
||||
// handle-length ahead of the plate by design, so it is the last resort
|
||||
// rather than the first.
|
||||
function getFootageStartFrames(footageItem, apiShot, fps) {
|
||||
var probed = probeFootageStartFrames(footageItem, fps);
|
||||
var exrTc = readExrTimecode(getFootageFirstFile(footageItem));
|
||||
var probed;
|
||||
var frames;
|
||||
|
||||
if (exrTc) {
|
||||
frames = timecodeToFrames(exrTc, fps);
|
||||
if (frames > 0) {
|
||||
return {
|
||||
frames: frames,
|
||||
source: "EXR timecode " + exrTc.text +
|
||||
(exrTc.dropFrame ? " (drop-frame flag set on the plate)" : "")
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
probed = probeFootageStartFrames(footageItem, fps);
|
||||
if (probed !== null && probed > 0) {
|
||||
return { frames: probed, source: "footage metadata" };
|
||||
}
|
||||
@@ -1069,7 +1287,10 @@ var PANEL_VERSION = "2.5.0";
|
||||
}
|
||||
}
|
||||
|
||||
return { frames: 0, source: probed === 0 ? "footage starts at 00:00:00:00" : "no timecode found" };
|
||||
return {
|
||||
frames: 0,
|
||||
source: (exrTc || probed === 0) ? "the plate starts at 00:00:00:00" : "no timecode found"
|
||||
};
|
||||
}
|
||||
|
||||
function findComp(name) {
|
||||
@@ -1914,7 +2135,9 @@ var PANEL_VERSION = "2.5.0";
|
||||
diagLog("start frame " + startInfo.frames + " from " + startInfo.source);
|
||||
|
||||
footageComp = app.project.items.addComp(shotCode + "_FOOTAGE", width, height, 1, maxDuration, fps);
|
||||
setCompStartFrame(footageComp, startInfo.frames);
|
||||
if (!setCompStartFrame(footageComp, startInfo.frames)) {
|
||||
diagLog("could not set the start frame on " + footageComp.name + " - it will read 00:00:00:00");
|
||||
}
|
||||
if (precompFolder) {
|
||||
footageComp.parentFolder = precompFolder;
|
||||
}
|
||||
@@ -1925,7 +2148,9 @@ var PANEL_VERSION = "2.5.0";
|
||||
}
|
||||
|
||||
shotComp = app.project.items.addComp(shotCode, width, height, 1, maxDuration, fps);
|
||||
setCompStartFrame(shotComp, startInfo.frames);
|
||||
if (!setCompStartFrame(shotComp, startInfo.frames)) {
|
||||
diagLog("could not set the start frame on " + shotComp.name + " - it will read 00:00:00:00");
|
||||
}
|
||||
if (episodeProjectFolder) {
|
||||
shotComp.parentFolder = episodeProjectFolder;
|
||||
} else {
|
||||
@@ -3636,13 +3861,34 @@ var PANEL_VERSION = "2.5.0";
|
||||
}
|
||||
}
|
||||
|
||||
// A scheduled task outlives the panel instance that armed it. Held only in
|
||||
// this closure, the id of a repeating task goes with the instance when the
|
||||
// panel is closed or reloaded, and nothing can cancel it again: it fires
|
||||
// every 15 s for the rest of the AE session, and every tick that lands
|
||||
// while a modal dialog is open raises "Cannot run a script while a modal
|
||||
// dialog is waiting for response." The id therefore lives beside the tick
|
||||
// in global scope, where the next instance can still reach it.
|
||||
var POLL_TASK_ID_KEY = "__vfxrExportPollTaskId";
|
||||
|
||||
function getPollTaskId() {
|
||||
var taskId = $.global[POLL_TASK_ID_KEY];
|
||||
|
||||
return (typeof taskId === "number" && taskId > 0) ? taskId : 0;
|
||||
}
|
||||
|
||||
function setPollTaskId(taskId) {
|
||||
$.global[POLL_TASK_ID_KEY] = taskId || 0;
|
||||
}
|
||||
|
||||
function stopExportPolling() {
|
||||
if (pipelineState.pollTaskId) {
|
||||
var taskId = getPollTaskId();
|
||||
|
||||
if (taskId) {
|
||||
try {
|
||||
app.cancelTask(pipelineState.pollTaskId);
|
||||
app.cancelTask(taskId);
|
||||
} catch (cancelError) {
|
||||
}
|
||||
pipelineState.pollTaskId = 0;
|
||||
setPollTaskId(0);
|
||||
}
|
||||
pipelineState.pollShotCode = null;
|
||||
}
|
||||
@@ -3676,9 +3922,9 @@ var PANEL_VERSION = "2.5.0";
|
||||
stopExportPolling();
|
||||
pipelineState.pollShotCode = shotCode;
|
||||
try {
|
||||
pipelineState.pollTaskId = app.scheduleTask("__vfxrExportPollTick()", 15000, true);
|
||||
setPollTaskId(app.scheduleTask("__vfxrExportPollTick()", 15000, true));
|
||||
} catch (scheduleError) {
|
||||
pipelineState.pollTaskId = 0;
|
||||
setPollTaskId(0);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4174,8 +4420,13 @@ var PANEL_VERSION = "2.5.0";
|
||||
// catching mask slips, export glitches and metadata faults at full res, so
|
||||
// selecting a queue entry imports the real sequence.
|
||||
|
||||
// The queue endpoint defaults to 50 rows and refuses anything above 200, so
|
||||
// ask for the ceiling: a busy project can have well over 50 exports sitting
|
||||
// in READY_FOR_QC, and the panel silently showed only the oldest 50.
|
||||
var QC_QUEUE_LIMIT = 200;
|
||||
|
||||
function loadQCQueue() {
|
||||
var url = CONFIG.baseUrl + "/api/ext/qc/queue";
|
||||
var url = CONFIG.baseUrl + "/api/ext/qc/queue?limit=" + QC_QUEUE_LIMIT;
|
||||
var data;
|
||||
var entries;
|
||||
var i;
|
||||
@@ -4186,7 +4437,7 @@ var PANEL_VERSION = "2.5.0";
|
||||
return;
|
||||
}
|
||||
if (CURRENT_PROJECT) {
|
||||
url += "?projectCode=" + encodeURIComponent(CURRENT_PROJECT.code);
|
||||
url += "&projectCode=" + encodeURIComponent(CURRENT_PROJECT.code);
|
||||
}
|
||||
|
||||
setQCStatus("Loading QC queue...");
|
||||
@@ -4211,7 +4462,8 @@ var PANEL_VERSION = "2.5.0";
|
||||
|
||||
if (entries.length) {
|
||||
uiState.qcList.selection = 0;
|
||||
setQCStatus(entries.length + " export(s) awaiting QC");
|
||||
setQCStatus(entries.length + " export(s) awaiting QC" +
|
||||
(entries.length >= QC_QUEUE_LIMIT ? " (list is capped — QC some and reload)" : ""));
|
||||
} else {
|
||||
setQCStatus("Nothing waiting for QC");
|
||||
}
|
||||
@@ -4797,6 +5049,11 @@ var PANEL_VERSION = "2.5.0";
|
||||
return win;
|
||||
}
|
||||
|
||||
// A previous instance may have left a repeating poll armed, and its shot
|
||||
// code went with that closure. Cancel it before the tick is pointed at this
|
||||
// instance, rather than letting it fire into a fresh, empty state.
|
||||
stopExportPolling();
|
||||
|
||||
// app.scheduleTask evaluates in global scope — expose the poll tick there
|
||||
$.global.__vfxrExportPollTick = pollExportTick;
|
||||
|
||||
@@ -4807,6 +5064,13 @@ var PANEL_VERSION = "2.5.0";
|
||||
diagLog("panel v" + PANEL_VERSION + " loaded on " + getHostName());
|
||||
reportPanelVersion();
|
||||
|
||||
// Closing the panel leaves an armed task running with no UI left to update.
|
||||
// The export itself is unaffected: it runs on the farm, and the panel picks
|
||||
// its status back up from the server on the next Refresh.
|
||||
panel.onClose = function () {
|
||||
stopExportPolling();
|
||||
};
|
||||
|
||||
if (panel instanceof Window) {
|
||||
panel.center();
|
||||
panel.show();
|
||||
|
||||
+25
-4
@@ -201,16 +201,37 @@ Constructs a full shot composite in the open AE project from the episode and sho
|
||||
**Process:**
|
||||
1. Calls the shot lookup API to retrieve metadata (description, notes, episode, scene, etc.).
|
||||
2. If a comp with the shot code already exists, updates its overlay instead of rebuilding.
|
||||
3. Scans `FOOTAGE_ROOT/{episodeCode}/` for subfolders matching `{shotCode}_*` and imports each as an EXR image sequence at 24 fps.
|
||||
3. Scans `FOOTAGE_ROOT/{episodeCode}/` for subfolders matching `{shotCode}_*` and imports each as an EXR image sequence, conformed to the shot's frame rate.
|
||||
4. Creates a `{shotCode}_FOOTAGE` precomp containing all imported sequences, each with an OCIO Color Space Transform effect added (disabled by default).
|
||||
5. Creates the main `{shotCode}` comp and places the footage precomp inside it.
|
||||
6. If a `_SHOW LUT` comp exists in the project, adds it as a collapsed layer on top.
|
||||
7. Calls **Add Overlay** logic to attach the `UNG_VFX_OVERLAY` comp.
|
||||
8. Organises items into `__SHOTS/{episodeCode}`, `_FOOTAGE_4K`, and `_PRECOMPS` project folders.
|
||||
6. Anchors both comps on the plate's start timecode — see [Start timecode](#start-timecode).
|
||||
7. If a `_SHOW LUT` comp exists in the project, adds it as a collapsed layer on top.
|
||||
8. Calls **Add Overlay** logic to attach the `UNG_VFX_OVERLAY` comp.
|
||||
9. Organises items into `__SHOTS/{episodeCode}`, `_FOOTAGE_4K`, and `_PRECOMPS` project folders.
|
||||
|
||||
If any step fails, the status line names the stage and a copyable report opens —
|
||||
see [Diagnostics and logging](#diagnostics-and-logging).
|
||||
|
||||
#### Start timecode
|
||||
|
||||
Neither comp starts at `00:00:00:00`. Both are anchored on the plate's own start
|
||||
timecode, taken from the first source that has one:
|
||||
|
||||
| Rank | Source | Notes |
|
||||
|---|---|---|
|
||||
| 1 | The first EXR's header | The `timeCode` attribute, or `timeCodeString` where the packed one is absent. Read straight off disk — no pixel decode, and no dependency on what AE chose to expose. |
|
||||
| 2 | AE's footage metadata | What "New Comp from Selection" would have inherited. |
|
||||
| 3 | API `timecodeStart` less `handleFrames` | The convention **Set Start Timecode** uses. Last resort: the API stores the *editorial* in-point, which is a handle-length ahead of the plate by design. |
|
||||
|
||||
This is the same ranking the render worker's validation uses (RenderPipeline2
|
||||
§8.1a), so a comp is anchored on exactly the value its EXRs are later checked
|
||||
against — a shot built from rank 3 and validated against rank 1 is how a
|
||||
timecode desync gets into a delivery.
|
||||
|
||||
The status line and the diagnostics log both name the rank that was used, e.g.
|
||||
`start frame 864108 from EXR timecode 10:00:04:12`. A plate carrying no timecode
|
||||
in any rank leaves the comp at `00:00:00:00` and says so.
|
||||
|
||||
---
|
||||
|
||||
## Render Pipeline
|
||||
|
||||
+82
-72
@@ -5,7 +5,7 @@ import { db } from "@/lib/db";
|
||||
import { revalidatePath } from "next/cache";
|
||||
import { z } from "zod";
|
||||
import { ApprovalStatus } from "@prisma/client";
|
||||
import { recalcShotStatus } from "@/lib/shot-status";
|
||||
import { recalcShotStatus, clearStaleShotApproval } from "@/lib/shot-status";
|
||||
import { notifyApprovalChange } from "@/lib/notifications";
|
||||
import { slackNotifyApproval } from "@/lib/slack";
|
||||
import { versionLabel } from "@/lib/utils";
|
||||
@@ -29,57 +29,62 @@ export async function submitApproval(data: z.infer<typeof approvalSchema>) {
|
||||
throw new Error("Insufficient permissions to review versions");
|
||||
}
|
||||
|
||||
// Create the approval record
|
||||
const approval = await db.approval.create({
|
||||
data: {
|
||||
versionId: parsed.versionId,
|
||||
userId: session.user.id,
|
||||
status: parsed.status,
|
||||
notes: parsed.notes,
|
||||
},
|
||||
});
|
||||
// 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,
|
||||
},
|
||||
});
|
||||
|
||||
// Update version approval status
|
||||
await db.version.update({
|
||||
where: { id: parsed.versionId },
|
||||
data: { approvalStatus: parsed.status },
|
||||
});
|
||||
await tx.version.update({
|
||||
where: { id: parsed.versionId },
|
||||
data: { approvalStatus: parsed.status },
|
||||
});
|
||||
|
||||
// Load version + task + shot + project for downstream effects
|
||||
const version = await db.version.findUnique({
|
||||
where: { id: parsed.versionId },
|
||||
include: {
|
||||
task: {
|
||||
include: {
|
||||
shot: true,
|
||||
project: true,
|
||||
// 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 };
|
||||
});
|
||||
|
||||
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 db.task.update({
|
||||
where: { id: version.task.id },
|
||||
data: { status: "DONE" },
|
||||
});
|
||||
} else if (parsed.status === "REJECTED" || parsed.status === "NEEDS_CHANGES") {
|
||||
await db.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).catch(() => {});
|
||||
}
|
||||
}
|
||||
|
||||
// Notifications
|
||||
const reviewer = await db.user.findUnique({ where: { id: session.user.id } });
|
||||
const reviewerName = reviewer?.name ?? "Reviewer";
|
||||
@@ -166,34 +171,39 @@ export async function unapproveVersion(versionId: string) {
|
||||
throw new Error("Only approved versions can be unapproved");
|
||||
}
|
||||
|
||||
// Create an audit record for the unapproval
|
||||
await db.approval.create({
|
||||
data: {
|
||||
versionId,
|
||||
userId: session.user.id,
|
||||
status: "PENDING_REVIEW",
|
||||
notes: "Approval undone",
|
||||
},
|
||||
});
|
||||
|
||||
// Reset version approval status
|
||||
await db.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 db.task.update({
|
||||
where: { id: version.task.id },
|
||||
data: { status: "INTERNAL_REVIEW" },
|
||||
// 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",
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
// Recalculate shot status
|
||||
if (version.task?.shot) {
|
||||
await recalcShotStatus(version.task.shot.id).catch(() => {});
|
||||
}
|
||||
// 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) {
|
||||
|
||||
+51
-46
@@ -5,7 +5,7 @@ import { db } from "@/lib/db";
|
||||
import { revalidatePath } from "next/cache";
|
||||
import { z } from "zod";
|
||||
import { ShotStatus, ShotPriority, ShotApprovalStatus, Prisma } from "@prisma/client";
|
||||
import { recalcShotStatus } from "@/lib/shot-status";
|
||||
import { recalcShotStatus, markShotForRevisions } from "@/lib/shot-status";
|
||||
|
||||
const createShotSchema = z.object({
|
||||
scene: z.string().min(1).max(50).regex(/^[A-Z0-9_]+$/i, "Alphanumeric and underscore only"),
|
||||
@@ -341,6 +341,15 @@ export async function importShotsFromCsv(
|
||||
return { success: true, created, errors };
|
||||
}
|
||||
|
||||
/**
|
||||
* Manual override of the shot's status.
|
||||
*
|
||||
* Deliberately the one place that writes Shot.status without deriving it — but
|
||||
* note the override is transient: Shot.status is a derived field, so the next
|
||||
* recalc (any task move, approval, upload or render) recomputes it from the
|
||||
* tasks and approval flags and discards whatever was set here. Change the
|
||||
* underlying task states if the new status needs to stick.
|
||||
*/
|
||||
export async function updateShotStatus(
|
||||
shotId: string,
|
||||
status: ShotStatus
|
||||
@@ -737,13 +746,19 @@ export async function internallyApproveShot(shotId: string) {
|
||||
});
|
||||
if (!shot) throw new Error("Shot not found");
|
||||
|
||||
await db.shot.update({
|
||||
where: { id: shotId },
|
||||
data: {
|
||||
shotApprovalStatus: "INTERNALLY_APPROVED",
|
||||
sharedWithClient: false,
|
||||
status: "READY_FOR_CLIENT",
|
||||
},
|
||||
// Set the approval inputs and let the derivation pick the status. Writing
|
||||
// READY_FOR_CLIENT directly skipped the rule that an outstanding CHANGES task
|
||||
// outranks any approval, so a shot could be pushed past open rework and then
|
||||
// snap back to REVISIONS on the next unrelated recalc.
|
||||
await db.$transaction(async (tx) => {
|
||||
await tx.shot.update({
|
||||
where: { id: shotId },
|
||||
data: {
|
||||
shotApprovalStatus: "INTERNALLY_APPROVED",
|
||||
sharedWithClient: false,
|
||||
},
|
||||
});
|
||||
await recalcShotStatus(shotId, tx);
|
||||
});
|
||||
|
||||
revalidatePath(`/projects/${shot.projectId}`);
|
||||
@@ -786,7 +801,7 @@ export async function shareWithClient(shotId: string) {
|
||||
// Mark shot as shared
|
||||
await tx.shot.update({
|
||||
where: { id: shotId },
|
||||
data: { sharedWithClient: true, status: "CLIENT_REVIEW" },
|
||||
data: { sharedWithClient: true },
|
||||
});
|
||||
|
||||
// For each task, make the latest version client-visible
|
||||
@@ -806,6 +821,8 @@ export async function shareWithClient(shotId: string) {
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
await recalcShotStatus(shotId, tx);
|
||||
});
|
||||
|
||||
revalidatePath(`/projects/${shot.projectId}`);
|
||||
@@ -838,7 +855,7 @@ export async function unshareFromClient(shotId: string) {
|
||||
await db.$transaction(async (tx) => {
|
||||
await tx.shot.update({
|
||||
where: { id: shotId },
|
||||
data: { sharedWithClient: false, status: "READY_FOR_CLIENT" },
|
||||
data: { sharedWithClient: false },
|
||||
});
|
||||
|
||||
// Hide all client-visible versions on this shot's tasks
|
||||
@@ -849,6 +866,8 @@ export async function unshareFromClient(shotId: string) {
|
||||
data: { isClientVisible: false },
|
||||
});
|
||||
}
|
||||
|
||||
await recalcShotStatus(shotId, tx);
|
||||
});
|
||||
|
||||
revalidatePath(`/projects/${shot.projectId}`);
|
||||
@@ -877,9 +896,12 @@ export async function clientApproveShot(shotId: string) {
|
||||
if (!shot) throw new Error("Shot not found");
|
||||
if (!shot.sharedWithClient) throw new Error("Shot is not shared with client");
|
||||
|
||||
await db.shot.update({
|
||||
where: { id: shotId },
|
||||
data: { shotApprovalStatus: "CLIENT_APPROVED", status: "COMPLETE" },
|
||||
await db.$transaction(async (tx) => {
|
||||
await tx.shot.update({
|
||||
where: { id: shotId },
|
||||
data: { shotApprovalStatus: "CLIENT_APPROVED" },
|
||||
});
|
||||
await recalcShotStatus(shotId, tx);
|
||||
});
|
||||
|
||||
revalidatePath(`/projects/${shot.projectId}`);
|
||||
@@ -909,14 +931,15 @@ export async function unapproveShot(shotId: string) {
|
||||
throw new Error("Shot is not client-approved");
|
||||
}
|
||||
|
||||
const newStatus = shot.sharedWithClient ? "CLIENT_REVIEW" : "READY_FOR_CLIENT";
|
||||
|
||||
await db.shot.update({
|
||||
where: { id: shotId },
|
||||
data: {
|
||||
shotApprovalStatus: "INTERNALLY_APPROVED",
|
||||
status: newStatus,
|
||||
},
|
||||
// The derivation already encodes "CLIENT_REVIEW if still shared, else
|
||||
// READY_FOR_CLIENT" for an INTERNALLY_APPROVED shot, and additionally honours
|
||||
// any open CHANGES task.
|
||||
await db.$transaction(async (tx) => {
|
||||
await tx.shot.update({
|
||||
where: { id: shotId },
|
||||
data: { shotApprovalStatus: "INTERNALLY_APPROVED" },
|
||||
});
|
||||
await recalcShotStatus(shotId, tx);
|
||||
});
|
||||
|
||||
revalidatePath(`/projects/${shot.projectId}`);
|
||||
@@ -1217,9 +1240,12 @@ export async function assignShotGroups(
|
||||
}
|
||||
|
||||
/**
|
||||
* Internal: handle client requesting changes on a shot.
|
||||
* Resets shotApprovalStatus = PENDING, sharedWithClient = false.
|
||||
* Recalculates shot status (will become REVISIONS if tasks set to CHANGES).
|
||||
* Session-authenticated wrapper for requesting changes on a shot — a supervisor
|
||||
* or producer relaying a client note from inside the app.
|
||||
*
|
||||
* The client portal cannot use this: it runs on a review token, not a session,
|
||||
* so it calls markShotForRevisions directly from its route. Both go through that
|
||||
* one helper so the two entry points cannot drift apart again.
|
||||
*/
|
||||
export async function clientRequestShotChanges(shotId: string, taskId?: string) {
|
||||
const session = await auth();
|
||||
@@ -1234,28 +1260,7 @@ export async function clientRequestShotChanges(shotId: string, taskId?: string)
|
||||
});
|
||||
if (!shot) throw new Error("Shot not found");
|
||||
|
||||
await db.$transaction(async (tx) => {
|
||||
// Reset shot approval
|
||||
await tx.shot.update({
|
||||
where: { id: shotId },
|
||||
data: { shotApprovalStatus: "PENDING", sharedWithClient: false },
|
||||
});
|
||||
|
||||
// If a specific task is called out, mark it CHANGES; otherwise mark all non-DONE tasks
|
||||
if (taskId) {
|
||||
await tx.task.update({
|
||||
where: { id: taskId },
|
||||
data: { status: "CHANGES" },
|
||||
});
|
||||
} else {
|
||||
await tx.task.updateMany({
|
||||
where: { shotId, status: { not: "DONE" } },
|
||||
data: { status: "CHANGES" },
|
||||
});
|
||||
}
|
||||
|
||||
await recalcShotStatus(shotId, tx);
|
||||
});
|
||||
await db.$transaction((tx) => markShotForRevisions(tx, shotId, taskId));
|
||||
|
||||
revalidatePath(`/projects/${shot.projectId}`);
|
||||
revalidatePath(`/projects/${shot.projectId}/shots/${shotId}`);
|
||||
|
||||
+10
-3
@@ -4,7 +4,7 @@ import { auth } from "@/auth";
|
||||
import { db } from "@/lib/db";
|
||||
import { revalidatePath } from "next/cache";
|
||||
import { z } from "zod";
|
||||
import { recalcShotStatus } from "@/lib/shot-status";
|
||||
import { recalcShotStatus, clearStaleShotApproval } from "@/lib/shot-status";
|
||||
import { notifyNewVersionUploaded } from "@/lib/notifications";
|
||||
import { slackNotifyVersionUploaded } from "@/lib/slack";
|
||||
|
||||
@@ -50,9 +50,16 @@ export async function createVersion(data: z.infer<typeof createVersionSchema>) {
|
||||
data: { status: "INTERNAL_REVIEW" },
|
||||
});
|
||||
|
||||
// Recalculate shot status
|
||||
// Recalculate shot status — clearing any stale sign-off first, so a new
|
||||
// version does not land under a shot still reading COMPLETE.
|
||||
if (task.shot) {
|
||||
await recalcShotStatus(task.shot.id).catch(() => {});
|
||||
const shotId = task.shot.id;
|
||||
await db
|
||||
.$transaction(async (tx) => {
|
||||
await clearStaleShotApproval(tx, shotId);
|
||||
await recalcShotStatus(shotId, tx);
|
||||
})
|
||||
.catch(() => {});
|
||||
}
|
||||
|
||||
// Get the next version number for this task
|
||||
|
||||
@@ -2,7 +2,7 @@ import { NextRequest, NextResponse } from "next/server";
|
||||
import { auth } from "@/auth";
|
||||
import { db } from "@/lib/db";
|
||||
import { uploadToHetzner, deleteFromHetzner } from "@/lib/storage";
|
||||
import { recalcShotStatus } from "@/lib/shot-status";
|
||||
import { recalcShotStatus, clearStaleShotApproval } from "@/lib/shot-status";
|
||||
|
||||
export const maxDuration = 300; // 5 min — large .mov high-res files
|
||||
|
||||
@@ -194,8 +194,14 @@ export async function POST(
|
||||
data: { status: "INTERNAL_REVIEW" },
|
||||
});
|
||||
|
||||
// Recalculate the parent shot's status
|
||||
await recalcShotStatus(shotId).catch(() => {});
|
||||
// Recalculate the parent shot's status, clearing any stale sign-off first so
|
||||
// the new version does not land under a shot still reading COMPLETE.
|
||||
await db
|
||||
.$transaction(async (tx) => {
|
||||
await clearStaleShotApproval(tx, shotId);
|
||||
await recalcShotStatus(shotId, tx);
|
||||
})
|
||||
.catch(() => {});
|
||||
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
|
||||
@@ -1,21 +1,8 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { db } from "@/lib/db";
|
||||
import { ApprovalStatus } from "@prisma/client";
|
||||
import { recalcShotStatus } from "@/lib/shot-status";
|
||||
import { validateReviewToken } from "@/lib/review-auth";
|
||||
|
||||
async function getOrCreateClientUser(email: string, label?: string | null) {
|
||||
const existing = await db.user.findUnique({ where: { email } });
|
||||
if (existing) return existing;
|
||||
return db.user.create({
|
||||
data: {
|
||||
email,
|
||||
name: label ?? email.split("@")[0],
|
||||
role: "CLIENT",
|
||||
isActive: true,
|
||||
},
|
||||
});
|
||||
}
|
||||
import { recalcShotStatus, markShotForRevisions } from "@/lib/shot-status";
|
||||
import { validateReviewToken, getOrCreateReviewUser } from "@/lib/review-auth";
|
||||
|
||||
export async function POST(
|
||||
req: NextRequest,
|
||||
@@ -48,9 +35,12 @@ export async function POST(
|
||||
}
|
||||
|
||||
if (action === "APPROVE") {
|
||||
await db.shot.update({
|
||||
where: { id: shotId },
|
||||
data: { shotApprovalStatus: "CLIENT_APPROVED", status: "COMPLETE" },
|
||||
await db.$transaction(async (tx) => {
|
||||
await tx.shot.update({
|
||||
where: { id: shotId },
|
||||
data: { shotApprovalStatus: "CLIENT_APPROVED" },
|
||||
});
|
||||
await recalcShotStatus(shotId, tx);
|
||||
});
|
||||
} else if (action === "NEEDS_CHANGES") {
|
||||
// Increment shotVersion: v001 → v002, v009 → v010, etc.
|
||||
@@ -59,17 +49,41 @@ export async function POST(
|
||||
const nextNum = verMatch ? parseInt(verMatch[1], 10) + 1 : 2;
|
||||
const nextVersion = "v" + String(nextNum).padStart(3, "0");
|
||||
|
||||
const user = await getOrCreateReviewUser(session, token);
|
||||
|
||||
await db.$transaction(async (tx) => {
|
||||
await tx.shot.update({
|
||||
where: { id: shotId },
|
||||
data: { shotApprovalStatus: "PENDING", sharedWithClient: false, shotVersion: nextVersion },
|
||||
data: { shotVersion: nextVersion },
|
||||
});
|
||||
// Mark all non-DONE tasks as CHANGES
|
||||
await tx.task.updateMany({
|
||||
where: { shotId, status: { not: "DONE" } },
|
||||
data: { status: "CHANGES" },
|
||||
|
||||
// Clears the approval, unshares, marks the tasks needing rework and
|
||||
// recalculates — including the case where every task was already DONE,
|
||||
// which used to match nothing and leave the request with no effect.
|
||||
await markShotForRevisions(tx, shotId);
|
||||
|
||||
// The shot-level verdict has to land on the versions too: the dashboard
|
||||
// counters, the version badges and the client portal's own filters all
|
||||
// read Version.approvalStatus, so a shot-level change request was
|
||||
// invisible everywhere those look.
|
||||
const shown = await tx.version.findMany({
|
||||
where: { task: { shotId }, isClientVisible: true, isLatest: true },
|
||||
select: { id: true },
|
||||
});
|
||||
await recalcShotStatus(shotId, tx);
|
||||
for (const v of shown) {
|
||||
await tx.approval.create({
|
||||
data: {
|
||||
versionId: v.id,
|
||||
userId: user.id,
|
||||
status: "NEEDS_CHANGES",
|
||||
notes: notes ?? "Changes requested on the shot",
|
||||
},
|
||||
});
|
||||
await tx.version.update({
|
||||
where: { id: v.id },
|
||||
data: { approvalStatus: "NEEDS_CHANGES" },
|
||||
});
|
||||
}
|
||||
});
|
||||
} else {
|
||||
return NextResponse.json({ error: "Invalid action" }, { status: 400 });
|
||||
@@ -99,8 +113,7 @@ export async function POST(
|
||||
return NextResponse.json({ error: "Version not found" }, { status: 404 });
|
||||
}
|
||||
|
||||
const email = session.email ?? `client+${token.slice(0, 8)}@review.external`;
|
||||
const user = await getOrCreateClientUser(email, session.label);
|
||||
const user = await getOrCreateReviewUser(session, token);
|
||||
|
||||
// Record approval
|
||||
await db.approval.create({
|
||||
@@ -126,9 +139,12 @@ export async function POST(
|
||||
select: { sharedWithClient: true, shotApprovalStatus: true },
|
||||
});
|
||||
if (shot?.sharedWithClient && shot.shotApprovalStatus !== "CLIENT_APPROVED") {
|
||||
// status is left to the recalc below — writing COMPLETE here was
|
||||
// overwritten by it anyway, and disagreed with it whenever another
|
||||
// task on the shot was still on CHANGES.
|
||||
await db.shot.update({
|
||||
where: { id: version.task.shot.id },
|
||||
data: { shotApprovalStatus: "CLIENT_APPROVED", status: "COMPLETE" },
|
||||
data: { shotApprovalStatus: "CLIENT_APPROVED" },
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,127 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { db } from "@/lib/db";
|
||||
import { validateReviewToken, findReviewUser, ownsComment } from "@/lib/review-auth";
|
||||
|
||||
/**
|
||||
* Edit and delete for notes left through a client review link.
|
||||
*
|
||||
* A reviewer may only touch their own notes: the studio's comments and those of
|
||||
* any other review session are read-only here, whatever the link holder sends.
|
||||
* Ownership is the review session's guest User (lib/review-auth.ts) — the link
|
||||
* is the credential, so everyone holding it shares that identity.
|
||||
*/
|
||||
|
||||
/** Matches the internal addComment/editComment limits (actions/comments.ts). */
|
||||
const MAX_LENGTH = 5000;
|
||||
|
||||
/** The annotation companion comments written by the drawing tools. */
|
||||
const ANNOTATION_PREFIX = "✏️ Annotation at frame";
|
||||
|
||||
type Ctx = { params: Promise<{ token: string; commentId: string }> };
|
||||
|
||||
/**
|
||||
* Resolves the request to a comment the caller is allowed to change, or the
|
||||
* response explaining why not.
|
||||
*
|
||||
* "Not yours" is deliberately answered with 404 rather than 403: a link holder
|
||||
* has no business learning which comment ids exist outside their own notes.
|
||||
*/
|
||||
async function authorizeCommentEdit(req: NextRequest, ctx: Ctx) {
|
||||
const { token, commentId } = await ctx.params;
|
||||
|
||||
const result = await validateReviewToken(token, req);
|
||||
if (result.type === "requiresPassword") {
|
||||
return { error: NextResponse.json({ requiresPassword: true }, { status: 401 }) };
|
||||
}
|
||||
if (result.type === "invalid") {
|
||||
return {
|
||||
error: NextResponse.json({ error: "Invalid or expired review link" }, { status: 403 }),
|
||||
};
|
||||
}
|
||||
const session = result.session;
|
||||
|
||||
const notFound = NextResponse.json({ error: "Comment not found" }, { status: 404 });
|
||||
|
||||
const comment = await db.comment.findUnique({
|
||||
where: { id: commentId },
|
||||
select: {
|
||||
id: true,
|
||||
authorId: true,
|
||||
versionId: true,
|
||||
frameNumber: true,
|
||||
text: true,
|
||||
version: {
|
||||
select: {
|
||||
shot: { select: { projectId: true } },
|
||||
task: { select: { projectId: true } },
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
if (!comment) return { error: notFound };
|
||||
|
||||
// Same project scoping the rest of the portal applies.
|
||||
const projectId = comment.version.shot?.projectId ?? comment.version.task?.projectId;
|
||||
if (projectId !== session.projectId) return { error: notFound };
|
||||
|
||||
const user = await findReviewUser(session, token);
|
||||
if (!ownsComment(comment, user?.id)) return { error: notFound };
|
||||
|
||||
return { comment };
|
||||
}
|
||||
|
||||
/** PATCH — change the text of one's own note. */
|
||||
export async function PATCH(req: NextRequest, ctx: Ctx) {
|
||||
const authorized = await authorizeCommentEdit(req, ctx);
|
||||
if (authorized.error) return authorized.error;
|
||||
const { comment } = authorized;
|
||||
|
||||
const body = await req.json().catch(() => null);
|
||||
const text = typeof body?.text === "string" ? body.text.trim() : "";
|
||||
if (!text) {
|
||||
return NextResponse.json({ error: "Note text is required" }, { status: 400 });
|
||||
}
|
||||
if (text.length > MAX_LENGTH) {
|
||||
return NextResponse.json(
|
||||
{ error: `Note must be ${MAX_LENGTH} characters or fewer` },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
// Only the text is editable. The frame a note is pinned to is what the studio
|
||||
// works from, so moving it would silently repoint feedback someone may have
|
||||
// already actioned; a note about a different frame is a new note.
|
||||
const updated = await db.comment.update({
|
||||
where: { id: comment.id },
|
||||
data: { text },
|
||||
include: {
|
||||
author: { select: { id: true, name: true, image: true, email: true } },
|
||||
replies: {
|
||||
orderBy: { createdAt: "asc" },
|
||||
include: { author: { select: { id: true, name: true, image: true, email: true } } },
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
return NextResponse.json({ comment: { ...updated, canEdit: true } });
|
||||
}
|
||||
|
||||
/** DELETE — remove one's own note. */
|
||||
export async function DELETE(req: NextRequest, ctx: Ctx) {
|
||||
const authorized = await authorizeCommentEdit(req, ctx);
|
||||
if (authorized.error) return authorized.error;
|
||||
const { comment } = authorized;
|
||||
|
||||
await db.comment.delete({ where: { id: comment.id } });
|
||||
|
||||
// A drawing leaves a companion comment; deleting the note without the strokes
|
||||
// would leave marks on the frame that nothing explains. Mirrors deleteComment
|
||||
// in actions/comments.ts.
|
||||
if (comment.text.startsWith(ANNOTATION_PREFIX)) {
|
||||
await db.annotation.deleteMany({
|
||||
where: { versionId: comment.versionId, frameNumber: comment.frameNumber },
|
||||
});
|
||||
}
|
||||
|
||||
return NextResponse.json({ success: true });
|
||||
}
|
||||
@@ -1,21 +1,7 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { db } from "@/lib/db";
|
||||
import { slackNotifyNewFeedback } from "@/lib/slack";
|
||||
import { validateReviewToken } from "@/lib/review-auth";
|
||||
|
||||
/** Find or create a guest user for the client reviewer based on the session email */
|
||||
async function getOrCreateClientUser(email: string, label?: string | null) {
|
||||
const existing = await db.user.findUnique({ where: { email } });
|
||||
if (existing) return existing;
|
||||
return db.user.create({
|
||||
data: {
|
||||
email,
|
||||
name: label ?? email.split("@")[0],
|
||||
role: "CLIENT",
|
||||
isActive: true,
|
||||
},
|
||||
});
|
||||
}
|
||||
import { validateReviewToken, getOrCreateReviewUser } from "@/lib/review-auth";
|
||||
|
||||
export async function POST(
|
||||
req: NextRequest,
|
||||
@@ -52,8 +38,7 @@ export async function POST(
|
||||
}
|
||||
|
||||
// Resolve commenter identity
|
||||
const email = session.email ?? `client+${token.slice(0, 8)}@review.external`;
|
||||
const user = await getOrCreateClientUser(email, session.label);
|
||||
const user = await getOrCreateReviewUser(session, token);
|
||||
|
||||
const comment = await db.comment.create({
|
||||
data: {
|
||||
@@ -85,5 +70,6 @@ export async function POST(
|
||||
});
|
||||
}
|
||||
|
||||
return NextResponse.json({ comment }, { status: 201 });
|
||||
// canEdit mirrors the GET shape — a note you just wrote is always your own.
|
||||
return NextResponse.json({ comment: { ...comment, canEdit: true } }, { status: 201 });
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { db } from "@/lib/db";
|
||||
import { validateReviewToken } from "@/lib/review-auth";
|
||||
import { validateReviewToken, findReviewUser, ownsComment } from "@/lib/review-auth";
|
||||
import { clientShotCode, clientTaskTitle } from "@/lib/shot-code";
|
||||
|
||||
/** GET /api/client/[token]/versions/[versionId] — returns version + comments for client portal */
|
||||
@@ -65,7 +65,7 @@ export async function GET(
|
||||
return NextResponse.json({ error: "Version not found" }, { status: 404 });
|
||||
}
|
||||
|
||||
const comments = await db.comment.findMany({
|
||||
const commentRows = await db.comment.findMany({
|
||||
where: { versionId },
|
||||
orderBy: { frameNumber: "asc" },
|
||||
include: {
|
||||
@@ -79,6 +79,16 @@ export async function GET(
|
||||
},
|
||||
});
|
||||
|
||||
// Which notes this reviewer may edit or delete. Read-only: opening a review
|
||||
// link should not create the guest User, so a session that has never posted
|
||||
// simply owns nothing. The edit/delete route re-checks this — the flag drives
|
||||
// the UI, it does not grant anything.
|
||||
const reviewUser = await findReviewUser(session, token);
|
||||
const comments = commentRows.map((c) => ({
|
||||
...c,
|
||||
canEdit: ownsComment(c, reviewUser?.id),
|
||||
}));
|
||||
|
||||
// Resolve the shot that has the high-res file (comes from version.shot OR version.task.shot)
|
||||
const highResShot = version.shot ?? (version.task as any)?.shot ?? null;
|
||||
|
||||
|
||||
@@ -31,6 +31,8 @@ import {
|
||||
Copy,
|
||||
Check,
|
||||
Download,
|
||||
Pencil,
|
||||
Trash2,
|
||||
} from "lucide-react";
|
||||
import { useReviewStore } from "@/hooks/use-review-player";
|
||||
import { ReviewPasswordGate } from "@/components/clients/ReviewPasswordGate";
|
||||
@@ -42,6 +44,8 @@ interface Comment {
|
||||
text: string;
|
||||
isResolved: boolean;
|
||||
createdAt: string;
|
||||
/** This reviewer wrote it, so they can change or remove it. Set by the API. */
|
||||
canEdit?: boolean;
|
||||
author: { id: string; name: string | null; image: string | null; email: string };
|
||||
replies: { id: string; text: string; createdAt: string; author: { name: string | null } }[];
|
||||
}
|
||||
@@ -104,6 +108,13 @@ export default function ClientReviewPage({
|
||||
const [commentFrame, setCommentFrame] = useState<number | null>(null);
|
||||
const [submittingComment, setSubmittingComment] = useState(false);
|
||||
|
||||
// Editing / deleting one's own notes
|
||||
const [editingCommentId, setEditingCommentId] = useState<string | null>(null);
|
||||
const [editingText, setEditingText] = useState("");
|
||||
const [savingEdit, setSavingEdit] = useState(false);
|
||||
const [deletingComment, setDeletingComment] = useState<Comment | null>(null);
|
||||
const [deleting, setDeleting] = useState(false);
|
||||
|
||||
// Approval dialog
|
||||
const [approvalDialog, setApprovalDialog] = useState<{
|
||||
open: boolean;
|
||||
@@ -209,6 +220,58 @@ export default function ClientReviewPage({
|
||||
}
|
||||
};
|
||||
|
||||
const beginEditComment = (comment: Comment) => {
|
||||
setEditingCommentId(comment.id);
|
||||
setEditingText(comment.text);
|
||||
};
|
||||
|
||||
const cancelEditComment = () => {
|
||||
setEditingCommentId(null);
|
||||
setEditingText("");
|
||||
};
|
||||
|
||||
const handleSaveEditedComment = async () => {
|
||||
const trimmed = editingText.trim();
|
||||
if (!editingCommentId || !trimmed || !version) return;
|
||||
setSavingEdit(true);
|
||||
try {
|
||||
const res = await fetch(`/api/client/${token}/comment/${editingCommentId}`, {
|
||||
method: "PATCH",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ text: trimmed }),
|
||||
});
|
||||
if (!res.ok) throw new Error("Failed to save note");
|
||||
cancelEditComment();
|
||||
await refreshComments(token, version.id);
|
||||
toast({ title: "Note updated" });
|
||||
} catch {
|
||||
toast({ title: "Failed to update note", variant: "destructive" });
|
||||
} finally {
|
||||
setSavingEdit(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleDeleteComment = async () => {
|
||||
if (!deletingComment || !version) return;
|
||||
setDeleting(true);
|
||||
try {
|
||||
const res = await fetch(`/api/client/${token}/comment/${deletingComment.id}`, {
|
||||
method: "DELETE",
|
||||
});
|
||||
if (!res.ok) throw new Error("Failed to delete note");
|
||||
setDeletingComment(null);
|
||||
// Deleting a drawing note also removes its strokes server-side, and those
|
||||
// live in the canvas's own state — a full reload remounts the player so
|
||||
// the frame does not keep showing marks that no longer exist.
|
||||
loadVersion(token, version.id);
|
||||
toast({ title: "Note deleted" });
|
||||
} catch {
|
||||
toast({ title: "Failed to delete note", variant: "destructive" });
|
||||
} finally {
|
||||
setDeleting(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleDownloadHighRes = async () => {
|
||||
const shotId = version?.highResShotId ?? version?.shot?.id;
|
||||
if (!shotId || !token) return;
|
||||
@@ -510,8 +573,51 @@ export default function ClientReviewPage({
|
||||
<div className="space-y-3">
|
||||
{comments.map((comment) => (
|
||||
<div key={comment.id} className="space-y-2">
|
||||
{editingCommentId === comment.id ? (
|
||||
// Editing replaces the note in place, so it stays in the
|
||||
// list at its own frame rather than jumping to a dialog.
|
||||
<div className="rounded-lg bg-zinc-800/70 p-3 space-y-2">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-xs text-zinc-400">Editing note</span>
|
||||
<span className="ml-auto font-mono text-xs text-amber-400/80">
|
||||
{frameToTimecode(comment.frameNumber, version.fps)}
|
||||
</span>
|
||||
</div>
|
||||
<Textarea
|
||||
value={editingText}
|
||||
onChange={(e) => setEditingText(e.target.value)}
|
||||
rows={3}
|
||||
maxLength={5000}
|
||||
autoFocus
|
||||
className="bg-zinc-900 border-zinc-700 text-sm resize-none"
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === "Enter" && (e.metaKey || e.ctrlKey)) handleSaveEditedComment();
|
||||
if (e.key === "Escape") cancelEditComment();
|
||||
}}
|
||||
/>
|
||||
<div className="flex gap-2">
|
||||
<Button
|
||||
size="sm"
|
||||
className="h-7 text-xs"
|
||||
disabled={!editingText.trim() || savingEdit}
|
||||
onClick={handleSaveEditedComment}
|
||||
>
|
||||
{savingEdit ? "Saving…" : "Save"}
|
||||
</Button>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
className="h-7 text-xs"
|
||||
onClick={cancelEditComment}
|
||||
disabled={savingEdit}
|
||||
>
|
||||
Cancel
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div
|
||||
className="rounded-lg bg-zinc-800/70 p-3 space-y-2 cursor-pointer hover:bg-zinc-700/70 transition-colors"
|
||||
className="group rounded-lg bg-zinc-800/70 p-3 space-y-2 cursor-pointer hover:bg-zinc-700/70 transition-colors"
|
||||
onClick={() => playerRef.current?.seekToFrame(comment.frameNumber)}
|
||||
title={`Jump to frame ${comment.frameNumber}`}
|
||||
>
|
||||
@@ -529,7 +635,36 @@ export default function ClientReviewPage({
|
||||
</span>
|
||||
</div>
|
||||
<p className="text-sm text-zinc-200 leading-relaxed">{comment.text}</p>
|
||||
{comment.canEdit && (
|
||||
// Own notes only. The buttons stop propagation so they
|
||||
// do not also seek the player to the note's frame.
|
||||
<div className="flex items-center gap-1 pt-1 opacity-0 group-hover:opacity-100 focus-within:opacity-100 transition-opacity">
|
||||
<button
|
||||
type="button"
|
||||
className="flex items-center gap-1 rounded px-1.5 py-0.5 text-xs text-zinc-400 hover:text-white hover:bg-zinc-700"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
beginEditComment(comment);
|
||||
}}
|
||||
>
|
||||
<Pencil className="h-3 w-3" />
|
||||
Edit
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="flex items-center gap-1 rounded px-1.5 py-0.5 text-xs text-zinc-400 hover:text-red-400 hover:bg-zinc-700"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
setDeletingComment(comment);
|
||||
}}
|
||||
>
|
||||
<Trash2 className="h-3 w-3" />
|
||||
Delete
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
{comment.replies.map((reply) => (
|
||||
<div key={reply.id} className="ml-4 rounded-lg bg-zinc-800/40 border border-zinc-700/50 p-2.5">
|
||||
<span className="text-xs text-zinc-400 font-medium">
|
||||
@@ -658,6 +793,49 @@ export default function ClientReviewPage({
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
{/* Delete confirmation — a note may already have been actioned by the
|
||||
studio, so removing it is worth one deliberate step. */}
|
||||
<Dialog
|
||||
open={!!deletingComment}
|
||||
onOpenChange={(open) => { if (!open) setDeletingComment(null); }}
|
||||
>
|
||||
<DialogContent className="sm:max-w-md">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Delete this note?</DialogTitle>
|
||||
</DialogHeader>
|
||||
{deletingComment && (
|
||||
<div className="space-y-2">
|
||||
<p className="text-xs text-zinc-500 font-mono">
|
||||
Frame {deletingComment.frameNumber} ·{" "}
|
||||
{version ? frameToTimecode(deletingComment.frameNumber, version.fps) : ""}
|
||||
</p>
|
||||
<p className="rounded bg-zinc-800/70 p-3 text-sm text-zinc-200">
|
||||
{deletingComment.text}
|
||||
</p>
|
||||
<p className="text-xs text-zinc-500">
|
||||
This removes it for everyone, including the studio. It cannot be undone.
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
<DialogFooter>
|
||||
<Button
|
||||
variant="ghost"
|
||||
onClick={() => setDeletingComment(null)}
|
||||
disabled={deleting}
|
||||
>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button
|
||||
variant="destructive"
|
||||
onClick={handleDeleteComment}
|
||||
disabled={deleting}
|
||||
>
|
||||
{deleting ? "Deleting…" : "Delete note"}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -143,7 +143,8 @@ export function KanbanCard({ task, isDragOverlay = false }: KanbanCardProps) {
|
||||
</span>
|
||||
{latestVersion.approvalStatus === "APPROVED" ? (
|
||||
<CheckCircle2 className="h-3.5 w-3.5 text-emerald-500" />
|
||||
) : latestVersion.approvalStatus === "CHANGES_REQUESTED" ? (
|
||||
) : latestVersion.approvalStatus === "NEEDS_CHANGES" ||
|
||||
latestVersion.approvalStatus === "REJECTED" ? (
|
||||
<XCircle className="h-3.5 w-3.5 text-red-500" />
|
||||
) : (
|
||||
<Clock className="h-3.5 w-3.5 text-zinc-600" />
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { DELIVERY_CONFIG_DEFAULT, applyTokens, nextPackageName, tidyPath } from "./deliveries";
|
||||
|
||||
const BASE = "260901_Delivery";
|
||||
|
||||
describe("nextPackageName", () => {
|
||||
it("uses the bare base for the first package of the day", () => {
|
||||
expect(nextPackageName(BASE, [])).toBe(BASE);
|
||||
});
|
||||
|
||||
it("suffixes later packages sharing the base", () => {
|
||||
expect(nextPackageName(BASE, [BASE])).toBe(`${BASE}_02`);
|
||||
expect(nextPackageName(BASE, [BASE, `${BASE}_02`])).toBe(`${BASE}_03`);
|
||||
});
|
||||
|
||||
it("never reuses a number after a gap", () => {
|
||||
expect(nextPackageName(BASE, [BASE, `${BASE}_02`, `${BASE}_04`])).toBe(`${BASE}_05`);
|
||||
});
|
||||
|
||||
it("ignores names that only share a prefix", () => {
|
||||
expect(nextPackageName(BASE, [`${BASE}_final`, "260902_Delivery"])).toBe(BASE);
|
||||
});
|
||||
});
|
||||
|
||||
describe("delivery layout", () => {
|
||||
const tokens = {
|
||||
deliveryRoot: "//SAN/DELIVERY",
|
||||
showId: "ACME",
|
||||
episode: "101",
|
||||
packageName: BASE,
|
||||
};
|
||||
|
||||
it("separates shows so two shows' episode 101 cannot collide", () => {
|
||||
const acme = applyTokens(DELIVERY_CONFIG_DEFAULT.layout.packageDir, tokens);
|
||||
const other = applyTokens(DELIVERY_CONFIG_DEFAULT.layout.packageDir, { ...tokens, showId: "BRAVO" });
|
||||
expect(acme).toBe("//SAN/DELIVERY/ACME/101/260901_Delivery");
|
||||
expect(other).not.toBe(acme);
|
||||
});
|
||||
|
||||
it("puts producer reviews under the show too", () => {
|
||||
expect(applyTokens(DELIVERY_CONFIG_DEFAULT.layout.reviewDir, tokens)).toBe(
|
||||
"//SAN/DELIVERY/ACME/PRODUCER_REVIEWS/260901_Delivery"
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("tidyPath", () => {
|
||||
it("drops the empty segment a non-episodic show leaves behind", () => {
|
||||
const raw = applyTokens(DELIVERY_CONFIG_DEFAULT.layout.packageDir, {
|
||||
deliveryRoot: "//SAN/DELIVERY",
|
||||
showId: "ACME",
|
||||
episode: "",
|
||||
packageName: BASE,
|
||||
});
|
||||
expect(tidyPath(raw)).toBe("//SAN/DELIVERY/ACME/260901_Delivery");
|
||||
});
|
||||
|
||||
it("keeps the UNC root intact", () => {
|
||||
expect(tidyPath("//SAN/DELIVERY/ACME")).toBe("//SAN/DELIVERY/ACME");
|
||||
});
|
||||
|
||||
it("leaves a well-formed path alone", () => {
|
||||
expect(tidyPath("V:/DELIVERY/ACME/101/x")).toBe("V:/DELIVERY/ACME/101/x");
|
||||
});
|
||||
});
|
||||
@@ -46,10 +46,12 @@ export const DELIVERY_CONFIG_DEFAULT: DeliveryConfig = {
|
||||
packageNameTemplate: "{yymmdd}_Delivery",
|
||||
reviewNameTemplate: "{yyyymmdd}_Producer_review",
|
||||
layout: {
|
||||
packageDir: "{deliveryRoot}/{episode}/{packageName}",
|
||||
// {showId} is not optional in practice: without it every show's episode 101
|
||||
// lands in one folder on the delivery volume.
|
||||
packageDir: "{deliveryRoot}/{showId}/{episode}/{packageName}",
|
||||
shotDir: "{packageDir}/{shotCode}",
|
||||
reportFile: "{packageDir}/{packageName}_report.csv",
|
||||
reviewDir: "{deliveryRoot}/PRODUCER_REVIEWS/{packageName}",
|
||||
reviewDir: "{deliveryRoot}/{showId}/PRODUCER_REVIEWS/{packageName}",
|
||||
},
|
||||
deliveryRoot: "//SAN/DELIVERY",
|
||||
includeMovs: true,
|
||||
@@ -108,6 +110,36 @@ export function applyTokens(template: string, tokens: Partial<TokenValues>): str
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Collapse the empty segment an unset token leaves behind — a non-episodic
|
||||
* show resolves {episode} to "" and would otherwise build ".../SHOW//NAME".
|
||||
* The leading pair of a UNC root (//SAN/...) is preserved.
|
||||
*/
|
||||
export function tidyPath(path: string): string {
|
||||
const uncPrefix = /^\/\//.test(path) ? "//" : "";
|
||||
return uncPrefix + path.slice(uncPrefix.length).replace(/\/{2,}/g, "/").replace(/\/+$/, "");
|
||||
}
|
||||
|
||||
function escapeRegExp(value: string): string {
|
||||
return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
||||
}
|
||||
|
||||
/**
|
||||
* Second and later packages sharing a base name get `_02`, `_03`, ... Numbering
|
||||
* counts every package built under that base — cancelled and failed ones
|
||||
* included — so a number is never reused for a different folder.
|
||||
*/
|
||||
export function nextPackageName(base: string, existingNames: string[]): string {
|
||||
const pattern = new RegExp(`^${escapeRegExp(base)}(?:_(\\d+))?$`);
|
||||
let highest = 0;
|
||||
for (const name of existingNames) {
|
||||
const match = pattern.exec(name);
|
||||
if (!match) continue;
|
||||
highest = Math.max(highest, match[1] ? Number.parseInt(match[1], 10) : 1);
|
||||
}
|
||||
return highest === 0 ? base : `${base}_${String(highest + 1).padStart(2, "0")}`;
|
||||
}
|
||||
|
||||
export function dateTokens(date: Date) {
|
||||
const yyyy = String(date.getFullYear());
|
||||
const mm = String(date.getMonth() + 1).padStart(2, "0");
|
||||
@@ -280,8 +312,17 @@ export async function createDeliveryPackage(input: CreateDeliveryInput, userId:
|
||||
versionString: "",
|
||||
packageNumber: String(packageNumber),
|
||||
};
|
||||
tokens.packageName = input.options?.name ?? applyTokens(config.packageNameTemplate, tokens);
|
||||
tokens.packageDir = applyTokens(config.layout.packageDir, tokens);
|
||||
// A second delivery on the same day is normal — a retake batch, or a client
|
||||
// asking for the rest of a sequence — and the date-only template gives it a
|
||||
// name identical to the morning's. Suffix it the way MOV reviews already
|
||||
// are, so it gets its own folder instead of merging into the first one.
|
||||
const baseName = applyTokens(config.packageNameTemplate, tokens);
|
||||
const sameBase = await tx.deliveryPackage.findMany({
|
||||
where: { projectId: project.id, kind: "EXR_DELIVERY", name: { startsWith: baseName } },
|
||||
select: { name: true },
|
||||
});
|
||||
tokens.packageName = input.options?.name ?? nextPackageName(baseName, sameBase.map((p) => p.name));
|
||||
tokens.packageDir = tidyPath(applyTokens(config.layout.packageDir, tokens));
|
||||
|
||||
const pkg = await tx.deliveryPackage.create({
|
||||
data: {
|
||||
|
||||
@@ -74,9 +74,11 @@ export const renderManifestSchema = z
|
||||
timingPlate: plateRefSchema.optional(),
|
||||
plates: z.array(plateRefSchema).optional(),
|
||||
/**
|
||||
* Verbatim from the panel's start-frame resolution: "footage metadata"
|
||||
* (trustworthy) or "API timecode …" (fallback, suspect). Known at queue
|
||||
* time, so a suspect export is flagged before it burns render hours.
|
||||
* Verbatim from the panel's start-frame resolution, in the order it
|
||||
* ranks them: "EXR timecode …" (the plate's own header, best),
|
||||
* "footage metadata" (AE's read of it, trustworthy) or
|
||||
* "API timecode …" (fallback, suspect). Known at queue time, so a
|
||||
* suspect export is flagged before it burns render hours.
|
||||
*/
|
||||
startSource: z.string().optional(),
|
||||
startFrames: z.number().int().optional(),
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { nextTaskTitle } from "./preview";
|
||||
import { nextTaskTitle, carryApproval } from "./preview";
|
||||
|
||||
describe("nextTaskTitle", () => {
|
||||
it("swaps an existing version suffix", () => {
|
||||
@@ -30,3 +30,28 @@ describe("nextTaskTitle", () => {
|
||||
expect(nextTaskTitle("SHOT_cmp_TT_V12", "v013")).toBe("SHOT_cmp_TT_v013");
|
||||
});
|
||||
});
|
||||
|
||||
describe("carryApproval", () => {
|
||||
it("carries an approval forward, so a re-export does not reopen a signed-off shot", () => {
|
||||
expect(carryApproval("APPROVED")).toBe("APPROVED");
|
||||
});
|
||||
|
||||
// The regression: a render queued to address a note used to arrive already
|
||||
// wearing that note, so nothing registered that the work had been redone.
|
||||
it("resets NEEDS_CHANGES — this render is the fix for it", () => {
|
||||
expect(carryApproval("NEEDS_CHANGES")).toBe("PENDING_REVIEW");
|
||||
});
|
||||
|
||||
it("resets REJECTED for the same reason", () => {
|
||||
expect(carryApproval("REJECTED")).toBe("PENDING_REVIEW");
|
||||
});
|
||||
|
||||
it("leaves an unreviewed version pending", () => {
|
||||
expect(carryApproval("PENDING_REVIEW")).toBe("PENDING_REVIEW");
|
||||
});
|
||||
|
||||
it("defaults to pending when there is no previous version", () => {
|
||||
expect(carryApproval(null)).toBe("PENDING_REVIEW");
|
||||
expect(carryApproval(undefined)).toBe("PENDING_REVIEW");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
import { ExportStatus, Prisma } from "@prisma/client";
|
||||
import { ApprovalStatus, ExportStatus, Prisma } from "@prisma/client";
|
||||
import { db } from "@/lib/db";
|
||||
import { PipelineError } from "./errors";
|
||||
import { applyTransition } from "./transitions";
|
||||
import { getConfigNumber, getPreviewConfig } from "./config";
|
||||
import { resolveProjectTemplates, autoShotThumbnailEnabled } from "./project-templates";
|
||||
import { clientShotCode } from "@/lib/shot-code";
|
||||
import { recalcShotStatus, clearStaleShotApproval } from "@/lib/shot-status";
|
||||
import { renderOutputBase } from "./exports";
|
||||
|
||||
/** Slate date format used by the panel's getDateString (YYYY/MM/DD). */
|
||||
@@ -261,6 +262,22 @@ export async function createPreviewJob(
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* What approval a pipeline-created Version inherits from the one it supersedes.
|
||||
*
|
||||
* Only APPROVED carries. A re-export re-renders EXRs for delivery from a shot
|
||||
* that has usually already been signed off, and defaulting to PENDING_REVIEW
|
||||
* would make an approved shot silently reappear as awaiting review.
|
||||
*
|
||||
* The rejecting verdicts are the opposite case: NEEDS_CHANGES and REJECTED
|
||||
* describe the version someone asked to be fixed, and the render coming through
|
||||
* here is the fix. Carrying them forward left every re-render wearing the note
|
||||
* that prompted it, so nothing in the app registered that the work was redone.
|
||||
*/
|
||||
export function carryApproval(previous: ApprovalStatus | null | undefined): ApprovalStatus {
|
||||
return previous === "APPROVED" ? "APPROVED" : "PENDING_REVIEW";
|
||||
}
|
||||
|
||||
/**
|
||||
* `UNG_102_019_010_cmp_TT_v004` + v005 → `UNG_102_019_010_cmp_TT_v005`.
|
||||
* Mirrors `nextExrOutputBase` (exports.ts) so the task title, the EXR base and
|
||||
@@ -330,6 +347,7 @@ export async function finalizePreview(jobId: string, machineId: string, body: Fi
|
||||
|
||||
let versionId: string | null = null;
|
||||
let versionReplaced = false;
|
||||
let versionCreated = false;
|
||||
let inheritedApproval: string | null = null;
|
||||
if (artifacts.previewMovKey) {
|
||||
const mediaFields = {
|
||||
@@ -362,12 +380,6 @@ export async function finalizePreview(jobId: string, machineId: string, body: Fi
|
||||
// Version numbering stays monotonic for the task (existing review flows
|
||||
// rely on the newest version having the highest number) while matching
|
||||
// the export version whenever it is ahead.
|
||||
// A re-export does not change the picture — it re-renders EXRs for
|
||||
// delivery from a shot that has usually already been approved. A fresh
|
||||
// Version defaults to PENDING_REVIEW, which is what the dashboard, the
|
||||
// shot page and the client portal all read, so an approved shot would
|
||||
// silently reappear as awaiting review. The approval carries over from
|
||||
// the version this one supersedes.
|
||||
const previousLatest = exportRow.taskId
|
||||
? await tx.version.findFirst({
|
||||
where: { taskId: exportRow.taskId },
|
||||
@@ -375,6 +387,7 @@ export async function finalizePreview(jobId: string, machineId: string, body: Fi
|
||||
select: { approvalStatus: true, versionNumber: true },
|
||||
})
|
||||
: null;
|
||||
const carriedApproval = carryApproval(previousLatest?.approvalStatus);
|
||||
|
||||
const taskMax = exportRow.taskId
|
||||
? await tx.version.aggregate({
|
||||
@@ -395,13 +408,14 @@ export async function finalizePreview(jobId: string, machineId: string, body: Fi
|
||||
// client portal, so the pipeline stays out of it. What this version
|
||||
// is and where it came from lives on the Export and its timeline,
|
||||
// which is where someone would go looking anyway.
|
||||
approvalStatus: previousLatest?.approvalStatus ?? "PENDING_REVIEW",
|
||||
approvalStatus: carriedApproval,
|
||||
isLatest: true,
|
||||
isClientVisible: false, // never shared to the client portal (§10.0)
|
||||
},
|
||||
});
|
||||
versionId = version.id;
|
||||
inheritedApproval = previousLatest?.approvalStatus ?? null;
|
||||
versionCreated = true;
|
||||
inheritedApproval = carriedApproval;
|
||||
}
|
||||
|
||||
if (exportRow.taskId) {
|
||||
@@ -473,6 +487,40 @@ export async function finalizePreview(jobId: string, machineId: string, body: Fi
|
||||
}
|
||||
}
|
||||
|
||||
// A genuinely new version is new work awaiting review, so the task moves the
|
||||
// same way a manual upload moves it (actions/versions.ts, batch-upload) —
|
||||
// otherwise a task left on CHANGES by a review or a QC fail stays there
|
||||
// through every re-render, and the shot stays on REVISIONS with no way out
|
||||
// but a manual kanban drag.
|
||||
//
|
||||
// A *replaced* version is deliberately excluded: regeneratePreview
|
||||
// re-delivers the same version after a slate fix, and that is not a new
|
||||
// submission. Nor is an already-approved carry-over, which would drag a
|
||||
// signed-off shot back into review.
|
||||
let taskStatusMoved = false;
|
||||
let approvalCleared = false;
|
||||
if (versionCreated && exportRow.taskId && inheritedApproval !== "APPROVED") {
|
||||
const task = await tx.task.findUnique({
|
||||
where: { id: exportRow.taskId },
|
||||
select: { status: true },
|
||||
});
|
||||
if (task && task.status !== "INTERNAL_REVIEW") {
|
||||
await tx.task.update({
|
||||
where: { id: exportRow.taskId },
|
||||
data: { status: "INTERNAL_REVIEW" },
|
||||
});
|
||||
taskStatusMoved = true;
|
||||
}
|
||||
approvalCleared = await clearStaleShotApproval(tx, exportRow.shotId);
|
||||
}
|
||||
|
||||
// Shot.status is derived from task states (lib/shot-status.ts); nothing in
|
||||
// the pipeline recalculated it, so shot boards went stale the moment a
|
||||
// render changed a task.
|
||||
if (taskStatusMoved || approvalCleared) {
|
||||
await recalcShotStatus(exportRow.shotId, tx);
|
||||
}
|
||||
|
||||
const updated = await applyTransition(
|
||||
tx,
|
||||
exportRow,
|
||||
@@ -488,6 +536,7 @@ export async function finalizePreview(jobId: string, machineId: string, body: Fi
|
||||
: ` — review version created (${inheritedApproval ?? "PENDING_REVIEW"})`
|
||||
: " — no preview media reported") +
|
||||
(taskRenamed ? ` — task renamed to ${taskTitle}` : "") +
|
||||
(taskStatusMoved ? " — task moved to INTERNAL_REVIEW" : "") +
|
||||
thumbnailNote,
|
||||
},
|
||||
{
|
||||
|
||||
@@ -3,6 +3,7 @@ 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
|
||||
@@ -104,6 +105,9 @@ export async function submitQCReview(exportId: string, input: QCSubmitInput, act
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -6,7 +6,9 @@ import { getConfigNumber } from "./config";
|
||||
import {
|
||||
applyTokens,
|
||||
dateTokens,
|
||||
nextPackageName,
|
||||
resolveDeliveryConfig,
|
||||
tidyPath,
|
||||
type DeliveryConfig,
|
||||
type DeliveryManifest,
|
||||
type TokenValues,
|
||||
@@ -165,25 +167,12 @@ export async function resolveReviewCandidates(shotIds: string[]) {
|
||||
|
||||
// ── Folder naming ────────────────────────────────────────────────────────────
|
||||
|
||||
function escapeRegExp(value: string): string {
|
||||
return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
||||
}
|
||||
|
||||
/**
|
||||
* `20260828_Producer_review`, then `_02`, `_03` for further reviews the same
|
||||
* day. Numbering counts every package built under that base — cancelled and
|
||||
* failed ones included — so a number is never reused for a different folder.
|
||||
* day. EXR deliveries now number the same way, so the rule lives in
|
||||
* deliveries.ts; this name is kept because it reads better at the call site.
|
||||
*/
|
||||
export function nextReviewName(base: string, existingNames: string[]): string {
|
||||
const pattern = new RegExp(`^${escapeRegExp(base)}(?:_(\\d+))?$`);
|
||||
let highest = 0;
|
||||
for (const name of existingNames) {
|
||||
const match = pattern.exec(name);
|
||||
if (!match) continue;
|
||||
highest = Math.max(highest, match[1] ? Number.parseInt(match[1], 10) : 1);
|
||||
}
|
||||
return highest === 0 ? base : `${base}_${String(highest + 1).padStart(2, "0")}`;
|
||||
}
|
||||
export const nextReviewName = nextPackageName;
|
||||
|
||||
async function reviewNameFor(
|
||||
tx: Prisma.TransactionClient | typeof db,
|
||||
@@ -243,7 +232,7 @@ export async function previewMovReviewPackage(shotIds: string[]) {
|
||||
const tokens = reviewTokens(config, project, commonEpisode(candidates), buildDate, 0);
|
||||
const base = applyTokens(config.reviewNameTemplate, tokens);
|
||||
tokens.packageName = await reviewNameFor(db, project.id, base);
|
||||
tokens.packageDir = applyTokens(config.layout.reviewDir, tokens);
|
||||
tokens.packageDir = tidyPath(applyTokens(config.layout.reviewDir, tokens));
|
||||
|
||||
return {
|
||||
projectId: project.id,
|
||||
@@ -299,7 +288,7 @@ export async function createMovReviewPackage(input: CreateMovReviewInput, userId
|
||||
const tokens = reviewTokens(config, project, episode, buildDate, packageNumber);
|
||||
const base = applyTokens(config.reviewNameTemplate, tokens);
|
||||
tokens.packageName = input.options?.name ?? (await reviewNameFor(tx, project.id, base));
|
||||
tokens.packageDir = applyTokens(config.layout.reviewDir, tokens);
|
||||
tokens.packageDir = tidyPath(applyTokens(config.layout.reviewDir, tokens));
|
||||
|
||||
const pkg = await tx.deliveryPackage.create({
|
||||
data: {
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
import { describe, it, expect, vi } from "vitest";
|
||||
|
||||
// Mock Prisma so the pure helpers can be tested without a database.
|
||||
vi.mock("@/lib/db", () => ({ db: {} }));
|
||||
|
||||
import { reviewClientEmail, ownsComment } from "./review-auth";
|
||||
import type { ReviewSession } from "@prisma/client";
|
||||
|
||||
const session = (email: string | null): ReviewSession =>
|
||||
({ email, label: null } as ReviewSession);
|
||||
|
||||
describe("reviewClientEmail", () => {
|
||||
it("uses the session's own email when it has one", () => {
|
||||
expect(reviewClientEmail(session("dailies@client.com"), "tok123456789")).toBe(
|
||||
"dailies@client.com"
|
||||
);
|
||||
});
|
||||
|
||||
it("falls back to a token-derived address when it has none", () => {
|
||||
expect(reviewClientEmail(session(null), "tok123456789")).toBe(
|
||||
"client+tok12345@review.external"
|
||||
);
|
||||
});
|
||||
|
||||
// Identity has to be stable across requests, or a reviewer would stop owning
|
||||
// the notes they wrote a minute ago.
|
||||
it("is stable for the same token", () => {
|
||||
const a = reviewClientEmail(session(null), "tok123456789");
|
||||
const b = reviewClientEmail(session(null), "tok123456789");
|
||||
expect(a).toBe(b);
|
||||
});
|
||||
|
||||
it("separates two different review links", () => {
|
||||
expect(reviewClientEmail(session(null), "aaaaaaaaaaaa")).not.toBe(
|
||||
reviewClientEmail(session(null), "bbbbbbbbbbbb")
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("ownsComment", () => {
|
||||
it("lets a reviewer edit their own note", () => {
|
||||
expect(ownsComment({ authorId: "u1" }, "u1")).toBe(true);
|
||||
});
|
||||
|
||||
it("refuses another author's note", () => {
|
||||
expect(ownsComment({ authorId: "u2" }, "u1")).toBe(false);
|
||||
});
|
||||
|
||||
// The studio's notes reach the portal in the same list; they must stay
|
||||
// read-only there.
|
||||
it("refuses a note written by an internal user", () => {
|
||||
expect(ownsComment({ authorId: "supervisor-id" }, "client-id")).toBe(false);
|
||||
});
|
||||
|
||||
it("refuses when the reviewer has never posted, so has no identity yet", () => {
|
||||
expect(ownsComment({ authorId: "u1" }, undefined)).toBe(false);
|
||||
expect(ownsComment({ authorId: "u1" }, null)).toBe(false);
|
||||
});
|
||||
|
||||
// An authorless comment (its User row was deleted — Comment.authorId is
|
||||
// SetNull) belongs to nobody and must not become claimable.
|
||||
it("refuses an authorless note rather than letting it be claimed", () => {
|
||||
expect(ownsComment({ authorId: null }, "u1")).toBe(false);
|
||||
expect(ownsComment({ authorId: null }, null)).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -32,3 +32,62 @@ export async function validateReviewToken(
|
||||
|
||||
return { type: "ok", session };
|
||||
}
|
||||
|
||||
/**
|
||||
* The email a review session writes its activity under.
|
||||
*
|
||||
* A session with no email on it still needs a stable identity so its comments
|
||||
* group under one author and stay attributable to that link — hence the
|
||||
* token-derived fallback. Note what this means for ownership: everyone holding
|
||||
* the same review link *is* the same author. That is the intended scope, since
|
||||
* the link is the credential.
|
||||
*/
|
||||
export function reviewClientEmail(session: ReviewSession, token: string): string {
|
||||
return session.email ?? `client+${token.slice(0, 8)}@review.external`;
|
||||
}
|
||||
|
||||
/** The guest User a review session posts as, creating it on first activity. */
|
||||
export async function getOrCreateReviewUser(session: ReviewSession, token: string) {
|
||||
const email = reviewClientEmail(session, token);
|
||||
const existing = await db.user.findUnique({ where: { email } });
|
||||
if (existing) return existing;
|
||||
return db.user.create({
|
||||
data: {
|
||||
email,
|
||||
name: session.label ?? email.split("@")[0],
|
||||
role: "CLIENT",
|
||||
isActive: true,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* The guest User a review session posts as, or null if it has never posted.
|
||||
*
|
||||
* Read-only counterpart to getOrCreateReviewUser, for the paths that only need
|
||||
* to ask "is this theirs?" — merely opening a review link should not conjure a
|
||||
* User row.
|
||||
*/
|
||||
export async function findReviewUser(session: ReviewSession, token: string) {
|
||||
return db.user.findUnique({
|
||||
where: { email: reviewClientEmail(session, token) },
|
||||
select: { id: true },
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* May this review session change or remove this comment?
|
||||
*
|
||||
* Only its own. The studio's notes and those of every other review session are
|
||||
* read-only through a client link, and an authorless comment (its User was
|
||||
* deleted) belongs to nobody and so cannot be claimed.
|
||||
*
|
||||
* Shared by the listing route, which uses it to decide whether to offer the
|
||||
* controls, and the edit/delete route, which enforces it.
|
||||
*/
|
||||
export function ownsComment(
|
||||
comment: { authorId: string | null },
|
||||
reviewUserId: string | null | undefined
|
||||
): boolean {
|
||||
return !!reviewUserId && !!comment.authorId && comment.authorId === reviewUserId;
|
||||
}
|
||||
|
||||
+190
-2
@@ -3,8 +3,13 @@ import { describe, it, expect, vi } from "vitest";
|
||||
// Mock Prisma db so the pure deriveShotStatus function can be tested in isolation
|
||||
vi.mock("@/lib/db", () => ({ db: {} }));
|
||||
|
||||
import { deriveShotStatus } from "./shot-status";
|
||||
import type { TaskStatus } from "@prisma/client";
|
||||
import {
|
||||
deriveShotStatus,
|
||||
clearStaleShotApproval,
|
||||
markShotForRevisions,
|
||||
recalcShotStatus,
|
||||
} from "./shot-status";
|
||||
import type { TaskStatus, ShotApprovalStatus } from "@prisma/client";
|
||||
|
||||
// Helper to build task arrays quickly
|
||||
const tasks = (...statuses: TaskStatus[]) => statuses.map((status) => ({ status }));
|
||||
@@ -142,3 +147,186 @@ describe("deriveShotStatus", () => {
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
// ─────────────────────────────────────────────────────────────────────────────
|
||||
// Fake Prisma client — enough of the surface for the two write helpers. Each
|
||||
// call mutates the in-memory shot so the assertions read final state, not spies.
|
||||
// ─────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
type FakeTask = { id: string; status: TaskStatus };
|
||||
type FakeVersion = { id: string; taskId: string; isLatest: boolean; createdAt: Date };
|
||||
|
||||
// The helpers take a Prisma client; the fake implements just the calls they make.
|
||||
type TxArg = Parameters<typeof recalcShotStatus>[1];
|
||||
const asTx = (c: { shotState: unknown }): NonNullable<TxArg> =>
|
||||
c as unknown as NonNullable<TxArg>;
|
||||
|
||||
function fakeClient(shot: {
|
||||
id: string;
|
||||
shotApprovalStatus: ShotApprovalStatus;
|
||||
sharedWithClient: boolean;
|
||||
status?: string;
|
||||
tasks: FakeTask[];
|
||||
versions?: FakeVersion[];
|
||||
}) {
|
||||
const versions = shot.versions ?? [];
|
||||
return {
|
||||
shot: {
|
||||
findUnique: async () => shot,
|
||||
update: async ({ data }: { data: Record<string, unknown> }) => {
|
||||
Object.assign(shot, data);
|
||||
return shot;
|
||||
},
|
||||
},
|
||||
task: {
|
||||
findMany: async ({ where }: { where: { status?: { not: TaskStatus } } }) =>
|
||||
where.status?.not
|
||||
? shot.tasks.filter((t) => t.status !== where.status!.not)
|
||||
: shot.tasks,
|
||||
update: async ({ where, data }: { where: { id: string }; data: { status: TaskStatus } }) => {
|
||||
const t = shot.tasks.find((x) => x.id === where.id);
|
||||
if (t) t.status = data.status;
|
||||
return t;
|
||||
},
|
||||
updateMany: async ({
|
||||
where,
|
||||
data,
|
||||
}: {
|
||||
where: { status?: { not: TaskStatus } };
|
||||
data: { status: TaskStatus };
|
||||
}) => {
|
||||
for (const t of shot.tasks) {
|
||||
if (!where.status?.not || t.status !== where.status.not) t.status = data.status;
|
||||
}
|
||||
return { count: shot.tasks.length };
|
||||
},
|
||||
},
|
||||
version: {
|
||||
findFirst: async () =>
|
||||
[...versions].sort(
|
||||
(a, b) =>
|
||||
Number(b.isLatest) - Number(a.isLatest) ||
|
||||
b.createdAt.getTime() - a.createdAt.getTime()
|
||||
)[0] ?? null,
|
||||
},
|
||||
shotState: shot,
|
||||
};
|
||||
}
|
||||
|
||||
describe("clearStaleShotApproval", () => {
|
||||
it("clears an internal sign-off so new work is visible", async () => {
|
||||
const c = fakeClient({
|
||||
id: "s1",
|
||||
shotApprovalStatus: "INTERNALLY_APPROVED",
|
||||
sharedWithClient: false,
|
||||
tasks: [{ id: "t1", status: "INTERNAL_REVIEW" }],
|
||||
});
|
||||
expect(await clearStaleShotApproval(asTx(c), "s1")).toBe(true);
|
||||
expect(c.shotState.shotApprovalStatus).toBe("PENDING");
|
||||
});
|
||||
|
||||
it("clears a client sign-off, so an upload cannot hide under COMPLETE", async () => {
|
||||
const c = fakeClient({
|
||||
id: "s1",
|
||||
shotApprovalStatus: "CLIENT_APPROVED",
|
||||
sharedWithClient: true,
|
||||
tasks: [{ id: "t1", status: "INTERNAL_REVIEW" }],
|
||||
});
|
||||
expect(await clearStaleShotApproval(asTx(c), "s1")).toBe(true);
|
||||
expect(c.shotState.shotApprovalStatus).toBe("PENDING");
|
||||
});
|
||||
|
||||
it("is a no-op when there is no sign-off to clear", async () => {
|
||||
const c = fakeClient({
|
||||
id: "s1",
|
||||
shotApprovalStatus: "PENDING",
|
||||
sharedWithClient: false,
|
||||
tasks: [{ id: "t1", status: "IN_PROGRESS" }],
|
||||
});
|
||||
expect(await clearStaleShotApproval(asTx(c), "s1")).toBe(false);
|
||||
});
|
||||
|
||||
it("leaves sharedWithClient alone — revoking access is a separate act", async () => {
|
||||
const c = fakeClient({
|
||||
id: "s1",
|
||||
shotApprovalStatus: "CLIENT_APPROVED",
|
||||
sharedWithClient: true,
|
||||
tasks: [{ id: "t1", status: "DONE" }],
|
||||
});
|
||||
await clearStaleShotApproval(asTx(c), "s1");
|
||||
expect(c.shotState.sharedWithClient).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("markShotForRevisions", () => {
|
||||
it("marks the open tasks and lands the shot on REVISIONS", async () => {
|
||||
const c = fakeClient({
|
||||
id: "s1",
|
||||
shotApprovalStatus: "CLIENT_APPROVED",
|
||||
sharedWithClient: true,
|
||||
tasks: [
|
||||
{ id: "t1", status: "DONE" },
|
||||
{ id: "t2", status: "IN_PROGRESS" },
|
||||
],
|
||||
});
|
||||
const changed = await markShotForRevisions(asTx(c), "s1");
|
||||
expect(changed).toEqual(["t2"]);
|
||||
expect(c.shotState.tasks.find((t) => t.id === "t1")!.status).toBe("DONE");
|
||||
expect(c.shotState.tasks.find((t) => t.id === "t2")!.status).toBe("CHANGES");
|
||||
expect(c.shotState.shotApprovalStatus).toBe("PENDING");
|
||||
expect(c.shotState.sharedWithClient).toBe(false);
|
||||
expect(c.shotState.status).toBe("REVISIONS");
|
||||
});
|
||||
|
||||
// The regression this helper exists for: a shot out for client review has all
|
||||
// its tasks DONE, so the old "non-DONE" filter matched nothing and the change
|
||||
// request silently derived to INTERNAL_REVIEW instead of REVISIONS.
|
||||
it("reopens the task behind the latest version when every task is DONE", async () => {
|
||||
const c = fakeClient({
|
||||
id: "s1",
|
||||
shotApprovalStatus: "CLIENT_APPROVED",
|
||||
sharedWithClient: true,
|
||||
tasks: [
|
||||
{ id: "t1", status: "DONE" },
|
||||
{ id: "t2", status: "DONE" },
|
||||
],
|
||||
versions: [
|
||||
{ id: "v1", taskId: "t1", isLatest: false, createdAt: new Date("2026-01-01") },
|
||||
{ id: "v2", taskId: "t2", isLatest: true, createdAt: new Date("2026-02-01") },
|
||||
],
|
||||
});
|
||||
const changed = await markShotForRevisions(asTx(c), "s1");
|
||||
expect(changed).toEqual(["t2"]);
|
||||
expect(c.shotState.tasks.find((t) => t.id === "t2")!.status).toBe("CHANGES");
|
||||
expect(c.shotState.status).toBe("REVISIONS");
|
||||
});
|
||||
|
||||
it("marks only the called-out task when one is named", async () => {
|
||||
const c = fakeClient({
|
||||
id: "s1",
|
||||
shotApprovalStatus: "INTERNALLY_APPROVED",
|
||||
sharedWithClient: false,
|
||||
tasks: [
|
||||
{ id: "t1", status: "TODO" },
|
||||
{ id: "t2", status: "DONE" },
|
||||
],
|
||||
});
|
||||
const changed = await markShotForRevisions(asTx(c), "s1", "t2");
|
||||
expect(changed).toEqual(["t2"]);
|
||||
expect(c.shotState.tasks.find((t) => t.id === "t1")!.status).toBe("TODO");
|
||||
expect(c.shotState.tasks.find((t) => t.id === "t2")!.status).toBe("CHANGES");
|
||||
});
|
||||
|
||||
it("still clears the approval when a shot has no tasks to mark", async () => {
|
||||
const c = fakeClient({
|
||||
id: "s1",
|
||||
shotApprovalStatus: "CLIENT_APPROVED",
|
||||
sharedWithClient: true,
|
||||
tasks: [],
|
||||
});
|
||||
const changed = await markShotForRevisions(asTx(c), "s1");
|
||||
expect(changed).toEqual([]);
|
||||
expect(c.shotState.shotApprovalStatus).toBe("PENDING");
|
||||
expect(c.shotState.status).toBe("WAITING");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -77,3 +77,100 @@ export async function recalcShotStatus(
|
||||
data: { status: newStatus },
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* New review material arrived on a shot, so any standing sign-off is stale.
|
||||
*
|
||||
* deriveShotStatus short-circuits on shotApprovalStatus: a CLIENT_APPROVED shot
|
||||
* reads COMPLETE and an INTERNALLY_APPROVED one reads READY_FOR_CLIENT no matter
|
||||
* what its tasks say. Without this, uploading a new version onto an approved
|
||||
* shot moved the task to INTERNAL_REVIEW and changed nothing visible — the shot
|
||||
* still read as signed off while carrying work nobody had looked at.
|
||||
*
|
||||
* sharedWithClient is left alone; clearing the approval is enough to pull the
|
||||
* shot back to INTERNAL_REVIEW, and revoking client access is a separate,
|
||||
* deliberate act (unshareFromClient).
|
||||
*
|
||||
* @returns true if a stale approval was actually cleared.
|
||||
*/
|
||||
export async function clearStaleShotApproval(
|
||||
client: TxClient,
|
||||
shotId: string
|
||||
): Promise<boolean> {
|
||||
const shot = await client.shot.findUnique({
|
||||
where: { id: shotId },
|
||||
select: { shotApprovalStatus: true },
|
||||
});
|
||||
if (!shot || shot.shotApprovalStatus === "PENDING") return false;
|
||||
|
||||
await client.shot.update({
|
||||
where: { id: shotId },
|
||||
data: { shotApprovalStatus: "PENDING" },
|
||||
});
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Put a shot into revisions: clear its approval, unshare it, and mark the tasks
|
||||
* that need rework so the derivation lands on REVISIONS.
|
||||
*
|
||||
* The task selection is the subtle part. Marking every non-DONE task as CHANGES
|
||||
* matches nothing at all on the shot this is most often called for — one that is
|
||||
* out for client review precisely *because* all of its tasks are finished. That
|
||||
* left the shot deriving to INTERNAL_REVIEW and the change request with no
|
||||
* visible effect anywhere. So when nothing was picked up, the task behind the
|
||||
* shot's latest version is marked instead: that is the deliverable the reviewer
|
||||
* was actually looking at.
|
||||
*
|
||||
* @param taskId Mark only this task (a reviewer calling out one specific task).
|
||||
* @returns ids of the tasks moved to CHANGES.
|
||||
*/
|
||||
export async function markShotForRevisions(
|
||||
client: TxClient,
|
||||
shotId: string,
|
||||
taskId?: string
|
||||
): Promise<string[]> {
|
||||
await client.shot.update({
|
||||
where: { id: shotId },
|
||||
data: { shotApprovalStatus: "PENDING", sharedWithClient: false },
|
||||
});
|
||||
|
||||
let changed: string[];
|
||||
|
||||
if (taskId) {
|
||||
await client.task.update({ where: { id: taskId }, data: { status: "CHANGES" } });
|
||||
changed = [taskId];
|
||||
} else {
|
||||
const open = await client.task.findMany({
|
||||
where: { shotId, status: { not: "DONE" } },
|
||||
select: { id: true },
|
||||
});
|
||||
|
||||
if (open.length > 0) {
|
||||
await client.task.updateMany({
|
||||
where: { shotId, status: { not: "DONE" } },
|
||||
data: { status: "CHANGES" },
|
||||
});
|
||||
changed = open.map((t) => t.id);
|
||||
} else {
|
||||
// Every task is DONE — reopen the one that produced what was reviewed.
|
||||
const latest = await client.version.findFirst({
|
||||
where: { task: { shotId } },
|
||||
orderBy: [{ isLatest: "desc" }, { createdAt: "desc" }],
|
||||
select: { taskId: true },
|
||||
});
|
||||
if (latest?.taskId) {
|
||||
await client.task.update({
|
||||
where: { id: latest.taskId },
|
||||
data: { status: "CHANGES" },
|
||||
});
|
||||
changed = [latest.taskId];
|
||||
} else {
|
||||
changed = [];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
await recalcShotStatus(shotId, client);
|
||||
return changed;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user