Compare commits
4 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 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"` |
|
| 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.
|
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
|
### 12.2 Buttons and their API calls
|
||||||
|
|
||||||
|
|||||||
+273
-15
@@ -32,7 +32,7 @@ var SETTINGS_KEY = "cfg";
|
|||||||
// Bump on every change deployed to a workstation. The panel reports this to
|
// 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
|
// the server on load, so Pipeline → Machines shows which version each machine
|
||||||
// is actually running and flags the ones left behind.
|
// is actually running and flags the ones left behind.
|
||||||
var PANEL_VERSION = "2.5.0";
|
var PANEL_VERSION = "2.6.1";
|
||||||
|
|
||||||
(function VFXReviewConnector(thisObj) {
|
(function VFXReviewConnector(thisObj) {
|
||||||
var uiState = {
|
var uiState = {
|
||||||
@@ -65,7 +65,6 @@ var PANEL_VERSION = "2.5.0";
|
|||||||
|
|
||||||
var pipelineState = {
|
var pipelineState = {
|
||||||
pollShotCode: null,
|
pollShotCode: null,
|
||||||
pollTaskId: 0,
|
|
||||||
prefilledShotCode: null
|
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) {
|
function setCompStartFrame(comp, frameNumber) {
|
||||||
|
var wanted = Math.round(frameNumber);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
comp.displayStartFrame = frameNumber;
|
comp.displayStartFrame = frameNumber;
|
||||||
return;
|
if (Math.round(comp.displayStartFrame) === wanted) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
} catch (frameError) {
|
} catch (frameError) {
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
comp.displayStartTime = frameNumber / comp.frameRate;
|
comp.displayStartTime = frameNumber / comp.frameRate;
|
||||||
|
return Math.round(comp.displayStartTime * comp.frameRate) === wanted;
|
||||||
} catch (timeError) {
|
} catch (timeError) {
|
||||||
}
|
}
|
||||||
|
|
||||||
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
function deselectAllProjectItems() {
|
function deselectAllProjectItems() {
|
||||||
@@ -1051,13 +1062,220 @@ var PANEL_VERSION = "2.5.0";
|
|||||||
return frames;
|
return frames;
|
||||||
}
|
}
|
||||||
|
|
||||||
// The plate's own start timecode: AE metadata when we can read it,
|
// The first file of an imported sequence: the frame whose header carries the
|
||||||
// otherwise the API's source clip timecode less the handle frames — the
|
// plate's start timecode. importEXRSequence sorts before importing, so this
|
||||||
// same convention the Set Start Timecode button uses.
|
// 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) {
|
function getFootageStartFrames(footageItem, apiShot, fps) {
|
||||||
var probed = probeFootageStartFrames(footageItem, fps);
|
var exrTc = readExrTimecode(getFootageFirstFile(footageItem));
|
||||||
|
var probed;
|
||||||
var frames;
|
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) {
|
if (probed !== null && probed > 0) {
|
||||||
return { frames: probed, source: "footage metadata" };
|
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) {
|
function findComp(name) {
|
||||||
@@ -1914,7 +2135,9 @@ var PANEL_VERSION = "2.5.0";
|
|||||||
diagLog("start frame " + startInfo.frames + " from " + startInfo.source);
|
diagLog("start frame " + startInfo.frames + " from " + startInfo.source);
|
||||||
|
|
||||||
footageComp = app.project.items.addComp(shotCode + "_FOOTAGE", width, height, 1, maxDuration, fps);
|
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) {
|
if (precompFolder) {
|
||||||
footageComp.parentFolder = 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);
|
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) {
|
if (episodeProjectFolder) {
|
||||||
shotComp.parentFolder = episodeProjectFolder;
|
shotComp.parentFolder = episodeProjectFolder;
|
||||||
} else {
|
} 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() {
|
function stopExportPolling() {
|
||||||
if (pipelineState.pollTaskId) {
|
var taskId = getPollTaskId();
|
||||||
|
|
||||||
|
if (taskId) {
|
||||||
try {
|
try {
|
||||||
app.cancelTask(pipelineState.pollTaskId);
|
app.cancelTask(taskId);
|
||||||
} catch (cancelError) {
|
} catch (cancelError) {
|
||||||
}
|
}
|
||||||
pipelineState.pollTaskId = 0;
|
setPollTaskId(0);
|
||||||
}
|
}
|
||||||
pipelineState.pollShotCode = null;
|
pipelineState.pollShotCode = null;
|
||||||
}
|
}
|
||||||
@@ -3676,9 +3922,9 @@ var PANEL_VERSION = "2.5.0";
|
|||||||
stopExportPolling();
|
stopExportPolling();
|
||||||
pipelineState.pollShotCode = shotCode;
|
pipelineState.pollShotCode = shotCode;
|
||||||
try {
|
try {
|
||||||
pipelineState.pollTaskId = app.scheduleTask("__vfxrExportPollTick()", 15000, true);
|
setPollTaskId(app.scheduleTask("__vfxrExportPollTick()", 15000, true));
|
||||||
} catch (scheduleError) {
|
} catch (scheduleError) {
|
||||||
pipelineState.pollTaskId = 0;
|
setPollTaskId(0);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -4797,6 +5043,11 @@ var PANEL_VERSION = "2.5.0";
|
|||||||
return win;
|
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
|
// app.scheduleTask evaluates in global scope — expose the poll tick there
|
||||||
$.global.__vfxrExportPollTick = pollExportTick;
|
$.global.__vfxrExportPollTick = pollExportTick;
|
||||||
|
|
||||||
@@ -4807,6 +5058,13 @@ var PANEL_VERSION = "2.5.0";
|
|||||||
diagLog("panel v" + PANEL_VERSION + " loaded on " + getHostName());
|
diagLog("panel v" + PANEL_VERSION + " loaded on " + getHostName());
|
||||||
reportPanelVersion();
|
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) {
|
if (panel instanceof Window) {
|
||||||
panel.center();
|
panel.center();
|
||||||
panel.show();
|
panel.show();
|
||||||
|
|||||||
+25
-4
@@ -201,16 +201,37 @@ Constructs a full shot composite in the open AE project from the episode and sho
|
|||||||
**Process:**
|
**Process:**
|
||||||
1. Calls the shot lookup API to retrieve metadata (description, notes, episode, scene, etc.).
|
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.
|
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).
|
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.
|
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.
|
6. Anchors both comps on the plate's start timecode — see [Start timecode](#start-timecode).
|
||||||
7. Calls **Add Overlay** logic to attach the `UNG_VFX_OVERLAY` comp.
|
7. If a `_SHOW LUT` comp exists in the project, adds it as a collapsed layer on top.
|
||||||
8. Organises items into `__SHOTS/{episodeCode}`, `_FOOTAGE_4K`, and `_PRECOMPS` project folders.
|
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 —
|
If any step fails, the status line names the stage and a copyable report opens —
|
||||||
see [Diagnostics and logging](#diagnostics-and-logging).
|
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
|
## Render Pipeline
|
||||||
|
|||||||
+82
-72
@@ -5,7 +5,7 @@ import { db } from "@/lib/db";
|
|||||||
import { revalidatePath } from "next/cache";
|
import { revalidatePath } from "next/cache";
|
||||||
import { z } from "zod";
|
import { z } from "zod";
|
||||||
import { ApprovalStatus } from "@prisma/client";
|
import { ApprovalStatus } from "@prisma/client";
|
||||||
import { recalcShotStatus } from "@/lib/shot-status";
|
import { recalcShotStatus, clearStaleShotApproval } from "@/lib/shot-status";
|
||||||
import { notifyApprovalChange } from "@/lib/notifications";
|
import { notifyApprovalChange } from "@/lib/notifications";
|
||||||
import { slackNotifyApproval } from "@/lib/slack";
|
import { slackNotifyApproval } from "@/lib/slack";
|
||||||
import { versionLabel } from "@/lib/utils";
|
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");
|
throw new Error("Insufficient permissions to review versions");
|
||||||
}
|
}
|
||||||
|
|
||||||
// Create the approval record
|
// The verdict, the version, the task and the derived shot status are one
|
||||||
const approval = await db.approval.create({
|
// decision and are written as one: a failure partway through used to leave the
|
||||||
data: {
|
// three layers disagreeing, with no way to tell which one was right.
|
||||||
versionId: parsed.versionId,
|
const { approval, version } = await db.$transaction(async (tx) => {
|
||||||
userId: session.user.id,
|
const approval = await tx.approval.create({
|
||||||
status: parsed.status,
|
data: {
|
||||||
notes: parsed.notes,
|
versionId: parsed.versionId,
|
||||||
},
|
userId: session.user.id,
|
||||||
});
|
status: parsed.status,
|
||||||
|
notes: parsed.notes,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
// Update version approval status
|
await tx.version.update({
|
||||||
await db.version.update({
|
where: { id: parsed.versionId },
|
||||||
where: { id: parsed.versionId },
|
data: { approvalStatus: parsed.status },
|
||||||
data: { approvalStatus: parsed.status },
|
});
|
||||||
});
|
|
||||||
|
|
||||||
// Load version + task + shot + project for downstream effects
|
// Load version + task + shot + project for downstream effects
|
||||||
const version = await db.version.findUnique({
|
const version = await tx.version.findUnique({
|
||||||
where: { id: parsed.versionId },
|
where: { id: parsed.versionId },
|
||||||
include: {
|
include: {
|
||||||
task: {
|
task: {
|
||||||
include: {
|
include: {
|
||||||
shot: true,
|
shot: true,
|
||||||
project: 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
|
// Notifications
|
||||||
const reviewer = await db.user.findUnique({ where: { id: session.user.id } });
|
const reviewer = await db.user.findUnique({ where: { id: session.user.id } });
|
||||||
const reviewerName = reviewer?.name ?? "Reviewer";
|
const reviewerName = reviewer?.name ?? "Reviewer";
|
||||||
@@ -166,34 +171,39 @@ export async function unapproveVersion(versionId: string) {
|
|||||||
throw new Error("Only approved versions can be unapproved");
|
throw new Error("Only approved versions can be unapproved");
|
||||||
}
|
}
|
||||||
|
|
||||||
// Create an audit record for the unapproval
|
// One decision, one write — same reasoning as submitApproval.
|
||||||
await db.approval.create({
|
await db.$transaction(async (tx) => {
|
||||||
data: {
|
// Create an audit record for the unapproval
|
||||||
versionId,
|
await tx.approval.create({
|
||||||
userId: session.user.id,
|
data: {
|
||||||
status: "PENDING_REVIEW",
|
versionId,
|
||||||
notes: "Approval undone",
|
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" },
|
|
||||||
});
|
});
|
||||||
}
|
|
||||||
|
|
||||||
// Recalculate shot status
|
// Reset version approval status
|
||||||
if (version.task?.shot) {
|
await tx.version.update({
|
||||||
await recalcShotStatus(version.task.shot.id).catch(() => {});
|
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}`);
|
revalidatePath(`/review/${versionId}`);
|
||||||
if (version.task) {
|
if (version.task) {
|
||||||
|
|||||||
+51
-46
@@ -5,7 +5,7 @@ import { db } from "@/lib/db";
|
|||||||
import { revalidatePath } from "next/cache";
|
import { revalidatePath } from "next/cache";
|
||||||
import { z } from "zod";
|
import { z } from "zod";
|
||||||
import { ShotStatus, ShotPriority, ShotApprovalStatus, Prisma } from "@prisma/client";
|
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({
|
const createShotSchema = z.object({
|
||||||
scene: z.string().min(1).max(50).regex(/^[A-Z0-9_]+$/i, "Alphanumeric and underscore only"),
|
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 };
|
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(
|
export async function updateShotStatus(
|
||||||
shotId: string,
|
shotId: string,
|
||||||
status: ShotStatus
|
status: ShotStatus
|
||||||
@@ -737,13 +746,19 @@ export async function internallyApproveShot(shotId: string) {
|
|||||||
});
|
});
|
||||||
if (!shot) throw new Error("Shot not found");
|
if (!shot) throw new Error("Shot not found");
|
||||||
|
|
||||||
await db.shot.update({
|
// Set the approval inputs and let the derivation pick the status. Writing
|
||||||
where: { id: shotId },
|
// READY_FOR_CLIENT directly skipped the rule that an outstanding CHANGES task
|
||||||
data: {
|
// outranks any approval, so a shot could be pushed past open rework and then
|
||||||
shotApprovalStatus: "INTERNALLY_APPROVED",
|
// snap back to REVISIONS on the next unrelated recalc.
|
||||||
sharedWithClient: false,
|
await db.$transaction(async (tx) => {
|
||||||
status: "READY_FOR_CLIENT",
|
await tx.shot.update({
|
||||||
},
|
where: { id: shotId },
|
||||||
|
data: {
|
||||||
|
shotApprovalStatus: "INTERNALLY_APPROVED",
|
||||||
|
sharedWithClient: false,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
await recalcShotStatus(shotId, tx);
|
||||||
});
|
});
|
||||||
|
|
||||||
revalidatePath(`/projects/${shot.projectId}`);
|
revalidatePath(`/projects/${shot.projectId}`);
|
||||||
@@ -786,7 +801,7 @@ export async function shareWithClient(shotId: string) {
|
|||||||
// Mark shot as shared
|
// Mark shot as shared
|
||||||
await tx.shot.update({
|
await tx.shot.update({
|
||||||
where: { id: shotId },
|
where: { id: shotId },
|
||||||
data: { sharedWithClient: true, status: "CLIENT_REVIEW" },
|
data: { sharedWithClient: true },
|
||||||
});
|
});
|
||||||
|
|
||||||
// For each task, make the latest version client-visible
|
// 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}`);
|
revalidatePath(`/projects/${shot.projectId}`);
|
||||||
@@ -838,7 +855,7 @@ export async function unshareFromClient(shotId: string) {
|
|||||||
await db.$transaction(async (tx) => {
|
await db.$transaction(async (tx) => {
|
||||||
await tx.shot.update({
|
await tx.shot.update({
|
||||||
where: { id: shotId },
|
where: { id: shotId },
|
||||||
data: { sharedWithClient: false, status: "READY_FOR_CLIENT" },
|
data: { sharedWithClient: false },
|
||||||
});
|
});
|
||||||
|
|
||||||
// Hide all client-visible versions on this shot's tasks
|
// Hide all client-visible versions on this shot's tasks
|
||||||
@@ -849,6 +866,8 @@ export async function unshareFromClient(shotId: string) {
|
|||||||
data: { isClientVisible: false },
|
data: { isClientVisible: false },
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
await recalcShotStatus(shotId, tx);
|
||||||
});
|
});
|
||||||
|
|
||||||
revalidatePath(`/projects/${shot.projectId}`);
|
revalidatePath(`/projects/${shot.projectId}`);
|
||||||
@@ -877,9 +896,12 @@ export async function clientApproveShot(shotId: string) {
|
|||||||
if (!shot) throw new Error("Shot not found");
|
if (!shot) throw new Error("Shot not found");
|
||||||
if (!shot.sharedWithClient) throw new Error("Shot is not shared with client");
|
if (!shot.sharedWithClient) throw new Error("Shot is not shared with client");
|
||||||
|
|
||||||
await db.shot.update({
|
await db.$transaction(async (tx) => {
|
||||||
where: { id: shotId },
|
await tx.shot.update({
|
||||||
data: { shotApprovalStatus: "CLIENT_APPROVED", status: "COMPLETE" },
|
where: { id: shotId },
|
||||||
|
data: { shotApprovalStatus: "CLIENT_APPROVED" },
|
||||||
|
});
|
||||||
|
await recalcShotStatus(shotId, tx);
|
||||||
});
|
});
|
||||||
|
|
||||||
revalidatePath(`/projects/${shot.projectId}`);
|
revalidatePath(`/projects/${shot.projectId}`);
|
||||||
@@ -909,14 +931,15 @@ export async function unapproveShot(shotId: string) {
|
|||||||
throw new Error("Shot is not client-approved");
|
throw new Error("Shot is not client-approved");
|
||||||
}
|
}
|
||||||
|
|
||||||
const newStatus = shot.sharedWithClient ? "CLIENT_REVIEW" : "READY_FOR_CLIENT";
|
// The derivation already encodes "CLIENT_REVIEW if still shared, else
|
||||||
|
// READY_FOR_CLIENT" for an INTERNALLY_APPROVED shot, and additionally honours
|
||||||
await db.shot.update({
|
// any open CHANGES task.
|
||||||
where: { id: shotId },
|
await db.$transaction(async (tx) => {
|
||||||
data: {
|
await tx.shot.update({
|
||||||
shotApprovalStatus: "INTERNALLY_APPROVED",
|
where: { id: shotId },
|
||||||
status: newStatus,
|
data: { shotApprovalStatus: "INTERNALLY_APPROVED" },
|
||||||
},
|
});
|
||||||
|
await recalcShotStatus(shotId, tx);
|
||||||
});
|
});
|
||||||
|
|
||||||
revalidatePath(`/projects/${shot.projectId}`);
|
revalidatePath(`/projects/${shot.projectId}`);
|
||||||
@@ -1217,9 +1240,12 @@ export async function assignShotGroups(
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Internal: handle client requesting changes on a shot.
|
* Session-authenticated wrapper for requesting changes on a shot — a supervisor
|
||||||
* Resets shotApprovalStatus = PENDING, sharedWithClient = false.
|
* or producer relaying a client note from inside the app.
|
||||||
* Recalculates shot status (will become REVISIONS if tasks set to CHANGES).
|
*
|
||||||
|
* 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) {
|
export async function clientRequestShotChanges(shotId: string, taskId?: string) {
|
||||||
const session = await auth();
|
const session = await auth();
|
||||||
@@ -1234,28 +1260,7 @@ export async function clientRequestShotChanges(shotId: string, taskId?: string)
|
|||||||
});
|
});
|
||||||
if (!shot) throw new Error("Shot not found");
|
if (!shot) throw new Error("Shot not found");
|
||||||
|
|
||||||
await db.$transaction(async (tx) => {
|
await db.$transaction((tx) => markShotForRevisions(tx, shotId, taskId));
|
||||||
// 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);
|
|
||||||
});
|
|
||||||
|
|
||||||
revalidatePath(`/projects/${shot.projectId}`);
|
revalidatePath(`/projects/${shot.projectId}`);
|
||||||
revalidatePath(`/projects/${shot.projectId}/shots/${shotId}`);
|
revalidatePath(`/projects/${shot.projectId}/shots/${shotId}`);
|
||||||
|
|||||||
+10
-3
@@ -4,7 +4,7 @@ import { auth } from "@/auth";
|
|||||||
import { db } from "@/lib/db";
|
import { db } from "@/lib/db";
|
||||||
import { revalidatePath } from "next/cache";
|
import { revalidatePath } from "next/cache";
|
||||||
import { z } from "zod";
|
import { z } from "zod";
|
||||||
import { recalcShotStatus } from "@/lib/shot-status";
|
import { recalcShotStatus, clearStaleShotApproval } from "@/lib/shot-status";
|
||||||
import { notifyNewVersionUploaded } from "@/lib/notifications";
|
import { notifyNewVersionUploaded } from "@/lib/notifications";
|
||||||
import { slackNotifyVersionUploaded } from "@/lib/slack";
|
import { slackNotifyVersionUploaded } from "@/lib/slack";
|
||||||
|
|
||||||
@@ -50,9 +50,16 @@ export async function createVersion(data: z.infer<typeof createVersionSchema>) {
|
|||||||
data: { status: "INTERNAL_REVIEW" },
|
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) {
|
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
|
// Get the next version number for this task
|
||||||
|
|||||||
@@ -2,7 +2,7 @@ import { NextRequest, NextResponse } from "next/server";
|
|||||||
import { auth } from "@/auth";
|
import { auth } from "@/auth";
|
||||||
import { db } from "@/lib/db";
|
import { db } from "@/lib/db";
|
||||||
import { uploadToHetzner, deleteFromHetzner } from "@/lib/storage";
|
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
|
export const maxDuration = 300; // 5 min — large .mov high-res files
|
||||||
|
|
||||||
@@ -194,8 +194,14 @@ export async function POST(
|
|||||||
data: { status: "INTERNAL_REVIEW" },
|
data: { status: "INTERNAL_REVIEW" },
|
||||||
});
|
});
|
||||||
|
|
||||||
// Recalculate the parent shot's status
|
// Recalculate the parent shot's status, clearing any stale sign-off first so
|
||||||
await recalcShotStatus(shotId).catch(() => {});
|
// 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({
|
return NextResponse.json({
|
||||||
success: true,
|
success: true,
|
||||||
|
|||||||
@@ -1,21 +1,8 @@
|
|||||||
import { NextRequest, NextResponse } from "next/server";
|
import { NextRequest, NextResponse } from "next/server";
|
||||||
import { db } from "@/lib/db";
|
import { db } from "@/lib/db";
|
||||||
import { ApprovalStatus } from "@prisma/client";
|
import { ApprovalStatus } from "@prisma/client";
|
||||||
import { recalcShotStatus } from "@/lib/shot-status";
|
import { recalcShotStatus, markShotForRevisions } from "@/lib/shot-status";
|
||||||
import { validateReviewToken } from "@/lib/review-auth";
|
import { validateReviewToken, getOrCreateReviewUser } 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,
|
|
||||||
},
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function POST(
|
export async function POST(
|
||||||
req: NextRequest,
|
req: NextRequest,
|
||||||
@@ -48,9 +35,12 @@ export async function POST(
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (action === "APPROVE") {
|
if (action === "APPROVE") {
|
||||||
await db.shot.update({
|
await db.$transaction(async (tx) => {
|
||||||
where: { id: shotId },
|
await tx.shot.update({
|
||||||
data: { shotApprovalStatus: "CLIENT_APPROVED", status: "COMPLETE" },
|
where: { id: shotId },
|
||||||
|
data: { shotApprovalStatus: "CLIENT_APPROVED" },
|
||||||
|
});
|
||||||
|
await recalcShotStatus(shotId, tx);
|
||||||
});
|
});
|
||||||
} else if (action === "NEEDS_CHANGES") {
|
} else if (action === "NEEDS_CHANGES") {
|
||||||
// Increment shotVersion: v001 → v002, v009 → v010, etc.
|
// 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 nextNum = verMatch ? parseInt(verMatch[1], 10) + 1 : 2;
|
||||||
const nextVersion = "v" + String(nextNum).padStart(3, "0");
|
const nextVersion = "v" + String(nextNum).padStart(3, "0");
|
||||||
|
|
||||||
|
const user = await getOrCreateReviewUser(session, token);
|
||||||
|
|
||||||
await db.$transaction(async (tx) => {
|
await db.$transaction(async (tx) => {
|
||||||
await tx.shot.update({
|
await tx.shot.update({
|
||||||
where: { id: shotId },
|
where: { id: shotId },
|
||||||
data: { shotApprovalStatus: "PENDING", sharedWithClient: false, shotVersion: nextVersion },
|
data: { shotVersion: nextVersion },
|
||||||
});
|
});
|
||||||
// Mark all non-DONE tasks as CHANGES
|
|
||||||
await tx.task.updateMany({
|
// Clears the approval, unshares, marks the tasks needing rework and
|
||||||
where: { shotId, status: { not: "DONE" } },
|
// recalculates — including the case where every task was already DONE,
|
||||||
data: { status: "CHANGES" },
|
// 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 {
|
} else {
|
||||||
return NextResponse.json({ error: "Invalid action" }, { status: 400 });
|
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 });
|
return NextResponse.json({ error: "Version not found" }, { status: 404 });
|
||||||
}
|
}
|
||||||
|
|
||||||
const email = session.email ?? `client+${token.slice(0, 8)}@review.external`;
|
const user = await getOrCreateReviewUser(session, token);
|
||||||
const user = await getOrCreateClientUser(email, session.label);
|
|
||||||
|
|
||||||
// Record approval
|
// Record approval
|
||||||
await db.approval.create({
|
await db.approval.create({
|
||||||
@@ -126,9 +139,12 @@ export async function POST(
|
|||||||
select: { sharedWithClient: true, shotApprovalStatus: true },
|
select: { sharedWithClient: true, shotApprovalStatus: true },
|
||||||
});
|
});
|
||||||
if (shot?.sharedWithClient && shot.shotApprovalStatus !== "CLIENT_APPROVED") {
|
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({
|
await db.shot.update({
|
||||||
where: { id: version.task.shot.id },
|
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 { NextRequest, NextResponse } from "next/server";
|
||||||
import { db } from "@/lib/db";
|
import { db } from "@/lib/db";
|
||||||
import { slackNotifyNewFeedback } from "@/lib/slack";
|
import { slackNotifyNewFeedback } from "@/lib/slack";
|
||||||
import { validateReviewToken } from "@/lib/review-auth";
|
import { validateReviewToken, getOrCreateReviewUser } 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,
|
|
||||||
},
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function POST(
|
export async function POST(
|
||||||
req: NextRequest,
|
req: NextRequest,
|
||||||
@@ -52,8 +38,7 @@ export async function POST(
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Resolve commenter identity
|
// Resolve commenter identity
|
||||||
const email = session.email ?? `client+${token.slice(0, 8)}@review.external`;
|
const user = await getOrCreateReviewUser(session, token);
|
||||||
const user = await getOrCreateClientUser(email, session.label);
|
|
||||||
|
|
||||||
const comment = await db.comment.create({
|
const comment = await db.comment.create({
|
||||||
data: {
|
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 { NextRequest, NextResponse } from "next/server";
|
||||||
import { db } from "@/lib/db";
|
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";
|
import { clientShotCode, clientTaskTitle } from "@/lib/shot-code";
|
||||||
|
|
||||||
/** GET /api/client/[token]/versions/[versionId] — returns version + comments for client portal */
|
/** 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 });
|
return NextResponse.json({ error: "Version not found" }, { status: 404 });
|
||||||
}
|
}
|
||||||
|
|
||||||
const comments = await db.comment.findMany({
|
const commentRows = await db.comment.findMany({
|
||||||
where: { versionId },
|
where: { versionId },
|
||||||
orderBy: { frameNumber: "asc" },
|
orderBy: { frameNumber: "asc" },
|
||||||
include: {
|
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)
|
// 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;
|
const highResShot = version.shot ?? (version.task as any)?.shot ?? null;
|
||||||
|
|
||||||
|
|||||||
@@ -31,6 +31,8 @@ import {
|
|||||||
Copy,
|
Copy,
|
||||||
Check,
|
Check,
|
||||||
Download,
|
Download,
|
||||||
|
Pencil,
|
||||||
|
Trash2,
|
||||||
} from "lucide-react";
|
} from "lucide-react";
|
||||||
import { useReviewStore } from "@/hooks/use-review-player";
|
import { useReviewStore } from "@/hooks/use-review-player";
|
||||||
import { ReviewPasswordGate } from "@/components/clients/ReviewPasswordGate";
|
import { ReviewPasswordGate } from "@/components/clients/ReviewPasswordGate";
|
||||||
@@ -42,6 +44,8 @@ interface Comment {
|
|||||||
text: string;
|
text: string;
|
||||||
isResolved: boolean;
|
isResolved: boolean;
|
||||||
createdAt: string;
|
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 };
|
author: { id: string; name: string | null; image: string | null; email: string };
|
||||||
replies: { id: string; text: string; createdAt: string; author: { name: string | null } }[];
|
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 [commentFrame, setCommentFrame] = useState<number | null>(null);
|
||||||
const [submittingComment, setSubmittingComment] = useState(false);
|
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
|
// Approval dialog
|
||||||
const [approvalDialog, setApprovalDialog] = useState<{
|
const [approvalDialog, setApprovalDialog] = useState<{
|
||||||
open: boolean;
|
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 handleDownloadHighRes = async () => {
|
||||||
const shotId = version?.highResShotId ?? version?.shot?.id;
|
const shotId = version?.highResShotId ?? version?.shot?.id;
|
||||||
if (!shotId || !token) return;
|
if (!shotId || !token) return;
|
||||||
@@ -510,8 +573,51 @@ export default function ClientReviewPage({
|
|||||||
<div className="space-y-3">
|
<div className="space-y-3">
|
||||||
{comments.map((comment) => (
|
{comments.map((comment) => (
|
||||||
<div key={comment.id} className="space-y-2">
|
<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
|
<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)}
|
onClick={() => playerRef.current?.seekToFrame(comment.frameNumber)}
|
||||||
title={`Jump to frame ${comment.frameNumber}`}
|
title={`Jump to frame ${comment.frameNumber}`}
|
||||||
>
|
>
|
||||||
@@ -529,7 +635,36 @@ export default function ClientReviewPage({
|
|||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
<p className="text-sm text-zinc-200 leading-relaxed">{comment.text}</p>
|
<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>
|
</div>
|
||||||
|
)}
|
||||||
{comment.replies.map((reply) => (
|
{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">
|
<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">
|
<span className="text-xs text-zinc-400 font-medium">
|
||||||
@@ -658,6 +793,49 @@ export default function ClientReviewPage({
|
|||||||
</DialogFooter>
|
</DialogFooter>
|
||||||
</DialogContent>
|
</DialogContent>
|
||||||
</Dialog>
|
</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>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -143,7 +143,8 @@ export function KanbanCard({ task, isDragOverlay = false }: KanbanCardProps) {
|
|||||||
</span>
|
</span>
|
||||||
{latestVersion.approvalStatus === "APPROVED" ? (
|
{latestVersion.approvalStatus === "APPROVED" ? (
|
||||||
<CheckCircle2 className="h-3.5 w-3.5 text-emerald-500" />
|
<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" />
|
<XCircle className="h-3.5 w-3.5 text-red-500" />
|
||||||
) : (
|
) : (
|
||||||
<Clock className="h-3.5 w-3.5 text-zinc-600" />
|
<Clock className="h-3.5 w-3.5 text-zinc-600" />
|
||||||
|
|||||||
@@ -74,9 +74,11 @@ export const renderManifestSchema = z
|
|||||||
timingPlate: plateRefSchema.optional(),
|
timingPlate: plateRefSchema.optional(),
|
||||||
plates: z.array(plateRefSchema).optional(),
|
plates: z.array(plateRefSchema).optional(),
|
||||||
/**
|
/**
|
||||||
* Verbatim from the panel's start-frame resolution: "footage metadata"
|
* Verbatim from the panel's start-frame resolution, in the order it
|
||||||
* (trustworthy) or "API timecode …" (fallback, suspect). Known at queue
|
* ranks them: "EXR timecode …" (the plate's own header, best),
|
||||||
* time, so a suspect export is flagged before it burns render hours.
|
* "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(),
|
startSource: z.string().optional(),
|
||||||
startFrames: z.number().int().optional(),
|
startFrames: z.number().int().optional(),
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import { describe, it, expect } from "vitest";
|
import { describe, it, expect } from "vitest";
|
||||||
import { nextTaskTitle } from "./preview";
|
import { nextTaskTitle, carryApproval } from "./preview";
|
||||||
|
|
||||||
describe("nextTaskTitle", () => {
|
describe("nextTaskTitle", () => {
|
||||||
it("swaps an existing version suffix", () => {
|
it("swaps an existing version suffix", () => {
|
||||||
@@ -30,3 +30,28 @@ describe("nextTaskTitle", () => {
|
|||||||
expect(nextTaskTitle("SHOT_cmp_TT_V12", "v013")).toBe("SHOT_cmp_TT_v013");
|
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 { db } from "@/lib/db";
|
||||||
import { PipelineError } from "./errors";
|
import { PipelineError } from "./errors";
|
||||||
import { applyTransition } from "./transitions";
|
import { applyTransition } from "./transitions";
|
||||||
import { getConfigNumber, getPreviewConfig } from "./config";
|
import { getConfigNumber, getPreviewConfig } from "./config";
|
||||||
import { resolveProjectTemplates, autoShotThumbnailEnabled } from "./project-templates";
|
import { resolveProjectTemplates, autoShotThumbnailEnabled } from "./project-templates";
|
||||||
import { clientShotCode } from "@/lib/shot-code";
|
import { clientShotCode } from "@/lib/shot-code";
|
||||||
|
import { recalcShotStatus, clearStaleShotApproval } from "@/lib/shot-status";
|
||||||
import { renderOutputBase } from "./exports";
|
import { renderOutputBase } from "./exports";
|
||||||
|
|
||||||
/** Slate date format used by the panel's getDateString (YYYY/MM/DD). */
|
/** 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`.
|
* `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
|
* 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 versionId: string | null = null;
|
||||||
let versionReplaced = false;
|
let versionReplaced = false;
|
||||||
|
let versionCreated = false;
|
||||||
let inheritedApproval: string | null = null;
|
let inheritedApproval: string | null = null;
|
||||||
if (artifacts.previewMovKey) {
|
if (artifacts.previewMovKey) {
|
||||||
const mediaFields = {
|
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
|
// Version numbering stays monotonic for the task (existing review flows
|
||||||
// rely on the newest version having the highest number) while matching
|
// rely on the newest version having the highest number) while matching
|
||||||
// the export version whenever it is ahead.
|
// 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
|
const previousLatest = exportRow.taskId
|
||||||
? await tx.version.findFirst({
|
? await tx.version.findFirst({
|
||||||
where: { taskId: exportRow.taskId },
|
where: { taskId: exportRow.taskId },
|
||||||
@@ -375,6 +387,7 @@ export async function finalizePreview(jobId: string, machineId: string, body: Fi
|
|||||||
select: { approvalStatus: true, versionNumber: true },
|
select: { approvalStatus: true, versionNumber: true },
|
||||||
})
|
})
|
||||||
: null;
|
: null;
|
||||||
|
const carriedApproval = carryApproval(previousLatest?.approvalStatus);
|
||||||
|
|
||||||
const taskMax = exportRow.taskId
|
const taskMax = exportRow.taskId
|
||||||
? await tx.version.aggregate({
|
? 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
|
// 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,
|
// is and where it came from lives on the Export and its timeline,
|
||||||
// which is where someone would go looking anyway.
|
// which is where someone would go looking anyway.
|
||||||
approvalStatus: previousLatest?.approvalStatus ?? "PENDING_REVIEW",
|
approvalStatus: carriedApproval,
|
||||||
isLatest: true,
|
isLatest: true,
|
||||||
isClientVisible: false, // never shared to the client portal (§10.0)
|
isClientVisible: false, // never shared to the client portal (§10.0)
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
versionId = version.id;
|
versionId = version.id;
|
||||||
inheritedApproval = previousLatest?.approvalStatus ?? null;
|
versionCreated = true;
|
||||||
|
inheritedApproval = carriedApproval;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (exportRow.taskId) {
|
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(
|
const updated = await applyTransition(
|
||||||
tx,
|
tx,
|
||||||
exportRow,
|
exportRow,
|
||||||
@@ -488,6 +536,7 @@ export async function finalizePreview(jobId: string, machineId: string, body: Fi
|
|||||||
: ` — review version created (${inheritedApproval ?? "PENDING_REVIEW"})`
|
: ` — review version created (${inheritedApproval ?? "PENDING_REVIEW"})`
|
||||||
: " — no preview media reported") +
|
: " — no preview media reported") +
|
||||||
(taskRenamed ? ` — task renamed to ${taskTitle}` : "") +
|
(taskRenamed ? ` — task renamed to ${taskTitle}` : "") +
|
||||||
|
(taskStatusMoved ? " — task moved to INTERNAL_REVIEW" : "") +
|
||||||
thumbnailNote,
|
thumbnailNote,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ import { z } from "zod";
|
|||||||
import { db } from "@/lib/db";
|
import { db } from "@/lib/db";
|
||||||
import { PipelineError } from "./errors";
|
import { PipelineError } from "./errors";
|
||||||
import { applyTransition } from "./transitions";
|
import { applyTransition } from "./transitions";
|
||||||
|
import { recalcShotStatus } from "@/lib/shot-status";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* QC workflow (RenderPipeline2 §10) — technical/final-delivery QC on shots the
|
* 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") {
|
if (task && task.status !== "CHANGES") {
|
||||||
await tx.task.update({ where: { id: task.id }, data: { status: "CHANGES" } });
|
await tx.task.update({ where: { id: task.id }, data: { status: "CHANGES" } });
|
||||||
taskUpdated = { id: task.id, 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);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -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 };
|
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
|
// Mock Prisma db so the pure deriveShotStatus function can be tested in isolation
|
||||||
vi.mock("@/lib/db", () => ({ db: {} }));
|
vi.mock("@/lib/db", () => ({ db: {} }));
|
||||||
|
|
||||||
import { deriveShotStatus } from "./shot-status";
|
import {
|
||||||
import type { TaskStatus } from "@prisma/client";
|
deriveShotStatus,
|
||||||
|
clearStaleShotApproval,
|
||||||
|
markShotForRevisions,
|
||||||
|
recalcShotStatus,
|
||||||
|
} from "./shot-status";
|
||||||
|
import type { TaskStatus, ShotApprovalStatus } from "@prisma/client";
|
||||||
|
|
||||||
// Helper to build task arrays quickly
|
// Helper to build task arrays quickly
|
||||||
const tasks = (...statuses: TaskStatus[]) => statuses.map((status) => ({ status }));
|
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 },
|
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