Compare commits
18 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 0c4f94d56a | |||
| 40b99f3add | |||
| 33bc6a935c | |||
| 532ebd82d7 | |||
| 708e8a0d8f | |||
| 97246bcbc3 | |||
| 400cf3f6ea | |||
| 2dee1bf6fc | |||
| 469d782b4f | |||
| 6afbe82a29 | |||
| 6bfc013e35 | |||
| f6a7f0ef5a | |||
| fe420b9455 | |||
| 2a8888089f | |||
| a073f92da3 | |||
| 04e5eb123a | |||
| 75f9258b69 | |||
| 269a5cbfda |
@@ -0,0 +1,11 @@
|
||||
{
|
||||
"version": "0.0.1",
|
||||
"configurations": [
|
||||
{
|
||||
"name": "web",
|
||||
"runtimeExecutable": "npm",
|
||||
"runtimeArgs": ["run", "dev"],
|
||||
"port": 3000
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -1073,6 +1073,8 @@ Timecode is the check this engine exists for. It is validated **against the sour
|
||||
| 2 | Plate re-derived on the worker from the footage root + shot code (manifestVersion 1, or a timing plate that no longer resolves). If elements disagree, the one matching the render's frame count wins; still ambiguous → WARN, never PASS | PASS / FAIL, `reference: "derived"` |
|
||||
| 3 | API `Shot.timecodeStart` **minus `handleFrames`** | **WARN only, never PASS** — `reference: "api"`, message states the plate could not be read |
|
||||
|
||||
**Several delivered elements.** When the rank-1 timing plate does not match, the worker tries the manifest's other `plates[]` before failing — the panel's longest-duration pick is not always the element the comp was anchored to. A match against one of them is a PASS naming that element; no match still FAILs against the timing plate, listing the others tried. Only delivered footage qualifies: plates under a configured plate search root, or (with none configured) alongside the timing plate in its footage folder. `plates[]` also holds pre-renders, which agree with the render by construction and must never rescue it.
|
||||
|
||||
Rank 3 is a diagnostic, not a verification: it depends on the show's handle count being correct for that specific plate, which is exactly the assumption the defects above violate.
|
||||
|
||||
**Comparison, given the plate reference:**
|
||||
|
||||
@@ -73,6 +73,46 @@ public class BlenderProgressParserTests
|
||||
Assert.Equal(1002, frames[^1]);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Blender 5.x prefixes every line with elapsed time and a log category.
|
||||
/// Anchored on "Saved:", the parser counted no frames from a render that
|
||||
/// wrote every one, and the job failed as "saved no frames".
|
||||
/// These lines are verbatim Blender 5.2 output.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void ParsesBlender5PrefixedOutput()
|
||||
{
|
||||
Assert.Equal(@"X:\renders\frame_0001.png",
|
||||
BlenderProgressParser.ParseSaved(@"00:02.954 render | Saved: 'X:\renders\frame_0001.png'"));
|
||||
Assert.Equal(1, BlenderProgressParser.ParseFrame("00:02.469 render | Fra: 1 | Mem: 0M | Synchronizing object | Cube"));
|
||||
Assert.Null(BlenderProgressParser.ParseSaved("00:02.954 render | Time: 00:00.87 (Saving: 00:00.14)"));
|
||||
Assert.Null(BlenderProgressParser.ParseFrame("00:02.079 render | Rendering frame 1"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RecognisesBlender5Errors()
|
||||
{
|
||||
const string unwritable = @"00:03.063 reports | ERROR Render error (No such file or directory) cannot save: 'Q:\out\f_0001.png'";
|
||||
Assert.True(BlenderProgressParser.IsErrorLine(unwritable));
|
||||
Assert.True(BlenderProgressParser.IsNonRetryableError(unwritable));
|
||||
|
||||
const string missing = @"00:13.250 reports | ERROR Cannot read file ""X:\gone.blend"": No such file or directory";
|
||||
Assert.True(BlenderProgressParser.IsErrorLine(missing));
|
||||
Assert.True(BlenderProgressParser.IsNonRetryableError(missing));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Add-ons print warnings on every launch; one must never become the
|
||||
/// reported reason a render failed.
|
||||
/// </summary>
|
||||
[Theory]
|
||||
[InlineData("Warning: add-on missing 'bl_info', this can cause poor performance!: 'G:\\addons\\x\\__init__.py'")]
|
||||
[InlineData("00:01.000 addon | WARNING something harmless")]
|
||||
public void WarningsAreNotErrors(string line)
|
||||
{
|
||||
Assert.False(BlenderProgressParser.IsErrorLine(line));
|
||||
}
|
||||
|
||||
/// <summary>Mirrors BlenderRunner.PumpAsync: CR and LF both end a line.</summary>
|
||||
private static List<string> SplitLikeThePump(string text)
|
||||
{
|
||||
|
||||
@@ -70,6 +70,59 @@ public class PrepareOutputDirTests
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The version folder holds the preview MOV/MP4 built from the same
|
||||
/// basename. A shot re-rendered at the same version — the "No preview"
|
||||
/// workflow, where the EXRs are re-exported unscaled and the earlier MOV is
|
||||
/// inherited as the review media — must not have that MOV cleared out from
|
||||
/// under it before aerender starts.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void KeepsPreviewMediaSharingThePatternPrefix()
|
||||
{
|
||||
var dir = Path.Combine(Path.GetTempPath(), "vfxr-test-" + Guid.NewGuid().ToString("N"));
|
||||
Directory.CreateDirectory(dir);
|
||||
try
|
||||
{
|
||||
File.WriteAllText(Path.Combine(dir, "SHOT_cmp_TT_v004.1001.exr"), "old");
|
||||
File.WriteAllText(Path.Combine(dir, "SHOT_cmp_TT_v004.mov"), "delivery mov");
|
||||
File.WriteAllText(Path.Combine(dir, "SHOT_cmp_TT_v004.mp4"), "review mp4");
|
||||
|
||||
AerenderRunner.PrepareOutputDir(dir, "SHOT_cmp_TT_v004.[####].exr");
|
||||
|
||||
Assert.False(File.Exists(Path.Combine(dir, "SHOT_cmp_TT_v004.1001.exr")));
|
||||
Assert.True(File.Exists(Path.Combine(dir, "SHOT_cmp_TT_v004.mov")));
|
||||
Assert.True(File.Exists(Path.Combine(dir, "SHOT_cmp_TT_v004.mp4")));
|
||||
}
|
||||
finally
|
||||
{
|
||||
Directory.Delete(dir, recursive: true);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ClearsOnlyThisVersionsFrames()
|
||||
{
|
||||
var dir = Path.Combine(Path.GetTempPath(), "vfxr-test-" + Guid.NewGuid().ToString("N"));
|
||||
Directory.CreateDirectory(dir);
|
||||
try
|
||||
{
|
||||
File.WriteAllText(Path.Combine(dir, "SHOT_cmp_TT_v004.1001.exr"), "old");
|
||||
File.WriteAllText(Path.Combine(dir, "SHOT_cmp_TT_v005.1001.exr"), "other version");
|
||||
File.WriteAllText(Path.Combine(dir, "OTHERSHOT_cmp_TT_v004.1001.exr"), "other shot");
|
||||
|
||||
AerenderRunner.PrepareOutputDir(dir, "SHOT_cmp_TT_v004.[####].exr");
|
||||
|
||||
Assert.False(File.Exists(Path.Combine(dir, "SHOT_cmp_TT_v004.1001.exr")));
|
||||
Assert.True(File.Exists(Path.Combine(dir, "SHOT_cmp_TT_v005.1001.exr")));
|
||||
Assert.True(File.Exists(Path.Combine(dir, "OTHERSHOT_cmp_TT_v004.1001.exr")));
|
||||
}
|
||||
finally
|
||||
{
|
||||
Directory.Delete(dir, recursive: true);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void CreatesMissingDirectory()
|
||||
{
|
||||
|
||||
@@ -117,4 +117,21 @@ public class LogTailTests
|
||||
for (var i = 1; i <= 5; i++) tail.Add($"line {i}");
|
||||
Assert.Equal("line 3\nline 4\nline 5", tail.ToString());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ReadingWhileAnotherThreadWritesDoesNotThrow()
|
||||
{
|
||||
// The Blender runner's output pumps add lines while its progress loop
|
||||
// reads the tail; unsynchronised this threw "Collection was modified".
|
||||
var tail = new LogTail(200);
|
||||
using var stop = new CancellationTokenSource(TimeSpan.FromSeconds(1));
|
||||
var writer = Task.Run(() =>
|
||||
{
|
||||
var i = 0;
|
||||
while (!stop.IsCancellationRequested) tail.Add($"Fra:1001 Sample {i++}/128");
|
||||
});
|
||||
|
||||
while (!stop.IsCancellationRequested) _ = tail.ToString();
|
||||
await writer;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -109,6 +109,74 @@ public class ValidationStageTests : IDisposable
|
||||
Assert.Contains("8-frame handle", tc.Message);
|
||||
}
|
||||
|
||||
/// <summary>Writes a one-frame plate into a footage-style element folder.</summary>
|
||||
private string WritePlate(string element, string timecode, int fps = 24)
|
||||
{
|
||||
var plate = Path.Combine(_dir, "footage", $"UNG_107_051_010_{element}_TT_v001", $"UNG_107_051_010_{element}_TT_v001.01001.exr");
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(plate)!);
|
||||
File.Move(ExrFixture.Write(timecode, 3840, 2160, new[] { ("B", 1), ("G", 1), ("R", 1) }, fps, 4), plate);
|
||||
return plate;
|
||||
}
|
||||
|
||||
private static ManifestSource Source(string timingPlate, params string[] plates) => new()
|
||||
{
|
||||
TimingPlate = new PlateRef { Path = timingPlate, FrameStart = 1001 },
|
||||
Plates = plates.Select(p => new PlateRef { Path = p, FrameStart = 1001 }).ToList(),
|
||||
HandleFrames = 8,
|
||||
};
|
||||
|
||||
[Fact]
|
||||
public void AnotherDeliveredPlatePassesWhenTheTimingPlateDoesNot()
|
||||
{
|
||||
// The comp was anchored to FG01, but the panel named BG01 (longest) as
|
||||
// the timing plate — the two carry unrelated camera timecodes.
|
||||
WriteSequence(105, "09:12:00:00");
|
||||
var bg = WritePlate("BG01", "14:26:31:08");
|
||||
var fg = WritePlate("FG01", "09:12:00:00");
|
||||
|
||||
var manifest = Manifest(_dir, null, 1001);
|
||||
manifest.Source = Source(bg, bg, fg);
|
||||
|
||||
var tc = Check(NewStage().Run(manifest, _dir, new ServerConfig()), "timecode_plate_match");
|
||||
Assert.Equal("PASS", tc.Status);
|
||||
Assert.Contains("UNG_107_051_010_FG01_TT_v001.01001.exr", tc.Message);
|
||||
Assert.Contains("BG01", tc.Message);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void NoMatchingPlateStillFailsAgainstTheTimingPlate()
|
||||
{
|
||||
WriteSequence(105, "14:26:31:16");
|
||||
var bg = WritePlate("BG01", "14:26:31:08");
|
||||
var fg = WritePlate("FG01", "09:12:00:00");
|
||||
|
||||
var manifest = Manifest(_dir, null, 1001);
|
||||
manifest.Source = Source(bg, bg, fg);
|
||||
|
||||
var tc = Check(NewStage().Run(manifest, _dir, new ServerConfig()), "timecode_plate_match");
|
||||
Assert.Equal("FAIL", tc.Status);
|
||||
Assert.Equal("14:26:31:08", tc.Expected);
|
||||
Assert.Contains("8-frame handle", tc.Message);
|
||||
Assert.Contains("1 other delivered plate", tc.Message);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void APreRenderIsNeverUsedAsTheFallbackPlate()
|
||||
{
|
||||
// plates[] is every file in the comp. A pre-render was rendered from
|
||||
// this comp, so it agrees with the render whether or not either is right.
|
||||
WriteSequence(105, "14:26:31:16");
|
||||
var bg = WritePlate("BG01", "14:26:31:08");
|
||||
var preRender = Path.Combine(_dir, "renders", "prerender", "UNG_107_051_010_PRERENDER_01001.exr");
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(preRender)!);
|
||||
File.Move(ExrFixture.Write("14:26:31:16", 3840, 2160, new[] { ("B", 1), ("G", 1), ("R", 1) }, 24, 4), preRender);
|
||||
|
||||
var manifest = Manifest(_dir, null, 1001);
|
||||
manifest.Source = Source(bg, bg, preRender);
|
||||
|
||||
Assert.Equal("FAIL", Check(NewStage().Run(manifest, _dir, new ServerConfig()), "timecode_plate_match").Status);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void APlateAtADifferentRateFailsPlateFps()
|
||||
{
|
||||
|
||||
@@ -234,26 +234,30 @@ public sealed class AerenderRunner
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// §7.3: outputDir is created before launch; a pre-existing non-empty dir
|
||||
/// can only hold output from a previous crashed attempt of this same
|
||||
/// immutable version. Safety guard: only files matching the job's own
|
||||
/// output pattern prefix are ever deleted.
|
||||
/// §7.3: outputDir is created before launch; a pre-existing dir can hold
|
||||
/// frames from a previous crashed attempt, which aerender would otherwise
|
||||
/// leave interleaved with this attempt's. Safety guard: only files matching
|
||||
/// the job's own output pattern — its prefix *and* its extension — are ever
|
||||
/// deleted.
|
||||
///
|
||||
/// The extension is not optional. The version folder is shared with the
|
||||
/// preview stage, whose MOV and MP4 are built from the same basename
|
||||
/// (preview.ts: `{outputDir}/{base}.mov`), so prefix alone also matches
|
||||
/// them. A version folder can legitimately be rendered into twice — the
|
||||
/// output path is keyed on the shot's manually-set version, not on the
|
||||
/// export — and on a no-preview re-render (Export.skipPreview) the media
|
||||
/// that gets inherited is precisely the MOV sitting in this folder.
|
||||
/// Deleting it left the export pointing at a file that no longer existed,
|
||||
/// and delivery silently packaged the EXRs without their viewing copy.
|
||||
/// </summary>
|
||||
/// <summary>Filename prefix of an output pattern ("X.[####].exr" → "X").</summary>
|
||||
internal static string OutputPatternPrefix(string outputPattern)
|
||||
{
|
||||
var bracket = outputPattern.IndexOf('[');
|
||||
return bracket > 0 ? outputPattern[..bracket].TrimEnd('.') : Path.GetFileNameWithoutExtension(outputPattern);
|
||||
}
|
||||
|
||||
internal static void PrepareOutputDir(string outputDirLocal, string outputPattern)
|
||||
{
|
||||
Directory.CreateDirectory(outputDirLocal);
|
||||
var prefix = OutputPatternPrefix(outputPattern);
|
||||
if (string.IsNullOrEmpty(prefix)) return;
|
||||
var pattern = SequencePattern.FromOutputPattern(outputPattern);
|
||||
if (string.IsNullOrEmpty(pattern.Prefix)) return;
|
||||
foreach (var file in Directory.EnumerateFiles(outputDirLocal))
|
||||
{
|
||||
if (Path.GetFileName(file).StartsWith(prefix, StringComparison.OrdinalIgnoreCase))
|
||||
if (pattern.MatchesOutputFile(Path.GetFileName(file)))
|
||||
{
|
||||
try { File.Delete(file); } catch { /* locked leftovers surface as an aerender error */ }
|
||||
}
|
||||
@@ -276,11 +280,19 @@ public sealed class AerenderRunner
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Ring buffer of the last N output lines (§5.3 logTail).</summary>
|
||||
/// <summary>
|
||||
/// Ring buffer of the last N output lines (§5.3 logTail).
|
||||
///
|
||||
/// Thread-safe: output readers add lines while the progress loop reads the
|
||||
/// tail for its report. Unsynchronised, ToString enumerates the queue while a
|
||||
/// reader enqueues and throws "Collection was modified" — Blender, which
|
||||
/// writes a status line many times a second, hit this on every job.
|
||||
/// </summary>
|
||||
public sealed class LogTail
|
||||
{
|
||||
private readonly Queue<string> _lines;
|
||||
private readonly int _capacity;
|
||||
private readonly object _gate = new();
|
||||
|
||||
public LogTail(int capacity)
|
||||
{
|
||||
@@ -290,9 +302,15 @@ public sealed class LogTail
|
||||
|
||||
public void Add(string line)
|
||||
{
|
||||
_lines.Enqueue(line);
|
||||
while (_lines.Count > _capacity) _lines.Dequeue();
|
||||
lock (_gate)
|
||||
{
|
||||
_lines.Enqueue(line);
|
||||
while (_lines.Count > _capacity) _lines.Dequeue();
|
||||
}
|
||||
}
|
||||
|
||||
public override string ToString() => string.Join('\n', _lines);
|
||||
public override string ToString()
|
||||
{
|
||||
lock (_gate) return string.Join('\n', _lines);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,18 +8,36 @@ namespace VFXReviewWorker;
|
||||
/// with "Saved: '...'". The saved lines are the reliable signal — a frame can
|
||||
/// be reported for a long time while it renders — so progress counts those and
|
||||
/// falls back to Fra: for a first sign of life.
|
||||
///
|
||||
/// Blender 5.x logs through CLOG, which prefixes every line with an elapsed
|
||||
/// time and a category ("00:02.954 render | Saved: '...'") and
|
||||
/// reports errors as "ERROR ..." rather than "Error: ...". The prefix is
|
||||
/// stripped before matching, so both formats parse the same way.
|
||||
/// </summary>
|
||||
public static partial class BlenderProgressParser
|
||||
{
|
||||
[GeneratedRegex(@"^Fra:(\d+)", RegexOptions.Compiled)]
|
||||
[GeneratedRegex(@"^(?:\d+:)?\d{2}:\d{2}\.\d{3}\s+\S+\s*\| ?", RegexOptions.Compiled)]
|
||||
private static partial Regex LogPrefix();
|
||||
|
||||
[GeneratedRegex(@"^Fra:\s*(\d+)", RegexOptions.Compiled)]
|
||||
private static partial Regex FrameLine();
|
||||
|
||||
[GeneratedRegex(@"^Saved:\s*'(.+)'", RegexOptions.Compiled)]
|
||||
private static partial Regex SavedLine();
|
||||
|
||||
[GeneratedRegex(@"^(Error|Warning): |^Error: ", RegexOptions.Compiled | RegexOptions.IgnoreCase)]
|
||||
// Errors only. Warnings are not failures, and add-ons print them on every
|
||||
// launch ("Warning: add-on missing 'bl_info'"), so counting them made an
|
||||
// add-on's complaint the reported reason for a failed render.
|
||||
[GeneratedRegex(@"(?i:^Error: )|^(ERROR|FATAL) ", RegexOptions.Compiled)]
|
||||
private static partial Regex ErrorLine();
|
||||
|
||||
/// <summary>The line without Blender 5.x's "elapsed category | " prefix.</summary>
|
||||
private static string Message(string line)
|
||||
{
|
||||
var m = LogPrefix().Match(line);
|
||||
return m.Success ? line[m.Length..] : line;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Failures that will repeat identically on another machine — a missing
|
||||
/// file, an unknown scene, an unwritable output. Retrying these burns the
|
||||
@@ -35,7 +53,9 @@ public static partial class BlenderProgressParser
|
||||
"unknown scene",
|
||||
"scene not found",
|
||||
"unable to create directory",
|
||||
"couldn't create directory",
|
||||
"cannot write file",
|
||||
"cannot save:",
|
||||
"no camera",
|
||||
"python script fail",
|
||||
"unknown argument",
|
||||
@@ -44,18 +64,18 @@ public static partial class BlenderProgressParser
|
||||
/// <summary>The frame Blender is currently working on, or null.</summary>
|
||||
public static int? ParseFrame(string line)
|
||||
{
|
||||
var m = FrameLine().Match(line);
|
||||
var m = FrameLine().Match(Message(line));
|
||||
return m.Success && int.TryParse(m.Groups[1].Value, out var f) ? f : null;
|
||||
}
|
||||
|
||||
/// <summary>The path of a frame Blender has just written, or null.</summary>
|
||||
public static string? ParseSaved(string line)
|
||||
{
|
||||
var m = SavedLine().Match(line);
|
||||
var m = SavedLine().Match(Message(line));
|
||||
return m.Success ? m.Groups[1].Value : null;
|
||||
}
|
||||
|
||||
public static bool IsErrorLine(string line) => ErrorLine().IsMatch(line);
|
||||
public static bool IsErrorLine(string line) => ErrorLine().IsMatch(Message(line));
|
||||
|
||||
public static bool IsNonRetryableError(string line)
|
||||
{
|
||||
|
||||
@@ -190,75 +190,93 @@ public sealed class BlenderRunner
|
||||
PumpAsync(process.StandardError, line => HandleLine(line, isStderr: true)),
|
||||
};
|
||||
|
||||
while (!process.HasExited)
|
||||
try
|
||||
{
|
||||
await Task.Delay(TimeSpan.FromSeconds(2), CancellationToken.None);
|
||||
return await MonitorAsync();
|
||||
}
|
||||
catch
|
||||
{
|
||||
// Disposing a Process does not end it: without this, any exception
|
||||
// in the monitor loop leaves Blender rendering on the node,
|
||||
// unsupervised, while the job is retried alongside it.
|
||||
KillTree(process);
|
||||
throw;
|
||||
}
|
||||
|
||||
if (cancelJob.IsCancellationRequested || shutdown.IsCancellationRequested)
|
||||
async Task<RenderResult> MonitorAsync()
|
||||
{
|
||||
while (!process.HasExited)
|
||||
{
|
||||
_log.LogWarning("Cancellation requested — killing Blender tree for job {JobId}", jobId);
|
||||
KillTree(process);
|
||||
cancelledByServer = cancelJob.IsCancellationRequested;
|
||||
break;
|
||||
await Task.Delay(TimeSpan.FromSeconds(2), CancellationToken.None);
|
||||
|
||||
if (cancelJob.IsCancellationRequested || shutdown.IsCancellationRequested)
|
||||
{
|
||||
_log.LogWarning("Cancellation requested — killing Blender tree for job {JobId}", jobId);
|
||||
KillTree(process);
|
||||
cancelledByServer = cancelJob.IsCancellationRequested;
|
||||
break;
|
||||
}
|
||||
|
||||
if ((DateTimeOffset.UtcNow - lastProgressAt).TotalSeconds > config.StallTimeoutSeconds)
|
||||
{
|
||||
_log.LogError("Blender stalled ({Sec}s without output) — killing job {JobId}", config.StallTimeoutSeconds, jobId);
|
||||
KillTree(process);
|
||||
await WaitForExitSafe(process);
|
||||
return new RenderResult(false, -2, Retryable: true,
|
||||
$"Blender produced no output for {config.StallTimeoutSeconds}s (stall timeout)",
|
||||
tail.ToString(), fullLogPath, sw.Elapsed.TotalSeconds);
|
||||
}
|
||||
|
||||
if ((DateTimeOffset.UtcNow - lastReportAt).TotalSeconds >= 10)
|
||||
{
|
||||
lastReportAt = DateTimeOffset.UtcNow;
|
||||
var progress = totalFrames > 0 ? Math.Min(1.0, (double)framesSaved / totalFrames) : 0;
|
||||
var resp = await _api.ProgressAsync(jobId, machineId, progress, currentFrame, totalFrames,
|
||||
eta.EstimateSeconds(totalFrames - framesSaved), tail.ToString(), shutdown);
|
||||
if (resp?.CancelRequested == true)
|
||||
{
|
||||
_log.LogWarning("Server requested cancel for job {JobId}", jobId);
|
||||
KillTree(process);
|
||||
cancelledByServer = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if ((DateTimeOffset.UtcNow - lastProgressAt).TotalSeconds > config.StallTimeoutSeconds)
|
||||
await WaitForExitSafe(process);
|
||||
// Let the readers drain what is still buffered before judging the run —
|
||||
// the last frame's "Saved:" often arrives after the process exits.
|
||||
try { await Task.WhenAll(pumps).WaitAsync(TimeSpan.FromSeconds(10)); } catch { }
|
||||
sw.Stop();
|
||||
lock (logLock) { fullLog.Flush(); }
|
||||
|
||||
if (cancelledByServer)
|
||||
{
|
||||
_log.LogError("Blender stalled ({Sec}s without output) — killing job {JobId}", config.StallTimeoutSeconds, jobId);
|
||||
KillTree(process);
|
||||
await WaitForExitSafe(process);
|
||||
return new RenderResult(false, -2, Retryable: true,
|
||||
$"Blender produced no output for {config.StallTimeoutSeconds}s (stall timeout)",
|
||||
return new RenderResult(false, -3, Retryable: false, "Cancelled", tail.ToString(), fullLogPath, sw.Elapsed.TotalSeconds);
|
||||
}
|
||||
|
||||
var exitCode = process.ExitCode;
|
||||
if (exitCode != 0)
|
||||
{
|
||||
return new RenderResult(false, exitCode, Retryable: !nonRetryable,
|
||||
firstError ?? $"Blender exited with code {exitCode}",
|
||||
tail.ToString(), fullLogPath, sw.Elapsed.TotalSeconds);
|
||||
}
|
||||
|
||||
if ((DateTimeOffset.UtcNow - lastReportAt).TotalSeconds >= 10)
|
||||
// Blender exits 0 having rendered nothing if the range is empty or the
|
||||
// output path is unwritable, so a silent success is treated as failure.
|
||||
if (framesSaved == 0)
|
||||
{
|
||||
lastReportAt = DateTimeOffset.UtcNow;
|
||||
var progress = totalFrames > 0 ? Math.Min(1.0, (double)framesSaved / totalFrames) : 0;
|
||||
var resp = await _api.ProgressAsync(jobId, machineId, progress, currentFrame, totalFrames,
|
||||
eta.EstimateSeconds(totalFrames - framesSaved), tail.ToString(), shutdown);
|
||||
if (resp?.CancelRequested == true)
|
||||
{
|
||||
_log.LogWarning("Server requested cancel for job {JobId}", jobId);
|
||||
KillTree(process);
|
||||
cancelledByServer = true;
|
||||
break;
|
||||
}
|
||||
return new RenderResult(false, 0, Retryable: false,
|
||||
firstError is not null
|
||||
? $"Blender exited cleanly but saved no frames: {firstError}"
|
||||
: "Blender exited cleanly but saved no frames — check the output path and frame range in the .blend",
|
||||
tail.ToString(), fullLogPath, sw.Elapsed.TotalSeconds);
|
||||
}
|
||||
|
||||
_log.LogInformation("Job {JobId}: {Saved}/{Total} frames in {Sec:F0}s", jobId, framesSaved, totalFrames, sw.Elapsed.TotalSeconds);
|
||||
return new RenderResult(true, 0, true, null, tail.ToString(), fullLogPath, sw.Elapsed.TotalSeconds);
|
||||
}
|
||||
|
||||
await WaitForExitSafe(process);
|
||||
// Let the readers drain what is still buffered before judging the run —
|
||||
// the last frame's "Saved:" often arrives after the process exits.
|
||||
try { await Task.WhenAll(pumps).WaitAsync(TimeSpan.FromSeconds(10)); } catch { }
|
||||
sw.Stop();
|
||||
lock (logLock) { fullLog.Flush(); }
|
||||
|
||||
if (cancelledByServer)
|
||||
{
|
||||
return new RenderResult(false, -3, Retryable: false, "Cancelled", tail.ToString(), fullLogPath, sw.Elapsed.TotalSeconds);
|
||||
}
|
||||
|
||||
var exitCode = process.ExitCode;
|
||||
if (exitCode != 0)
|
||||
{
|
||||
return new RenderResult(false, exitCode, Retryable: !nonRetryable,
|
||||
firstError ?? $"Blender exited with code {exitCode}",
|
||||
tail.ToString(), fullLogPath, sw.Elapsed.TotalSeconds);
|
||||
}
|
||||
|
||||
// Blender exits 0 having rendered nothing if the range is empty or the
|
||||
// output path is unwritable, so a silent success is treated as failure.
|
||||
if (framesSaved == 0)
|
||||
{
|
||||
return new RenderResult(false, 0, Retryable: false,
|
||||
"Blender exited cleanly but saved no frames — check the output path and frame range in the .blend",
|
||||
tail.ToString(), fullLogPath, sw.Elapsed.TotalSeconds);
|
||||
}
|
||||
|
||||
_log.LogInformation("Job {JobId}: {Saved}/{Total} frames in {Sec:F0}s", jobId, framesSaved, totalFrames, sw.Elapsed.TotalSeconds);
|
||||
return new RenderResult(true, 0, true, null, tail.ToString(), fullLogPath, sw.Elapsed.TotalSeconds);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
@@ -76,12 +76,15 @@ public sealed class JobExecutor
|
||||
{
|
||||
long totalBytes = 0;
|
||||
int fileCount = 0;
|
||||
var prefix = AerenderRunner.OutputPatternPrefix(manifest.OutputPattern);
|
||||
// Prefix and extension both: the preview MOV/MP4 for this
|
||||
// version share the basename and live in this same folder, and
|
||||
// counting them as frames would inflate the EXR stats.
|
||||
var pattern = SequencePattern.FromOutputPattern(manifest.OutputPattern);
|
||||
try
|
||||
{
|
||||
foreach (var f in Directory.EnumerateFiles(outputDirLocal))
|
||||
{
|
||||
if (!Path.GetFileName(f).StartsWith(prefix, StringComparison.OrdinalIgnoreCase)) continue;
|
||||
if (!pattern.MatchesOutputFile(Path.GetFileName(f))) continue;
|
||||
fileCount++;
|
||||
totalBytes += new FileInfo(f).Length;
|
||||
}
|
||||
@@ -94,8 +97,8 @@ public sealed class JobExecutor
|
||||
// range, template mismatch, silently swallowed error).
|
||||
// Until Phase 3 validation exists, an empty output dir must
|
||||
// never become READY_FOR_QC.
|
||||
_log.LogError("Job {JobId}: aerender exited 0 but no \"{Prefix}*\" files exist in {Dir} — reporting failure",
|
||||
job.Id, prefix, outputDirLocal);
|
||||
_log.LogError("Job {JobId}: aerender exited 0 but no \"{Prefix}*{Ext}\" files exist in {Dir} — reporting failure",
|
||||
job.Id, pattern.Prefix, pattern.Extension, outputDirLocal);
|
||||
_spooler.Enqueue("fail", job.Id, new Dictionary<string, object?>
|
||||
{
|
||||
["machineId"] = machineId,
|
||||
|
||||
@@ -15,7 +15,7 @@
|
||||
every change that gets published. publish.ps1 appends the git SHA via
|
||||
SourceRevisionId, giving "1.1.0+feb1c7b".
|
||||
-->
|
||||
<Version>1.6.0</Version>
|
||||
<Version>1.6.3</Version>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
|
||||
@@ -350,6 +350,31 @@ public sealed class ValidationStage
|
||||
return;
|
||||
}
|
||||
|
||||
var deltaOf = (TimecodeReference r) =>
|
||||
renderTc.ToFrames(fps) - (r.PlateTimecode.ToFrames(fps) + (renderFirstFrame - r.PlateFirstFrame));
|
||||
|
||||
// A shot with several delivered elements: the panel names the longest
|
||||
// as the timing plate, but the comp may have been anchored to another
|
||||
// (BG01 and FG01 carry unrelated camera timecodes). When the timing
|
||||
// plate disagrees, the manifest's other delivered plates are tried
|
||||
// before failing. The comparison is unchanged — it is still a plate, so
|
||||
// a match is a real PASS and no match still FAILs against the timing plate.
|
||||
var timingPlate = reference;
|
||||
var alternatesTried = new List<object>();
|
||||
if (reference.Kind == "manifest" && deltaOf(reference) != 0)
|
||||
{
|
||||
foreach (var alternate in ResolveAlternatePlates(m, renderFirstFrame, reference))
|
||||
{
|
||||
var altDelta = deltaOf(alternate);
|
||||
alternatesTried.Add(new { platePath = alternate.PlatePath, plateTimecode = alternate.PlateTimecode.ToString(), deltaFrames = altDelta });
|
||||
if (altDelta == 0)
|
||||
{
|
||||
reference = alternate;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// plate_fps — the render's rate against the plate's own.
|
||||
//
|
||||
// timecode_fps only compares the render to the manifest, and both come
|
||||
@@ -377,8 +402,8 @@ public sealed class ValidationStage
|
||||
|
||||
var expectedFrames = reference.PlateTimecode.ToFrames(fps) + (renderFirstFrame - reference.PlateFirstFrame);
|
||||
var expected = Timecode.FromFrames(expectedFrames, fps);
|
||||
var actualFrames = renderTc.ToFrames(fps);
|
||||
var deltaFrames = actualFrames - expectedFrames;
|
||||
var deltaFrames = deltaOf(reference);
|
||||
var matchedAlternate = !ReferenceEquals(reference, timingPlate);
|
||||
var details = new
|
||||
{
|
||||
reference = reference.Kind,
|
||||
@@ -387,10 +412,14 @@ public sealed class ValidationStage
|
||||
plateFirstFrame = reference.PlateFirstFrame,
|
||||
renderFirstFrame,
|
||||
deltaFrames,
|
||||
timingPlatePath = timingPlate.PlatePath,
|
||||
matchedAlternate,
|
||||
alternatesTried,
|
||||
};
|
||||
|
||||
if (deltaFrames == 0)
|
||||
{
|
||||
var timingDelta = deltaOf(timingPlate);
|
||||
// The API fallback proves nothing on its own (§8.1a): it is the
|
||||
// editorial in-point minus a handle count that may not be this
|
||||
// plate's, so a match is reported as a WARN, never a PASS.
|
||||
@@ -398,7 +427,11 @@ public sealed class ValidationStage
|
||||
? ValidationCheck.Warn("timecode_plate_match", expected.ToString(), renderTc.ToString(),
|
||||
"Matches the API timecode less handles, but the plate itself could not be read — unverified.", details)
|
||||
: ValidationCheck.Pass("timecode_plate_match", expected.ToString(), renderTc.ToString(),
|
||||
$"Matches {reference.Kind} plate {Path.GetFileName(reference.PlatePath ?? "")}", details));
|
||||
$"Matches {reference.Kind} plate {Path.GetFileName(reference.PlatePath ?? "")}" +
|
||||
(matchedAlternate
|
||||
? $" (the timing plate {Path.GetFileName(timingPlate.PlatePath ?? "")} is {(timingDelta > 0 ? "+" : "")}{timingDelta} frames off — the comp was anchored to this element instead)"
|
||||
: ""),
|
||||
details));
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -409,7 +442,10 @@ public sealed class ValidationStage
|
||||
? $"That is exactly the {reference.HandleFrames}-frame handle: the comp was anchored to the editorial in-point instead of the plate's first frame."
|
||||
: renderTc.Hours == 0 && renderTc.Minutes == 0
|
||||
? "A near-zero timecode means the comp had no source timecode at all and AE derived it from the frame number."
|
||||
: "");
|
||||
: "") +
|
||||
(alternatesTried.Count > 0
|
||||
? $" Also checked {alternatesTried.Count} other delivered plate{(alternatesTried.Count == 1 ? "" : "s")} in the manifest: none match."
|
||||
: "");
|
||||
|
||||
checks.Add(reference.Kind == "api"
|
||||
? ValidationCheck.Warn("timecode_plate_match", expected.ToString(), renderTc.ToString(),
|
||||
@@ -430,20 +466,9 @@ public sealed class ValidationStage
|
||||
var timing = m.Source?.TimingPlate;
|
||||
if (timing is not null && !string.IsNullOrWhiteSpace(timing.Path))
|
||||
{
|
||||
var local = mapper.Map(timing.Path);
|
||||
var header = File.Exists(local) ? ExrHeader.TryRead(local) : null;
|
||||
if (header?.Timecode is not null)
|
||||
{
|
||||
// The plate's own file numbering, never the comp's frame range:
|
||||
// the render's first frame is in output numbering, so anchoring
|
||||
// on a comp frame skews the comparison by the gap between them.
|
||||
var frame = SequencePattern.FrameFromName(Path.GetFileName(local))
|
||||
?? timing.FrameStart
|
||||
?? renderFirstFrame;
|
||||
return new TimecodeReference("manifest", local, header.Timecode.Value, frame, handleFrames,
|
||||
header.FramesPerSecond);
|
||||
}
|
||||
_log.LogWarning("Timing plate from manifest is unreadable: {Path}", local);
|
||||
var manifestPlate = ReadManifestPlate(timing, mapper, handleFrames, renderFirstFrame);
|
||||
if (manifestPlate is not null) return manifestPlate;
|
||||
_log.LogWarning("Timing plate from manifest is unreadable: {Path}", mapper.Map(timing.Path));
|
||||
}
|
||||
|
||||
// Rank 2 — derive the plate from a configured search root.
|
||||
@@ -469,6 +494,63 @@ public sealed class ValidationStage
|
||||
return null;
|
||||
}
|
||||
|
||||
private static TimecodeReference? ReadManifestPlate(PlateRef plate, PathMapper mapper, int handleFrames, int renderFirstFrame)
|
||||
{
|
||||
var local = mapper.Map(plate.Path);
|
||||
var header = File.Exists(local) ? ExrHeader.TryRead(local) : null;
|
||||
if (header?.Timecode is null) return null;
|
||||
|
||||
// The plate's own file numbering, never the comp's frame range: the
|
||||
// render's first frame is in output numbering, so anchoring on a comp
|
||||
// frame skews the comparison by the gap between them.
|
||||
var frame = SequencePattern.FrameFromName(Path.GetFileName(local))
|
||||
?? plate.FrameStart
|
||||
?? renderFirstFrame;
|
||||
return new TimecodeReference("manifest", local, header.Timecode.Value, frame, handleFrames,
|
||||
header.FramesPerSecond);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The manifest's other delivered plates, tried when the timing plate does
|
||||
/// not match. Only real footage qualifies — under a configured plate search
|
||||
/// root or, with none configured, alongside the timing plate in its footage
|
||||
/// folder — because plates[] is every file in the comp, and a pre-render
|
||||
/// agrees with the render whether or not either is right.
|
||||
/// </summary>
|
||||
private IEnumerable<TimecodeReference> ResolveAlternatePlates(RenderManifest m, int renderFirstFrame, TimecodeReference timingPlate)
|
||||
{
|
||||
var plates = m.Source?.Plates;
|
||||
if (plates is null || plates.Count == 0 || timingPlate.PlatePath is null) yield break;
|
||||
|
||||
var mapper = new PathMapper(_options.PathMappings);
|
||||
static string AsFolder(string dir) => Path.TrimEndingDirectorySeparator(Path.GetFullPath(dir)) + Path.DirectorySeparatorChar;
|
||||
|
||||
var deliveredRoots = _options.PlateSearchRoots.Count > 0
|
||||
? _options.PlateSearchRoots.Select(r => AsFolder(mapper.Map(r))).ToList()
|
||||
// {footage}/{shot}_{element}/file.exr or {footage}/{shot}/{element}/file.exr:
|
||||
// two levels up from the timing plate is the folder its siblings share.
|
||||
: Path.GetDirectoryName(Path.GetDirectoryName(Path.GetFullPath(timingPlate.PlatePath))) is { } footage
|
||||
? new List<string> { AsFolder(footage) }
|
||||
: new List<string>();
|
||||
|
||||
var seen = new HashSet<string>(StringComparer.OrdinalIgnoreCase) { Path.GetFullPath(timingPlate.PlatePath) };
|
||||
foreach (var plate in plates)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(plate.Path)) continue;
|
||||
var local = Path.GetFullPath(mapper.Map(plate.Path));
|
||||
if (!seen.Add(local)) continue;
|
||||
if (!deliveredRoots.Any(root => local.StartsWith(root, StringComparison.OrdinalIgnoreCase))) continue;
|
||||
|
||||
var reference = ReadManifestPlate(plate, mapper, timingPlate.HandleFrames, renderFirstFrame);
|
||||
if (reference is null)
|
||||
{
|
||||
_log.LogWarning("Alternate plate from manifest is unreadable: {Path}", local);
|
||||
continue;
|
||||
}
|
||||
yield return reference;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Rank 2: look for the shot's plate folders under the configured roots,
|
||||
/// mirroring the panel's two on-disk layouts ({shotCode}/{element}/ and
|
||||
@@ -645,6 +727,16 @@ public sealed class SequencePattern
|
||||
return new SequencePattern { Prefix = prefix, Extension = ext, Padding = padding };
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Whether a filename belongs to *this* render's output: the pattern's own
|
||||
/// prefix and extension. A version folder also holds the preview MOV and
|
||||
/// MP4, which are built from the same basename and so share the prefix —
|
||||
/// only the extension separates them from the frames.
|
||||
/// </summary>
|
||||
public bool MatchesOutputFile(string fileName) =>
|
||||
fileName.StartsWith(Prefix, StringComparison.OrdinalIgnoreCase)
|
||||
&& fileName.EndsWith(Extension, StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
public int? FrameNumberOf(string fileName) => FrameFromName(fileName);
|
||||
|
||||
/// <summary>`UNG_102_019_010_cmp_TT_v005.01001.exr` → 1001.</summary>
|
||||
|
||||
@@ -652,6 +652,57 @@ export async function bulkUpdateDueDates(
|
||||
return { success: true, updated: shots.length };
|
||||
}
|
||||
|
||||
// ── Bulk Assign Artist ────────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Point a selection of shots at one artist, or clear the assignment when
|
||||
* `artistId` is null. Mirrors the single-shot artist field in updateShot —
|
||||
* the assignment is a plain column write with no notification, so reassigning
|
||||
* a batch during planning stays quiet.
|
||||
*/
|
||||
export async function bulkAssignArtist(shotIds: string[], artistId: string | null) {
|
||||
const session = await auth();
|
||||
if (!session?.user) throw new Error("Unauthorized");
|
||||
if (!["ADMIN", "PRODUCER", "SUPERVISOR"].includes(session.user.role)) {
|
||||
throw new Error("Insufficient permissions");
|
||||
}
|
||||
|
||||
const ids = z.array(z.string().cuid()).parse(shotIds);
|
||||
if (!ids.length) return { success: true, updated: 0, artistName: null as string | null };
|
||||
|
||||
let artistName: string | null = null;
|
||||
if (artistId) {
|
||||
const artist = await db.user.findUnique({
|
||||
where: { id: z.string().cuid().parse(artistId) },
|
||||
select: { id: true, name: true, email: true, role: true, isActive: true },
|
||||
});
|
||||
// A deactivated user or a client account must never end up owning a shot,
|
||||
// so this is checked here rather than trusting whatever the picker sent.
|
||||
if (!artist || !artist.isActive || artist.role === "CLIENT") {
|
||||
throw new Error("That user cannot be assigned shots");
|
||||
}
|
||||
artistName = artist.name ?? artist.email;
|
||||
}
|
||||
|
||||
const shots = await db.shot.findMany({
|
||||
where: { id: { in: ids } },
|
||||
select: { id: true, projectId: true },
|
||||
});
|
||||
if (shots.length !== ids.length) throw new Error("Some shots not found");
|
||||
|
||||
await db.shot.updateMany({
|
||||
where: { id: { in: ids } },
|
||||
data: { artistId },
|
||||
});
|
||||
|
||||
for (const pid of [...new Set(shots.map((s) => s.projectId))]) {
|
||||
revalidatePath(`/projects/${pid}`);
|
||||
}
|
||||
revalidatePath(`/shot-status`);
|
||||
|
||||
return { success: true, updated: shots.length, artistName };
|
||||
}
|
||||
|
||||
// ── Bulk Delete Shots ─────────────────────────────────────────────────────────
|
||||
|
||||
export async function bulkDeleteShots(shotIds: string[]) {
|
||||
|
||||
@@ -59,7 +59,7 @@ export default async function ClientDetailPage({
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="p-6 max-w-5xl mx-auto space-y-6">
|
||||
<div className="p-4 md:p-6 max-w-5xl mx-auto space-y-6">
|
||||
{/* Back */}
|
||||
<Link
|
||||
href="/clients"
|
||||
|
||||
@@ -26,7 +26,7 @@ export default async function ClientsPage() {
|
||||
const clients = await getClients();
|
||||
|
||||
return (
|
||||
<div className="p-6 max-w-5xl mx-auto space-y-6">
|
||||
<div className="p-4 md:p-6 max-w-5xl mx-auto space-y-6">
|
||||
{/* Header */}
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
|
||||
@@ -1,58 +1,63 @@
|
||||
import { auth } from "@/auth";
|
||||
import { db } from "@/lib/db";
|
||||
import { StatsCards } from "@/components/dashboard/StatsCards";
|
||||
import { BlockedQueue } from "@/components/dashboard/BlockedQueue";
|
||||
import { FarmStrip } from "@/components/dashboard/FarmStrip";
|
||||
import { DeliveryCountdown } from "@/components/dashboard/DeliveryCountdown";
|
||||
import { QcQueue } from "@/components/dashboard/QcQueue";
|
||||
import { RecentDeliveries } from "@/components/dashboard/RecentDeliveries";
|
||||
import { WhoseCourt } from "@/components/dashboard/WhoseCourt";
|
||||
import { ShotQueue } from "@/components/dashboard/ShotQueue";
|
||||
import { RecentActivity } from "@/components/dashboard/RecentActivity";
|
||||
import { TaskWidgets } from "@/components/dashboard/TaskWidgets";
|
||||
import { ScheduleWidgets } from "@/components/dashboard/ScheduleWidgets";
|
||||
import {
|
||||
getBlockedExports,
|
||||
getDeliveryCountdown,
|
||||
getFarmStatus,
|
||||
getOpsCounts,
|
||||
getQcQueue,
|
||||
getQcStaleHours,
|
||||
getRecentDeliveries,
|
||||
getWhoseCourt,
|
||||
} from "@/lib/dashboard/ops";
|
||||
import type { DashboardStats } from "@/types";
|
||||
|
||||
export const metadata = { title: "Dashboard" };
|
||||
|
||||
// Queue depth and machine state are stale the moment they are cached.
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
/**
|
||||
* The dashboard answers one question: can we ship what is due, and what is
|
||||
* stopping us? Everything on it is pipeline state — exports, QC, deliveries,
|
||||
* worker heartbeats — rather than anything a person has to maintain by hand.
|
||||
*/
|
||||
async function getDashboardData(userId: string, role: string) {
|
||||
const isArtist = role === "ARTIST";
|
||||
const isClient = role === "CLIENT";
|
||||
const now = new Date();
|
||||
const todayStart = new Date(now.getFullYear(), now.getMonth(), now.getDate());
|
||||
const todayEnd = new Date(todayStart.getTime() + 86400000);
|
||||
|
||||
const [awaitingReview, needsRevisions, approved, activeProjects,
|
||||
tasksDueToday, tasksInReview, tasksOverdue, myTasksCount] =
|
||||
// Producers see the floor; an artist sees the failures that are theirs.
|
||||
const [counts, blocked, farm, episodes, qcQueue, qcStaleHours, deliveries, court] =
|
||||
await Promise.all([
|
||||
db.version.count({ where: { approvalStatus: "PENDING_REVIEW" } }),
|
||||
db.version.count({ where: { approvalStatus: "NEEDS_CHANGES" } }),
|
||||
db.version.count({ where: { approvalStatus: "APPROVED" } }),
|
||||
db.project.count({ where: { status: "ACTIVE" } }),
|
||||
db.task.count({
|
||||
where: {
|
||||
dueDate: { gte: todayStart, lt: todayEnd },
|
||||
status: { not: "DONE" },
|
||||
...(isArtist ? { assignedArtistId: userId } : {}),
|
||||
},
|
||||
}),
|
||||
db.task.count({
|
||||
where: {
|
||||
status: { in: ["INTERNAL_REVIEW", "CLIENT_REVIEW"] },
|
||||
...(isArtist ? { assignedArtistId: userId } : {}),
|
||||
},
|
||||
}),
|
||||
db.task.count({
|
||||
where: {
|
||||
dueDate: { lt: todayStart },
|
||||
status: { not: "DONE" },
|
||||
...(isArtist ? { assignedArtistId: userId } : {}),
|
||||
},
|
||||
}),
|
||||
db.task.count({
|
||||
where: { assignedArtistId: userId, status: { not: "DONE" } },
|
||||
}),
|
||||
getOpsCounts(isArtist ? userId : undefined),
|
||||
getBlockedExports(isArtist ? { artistId: userId } : {}),
|
||||
getFarmStatus(),
|
||||
getDeliveryCountdown(),
|
||||
isArtist || isClient ? [] : getQcQueue(),
|
||||
getQcStaleHours(),
|
||||
isArtist || isClient ? [] : getRecentDeliveries(),
|
||||
isArtist || isClient ? null : getWhoseCourt(),
|
||||
]);
|
||||
|
||||
const shotsWhere = isArtist ? { artistId: userId } : {};
|
||||
// An artist's own shots come first; everyone else sees the floor.
|
||||
const shots = await db.shot.findMany({
|
||||
where: { ...shotsWhere, status: { not: "COMPLETE" } },
|
||||
where: {
|
||||
...(isArtist ? { artistId: userId } : {}),
|
||||
status: { not: "COMPLETE" },
|
||||
project: { status: { in: ["ACTIVE", "ON_HOLD"] } },
|
||||
},
|
||||
take: 15,
|
||||
orderBy: { updatedAt: "desc" },
|
||||
orderBy: [{ dueDate: { sort: "asc", nulls: "last" } }, { updatedAt: "desc" }],
|
||||
include: {
|
||||
artist: { select: { id: true, name: true, image: true, email: true } },
|
||||
versions: {
|
||||
@@ -63,12 +68,8 @@ async function getDashboardData(userId: string, role: string) {
|
||||
},
|
||||
});
|
||||
|
||||
// My tasks (for widget)
|
||||
const myTasks = await db.task.findMany({
|
||||
where: {
|
||||
assignedArtistId: userId,
|
||||
status: { not: "DONE" },
|
||||
},
|
||||
where: { assignedArtistId: userId, status: { not: "DONE" } },
|
||||
take: 8,
|
||||
orderBy: [{ dueDate: "asc" }, { priority: "desc" }],
|
||||
include: {
|
||||
@@ -78,7 +79,6 @@ async function getDashboardData(userId: string, role: string) {
|
||||
},
|
||||
});
|
||||
|
||||
// Tasks in review (for supervisors/producers)
|
||||
const reviewTasks = isArtist || isClient ? [] : await db.task.findMany({
|
||||
where: { status: { in: ["INTERNAL_REVIEW", "CLIENT_REVIEW"] } },
|
||||
take: 8,
|
||||
@@ -91,14 +91,8 @@ async function getDashboardData(userId: string, role: string) {
|
||||
},
|
||||
});
|
||||
|
||||
const activity = await db.notification.findMany({
|
||||
where: isClient ? { userId } : {},
|
||||
take: 20,
|
||||
orderBy: { createdAt: "desc" },
|
||||
include: { user: { select: { name: true, image: true } } },
|
||||
});
|
||||
|
||||
// Schedule data (for producers/supervisors/admins)
|
||||
// Schedule overview (producers/supervisors/admins) — unchanged; it reads the
|
||||
// schedule page's own data rather than anything the pipeline owns.
|
||||
const scheduledTasks =
|
||||
!isArtist && !isClient
|
||||
? await db.task.findMany({
|
||||
@@ -119,46 +113,55 @@ async function getDashboardData(userId: string, role: string) {
|
||||
!isArtist && !isClient
|
||||
? await db.user.findMany({
|
||||
where: { isActive: true, role: { not: "CLIENT" } },
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
email: true,
|
||||
image: true,
|
||||
role: true,
|
||||
},
|
||||
select: { id: true, name: true, email: true, image: true, role: true },
|
||||
orderBy: { name: "asc" },
|
||||
})
|
||||
: [];
|
||||
|
||||
const stats: DashboardStats = {
|
||||
awaitingReview,
|
||||
needsRevisions,
|
||||
approved,
|
||||
overdue: tasksOverdue,
|
||||
activeProjects,
|
||||
tasksDueToday,
|
||||
tasksInReview,
|
||||
tasksOverdue,
|
||||
myTasksCount,
|
||||
};
|
||||
const stats: DashboardStats = counts;
|
||||
|
||||
return { stats, shots, activity, myTasks, reviewTasks, scheduledTasks, scheduleArtists };
|
||||
return {
|
||||
stats,
|
||||
blocked,
|
||||
farm,
|
||||
episodes,
|
||||
qcQueue,
|
||||
qcStaleHours,
|
||||
deliveries,
|
||||
court,
|
||||
shots,
|
||||
myTasks,
|
||||
reviewTasks,
|
||||
scheduledTasks,
|
||||
scheduleArtists,
|
||||
};
|
||||
}
|
||||
|
||||
export default async function DashboardPage() {
|
||||
const session = await auth();
|
||||
if (!session?.user) return null;
|
||||
|
||||
const { stats, shots, activity, myTasks, reviewTasks, scheduledTasks, scheduleArtists } =
|
||||
await getDashboardData(session.user.id, session.user.role);
|
||||
|
||||
const isClient = session.user.role === "CLIENT";
|
||||
const canSeeSchedule = ["ADMIN", "PRODUCER", "SUPERVISOR"].includes(
|
||||
session.user.role
|
||||
);
|
||||
const isArtistRole = session.user.role === "ARTIST";
|
||||
const canSeeSchedule = ["ADMIN", "PRODUCER", "SUPERVISOR"].includes(session.user.role);
|
||||
const {
|
||||
stats,
|
||||
blocked,
|
||||
farm,
|
||||
episodes,
|
||||
qcQueue,
|
||||
qcStaleHours,
|
||||
deliveries,
|
||||
court,
|
||||
shots,
|
||||
myTasks,
|
||||
reviewTasks,
|
||||
scheduledTasks,
|
||||
scheduleArtists,
|
||||
} = await getDashboardData(session.user.id, session.user.role);
|
||||
|
||||
return (
|
||||
<div className="p-8 space-y-6 max-w-[1600px] mx-auto">
|
||||
<div className="p-4 md:p-8 space-y-6 max-w-[1600px] mx-auto">
|
||||
<div className="mb-4">
|
||||
<h1 className="text-3xl font-bold text-white">Dashboard</h1>
|
||||
<p className="text-zinc-400 mt-1">
|
||||
@@ -166,7 +169,62 @@ export default async function DashboardPage() {
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<StatsCards stats={stats} />
|
||||
{!isClient && <StatsCards stats={stats} />}
|
||||
|
||||
{!isClient && (
|
||||
<div className="space-y-3">
|
||||
<h2 className="text-sm font-semibold text-muted-foreground uppercase tracking-wide">
|
||||
Delivery countdown
|
||||
</h2>
|
||||
<DeliveryCountdown episodes={episodes} />
|
||||
</div>
|
||||
)}
|
||||
|
||||
{!isClient && (
|
||||
<div id="blocked" className="grid grid-cols-1 xl:grid-cols-3 gap-6 items-start scroll-mt-6">
|
||||
<div className="xl:col-span-2 space-y-3">
|
||||
<h2 className="text-sm font-semibold text-muted-foreground uppercase tracking-wide">
|
||||
{isArtistRole ? "Your blocked shots" : "Blocked — needs a human"}
|
||||
</h2>
|
||||
<BlockedQueue blocked={blocked} />
|
||||
</div>
|
||||
|
||||
<div className="space-y-3">
|
||||
<h2 className="text-sm font-semibold text-muted-foreground uppercase tracking-wide">
|
||||
Render farm
|
||||
</h2>
|
||||
<FarmStrip farm={farm} />
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{!isClient && !isArtistRole && (
|
||||
<div className="grid grid-cols-1 xl:grid-cols-3 gap-6 items-start">
|
||||
<div className="xl:col-span-2 space-y-3">
|
||||
<h2 className="text-sm font-semibold text-muted-foreground uppercase tracking-wide">
|
||||
QC queue
|
||||
</h2>
|
||||
<QcQueue entries={qcQueue} staleHours={qcStaleHours} />
|
||||
</div>
|
||||
|
||||
<div className="space-y-6">
|
||||
<div className="space-y-3">
|
||||
<h2 className="text-sm font-semibold text-muted-foreground uppercase tracking-wide">
|
||||
Deliveries
|
||||
</h2>
|
||||
<RecentDeliveries deliveries={deliveries} />
|
||||
</div>
|
||||
{court && (
|
||||
<div className="space-y-3">
|
||||
<h2 className="text-sm font-semibold text-muted-foreground uppercase tracking-wide">
|
||||
Whose court
|
||||
</h2>
|
||||
<WhoseCourt court={court} />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{!isClient && (
|
||||
<TaskWidgets
|
||||
@@ -181,30 +239,16 @@ export default async function DashboardPage() {
|
||||
<h2 className="text-sm font-semibold text-muted-foreground uppercase tracking-wide">
|
||||
Schedule Overview
|
||||
</h2>
|
||||
<ScheduleWidgets
|
||||
scheduledTasks={scheduledTasks as any}
|
||||
artists={scheduleArtists}
|
||||
/>
|
||||
<ScheduleWidgets scheduledTasks={scheduledTasks as any} artists={scheduleArtists} />
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="grid grid-cols-1 xl:grid-cols-3 gap-6">
|
||||
<div className="xl:col-span-2 space-y-3">
|
||||
<h2 className="text-sm font-semibold text-muted-foreground uppercase tracking-wide">
|
||||
Shot Queue
|
||||
</h2>
|
||||
<div className="rounded-lg border border-border bg-card p-1">
|
||||
<ShotQueue shots={shots as any} />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="space-y-3">
|
||||
<h2 className="text-sm font-semibold text-muted-foreground uppercase tracking-wide">
|
||||
Recent Activity
|
||||
</h2>
|
||||
<div className="rounded-lg border border-border bg-card h-[400px] overflow-hidden">
|
||||
<RecentActivity activities={activity as any} />
|
||||
</div>
|
||||
<div className="space-y-3">
|
||||
<h2 className="text-sm font-semibold text-muted-foreground uppercase tracking-wide">
|
||||
{session.user.role === "ARTIST" ? "My shots" : "Shots in flight"}
|
||||
</h2>
|
||||
<div className="rounded-lg border border-border bg-card p-1">
|
||||
<ShotQueue shots={shots as any} />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
+13
-10
@@ -2,6 +2,7 @@ import { auth } from "@/auth";
|
||||
import { redirect } from "next/navigation";
|
||||
import { Sidebar } from "@/components/layout/Sidebar";
|
||||
import { Header } from "@/components/layout/Header";
|
||||
import { MobileNavProvider } from "@/components/layout/MobileNav";
|
||||
|
||||
export default async function DashboardLayout({
|
||||
children,
|
||||
@@ -12,18 +13,20 @@ export default async function DashboardLayout({
|
||||
if (!session?.user) redirect("/login");
|
||||
|
||||
return (
|
||||
<div className="flex h-screen bg-zinc-950 overflow-hidden print:block print:h-auto print:overflow-visible">
|
||||
<div className="print:hidden">
|
||||
<Sidebar />
|
||||
</div>
|
||||
<div className="flex-1 flex flex-col overflow-hidden print:block print:overflow-visible">
|
||||
<MobileNavProvider>
|
||||
<div className="flex h-screen bg-zinc-950 overflow-hidden print:block print:h-auto print:overflow-visible">
|
||||
<div className="print:hidden">
|
||||
<Header />
|
||||
<Sidebar />
|
||||
</div>
|
||||
<div className="flex-1 flex flex-col overflow-hidden print:block print:overflow-visible">
|
||||
<div className="print:hidden">
|
||||
<Header />
|
||||
</div>
|
||||
<main className="flex-1 overflow-auto print:overflow-visible">
|
||||
{children}
|
||||
</main>
|
||||
</div>
|
||||
<main className="flex-1 overflow-auto print:overflow-visible">
|
||||
{children}
|
||||
</main>
|
||||
</div>
|
||||
</div>
|
||||
</MobileNavProvider>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -4,9 +4,10 @@ import { useState } from "react";
|
||||
import Link from "next/link";
|
||||
import { useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { useSession } from "next-auth/react";
|
||||
import { RefreshCw, RotateCcw, XCircle, CheckCircle2, Server, Package } from "lucide-react";
|
||||
import { RefreshCw, RotateCcw, XCircle, CheckCircle2, Server, Package, ChevronLeft, ChevronRight } from "lucide-react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Progress } from "@/components/ui/progress";
|
||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
@@ -51,37 +52,64 @@ interface QueueExport {
|
||||
|
||||
interface Props {
|
||||
projects: { id: string; name: string; code: string }[];
|
||||
/** Status to open filtered to, from `?status=` (see page.tsx). */
|
||||
initialStatus?: string;
|
||||
}
|
||||
|
||||
export function PipelineQueueClient({ projects }: Props) {
|
||||
const PAGE_SIZE = 25;
|
||||
|
||||
const BLENDER_ACTIVE = ["QUEUED", "CLAIMED", "RUNNING"];
|
||||
|
||||
export function PipelineQueueClient({ projects, initialStatus = "all" }: Props) {
|
||||
const { data: session } = useSession();
|
||||
const { toast } = useToast();
|
||||
const queryClient = useQueryClient();
|
||||
const [projectId, setProjectId] = useState<string>("all");
|
||||
const [statusFilter, setStatusFilter] = useState<string>("all");
|
||||
const [statusFilter, setStatusFilter] = useState<string>(initialStatus);
|
||||
const [page, setPage] = useState(1);
|
||||
const isAdmin = ["ADMIN", "PRODUCER", "SUPERVISOR"].includes(session?.user?.role ?? "");
|
||||
|
||||
const { data, isLoading, refetch, isFetching } = useQuery({
|
||||
queryKey: ["pipeline-queue", projectId, statusFilter],
|
||||
queryKey: ["pipeline-queue", projectId, statusFilter, page],
|
||||
queryFn: async () => {
|
||||
const params = new URLSearchParams({ limit: "200" });
|
||||
const params = new URLSearchParams({ limit: String(PAGE_SIZE), page: String(page) });
|
||||
if (projectId !== "all") params.set("projectId", projectId);
|
||||
if (statusFilter !== "all") params.set("status", statusFilter);
|
||||
const res = await fetch(`/api/render/queue?${params}`);
|
||||
if (!res.ok) throw new Error("Failed to load queue");
|
||||
return res.json() as Promise<{ exports: QueueExport[]; pagination: { total: number } }>;
|
||||
return res.json() as Promise<{
|
||||
exports: QueueExport[];
|
||||
pagination: { page: number; total: number; pages: number };
|
||||
statusCounts: Record<string, number>;
|
||||
}>;
|
||||
},
|
||||
refetchInterval: 5000,
|
||||
// Keep the current page on screen while the next one loads, instead of
|
||||
// flashing "Loading…" on every page turn.
|
||||
placeholderData: (previous) => previous,
|
||||
});
|
||||
|
||||
// Fetched here rather than in the tab so the tab label can say how many are
|
||||
// running: a Blender render must not become invisible by sitting in a tab.
|
||||
const { data: blenderData } = useQuery({
|
||||
queryKey: ["blender-jobs", projectId],
|
||||
queryFn: async () => {
|
||||
const qs = projectId !== "all" ? `?projectId=${encodeURIComponent(projectId)}` : "";
|
||||
const res = await fetch(`/api/render/blender${qs}`);
|
||||
if (!res.ok) throw new Error("Failed to load Blender jobs");
|
||||
return res.json() as Promise<{ jobs: BlenderJobRow[] }>;
|
||||
},
|
||||
refetchInterval: 5000,
|
||||
});
|
||||
|
||||
const exports = data?.exports ?? [];
|
||||
const counts = {
|
||||
queued: exports.filter((e) => e.status === "QUEUED").length,
|
||||
rendering: exports.filter((e) => e.status === "RENDERING").length,
|
||||
failed: exports.filter((e) => FAILED_STATUSES.includes(e.status)).length,
|
||||
readyForQc: exports.filter((e) => e.status === "READY_FOR_QC").length,
|
||||
readyForDelivery: exports.filter((e) => e.status === "READY_FOR_DELIVERY").length,
|
||||
};
|
||||
const pagination = data?.pagination;
|
||||
const statusCounts = data?.statusCounts ?? {};
|
||||
const countOf = (statuses: string[]) => statuses.reduce((n, s) => n + (statusCounts[s] ?? 0), 0);
|
||||
const totalExports = Object.values(statusCounts).reduce((n, c) => n + c, 0);
|
||||
const blenderJobs = blenderData?.jobs ?? [];
|
||||
const blenderActive = blenderJobs.filter((j) => BLENDER_ACTIVE.includes(j.status)).length;
|
||||
const blenderFailed = blenderJobs.filter((j) => ["FAILED", "EXPIRED"].includes(j.status)).length;
|
||||
|
||||
async function action(exportId: string, verb: "retry" | "cancel" | "mark-done") {
|
||||
const res = await fetch(`/api/render/exports/${exportId}/${verb}`, { method: "POST" });
|
||||
@@ -94,30 +122,56 @@ export function PipelineQueueClient({ projects }: Props) {
|
||||
queryClient.invalidateQueries({ queryKey: ["pipeline-queue"] });
|
||||
}
|
||||
|
||||
const cards: { label: string; value: number; className?: string }[] = [
|
||||
{ label: "Queued", value: counts.queued },
|
||||
{ label: "Rendering", value: counts.rendering, className: "text-blue-400" },
|
||||
{ label: "Failed", value: counts.failed, className: "text-red-400" },
|
||||
{ label: "Ready for QC", value: counts.readyForQc, className: "text-amber-400" },
|
||||
{ label: "Ready for Delivery", value: counts.readyForDelivery, className: "text-green-400" },
|
||||
const cards: { label: string; value: number; status?: string; className?: string }[] = [
|
||||
{ label: "Queued", value: countOf(["QUEUED"]), status: "QUEUED" },
|
||||
{ label: "Rendering", value: countOf(["RENDERING"]), status: "RENDERING", className: "text-blue-400" },
|
||||
// Several statuses count as failed and the filter takes one, so this card
|
||||
// is a figure only.
|
||||
{ label: "Failed", value: countOf(FAILED_STATUSES), className: "text-red-400" },
|
||||
{ label: "Ready for QC", value: countOf(["READY_FOR_QC"]), status: "READY_FOR_QC", className: "text-amber-400" },
|
||||
{
|
||||
label: "Ready for Delivery",
|
||||
value: countOf(["READY_FOR_DELIVERY"]),
|
||||
status: "READY_FOR_DELIVERY",
|
||||
className: "text-green-400",
|
||||
},
|
||||
];
|
||||
|
||||
const changeProject = (id: string) => {
|
||||
setProjectId(id);
|
||||
setPage(1);
|
||||
};
|
||||
const changeStatus = (status: string) => {
|
||||
setStatusFilter(status);
|
||||
setPage(1);
|
||||
};
|
||||
|
||||
const firstRow = pagination && pagination.total > 0 ? (pagination.page - 1) * PAGE_SIZE + 1 : 0;
|
||||
const lastRow = pagination ? Math.min(pagination.page * PAGE_SIZE, pagination.total) : 0;
|
||||
|
||||
return (
|
||||
<div className="p-6 space-y-6">
|
||||
<div className="p-4 md:p-6 space-y-6">
|
||||
<div className="flex items-center justify-between gap-4 flex-wrap">
|
||||
<div>
|
||||
<h1 className="text-2xl font-semibold text-white">Render Queue</h1>
|
||||
<p className="text-sm text-zinc-400 mt-1">
|
||||
Exports queued from the AE panel — live status, retries and history
|
||||
After Effects exports and Blender renders — live status, retries and history
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<Link href="/pipeline/deliveries">
|
||||
<Button variant="outline" size="sm">
|
||||
<Package className="h-4 w-4 mr-2" />
|
||||
Deliveries
|
||||
</Button>
|
||||
</Link>
|
||||
<div className="flex items-center gap-2 flex-wrap">
|
||||
<Select value={projectId} onValueChange={changeProject}>
|
||||
<SelectTrigger className="w-56">
|
||||
<SelectValue placeholder="All projects" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="all">All projects</SelectItem>
|
||||
{projects.map((p) => (
|
||||
<SelectItem key={p.id} value={p.id}>
|
||||
{p.name}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<Link href="/pipeline/deliveries">
|
||||
<Button variant="outline" size="sm">
|
||||
<Package className="h-4 w-4 mr-2" />
|
||||
@@ -136,152 +190,206 @@ export function PipelineQueueClient({ projects }: Props) {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Summary cards */}
|
||||
<div className="grid grid-cols-2 sm:grid-cols-5 gap-3">
|
||||
{cards.map((c) => (
|
||||
<div key={c.label} className="rounded-lg border border-zinc-800 bg-zinc-900 px-4 py-3">
|
||||
<div className={cn("text-2xl font-semibold text-white", c.className)}>{c.value}</div>
|
||||
<div className="text-xs text-zinc-400 mt-0.5">{c.label}</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{/* Filters */}
|
||||
<div className="flex items-center gap-3 flex-wrap">
|
||||
<Select value={projectId} onValueChange={setProjectId}>
|
||||
<SelectTrigger className="w-56">
|
||||
<SelectValue placeholder="All projects" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="all">All projects</SelectItem>
|
||||
{projects.map((p) => (
|
||||
<SelectItem key={p.id} value={p.id}>
|
||||
{p.name}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<Select value={statusFilter} onValueChange={setStatusFilter}>
|
||||
<SelectTrigger className="w-56">
|
||||
<SelectValue placeholder="All statuses" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="all">All statuses</SelectItem>
|
||||
{Object.keys(EXPORT_STATUS_STYLES).map((s) => (
|
||||
<SelectItem key={s} value={s}>
|
||||
{statusLabel(s)}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
{/* Table */}
|
||||
<div className="rounded-lg border border-zinc-800 overflow-x-auto">
|
||||
<table className="w-full text-sm">
|
||||
<thead>
|
||||
<tr className="border-b border-zinc-800 bg-zinc-900/60 text-left text-xs text-zinc-400">
|
||||
<th className="px-4 py-2.5 font-medium">Shot</th>
|
||||
<th className="px-4 py-2.5 font-medium">Version</th>
|
||||
<th className="px-4 py-2.5 font-medium">Status</th>
|
||||
<th className="px-4 py-2.5 font-medium w-48">Progress</th>
|
||||
<th className="px-4 py-2.5 font-medium">Machine</th>
|
||||
<th className="px-4 py-2.5 font-medium">Attempt</th>
|
||||
<th className="px-4 py-2.5 font-medium">Queued</th>
|
||||
<th className="px-4 py-2.5 font-medium text-right">Actions</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{isLoading ? (
|
||||
<tr>
|
||||
<td colSpan={8} className="px-4 py-10 text-center text-zinc-500">
|
||||
Loading…
|
||||
</td>
|
||||
</tr>
|
||||
) : exports.length === 0 ? (
|
||||
<tr>
|
||||
<td colSpan={8} className="px-4 py-10 text-center text-zinc-500">
|
||||
No exports yet — queue one from the After Effects panel
|
||||
</td>
|
||||
</tr>
|
||||
<Tabs defaultValue="exports" className="space-y-4">
|
||||
<TabsList className="bg-zinc-900 border border-zinc-800">
|
||||
<TabsTrigger value="exports">
|
||||
After Effects exports
|
||||
<span className="ml-2 text-xs text-zinc-500">{totalExports}</span>
|
||||
</TabsTrigger>
|
||||
<TabsTrigger value="blender">
|
||||
Blender renders
|
||||
{blenderActive > 0 ? (
|
||||
<span className="ml-2 rounded-full bg-blue-500/20 px-1.5 text-xs text-blue-400">
|
||||
{blenderActive} active
|
||||
</span>
|
||||
) : blenderFailed > 0 ? (
|
||||
<span className="ml-2 rounded-full bg-red-500/20 px-1.5 text-xs text-red-400">
|
||||
{blenderFailed} failed
|
||||
</span>
|
||||
) : (
|
||||
exports.map((e) => (
|
||||
<tr key={e.id} className="border-b border-zinc-800/60 hover:bg-zinc-900/40">
|
||||
<td className="px-4 py-2.5">
|
||||
<Link href={`/pipeline/exports/${e.id}`} className="text-white hover:text-amber-400 font-medium">
|
||||
{e.shotCode}
|
||||
</Link>
|
||||
<div className="text-xs text-zinc-500">
|
||||
{e.projectCode}
|
||||
{e.episode ? ` · ep ${e.episode}` : ""}
|
||||
</div>
|
||||
</td>
|
||||
<td className="px-4 py-2.5 text-zinc-300">{e.versionString}</td>
|
||||
<td className="px-4 py-2.5">
|
||||
<span
|
||||
className={cn(
|
||||
"inline-block rounded-full border px-2 py-0.5 text-xs whitespace-nowrap",
|
||||
EXPORT_STATUS_STYLES[e.status] ?? "bg-zinc-500/15 text-zinc-300 border-zinc-500/30"
|
||||
)}
|
||||
title={e.job?.errorMessage ?? undefined}
|
||||
>
|
||||
{statusLabel(e.status)}
|
||||
</span>
|
||||
</td>
|
||||
<td className="px-4 py-2.5">
|
||||
{e.status === "RENDERING" && e.job ? (
|
||||
<div className="space-y-1">
|
||||
<Progress value={e.job.progress * 100} className="h-1.5" />
|
||||
<div className="text-xs text-zinc-500">
|
||||
{e.job.currentFrame != null && e.job.totalFrames != null
|
||||
? `frame ${e.job.currentFrame}/${e.job.totalFrames} · `
|
||||
: ""}
|
||||
ETA {formatEta(e.job.etaSeconds)}
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<span className="text-zinc-600 text-xs">—</span>
|
||||
)}
|
||||
</td>
|
||||
<td className="px-4 py-2.5 text-zinc-400">{e.job?.machineName ?? "—"}</td>
|
||||
<td className="px-4 py-2.5 text-zinc-400">
|
||||
{e.job ? `${e.job.attempt}` : "—"}
|
||||
</td>
|
||||
<td className="px-4 py-2.5 text-zinc-500 text-xs whitespace-nowrap">
|
||||
{new Date(e.createdAt).toLocaleString()}
|
||||
</td>
|
||||
<td className="px-4 py-2.5">
|
||||
<div className="flex items-center justify-end gap-1">
|
||||
{FAILED_STATUSES.includes(e.status) && (
|
||||
<Button variant="ghost" size="icon-sm" title="Retry" onClick={() => action(e.id, "retry")}>
|
||||
<RotateCcw className="h-4 w-4 text-amber-400" />
|
||||
</Button>
|
||||
)}
|
||||
{ACTIVE_STATUSES.includes(e.status) && (
|
||||
<Button variant="ghost" size="icon-sm" title="Cancel" onClick={() => action(e.id, "cancel")}>
|
||||
<XCircle className="h-4 w-4 text-red-400" />
|
||||
</Button>
|
||||
)}
|
||||
{isAdmin && ["QUEUED", "RENDERING"].includes(e.status) && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon-sm"
|
||||
title="Mark done manually (rendered outside the pipeline)"
|
||||
onClick={() => action(e.id, "mark-done")}
|
||||
>
|
||||
<CheckCircle2 className="h-4 w-4 text-green-400" />
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
))
|
||||
<span className="ml-2 text-xs text-zinc-500">{blenderJobs.length}</span>
|
||||
)}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</TabsTrigger>
|
||||
</TabsList>
|
||||
|
||||
<BlenderQueue projectId={projectId} />
|
||||
<TabsContent value="exports" className="space-y-4 mt-0">
|
||||
{/* Summary cards — each one with a status filters the table to what it counts */}
|
||||
<div className="grid grid-cols-2 sm:grid-cols-5 gap-3">
|
||||
{cards.map((c) => {
|
||||
const selected = c.status !== undefined && statusFilter === c.status;
|
||||
const body = (
|
||||
<>
|
||||
<div className={cn("text-2xl font-semibold text-white", c.className)}>{c.value}</div>
|
||||
<div className="text-xs text-zinc-400 mt-0.5">{c.label}</div>
|
||||
</>
|
||||
);
|
||||
return c.status ? (
|
||||
<button
|
||||
key={c.label}
|
||||
type="button"
|
||||
onClick={() => changeStatus(selected ? "all" : c.status!)}
|
||||
className={cn(
|
||||
"rounded-lg border bg-zinc-900 px-4 py-3 text-left transition-colors hover:border-zinc-600",
|
||||
selected ? "border-zinc-500" : "border-zinc-800"
|
||||
)}
|
||||
>
|
||||
{body}
|
||||
</button>
|
||||
) : (
|
||||
<div key={c.label} className="rounded-lg border border-zinc-800 bg-zinc-900 px-4 py-3">
|
||||
{body}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
|
||||
<Select value={statusFilter} onValueChange={changeStatus}>
|
||||
<SelectTrigger className="w-56">
|
||||
<SelectValue placeholder="All statuses" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="all">All statuses</SelectItem>
|
||||
{Object.keys(EXPORT_STATUS_STYLES).map((s) => (
|
||||
<SelectItem key={s} value={s}>
|
||||
{statusLabel(s)}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
|
||||
<div className="rounded-lg border border-zinc-800 overflow-x-auto">
|
||||
<table className="w-full text-sm">
|
||||
<thead>
|
||||
<tr className="border-b border-zinc-800 bg-zinc-900/60 text-left text-xs text-zinc-400">
|
||||
<th className="px-4 py-2.5 font-medium">Shot</th>
|
||||
<th className="px-4 py-2.5 font-medium">Version</th>
|
||||
<th className="px-4 py-2.5 font-medium">Status</th>
|
||||
<th className="px-4 py-2.5 font-medium w-48">Progress</th>
|
||||
<th className="px-4 py-2.5 font-medium">Machine</th>
|
||||
<th className="px-4 py-2.5 font-medium">Attempt</th>
|
||||
<th className="px-4 py-2.5 font-medium">Queued</th>
|
||||
<th className="px-4 py-2.5 font-medium text-right">Actions</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{isLoading ? (
|
||||
<tr>
|
||||
<td colSpan={8} className="px-4 py-10 text-center text-zinc-500">
|
||||
Loading…
|
||||
</td>
|
||||
</tr>
|
||||
) : exports.length === 0 ? (
|
||||
<tr>
|
||||
<td colSpan={8} className="px-4 py-10 text-center text-zinc-500">
|
||||
{statusFilter === "all"
|
||||
? "No exports yet — queue one from the After Effects panel"
|
||||
: `No exports are ${statusLabel(statusFilter).toLowerCase()}`}
|
||||
</td>
|
||||
</tr>
|
||||
) : (
|
||||
exports.map((e) => (
|
||||
<tr key={e.id} className="border-b border-zinc-800/60 hover:bg-zinc-900/40">
|
||||
<td className="px-4 py-2.5">
|
||||
<Link href={`/pipeline/exports/${e.id}`} className="text-white hover:text-amber-400 font-medium">
|
||||
{e.shotCode}
|
||||
</Link>
|
||||
<div className="text-xs text-zinc-500">
|
||||
{e.projectCode}
|
||||
{e.episode ? ` · ep ${e.episode}` : ""}
|
||||
</div>
|
||||
</td>
|
||||
<td className="px-4 py-2.5 text-zinc-300">{e.versionString}</td>
|
||||
<td className="px-4 py-2.5">
|
||||
<span
|
||||
className={cn(
|
||||
"inline-block rounded-full border px-2 py-0.5 text-xs whitespace-nowrap",
|
||||
EXPORT_STATUS_STYLES[e.status] ?? "bg-zinc-500/15 text-zinc-300 border-zinc-500/30"
|
||||
)}
|
||||
title={e.job?.errorMessage ?? undefined}
|
||||
>
|
||||
{statusLabel(e.status)}
|
||||
</span>
|
||||
</td>
|
||||
<td className="px-4 py-2.5">
|
||||
{e.status === "RENDERING" && e.job ? (
|
||||
<div className="space-y-1">
|
||||
<Progress value={e.job.progress * 100} className="h-1.5" />
|
||||
<div className="text-xs text-zinc-500">
|
||||
{e.job.currentFrame != null && e.job.totalFrames != null
|
||||
? `frame ${e.job.currentFrame}/${e.job.totalFrames} · `
|
||||
: ""}
|
||||
ETA {formatEta(e.job.etaSeconds)}
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<span className="text-zinc-600 text-xs">—</span>
|
||||
)}
|
||||
</td>
|
||||
<td className="px-4 py-2.5 text-zinc-400">{e.job?.machineName ?? "—"}</td>
|
||||
<td className="px-4 py-2.5 text-zinc-400">{e.job ? `${e.job.attempt}` : "—"}</td>
|
||||
<td className="px-4 py-2.5 text-zinc-500 text-xs whitespace-nowrap">
|
||||
{new Date(e.createdAt).toLocaleString()}
|
||||
</td>
|
||||
<td className="px-4 py-2.5">
|
||||
<div className="flex items-center justify-end gap-1">
|
||||
{FAILED_STATUSES.includes(e.status) && (
|
||||
<Button variant="ghost" size="icon-sm" title="Retry" onClick={() => action(e.id, "retry")}>
|
||||
<RotateCcw className="h-4 w-4 text-amber-400" />
|
||||
</Button>
|
||||
)}
|
||||
{ACTIVE_STATUSES.includes(e.status) && (
|
||||
<Button variant="ghost" size="icon-sm" title="Cancel" onClick={() => action(e.id, "cancel")}>
|
||||
<XCircle className="h-4 w-4 text-red-400" />
|
||||
</Button>
|
||||
)}
|
||||
{isAdmin && ["QUEUED", "RENDERING"].includes(e.status) && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon-sm"
|
||||
title="Mark done manually (rendered outside the pipeline)"
|
||||
onClick={() => action(e.id, "mark-done")}
|
||||
>
|
||||
<CheckCircle2 className="h-4 w-4 text-green-400" />
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
))
|
||||
)}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
{pagination && pagination.pages > 1 && (
|
||||
<div className="flex items-center justify-between text-sm text-zinc-400">
|
||||
<span>
|
||||
{firstRow}–{lastRow} of {pagination.total}
|
||||
</span>
|
||||
<div className="flex items-center gap-2">
|
||||
<Button variant="outline" size="sm" disabled={page <= 1} onClick={() => setPage((p) => p - 1)}>
|
||||
<ChevronLeft className="h-4 w-4" />
|
||||
</Button>
|
||||
<span className="text-xs">
|
||||
Page {pagination.page} of {pagination.pages}
|
||||
</span>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
disabled={page >= pagination.pages}
|
||||
onClick={() => setPage((p) => p + 1)}
|
||||
>
|
||||
<ChevronRight className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="blender" className="mt-0">
|
||||
<BlenderQueue jobs={blenderJobs} loaded={blenderData !== undefined} />
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -318,24 +426,13 @@ const BLENDER_STATUS_STYLES: Record<string, string> = {
|
||||
|
||||
/**
|
||||
* Standalone Blender renders. They have no Export behind them, so they cannot
|
||||
* appear in the table above — but they share the queue, and a render nobody can
|
||||
* see is a render nobody can retry.
|
||||
* appear in the exports table — but they share the queue, and a render nobody
|
||||
* can see is a render nobody can retry.
|
||||
*/
|
||||
function BlenderQueue({ projectId }: { projectId: string }) {
|
||||
function BlenderQueue({ jobs, loaded }: { jobs: BlenderJobRow[]; loaded: boolean }) {
|
||||
const { toast } = useToast();
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
const { data } = useQuery({
|
||||
queryKey: ["blender-jobs", projectId],
|
||||
queryFn: async () => {
|
||||
const qs = projectId && projectId !== "all" ? `?projectId=${encodeURIComponent(projectId)}` : "";
|
||||
const res = await fetch(`/api/render/blender${qs}`);
|
||||
if (!res.ok) throw new Error("Failed to load Blender jobs");
|
||||
return res.json() as Promise<{ jobs: BlenderJobRow[] }>;
|
||||
},
|
||||
refetchInterval: 5000,
|
||||
});
|
||||
|
||||
async function jobAction(id: string, verb: "cancel" | "retry") {
|
||||
const res = await fetch(`/api/render/blender/${id}?action=${verb}`, { method: "POST" });
|
||||
if (!res.ok) {
|
||||
@@ -345,14 +442,16 @@ function BlenderQueue({ projectId }: { projectId: string }) {
|
||||
queryClient.invalidateQueries({ queryKey: ["blender-jobs"] });
|
||||
}
|
||||
|
||||
const jobs = data?.jobs ?? [];
|
||||
if (jobs.length === 0) return null;
|
||||
if (jobs.length === 0) {
|
||||
return (
|
||||
<div className="rounded-lg border border-zinc-800 px-4 py-10 text-center text-sm text-zinc-500">
|
||||
{loaded ? "No Blender renders yet — submit one from the Blender panel" : "Loading…"}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="rounded-lg border border-zinc-800 bg-zinc-900/40">
|
||||
<div className="px-4 py-2.5 border-b border-zinc-800 text-sm font-medium text-white">
|
||||
Blender renders
|
||||
</div>
|
||||
<div className="divide-y divide-zinc-800/60">
|
||||
{jobs.map((j) => (
|
||||
<div key={j.id} className="px-4 py-3 text-sm">
|
||||
|
||||
@@ -140,7 +140,7 @@ export function DeliveriesClient({ canBuild }: { canBuild: boolean }) {
|
||||
const shown = episode ? episodes.filter((e) => e.episode === episode) : episodes;
|
||||
|
||||
return (
|
||||
<div className="p-6 space-y-6 max-w-6xl">
|
||||
<div className="p-4 md:p-6 space-y-6 max-w-6xl">
|
||||
<div className="flex items-center gap-3">
|
||||
<Link href="/pipeline">
|
||||
<Button variant="ghost" size="icon-sm">
|
||||
|
||||
@@ -155,10 +155,10 @@ export function ExportDetailClient({ exportId }: { exportId: string }) {
|
||||
}
|
||||
}
|
||||
|
||||
if (isLoading) return <div className="p-6 text-zinc-500">Loading…</div>;
|
||||
if (isLoading) return <div className="p-4 md:p-6 text-zinc-500">Loading…</div>;
|
||||
if (error || !data) {
|
||||
return (
|
||||
<div className="p-6 text-red-400">
|
||||
<div className="p-4 md:p-6 text-red-400">
|
||||
{(error as Error)?.message ?? "Export not found"}
|
||||
</div>
|
||||
);
|
||||
@@ -180,7 +180,7 @@ export function ExportDetailClient({ exportId }: { exportId: string }) {
|
||||
];
|
||||
|
||||
return (
|
||||
<div className="p-6 space-y-6 max-w-5xl">
|
||||
<div className="p-4 md:p-6 space-y-6 max-w-5xl">
|
||||
<div className="flex items-center justify-between gap-4 flex-wrap">
|
||||
<div className="flex items-center gap-3">
|
||||
<Link href="/pipeline">
|
||||
|
||||
@@ -76,7 +76,7 @@ export function MachinesClient() {
|
||||
const machines = data?.machines ?? [];
|
||||
|
||||
return (
|
||||
<div className="p-6 space-y-6">
|
||||
<div className="p-4 md:p-6 space-y-6">
|
||||
<div className="flex items-center gap-3">
|
||||
<Link href="/pipeline">
|
||||
<Button variant="ghost" size="icon-sm">
|
||||
|
||||
@@ -1,20 +1,32 @@
|
||||
import { auth } from "@/auth";
|
||||
import { redirect } from "next/navigation";
|
||||
import { ExportStatus } from "@prisma/client";
|
||||
import { db } from "@/lib/db";
|
||||
import { PipelineQueueClient } from "./PipelineQueueClient";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
export default async function PipelinePage() {
|
||||
export default async function PipelinePage({
|
||||
searchParams,
|
||||
}: {
|
||||
searchParams: Promise<{ status?: string }>;
|
||||
}) {
|
||||
const session = await auth();
|
||||
if (!session?.user) redirect("/login");
|
||||
if (session.user.role === "CLIENT") redirect("/dashboard");
|
||||
|
||||
// Lets other pages link straight to a filtered queue — the dashboard's "In
|
||||
// QC" figure is only useful if it leads to the rows it counted. Anything
|
||||
// that is not a real status falls back to the unfiltered queue.
|
||||
const requested = (await searchParams).status;
|
||||
const initialStatus =
|
||||
requested && (Object.values(ExportStatus) as string[]).includes(requested) ? requested : "all";
|
||||
|
||||
const projects = await db.project.findMany({
|
||||
where: { status: { in: ["ACTIVE", "ON_HOLD"] } },
|
||||
select: { id: true, name: true, code: true },
|
||||
orderBy: { name: "asc" },
|
||||
});
|
||||
|
||||
return <PipelineQueueClient projects={projects} />;
|
||||
return <PipelineQueueClient projects={projects} initialStatus={initialStatus} />;
|
||||
}
|
||||
|
||||
@@ -69,7 +69,7 @@ export default async function KanbanPage({
|
||||
]);
|
||||
|
||||
return (
|
||||
<div className="p-6 space-y-6 max-w-[1800px] mx-auto">
|
||||
<div className="p-4 md:p-6 space-y-6 max-w-[1800px] mx-auto">
|
||||
{/* Breadcrumb */}
|
||||
<div className="flex items-center gap-2 text-sm text-muted-foreground">
|
||||
<Link href="/projects" className="hover:text-foreground transition-colors">
|
||||
|
||||
@@ -123,7 +123,7 @@ export default async function ProjectPage({ params }: { params: Promise<{ id: st
|
||||
const doneTasks = project.tasks.filter((t) => t.status === "DONE").length;
|
||||
|
||||
return (
|
||||
<div className="p-8 space-y-6 max-w-[1600px] mx-auto">
|
||||
<div className="p-4 md:p-8 space-y-6 max-w-[1600px] mx-auto">
|
||||
{/* Breadcrumb */}
|
||||
<div className="flex items-center gap-2 text-sm text-zinc-500">
|
||||
<Link href="/projects" className="hover:text-white transition-colors">
|
||||
|
||||
@@ -230,7 +230,7 @@ export default function ShotDetailPage() {
|
||||
const { Icon: StatusIcon } = statusCfg;
|
||||
|
||||
return (
|
||||
<div className="p-6 space-y-6 max-w-[1400px] mx-auto">
|
||||
<div className="p-4 md:p-6 space-y-6 max-w-[1400px] mx-auto">
|
||||
{/* Breadcrumb */}
|
||||
<div className="flex items-center gap-2 text-sm text-muted-foreground">
|
||||
<Link href="/projects" className="hover:text-foreground transition-colors">
|
||||
@@ -245,7 +245,9 @@ export default function ShotDetailPage() {
|
||||
</div>
|
||||
|
||||
{/* Header */}
|
||||
<div className="flex items-start gap-6">
|
||||
{/* Phones: back button, then a full-width thumbnail, then the details
|
||||
below it. From md: one row, as on desktop. */}
|
||||
<div className="flex flex-wrap md:flex-nowrap items-start gap-4 md:gap-6">
|
||||
{/* Thumbnail – cinema scope 2.39:1 */}
|
||||
<Button variant="ghost" size="icon" asChild className="-ml-2 h-8 w-8">
|
||||
<Link href={`/projects/${params.id}`}>
|
||||
@@ -253,7 +255,7 @@ export default function ShotDetailPage() {
|
||||
</Link>
|
||||
</Button>
|
||||
{shotThumbnail(shot) && (
|
||||
<div className="relative flex-shrink-0 w-72 aspect-[2.39] rounded-lg overflow-hidden border border-border">
|
||||
<div className="relative flex-shrink-0 w-full md:w-72 aspect-[2.39] rounded-lg overflow-hidden border border-border">
|
||||
|
||||
<Image
|
||||
src={shotThumbnail(shot)!}
|
||||
@@ -263,10 +265,10 @@ export default function ShotDetailPage() {
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
<div className="space-y-2">
|
||||
<div className="flex items-center gap-3">
|
||||
|
||||
<h1 className="text-2xl font-bold font-mono">{shot.shotCode}</h1>
|
||||
<div className="space-y-2 min-w-0 w-full md:w-auto md:min-w-min">
|
||||
<div className="flex flex-wrap items-center gap-3">
|
||||
|
||||
<h1 className="text-2xl font-bold font-mono break-all md:break-normal">{shot.shotCode}</h1>
|
||||
|
||||
{/* Shot version badge — click to edit for managers */}
|
||||
{canManage ? (
|
||||
@@ -424,7 +426,7 @@ export default function ShotDetailPage() {
|
||||
)}
|
||||
|
||||
{canManage && (
|
||||
<div className="ml-auto shrink-0 flex items-center gap-2">
|
||||
<div className="ml-auto shrink-0 flex flex-wrap md:flex-nowrap items-center gap-2 w-full md:w-auto">
|
||||
{/* Internal approval action */}
|
||||
{canInternallyApprove && shot.shotApprovalStatus === "PENDING" && (
|
||||
<Button
|
||||
@@ -510,7 +512,8 @@ export default function ShotDetailPage() {
|
||||
|
||||
{/* Tabs */}
|
||||
<div>
|
||||
<div className="flex border-b border-border mb-5">
|
||||
{/* Phones: five tabs are wider than the screen, so the bar scrolls sideways. */}
|
||||
<div className="flex border-b border-border mb-5 overflow-x-auto overflow-y-hidden md:overflow-visible [&>button]:shrink-0 [&>button]:whitespace-nowrap">
|
||||
<button
|
||||
onClick={() => setActiveTab("tasks")}
|
||||
className={cn(
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
"use client";
|
||||
|
||||
import { useState, useEffect } from "react";
|
||||
import { useState, useEffect, useRef } from "react";
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
@@ -8,6 +8,7 @@ import { ProjectCard } from "@/components/projects/ProjectCard";
|
||||
import { NewProjectDialog } from "@/components/projects/NewProjectDialog";
|
||||
import { Plus, Search, Loader2 } from "lucide-react";
|
||||
import { HIDE_ARCHIVED_KEY } from "@/components/settings/HideArchivedToggle";
|
||||
import { useScrollMemory } from "@/hooks/use-scroll-memory";
|
||||
|
||||
export default function ProjectsPage() {
|
||||
const [search, setSearch] = useState("");
|
||||
@@ -43,22 +44,11 @@ export default function ProjectsPage() {
|
||||
|
||||
const visibleProjects = hideArchived ? projects.filter((p: any) => p.status !== "ARCHIVED") : projects;
|
||||
|
||||
const SCROLL_KEY = 'projects-scroll';
|
||||
|
||||
useEffect(() => {
|
||||
if (!isLoading) {
|
||||
const saved = sessionStorage.getItem(SCROLL_KEY);
|
||||
if (saved) {
|
||||
sessionStorage.removeItem(SCROLL_KEY);
|
||||
requestAnimationFrame(() => window.scrollTo(0, parseInt(saved, 10)));
|
||||
}
|
||||
}
|
||||
}, [isLoading]);
|
||||
|
||||
const saveScroll = () => sessionStorage.setItem(SCROLL_KEY, String(window.scrollY));
|
||||
const pageRef = useRef<HTMLDivElement>(null);
|
||||
useScrollMemory("projects", pageRef, !isLoading);
|
||||
|
||||
return (
|
||||
<div className="p-8 space-y-6 max-w-[1600px] mx-auto">
|
||||
<div ref={pageRef} className="p-4 md:p-8 space-y-6 max-w-[1600px] mx-auto">
|
||||
<div className="flex items-center justify-between gap-4 mb-8">
|
||||
<div>
|
||||
<h1 className="text-3xl font-bold text-white">Projects</h1>
|
||||
@@ -104,9 +94,11 @@ export default function ProjectsPage() {
|
||||
</Button>
|
||||
</div>
|
||||
) : (
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4">
|
||||
// auto-rows-fr keeps every row the same height, so a project with a
|
||||
// long description does not make its whole row taller than the rest.
|
||||
<div className="grid auto-rows-fr grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4">
|
||||
{visibleProjects.map((project: any) => (
|
||||
<div key={project.id} onClick={saveScroll}>
|
||||
<div key={project.id} className="h-full">
|
||||
<ProjectCard project={project} />
|
||||
</div>
|
||||
))}
|
||||
|
||||
@@ -186,7 +186,7 @@ export default function MigrationPage() {
|
||||
|
||||
if (fetchError) {
|
||||
return (
|
||||
<div className="p-6 max-w-2xl">
|
||||
<div className="p-4 md:p-6 max-w-2xl">
|
||||
<div className="flex items-center gap-2 text-sm text-red-400 rounded-md border border-red-500/20 bg-red-500/10 px-3 py-2">
|
||||
<AlertCircle className="h-4 w-4 shrink-0" />
|
||||
{fetchError}
|
||||
@@ -200,7 +200,7 @@ export default function MigrationPage() {
|
||||
|
||||
if (!hetznerConfigured) {
|
||||
return (
|
||||
<div className="p-6 max-w-2xl">
|
||||
<div className="p-4 md:p-6 max-w-2xl">
|
||||
<div className="flex items-center gap-2 text-sm text-amber-400 rounded-md border border-amber-500/20 bg-amber-500/10 px-3 py-2">
|
||||
<AlertCircle className="h-4 w-4 shrink-0" />
|
||||
Hetzner object storage is not configured. Set{" "}
|
||||
@@ -217,7 +217,7 @@ export default function MigrationPage() {
|
||||
const allFilteredSelected = filtered.length > 0 && filtered.every((f) => selected.has(f.key));
|
||||
|
||||
return (
|
||||
<div className="p-6 space-y-4 max-w-5xl">
|
||||
<div className="p-4 md:p-6 space-y-4 max-w-5xl">
|
||||
{/* Header */}
|
||||
<div className="flex items-start justify-between gap-4">
|
||||
<div>
|
||||
|
||||
@@ -19,7 +19,7 @@ export default async function SettingsPage() {
|
||||
const hetznerConfig = isAdmin ? await getHetznerConfig() : null;
|
||||
|
||||
return (
|
||||
<div className="p-6 space-y-6 max-w-2xl mx-auto">
|
||||
<div className="p-4 md:p-6 space-y-6 max-w-2xl mx-auto">
|
||||
<h1 className="text-2xl font-bold">Account Settings</h1>
|
||||
|
||||
<Card>
|
||||
|
||||
@@ -72,7 +72,7 @@ export default function StorageTestPage() {
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="p-6 max-w-3xl space-y-6">
|
||||
<div className="p-4 md:p-6 max-w-3xl space-y-6">
|
||||
<div>
|
||||
<h1 className="text-xl font-semibold">Object Storage Playback Test</h1>
|
||||
<p className="text-sm text-muted-foreground mt-1">
|
||||
|
||||
@@ -4,10 +4,12 @@ import { useState, useTransition, useCallback, useEffect, useRef } from "react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import Image from "next/image";
|
||||
import Link from "next/link";
|
||||
import { useScrollMemory } from "@/hooks/use-scroll-memory";
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectSeparator,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from "@/components/ui/select";
|
||||
@@ -28,8 +30,9 @@ import {
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Textarea } from "@/components/ui/textarea";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { updateShotNotes, bulkUpdateDueDates, bulkDeleteShots, toggleKeyShot, toggleScaledShot } from "@/actions/shots";
|
||||
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
|
||||
import { cn, getInitials } from "@/lib/utils";
|
||||
import { updateShotNotes, bulkUpdateDueDates, bulkAssignArtist, bulkDeleteShots, toggleKeyShot, toggleScaledShot } from "@/actions/shots";
|
||||
import { previewMovReview, buildMovReview } from "@/actions/deliveries";
|
||||
import { useToast } from "@/components/ui/use-toast";
|
||||
import {
|
||||
@@ -50,6 +53,7 @@ import {
|
||||
ChevronsUpDown,
|
||||
Clapperboard,
|
||||
Scaling,
|
||||
UserPlus,
|
||||
} from "lucide-react";
|
||||
import { format } from "date-fns";
|
||||
import { shotThumbnail } from "@/lib/shot-thumbnail";
|
||||
@@ -74,6 +78,13 @@ type ShotRow = {
|
||||
shotGroup: { id: string; name: string } | null;
|
||||
};
|
||||
|
||||
interface Artist {
|
||||
id: string;
|
||||
name: string | null;
|
||||
email: string;
|
||||
image: string | null;
|
||||
}
|
||||
|
||||
interface Project {
|
||||
id: string;
|
||||
name: string;
|
||||
@@ -87,10 +98,29 @@ interface ShotStatusClientProps {
|
||||
selectedProject: Project | null;
|
||||
shots: ShotRow[];
|
||||
episodeDueDates: { episode: string; dueDate: Date | string }[];
|
||||
artists: Artist[];
|
||||
canManage: boolean;
|
||||
}
|
||||
|
||||
const SCROLL_KEY = 'shot-status-scroll';
|
||||
function readStored(key: string): string | null {
|
||||
try {
|
||||
return localStorage.getItem(key);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** A saved list of open sections, or null when none was saved (or it is unreadable). */
|
||||
function readStoredList(key: string): string[] | null {
|
||||
const raw = readStored(key);
|
||||
if (!raw) return null;
|
||||
try {
|
||||
const parsed = JSON.parse(raw);
|
||||
return Array.isArray(parsed) ? parsed.filter((v): v is string => typeof v === "string") : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
const STATUS_CONFIG: Record<string, { label: string; color: string; icon: React.ElementType }> = {
|
||||
WAITING: { label: "Waiting", color: "bg-zinc-500/10 text-zinc-400 border-zinc-500/20", icon: Clock },
|
||||
@@ -225,6 +255,103 @@ function BulkDueDateDialog({
|
||||
);
|
||||
}
|
||||
|
||||
// ── BulkAssignArtistDialog ────────────────────────────────────────────────────
|
||||
|
||||
const UNASSIGN = "__unassign__";
|
||||
|
||||
/**
|
||||
* Hand a selection of shots to one artist, or clear the assignment.
|
||||
*
|
||||
* Unassigning is offered as an explicit choice rather than a separate menu
|
||||
* entry — reassignment and hand-back are the same production move, and the
|
||||
* confirm button changes wording so nobody clears a batch by accident.
|
||||
*/
|
||||
function BulkAssignArtistDialog({
|
||||
open,
|
||||
onClose,
|
||||
onApply,
|
||||
artists,
|
||||
count,
|
||||
}: {
|
||||
open: boolean;
|
||||
onClose: () => void;
|
||||
onApply: (artistId: string | null) => Promise<void>;
|
||||
artists: Artist[];
|
||||
count: number;
|
||||
}) {
|
||||
const [value, setValue] = useState("");
|
||||
const [isPending, startTransition] = useTransition();
|
||||
|
||||
useEffect(() => {
|
||||
if (open) setValue("");
|
||||
}, [open]);
|
||||
|
||||
const handleApply = () => {
|
||||
if (!value) return;
|
||||
startTransition(async () => {
|
||||
await onApply(value === UNASSIGN ? null : value);
|
||||
});
|
||||
};
|
||||
|
||||
const unassigning = value === UNASSIGN;
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={(o) => { if (!o && !isPending) onClose(); }}>
|
||||
<DialogContent className="sm:max-w-sm">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Assign Artist</DialogTitle>
|
||||
</DialogHeader>
|
||||
|
||||
<p className="text-sm text-zinc-400 -mt-1">
|
||||
Applying to <span className="text-white font-medium">{count}</span>{" "}
|
||||
shot{count !== 1 ? "s" : ""}
|
||||
</p>
|
||||
|
||||
<div className="space-y-1.5 pt-1">
|
||||
<label className="text-xs font-medium text-zinc-400">Artist</label>
|
||||
<Select value={value} onValueChange={setValue}>
|
||||
<SelectTrigger className="w-full">
|
||||
<SelectValue placeholder="Select an artist..." />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{artists.map((a) => (
|
||||
<SelectItem key={a.id} value={a.id}>
|
||||
<span className="flex items-center gap-2">
|
||||
<Avatar className="h-5 w-5">
|
||||
<AvatarImage src={a.image ?? undefined} />
|
||||
<AvatarFallback className="text-[9px] bg-zinc-700 text-zinc-300">
|
||||
{getInitials(a.name ?? a.email)}
|
||||
</AvatarFallback>
|
||||
</Avatar>
|
||||
{a.name ?? a.email}
|
||||
</span>
|
||||
</SelectItem>
|
||||
))}
|
||||
<SelectSeparator />
|
||||
<SelectItem value={UNASSIGN}>
|
||||
<span className="text-zinc-400">Unassign</span>
|
||||
</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<p className="text-xs text-zinc-500 pt-1">
|
||||
This replaces whoever is currently on {count === 1 ? "the shot" : "these shots"}.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<DialogFooter className="mt-2">
|
||||
<Button variant="ghost" onClick={onClose} disabled={isPending}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button onClick={handleApply} disabled={!value || isPending}>
|
||||
{isPending && <Loader2 className="h-3.5 w-3.5 mr-1.5 animate-spin" />}
|
||||
{unassigning ? "Unassign" : "Assign"}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
|
||||
function BulkDeleteDialog({
|
||||
open,
|
||||
onClose,
|
||||
@@ -601,6 +728,7 @@ function ShotTable({
|
||||
<th className="text-left py-2 px-3 text-xs font-medium text-zinc-500 w-32">Thumb</th>
|
||||
<th className="text-left py-2 px-3 text-xs font-medium text-zinc-500">Shot</th>
|
||||
<th className="text-left py-2 px-3 text-xs font-medium text-zinc-500 w-32">Status</th>
|
||||
<th className="text-left py-2 px-3 text-xs font-medium text-zinc-500 w-40">Artist</th>
|
||||
<th className="text-left py-2 px-3 text-xs font-medium text-zinc-500 w-32">Due Date</th>
|
||||
<th className="text-left py-2 px-3 text-xs font-medium text-zinc-500">Notes</th>
|
||||
<th className="py-2 px-3 text-xs font-medium text-zinc-500 w-20 text-center">
|
||||
@@ -671,7 +799,6 @@ function ShotTable({
|
||||
<Link
|
||||
href={`/projects/${projectId}/shots/${shot.id}`}
|
||||
className="font-mono text-sm text-white hover:text-blue-400 transition-colors"
|
||||
onClick={() => sessionStorage.setItem(SCROLL_KEY, String(window.scrollY))}
|
||||
>
|
||||
{shot.shotCode}
|
||||
</Link>
|
||||
@@ -700,6 +827,25 @@ function ShotTable({
|
||||
</Badge>
|
||||
</td>
|
||||
|
||||
{/* Artist */}
|
||||
<td className="py-2 px-3">
|
||||
{shot.artist ? (
|
||||
<span className="flex items-center gap-2 min-w-0">
|
||||
<Avatar className="h-5 w-5 shrink-0">
|
||||
<AvatarImage src={shot.artist.image ?? undefined} />
|
||||
<AvatarFallback className="text-[9px] bg-zinc-700 text-zinc-300">
|
||||
{getInitials(shot.artist.name ?? shot.artist.email)}
|
||||
</AvatarFallback>
|
||||
</Avatar>
|
||||
<span className="text-xs text-zinc-300 truncate">
|
||||
{shot.artist.name ?? shot.artist.email}
|
||||
</span>
|
||||
</span>
|
||||
) : (
|
||||
<span className="text-xs text-zinc-600 italic">Unassigned</span>
|
||||
)}
|
||||
</td>
|
||||
|
||||
{/* Due date */}
|
||||
<td className="py-2 px-3">
|
||||
{dueDate ? (
|
||||
@@ -745,20 +891,12 @@ export function ShotStatusClient({
|
||||
selectedProject,
|
||||
shots,
|
||||
episodeDueDates,
|
||||
artists,
|
||||
canManage,
|
||||
}: ShotStatusClientProps) {
|
||||
const router = useRouter();
|
||||
const { toast } = useToast();
|
||||
|
||||
// Restore scroll position when shots load
|
||||
useEffect(() => {
|
||||
const saved = sessionStorage.getItem(SCROLL_KEY);
|
||||
if (saved) {
|
||||
sessionStorage.removeItem(SCROLL_KEY);
|
||||
requestAnimationFrame(() => window.scrollTo(0, parseInt(saved, 10)));
|
||||
}
|
||||
}, [shots]);
|
||||
|
||||
// Restore last selected project if no project is currently selected
|
||||
useEffect(() => {
|
||||
if (!selectedProjectId) {
|
||||
@@ -776,23 +914,41 @@ export function ShotStatusClient({
|
||||
const [groupMode, setGroupMode] = useState<"flat" | "scene" | "group">("flat");
|
||||
const [selectedIds, setSelectedIds] = useState<Set<string>>(new Set());
|
||||
|
||||
// Load saved episode expand state when project changes
|
||||
// Which sections were open is restored before the scroll position: until
|
||||
// they are, the page is shorter and the saved offset would not fit.
|
||||
const [expandRestored, setExpandRestored] = useState(false);
|
||||
const pageRef = useRef<HTMLDivElement>(null);
|
||||
useScrollMemory(selectedProjectId ? `shotStatus:${selectedProjectId}` : null, pageRef, expandRestored);
|
||||
|
||||
// Load saved expand state and grouping when the project changes
|
||||
useEffect(() => {
|
||||
if (!selectedProjectId) return;
|
||||
try {
|
||||
const saved = localStorage.getItem(`shotStatus:${selectedProjectId}:episodeExpand`);
|
||||
setExpandedEpisodes(saved ? new Set(JSON.parse(saved) as string[]) : new Set());
|
||||
} catch {
|
||||
setExpandedEpisodes(new Set());
|
||||
}
|
||||
try {
|
||||
const savedGroup = localStorage.getItem(`shotStatus:${selectedProjectId}:groupMode`);
|
||||
setGroupMode((savedGroup as "flat" | "scene" | "group") ?? "flat");
|
||||
} catch {
|
||||
setGroupMode("flat");
|
||||
}
|
||||
setExpandRestored(false);
|
||||
const mode = (readStored(`shotStatus:${selectedProjectId}:groupMode`) ?? "flat") as "flat" | "scene" | "group";
|
||||
setGroupMode(mode);
|
||||
setExpandedEpisodes(new Set(readStoredList(`shotStatus:${selectedProjectId}:episodeExpand`) ?? []));
|
||||
// Scenes and groups open fully when their mode is first chosen, so with
|
||||
// nothing saved yet they come back that way rather than all collapsed.
|
||||
setExpandedScenes(
|
||||
new Set(readStoredList(`shotStatus:${selectedProjectId}:sceneExpand`) ?? shots.map((s) => s.scene))
|
||||
);
|
||||
setExpandedGroups(
|
||||
new Set(readStoredList(`shotStatus:${selectedProjectId}:groupExpand`) ?? shots.map((s) => s.shotGroup?.id ?? ""))
|
||||
);
|
||||
setExpandRestored(true);
|
||||
// Shots are read only for the defaults; a refresh after an edit must not
|
||||
// reset what the user has opened.
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [selectedProjectId]);
|
||||
|
||||
const saveExpanded = (kind: "episodeExpand" | "sceneExpand" | "groupExpand", open: Set<string>) => {
|
||||
if (!selectedProjectId) return;
|
||||
try {
|
||||
localStorage.setItem(`shotStatus:${selectedProjectId}:${kind}`, JSON.stringify([...open]));
|
||||
} catch {}
|
||||
};
|
||||
const [dueDateDialogOpen, setDueDateDialogOpen] = useState(false);
|
||||
const [assignDialogOpen, setAssignDialogOpen] = useState(false);
|
||||
const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
|
||||
const [movReviewDialogOpen, setMovReviewDialogOpen] = useState(false);
|
||||
|
||||
@@ -800,11 +956,7 @@ export function ShotStatusClient({
|
||||
setExpandedEpisodes((prev) => {
|
||||
const next = new Set(prev);
|
||||
next.has(ep) ? next.delete(ep) : next.add(ep);
|
||||
if (selectedProjectId) {
|
||||
try {
|
||||
localStorage.setItem(`shotStatus:${selectedProjectId}:episodeExpand`, JSON.stringify([...next]));
|
||||
} catch {}
|
||||
}
|
||||
saveExpanded("episodeExpand", next);
|
||||
return next;
|
||||
});
|
||||
|
||||
@@ -812,6 +964,7 @@ export function ShotStatusClient({
|
||||
setExpandedScenes((prev) => {
|
||||
const next = new Set(prev);
|
||||
next.has(sc) ? next.delete(sc) : next.add(sc);
|
||||
saveExpanded("sceneExpand", next);
|
||||
return next;
|
||||
});
|
||||
|
||||
@@ -819,13 +972,22 @@ export function ShotStatusClient({
|
||||
setExpandedGroups((prev) => {
|
||||
const next = new Set(prev);
|
||||
next.has(g) ? next.delete(g) : next.add(g);
|
||||
saveExpanded("groupExpand", next);
|
||||
return next;
|
||||
});
|
||||
|
||||
const handleGroupMode = (mode: "flat" | "scene" | "group") => {
|
||||
setGroupMode(mode);
|
||||
if (mode === "scene") setExpandedScenes(new Set(shots.map((s) => s.scene)));
|
||||
if (mode === "group") setExpandedGroups(new Set(shots.map((s) => s.shotGroup?.id ?? "")));
|
||||
if (mode === "scene") {
|
||||
const all = new Set(shots.map((s) => s.scene));
|
||||
setExpandedScenes(all);
|
||||
saveExpanded("sceneExpand", all);
|
||||
}
|
||||
if (mode === "group") {
|
||||
const all = new Set(shots.map((s) => s.shotGroup?.id ?? ""));
|
||||
setExpandedGroups(all);
|
||||
saveExpanded("groupExpand", all);
|
||||
}
|
||||
if (selectedProjectId) {
|
||||
try { localStorage.setItem(`shotStatus:${selectedProjectId}:groupMode`, mode); } catch {}
|
||||
}
|
||||
@@ -868,6 +1030,26 @@ export function ShotStatusClient({
|
||||
}
|
||||
};
|
||||
|
||||
const handleBulkAssignArtist = async (artistId: string | null) => {
|
||||
try {
|
||||
const result = await bulkAssignArtist([...selectedIds], artistId);
|
||||
toast({
|
||||
title: result.artistName
|
||||
? `${result.updated} shot${result.updated !== 1 ? "s" : ""} assigned to ${result.artistName}`
|
||||
: `${result.updated} shot${result.updated !== 1 ? "s" : ""} unassigned`,
|
||||
});
|
||||
setAssignDialogOpen(false);
|
||||
clearSelection();
|
||||
router.refresh();
|
||||
} catch (e) {
|
||||
toast({
|
||||
title: "Failed to assign artist",
|
||||
description: e instanceof Error ? e.message : undefined,
|
||||
variant: "destructive",
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
const handleBulkDelete = async () => {
|
||||
try {
|
||||
const result = await bulkDeleteShots([...selectedIds]);
|
||||
@@ -942,7 +1124,7 @@ export function ShotStatusClient({
|
||||
const selectionCount = selectedIds.size;
|
||||
|
||||
return (
|
||||
<div className="p-8 space-y-6 max-w-[1600px] mx-auto">
|
||||
<div ref={pageRef} className="p-4 md:p-8 space-y-6 max-w-[1600px] mx-auto">
|
||||
{/* Header */}
|
||||
<div>
|
||||
<h1 className="text-3xl font-bold text-white">Shot Status</h1>
|
||||
@@ -1040,6 +1222,10 @@ export function ShotStatusClient({
|
||||
<CalendarDays className="h-3.5 w-3.5 mr-2" />
|
||||
Change Due Date
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem onClick={() => setAssignDialogOpen(true)}>
|
||||
<UserPlus className="h-3.5 w-3.5 mr-2" />
|
||||
Assign Artist
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem onClick={() => setMovReviewDialogOpen(true)}>
|
||||
<Clapperboard className="h-3.5 w-3.5 mr-2" />
|
||||
Build MOV Review Package
|
||||
@@ -1249,6 +1435,15 @@ export function ShotStatusClient({
|
||||
count={selectionCount}
|
||||
/>
|
||||
|
||||
{/* Bulk artist assignment dialog */}
|
||||
<BulkAssignArtistDialog
|
||||
open={assignDialogOpen}
|
||||
onClose={() => setAssignDialogOpen(false)}
|
||||
onApply={handleBulkAssignArtist}
|
||||
artists={artists}
|
||||
count={selectionCount}
|
||||
/>
|
||||
|
||||
{/* Bulk delete dialog */}
|
||||
<BulkDeleteDialog
|
||||
open={deleteDialogOpen}
|
||||
|
||||
@@ -19,6 +19,15 @@ async function getEpisodeDueDatesForProject(projectId: string) {
|
||||
});
|
||||
}
|
||||
|
||||
/** Everyone a shot can be handed to — clients and deactivated accounts excluded. */
|
||||
async function getAssignableArtists() {
|
||||
return db.user.findMany({
|
||||
where: { isActive: true, role: { not: "CLIENT" } },
|
||||
select: { id: true, name: true, email: true, image: true },
|
||||
orderBy: { name: "asc" },
|
||||
});
|
||||
}
|
||||
|
||||
async function getShotsForProject(projectId: string) {
|
||||
return db.shot.findMany({
|
||||
where: { projectId },
|
||||
@@ -62,10 +71,11 @@ export default async function ShotStatusPage({
|
||||
const { projectId } = await searchParams;
|
||||
const canManage = ["ADMIN", "PRODUCER", "SUPERVISOR"].includes(session.user.role);
|
||||
|
||||
const [projects, shots, episodeDueDates] = await Promise.all([
|
||||
const [projects, shots, episodeDueDates, artists] = await Promise.all([
|
||||
getProjects(),
|
||||
projectId ? getShotsForProject(projectId) : Promise.resolve([]),
|
||||
projectId ? getEpisodeDueDatesForProject(projectId) : Promise.resolve([]),
|
||||
canManage ? getAssignableArtists() : Promise.resolve([]),
|
||||
]);
|
||||
|
||||
const selectedProject = projects.find((p) => p.id === projectId) ?? null;
|
||||
@@ -77,6 +87,7 @@ export default async function ShotStatusPage({
|
||||
selectedProject={selectedProject}
|
||||
shots={shots as any}
|
||||
episodeDueDates={episodeDueDates}
|
||||
artists={artists}
|
||||
canManage={canManage}
|
||||
/>
|
||||
);
|
||||
|
||||
@@ -110,7 +110,7 @@ export function TasksPageClient({
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="p-6 max-w-5xl mx-auto space-y-6">
|
||||
<div className="p-4 md:p-6 max-w-5xl mx-auto space-y-6">
|
||||
{/* Header */}
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
|
||||
@@ -32,7 +32,7 @@ export default async function UsersPage() {
|
||||
}));
|
||||
|
||||
return (
|
||||
<div className="p-6 max-w-5xl mx-auto space-y-6">
|
||||
<div className="p-4 md:p-6 max-w-5xl mx-auto space-y-6">
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="w-10 h-10 rounded-lg bg-amber-500/10 border border-amber-500/20 flex items-center justify-center shrink-0">
|
||||
<Users className="h-5 w-5 text-amber-400" />
|
||||
|
||||
@@ -0,0 +1,124 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { auth } from "@/auth";
|
||||
import { db } from "@/lib/db";
|
||||
import { PLATE_EXTS, parsePlateFilename } from "@/lib/batch-upload-parser";
|
||||
|
||||
export type PlatePreviewItemStatus =
|
||||
| "match" // shot found → a new footage plate will be added
|
||||
| "duplicate" // the shot already has a plate with this exact filename
|
||||
| "no-match" // no shot in this project matches the filename
|
||||
| "unsupported"; // extension is not an accepted video format
|
||||
|
||||
export interface PlatePreviewItem {
|
||||
fileName: string;
|
||||
shotCode: string | null;
|
||||
shotId: string | null;
|
||||
/** Label the new plate will be created with */
|
||||
label: string;
|
||||
status: PlatePreviewItemStatus;
|
||||
/** Number of plates the matched shot already has */
|
||||
existingPlateCount: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* POST /api/batch-upload/plates
|
||||
* Body: { projectId: string; fileNames: string[] }
|
||||
*
|
||||
* Previews which shot each footage plate file will be attached to, derived
|
||||
* from the filename. e.g. "DH2_VFX_058_120_REF.mov" → shot "DH2_VFX_058_120"
|
||||
* with the label "REF". Nothing is uploaded.
|
||||
*/
|
||||
export async function POST(req: NextRequest) {
|
||||
const session = await auth();
|
||||
if (!session?.user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
|
||||
|
||||
let body: unknown;
|
||||
try {
|
||||
body = await req.json();
|
||||
} catch {
|
||||
return NextResponse.json({ error: "Invalid JSON" }, { status: 400 });
|
||||
}
|
||||
|
||||
const { projectId, fileNames } = body as { projectId?: unknown; fileNames?: unknown };
|
||||
|
||||
if (!projectId || typeof projectId !== "string" || !Array.isArray(fileNames)) {
|
||||
return NextResponse.json(
|
||||
{ error: "projectId and fileNames[] are required" },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
const shots = await db.shot.findMany({
|
||||
where: { projectId },
|
||||
select: {
|
||||
id: true,
|
||||
shotCode: true,
|
||||
footagePlates: { select: { fileName: true } },
|
||||
},
|
||||
});
|
||||
|
||||
const shotCodes = shots.map((s) => s.shotCode);
|
||||
const shotByCode = new Map(shots.map((s) => [s.shotCode, s]));
|
||||
|
||||
// Several files in one batch can land on the same shot, so keep a running
|
||||
// count per shot to number the "Plate N" fallback labels correctly.
|
||||
const allocated = new Map<string, number>();
|
||||
|
||||
const items: PlatePreviewItem[] = fileNames.map((fileName: string) => {
|
||||
const parsed = parsePlateFilename(fileName, shotCodes);
|
||||
|
||||
if (!PLATE_EXTS.has(parsed.ext)) {
|
||||
return {
|
||||
fileName,
|
||||
shotCode: null,
|
||||
shotId: null,
|
||||
label: "",
|
||||
status: "unsupported" as const,
|
||||
existingPlateCount: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const shot = parsed.shotCode ? shotByCode.get(parsed.shotCode) ?? null : null;
|
||||
if (!shot) {
|
||||
return {
|
||||
fileName,
|
||||
shotCode: null,
|
||||
shotId: null,
|
||||
label: "",
|
||||
status: "no-match" as const,
|
||||
existingPlateCount: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const existingPlateCount = shot.footagePlates.length;
|
||||
|
||||
// Re-running a batch shouldn't silently pile up identical plates.
|
||||
const isDuplicate = shot.footagePlates.some(
|
||||
(p) => p.fileName.toLowerCase() === fileName.toLowerCase()
|
||||
);
|
||||
if (isDuplicate) {
|
||||
return {
|
||||
fileName,
|
||||
shotCode: shot.shotCode,
|
||||
shotId: shot.id,
|
||||
label: parsed.label,
|
||||
status: "duplicate" as const,
|
||||
existingPlateCount,
|
||||
};
|
||||
}
|
||||
|
||||
const takenSoFar = allocated.get(shot.id) ?? 0;
|
||||
allocated.set(shot.id, takenSoFar + 1);
|
||||
|
||||
return {
|
||||
fileName,
|
||||
shotCode: shot.shotCode,
|
||||
shotId: shot.id,
|
||||
label: parsed.label || `Plate ${existingPlateCount + takenSoFar + 1}`,
|
||||
status: "match" as const,
|
||||
existingPlateCount,
|
||||
};
|
||||
});
|
||||
|
||||
return NextResponse.json({ items });
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { auth } from "@/auth";
|
||||
import { db } from "@/lib/db";
|
||||
import { revalidatePath } from "next/cache";
|
||||
|
||||
export const maxDuration = 30;
|
||||
|
||||
/**
|
||||
* POST /api/batch-upload/plates/upload
|
||||
* Body: { projectId, shotId, key, fileName, fileSize?, label? }
|
||||
*
|
||||
* Commits a footage plate whose bytes were already uploaded straight to
|
||||
* Hetzner via POST /api/upload/presign, so large .mov plates never pass
|
||||
* through this server or the reverse proxy.
|
||||
*/
|
||||
export async function POST(req: NextRequest) {
|
||||
const session = await auth();
|
||||
if (!session?.user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
|
||||
if (!["ADMIN", "PRODUCER", "SUPERVISOR"].includes(session.user.role)) {
|
||||
return NextResponse.json({ error: "Forbidden" }, { status: 403 });
|
||||
}
|
||||
|
||||
let body: unknown;
|
||||
try {
|
||||
body = await req.json();
|
||||
} catch {
|
||||
return NextResponse.json({ error: "Invalid JSON" }, { status: 400 });
|
||||
}
|
||||
|
||||
const { projectId, shotId, key, fileName, fileSize, label } = body as {
|
||||
projectId?: unknown;
|
||||
shotId?: unknown;
|
||||
key?: unknown;
|
||||
fileName?: unknown;
|
||||
fileSize?: unknown;
|
||||
label?: unknown;
|
||||
};
|
||||
|
||||
if (
|
||||
typeof projectId !== "string" ||
|
||||
typeof shotId !== "string" ||
|
||||
typeof key !== "string" ||
|
||||
typeof fileName !== "string" ||
|
||||
!projectId ||
|
||||
!shotId ||
|
||||
!key ||
|
||||
!fileName
|
||||
) {
|
||||
return NextResponse.json(
|
||||
{ error: "projectId, shotId, key and fileName are required" },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
// The key must be one this app handed out via /api/upload/presign.
|
||||
if (!key.startsWith("videos/")) {
|
||||
return NextResponse.json({ error: "Invalid storage key" }, { status: 400 });
|
||||
}
|
||||
|
||||
const shot = await db.shot.findFirst({
|
||||
where: { id: shotId, projectId },
|
||||
select: { id: true },
|
||||
});
|
||||
if (!shot) return NextResponse.json({ error: "Shot not found" }, { status: 404 });
|
||||
|
||||
const last = await db.footagePlate.findFirst({
|
||||
where: { shotId },
|
||||
orderBy: { sortOrder: "desc" },
|
||||
select: { sortOrder: true },
|
||||
});
|
||||
|
||||
const size = typeof fileSize === "number" && Number.isFinite(fileSize) && fileSize > 0
|
||||
? BigInt(Math.round(fileSize))
|
||||
: null;
|
||||
|
||||
const plate = await db.footagePlate.create({
|
||||
data: {
|
||||
shotId,
|
||||
fileUrl: `/api/files/${key}`,
|
||||
fileKey: key,
|
||||
fileName,
|
||||
fileSize: size,
|
||||
label: typeof label === "string" ? label.trim().slice(0, 100) : "",
|
||||
sortOrder: (last?.sortOrder ?? -1) + 1,
|
||||
},
|
||||
});
|
||||
|
||||
revalidatePath(`/projects/${projectId}`);
|
||||
revalidatePath(`/projects/${projectId}/shots/${shotId}`);
|
||||
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
plateId: plate.id,
|
||||
label: plate.label,
|
||||
});
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { auth } from "@/auth";
|
||||
import { db } from "@/lib/db";
|
||||
import { getProjectPosters } from "@/lib/project-poster";
|
||||
|
||||
export async function GET(req: Request) {
|
||||
const session = await auth();
|
||||
@@ -53,9 +54,13 @@ export async function GET(req: Request) {
|
||||
statsMap.set(row.projectId, existing);
|
||||
}
|
||||
|
||||
// One still per project for the card art, chosen from the shots themselves.
|
||||
const posters = await getProjectPosters(projects.map((p) => p.id));
|
||||
|
||||
const projectsWithStats = projects.map((p) => ({
|
||||
...p,
|
||||
shotStats: statsMap.get(p.id) ?? { total: 0, approved: 0, inProgress: 0 },
|
||||
poster: posters.get(p.id) ?? null,
|
||||
}));
|
||||
|
||||
return NextResponse.json({ projects: projectsWithStats });
|
||||
|
||||
+25
-27
@@ -1,6 +1,7 @@
|
||||
'use client';
|
||||
|
||||
import { useState, useEffect } from 'react';
|
||||
import { useState, useRef, useEffect } from 'react';
|
||||
import { useScrollMemory } from '@/hooks/use-scroll-memory';
|
||||
import Link from 'next/link';
|
||||
import Image from 'next/image';
|
||||
import {
|
||||
@@ -127,7 +128,6 @@ const TASK_TYPE_LABELS: Record<string, string> = {
|
||||
GENERAL: 'Task',
|
||||
};
|
||||
|
||||
const SCROLL_KEY = 'client-portal-scroll';
|
||||
const QUEUE_KEY = 'client-portal-queue';
|
||||
const STATE_KEY = 'client-portal-state';
|
||||
const PREFS_KEY_PREFIX = 'client-portal-prefs-';
|
||||
@@ -154,6 +154,11 @@ export default function ClientPortalPage({
|
||||
const [sortMode, setSortMode] = useState<'episode' | 'recent'>('episode');
|
||||
const [searchQuery, setSearchQuery] = useState<string>('');
|
||||
const [episodeFilter, setEpisodeFilter] = useState<string | null>(null);
|
||||
// Filters and collapsed episodes set the page height, so the scroll
|
||||
// position is restored only once they are back.
|
||||
const [viewRestored, setViewRestored] = useState(false);
|
||||
const pageRef = useRef<HTMLDivElement>(null);
|
||||
useScrollMemory(token ? `clientPortal:${token}` : null, pageRef, viewRestored);
|
||||
|
||||
const toggleEpisode = (ep: string) => {
|
||||
setCollapsedEpisodes((prev) => {
|
||||
@@ -209,13 +214,7 @@ export default function ClientPortalPage({
|
||||
}
|
||||
} catch { /* ignore */ }
|
||||
}
|
||||
const saved = sessionStorage.getItem(SCROLL_KEY);
|
||||
if (saved) {
|
||||
sessionStorage.removeItem(SCROLL_KEY);
|
||||
requestAnimationFrame(() => {
|
||||
window.scrollTo(0, parseInt(saved, 10));
|
||||
});
|
||||
}
|
||||
setViewRestored(true);
|
||||
}
|
||||
}, [loading, token]);
|
||||
|
||||
@@ -429,7 +428,6 @@ export default function ClientPortalPage({
|
||||
};
|
||||
|
||||
const handleReviewClick = () => {
|
||||
sessionStorage.setItem(SCROLL_KEY, String(window.scrollY));
|
||||
sessionStorage.setItem(QUEUE_KEY, JSON.stringify(getReviewQueue()));
|
||||
sessionStorage.setItem(
|
||||
STATE_KEY,
|
||||
@@ -444,7 +442,7 @@ export default function ClientPortalPage({
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-zinc-950 text-white">
|
||||
<div ref={pageRef} className="min-h-screen bg-zinc-950 text-white">
|
||||
<header className="border-b border-zinc-800 bg-zinc-900">
|
||||
<div className="max-w-5xl mx-auto px-6 py-4 flex items-center justify-between">
|
||||
{/* Logo */}
|
||||
@@ -454,7 +452,7 @@ export default function ClientPortalPage({
|
||||
</div>
|
||||
|
||||
<div className={montserrat.className}>
|
||||
<span className="block text-2xl font-light text-white leading-none">
|
||||
<span className="block text-2xl font-light text-white leading-none whitespace-nowrap">
|
||||
TWO TALES
|
||||
</span>
|
||||
|
||||
@@ -464,7 +462,7 @@ export default function ClientPortalPage({
|
||||
</div>
|
||||
</div>
|
||||
{sessionLabel && (
|
||||
<span className="text-sm text-zinc-400">{sessionLabel}</span>
|
||||
<span className="ml-4 min-w-0 truncate text-right text-sm text-zinc-400" title={sessionLabel}>{sessionLabel}</span>
|
||||
)}
|
||||
</div>
|
||||
</header>
|
||||
@@ -687,7 +685,7 @@ export default function ClientPortalPage({
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
<div className="flex items-center gap-1.5 group/itemlabel">
|
||||
<div className="flex min-w-0 items-center gap-1.5 group/itemlabel">
|
||||
<p className="font-mono text-xs text-zinc-500">
|
||||
{item.label}
|
||||
{item.description && (
|
||||
@@ -698,7 +696,7 @@ export default function ClientPortalPage({
|
||||
</p>
|
||||
<button
|
||||
onClick={() => copyToClipboard(item.label, `label-${task.id}`)}
|
||||
className="shrink-0 p-0.5 rounded opacity-0 group-hover/itemlabel:opacity-100 text-zinc-600 hover:text-zinc-300 transition-all"
|
||||
className="hidden sm:block shrink-0 p-0.5 rounded opacity-0 group-hover/itemlabel:opacity-100 text-zinc-600 hover:text-zinc-300 transition-all"
|
||||
title="Copy name"
|
||||
>
|
||||
{copiedId === `label-${task.id}` ? (
|
||||
@@ -709,7 +707,7 @@ export default function ClientPortalPage({
|
||||
</button>
|
||||
</div>
|
||||
{ver?.createdAt && (
|
||||
<p className="ml-auto text-xs text-zinc-600">
|
||||
<p className="ml-auto shrink-0 whitespace-nowrap text-xs text-zinc-600">
|
||||
{formatDate(ver.createdAt)}
|
||||
</p>
|
||||
)}
|
||||
@@ -718,19 +716,19 @@ export default function ClientPortalPage({
|
||||
href={ver ? `/client/${token}/review/${ver.id}` : '#'}
|
||||
onClick={handleReviewClick}
|
||||
className={cn(
|
||||
'flex items-center gap-4 p-4 rounded-xl border transition-all group',
|
||||
'flex flex-wrap sm:flex-nowrap items-center gap-x-4 gap-y-2 p-3 sm:p-4 rounded-xl border transition-all group',
|
||||
'bg-zinc-900 border-zinc-800 hover:border-zinc-600 hover:bg-zinc-800/70',
|
||||
!ver && 'pointer-events-none opacity-40',
|
||||
)}
|
||||
>
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="min-w-0 w-full sm:w-auto sm:flex-1">
|
||||
<div className="flex items-center gap-1.5">
|
||||
<p className="text-sm font-medium text-white">
|
||||
<p className="text-sm font-medium text-white min-w-0 break-words">
|
||||
{task.title}
|
||||
</p>
|
||||
<button
|
||||
onClick={(e) => { e.preventDefault(); e.stopPropagation(); copyToClipboard(task.title, `task-${task.id}`); }}
|
||||
className="shrink-0 p-0.5 rounded opacity-0 group-hover:opacity-100 text-zinc-600 hover:text-zinc-300 transition-all"
|
||||
className="hidden sm:block shrink-0 p-0.5 rounded opacity-0 group-hover:opacity-100 text-zinc-600 hover:text-zinc-300 transition-all"
|
||||
title="Copy task name"
|
||||
>
|
||||
{copiedId === `task-${task.id}` ? (
|
||||
@@ -759,7 +757,7 @@ export default function ClientPortalPage({
|
||||
No versions yet
|
||||
</span>
|
||||
)}
|
||||
<ChevronRight className="h-4 w-4 text-zinc-600 group-hover:text-zinc-400 shrink-0 transition-colors" />
|
||||
<ChevronRight className="h-4 w-4 text-zinc-600 group-hover:text-zinc-400 shrink-0 transition-colors ml-auto sm:ml-0" />
|
||||
</Link>
|
||||
</div>
|
||||
);
|
||||
@@ -888,19 +886,19 @@ export default function ClientPortalPage({
|
||||
href={ver ? `/client/${token}/review/${ver.id}` : '#'}
|
||||
onClick={handleReviewClick}
|
||||
className={cn(
|
||||
'flex items-center gap-4 p-4 rounded-xl border transition-all group',
|
||||
'flex flex-wrap sm:flex-nowrap items-center gap-x-4 gap-y-2 p-3 sm:p-4 rounded-xl border transition-all group',
|
||||
'bg-zinc-900 border-zinc-800 hover:border-zinc-600 hover:bg-zinc-800/70',
|
||||
!ver && 'pointer-events-none opacity-40',
|
||||
)}
|
||||
>
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="min-w-0 w-full sm:w-auto sm:flex-1">
|
||||
<div className="flex items-center gap-1.5">
|
||||
<p className="text-sm font-medium text-white">
|
||||
<p className="text-sm font-medium text-white min-w-0 break-words">
|
||||
{task.title}
|
||||
</p>
|
||||
<button
|
||||
onClick={(e) => { e.preventDefault(); e.stopPropagation(); copyToClipboard(task.title, `task-${task.id}`); }}
|
||||
className="shrink-0 p-0.5 rounded opacity-0 group-hover:opacity-100 text-zinc-600 hover:text-zinc-300 transition-all"
|
||||
className="hidden sm:block shrink-0 p-0.5 rounded opacity-0 group-hover:opacity-100 text-zinc-600 hover:text-zinc-300 transition-all"
|
||||
title="Copy task name"
|
||||
>
|
||||
{copiedId === `task-${task.id}` ? (
|
||||
@@ -936,7 +934,7 @@ export default function ClientPortalPage({
|
||||
No versions yet
|
||||
</span>
|
||||
)}
|
||||
<ChevronRight className="h-4 w-4 text-zinc-600 group-hover:text-zinc-400 shrink-0 transition-colors" />
|
||||
<ChevronRight className="h-4 w-4 text-zinc-600 group-hover:text-zinc-400 shrink-0 transition-colors ml-auto sm:ml-0" />
|
||||
</Link>
|
||||
);
|
||||
})}
|
||||
@@ -1007,7 +1005,7 @@ export default function ClientPortalPage({
|
||||
</p>
|
||||
<button
|
||||
onClick={(e) => { e.preventDefault(); e.stopPropagation(); copyToClipboard(task.title, `task-${task.id}`); }}
|
||||
className="shrink-0 p-0.5 rounded opacity-0 group-hover:opacity-100 text-zinc-600 hover:text-zinc-300 transition-all"
|
||||
className="hidden sm:block shrink-0 p-0.5 rounded opacity-0 group-hover:opacity-100 text-zinc-600 hover:text-zinc-300 transition-all"
|
||||
title="Copy task name"
|
||||
>
|
||||
{copiedId === `task-${task.id}` ? (
|
||||
|
||||
@@ -21,11 +21,14 @@ import {
|
||||
ArrowRight,
|
||||
RotateCcw,
|
||||
ImageIcon,
|
||||
Film,
|
||||
} from "lucide-react";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { useToast } from "@/components/ui/use-toast";
|
||||
import { PLATE_EXTS, plateContentType } from "@/lib/batch-upload-parser";
|
||||
import type { PreviewItem, PreviewItemStatus } from "@/app/api/batch-upload/preview/route";
|
||||
import type { ThumbnailPreviewItem } from "@/app/api/batch-upload/thumbnails/route";
|
||||
import type { PlatePreviewItem } from "@/app/api/batch-upload/plates/route";
|
||||
|
||||
interface Project {
|
||||
id: string;
|
||||
@@ -40,6 +43,12 @@ interface UploadState {
|
||||
error?: string;
|
||||
}
|
||||
|
||||
/** Footage plates are large, so they also carry per-file upload progress. */
|
||||
interface PlateUploadState extends UploadState {
|
||||
/** 0–1, only meaningful while status is "uploading" */
|
||||
progress?: number;
|
||||
}
|
||||
|
||||
interface BatchUploadClientProps {
|
||||
projects: Project[];
|
||||
}
|
||||
@@ -76,6 +85,25 @@ export function BatchUploadClient({ projects }: BatchUploadClientProps) {
|
||||
setThumbUploadComplete(false);
|
||||
};
|
||||
|
||||
// ── Footage plate upload state ─────────────────────────────────────────────
|
||||
const plateInputRef = useRef<HTMLInputElement>(null);
|
||||
const [plateFiles, setPlateFiles] = useState<File[]>([]);
|
||||
const [plateIsDragging, setPlateIsDragging] = useState(false);
|
||||
const [platePreview, setPlatePreview] = useState<PlatePreviewItem[] | null>(null);
|
||||
const [plateLoadingPreview, setPlateLoadingPreview] = useState(false);
|
||||
const [plateUploadStates, setPlateUploadStates] = useState<Record<string, PlateUploadState>>({});
|
||||
const [plateIsUploading, setPlateIsUploading] = useState(false);
|
||||
const [plateUploadComplete, setPlateUploadComplete] = useState(false);
|
||||
|
||||
const acceptPlate = (f: File) => PLATE_EXTS.has(f.name.split(".").pop()?.toLowerCase() ?? "");
|
||||
|
||||
const resetPlates = () => {
|
||||
setPlateFiles([]);
|
||||
setPlatePreview(null);
|
||||
setPlateUploadStates({});
|
||||
setPlateUploadComplete(false);
|
||||
};
|
||||
|
||||
const reset = () => {
|
||||
setFiles([]);
|
||||
setPreview(null);
|
||||
@@ -324,6 +352,136 @@ export function BatchUploadClient({ projects }: BatchUploadClientProps) {
|
||||
setThumbUploadComplete(true);
|
||||
};
|
||||
|
||||
// ── Footage plate handlers ─────────────────────────────────────────────────
|
||||
|
||||
const handlePlateDrop = useCallback((e: React.DragEvent) => {
|
||||
e.preventDefault();
|
||||
setPlateIsDragging(false);
|
||||
const dropped = Array.from(e.dataTransfer.files).filter(acceptPlate);
|
||||
if (dropped.length > 0) {
|
||||
setPlateFiles(dropped);
|
||||
setPlatePreview(null);
|
||||
setPlateUploadStates({});
|
||||
setPlateUploadComplete(false);
|
||||
} else {
|
||||
toast({
|
||||
title: "No supported files",
|
||||
description: "Only .mov, .mp4, .mxf, .avi, .mkv and .webm files are accepted.",
|
||||
});
|
||||
}
|
||||
}, [toast]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
|
||||
const handlePlateInput = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const selected = Array.from(e.target.files ?? []).filter(acceptPlate);
|
||||
if (selected.length > 0) {
|
||||
setPlateFiles(selected);
|
||||
setPlatePreview(null);
|
||||
setPlateUploadStates({});
|
||||
setPlateUploadComplete(false);
|
||||
}
|
||||
e.target.value = "";
|
||||
};
|
||||
|
||||
const fetchPlatePreview = async () => {
|
||||
if (!projectId || plateFiles.length === 0) return;
|
||||
setPlateLoadingPreview(true);
|
||||
try {
|
||||
const res = await fetch("/api/batch-upload/plates", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ projectId, fileNames: plateFiles.map((f) => f.name) }),
|
||||
});
|
||||
if (!res.ok) throw new Error("Preview failed");
|
||||
const data = await res.json();
|
||||
setPlatePreview(data.items);
|
||||
const states: Record<string, PlateUploadState> = {};
|
||||
for (const item of data.items as PlatePreviewItem[]) states[item.fileName] = { status: "pending" };
|
||||
setPlateUploadStates(states);
|
||||
} catch {
|
||||
toast({ title: "Preview failed", variant: "destructive" });
|
||||
} finally {
|
||||
setPlateLoadingPreview(false);
|
||||
}
|
||||
};
|
||||
|
||||
const startPlateUpload = async () => {
|
||||
if (!platePreview || !projectId) return;
|
||||
setPlateIsUploading(true);
|
||||
|
||||
const matched = platePreview.filter((i) => i.status === "match");
|
||||
|
||||
for (const item of matched) {
|
||||
const file = plateFiles.find((f) => f.name === item.fileName);
|
||||
if (!file) continue;
|
||||
|
||||
setPlateUploadStates((prev) => ({
|
||||
...prev,
|
||||
[item.fileName]: { status: "uploading", progress: 0 },
|
||||
}));
|
||||
|
||||
try {
|
||||
// Step 1 — presigned PUT URL. Plates are multi-GB, so the bytes go
|
||||
// straight to Hetzner and never touch this server or the proxy.
|
||||
const presignRes = await fetch("/api/upload/presign", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
fileName: file.name,
|
||||
contentType: plateContentType(file.name),
|
||||
folder: "videos",
|
||||
}),
|
||||
});
|
||||
if (!presignRes.ok) {
|
||||
const d = await presignRes.json().catch(() => ({ error: "Failed to get upload URL" }));
|
||||
throw new Error((d as { error?: string }).error ?? "Failed to get upload URL");
|
||||
}
|
||||
const { presignedUrl, key } = (await presignRes.json()) as {
|
||||
presignedUrl: string;
|
||||
key: string;
|
||||
};
|
||||
|
||||
// Step 2 — PUT directly to storage, tracking progress via XHR.
|
||||
await putWithProgress(presignedUrl, file, (fraction) => {
|
||||
setPlateUploadStates((prev) => ({
|
||||
...prev,
|
||||
[item.fileName]: { status: "uploading", progress: fraction },
|
||||
}));
|
||||
});
|
||||
|
||||
// Step 3 — commit the plate record against the matched shot.
|
||||
const commitRes = await fetch("/api/batch-upload/plates/upload", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
projectId,
|
||||
shotId: item.shotId,
|
||||
key,
|
||||
fileName: file.name,
|
||||
fileSize: file.size,
|
||||
label: item.label,
|
||||
}),
|
||||
});
|
||||
if (!commitRes.ok) {
|
||||
const d = await commitRes.json().catch(() => ({ error: "Failed to save plate" }));
|
||||
throw new Error((d as { error?: string }).error ?? "Failed to save plate");
|
||||
}
|
||||
|
||||
setPlateUploadStates((prev) => ({ ...prev, [item.fileName]: { status: "success" } }));
|
||||
} catch (err) {
|
||||
setPlateUploadStates((prev) => ({
|
||||
...prev,
|
||||
[item.fileName]: {
|
||||
status: "error",
|
||||
error: err instanceof Error ? err.message : "Upload failed",
|
||||
},
|
||||
}));
|
||||
}
|
||||
}
|
||||
|
||||
setPlateIsUploading(false);
|
||||
setPlateUploadComplete(true);
|
||||
};
|
||||
|
||||
// ── Derived counts ─────────────────────────────────────────────────────────
|
||||
|
||||
const uploadable = preview?.filter(
|
||||
@@ -359,7 +517,11 @@ export function BatchUploadClient({ projects }: BatchUploadClientProps) {
|
||||
value={projectId}
|
||||
onValueChange={(v) => {
|
||||
setProjectId(v);
|
||||
// Every preview is resolved against a specific project, so none
|
||||
// of them survive a project switch.
|
||||
reset();
|
||||
resetThumbs();
|
||||
resetPlates();
|
||||
}}
|
||||
>
|
||||
<SelectTrigger className="w-80 bg-zinc-800 border-zinc-700">
|
||||
@@ -735,12 +897,260 @@ export function BatchUploadClient({ projects }: BatchUploadClientProps) {
|
||||
</Card>
|
||||
);
|
||||
})()}
|
||||
|
||||
{/* ── Footage plate bulk upload ───────────────────────────────── */}
|
||||
<div className="border-t border-zinc-800 pt-2">
|
||||
<h2 className="text-base font-semibold text-white">Bulk Footage Plate Upload</h2>
|
||||
<p className="text-zinc-400 text-sm mt-1">
|
||||
Drop plate movies here to add them to a shot's Footage tab. The shot is taken
|
||||
from the start of the filename and the remainder becomes the plate label —{" "}
|
||||
<span className="text-zinc-300 font-mono text-xs">DH2_VFX_058_120_REF.mov</span>{" "}
|
||||
becomes the plate <span className="text-zinc-300">REF</span> on shot{" "}
|
||||
<span className="text-zinc-300 font-mono text-xs">DH2_VFX_058_120</span>.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Plate drop zone */}
|
||||
{!plateUploadComplete && (
|
||||
<Card>
|
||||
<CardContent className="pt-5">
|
||||
<div
|
||||
onDragOver={(e) => { e.preventDefault(); setPlateIsDragging(true); }}
|
||||
onDragLeave={() => setPlateIsDragging(false)}
|
||||
onDrop={handlePlateDrop}
|
||||
onClick={() => plateInputRef.current?.click()}
|
||||
className={cn(
|
||||
"border-2 border-dashed rounded-xl p-10 text-center cursor-pointer transition-colors select-none",
|
||||
plateIsDragging
|
||||
? "border-emerald-400 bg-emerald-400/5"
|
||||
: "border-zinc-700 hover:border-zinc-500 hover:bg-zinc-800/30"
|
||||
)}
|
||||
>
|
||||
<Film className="h-9 w-9 text-zinc-500 mx-auto mb-3" />
|
||||
<p className="text-zinc-300 font-medium">Drop footage plates here</p>
|
||||
<p className="text-zinc-500 text-sm mt-1">
|
||||
MOV, MP4, MXF, AVI, MKV, WebM · or click to browse
|
||||
</p>
|
||||
{plateFiles.length > 0 && (
|
||||
<p className="text-emerald-400 text-sm mt-3 font-medium">
|
||||
{plateFiles.length} file{plateFiles.length !== 1 ? "s" : ""} selected
|
||||
</p>
|
||||
)}
|
||||
<input
|
||||
ref={plateInputRef}
|
||||
type="file"
|
||||
multiple
|
||||
accept=".mov,.mp4,.m4v,.mxf,.avi,.mkv,.webm,video/*"
|
||||
className="hidden"
|
||||
onChange={handlePlateInput}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{plateFiles.length > 0 && !platePreview && (
|
||||
<div className="mt-4 flex items-center gap-3">
|
||||
<Button onClick={fetchPlatePreview} disabled={plateLoadingPreview}>
|
||||
{plateLoadingPreview ? (
|
||||
<><Loader2 className="h-4 w-4 mr-2 animate-spin" />Loading preview…</>
|
||||
) : (
|
||||
<>Preview<ChevronRight className="h-4 w-4 ml-2" /></>
|
||||
)}
|
||||
</Button>
|
||||
<Button variant="ghost" onClick={resetPlates} disabled={plateLoadingPreview}>Clear</Button>
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
{/* Plate preview table */}
|
||||
{platePreview && !plateUploadComplete && (() => {
|
||||
const matched = platePreview.filter((i) => i.status === "match");
|
||||
const skippedPlates = platePreview.filter((i) => i.status !== "match");
|
||||
const dupes = platePreview.filter((i) => i.status === "duplicate");
|
||||
const plateSuccess = Object.values(plateUploadStates).filter((s) => s.status === "success").length;
|
||||
const plateErrors = Object.values(plateUploadStates).filter((s) => s.status === "error").length;
|
||||
const plateDone = plateSuccess + plateErrors;
|
||||
const plateProgress = matched.length > 0 ? (plateDone / matched.length) * 100 : 0;
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader className="pb-0">
|
||||
<CardTitle className="text-base font-medium text-zinc-200">
|
||||
Footage plate preview —{" "}
|
||||
<span className="text-zinc-400 font-normal">
|
||||
{matched.length} matched · {skippedPlates.length} skipped
|
||||
</span>
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="p-0 mt-4">
|
||||
<div className="overflow-x-auto">
|
||||
<table className="w-full text-sm">
|
||||
<thead>
|
||||
<tr className="border-b border-zinc-800">
|
||||
<th className="text-left text-xs text-zinc-500 font-normal px-6 py-2.5">File</th>
|
||||
<th className="text-left text-xs text-zinc-500 font-normal px-6 py-2.5">Matched Shot</th>
|
||||
<th className="text-left text-xs text-zinc-500 font-normal px-6 py-2.5">Plate label</th>
|
||||
<th className="text-left text-xs text-zinc-500 font-normal px-4 py-2.5 w-32">Status</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="divide-y divide-zinc-800/60">
|
||||
{platePreview.map((item) => {
|
||||
const state = plateUploadStates[item.fileName];
|
||||
return (
|
||||
<tr key={item.fileName} className="hover:bg-zinc-800/30 transition-colors">
|
||||
<td className="px-6 py-3">
|
||||
<div className="flex items-center gap-2">
|
||||
<FileVideo className="h-4 w-4 text-zinc-500 shrink-0" />
|
||||
<span className="text-zinc-200 font-mono text-xs truncate max-w-[240px]">{item.fileName}</span>
|
||||
</div>
|
||||
</td>
|
||||
<td className="px-6 py-3">
|
||||
{item.shotCode ? (
|
||||
<span className="font-mono text-xs text-zinc-300">
|
||||
{item.shotCode}
|
||||
{item.existingPlateCount > 0 && (
|
||||
<span className="text-zinc-600 ml-1.5 font-sans">
|
||||
({item.existingPlateCount} plate{item.existingPlateCount !== 1 ? "s" : ""})
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
) : (
|
||||
<span className="text-xs text-zinc-600 italic">
|
||||
{item.status === "unsupported" ? "unsupported file" : "no match"}
|
||||
</span>
|
||||
)}
|
||||
</td>
|
||||
<td className="px-6 py-3">
|
||||
{item.status === "match" ? (
|
||||
<span className="text-zinc-300 text-xs">{item.label}</span>
|
||||
) : (
|
||||
<span className="text-zinc-700 text-xs">—</span>
|
||||
)}
|
||||
</td>
|
||||
<td className="px-4 py-3">
|
||||
{item.status === "duplicate" ? (
|
||||
<span className="flex items-center gap-1 text-xs text-zinc-500" title="This shot already has a plate with this filename">
|
||||
<XCircle className="h-3.5 w-3.5" />already added
|
||||
</span>
|
||||
) : item.status !== "match" ? (
|
||||
<span className="flex items-center gap-1 text-xs text-zinc-500"><XCircle className="h-3.5 w-3.5" />skip</span>
|
||||
) : !state || state.status === "pending" ? (
|
||||
<span className="flex items-center gap-1 text-xs text-emerald-400"><ArrowRight className="h-3.5 w-3.5" />add plate</span>
|
||||
) : state.status === "uploading" ? (
|
||||
<span className="flex items-center gap-1 text-xs text-amber-400">
|
||||
<Loader2 className="h-3.5 w-3.5 animate-spin" />
|
||||
{Math.round((state.progress ?? 0) * 100)}%
|
||||
</span>
|
||||
) : state.status === "success" ? (
|
||||
<span className="flex items-center gap-1 text-xs text-emerald-400"><CheckCircle2 className="h-3.5 w-3.5" />done</span>
|
||||
) : (
|
||||
<span className="flex items-center gap-1 text-xs text-red-400" title={state.error}><XCircle className="h-3.5 w-3.5" />error</span>
|
||||
)}
|
||||
</td>
|
||||
</tr>
|
||||
);
|
||||
})}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
{plateIsUploading && (
|
||||
<div className="px-6 py-3 border-t border-zinc-800">
|
||||
<div className="flex justify-between text-xs text-zinc-400 mb-1.5">
|
||||
<span>Uploading {Math.min(plateDone + 1, matched.length)} of {matched.length}…</span>
|
||||
<span>{Math.round(plateProgress)}%</span>
|
||||
</div>
|
||||
<Progress value={plateProgress} className="h-1.5" />
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="px-6 py-4 border-t border-zinc-800 flex items-center justify-between gap-4">
|
||||
<p className="text-zinc-500 text-xs">
|
||||
{matched.length} plate{matched.length !== 1 ? "s" : ""} will be added
|
||||
{skippedPlates.length > 0 && (
|
||||
<span className="text-zinc-600">
|
||||
{" "}· {skippedPlates.length} skipped
|
||||
{dupes.length > 0 && ` (${dupes.length} already uploaded)`}
|
||||
</span>
|
||||
)}
|
||||
</p>
|
||||
<div className="flex gap-3 shrink-0">
|
||||
<Button variant="ghost" size="sm" onClick={resetPlates} disabled={plateIsUploading}>Change files</Button>
|
||||
<Button size="sm" onClick={startPlateUpload} disabled={plateIsUploading || matched.length === 0}>
|
||||
{plateIsUploading ? (
|
||||
<><Loader2 className="h-4 w-4 mr-2 animate-spin" />Uploading…</>
|
||||
) : (
|
||||
`Upload ${matched.length} plate${matched.length !== 1 ? "s" : ""}`
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
})()}
|
||||
|
||||
{/* Plate done summary */}
|
||||
{plateUploadComplete && (() => {
|
||||
const plateSuccess = Object.values(plateUploadStates).filter((s) => s.status === "success").length;
|
||||
const plateErrors = Object.values(plateUploadStates).filter((s) => s.status === "error").length;
|
||||
return (
|
||||
<Card>
|
||||
<CardContent className="pt-8 pb-8 flex flex-col items-center gap-4 text-center">
|
||||
<CheckCircle2 className="h-12 w-12 text-green-500" />
|
||||
<div>
|
||||
<p className="text-white font-semibold text-lg">Footage plates uploaded</p>
|
||||
<p className="text-zinc-400 text-sm mt-1">
|
||||
{plateSuccess} added{plateErrors > 0 && <span className="text-red-400"> · {plateErrors} failed</span>}
|
||||
</p>
|
||||
</div>
|
||||
<Button variant="outline" onClick={resetPlates} className="mt-2">
|
||||
<RotateCcw className="h-4 w-4 mr-2" />Upload more plates
|
||||
</Button>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
})()}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// ── Helpers ────────────────────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* PUT a file to a presigned storage URL, reporting upload progress.
|
||||
*
|
||||
* `fetch` gives no upload progress, and footage plates are big enough that a
|
||||
* silent multi-minute wait per file is unusable — hence XHR.
|
||||
*/
|
||||
function putWithProgress(
|
||||
url: string,
|
||||
file: File,
|
||||
onProgress: (fraction: number) => void
|
||||
): Promise<void> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const xhr = new XMLHttpRequest();
|
||||
xhr.open("PUT", url);
|
||||
xhr.setRequestHeader("Content-Type", plateContentType(file.name));
|
||||
|
||||
xhr.upload.addEventListener("progress", (e) => {
|
||||
if (e.lengthComputable) onProgress(e.loaded / e.total);
|
||||
});
|
||||
|
||||
xhr.addEventListener("load", () => {
|
||||
if (xhr.status >= 200 && xhr.status < 300) resolve();
|
||||
else if (xhr.status === 403)
|
||||
reject(new Error("Storage upload failed — check Hetzner CORS / bucket policy"));
|
||||
else reject(new Error(`Storage upload failed (HTTP ${xhr.status})`));
|
||||
});
|
||||
|
||||
xhr.addEventListener("error", () => reject(new Error("Network error")));
|
||||
xhr.addEventListener("abort", () => reject(new Error("Upload aborted")));
|
||||
xhr.send(file);
|
||||
});
|
||||
}
|
||||
|
||||
// ── Sub-components ─────────────────────────────────────────────────────────────
|
||||
|
||||
function PreviewRow({
|
||||
|
||||
@@ -0,0 +1,110 @@
|
||||
import Link from "next/link";
|
||||
import { formatDistanceToNowStrict } from "date-fns";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { EXPORT_STATUS_STYLES, statusLabel } from "@/app/(dashboard)/pipeline/status-colors";
|
||||
import type { BlockedExport } from "@/lib/dashboard/ops";
|
||||
|
||||
/**
|
||||
* The exception list: exports that have stopped moving and need a person.
|
||||
*
|
||||
* Read by scanning down the left edge — the severity rail says which rows are
|
||||
* dead in the water (a failed state, which nothing retries) versus merely
|
||||
* overdue (still nominally in flight, or waiting on a QC pass). The reason
|
||||
* column exists so the answer to "what happened" doesn't require opening
|
||||
* anything.
|
||||
*/
|
||||
export function BlockedQueue({ blocked }: { blocked: BlockedExport[] }) {
|
||||
const critical = blocked.filter((b) => b.severity === "critical").length;
|
||||
|
||||
return (
|
||||
<div className="rounded-lg border border-zinc-800 bg-card overflow-hidden">
|
||||
<div className="flex items-center justify-between gap-3 border-b border-zinc-800/60 px-4 py-3">
|
||||
<h3 className="text-sm font-semibold text-white">
|
||||
{blocked.length === 0
|
||||
? "Nothing blocked"
|
||||
: `${blocked.length} export${blocked.length === 1 ? "" : "s"} stalled`}
|
||||
{critical > 0 && (
|
||||
<span className="ml-2 text-xs font-normal text-red-400">{critical} failed</span>
|
||||
)}
|
||||
</h3>
|
||||
<Link href="/pipeline" className="text-xs text-zinc-400 hover:text-amber-400">
|
||||
Open render queue →
|
||||
</Link>
|
||||
</div>
|
||||
|
||||
{blocked.length === 0 ? (
|
||||
<p className="px-4 py-10 text-center text-sm text-zinc-500">
|
||||
Every export is either moving or done.
|
||||
</p>
|
||||
) : (
|
||||
<div className="overflow-x-auto">
|
||||
<table className="w-full text-sm">
|
||||
<thead>
|
||||
<tr className="border-b border-zinc-800 bg-zinc-900/60 text-left text-xs text-zinc-400">
|
||||
<th className="w-[3px] p-0" />
|
||||
<th className="px-4 py-2.5 font-medium">Shot</th>
|
||||
<th className="px-4 py-2.5 font-medium">Status</th>
|
||||
<th className="px-4 py-2.5 font-medium whitespace-nowrap">Stuck</th>
|
||||
<th className="px-4 py-2.5 font-medium">Why</th>
|
||||
<th className="px-4 py-2.5 font-medium">Artist</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{blocked.map((b) => (
|
||||
<tr key={b.exportId} className="border-b border-zinc-800/60 hover:bg-zinc-900/40">
|
||||
<td className="w-[3px] p-0">
|
||||
<div
|
||||
className={cn(
|
||||
"h-9 w-[3px]",
|
||||
b.severity === "critical" ? "bg-red-500" : "bg-amber-500"
|
||||
)}
|
||||
/>
|
||||
</td>
|
||||
<td className="px-4 py-2.5">
|
||||
<Link
|
||||
href={`/pipeline/exports/${b.exportId}`}
|
||||
className="font-mono text-[13px] font-medium text-white hover:text-amber-400"
|
||||
>
|
||||
{b.shotCode}{" "}
|
||||
<span className="text-zinc-500">{b.versionString}</span>
|
||||
</Link>
|
||||
<div className="text-xs text-zinc-500">
|
||||
{b.projectCode}
|
||||
{b.episode ? ` · ep ${b.episode}` : ""}
|
||||
</div>
|
||||
</td>
|
||||
<td className="px-4 py-2.5">
|
||||
<span
|
||||
className={cn(
|
||||
"inline-block rounded-full border px-2 py-0.5 text-xs whitespace-nowrap",
|
||||
EXPORT_STATUS_STYLES[b.status] ?? "bg-zinc-500/15 text-zinc-300 border-zinc-500/30"
|
||||
)}
|
||||
>
|
||||
{statusLabel(b.status)}
|
||||
</span>
|
||||
</td>
|
||||
<td
|
||||
className={cn(
|
||||
"px-4 py-2.5 tabular-nums whitespace-nowrap",
|
||||
b.severity === "critical" ? "text-red-400" : "text-zinc-300"
|
||||
)}
|
||||
>
|
||||
{formatDistanceToNowStrict(b.since)}
|
||||
</td>
|
||||
{/* The reason can be an aerender error several lines long;
|
||||
it is clamped here and given in full on hover. */}
|
||||
<td className="px-4 py-2.5 text-zinc-400 max-w-md" title={b.reason}>
|
||||
<span className="line-clamp-2">{b.reason}</span>
|
||||
</td>
|
||||
<td className="px-4 py-2.5 text-zinc-300 whitespace-nowrap">
|
||||
{b.artistName ?? "—"}
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
import Link from "next/link";
|
||||
import { format } from "date-fns";
|
||||
import { cn } from "@/lib/utils";
|
||||
import type { CountdownVerdict, EpisodeCountdown } from "@/lib/dashboard/ops";
|
||||
|
||||
/**
|
||||
* Are we going to make the date? One card per episode, sorted by how soon.
|
||||
*
|
||||
* The bar is the episode's shots by where they actually are, and the row under
|
||||
* it is the only comparison that matters: shots per day still needed against
|
||||
* shots per day the studio has managed this week.
|
||||
*/
|
||||
|
||||
const VERDICT: Record<CountdownVerdict, { rail: string; chip: string; label: string }> = {
|
||||
overdue: { rail: "bg-red-500", chip: "text-red-400 bg-red-500/10", label: "Overdue" },
|
||||
behind: { rail: "bg-red-500", chip: "text-red-400 bg-red-500/10", label: "Behind" },
|
||||
stalled: { rail: "bg-red-500", chip: "text-red-400 bg-red-500/10", label: "Nothing delivered this week" },
|
||||
tight: { rail: "bg-amber-500", chip: "text-amber-400 bg-amber-500/10", label: "No slack" },
|
||||
ahead: { rail: "bg-green-500", chip: "text-green-400 bg-green-500/10", label: "On track" },
|
||||
complete: { rail: "bg-emerald-500", chip: "text-emerald-400 bg-emerald-500/10", label: "All delivered" },
|
||||
};
|
||||
|
||||
/** Two decimals is false precision for a shot count; one is the real resolution. */
|
||||
const perDay = (n: number) => n.toFixed(1);
|
||||
|
||||
export function DeliveryCountdown({ episodes }: { episodes: EpisodeCountdown[] }) {
|
||||
if (episodes.length === 0) {
|
||||
return (
|
||||
<div className="rounded-lg border border-zinc-800 bg-card px-4 py-8 text-center text-sm text-zinc-500">
|
||||
No delivery dates set. Add them on a project's Episodes tab to see the countdown here.
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="grid gap-4 grid-cols-1 md:grid-cols-2 xl:grid-cols-3">
|
||||
{episodes.map((ep) => {
|
||||
const verdict = VERDICT[ep.verdict];
|
||||
const pct = (n: number) => (ep.total === 0 ? 0 : (n / ep.total) * 100);
|
||||
|
||||
return (
|
||||
<Link
|
||||
key={`${ep.projectId}:${ep.episode ?? ""}`}
|
||||
href={`/shot-status?projectId=${ep.projectId}`}
|
||||
className="group relative flex flex-col gap-3.5 overflow-hidden rounded-lg border border-zinc-800 bg-card p-4 pl-[18px] transition-colors hover:border-zinc-700 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-amber-500"
|
||||
>
|
||||
{/* Severity rail — the card itself stays neutral so only the
|
||||
episode in trouble pulls the eye. */}
|
||||
<span className={cn("absolute inset-y-0 left-0 w-[3px]", verdict.rail)} aria-hidden="true" />
|
||||
|
||||
<div className="flex items-start justify-between gap-3">
|
||||
<div className="min-w-0">
|
||||
<div className="truncate text-[15px] font-semibold text-white">
|
||||
{ep.projectCode}
|
||||
{ep.episode && <span className="font-normal text-zinc-500"> · ep {ep.episode}</span>}
|
||||
</div>
|
||||
<div className="mt-0.5 text-xs text-zinc-400">
|
||||
Due {format(ep.dueDate, "EEE d MMM yyyy")}
|
||||
</div>
|
||||
</div>
|
||||
<div className="shrink-0 text-right">
|
||||
<b className="block text-3xl font-bold leading-none tabular-nums text-white">
|
||||
{Math.abs(ep.daysLeft)}
|
||||
</b>
|
||||
<small className="text-[11px] uppercase tracking-wide text-zinc-500">
|
||||
{ep.daysLeft < 0 ? "days over" : "days left"}
|
||||
</small>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<div
|
||||
className="flex h-2 overflow-hidden rounded-full bg-zinc-800"
|
||||
role="img"
|
||||
aria-label={`${ep.delivered} of ${ep.total} shots delivered, ${ep.inQc} through QC, ${ep.inProgress} in progress`}
|
||||
>
|
||||
<i className="block h-full bg-emerald-500" style={{ width: `${pct(ep.delivered)}%` }} />
|
||||
<i className="block h-full bg-amber-500" style={{ width: `${pct(ep.inQc)}%` }} />
|
||||
<i className="block h-full bg-blue-500" style={{ width: `${pct(ep.inProgress)}%` }} />
|
||||
</div>
|
||||
<div className="mt-2 flex flex-wrap gap-x-3 gap-y-1 text-xs text-zinc-400">
|
||||
<span className="inline-flex items-center gap-1.5">
|
||||
<i className="h-2 w-2 rounded-sm bg-emerald-500" /> {ep.delivered} delivered
|
||||
</span>
|
||||
<span className="inline-flex items-center gap-1.5">
|
||||
<i className="h-2 w-2 rounded-sm bg-amber-500" /> {ep.inQc} in QC
|
||||
</span>
|
||||
<span className="inline-flex items-center gap-1.5">
|
||||
<i className="h-2 w-2 rounded-sm bg-blue-500" /> {ep.inProgress} in progress
|
||||
</span>
|
||||
<span className="inline-flex items-center gap-1.5">
|
||||
<i className="h-2 w-2 rounded-sm bg-zinc-700" /> {ep.notStarted} not started
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center justify-between gap-3 border-t border-zinc-800/60 pt-3">
|
||||
<div>
|
||||
<div className="text-[11px] text-zinc-500">Needed / day</div>
|
||||
<div className="font-mono text-[15px] tabular-nums text-white">
|
||||
{perDay(ep.requiredPerDay)}
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<div className="text-[11px] text-zinc-500">Last 7 days</div>
|
||||
<div className="font-mono text-[15px] tabular-nums text-white">
|
||||
{perDay(ep.actualPerDay)}
|
||||
</div>
|
||||
</div>
|
||||
<span className={cn("rounded-full px-2.5 py-1 text-xs font-semibold", verdict.chip)}>
|
||||
{ep.verdict === "behind" && ep.daysBehind
|
||||
? `${ep.daysBehind} day${ep.daysBehind === 1 ? "" : "s"} behind`
|
||||
: ep.verdict === "overdue" && ep.daysBehind
|
||||
? `${ep.daysBehind} day${ep.daysBehind === 1 ? "" : "s"} over`
|
||||
: verdict.label}
|
||||
</span>
|
||||
</div>
|
||||
</Link>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
import Link from "next/link";
|
||||
import { formatDistanceToNowStrict } from "date-fns";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { formatEta } from "@/app/(dashboard)/pipeline/status-colors";
|
||||
import type { FarmStatus } from "@/lib/dashboard/ops";
|
||||
|
||||
/**
|
||||
* Farm health: who is up, what is waiting, and who is running an old worker.
|
||||
*
|
||||
* The version row is not trivia — a worker's version is what decides whether
|
||||
* it has a given fix, and a machine that quietly stayed behind keeps producing
|
||||
* the bug everyone else has stopped seeing.
|
||||
*/
|
||||
export function FarmStrip({ farm }: { farm: FarmStatus }) {
|
||||
return (
|
||||
<div className="rounded-lg border border-zinc-800 bg-card overflow-hidden">
|
||||
<div className="flex items-center justify-between gap-3 border-b border-zinc-800/60 px-4 py-3">
|
||||
<h3 className="text-sm font-semibold text-white">
|
||||
{farm.online} of {farm.total} online
|
||||
</h3>
|
||||
<Link href="/pipeline/machines" className="text-xs text-zinc-400 hover:text-amber-400">
|
||||
Machines →
|
||||
</Link>
|
||||
</div>
|
||||
|
||||
{farm.machines.length === 0 ? (
|
||||
<p className="px-4 py-8 text-center text-sm text-zinc-500">
|
||||
No machines have registered yet.
|
||||
</p>
|
||||
) : (
|
||||
farm.machines.map((m) => (
|
||||
<div
|
||||
key={m.id}
|
||||
className="flex items-center gap-3 border-b border-zinc-800/60 px-4 py-2.5 last:border-b-0"
|
||||
>
|
||||
<span
|
||||
className={cn(
|
||||
"h-2 w-2 shrink-0 rounded-full",
|
||||
m.status === "ONLINE"
|
||||
? "bg-green-500 ring-4 ring-green-500/15"
|
||||
: m.status === "DISABLED"
|
||||
? "bg-zinc-600"
|
||||
: "bg-zinc-500"
|
||||
)}
|
||||
title={m.status}
|
||||
/>
|
||||
<span className="w-24 shrink-0 font-mono text-[12.5px] text-white">{m.name}</span>
|
||||
<span className="min-w-0 flex-1 truncate text-[12.5px] text-zinc-400">
|
||||
{m.currentJob
|
||||
? `${m.currentJob.shotCode ?? "job"} ${m.currentJob.versionString ?? ""} · ${Math.round(
|
||||
(m.currentJob.progress ?? 0) * 100
|
||||
)}% · ETA ${formatEta(m.currentJob.etaSeconds)}`
|
||||
: m.status === "ONLINE"
|
||||
? "Idle"
|
||||
: m.lastSeenAt
|
||||
? `Offline · last seen ${formatDistanceToNowStrict(new Date(m.lastSeenAt))} ago`
|
||||
: "Never seen"}
|
||||
</span>
|
||||
<span
|
||||
className={cn(
|
||||
"shrink-0 font-mono text-[11.5px]",
|
||||
farm.latestWorkerVersion && m.workerVersion !== farm.latestWorkerVersion
|
||||
? "text-amber-400"
|
||||
: "text-zinc-500"
|
||||
)}
|
||||
>
|
||||
{m.workerVersion ?? "—"}
|
||||
</span>
|
||||
</div>
|
||||
))
|
||||
)}
|
||||
|
||||
<div className="grid grid-cols-3 border-t border-zinc-800/60">
|
||||
<div className="border-r border-zinc-800/60 px-4 py-2.5">
|
||||
<b className="block font-mono text-lg font-semibold leading-tight text-white">
|
||||
{farm.queued.render}
|
||||
</b>
|
||||
<small className="text-xs text-zinc-500">renders queued</small>
|
||||
</div>
|
||||
<div className="border-r border-zinc-800/60 px-4 py-2.5">
|
||||
<b className="block font-mono text-lg font-semibold leading-tight text-white">
|
||||
{farm.queued.preview}
|
||||
</b>
|
||||
<small className="text-xs text-zinc-500">previews queued</small>
|
||||
</div>
|
||||
<div className="px-4 py-2.5">
|
||||
<b className="block font-mono text-lg font-semibold leading-tight text-white">
|
||||
{farm.oldestQueuedMs == null
|
||||
? "—"
|
||||
: formatDistanceToNowStrict(new Date(Date.now() - farm.oldestQueuedMs))}
|
||||
</b>
|
||||
<small className="text-xs text-zinc-500">oldest wait</small>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{farm.behindMachines.length > 0 && (
|
||||
<div className="flex gap-2 border-t border-amber-500/20 bg-amber-500/[0.07] px-4 py-2.5 text-xs text-amber-400">
|
||||
<span aria-hidden="true">▲</span>
|
||||
<span>
|
||||
{farm.behindMachines.length} machine
|
||||
{farm.behindMachines.length === 1 ? " is" : "s are"} behind{" "}
|
||||
<span className="font-mono">{farm.latestWorkerVersion}</span> —{" "}
|
||||
{farm.behindMachines
|
||||
.map((m) => `${m.name} (${m.workerVersion ?? "unknown"})`)
|
||||
.join(", ")}
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
import Link from "next/link";
|
||||
import { formatDistanceToNowStrict } from "date-fns";
|
||||
import { cn } from "@/lib/utils";
|
||||
import type { QcQueueEntry } from "@/lib/dashboard/ops";
|
||||
|
||||
/**
|
||||
* What is waiting on someone to watch the frames, oldest first.
|
||||
*
|
||||
* Everything upstream of QC is worked by the farm; this is the one stage that
|
||||
* only drains when a person sits down to it, which is why depth here is worth
|
||||
* a panel of its own rather than a filter on the queue page.
|
||||
*/
|
||||
export function QcQueue({ entries, staleHours }: { entries: QcQueueEntry[]; staleHours: number }) {
|
||||
const oldest = entries[0];
|
||||
|
||||
return (
|
||||
<div className="rounded-lg border border-zinc-800 bg-card overflow-hidden">
|
||||
<div className="flex items-center justify-between gap-3 border-b border-zinc-800/60 px-4 py-3">
|
||||
<h3 className="text-sm font-semibold text-white">
|
||||
{entries.length === 0
|
||||
? "QC queue empty"
|
||||
: `${entries.length} waiting on QC`}
|
||||
{oldest && (
|
||||
<span className="ml-2 text-xs font-normal text-zinc-500">
|
||||
oldest {formatDistanceToNowStrict(oldest.since)}
|
||||
</span>
|
||||
)}
|
||||
</h3>
|
||||
<Link
|
||||
href="/pipeline?status=READY_FOR_QC"
|
||||
className="text-xs text-zinc-400 hover:text-amber-400"
|
||||
>
|
||||
Open QC →
|
||||
</Link>
|
||||
</div>
|
||||
|
||||
{entries.length === 0 ? (
|
||||
<p className="px-4 py-10 text-center text-sm text-zinc-500">
|
||||
Nothing is waiting on a QC pass.
|
||||
</p>
|
||||
) : (
|
||||
<div className="overflow-x-auto">
|
||||
<table className="w-full text-sm">
|
||||
<thead>
|
||||
<tr className="border-b border-zinc-800 bg-zinc-900/60 text-left text-xs text-zinc-400">
|
||||
<th className="px-4 py-2.5 font-medium">Shot</th>
|
||||
<th className="px-4 py-2.5 font-medium">Version</th>
|
||||
<th className="px-4 py-2.5 font-medium">Waiting</th>
|
||||
<th className="px-4 py-2.5 font-medium">Frames</th>
|
||||
<th className="px-4 py-2.5 font-medium">Submitted by</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{entries.map((e) => {
|
||||
const stale = Date.now() - e.since.getTime() > staleHours * 3600_000;
|
||||
return (
|
||||
<tr key={e.exportId} className="border-b border-zinc-800/60 hover:bg-zinc-900/40">
|
||||
<td className="px-4 py-2.5">
|
||||
<Link
|
||||
href={`/pipeline/exports/${e.exportId}`}
|
||||
className="font-mono text-[13px] font-medium text-white hover:text-amber-400"
|
||||
>
|
||||
{e.shotCode}
|
||||
</Link>
|
||||
<div className="text-xs text-zinc-500">
|
||||
{e.projectCode}
|
||||
{e.episode ? ` · ep ${e.episode}` : ""}
|
||||
</div>
|
||||
</td>
|
||||
<td className="px-4 py-2.5 font-mono text-[13px] text-zinc-300">
|
||||
{e.versionString}
|
||||
</td>
|
||||
<td
|
||||
className={cn(
|
||||
"px-4 py-2.5 tabular-nums whitespace-nowrap",
|
||||
stale ? "text-amber-400" : "text-zinc-300"
|
||||
)}
|
||||
>
|
||||
{formatDistanceToNowStrict(e.since)}
|
||||
</td>
|
||||
<td className="px-4 py-2.5 font-mono text-[13px] tabular-nums text-zinc-400 whitespace-nowrap">
|
||||
{e.frameStart}–{e.frameEnd}
|
||||
</td>
|
||||
<td className="px-4 py-2.5 text-zinc-300 whitespace-nowrap">
|
||||
{e.submittedBy ?? "—"}
|
||||
</td>
|
||||
</tr>
|
||||
);
|
||||
})}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
import Link from "next/link";
|
||||
import { formatDistanceToNowStrict } from "date-fns";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { DELIVERY_STATUS_STYLES } from "@/app/(dashboard)/pipeline/status-colors";
|
||||
import type { DeliverySummary } from "@/lib/dashboard/ops";
|
||||
|
||||
/**
|
||||
* The last few packages, and whether any of them went wrong.
|
||||
*
|
||||
* A failed build is otherwise silent — the exports stay READY_FOR_DELIVERY and
|
||||
* nothing reaches the delivery volume, but no one finds out until the client
|
||||
* asks where the shots are.
|
||||
*/
|
||||
export function RecentDeliveries({ deliveries }: { deliveries: DeliverySummary[] }) {
|
||||
const problems = deliveries.filter((d) => d.status === "FAILED" || d.stuck).length;
|
||||
|
||||
return (
|
||||
<div className="rounded-lg border border-zinc-800 bg-card overflow-hidden">
|
||||
<div className="flex items-center justify-between gap-3 border-b border-zinc-800/60 px-4 py-3">
|
||||
<h3 className="text-sm font-semibold text-white">
|
||||
Recent packages
|
||||
{problems > 0 && (
|
||||
<span className="ml-2 text-xs font-normal text-red-400">
|
||||
{problems} need{problems === 1 ? "s" : ""} attention
|
||||
</span>
|
||||
)}
|
||||
</h3>
|
||||
<Link href="/pipeline/deliveries" className="text-xs text-zinc-400 hover:text-amber-400">
|
||||
All deliveries →
|
||||
</Link>
|
||||
</div>
|
||||
|
||||
{deliveries.length === 0 ? (
|
||||
<p className="px-4 py-8 text-center text-sm text-zinc-500">No packages built yet.</p>
|
||||
) : (
|
||||
deliveries.map((d) => (
|
||||
<Link
|
||||
key={d.id}
|
||||
href="/pipeline/deliveries"
|
||||
className="flex items-center gap-3 border-b border-zinc-800/60 px-4 py-2.5 last:border-b-0 hover:bg-zinc-900/40"
|
||||
>
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="truncate text-[13px] text-white">
|
||||
<span className="font-mono font-medium">#{d.packageNumber}</span>{" "}
|
||||
<span className="text-zinc-500">
|
||||
{d.projectCode}
|
||||
{d.episode ? ` · ${d.episode}` : ""}
|
||||
{d.kind === "MOV_REVIEW" ? " · review" : ""}
|
||||
</span>
|
||||
</div>
|
||||
<div className="truncate text-xs text-zinc-500" title={d.errorMessage ?? undefined}>
|
||||
{d.status === "FAILED" && d.errorMessage
|
||||
? d.errorMessage
|
||||
: `${d.itemCount} shot${d.itemCount === 1 ? "" : "s"} · ${d.atLabel} ${formatDistanceToNowStrict(d.at)} ago`}
|
||||
</div>
|
||||
</div>
|
||||
<span
|
||||
className={cn(
|
||||
"shrink-0 rounded-full border px-2 py-0.5 text-xs whitespace-nowrap",
|
||||
// A build that never finished reads as a problem, not as work
|
||||
// still in progress.
|
||||
d.stuck
|
||||
? "bg-red-500/15 text-red-400 border-red-500/30"
|
||||
: DELIVERY_STATUS_STYLES[d.status] ?? "bg-zinc-500/15 text-zinc-300 border-zinc-500/30"
|
||||
)}
|
||||
>
|
||||
{d.stuck ? "STUCK" : d.status}
|
||||
</span>
|
||||
</Link>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,12 +1,11 @@
|
||||
"use client";
|
||||
|
||||
import Link from "next/link";
|
||||
import { Card, CardContent } from "@/components/ui/card";
|
||||
import { cn } from "@/lib/utils";
|
||||
import {
|
||||
Clock,
|
||||
AlertCircle,
|
||||
CheckCircle2,
|
||||
XCircle,
|
||||
AlertTriangle,
|
||||
ClipboardCheck,
|
||||
PackageCheck,
|
||||
Eye,
|
||||
TrendingUp,
|
||||
} from "lucide-react";
|
||||
import type { DashboardStats } from "@/types";
|
||||
@@ -15,47 +14,54 @@ interface StatsCardsProps {
|
||||
stats: DashboardStats;
|
||||
}
|
||||
|
||||
/**
|
||||
* Five numbers that can go down. Each one links to the page that lists what it
|
||||
* counts — a figure with no way through to the rows behind it is wallpaper.
|
||||
*/
|
||||
export function StatsCards({ stats }: StatsCardsProps) {
|
||||
const cards = [
|
||||
{
|
||||
label: "Awaiting Review",
|
||||
value: stats.awaitingReview,
|
||||
icon: Clock,
|
||||
color: "text-amber-400",
|
||||
bg: "bg-amber-500/10",
|
||||
ring: "ring-amber-500/20",
|
||||
},
|
||||
{
|
||||
label: "Needs Revisions",
|
||||
value: stats.needsRevisions,
|
||||
icon: AlertCircle,
|
||||
color: "text-orange-400",
|
||||
bg: "bg-orange-500/10",
|
||||
ring: "ring-orange-500/20",
|
||||
},
|
||||
{
|
||||
label: "Approved",
|
||||
value: stats.approved,
|
||||
icon: CheckCircle2,
|
||||
color: "text-emerald-400",
|
||||
bg: "bg-emerald-500/10",
|
||||
ring: "ring-emerald-500/20",
|
||||
},
|
||||
{
|
||||
label: "Overdue Tasks",
|
||||
value: stats.tasksOverdue ?? stats.overdue,
|
||||
icon: XCircle,
|
||||
label: "Blocked",
|
||||
value: stats.blocked,
|
||||
href: "#blocked",
|
||||
icon: AlertTriangle,
|
||||
color: "text-red-400",
|
||||
bg: "bg-red-500/10",
|
||||
ring: "ring-red-500/20",
|
||||
// The only card that earns emphasis when it is non-zero: everything else
|
||||
// here is a queue depth, this one is work that has stopped.
|
||||
emphasise: stats.blocked > 0,
|
||||
},
|
||||
{
|
||||
label: "Active Projects",
|
||||
value: stats.activeProjects,
|
||||
icon: TrendingUp,
|
||||
label: "In QC",
|
||||
value: stats.inQc,
|
||||
href: "/pipeline?status=READY_FOR_QC",
|
||||
icon: ClipboardCheck,
|
||||
color: "text-amber-400",
|
||||
bg: "bg-amber-500/10",
|
||||
},
|
||||
{
|
||||
label: "Ready to deliver",
|
||||
value: stats.readyToDeliver,
|
||||
href: "/pipeline/deliveries",
|
||||
icon: PackageCheck,
|
||||
color: "text-green-400",
|
||||
bg: "bg-green-500/10",
|
||||
},
|
||||
{
|
||||
label: "With the client",
|
||||
value: stats.awaitingClientReview,
|
||||
href: "/playlist",
|
||||
icon: Eye,
|
||||
color: "text-blue-400",
|
||||
bg: "bg-blue-500/10",
|
||||
ring: "ring-blue-500/20",
|
||||
},
|
||||
{
|
||||
label: "Active projects",
|
||||
value: stats.activeProjects,
|
||||
href: "/projects",
|
||||
icon: TrendingUp,
|
||||
color: "text-zinc-400",
|
||||
bg: "bg-zinc-500/10",
|
||||
},
|
||||
];
|
||||
|
||||
@@ -64,19 +70,31 @@ export function StatsCards({ stats }: StatsCardsProps) {
|
||||
{cards.map((card) => {
|
||||
const Icon = card.icon;
|
||||
return (
|
||||
<Card key={card.label}>
|
||||
<CardContent className="p-4">
|
||||
<div className="flex items-center justify-between mb-3">
|
||||
<div className={cn("p-2 rounded-md", card.bg)}>
|
||||
<Icon className={cn("h-4 w-4", card.color)} />
|
||||
<Link key={card.label} href={card.href} className="group rounded-lg focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-amber-500">
|
||||
<Card
|
||||
className={cn(
|
||||
"h-full transition-colors group-hover:border-zinc-700",
|
||||
card.emphasise && "border-red-500/40"
|
||||
)}
|
||||
>
|
||||
<CardContent className="p-4">
|
||||
<div className="flex items-center justify-between mb-3">
|
||||
<div className={cn("p-2 rounded-md", card.bg)}>
|
||||
<Icon className={cn("h-4 w-4", card.color)} />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<p className="text-3xl font-bold text-white">
|
||||
{card.value}
|
||||
</p>
|
||||
<p className="text-sm text-zinc-400 mt-0.5">{card.label}</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
<p
|
||||
className={cn(
|
||||
"text-3xl font-bold tabular-nums",
|
||||
card.emphasise ? "text-red-400" : "text-white"
|
||||
)}
|
||||
>
|
||||
{card.value}
|
||||
</p>
|
||||
<p className="text-sm text-zinc-400 mt-0.5">{card.label}</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</Link>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
import Link from "next/link";
|
||||
import type { WhoseCourt as WhoseCourtData } from "@/lib/dashboard/ops";
|
||||
|
||||
/**
|
||||
* Which waits are the client's and which are ours.
|
||||
*
|
||||
* Two numbers rather than one, because they call for opposite responses: a
|
||||
* version unanswered for a fortnight is a phone call, while notes nobody has
|
||||
* picked up is a scheduling problem.
|
||||
*/
|
||||
export function WhoseCourt({ court }: { court: WhoseCourtData }) {
|
||||
return (
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 rounded-lg border border-zinc-800 bg-card overflow-hidden">
|
||||
<Side
|
||||
title="Waiting on the client"
|
||||
subtitle="Sent for review, no verdict yet"
|
||||
side={court.client}
|
||||
empty="Nothing is with the client."
|
||||
className="border-b border-zinc-800/60 sm:border-b-0 sm:border-r"
|
||||
/>
|
||||
<Side
|
||||
title="Waiting on us"
|
||||
subtitle="Notes in, still unresolved"
|
||||
side={court.us}
|
||||
empty="No open notes."
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function Side({
|
||||
title,
|
||||
subtitle,
|
||||
side,
|
||||
empty,
|
||||
className,
|
||||
}: {
|
||||
title: string;
|
||||
subtitle: string;
|
||||
side: WhoseCourtData["client"];
|
||||
empty: string;
|
||||
className?: string;
|
||||
}) {
|
||||
return (
|
||||
<div className={`px-4 py-3 ${className ?? ""}`}>
|
||||
<h4 className="text-xs font-semibold text-white">{title}</h4>
|
||||
<p className="text-[11px] text-zinc-500">{subtitle}</p>
|
||||
<b className="mt-2 mb-2 block font-mono text-2xl font-bold leading-none tabular-nums text-white">
|
||||
{side.count}
|
||||
</b>
|
||||
{side.items.length === 0 ? (
|
||||
<p className="text-xs text-zinc-500">{empty}</p>
|
||||
) : (
|
||||
<ul className="flex flex-col gap-1.5">
|
||||
{side.items.map((item) => (
|
||||
<li key={item.id} className="flex items-baseline justify-between gap-3 text-xs">
|
||||
<Link
|
||||
href={item.href}
|
||||
className="truncate font-mono text-[11.5px] text-zinc-200 hover:text-amber-400"
|
||||
>
|
||||
{item.shotCode}
|
||||
</Link>
|
||||
<span className="shrink-0 tabular-nums text-zinc-500">{item.label}</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -12,8 +12,9 @@ import {
|
||||
} from "@/components/ui/dropdown-menu";
|
||||
import { NotificationBell } from "@/components/notifications/NotificationBell";
|
||||
import { getInitials } from "@/lib/utils";
|
||||
import { LogOut, User, Settings } from "lucide-react";
|
||||
import { LogOut, User, Settings, Menu } from "lucide-react";
|
||||
import Link from "next/link";
|
||||
import { useMobileNav } from "@/components/layout/MobileNav";
|
||||
|
||||
interface HeaderProps {
|
||||
title?: string;
|
||||
@@ -23,11 +24,21 @@ interface HeaderProps {
|
||||
export function Header({ title, breadcrumbs }: HeaderProps) {
|
||||
const { data: session } = useSession();
|
||||
const user = session?.user;
|
||||
const { setOpen: setMobileNavOpen } = useMobileNav();
|
||||
|
||||
return (
|
||||
<header className="flex h-14 items-center justify-between border-b border-zinc-800 bg-zinc-950 px-6">
|
||||
<header className="flex h-14 items-center justify-between border-b border-zinc-800 bg-zinc-950 px-4 md:px-6">
|
||||
{/* Left: Title / Breadcrumbs */}
|
||||
<div className="flex items-center gap-2 min-w-0">
|
||||
{/* Phones only: the sidebar is hidden below md and opens as a drawer. */}
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setMobileNavOpen(true)}
|
||||
className="md:hidden -ml-2 rounded-md p-2 text-zinc-400 hover:bg-zinc-800 hover:text-white"
|
||||
aria-label="Open menu"
|
||||
>
|
||||
<Menu className="h-5 w-5" />
|
||||
</button>
|
||||
{breadcrumbs ? (
|
||||
<nav className="flex items-center gap-1.5 text-sm">
|
||||
{breadcrumbs.map((crumb, i) => (
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
'use client';
|
||||
|
||||
import { createContext, useContext, useState } from 'react';
|
||||
|
||||
/**
|
||||
* Open/closed state of the phone-width navigation drawer, shared between the
|
||||
* Header (which has the menu button) and the Sidebar (which is the drawer).
|
||||
* At md and up the sidebar is always visible and this state is unused.
|
||||
*/
|
||||
const MobileNavContext = createContext<{ open: boolean; setOpen: (open: boolean) => void }>({
|
||||
open: false,
|
||||
setOpen: () => {},
|
||||
});
|
||||
|
||||
export function MobileNavProvider({ children }: { children: React.ReactNode }) {
|
||||
const [open, setOpen] = useState(false);
|
||||
return <MobileNavContext.Provider value={{ open, setOpen }}>{children}</MobileNavContext.Provider>;
|
||||
}
|
||||
|
||||
export const useMobileNav = () => useContext(MobileNavContext);
|
||||
@@ -22,10 +22,12 @@ import {
|
||||
Clapperboard,
|
||||
LayoutGrid,
|
||||
Server,
|
||||
X,
|
||||
} from 'lucide-react';
|
||||
import { useState } from 'react';
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useSession } from 'next-auth/react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { useMobileNav } from '@/components/layout/MobileNav';
|
||||
|
||||
const navItems = [
|
||||
{ href: '/dashboard', label: 'Dashboard', icon: LayoutDashboard },
|
||||
@@ -54,17 +56,76 @@ const montserrat = Montserrat({
|
||||
|
||||
export function Sidebar() {
|
||||
const pathname = usePathname();
|
||||
const { data: session } = useSession();
|
||||
const [collapsed, setCollapsed] = useState(false);
|
||||
const { open: mobileOpen, setOpen: setMobileOpen } = useMobileNav();
|
||||
|
||||
// Picking a page closes the phone drawer; so does Escape.
|
||||
useEffect(() => {
|
||||
setMobileOpen(false);
|
||||
}, [pathname, setMobileOpen]);
|
||||
useEffect(() => {
|
||||
if (!mobileOpen) return;
|
||||
const onKey = (e: KeyboardEvent) => e.key === 'Escape' && setMobileOpen(false);
|
||||
window.addEventListener('keydown', onKey);
|
||||
return () => window.removeEventListener('keydown', onKey);
|
||||
}, [mobileOpen, setMobileOpen]);
|
||||
|
||||
return (
|
||||
<>
|
||||
{/* md and up: the sidebar exactly as before. */}
|
||||
<aside
|
||||
className={cn(
|
||||
'hidden md:flex flex-col border-r border-zinc-800 bg-zinc-900 transition-all duration-200',
|
||||
collapsed ? 'w-16' : 'w-60',
|
||||
)}
|
||||
>
|
||||
<SidebarContent collapsed={collapsed} />
|
||||
{/* Collapse toggle */}
|
||||
<div className="border-t border-zinc-800 p-2">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon-sm"
|
||||
className="w-full"
|
||||
onClick={() => setCollapsed(!collapsed)}
|
||||
title={collapsed ? 'Expand sidebar' : 'Collapse sidebar'}
|
||||
>
|
||||
{collapsed ? (
|
||||
<ChevronRight className="h-4 w-4" />
|
||||
) : (
|
||||
<ChevronLeft className="h-4 w-4" />
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
</aside>
|
||||
|
||||
{/* Phones: the same navigation as a drawer, opened from the header. */}
|
||||
{mobileOpen && (
|
||||
<div className="fixed inset-0 z-50 md:hidden">
|
||||
<div className="absolute inset-0 bg-black/60" onClick={() => setMobileOpen(false)} />
|
||||
<aside className="absolute inset-y-0 left-0 flex w-64 max-w-[80vw] flex-col overflow-y-auto border-r border-zinc-800 bg-zinc-900">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setMobileOpen(false)}
|
||||
className="absolute right-2 top-2 rounded-md p-2 text-zinc-400 hover:bg-zinc-800 hover:text-white"
|
||||
aria-label="Close menu"
|
||||
>
|
||||
<X className="h-4 w-4" />
|
||||
</button>
|
||||
<SidebarContent collapsed={false} />
|
||||
</aside>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function SidebarContent({ collapsed }: { collapsed: boolean }) {
|
||||
const pathname = usePathname();
|
||||
const { data: session } = useSession();
|
||||
const isAdmin = ['ADMIN', 'PRODUCER'].includes(session?.user?.role ?? '');
|
||||
|
||||
return (
|
||||
<aside
|
||||
className={cn(
|
||||
'flex flex-col border-r border-zinc-800 bg-zinc-900 transition-all duration-200',
|
||||
collapsed ? 'w-16' : 'w-60',
|
||||
)}
|
||||
>
|
||||
<>
|
||||
{/* Logo */}
|
||||
<div
|
||||
className={cn(
|
||||
@@ -119,23 +180,6 @@ export function Sidebar() {
|
||||
);
|
||||
})}
|
||||
</nav>
|
||||
|
||||
{/* Collapse toggle */}
|
||||
<div className="border-t border-zinc-800 p-2">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon-sm"
|
||||
className="w-full"
|
||||
onClick={() => setCollapsed(!collapsed)}
|
||||
title={collapsed ? 'Expand sidebar' : 'Collapse sidebar'}
|
||||
>
|
||||
{collapsed ? (
|
||||
<ChevronRight className="h-4 w-4" />
|
||||
) : (
|
||||
<ChevronLeft className="h-4 w-4" />
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
</aside>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,131 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useState, type RefObject } from "react";
|
||||
import {
|
||||
blankingInsets,
|
||||
findAspectPreset,
|
||||
isFullFrame,
|
||||
letterboxRect,
|
||||
type BlankingMode,
|
||||
} from "@/lib/aspect-overlays";
|
||||
|
||||
interface AspectOverlayProps {
|
||||
/** Preset id, or "off" — anything unknown draws nothing. */
|
||||
presetId: string;
|
||||
mode: BlankingMode;
|
||||
videoRef: RefObject<HTMLVideoElement | null>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Delivery blanking drawn over the video. Purely visual: it never touches the
|
||||
* video element, sits under the annotation canvas, and passes every pointer
|
||||
* event through so click-to-play still works underneath it.
|
||||
*/
|
||||
export function AspectOverlay({ presetId, mode, videoRef }: AspectOverlayProps) {
|
||||
const preset = findAspectPreset(presetId);
|
||||
const [box, setBox] = useState<{
|
||||
top: number;
|
||||
bottom: number;
|
||||
left: number;
|
||||
right: number;
|
||||
rect: { left: number; top: number; width: number; height: number };
|
||||
} | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
const video = videoRef.current;
|
||||
if (!video || !preset) {
|
||||
setBox(null);
|
||||
return;
|
||||
}
|
||||
|
||||
const measure = () => {
|
||||
const rect = letterboxRect(
|
||||
video.clientWidth,
|
||||
video.clientHeight,
|
||||
video.videoWidth,
|
||||
video.videoHeight
|
||||
);
|
||||
// Before metadata lands videoWidth is 0 and there is nothing to measure.
|
||||
if (!rect) {
|
||||
setBox(null);
|
||||
return;
|
||||
}
|
||||
const insets = blankingInsets(rect, preset.ratio);
|
||||
setBox(isFullFrame(insets) ? null : { ...insets, rect });
|
||||
};
|
||||
|
||||
measure();
|
||||
|
||||
// The picture rect moves on layout changes (panel resize, fullscreen) and
|
||||
// on metadata, which is when intrinsic dimensions first exist.
|
||||
const observer = new ResizeObserver(measure);
|
||||
observer.observe(video);
|
||||
video.addEventListener("loadedmetadata", measure);
|
||||
|
||||
return () => {
|
||||
observer.disconnect();
|
||||
video.removeEventListener("loadedmetadata", measure);
|
||||
};
|
||||
}, [preset, videoRef]);
|
||||
|
||||
if (!preset || !box) return null;
|
||||
|
||||
const { rect } = box;
|
||||
const barClass =
|
||||
mode === "solid"
|
||||
? "absolute bg-black"
|
||||
: "absolute bg-black/60 ring-1 ring-inset ring-white/25";
|
||||
|
||||
// Each bar is positioned against the picture rect, not the element box, so
|
||||
// blanking lands on the image itself whatever shape the player is.
|
||||
const horizontal = box.top > 0;
|
||||
|
||||
return (
|
||||
// No z-index: the annotation canvas is also absolutely positioned and comes
|
||||
// later in the DOM, so it stays on top and marks drawn over a blanked area
|
||||
// remain visible.
|
||||
<div
|
||||
className="pointer-events-none absolute inset-0"
|
||||
aria-hidden="true"
|
||||
data-testid="aspect-overlay"
|
||||
>
|
||||
{horizontal ? (
|
||||
<>
|
||||
<div
|
||||
className={barClass}
|
||||
style={{ left: rect.left, top: rect.top, width: rect.width, height: box.top }}
|
||||
/>
|
||||
<div
|
||||
className={barClass}
|
||||
style={{
|
||||
left: rect.left,
|
||||
top: rect.top + rect.height - box.bottom,
|
||||
width: rect.width,
|
||||
height: box.bottom,
|
||||
}}
|
||||
/>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<div
|
||||
className={barClass}
|
||||
style={{ left: rect.left, top: rect.top, width: box.left, height: rect.height }}
|
||||
/>
|
||||
<div
|
||||
className={barClass}
|
||||
style={{
|
||||
left: rect.left + rect.width - box.right,
|
||||
top: rect.top,
|
||||
width: box.right,
|
||||
height: rect.height,
|
||||
}}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
|
||||
<div className="absolute bottom-3 right-3 rounded bg-black/70 px-2 py-1 font-mono text-[11px] text-zinc-300">
|
||||
{preset.label}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -13,6 +13,7 @@ import {
|
||||
Pencil,
|
||||
Eye,
|
||||
EyeOff,
|
||||
RectangleHorizontal,
|
||||
} from "lucide-react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
@@ -20,9 +21,17 @@ import {
|
||||
TooltipContent,
|
||||
TooltipTrigger,
|
||||
} from "@/components/ui/tooltip";
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectSeparator,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from "@/components/ui/select";
|
||||
import { useReviewStore } from "@/hooks/use-review-player";
|
||||
import { frameToTimecode } from "@/lib/frame-utils";
|
||||
import { ASPECT_OFF, ASPECT_PRESETS } from "@/lib/aspect-overlays";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
const PLAYBACK_RATES = [0.25, 0.5, 0.75, 1, 1.25, 1.5, 2];
|
||||
@@ -58,9 +67,13 @@ export function PlaybackControls({
|
||||
playbackRate,
|
||||
isAnnotating,
|
||||
showAnnotations,
|
||||
aspectPresetId,
|
||||
blankingMode,
|
||||
setPlaybackRate,
|
||||
setAnnotating,
|
||||
setShowAnnotations,
|
||||
setAspectPresetId,
|
||||
setBlankingMode,
|
||||
} = useReviewStore();
|
||||
|
||||
const handleRateChange = (val: string) => {
|
||||
@@ -69,6 +82,8 @@ export function PlaybackControls({
|
||||
setPlaybackRate(rate);
|
||||
};
|
||||
|
||||
const blankingOn = aspectPresetId !== ASPECT_OFF;
|
||||
|
||||
const timecode = frameToTimecode(currentFrame, fps);
|
||||
|
||||
return (
|
||||
@@ -216,6 +231,57 @@ export function PlaybackControls({
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
{/* Delivery blanking — hidden on mobile */}
|
||||
<div className="hidden sm:contents">
|
||||
<Select value={aspectPresetId} onValueChange={setAspectPresetId}>
|
||||
<SelectTrigger
|
||||
className={cn(
|
||||
"h-7 w-24 text-xs border-0 bg-white/5 px-2",
|
||||
blankingOn ? "text-amber-400" : "text-zinc-300"
|
||||
)}
|
||||
>
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value={ASPECT_OFF} className="text-xs">
|
||||
No blanking
|
||||
</SelectItem>
|
||||
<SelectSeparator />
|
||||
{ASPECT_PRESETS.map((p) => (
|
||||
<SelectItem key={p.id} value={p.id} className="text-xs">
|
||||
<span className="font-mono">{p.label}</span>
|
||||
<span className="ml-2 text-zinc-500">{p.note}</span>
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
|
||||
{blankingOn && (
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon-sm"
|
||||
className={cn(
|
||||
"text-zinc-400 hover:text-white",
|
||||
blankingMode === "guide" && "text-amber-400 bg-amber-400/10"
|
||||
)}
|
||||
onClick={() =>
|
||||
setBlankingMode(blankingMode === "solid" ? "guide" : "solid")
|
||||
}
|
||||
>
|
||||
<RectangleHorizontal className="h-4 w-4" />
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>
|
||||
{blankingMode === "solid"
|
||||
? "Dim the crop instead of hiding it"
|
||||
: "Hide the crop behind solid bars"}
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Annotation toggle */}
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
|
||||
@@ -12,6 +12,7 @@ import {
|
||||
import { useReviewStore } from "@/hooks/use-review-player";
|
||||
import { AnnotationCanvas } from "@/components/annotations/AnnotationCanvas";
|
||||
import { AnnotationTools } from "@/components/annotations/AnnotationTools";
|
||||
import { AspectOverlay } from "./AspectOverlay";
|
||||
import { FrameTimeline } from "./FrameTimeline";
|
||||
import { PlaybackControls } from "./PlaybackControls";
|
||||
import { timeToFrame, frameToTime, durationToFrameCount } from "@/lib/frame-utils";
|
||||
@@ -68,6 +69,8 @@ export const ReviewPlayer = forwardRef<ReviewPlayerRef, ReviewPlayerProps>(
|
||||
currentFrame,
|
||||
isAnnotating,
|
||||
showAnnotations,
|
||||
aspectPresetId,
|
||||
blankingMode,
|
||||
setPlaying,
|
||||
setCurrentFrame,
|
||||
setCurrentTime,
|
||||
@@ -283,6 +286,14 @@ export const ReviewPlayer = forwardRef<ReviewPlayerRef, ReviewPlayerProps>(
|
||||
playsInline
|
||||
/>
|
||||
|
||||
{/* Delivery blanking — under the annotation canvas, so a reviewer
|
||||
can still draw over a blanked area if they need to */}
|
||||
<AspectOverlay
|
||||
presetId={aspectPresetId}
|
||||
mode={blankingMode}
|
||||
videoRef={videoRef}
|
||||
/>
|
||||
|
||||
{/* Annotation canvas overlay */}
|
||||
<AnnotationCanvas
|
||||
versionId={versionId}
|
||||
|
||||
@@ -1,20 +1,10 @@
|
||||
"use client";
|
||||
|
||||
import Link from "next/link";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Card, CardContent, CardFooter, CardHeader } from "@/components/ui/card";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
|
||||
import { Progress } from "@/components/ui/progress";
|
||||
import { cn, getInitials, formatRelativeDate } from "@/lib/utils";
|
||||
import {
|
||||
Film,
|
||||
Layers,
|
||||
CheckCircle2,
|
||||
Clock,
|
||||
Users,
|
||||
ArrowUpRight,
|
||||
} from "lucide-react";
|
||||
import { Film, Layers, CheckCircle2, Clock, ArrowUpRight } from "lucide-react";
|
||||
|
||||
interface ProjectCardProps {
|
||||
project: {
|
||||
@@ -23,7 +13,9 @@ interface ProjectCardProps {
|
||||
code: string;
|
||||
status: string;
|
||||
description?: string | null;
|
||||
deadline?: Date | null;
|
||||
/** The column is `dueDate`; `deadline` is kept for older callers. */
|
||||
dueDate?: Date | string | null;
|
||||
deadline?: Date | string | null;
|
||||
createdAt: Date;
|
||||
client?: { company: string } | null;
|
||||
producer?: { name: string | null; image: string | null } | null;
|
||||
@@ -33,117 +25,147 @@ interface ProjectCardProps {
|
||||
approved: number;
|
||||
inProgress: number;
|
||||
};
|
||||
/** Still chosen from the project's own shots (lib/project-poster.ts). */
|
||||
poster?: { url: string; shotCode: string; isKeyShot: boolean } | null;
|
||||
};
|
||||
}
|
||||
|
||||
const STATUS_STYLES: Record<string, string> = {
|
||||
ACTIVE: "bg-green-900/60 text-green-300",
|
||||
ON_HOLD: "bg-yellow-900/60 text-yellow-300",
|
||||
COMPLETED: "bg-blue-900/60 text-blue-300",
|
||||
ARCHIVED: "bg-zinc-800 text-zinc-500",
|
||||
ACTIVE: "bg-green-900/70 text-green-300",
|
||||
ON_HOLD: "bg-yellow-900/70 text-yellow-300",
|
||||
COMPLETED: "bg-blue-900/70 text-blue-300",
|
||||
ARCHIVED: "bg-zinc-900/80 text-zinc-400",
|
||||
};
|
||||
|
||||
/**
|
||||
* A project card is scanned, not read: in a grid of twenty the frame is what
|
||||
* the eye picks out, so the still leads and the title sits on it. Every card is
|
||||
* the same height whatever it holds — a ragged grid reads as broken, and the
|
||||
* description is the only part that varies, so it is given fixed room rather
|
||||
* than allowed to push the rest around.
|
||||
*/
|
||||
export function ProjectCard({ project }: ProjectCardProps) {
|
||||
const total = project.shotStats?.total ?? project._count?.shots ?? 0;
|
||||
const approved = project.shotStats?.approved ?? 0;
|
||||
const progress = total > 0 ? Math.round((approved / total) * 100) : 0;
|
||||
const due = project.dueDate ?? project.deadline;
|
||||
const isArchived = project.status === "ARCHIVED";
|
||||
|
||||
return (
|
||||
<Card className="group hover:border-zinc-700 transition-all flex flex-col">
|
||||
<CardHeader className="pb-3">
|
||||
<div className="flex items-start justify-between gap-2">
|
||||
<div>
|
||||
<div className="flex items-center gap-2 mb-0.5">
|
||||
<span className="font-mono text-xs text-zinc-500">{project.code}</span>
|
||||
{project.client && (
|
||||
<span className="text-xs text-zinc-600">• {project.client.company}</span>
|
||||
)}
|
||||
</div>
|
||||
<h3 className="font-semibold text-base leading-tight text-white">{project.name}</h3>
|
||||
</div>
|
||||
<span
|
||||
<Link
|
||||
href={`/projects/${project.id}`}
|
||||
className="group flex h-full flex-col overflow-hidden rounded-lg border border-zinc-800 bg-card transition-colors hover:border-zinc-600 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-amber-500"
|
||||
>
|
||||
{/* Poster */}
|
||||
<div className="relative aspect-video w-full shrink-0 overflow-hidden bg-zinc-900">
|
||||
{project.poster ? (
|
||||
<img
|
||||
src={project.poster.url}
|
||||
alt=""
|
||||
loading="lazy"
|
||||
className={cn(
|
||||
"text-xs px-2 py-0.5 rounded-full border-0 font-medium shrink-0",
|
||||
STATUS_STYLES[project.status] ?? STATUS_STYLES.ACTIVE
|
||||
"h-full w-full object-cover transition-transform duration-500 group-hover:scale-[1.04]",
|
||||
// An archived show is still recognisable, just visibly past.
|
||||
isArchived && "opacity-50 grayscale"
|
||||
)}
|
||||
>
|
||||
{project.status.replace("_", " ")}
|
||||
</span>
|
||||
/>
|
||||
) : (
|
||||
// Same footprint as a real poster, so a project without stills does
|
||||
// not leave a hole in the grid.
|
||||
<div className="flex h-full w-full items-center justify-center bg-gradient-to-br from-zinc-900 to-zinc-950">
|
||||
<Film className="h-8 w-8 text-zinc-700" />
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Scrim: the title has to hold on a bright frame as well as a dark one. */}
|
||||
<div className="absolute inset-0 bg-gradient-to-t from-black/90 via-black/35 to-black/10" />
|
||||
|
||||
<span
|
||||
className={cn(
|
||||
"absolute right-2.5 top-2.5 rounded-full px-2 py-0.5 text-[11px] font-medium backdrop-blur-sm",
|
||||
STATUS_STYLES[project.status] ?? STATUS_STYLES.ACTIVE
|
||||
)}
|
||||
>
|
||||
{project.status.replace("_", " ")}
|
||||
</span>
|
||||
|
||||
<div className="absolute inset-x-0 bottom-0 p-3">
|
||||
<div className="flex items-center gap-2 text-[11px] text-zinc-300/90">
|
||||
<span className="font-mono">{project.code}</span>
|
||||
{project.client && (
|
||||
<span className="truncate text-zinc-400">• {project.client.company}</span>
|
||||
)}
|
||||
</div>
|
||||
<h3 className="mt-0.5 line-clamp-2 text-base font-semibold leading-tight text-white drop-shadow-sm">
|
||||
{project.name}
|
||||
</h3>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Body — fixed room so every card lands the same height */}
|
||||
<div className="flex flex-1 flex-col gap-3 p-3">
|
||||
<p className="line-clamp-2 min-h-[2.5rem] text-xs text-zinc-400">
|
||||
{project.description || <span className="text-zinc-600">No description</span>}
|
||||
</p>
|
||||
|
||||
<div className="space-y-1.5">
|
||||
<div className="flex items-center justify-between text-xs text-muted-foreground">
|
||||
<span>Shot progress</span>
|
||||
<span className="font-medium text-foreground tabular-nums">
|
||||
{total > 0 ? `${approved}/${total} approved` : "No shots yet"}
|
||||
</span>
|
||||
</div>
|
||||
<Progress value={progress} className="h-1.5" />
|
||||
</div>
|
||||
|
||||
{project.description && (
|
||||
<p className="text-sm text-zinc-400 line-clamp-2 mt-1">
|
||||
{project.description}
|
||||
</p>
|
||||
)}
|
||||
</CardHeader>
|
||||
|
||||
<CardContent className="flex-1 pb-3 space-y-3">
|
||||
{/* Progress */}
|
||||
{total > 0 && (
|
||||
<div className="space-y-1.5">
|
||||
<div className="flex items-center justify-between text-xs text-muted-foreground">
|
||||
<span>Shot progress</span>
|
||||
<span className="text-foreground font-medium">{approved}/{total} approved</span>
|
||||
</div>
|
||||
<Progress value={progress} className="h-1.5" />
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Stats */}
|
||||
<div className="grid grid-cols-3 gap-2 text-xs">
|
||||
<div className="flex flex-col items-center rounded-lg bg-zinc-800 py-2">
|
||||
<Layers className="h-3.5 w-3.5 text-zinc-400 mb-1" />
|
||||
<span className="font-semibold text-white">{total}</span>
|
||||
<div className="flex flex-col items-center rounded-lg bg-zinc-800 py-2">
|
||||
<Layers className="mb-1 h-3.5 w-3.5 text-zinc-400" />
|
||||
<span className="font-semibold tabular-nums text-white">{total}</span>
|
||||
<span className="text-zinc-400">shots</span>
|
||||
</div>
|
||||
<div className="flex flex-col items-center rounded-lg bg-zinc-800 py-2">
|
||||
<CheckCircle2 className="h-3.5 w-3.5 text-green-400 mb-1" />
|
||||
<span className="font-semibold text-white">{approved}</span>
|
||||
<CheckCircle2 className="mb-1 h-3.5 w-3.5 text-green-400" />
|
||||
<span className="font-semibold tabular-nums text-white">{approved}</span>
|
||||
<span className="text-zinc-400">done</span>
|
||||
</div>
|
||||
<div className="flex flex-col items-center rounded-lg bg-zinc-800 py-2">
|
||||
<Film className="h-3.5 w-3.5 text-blue-400 mb-1" />
|
||||
<span className="font-semibold text-white">
|
||||
<Film className="mb-1 h-3.5 w-3.5 text-blue-400" />
|
||||
<span className="font-semibold tabular-nums text-white">
|
||||
{project.shotStats?.inProgress ?? 0}
|
||||
</span>
|
||||
<span className="text-zinc-400">active</span>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
|
||||
<CardFooter className="pt-2 border-t border-zinc-800 flex items-center justify-between">
|
||||
<div className="flex items-center gap-2 text-xs text-zinc-400">
|
||||
{project.producer ? (
|
||||
<>
|
||||
<Avatar className="h-5 w-5">
|
||||
{project.producer.image && <AvatarImage src={project.producer.image} />}
|
||||
<AvatarFallback className="text-[9px]">
|
||||
{getInitials(project.producer.name)}
|
||||
</AvatarFallback>
|
||||
</Avatar>
|
||||
<span>{project.producer.name ?? "Producer"}</span>
|
||||
</>
|
||||
{/* Pinned to the bottom so the footers line up across the row. */}
|
||||
<div className="mt-auto flex items-center justify-between gap-2 border-t border-zinc-800 pt-2.5 text-xs text-zinc-400">
|
||||
<div className="flex min-w-0 items-center gap-2">
|
||||
{project.producer ? (
|
||||
<>
|
||||
<Avatar className="h-5 w-5 shrink-0">
|
||||
{project.producer.image && <AvatarImage src={project.producer.image} />}
|
||||
<AvatarFallback className="text-[9px]">
|
||||
{getInitials(project.producer.name)}
|
||||
</AvatarFallback>
|
||||
</Avatar>
|
||||
<span className="truncate">{project.producer.name ?? "Producer"}</span>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Clock className="h-3 w-3 shrink-0" />
|
||||
<span className="truncate">{formatRelativeDate(project.createdAt)}</span>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{due ? (
|
||||
<span className="shrink-0 text-amber-400">Due {formatRelativeDate(due as Date)}</span>
|
||||
) : (
|
||||
<>
|
||||
<Clock className="h-3 w-3" />
|
||||
<span>{formatRelativeDate(project.createdAt)}</span>
|
||||
</>
|
||||
)}
|
||||
{project.deadline && (
|
||||
<span className="text-amber-400 ml-2">
|
||||
Due {formatRelativeDate(project.deadline)}
|
||||
</span>
|
||||
<ArrowUpRight className="h-3.5 w-3.5 shrink-0 text-zinc-600 transition-colors group-hover:text-amber-400" />
|
||||
)}
|
||||
</div>
|
||||
|
||||
<Button variant="ghost" size="sm" asChild className="h-7 text-xs gap-1">
|
||||
<Link href={`/projects/${project.id}`}>
|
||||
Open
|
||||
<ArrowUpRight className="h-3 w-3" />
|
||||
</Link>
|
||||
</Button>
|
||||
</CardFooter>
|
||||
</Card>
|
||||
</div>
|
||||
</Link>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { create } from "zustand";
|
||||
import type { AnnotationTool } from "@/types";
|
||||
import { ASPECT_OFF, type BlankingMode } from "@/lib/aspect-overlays";
|
||||
|
||||
interface ReviewPlayerStore {
|
||||
// Playback
|
||||
@@ -19,6 +20,10 @@ interface ReviewPlayerStore {
|
||||
strokeWidth: number;
|
||||
showAnnotations: boolean;
|
||||
|
||||
// Delivery blanking — a viewing aid only, never part of the saved review
|
||||
aspectPresetId: string;
|
||||
blankingMode: BlankingMode;
|
||||
|
||||
// Config (set from version data)
|
||||
fps: number;
|
||||
totalFrames: number;
|
||||
@@ -37,6 +42,8 @@ interface ReviewPlayerStore {
|
||||
setSelectedColor: (color: string) => void;
|
||||
setStrokeWidth: (width: number) => void;
|
||||
setShowAnnotations: (show: boolean) => void;
|
||||
setAspectPresetId: (id: string) => void;
|
||||
setBlankingMode: (mode: BlankingMode) => void;
|
||||
setFps: (fps: number) => void;
|
||||
setTotalFrames: (frames: number) => void;
|
||||
reset: () => void;
|
||||
@@ -56,6 +63,8 @@ const initialState = {
|
||||
selectedColor: "#ef4444",
|
||||
strokeWidth: 2,
|
||||
showAnnotations: true,
|
||||
aspectPresetId: ASPECT_OFF,
|
||||
blankingMode: "solid" as BlankingMode,
|
||||
fps: 24,
|
||||
totalFrames: 0,
|
||||
};
|
||||
@@ -75,6 +84,8 @@ export const useReviewStore = create<ReviewPlayerStore>((set) => ({
|
||||
setSelectedColor: (selectedColor) => set({ selectedColor }),
|
||||
setStrokeWidth: (strokeWidth) => set({ strokeWidth }),
|
||||
setShowAnnotations: (showAnnotations) => set({ showAnnotations }),
|
||||
setAspectPresetId: (aspectPresetId) => set({ aspectPresetId }),
|
||||
setBlankingMode: (blankingMode) => set({ blankingMode }),
|
||||
setFps: (fps) => set({ fps }),
|
||||
setTotalFrames: (totalFrames) => set({ totalFrames }),
|
||||
reset: () => set(initialState),
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useRef } from "react";
|
||||
|
||||
/**
|
||||
* Remembers a page's scroll position for the browser session and puts it back
|
||||
* when the page is shown again — e.g. after opening a shot and coming back.
|
||||
*
|
||||
* Dashboard pages do not scroll the window: the layout scrolls its <main>
|
||||
* (overflow-auto), so window.scrollY is always 0. This finds the nearest
|
||||
* scrolling ancestor of `anchorRef` and saves that instead, falling back to
|
||||
* the document for pages that do scroll the window (the client portal).
|
||||
*
|
||||
* The position is saved as the user scrolls, not on a particular link's click,
|
||||
* so any way of leaving the page (another link, the sidebar, a browser
|
||||
* back/forward) keeps it.
|
||||
*
|
||||
* Restores once per `key`, and only when `ready` is true: the caller holds it
|
||||
* false until the content that sets the page height (expanded sections) is
|
||||
* back, or the saved offset would be clamped to a shorter page.
|
||||
*/
|
||||
export function useScrollMemory(
|
||||
key: string | null,
|
||||
anchorRef: React.RefObject<HTMLElement | null>,
|
||||
ready: boolean
|
||||
) {
|
||||
const restoredKey = useRef<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (!key || !ready || !anchorRef.current) return;
|
||||
const anchor = anchorRef.current;
|
||||
const scroller = findScroller(anchor);
|
||||
const storageKey = `scroll:${key}`;
|
||||
|
||||
if (restoredKey.current !== key) {
|
||||
restoredKey.current = key;
|
||||
let saved: number | null = null;
|
||||
try {
|
||||
const raw = sessionStorage.getItem(storageKey);
|
||||
saved = raw ? parseInt(raw, 10) : null;
|
||||
} catch {}
|
||||
if (saved && saved > 0) {
|
||||
// Thumbnails and late rows can still grow the page for a moment, so
|
||||
// keep trying for a short while until the offset actually fits.
|
||||
const target = saved;
|
||||
let frames = 0;
|
||||
const tryRestore = () => {
|
||||
scroller.scrollTop = target;
|
||||
if (Math.abs(scroller.scrollTop - target) > 1 && frames++ < 60) {
|
||||
requestAnimationFrame(tryRestore);
|
||||
}
|
||||
};
|
||||
requestAnimationFrame(tryRestore);
|
||||
}
|
||||
}
|
||||
|
||||
let pending = false;
|
||||
let disposed = false;
|
||||
const onScroll = () => {
|
||||
if (pending) return;
|
||||
pending = true;
|
||||
requestAnimationFrame(() => {
|
||||
pending = false;
|
||||
// The layout's scroller outlives this page. When the next page
|
||||
// replaces this one, the scroller clamps to the new, shorter content
|
||||
// and fires a scroll before this listener is removed; recording it
|
||||
// would overwrite the real position. Once this page's content is out
|
||||
// of the document, scrolls are not ours.
|
||||
if (disposed || !anchor.isConnected) return;
|
||||
try {
|
||||
sessionStorage.setItem(storageKey, String(Math.round(scroller.scrollTop)));
|
||||
} catch {}
|
||||
});
|
||||
};
|
||||
// When the document itself scrolls, the event fires on window, not on <html>.
|
||||
const target: HTMLElement | Window = scroller === document.scrollingElement ? window : scroller;
|
||||
target.addEventListener("scroll", onScroll, { passive: true });
|
||||
return () => {
|
||||
disposed = true;
|
||||
target.removeEventListener("scroll", onScroll);
|
||||
};
|
||||
}, [key, ready, anchorRef]);
|
||||
}
|
||||
|
||||
function findScroller(el: HTMLElement): HTMLElement {
|
||||
for (let node = el.parentElement; node; node = node.parentElement) {
|
||||
const overflowY = getComputedStyle(node).overflowY;
|
||||
if (overflowY === "auto" || overflowY === "scroll") return node;
|
||||
}
|
||||
return document.scrollingElement as HTMLElement;
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
ASPECT_PRESETS,
|
||||
blankingInsets,
|
||||
findAspectPreset,
|
||||
isFullFrame,
|
||||
letterboxRect,
|
||||
} from "./aspect-overlays";
|
||||
|
||||
describe("letterboxRect", () => {
|
||||
it("pillarboxes a 16:9 source in a squarer box", () => {
|
||||
const rect = letterboxRect(1000, 1000, 1920, 1080)!;
|
||||
expect(rect.width).toBeCloseTo(1000, 6);
|
||||
expect(rect.height).toBeCloseTo(562.5, 6);
|
||||
expect(rect.top).toBeCloseTo(218.75, 6);
|
||||
expect(rect.left).toBeCloseTo(0, 6);
|
||||
});
|
||||
|
||||
it("letterboxes a 16:9 source in a wider box", () => {
|
||||
const rect = letterboxRect(2000, 500, 1920, 1080)!;
|
||||
expect(rect.height).toBeCloseTo(500, 6);
|
||||
expect(rect.width).toBeCloseTo(888.888, 2);
|
||||
expect(rect.left).toBeCloseTo(555.555, 2);
|
||||
expect(rect.top).toBeCloseTo(0, 6);
|
||||
});
|
||||
|
||||
it("fills exactly when the box matches the source shape", () => {
|
||||
const rect = letterboxRect(1280, 720, 1920, 1080)!;
|
||||
expect(rect).toEqual({ left: 0, top: 0, width: 1280, height: 720 });
|
||||
});
|
||||
|
||||
it("returns null before metadata gives the video a size", () => {
|
||||
expect(letterboxRect(1000, 500, 0, 0)).toBeNull();
|
||||
expect(letterboxRect(0, 0, 1920, 1080)).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("blankingInsets", () => {
|
||||
const hd = { left: 0, top: 0, width: 1920, height: 1080 };
|
||||
|
||||
it("blanks top and bottom for a wider delivery ratio", () => {
|
||||
const insets = blankingInsets(hd, 2.39);
|
||||
// 1920 / 2.39 = 803.35 tall, so 138.32 above and below.
|
||||
expect(insets.top).toBeCloseTo(138.3, 1);
|
||||
expect(insets.bottom).toBeCloseTo(138.3, 1);
|
||||
expect(insets.left).toBe(0);
|
||||
expect(insets.right).toBe(0);
|
||||
});
|
||||
|
||||
it("blanks left and right for a taller delivery ratio", () => {
|
||||
const insets = blankingInsets(hd, 4 / 3);
|
||||
// 1080 * 1.333 = 1440 wide, so 240 either side.
|
||||
expect(insets.left).toBeCloseTo(240, 4);
|
||||
expect(insets.right).toBeCloseTo(240, 4);
|
||||
expect(insets.top).toBe(0);
|
||||
expect(insets.bottom).toBe(0);
|
||||
});
|
||||
|
||||
it("draws nothing when the target matches the source", () => {
|
||||
expect(isFullFrame(blankingInsets(hd, 16 / 9))).toBe(true);
|
||||
});
|
||||
|
||||
it("suppresses a sub-pixel hairline rather than drawing one", () => {
|
||||
// 1.7777... vs a 1.778 label: a real ratio difference, but under half a pixel.
|
||||
expect(isFullFrame(blankingInsets(hd, 1.778))).toBe(true);
|
||||
});
|
||||
|
||||
it("keeps the blanked area at the requested ratio", () => {
|
||||
const insets = blankingInsets(hd, 2.39);
|
||||
const visibleHeight = hd.height - insets.top - insets.bottom;
|
||||
expect(hd.width / visibleHeight).toBeCloseTo(2.39, 3);
|
||||
});
|
||||
|
||||
it("blanks a letterboxed picture rect, not the element box", () => {
|
||||
// 16:9 source shown in a tall panel: the picture is 1000x562.5 at y=218.75.
|
||||
const rect = letterboxRect(1000, 1000, 1920, 1080)!;
|
||||
const insets = blankingInsets(rect, 2.39);
|
||||
const visibleHeight = rect.height - insets.top - insets.bottom;
|
||||
expect(rect.width / visibleHeight).toBeCloseTo(2.39, 3);
|
||||
// Bars stay inside the picture, never spilling into the letterbox.
|
||||
expect(insets.top).toBeLessThan(rect.height / 2);
|
||||
});
|
||||
|
||||
it("is inert for a zero-size rect", () => {
|
||||
expect(isFullFrame(blankingInsets({ left: 0, top: 0, width: 0, height: 0 }, 2.39))).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("ASPECT_PRESETS", () => {
|
||||
it("has unique ids and positive ratios", () => {
|
||||
const ids = ASPECT_PRESETS.map((p) => p.id);
|
||||
expect(new Set(ids).size).toBe(ids.length);
|
||||
for (const p of ASPECT_PRESETS) expect(p.ratio).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
it("runs widest to tallest", () => {
|
||||
const ratios = ASPECT_PRESETS.map((p) => p.ratio);
|
||||
expect([...ratios].sort((a, b) => b - a)).toEqual(ratios);
|
||||
});
|
||||
|
||||
it("looks up by id and ignores unknown ids", () => {
|
||||
expect(findAspectPreset("2.39")?.ratio).toBe(2.39);
|
||||
expect(findAspectPreset("off")).toBeNull();
|
||||
expect(findAspectPreset("nonsense")).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,119 @@
|
||||
/**
|
||||
* Aspect-ratio blanking for the review player.
|
||||
*
|
||||
* A shot is reviewed at the framing it was rendered at, but it is usually
|
||||
* *delivered* cropped — a 16:9 render shown 2.39:1, say. These helpers work out
|
||||
* where the delivered frame's edges fall so the player can lay bars over
|
||||
* everything outside them, without touching the video itself.
|
||||
*/
|
||||
|
||||
export type BlankingMode = "solid" | "guide";
|
||||
|
||||
export interface AspectPreset {
|
||||
id: string;
|
||||
/** What the reviewer picks from the list, e.g. "2.39:1". */
|
||||
label: string;
|
||||
/** Where it comes from, e.g. "Scope". Shown beside the label. */
|
||||
note: string;
|
||||
ratio: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Delivery ratios in wide-to-tall order, which is how a reviewer thinks about
|
||||
* them. Values are the real delivery numbers, not the rounded label: 2.39:1 is
|
||||
* 2.39, but 16:9 is 1.7778 rather than the 1.78 on the button.
|
||||
*/
|
||||
export const ASPECT_PRESETS: AspectPreset[] = [
|
||||
{ id: "2.39", label: "2.39:1", note: "Scope", ratio: 2.39 },
|
||||
{ id: "2.35", label: "2.35:1", note: "Classic scope", ratio: 2.35 },
|
||||
{ id: "2.20", label: "2.20:1", note: "70mm", ratio: 2.2 },
|
||||
{ id: "2.00", label: "2.00:1", note: "Univisium", ratio: 2 },
|
||||
{ id: "1.90", label: "1.90:1", note: "IMAX digital", ratio: 1.9 },
|
||||
{ id: "1.85", label: "1.85:1", note: "Flat", ratio: 1.85 },
|
||||
{ id: "1.78", label: "16:9", note: "1.78:1", ratio: 16 / 9 },
|
||||
{ id: "1.66", label: "1.66:1", note: "Super 16", ratio: 5 / 3 },
|
||||
{ id: "1.50", label: "3:2", note: "1.50:1", ratio: 1.5 },
|
||||
{ id: "1.33", label: "4:3", note: "1.33:1", ratio: 4 / 3 },
|
||||
{ id: "1.00", label: "1:1", note: "Square", ratio: 1 },
|
||||
{ id: "0.80", label: "4:5", note: "Social", ratio: 0.8 },
|
||||
{ id: "0.5625", label: "9:16", note: "Vertical", ratio: 9 / 16 },
|
||||
];
|
||||
|
||||
export const ASPECT_OFF = "off";
|
||||
|
||||
export function findAspectPreset(id: string): AspectPreset | null {
|
||||
return ASPECT_PRESETS.find((p) => p.id === id) ?? null;
|
||||
}
|
||||
|
||||
export interface Rect {
|
||||
left: number;
|
||||
top: number;
|
||||
width: number;
|
||||
height: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Where the picture actually sits inside an `object-contain` video element.
|
||||
* The element fills its box, but the image is letterboxed within it, so bars
|
||||
* drawn against the element's own edges would be wrong on any player whose
|
||||
* shape does not match the source.
|
||||
*/
|
||||
export function letterboxRect(
|
||||
containerWidth: number,
|
||||
containerHeight: number,
|
||||
videoWidth: number,
|
||||
videoHeight: number
|
||||
): Rect | null {
|
||||
if (
|
||||
!(containerWidth > 0) ||
|
||||
!(containerHeight > 0) ||
|
||||
!(videoWidth > 0) ||
|
||||
!(videoHeight > 0)
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const scale = Math.min(containerWidth / videoWidth, containerHeight / videoHeight);
|
||||
const width = videoWidth * scale;
|
||||
const height = videoHeight * scale;
|
||||
|
||||
return {
|
||||
left: (containerWidth - width) / 2,
|
||||
top: (containerHeight - height) / 2,
|
||||
width,
|
||||
height,
|
||||
};
|
||||
}
|
||||
|
||||
export interface BlankingInsets {
|
||||
top: number;
|
||||
bottom: number;
|
||||
left: number;
|
||||
right: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* How thick the bars are on each edge, in pixels, for a target ratio inside a
|
||||
* given picture rect. A target wider than the source is blanked top and bottom;
|
||||
* a taller one is blanked left and right. Ratios within a pixel of the source
|
||||
* produce no bars at all rather than a hairline of rounding error.
|
||||
*/
|
||||
export function blankingInsets(rect: Rect, targetRatio: number): BlankingInsets {
|
||||
const none = { top: 0, bottom: 0, left: 0, right: 0 };
|
||||
if (!(targetRatio > 0) || !(rect.width > 0) || !(rect.height > 0)) return none;
|
||||
|
||||
const sourceRatio = rect.width / rect.height;
|
||||
|
||||
if (targetRatio > sourceRatio) {
|
||||
const bar = (rect.height - rect.width / targetRatio) / 2;
|
||||
return bar < 0.5 ? none : { top: bar, bottom: bar, left: 0, right: 0 };
|
||||
}
|
||||
|
||||
const bar = (rect.width - rect.height * targetRatio) / 2;
|
||||
return bar < 0.5 ? none : { top: 0, bottom: 0, left: bar, right: bar };
|
||||
}
|
||||
|
||||
/** True when the target crops nothing off this source — nothing to draw. */
|
||||
export function isFullFrame(insets: BlankingInsets): boolean {
|
||||
return !insets.top && !insets.bottom && !insets.left && !insets.right;
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { PLATE_EXTS, parsePlateFilename, plateContentType } from "./batch-upload-parser";
|
||||
|
||||
const SHOTS = ["DH2_VFX_058_120", "DH2_VFX_058_120_B", "DH2_VFX_058_10", "UNG_106_035_010"];
|
||||
|
||||
describe("parsePlateFilename", () => {
|
||||
it("derives the shot and label from a suffixed plate name", () => {
|
||||
const p = parsePlateFilename("DH2_VFX_058_120_REF.mov", SHOTS);
|
||||
expect(p.shotCode).toBe("DH2_VFX_058_120");
|
||||
expect(p.label).toBe("REF");
|
||||
expect(p.ext).toBe("mov");
|
||||
});
|
||||
|
||||
it("returns an empty label when the filename is exactly the shot code", () => {
|
||||
const p = parsePlateFilename("DH2_VFX_058_120.mov", SHOTS);
|
||||
expect(p.shotCode).toBe("DH2_VFX_058_120");
|
||||
expect(p.label).toBe("");
|
||||
});
|
||||
|
||||
it("prefers the longest matching shot code", () => {
|
||||
const p = parsePlateFilename("DH2_VFX_058_120_B_REF.mov", SHOTS);
|
||||
expect(p.shotCode).toBe("DH2_VFX_058_120_B");
|
||||
expect(p.label).toBe("REF");
|
||||
});
|
||||
|
||||
it("does not match a shot code that is only a partial segment", () => {
|
||||
// "DH2_VFX_058_10" must not swallow "DH2_VFX_058_1000"
|
||||
expect(parsePlateFilename("DH2_VFX_058_1000_REF.mov", SHOTS).shotCode).toBeNull();
|
||||
});
|
||||
|
||||
it("matches case-insensitively but reports the canonical shot code", () => {
|
||||
const p = parsePlateFilename("dh2_vfx_058_120_ref.mov", SHOTS);
|
||||
expect(p.shotCode).toBe("DH2_VFX_058_120");
|
||||
expect(p.label).toBe("ref");
|
||||
});
|
||||
|
||||
it("keeps multi-part labels intact", () => {
|
||||
expect(parsePlateFilename("UNG_106_035_010_BG_CLEAN_v002.mov", SHOTS).label).toBe(
|
||||
"BG_CLEAN_v002"
|
||||
);
|
||||
});
|
||||
|
||||
it("returns no shot code when nothing matches", () => {
|
||||
const p = parsePlateFilename("random_file.mov", SHOTS);
|
||||
expect(p.shotCode).toBeNull();
|
||||
expect(p.label).toBe("");
|
||||
});
|
||||
|
||||
it("handles filenames with dots in them", () => {
|
||||
const p = parsePlateFilename("DH2_VFX_058_120_REF.v2.mov", SHOTS);
|
||||
expect(p.shotCode).toBe("DH2_VFX_058_120");
|
||||
expect(p.label).toBe("REF.v2");
|
||||
expect(p.ext).toBe("mov");
|
||||
});
|
||||
});
|
||||
|
||||
describe("plateContentType", () => {
|
||||
it("maps every accepted extension to a video/* type", () => {
|
||||
for (const ext of PLATE_EXTS) {
|
||||
expect(plateContentType(`shot.${ext}`)).toMatch(/^video\//);
|
||||
}
|
||||
});
|
||||
|
||||
it("is case-insensitive", () => {
|
||||
expect(plateContentType("SHOT.MOV")).toBe("video/quicktime");
|
||||
});
|
||||
});
|
||||
@@ -93,3 +93,67 @@ export function findMatchingShotCode(
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
// ── Footage plates ────────────────────────────────────────────────────────────
|
||||
|
||||
/** Video extensions accepted by the footage plate batch upload. */
|
||||
export const PLATE_EXTS = new Set(["mov", "mp4", "m4v", "mxf", "avi", "mkv", "webm"]);
|
||||
|
||||
const PLATE_CONTENT_TYPES: Record<string, string> = {
|
||||
mov: "video/quicktime",
|
||||
mp4: "video/mp4",
|
||||
m4v: "video/mp4",
|
||||
mxf: "video/mxf",
|
||||
avi: "video/x-msvideo",
|
||||
mkv: "video/x-matroska",
|
||||
webm: "video/webm",
|
||||
};
|
||||
|
||||
/**
|
||||
* Derive a `video/*` content type from a plate filename's extension.
|
||||
*
|
||||
* Browsers routinely report an empty MIME type for .mov / .mxf files
|
||||
* (especially on Windows), and the presign endpoint rejects anything that
|
||||
* isn't `video/*`, so never trust `File.type` for these.
|
||||
*/
|
||||
export function plateContentType(fileName: string): string {
|
||||
const ext = fileName.split(".").pop()?.toLowerCase() ?? "";
|
||||
return PLATE_CONTENT_TYPES[ext] ?? "application/octet-stream";
|
||||
}
|
||||
|
||||
export interface ParsedPlateFilename {
|
||||
/** Lowercased extension without the leading dot */
|
||||
ext: string;
|
||||
/** Filename without the extension */
|
||||
nameWithoutExt: string;
|
||||
/** Shot code this file belongs to, or null when nothing matched */
|
||||
shotCode: string | null;
|
||||
/**
|
||||
* The filename remainder after the shot code, used as the plate label.
|
||||
* e.g. "DH2_VFX_058_120_REF.mov" → "REF".
|
||||
* Empty when the filename is exactly the shot code.
|
||||
*/
|
||||
label: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve a footage plate filename to a shot code and a plate label.
|
||||
*
|
||||
* e.g. "DH2_VFX_058_120_REF.mov" against shot "DH2_VFX_058_120"
|
||||
* → { shotCode: "DH2_VFX_058_120", label: "REF" }
|
||||
*/
|
||||
export function parsePlateFilename(
|
||||
fileName: string,
|
||||
shotCodes: string[]
|
||||
): ParsedPlateFilename {
|
||||
const lastDot = fileName.lastIndexOf(".");
|
||||
const ext = lastDot >= 0 ? fileName.slice(lastDot + 1).toLowerCase() : "";
|
||||
const nameWithoutExt = lastDot >= 0 ? fileName.slice(0, lastDot) : fileName;
|
||||
|
||||
const shotCode = findMatchingShotCode(nameWithoutExt, shotCodes);
|
||||
const label = shotCode
|
||||
? nameWithoutExt.slice(shotCode.length).replace(/^[_\-\s]+/, "").trim()
|
||||
: "";
|
||||
|
||||
return { ext, nameWithoutExt, shotCode, label };
|
||||
}
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { compareVersions, projectPace } from "./ops";
|
||||
|
||||
/**
|
||||
* The countdown's whole job is to say "you are not going to make it" early
|
||||
* enough to do something about it, so the arithmetic behind that sentence is
|
||||
* worth pinning down.
|
||||
*/
|
||||
describe("projectPace", () => {
|
||||
it("calls it behind when the trailing rate overruns the date", () => {
|
||||
// 29 shots to go, a fortnight left, 8 delivered last week: 1.14/day
|
||||
// against the 2.07/day needed, projecting 25.4 days of work — 11.4 days
|
||||
// past the date, rounded up to a whole day late.
|
||||
const pace = projectPace(29, 14, 8);
|
||||
expect(pace.verdict).toBe("behind");
|
||||
expect(pace.requiredPerDay).toBeCloseTo(2.07, 2);
|
||||
expect(pace.actualPerDay).toBeCloseTo(1.14, 2);
|
||||
expect(pace.daysBehind).toBe(12);
|
||||
});
|
||||
|
||||
it("calls a rate that only just lands tight rather than fine", () => {
|
||||
// Finishing on the last available day leaves no room for a QC failure.
|
||||
expect(projectPace(10, 10, 7).verdict).toBe("tight");
|
||||
});
|
||||
|
||||
it("is on track with real slack", () => {
|
||||
const pace = projectPace(5, 30, 7);
|
||||
expect(pace.verdict).toBe("ahead");
|
||||
expect(pace.daysBehind).toBeNull();
|
||||
});
|
||||
|
||||
it("separates a stall from being merely slow", () => {
|
||||
// Nothing shipped in a week is not a slow rate, it is no rate at all —
|
||||
// dividing by it would project infinity.
|
||||
const pace = projectPace(12, 20, 0);
|
||||
expect(pace.verdict).toBe("stalled");
|
||||
expect(pace.daysBehind).toBeNull();
|
||||
});
|
||||
|
||||
it("reports how far past the date an unfinished episode is", () => {
|
||||
const pace = projectPace(3, -5, 4);
|
||||
expect(pace.verdict).toBe("overdue");
|
||||
expect(pace.daysBehind).toBe(5);
|
||||
});
|
||||
|
||||
it("is complete once nothing is left, whatever the rate", () => {
|
||||
expect(projectPace(0, 3, 0).verdict).toBe("complete");
|
||||
expect(projectPace(0, 3, 0).requiredPerDay).toBe(0);
|
||||
});
|
||||
|
||||
it("does not divide by zero on the due date itself", () => {
|
||||
// daysLeft 0 means "today": the work still has to be quoted per day.
|
||||
expect(projectPace(4, 0, 7).requiredPerDay).toBe(4);
|
||||
expect(Number.isFinite(projectPace(4, 0, 7).requiredPerDay)).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* The farm strip flags machines running an older worker than the newest one
|
||||
* out there, which is only as reliable as this comparison: a plain string
|
||||
* compare ranks "1.10.0" below "1.9.0" and would quietly stop reporting drift
|
||||
* on the day the minor version reaches double digits.
|
||||
*/
|
||||
describe("compareVersions", () => {
|
||||
it("orders by numeric component, not lexically", () => {
|
||||
expect(compareVersions("1.10.0", "1.9.0")).toBeGreaterThan(0);
|
||||
expect(compareVersions("1.9.0", "1.10.0")).toBeLessThan(0);
|
||||
});
|
||||
|
||||
it("ignores the build stamp publish.ps1 appends", () => {
|
||||
// The exe reports "1.6.1+fe420b9"; two machines on the same release built
|
||||
// from different commits are not drifting.
|
||||
expect(compareVersions("1.6.1+fe420b9", "1.6.1")).toBe(0);
|
||||
expect(compareVersions("1.6.1+fe420b9", "1.6.0+2a88880")).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
it("treats a missing component as zero", () => {
|
||||
expect(compareVersions("1.6", "1.6.0")).toBe(0);
|
||||
expect(compareVersions("1.6", "1.6.1")).toBeLessThan(0);
|
||||
});
|
||||
|
||||
it("is transitive enough to pick a maximum", () => {
|
||||
const versions = ["1.5.2", "1.6.1", "1.6.0", "1.10.0"];
|
||||
const latest = versions.reduce((a, b) => (compareVersions(a, b) >= 0 ? a : b));
|
||||
expect(latest).toBe("1.10.0");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,750 @@
|
||||
import { db } from "@/lib/db";
|
||||
import { getConfigNumber } from "@/lib/render-pipeline/config";
|
||||
import { listMachines } from "@/lib/render-pipeline/machines";
|
||||
import type { ExportStatus, Prisma } from "@prisma/client";
|
||||
|
||||
/**
|
||||
* Data for the operations dashboard.
|
||||
*
|
||||
* Everything here is derived from state the pipeline maintains on its own —
|
||||
* export transitions, validation results, QC reviews, worker heartbeats — and
|
||||
* never from a field a human has to remember to fill in. The dashboard this
|
||||
* replaced counted `Task.dueDate`, which nothing in the pipeline writes, so
|
||||
* its headline numbers were structurally always zero.
|
||||
*/
|
||||
|
||||
/** Terminal-until-someone-acts: these never move on their own. */
|
||||
const FAILED_STATUSES: ExportStatus[] = [
|
||||
"RENDER_FAILED",
|
||||
"VALIDATION_FAILED",
|
||||
"PREVIEW_FAILED",
|
||||
"QC_FAILED",
|
||||
];
|
||||
|
||||
/** In flight: fine until they stop progressing, then they are stuck. */
|
||||
const IN_FLIGHT_STATUSES: ExportStatus[] = [
|
||||
"QUEUED",
|
||||
"RENDERING",
|
||||
"VALIDATING",
|
||||
"GENERATING_PREVIEW",
|
||||
];
|
||||
|
||||
export type BlockedSeverity = "critical" | "warning";
|
||||
|
||||
export interface BlockedExport {
|
||||
exportId: string;
|
||||
shotId: string;
|
||||
shotCode: string;
|
||||
versionString: string;
|
||||
projectCode: string;
|
||||
episode: string | null;
|
||||
status: ExportStatus;
|
||||
severity: BlockedSeverity;
|
||||
/** When it entered the status it is stuck in. */
|
||||
since: Date;
|
||||
/** What a human has to do something about, in one line. */
|
||||
reason: string;
|
||||
artistName: string | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Everything that has stopped moving and needs a person.
|
||||
*
|
||||
* Two kinds: exports in a failed state (which stay there forever — nothing
|
||||
* retries a VALIDATION_FAILED on its own), and exports sitting in a live state
|
||||
* far longer than that state should take, which is how a dead worker or a
|
||||
* forgotten QC pass shows up. A failed export is currently only visible if
|
||||
* someone thinks to open the render queue and filter for it.
|
||||
*/
|
||||
export async function getBlockedExports(
|
||||
opts: { artistId?: string; limit?: number } = {}
|
||||
): Promise<BlockedExport[]> {
|
||||
const { artistId, limit = 25 } = opts;
|
||||
const [qcStaleHours, stalledHours] = await Promise.all([
|
||||
getConfigNumber("dashboard.qcStaleHours"),
|
||||
getConfigNumber("dashboard.stalledJobHours"),
|
||||
]);
|
||||
const now = Date.now();
|
||||
const qcCutoff = new Date(now - qcStaleHours * 3600_000);
|
||||
const stalledCutoff = new Date(now - stalledHours * 3600_000);
|
||||
|
||||
const rows = await db.export.findMany({
|
||||
where: {
|
||||
// Finished shows would otherwise fill the list with failures nobody
|
||||
// intends to fix. Export carries a projectId but no project relation, so
|
||||
// the scope is reached through the shot.
|
||||
shot: {
|
||||
project: { status: { in: ["ACTIVE", "ON_HOLD"] } },
|
||||
// An artist's dashboard shows the failures that are theirs to fix.
|
||||
...(artistId ? { artistId } : {}),
|
||||
},
|
||||
OR: [
|
||||
{ status: { in: FAILED_STATUSES } },
|
||||
{ status: "READY_FOR_QC", statusChangedAt: { lt: qcCutoff } },
|
||||
{ status: { in: IN_FLIGHT_STATUSES }, statusChangedAt: { lt: stalledCutoff } },
|
||||
],
|
||||
},
|
||||
orderBy: { statusChangedAt: "asc" },
|
||||
take: limit,
|
||||
select: {
|
||||
id: true,
|
||||
shotId: true,
|
||||
versionString: true,
|
||||
status: true,
|
||||
statusChangedAt: true,
|
||||
shot: {
|
||||
select: {
|
||||
shotCode: true,
|
||||
episode: true,
|
||||
artist: { select: { name: true, email: true } },
|
||||
project: { select: { code: true } },
|
||||
},
|
||||
},
|
||||
// Only the failures matter for the reason line, and only a couple of
|
||||
// them: the point is to say what to look at, not to reproduce the
|
||||
// validation report.
|
||||
validations: {
|
||||
where: { status: "FAIL" },
|
||||
orderBy: { createdAt: "desc" },
|
||||
take: 3,
|
||||
select: { checkName: true, expected: true, actual: true, message: true },
|
||||
},
|
||||
qcReviews: {
|
||||
orderBy: { createdAt: "desc" },
|
||||
take: 1,
|
||||
select: { result: true, notes: true, reviewerName: true },
|
||||
},
|
||||
renderJobs: {
|
||||
orderBy: { createdAt: "desc" },
|
||||
take: 1,
|
||||
select: {
|
||||
errorMessage: true,
|
||||
status: true,
|
||||
attempt: true,
|
||||
maxAttempts: true,
|
||||
machine: { select: { name: true } },
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const blocked = rows.map((row): BlockedExport => {
|
||||
const job = row.renderJobs[0];
|
||||
const qc = row.qcReviews[0];
|
||||
let reason: string;
|
||||
|
||||
switch (row.status) {
|
||||
case "VALIDATION_FAILED": {
|
||||
const first = row.validations[0];
|
||||
const extra = row.validations.length > 1 ? ` (+${row.validations.length - 1} more)` : "";
|
||||
reason = first
|
||||
? `${first.checkName} — ${first.message ?? `expected ${first.expected ?? "?"}, got ${first.actual ?? "?"}`}${extra}`
|
||||
: "Validation failed";
|
||||
break;
|
||||
}
|
||||
case "QC_FAILED":
|
||||
reason = qc?.notes?.trim()
|
||||
? `${qc.notes.trim()}${qc.reviewerName ? ` — ${qc.reviewerName}` : ""}`
|
||||
: "Failed technical QC";
|
||||
break;
|
||||
case "RENDER_FAILED":
|
||||
case "PREVIEW_FAILED":
|
||||
reason =
|
||||
job?.errorMessage?.trim() ||
|
||||
(row.status === "RENDER_FAILED" ? "Render failed" : "Preview build failed");
|
||||
if (job && job.attempt >= job.maxAttempts) reason += ` (attempt ${job.attempt}/${job.maxAttempts})`;
|
||||
break;
|
||||
case "READY_FOR_QC":
|
||||
reason = "Waiting on a QC pass";
|
||||
break;
|
||||
default:
|
||||
// Still nominally in flight, but past the point where that is normal.
|
||||
reason = job?.machine?.name
|
||||
? `No progress since claim on ${job.machine.name}`
|
||||
: "Queued with no machine picking it up";
|
||||
}
|
||||
|
||||
return {
|
||||
exportId: row.id,
|
||||
shotId: row.shotId,
|
||||
shotCode: row.shot.shotCode,
|
||||
versionString: row.versionString,
|
||||
projectCode: row.shot.project.code,
|
||||
episode: row.shot.episode,
|
||||
status: row.status,
|
||||
severity: FAILED_STATUSES.includes(row.status) ? "critical" : "warning",
|
||||
since: row.statusChangedAt,
|
||||
reason,
|
||||
artistName: row.shot.artist?.name ?? row.shot.artist?.email ?? null,
|
||||
};
|
||||
});
|
||||
|
||||
// Failures first, then whatever has been waiting longest. Both orderings
|
||||
// matter: severity decides what to fix, age decides what to fix first.
|
||||
return blocked.sort((a, b) => {
|
||||
if (a.severity !== b.severity) return a.severity === "critical" ? -1 : 1;
|
||||
return a.since.getTime() - b.since.getTime();
|
||||
});
|
||||
}
|
||||
|
||||
export type CountdownVerdict = "complete" | "overdue" | "stalled" | "behind" | "tight" | "ahead";
|
||||
|
||||
export interface EpisodeCountdown {
|
||||
projectId: string;
|
||||
projectCode: string;
|
||||
projectName: string;
|
||||
/** Null on a standard (non-episodic) show, which has one date of its own. */
|
||||
episode: string | null;
|
||||
dueDate: Date;
|
||||
/** Calendar days to the due date; negative once it has passed. */
|
||||
daysLeft: number;
|
||||
total: number;
|
||||
delivered: number;
|
||||
inQc: number;
|
||||
inProgress: number;
|
||||
notStarted: number;
|
||||
/** Shots per day still needed to land the rest by the due date. */
|
||||
requiredPerDay: number;
|
||||
/** Shots per day actually delivered over the last week. */
|
||||
actualPerDay: number;
|
||||
verdict: CountdownVerdict;
|
||||
/**
|
||||
* How late this is: the days the current rate overruns by when `verdict` is
|
||||
* "behind", or the days the date has already passed when it is "overdue".
|
||||
*/
|
||||
daysBehind: number | null;
|
||||
}
|
||||
|
||||
const DAY_MS = 86_400_000;
|
||||
/** Shots past QC but not yet in a delivered package. */
|
||||
const POST_QC_STATUSES: ExportStatus[] = ["READY_FOR_QC", "READY_FOR_DELIVERY", "PACKAGED"];
|
||||
|
||||
/**
|
||||
* Turns "23 shots left, 14 days, 8 delivered last week" into a verdict.
|
||||
*
|
||||
* Kept free of the database so the arithmetic that decides whether a producer
|
||||
* panics can be tested directly. The trailing week is the rate we have
|
||||
* evidence for; anything else is a hope. A run that only just lands on the due
|
||||
* date is reported as tight rather than fine — finishing on the last available
|
||||
* day is luck, not schedule.
|
||||
*/
|
||||
export function projectPace(
|
||||
remaining: number,
|
||||
daysLeft: number,
|
||||
deliveredThisWeek: number
|
||||
): Pick<EpisodeCountdown, "requiredPerDay" | "actualPerDay" | "verdict" | "daysBehind"> {
|
||||
const actualPerDay = deliveredThisWeek / 7;
|
||||
const requiredPerDay = remaining <= 0 ? 0 : remaining / Math.max(daysLeft, 1);
|
||||
|
||||
if (remaining <= 0) {
|
||||
return { requiredPerDay, actualPerDay, verdict: "complete", daysBehind: null };
|
||||
}
|
||||
if (daysLeft < 0) {
|
||||
return { requiredPerDay, actualPerDay, verdict: "overdue", daysBehind: -daysLeft };
|
||||
}
|
||||
if (actualPerDay === 0) {
|
||||
return { requiredPerDay, actualPerDay, verdict: "stalled", daysBehind: null };
|
||||
}
|
||||
|
||||
const projectedDays = remaining / actualPerDay;
|
||||
if (projectedDays > daysLeft) {
|
||||
return {
|
||||
requiredPerDay,
|
||||
actualPerDay,
|
||||
verdict: "behind",
|
||||
daysBehind: Math.ceil(projectedDays - daysLeft),
|
||||
};
|
||||
}
|
||||
return {
|
||||
requiredPerDay,
|
||||
actualPerDay,
|
||||
verdict: projectedDays > daysLeft * 0.9 ? "tight" : "ahead",
|
||||
daysBehind: null,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Are we going to make the date, per episode?
|
||||
*
|
||||
* A shot counts as delivered when it appears in a package that has actually
|
||||
* gone out — a DeliveryItem in a DELIVERED EXR_DELIVERY package. Shot.status
|
||||
* is deliberately not the measure: it says where the work is, not whether the
|
||||
* client has the frames, and a review package (MOV_REVIEW) ships nothing.
|
||||
*
|
||||
* The run rate compares what is left per remaining day against what the studio
|
||||
* actually managed per day over the last week, which is the only honest way to
|
||||
* turn "23 shots to go" into "you are not going to make it".
|
||||
*/
|
||||
export async function getDeliveryCountdown(limit = 6): Promise<EpisodeCountdown[]> {
|
||||
const projects = await db.project.findMany({
|
||||
where: { status: "ACTIVE" },
|
||||
select: {
|
||||
id: true,
|
||||
code: true,
|
||||
name: true,
|
||||
dueDate: true,
|
||||
projectType: true,
|
||||
episodeDueDates: { select: { episode: true, dueDate: true } },
|
||||
},
|
||||
});
|
||||
if (projects.length === 0) return [];
|
||||
|
||||
const projectIds = projects.map((p) => p.id);
|
||||
const weekAgo = new Date(Date.now() - 7 * DAY_MS);
|
||||
|
||||
const [shots, postQc, deliveredItems] = await Promise.all([
|
||||
db.shot.findMany({
|
||||
where: { projectId: { in: projectIds } },
|
||||
select: { id: true, projectId: true, episode: true, status: true },
|
||||
}),
|
||||
db.export.findMany({
|
||||
where: { status: { in: POST_QC_STATUSES }, shot: { projectId: { in: projectIds } } },
|
||||
select: { shotId: true },
|
||||
}),
|
||||
db.deliveryItem.findMany({
|
||||
where: {
|
||||
package: {
|
||||
projectId: { in: projectIds },
|
||||
kind: "EXR_DELIVERY",
|
||||
status: "DELIVERED",
|
||||
},
|
||||
},
|
||||
select: { shotId: true, package: { select: { deliveredAt: true } } },
|
||||
}),
|
||||
]);
|
||||
|
||||
const postQcShots = new Set(postQc.map((e) => e.shotId));
|
||||
// A shot can be in several packages (a redelivery); the first one out is the
|
||||
// one that counts towards the rate.
|
||||
const deliveredAt = new Map<string, Date>();
|
||||
for (const item of deliveredItems) {
|
||||
const when = item.package.deliveredAt;
|
||||
if (!when) continue;
|
||||
const seen = deliveredAt.get(item.shotId);
|
||||
if (!seen || when < seen) deliveredAt.set(item.shotId, when);
|
||||
}
|
||||
|
||||
const now = Date.now();
|
||||
const rows: EpisodeCountdown[] = [];
|
||||
|
||||
for (const project of projects) {
|
||||
// Episodic shows carry a date per episode; a standard show has one date on
|
||||
// the project itself, and is treated as a single unnamed target.
|
||||
const targets: { episode: string | null; dueDate: Date }[] =
|
||||
project.projectType === "EPISODIC"
|
||||
? project.episodeDueDates.map((e) => ({ episode: e.episode, dueDate: e.dueDate }))
|
||||
: project.dueDate
|
||||
? [{ episode: null, dueDate: project.dueDate }]
|
||||
: [];
|
||||
|
||||
for (const target of targets) {
|
||||
const targetShots = shots.filter(
|
||||
(s) =>
|
||||
s.projectId === project.id &&
|
||||
(target.episode === null || (s.episode ?? "") === target.episode)
|
||||
);
|
||||
if (targetShots.length === 0) continue;
|
||||
|
||||
let delivered = 0;
|
||||
let inQc = 0;
|
||||
let inProgress = 0;
|
||||
let notStarted = 0;
|
||||
let deliveredThisWeek = 0;
|
||||
|
||||
for (const shot of targetShots) {
|
||||
const when = deliveredAt.get(shot.id);
|
||||
if (when) {
|
||||
delivered++;
|
||||
if (when >= weekAgo) deliveredThisWeek++;
|
||||
} else if (postQcShots.has(shot.id)) {
|
||||
inQc++;
|
||||
} else if (shot.status === "WAITING") {
|
||||
notStarted++;
|
||||
} else {
|
||||
inProgress++;
|
||||
}
|
||||
}
|
||||
|
||||
const total = targetShots.length;
|
||||
const daysLeft = Math.ceil((target.dueDate.getTime() - now) / DAY_MS);
|
||||
const pace = projectPace(total - delivered, daysLeft, deliveredThisWeek);
|
||||
|
||||
// A finished episode whose date has passed is history, not a countdown.
|
||||
if (pace.verdict === "complete" && daysLeft < 0) continue;
|
||||
|
||||
rows.push({
|
||||
projectId: project.id,
|
||||
projectCode: project.code,
|
||||
projectName: project.name,
|
||||
episode: target.episode,
|
||||
dueDate: target.dueDate,
|
||||
daysLeft,
|
||||
total,
|
||||
delivered,
|
||||
inQc,
|
||||
inProgress,
|
||||
notStarted,
|
||||
...pace,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return rows.sort((a, b) => a.dueDate.getTime() - b.dueDate.getTime()).slice(0, limit);
|
||||
}
|
||||
|
||||
export interface OpsCounts {
|
||||
blocked: number;
|
||||
inQc: number;
|
||||
readyToDeliver: number;
|
||||
awaitingClientReview: number;
|
||||
activeProjects: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* The headline numbers, all scoped to live productions.
|
||||
*
|
||||
* The counters these replaced were unscoped and cumulative — "approved" across
|
||||
* every project the studio has ever finished only ever goes up, so it never
|
||||
* told anyone anything. Each of these can go down, which is what makes it
|
||||
* worth looking at twice in a day.
|
||||
*/
|
||||
export async function getOpsCounts(artistId?: string): Promise<OpsCounts> {
|
||||
// Export has a projectId column but no project relation, so live-production
|
||||
// scope is reached through the shot. An artist gets their own figures, so the
|
||||
// cards agree with the blocked list underneath them rather than quoting a
|
||||
// studio-wide number beside a personal one.
|
||||
const liveProject: Prisma.ExportWhereInput = {
|
||||
shot: {
|
||||
project: { status: { in: ["ACTIVE", "ON_HOLD"] } },
|
||||
...(artistId ? { artistId } : {}),
|
||||
},
|
||||
};
|
||||
const [qcStaleHours, stalledHours] = await Promise.all([
|
||||
getConfigNumber("dashboard.qcStaleHours"),
|
||||
getConfigNumber("dashboard.stalledJobHours"),
|
||||
]);
|
||||
const now = Date.now();
|
||||
|
||||
const [blocked, inQc, readyToDeliver, awaitingClientReview, activeProjects] = await Promise.all([
|
||||
db.export.count({
|
||||
where: {
|
||||
...liveProject,
|
||||
OR: [
|
||||
{ status: { in: FAILED_STATUSES } },
|
||||
{ status: "READY_FOR_QC", statusChangedAt: { lt: new Date(now - qcStaleHours * 3600_000) } },
|
||||
{
|
||||
status: { in: IN_FLIGHT_STATUSES },
|
||||
statusChangedAt: { lt: new Date(now - stalledHours * 3600_000) },
|
||||
},
|
||||
],
|
||||
},
|
||||
}),
|
||||
db.export.count({ where: { ...liveProject, status: "READY_FOR_QC" } }),
|
||||
db.export.count({ where: { ...liveProject, status: "READY_FOR_DELIVERY" } }),
|
||||
// Sent to the client and still unanswered — the wait that is not ours to
|
||||
// end, as opposed to notes we have not acted on yet.
|
||||
db.version.count({
|
||||
where: {
|
||||
approvalStatus: "PENDING_REVIEW",
|
||||
isClientVisible: true,
|
||||
isLatest: true,
|
||||
shot: {
|
||||
project: { status: { in: ["ACTIVE", "ON_HOLD"] } },
|
||||
...(artistId ? { artistId } : {}),
|
||||
},
|
||||
},
|
||||
}),
|
||||
db.project.count({ where: { status: "ACTIVE" } }),
|
||||
]);
|
||||
|
||||
return { blocked, inQc, readyToDeliver, awaitingClientReview, activeProjects };
|
||||
}
|
||||
|
||||
/** How long an export may sit in READY_FOR_QC before the UI calls it stale. */
|
||||
export function getQcStaleHours(): Promise<number> {
|
||||
return getConfigNumber("dashboard.qcStaleHours");
|
||||
}
|
||||
|
||||
export interface QcQueueEntry {
|
||||
exportId: string;
|
||||
shotCode: string;
|
||||
versionString: string;
|
||||
projectCode: string;
|
||||
episode: string | null;
|
||||
since: Date;
|
||||
frameStart: number;
|
||||
frameEnd: number;
|
||||
submittedBy: string | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* What is waiting on a human to look at the frames.
|
||||
*
|
||||
* QC is the last gate before anything can be packaged, and it is the only
|
||||
* stage in the pipeline that cannot drain itself — everything before it is
|
||||
* worked by the farm. Depth here is the single best predictor of a delivery
|
||||
* slipping, and until now it had no home outside the render queue's filter.
|
||||
*/
|
||||
export async function getQcQueue(limit = 8): Promise<QcQueueEntry[]> {
|
||||
const rows = await db.export.findMany({
|
||||
where: {
|
||||
status: "READY_FOR_QC",
|
||||
shot: { project: { status: { in: ["ACTIVE", "ON_HOLD"] } } },
|
||||
},
|
||||
orderBy: { statusChangedAt: "asc" },
|
||||
take: limit,
|
||||
select: {
|
||||
id: true,
|
||||
versionString: true,
|
||||
statusChangedAt: true,
|
||||
frameStart: true,
|
||||
frameEnd: true,
|
||||
submittedByName: true,
|
||||
shot: {
|
||||
select: { shotCode: true, episode: true, project: { select: { code: true } } },
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
return rows.map((row) => ({
|
||||
exportId: row.id,
|
||||
shotCode: row.shot.shotCode,
|
||||
versionString: row.versionString,
|
||||
projectCode: row.shot.project.code,
|
||||
episode: row.shot.episode,
|
||||
since: row.statusChangedAt,
|
||||
frameStart: row.frameStart,
|
||||
frameEnd: row.frameEnd,
|
||||
// Free text from the panel's config: Export keeps submittedById for the
|
||||
// resolved account but carries no relation to it.
|
||||
submittedBy: row.submittedByName,
|
||||
}));
|
||||
}
|
||||
|
||||
export interface DeliverySummary {
|
||||
id: string;
|
||||
packageNumber: number;
|
||||
name: string;
|
||||
projectCode: string;
|
||||
episode: string;
|
||||
kind: string;
|
||||
status: string;
|
||||
itemCount: number;
|
||||
errorMessage: string | null;
|
||||
/** Most recent of delivered/built/created — what the timestamp column means. */
|
||||
at: Date;
|
||||
atLabel: "delivered" | "built" | "created";
|
||||
/** BUILDING for longer than a build plausibly takes. */
|
||||
stuck: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Recent packages, and whether any of them went wrong.
|
||||
*
|
||||
* A failed delivery build is otherwise silent: the export stays
|
||||
* READY_FOR_DELIVERY, nothing is on the delivery volume, and the only trace is
|
||||
* a status on a page nobody opens between deliveries.
|
||||
*/
|
||||
export async function getRecentDeliveries(limit = 5): Promise<DeliverySummary[]> {
|
||||
const rows = await db.deliveryPackage.findMany({
|
||||
where: { project: { status: { in: ["ACTIVE", "ON_HOLD"] } } },
|
||||
orderBy: { createdAt: "desc" },
|
||||
take: limit,
|
||||
select: {
|
||||
id: true,
|
||||
packageNumber: true,
|
||||
name: true,
|
||||
episode: true,
|
||||
kind: true,
|
||||
status: true,
|
||||
errorMessage: true,
|
||||
createdAt: true,
|
||||
builtAt: true,
|
||||
deliveredAt: true,
|
||||
project: { select: { code: true } },
|
||||
_count: { select: { items: true } },
|
||||
},
|
||||
});
|
||||
|
||||
const buildStuckAfter = 2 * 3600_000;
|
||||
return rows.map((row) => {
|
||||
const at = row.deliveredAt ?? row.builtAt ?? row.createdAt;
|
||||
return {
|
||||
id: row.id,
|
||||
packageNumber: row.packageNumber,
|
||||
name: row.name,
|
||||
projectCode: row.project.code,
|
||||
episode: row.episode,
|
||||
kind: row.kind,
|
||||
status: row.status,
|
||||
itemCount: row._count.items,
|
||||
errorMessage: row.errorMessage,
|
||||
at,
|
||||
atLabel: row.deliveredAt ? "delivered" : row.builtAt ? "built" : "created",
|
||||
// A build that never finished leaves the package sitting in BUILDING
|
||||
// forever; nothing times it out.
|
||||
stuck: row.status === "BUILDING" && Date.now() - row.createdAt.getTime() > buildStuckAfter,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
export interface CourtSide {
|
||||
count: number;
|
||||
items: { id: string; shotCode: string; label: string; href: string }[];
|
||||
}
|
||||
|
||||
export interface WhoseCourt {
|
||||
client: CourtSide;
|
||||
us: CourtSide;
|
||||
}
|
||||
|
||||
/**
|
||||
* Which waits are ours and which are the client's.
|
||||
*
|
||||
* The distinction is the useful part: a version sitting unanswered for eleven
|
||||
* days is a phone call, while notes nobody has actioned are a scheduling
|
||||
* problem. Lumping both into "needs revisions" hid which was which.
|
||||
*/
|
||||
export async function getWhoseCourt(perSide = 4): Promise<WhoseCourt> {
|
||||
const liveShot: Prisma.ShotWhereInput = {
|
||||
project: { status: { in: ["ACTIVE", "ON_HOLD"] } },
|
||||
};
|
||||
|
||||
const [withClient, openNotes] = await Promise.all([
|
||||
db.version.findMany({
|
||||
where: {
|
||||
approvalStatus: "PENDING_REVIEW",
|
||||
isClientVisible: true,
|
||||
isLatest: true,
|
||||
shot: liveShot,
|
||||
},
|
||||
// Longest wait first — that is the one worth chasing.
|
||||
orderBy: [{ sharedAt: { sort: "asc", nulls: "last" } }, { createdAt: "asc" }],
|
||||
take: perSide,
|
||||
select: {
|
||||
id: true,
|
||||
versionNumber: true,
|
||||
sharedAt: true,
|
||||
createdAt: true,
|
||||
shot: { select: { id: true, shotCode: true } },
|
||||
},
|
||||
}),
|
||||
// Unresolved notes on the version currently in play. Grouped in memory
|
||||
// because the interesting unit is the shot, not the comment.
|
||||
db.comment.findMany({
|
||||
where: {
|
||||
isResolved: false,
|
||||
version: { isLatest: true, shot: liveShot },
|
||||
},
|
||||
select: { id: true, version: { select: { shot: { select: { id: true, shotCode: true } } } } },
|
||||
}),
|
||||
]);
|
||||
|
||||
const byShot = new Map<string, { shotCode: string; count: number }>();
|
||||
for (const note of openNotes) {
|
||||
const shot = note.version?.shot;
|
||||
if (!shot) continue;
|
||||
const entry = byShot.get(shot.id) ?? { shotCode: shot.shotCode, count: 0 };
|
||||
entry.count++;
|
||||
byShot.set(shot.id, entry);
|
||||
}
|
||||
const ours = [...byShot.entries()].sort((a, b) => b[1].count - a[1].count);
|
||||
|
||||
const days = (from: Date) => Math.max(0, Math.floor((Date.now() - from.getTime()) / DAY_MS));
|
||||
|
||||
return {
|
||||
client: {
|
||||
count: withClient.length,
|
||||
items: withClient.map((v) => ({
|
||||
id: v.id,
|
||||
shotCode: v.shot?.shotCode ?? "—",
|
||||
label: `${days(v.sharedAt ?? v.createdAt)}d`,
|
||||
href: `/review/${v.id}`,
|
||||
})),
|
||||
},
|
||||
us: {
|
||||
count: ours.length,
|
||||
items: ours.slice(0, perSide).map(([shotId, entry]) => ({
|
||||
id: shotId,
|
||||
shotCode: entry.shotCode,
|
||||
label: `${entry.count} note${entry.count === 1 ? "" : "s"}`,
|
||||
href: `/shot-status`,
|
||||
})),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export interface FarmStatus {
|
||||
machines: Awaited<ReturnType<typeof listMachines>>;
|
||||
online: number;
|
||||
total: number;
|
||||
queued: { render: number; preview: number; delivery: number; blender: number; total: number };
|
||||
running: number;
|
||||
/** Age of the oldest job still waiting to be claimed, in ms. */
|
||||
oldestQueuedMs: number | null;
|
||||
/** Highest worker version any machine reports, and who is behind it. */
|
||||
latestWorkerVersion: string | null;
|
||||
behindMachines: { name: string; workerVersion: string | null }[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Farm health in one strip: who is up, what is waiting, and — because a
|
||||
* worker's version is what decides whether it has a given fix — which
|
||||
* machines are running something older than the newest one out there.
|
||||
*/
|
||||
export async function getFarmStatus(): Promise<FarmStatus> {
|
||||
const [machines, queuedByType, running, oldest] = await Promise.all([
|
||||
listMachines(),
|
||||
db.renderJob.groupBy({ by: ["type"], where: { status: "QUEUED" }, _count: { _all: true } }),
|
||||
db.renderJob.count({ where: { status: { in: ["CLAIMED", "RUNNING"] } } }),
|
||||
db.renderJob.findFirst({
|
||||
where: { status: "QUEUED" },
|
||||
orderBy: { createdAt: "asc" },
|
||||
select: { createdAt: true },
|
||||
}),
|
||||
]);
|
||||
|
||||
const countOf = (type: string) =>
|
||||
queuedByType.find((q) => q.type === type)?._count._all ?? 0;
|
||||
|
||||
const versions = machines
|
||||
.map((m) => m.workerVersion)
|
||||
.filter((v): v is string => Boolean(v));
|
||||
const latest = versions.length ? versions.reduce((a, b) => (compareVersions(a, b) >= 0 ? a : b)) : null;
|
||||
|
||||
return {
|
||||
machines,
|
||||
online: machines.filter((m) => m.status === "ONLINE").length,
|
||||
total: machines.length,
|
||||
queued: {
|
||||
render: countOf("AE_RENDER"),
|
||||
preview: countOf("PREVIEW_ONLY"),
|
||||
delivery: countOf("DELIVERY_BUILD"),
|
||||
blender: countOf("BLENDER_RENDER"),
|
||||
total: queuedByType.reduce((sum, q) => sum + q._count._all, 0),
|
||||
},
|
||||
running,
|
||||
oldestQueuedMs: oldest ? Date.now() - oldest.createdAt.getTime() : null,
|
||||
latestWorkerVersion: latest,
|
||||
behindMachines: latest
|
||||
? machines
|
||||
.filter((m) => m.workerVersion !== latest)
|
||||
.map((m) => ({ name: m.name, workerVersion: m.workerVersion }))
|
||||
: [],
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Compares "1.6.1+fe420b9" style versions numerically, ignoring the build
|
||||
* stamp publish.ps1 appends. A string compare would rank 1.10.0 below 1.9.0.
|
||||
*/
|
||||
export function compareVersions(a: string, b: string): number {
|
||||
const parts = (v: string) =>
|
||||
v.split("+")[0].split(".").map((n) => Number.parseInt(n, 10) || 0);
|
||||
const [pa, pb] = [parts(a), parts(b)];
|
||||
for (let i = 0; i < Math.max(pa.length, pb.length); i++) {
|
||||
const diff = (pa[i] ?? 0) - (pb[i] ?? 0);
|
||||
if (diff !== 0) return diff;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
import { Prisma } from "@prisma/client";
|
||||
import { db } from "@/lib/db";
|
||||
|
||||
/**
|
||||
* The still that stands for a project.
|
||||
*
|
||||
* There is no poster field on Project, and adding one would mean somebody
|
||||
* maintaining it. The shots already carry the images, and one of them is
|
||||
* already marked as the shot that represents the show — `isKeyShot` — so the
|
||||
* poster is chosen rather than uploaded:
|
||||
*
|
||||
* 1. a key shot with a still, then
|
||||
* 2. the most recently touched shot with a still.
|
||||
*
|
||||
* Within each, `thumbnailUrl` beats `generatedThumbnailUrl`, the same
|
||||
* precedence the rest of the app displays shots by (lib/shot-thumbnail.ts):
|
||||
* the reference frame from the brief is a deliberate choice, a promoted render
|
||||
* frame is whatever the pipeline happened to land on.
|
||||
*
|
||||
* The choice is deterministic, not random — a card whose image changes between
|
||||
* two loads of the same page reads as a glitch, and the eye stops using the
|
||||
* image to find the project.
|
||||
*/
|
||||
export interface ProjectPoster {
|
||||
url: string;
|
||||
shotCode: string;
|
||||
/** True when this is the show's marked key shot rather than a fallback. */
|
||||
isKeyShot: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* One poster per project in a single query.
|
||||
*
|
||||
* DISTINCT ON is Postgres-only and deliberate: the alternative is either a
|
||||
* query per project or dragging back every shot that has a still just to keep
|
||||
* the first of each in memory.
|
||||
*/
|
||||
export async function getProjectPosters(
|
||||
projectIds: string[]
|
||||
): Promise<Map<string, ProjectPoster>> {
|
||||
if (projectIds.length === 0) return new Map();
|
||||
|
||||
const rows = await db.$queryRaw<
|
||||
{ projectId: string; url: string; shotCode: string; isKeyShot: boolean }[]
|
||||
>(Prisma.sql`
|
||||
SELECT DISTINCT ON (s."projectId")
|
||||
s."projectId" AS "projectId",
|
||||
COALESCE(NULLIF(s."thumbnailUrl", ''), NULLIF(s."generatedThumbnailUrl", '')) AS "url",
|
||||
s."shotCode" AS "shotCode",
|
||||
s."isKeyShot" AS "isKeyShot"
|
||||
FROM "shots" s
|
||||
WHERE s."projectId" IN (${Prisma.join(projectIds)})
|
||||
AND COALESCE(NULLIF(s."thumbnailUrl", ''), NULLIF(s."generatedThumbnailUrl", '')) IS NOT NULL
|
||||
ORDER BY s."projectId", s."isKeyShot" DESC, s."updatedAt" DESC
|
||||
`);
|
||||
|
||||
return new Map(
|
||||
rows.map((row) => [
|
||||
row.projectId,
|
||||
{ url: row.url, shotCode: row.shotCode, isKeyShot: row.isKeyShot },
|
||||
])
|
||||
);
|
||||
}
|
||||
@@ -48,6 +48,13 @@ export const PIPELINE_CONFIG_DEFAULTS = {
|
||||
// names as a warning, so it is a config fix rather than a code change.
|
||||
"preview.slateScopeProp": "Scope",
|
||||
"preview.slateSubmissionProp": "Notes",
|
||||
/**
|
||||
* When the dashboard starts calling something stuck. An export waiting on QC
|
||||
* is normal for a day and suspicious after two; an export in a live render
|
||||
* state has either progressed or died long before four hours are up.
|
||||
*/
|
||||
"dashboard.qcStaleHours": 48,
|
||||
"dashboard.stalledJobHours": 4,
|
||||
} as const;
|
||||
|
||||
export type PipelineConfigKey = keyof typeof PIPELINE_CONFIG_DEFAULTS;
|
||||
|
||||
@@ -0,0 +1,98 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { DELIVERY_CONFIG_DEFAULT, applyTokens, dateTokens, nextPackageName, tidyPath } from "./deliveries";
|
||||
|
||||
const BASE = "20260901_Delivery";
|
||||
|
||||
describe("nextPackageName", () => {
|
||||
it("uses the bare base for the first package of the day", () => {
|
||||
expect(nextPackageName(BASE, [])).toBe(BASE);
|
||||
});
|
||||
|
||||
it("suffixes later packages sharing the base", () => {
|
||||
expect(nextPackageName(BASE, [BASE])).toBe(`${BASE}_02`);
|
||||
expect(nextPackageName(BASE, [BASE, `${BASE}_02`])).toBe(`${BASE}_03`);
|
||||
});
|
||||
|
||||
it("never reuses a number after a gap", () => {
|
||||
expect(nextPackageName(BASE, [BASE, `${BASE}_02`, `${BASE}_04`])).toBe(`${BASE}_05`);
|
||||
});
|
||||
|
||||
it("ignores names that only share a prefix", () => {
|
||||
expect(nextPackageName(BASE, [`${BASE}_final`, "20260902_Delivery"])).toBe(BASE);
|
||||
});
|
||||
});
|
||||
|
||||
describe("delivery layout", () => {
|
||||
const tokens = {
|
||||
deliveryRoot: "//SAN/DELIVERY",
|
||||
showId: "ACME",
|
||||
episode: "101",
|
||||
packageName: BASE,
|
||||
};
|
||||
|
||||
it("separates shows so two shows' episode 101 cannot collide", () => {
|
||||
const acme = applyTokens(DELIVERY_CONFIG_DEFAULT.layout.packageDir, tokens);
|
||||
const other = applyTokens(DELIVERY_CONFIG_DEFAULT.layout.packageDir, { ...tokens, showId: "BRAVO" });
|
||||
expect(acme).toBe("//SAN/DELIVERY/ACME/101/20260901_Delivery");
|
||||
expect(other).not.toBe(acme);
|
||||
});
|
||||
|
||||
it("puts producer reviews under the show too", () => {
|
||||
expect(applyTokens(DELIVERY_CONFIG_DEFAULT.layout.reviewDir, tokens)).toBe(
|
||||
"//SAN/DELIVERY/ACME/PRODUCER_REVIEWS/20260901_Delivery"
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("tidyPath", () => {
|
||||
it("drops the empty segment a non-episodic show leaves behind", () => {
|
||||
const raw = applyTokens(DELIVERY_CONFIG_DEFAULT.layout.packageDir, {
|
||||
deliveryRoot: "//SAN/DELIVERY",
|
||||
showId: "ACME",
|
||||
episode: "",
|
||||
packageName: BASE,
|
||||
});
|
||||
expect(tidyPath(raw)).toBe("//SAN/DELIVERY/ACME/20260901_Delivery");
|
||||
});
|
||||
|
||||
it("keeps the UNC root intact", () => {
|
||||
expect(tidyPath("//SAN/DELIVERY/ACME")).toBe("//SAN/DELIVERY/ACME");
|
||||
});
|
||||
|
||||
it("leaves a well-formed path alone", () => {
|
||||
expect(tidyPath("V:/DELIVERY/ACME/101/x")).toBe("V:/DELIVERY/ACME/101/x");
|
||||
});
|
||||
});
|
||||
|
||||
describe("per-episode numbering", () => {
|
||||
// The scoping itself lives in createDeliveryPackage's query, which passes
|
||||
// only the names already used by *this* episode. These pin the contract that
|
||||
// depends on: another episode's delivery must not push this one to _02.
|
||||
it("gives each episode's first delivery of the day the bare name", () => {
|
||||
const ep101 = nextPackageName(BASE, [BASE]);
|
||||
const ep102 = nextPackageName(BASE, []);
|
||||
expect(ep101).toBe(`${BASE}_02`);
|
||||
expect(ep102).toBe(BASE);
|
||||
});
|
||||
|
||||
it("keeps two episodes' same-named packages in separate folders", () => {
|
||||
const dirFor = (episode: string, packageName: string) =>
|
||||
tidyPath(
|
||||
applyTokens(DELIVERY_CONFIG_DEFAULT.layout.packageDir, {
|
||||
deliveryRoot: "//SAN/DELIVERY",
|
||||
showId: "ACME",
|
||||
episode,
|
||||
packageName,
|
||||
})
|
||||
);
|
||||
expect(dirFor("101", BASE)).toBe("//SAN/DELIVERY/ACME/101/20260901_Delivery");
|
||||
expect(dirFor("102", BASE)).toBe("//SAN/DELIVERY/ACME/102/20260901_Delivery");
|
||||
});
|
||||
});
|
||||
|
||||
describe("package name template", () => {
|
||||
it("names the day with a four-digit year", () => {
|
||||
const name = applyTokens(DELIVERY_CONFIG_DEFAULT.packageNameTemplate, dateTokens(new Date(2026, 8, 1)));
|
||||
expect(name).toBe("20260901_Delivery");
|
||||
});
|
||||
});
|
||||
@@ -43,13 +43,15 @@ export interface DeliveryConfig {
|
||||
}
|
||||
|
||||
export const DELIVERY_CONFIG_DEFAULT: DeliveryConfig = {
|
||||
packageNameTemplate: "{yymmdd}_Delivery",
|
||||
packageNameTemplate: "{yyyymmdd}_Delivery",
|
||||
reviewNameTemplate: "{yyyymmdd}_Producer_review",
|
||||
layout: {
|
||||
packageDir: "{deliveryRoot}/{episode}/{packageName}",
|
||||
// {showId} is not optional in practice: without it every show's episode 101
|
||||
// lands in one folder on the delivery volume.
|
||||
packageDir: "{deliveryRoot}/{showId}/{episode}/{packageName}",
|
||||
shotDir: "{packageDir}/{shotCode}",
|
||||
reportFile: "{packageDir}/{packageName}_report.csv",
|
||||
reviewDir: "{deliveryRoot}/PRODUCER_REVIEWS/{packageName}",
|
||||
reviewDir: "{deliveryRoot}/{showId}/PRODUCER_REVIEWS/{packageName}",
|
||||
},
|
||||
deliveryRoot: "//SAN/DELIVERY",
|
||||
includeMovs: true,
|
||||
@@ -108,6 +110,36 @@ export function applyTokens(template: string, tokens: Partial<TokenValues>): str
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Collapse the empty segment an unset token leaves behind — a non-episodic
|
||||
* show resolves {episode} to "" and would otherwise build ".../SHOW//NAME".
|
||||
* The leading pair of a UNC root (//SAN/...) is preserved.
|
||||
*/
|
||||
export function tidyPath(path: string): string {
|
||||
const uncPrefix = /^\/\//.test(path) ? "//" : "";
|
||||
return uncPrefix + path.slice(uncPrefix.length).replace(/\/{2,}/g, "/").replace(/\/+$/, "");
|
||||
}
|
||||
|
||||
function escapeRegExp(value: string): string {
|
||||
return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
||||
}
|
||||
|
||||
/**
|
||||
* Second and later packages sharing a base name get `_02`, `_03`, ... Numbering
|
||||
* counts every package built under that base — cancelled and failed ones
|
||||
* included — so a number is never reused for a different folder.
|
||||
*/
|
||||
export function nextPackageName(base: string, existingNames: string[]): string {
|
||||
const pattern = new RegExp(`^${escapeRegExp(base)}(?:_(\\d+))?$`);
|
||||
let highest = 0;
|
||||
for (const name of existingNames) {
|
||||
const match = pattern.exec(name);
|
||||
if (!match) continue;
|
||||
highest = Math.max(highest, match[1] ? Number.parseInt(match[1], 10) : 1);
|
||||
}
|
||||
return highest === 0 ? base : `${base}_${String(highest + 1).padStart(2, "0")}`;
|
||||
}
|
||||
|
||||
export function dateTokens(date: Date) {
|
||||
const yyyy = String(date.getFullYear());
|
||||
const mm = String(date.getMonth() + 1).padStart(2, "0");
|
||||
@@ -280,8 +312,22 @@ export async function createDeliveryPackage(input: CreateDeliveryInput, userId:
|
||||
versionString: "",
|
||||
packageNumber: String(packageNumber),
|
||||
};
|
||||
tokens.packageName = input.options?.name ?? applyTokens(config.packageNameTemplate, tokens);
|
||||
tokens.packageDir = applyTokens(config.layout.packageDir, tokens);
|
||||
// A second delivery on the same day is normal — a retake batch, or a client
|
||||
// asking for the rest of a sequence — and the date-only template gives it a
|
||||
// name identical to the morning's. Suffix it the way MOV reviews already
|
||||
// are, so it gets its own folder instead of merging into the first one.
|
||||
//
|
||||
// Numbering is per episode, not per project: packageDir already separates
|
||||
// episodes, so three episodes delivering today are each the day's first
|
||||
// delivery and each get the bare name. Only a repeat delivery of the *same*
|
||||
// episode collides, and only that one suffixes to _02.
|
||||
const baseName = applyTokens(config.packageNameTemplate, tokens);
|
||||
const sameBase = await tx.deliveryPackage.findMany({
|
||||
where: { projectId: project.id, episode, kind: "EXR_DELIVERY", name: { startsWith: baseName } },
|
||||
select: { name: true },
|
||||
});
|
||||
tokens.packageName = input.options?.name ?? nextPackageName(baseName, sameBase.map((p) => p.name));
|
||||
tokens.packageDir = tidyPath(applyTokens(config.layout.packageDir, tokens));
|
||||
|
||||
const pkg = await tx.deliveryPackage.create({
|
||||
data: {
|
||||
|
||||
@@ -515,14 +515,20 @@ export interface ListExportsFilter {
|
||||
export async function listExports(filter: ListExportsFilter) {
|
||||
const page = Math.max(1, filter.page ?? 1);
|
||||
const limit = Math.min(200, Math.max(1, filter.limit ?? 50));
|
||||
const where: Prisma.ExportWhereInput = {
|
||||
const scope: Prisma.ExportWhereInput = {
|
||||
...(filter.projectId ? { projectId: filter.projectId } : {}),
|
||||
...(filter.status ? { status: filter.status } : {}),
|
||||
...(filter.shotId ? { shotId: filter.shotId } : {}),
|
||||
...(filter.episode ? { shot: { episode: filter.episode } } : {}),
|
||||
};
|
||||
const [total, rows] = await Promise.all([
|
||||
const where: Prisma.ExportWhereInput = {
|
||||
...scope,
|
||||
...(filter.status ? { status: filter.status } : {}),
|
||||
};
|
||||
const [total, byStatus, rows] = await Promise.all([
|
||||
db.export.count({ where }),
|
||||
// Counted across the whole scope, ignoring the status filter and paging:
|
||||
// summary figures taken from the loaded page would count only that page.
|
||||
db.export.groupBy({ by: ["status"], where: scope, _count: { _all: true } }),
|
||||
db.export.findMany({
|
||||
where,
|
||||
orderBy: { createdAt: "desc" },
|
||||
@@ -540,6 +546,9 @@ export async function listExports(filter: ListExportsFilter) {
|
||||
]);
|
||||
return {
|
||||
pagination: { page, limit, total, pages: Math.ceil(total / limit) },
|
||||
statusCounts: Object.fromEntries(byStatus.map((g) => [g.status, g._count._all])) as Partial<
|
||||
Record<ExportStatus, number>
|
||||
>,
|
||||
exports: rows.map((e) => ({
|
||||
id: e.id,
|
||||
shotCode: e.shot.shotCode,
|
||||
|
||||
@@ -6,7 +6,9 @@ import { getConfigNumber } from "./config";
|
||||
import {
|
||||
applyTokens,
|
||||
dateTokens,
|
||||
nextPackageName,
|
||||
resolveDeliveryConfig,
|
||||
tidyPath,
|
||||
type DeliveryConfig,
|
||||
type DeliveryManifest,
|
||||
type TokenValues,
|
||||
@@ -165,25 +167,12 @@ export async function resolveReviewCandidates(shotIds: string[]) {
|
||||
|
||||
// ── Folder naming ────────────────────────────────────────────────────────────
|
||||
|
||||
function escapeRegExp(value: string): string {
|
||||
return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
||||
}
|
||||
|
||||
/**
|
||||
* `20260828_Producer_review`, then `_02`, `_03` for further reviews the same
|
||||
* day. Numbering counts every package built under that base — cancelled and
|
||||
* failed ones included — so a number is never reused for a different folder.
|
||||
* day. EXR deliveries now number the same way, so the rule lives in
|
||||
* deliveries.ts; this name is kept because it reads better at the call site.
|
||||
*/
|
||||
export function nextReviewName(base: string, existingNames: string[]): string {
|
||||
const pattern = new RegExp(`^${escapeRegExp(base)}(?:_(\\d+))?$`);
|
||||
let highest = 0;
|
||||
for (const name of existingNames) {
|
||||
const match = pattern.exec(name);
|
||||
if (!match) continue;
|
||||
highest = Math.max(highest, match[1] ? Number.parseInt(match[1], 10) : 1);
|
||||
}
|
||||
return highest === 0 ? base : `${base}_${String(highest + 1).padStart(2, "0")}`;
|
||||
}
|
||||
export const nextReviewName = nextPackageName;
|
||||
|
||||
async function reviewNameFor(
|
||||
tx: Prisma.TransactionClient | typeof db,
|
||||
@@ -243,7 +232,7 @@ export async function previewMovReviewPackage(shotIds: string[]) {
|
||||
const tokens = reviewTokens(config, project, commonEpisode(candidates), buildDate, 0);
|
||||
const base = applyTokens(config.reviewNameTemplate, tokens);
|
||||
tokens.packageName = await reviewNameFor(db, project.id, base);
|
||||
tokens.packageDir = applyTokens(config.layout.reviewDir, tokens);
|
||||
tokens.packageDir = tidyPath(applyTokens(config.layout.reviewDir, tokens));
|
||||
|
||||
return {
|
||||
projectId: project.id,
|
||||
@@ -299,7 +288,7 @@ export async function createMovReviewPackage(input: CreateMovReviewInput, userId
|
||||
const tokens = reviewTokens(config, project, episode, buildDate, packageNumber);
|
||||
const base = applyTokens(config.reviewNameTemplate, tokens);
|
||||
tokens.packageName = input.options?.name ?? (await reviewNameFor(tx, project.id, base));
|
||||
tokens.packageDir = applyTokens(config.layout.reviewDir, tokens);
|
||||
tokens.packageDir = tidyPath(applyTokens(config.layout.reviewDir, tokens));
|
||||
|
||||
const pkg = await tx.deliveryPackage.create({
|
||||
data: {
|
||||
|
||||
@@ -1112,7 +1112,7 @@ model DeliveryPackage {
|
||||
projectId String
|
||||
project Project @relation(fields: [projectId], references: [id])
|
||||
episode String // "101" — empty string on standard (non-episodic) shows, and on reviews spanning several
|
||||
name String // "260805_Delivery" | "20260828_Producer_review_02"
|
||||
name String // "20260805_Delivery" | "20260828_Producer_review_02"
|
||||
kind DeliveryKind @default(EXR_DELIVERY)
|
||||
packageNumber Int // sequential per project → "Package #15"
|
||||
status DeliveryStatus @default(DRAFT)
|
||||
|
||||
+9
-9
@@ -276,17 +276,17 @@ export interface AssetWithDetails {
|
||||
|
||||
// ── Dashboard Types ──────────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Dashboard headline numbers. Every one is derived from pipeline state and
|
||||
* scoped to live productions — see lib/dashboard/ops.ts. The previous shape
|
||||
* carried task due/overdue counts, which read a column nothing writes.
|
||||
*/
|
||||
export interface DashboardStats {
|
||||
awaitingReview: number;
|
||||
needsRevisions: number;
|
||||
approved: number;
|
||||
overdue: number;
|
||||
blocked: number;
|
||||
inQc: number;
|
||||
readyToDeliver: number;
|
||||
awaitingClientReview: number;
|
||||
activeProjects: number;
|
||||
// Task widgets
|
||||
tasksDueToday: number;
|
||||
tasksInReview: number;
|
||||
tasksOverdue: number;
|
||||
myTasksCount: number;
|
||||
}
|
||||
|
||||
// ── Notification Badge ────────────────────────────────────────────────────────
|
||||
|
||||
Reference in New Issue
Block a user