9 Commits

Author SHA1 Message Date
twotalesanimation 6afbe82a29 feat(dashboard): QC queue, deliveries and whose-court panels
Deploy / deploy (push) Successful in 6m51s
Completes the operations dashboard.

QC queue: what is waiting on a person to watch the frames, oldest first.
Every stage before QC is worked by the farm, so this is the only one that
cannot drain itself - depth here is the best early warning that a delivery
date is going to move, and it had no home outside a filter on the queue page.

Deliveries: the last few packages, flagging FAILED and builds stuck in
BUILDING. A failed build is otherwise silent - the exports stay
READY_FOR_DELIVERY, nothing reaches the delivery volume, and nobody finds out
until the client asks where the shots are.

Whose court: versions sent to the client and unanswered, against shots with
unresolved notes. Two numbers rather than one because they call for opposite
responses - a fortnight-old review is a phone call, unactioned notes are a
scheduling problem.

The artist view now scopes to the artist throughout: the blocked list, and
the counters above it, which otherwise quoted a studio-wide figure next to a
personal list.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-10 05:58:08 +02:00
twotalesanimation 6bfc013e35 feat(dashboard): episode delivery countdown
Turns "23 shots to go" into "you are not going to make it". One card per
episode from EpisodeDueDate (or the project's own date on a standard show):
days left, the episode's shots by where they actually are, and the only
comparison that matters - shots per day still needed against shots per day
the studio managed over the last week.

A shot counts as delivered when it appears in a DeliveryItem inside 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
MOV_REVIEW package ships nothing.

The pace arithmetic is a pure function so the sentence a producer acts on is
testable: a rate that only just lands on the due date reports as "no slack"
rather than fine, and a week with no deliveries reports as stalled instead of
projecting infinity.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-10 05:45:01 +02:00
twotalesanimation f6a7f0ef5a feat(dashboard): show what is blocked and how the farm is doing
The dashboard was a generic task-manager view of a studio that does not work
that way. Two of its five headline numbers counted Task.dueDate, which no
pipeline code writes - the only writer is a manual field on the task detail
page, so those cards read zero by construction. The rest were unscoped and
cumulative ("approved" across every project ever finished), the activity feed
was the notification table, and the shot queue sampled 15 rows by updatedAt,
a column the farm touches constantly. Nothing about failed exports, QC depth
or the render farm appeared at all, so a RENDER_FAILED was only visible if
someone thought to open the queue and filter for it.

Replaced with pipeline state, which the system maintains on its own:

- Blocked queue: the four failed statuses plus exports that stopped
  progressing, each with the reason read off the actual cause - the failing
  validation check, the QC note, the aerender error, or the machine that
  claimed it and went quiet.
- Farm strip: machines, queue depth by job type, oldest unclaimed job, and
  worker-version drift, since a worker's version decides which fixes it has.
- Five counters that can go down, scoped to live productions, each linking to
  the rows it counted.

The queue page ignored ?status=, so the counters had nowhere to link; it now
takes an initial filter from the URL. Stat cards are hidden from CLIENT users
- the old ones were generic version counts, these are internal pipeline state.

Thresholds live in SystemConfig (dashboard.qcStaleHours, .stalledJobHours) so
they can be tuned without a redeploy.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-10 05:40:40 +02:00
twotalesanimation fe420b9455 chore(worker): bump to 1.6.1 for the PrepareOutputDir fix
Deploy / deploy (push) Successful in 6m49s
The version is what a machine reports on startup, so it has to move for the
Machines page to show which nodes are still clearing the preview MOV out of
the version folder.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-09 07:06:37 +02:00
twotalesanimation 2a8888089f fix(worker): stop PrepareOutputDir deleting the version's preview MOV/MP4
Deploy / deploy (push) Successful in 6m33s
PrepareOutputDir cleared every file in the output dir whose name started
with the output pattern's prefix. The preview stage writes its MOV and MP4
into that same folder from the same basename ({outputDir}/{base}.mov), so
they matched the prefix and were deleted before aerender started.

The dir is not private to one export: outputDir is keyed on the shot's
manually-set shotVersion, not on the export, so re-queuing without a
Version Up renders into the folder again. That is exactly the "No preview"
workflow - export scaled, reverse the scale, re-render only the EXRs and
inherit the earlier MOV - and inheritPreviewMedia then handed the new
export a deliveryMovPath pointing at the file the render had just removed.
Nothing surfaced it: the review MP4 is an uploaded blob and still played,
and DeliveryStage treats a missing MOV as non-fatal, so the package
silently shipped EXRs with no viewing copy.

Match on prefix and extension instead, via a new
SequencePattern.MatchesOutputFile - the predicate ValidationStage and
DeliveryStage already applied inline. Crashed-attempt cleanup is unchanged;
only files with a different extension are now spared.

JobExecutor's post-render stats loop matched on prefix alone too. With the
media no longer deleted it would have counted the MOV/MP4 as frames and
failed validation's file_count check, so it uses the same matcher.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-08 23:19:33 +02:00
twotalesanimation a073f92da3 fix(delivery): number same-day packages per episode, not per project
Deploy / deploy (push) Successful in 7m31s
Numbering was scoped to the project, so the day's first delivery of
episode 102 was named _02 purely because episode 101 had already gone out
that morning. The count is meant to distinguish repeat deliveries of the
same content, and packageDir already separates episodes — three episodes
delivering today each land in their own folder and each are that folder's
first delivery. Adding `episode` to the lookup makes the suffix mean what
the folder layout already implies: only a second delivery of the *same*
episode becomes _02. The [projectId, episode] index already exists, so
the extra filter costs nothing.

packageNameTemplate also moves from {yymmdd} to {yyyymmdd}. The AE panel
has always built its local delivery folders with a four-digit year, so
this is the server matching the connector rather than a new convention.
The {yymmdd} token stays in TokenValues: a project carrying its own
template in deliveryConfig is unaffected either way.

Existing packages are untouched — buildDeliveryJobManifest reads rootPath
off the record. On the day of the changeover an episode that already
delivered as 260903_Delivery starts again at the bare 20260903_Delivery,
which is a different name and a different folder, so nothing merges.

Producer reviews keep their per-project numbering: a review can span
several episodes and stores episode as "", so scoping it the same way
would put every such review in one bucket.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-03 10:07:52 +02:00
twotalesanimation 04e5eb123a feat(shot-status): bulk-assign selected shots to an artist
Deploy / deploy (push) Successful in 6m30s
Adds an "Assign Artist" entry to the bulk actions menu, backed by a
bulkAssignArtist server action. The action re-checks the target user
server-side — a deactivated account or a CLIENT is rejected rather than
trusted from the picker — and passing null clears the assignment, so
reassignment and hand-back are the same flow.

Like single-shot assignment in updateShot this writes the column and
sends no notification, so reshuffling a batch during planning stays quiet.

Also renders the Artist column the page was already querying but never
showing; without it there was no way to see the result of an assignment.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-03 09:51:13 +02:00
twotalesanimation 75f9258b69 feat(player): aspect-ratio blanking overlay in the review player
Deploy / deploy (push) Successful in 5m39s
A shot is reviewed at the framing it was rendered at but usually delivered
cropped, so add a dropdown beside the playback-speed control that lays
delivery blanking over the video: 2.39 through 9:16, widest to tallest, with
"No blanking" as the default. Purely a viewing aid — nothing is written to
the review, and the video element is untouched.

The geometry is the awkward part. The video is object-contain, so the picture
is letterboxed inside the element and bars drawn against the element's edges
would be wrong on any panel whose shape does not match the source.
letterboxRect works out where the picture is actually painted and the bars are
positioned against that, kept current by a ResizeObserver and a loadedmetadata
listener so resizes and fullscreen stay correct. Ratios within half a pixel of
the source draw nothing rather than a hairline of rounding error.

Two modes, since blanking and crop bars are different jobs: solid black hides
the crop the way the master will, guide dims it so the excluded area is still
readable. The overlay sits under the annotation canvas — deliberately no
z-index, since the canvas sets none either and DOM order alone gives marks
drawn over a blanked area the right precedence.

Verified against real browser layout, not just unit tests: the computed
picture rect lands exactly on the image edges across three panel shapes, and
the visible area measures the requested ratio.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-02 07:21:58 +02:00
twotalesanimation 269a5cbfda fix(delivery): separate packages by show, and number same-day deliveries
Deploy / deploy (push) Successful in 6m27s
Two faults in how a package's folder is named, both of which put unrelated
files in one directory on the delivery volume.

The default layout had no {showId}, so every show's episode 101 resolved to
{deliveryRoot}/101/{packageName}. The token existed and was populated — it
just never appeared in the path. With hardlinked packages that means two
shows delivering the same episode number on the same day write into the same
folder, and identically named shots overwrite each other. reviewDir had the
same hole, and is worse there: reviewNameFor scopes its lookup by projectId,
so a second show computes the bare base name and lands on the first show's
folder instead of suffixing past it.

createDeliveryPackage also never checked for an existing package of the same
name. packageNameTemplate is date-only and packageNumber is a per-project
counter that is not in the template, so a second delivery on the same day got
an identical name and rootPath and built on top of the first. MOV reviews
already did this correctly, so nextReviewName moves to deliveries.ts as
nextPackageName and both paths share it; the review-side name is kept as an
alias because it reads better at that call site.

Putting {showId} ahead of {episode} exposes an empty segment on non-episodic
shows, so paths go through tidyPath, which collapses it and leaves the UNC
root alone.

Historic packages are unaffected: buildDeliveryJobManifest reads rootPath and
configSnapshot off the record, so only new packages use the new layout. A
project with its own deliveryConfig.layout in the database still overrides
these defaults.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-01 08:08:37 +02:00
32 changed files with 2583 additions and 207 deletions
@@ -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()
{
+18 -14
View File
@@ -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 */ }
}
+7 -4
View File
@@ -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.1</Version>
</PropertyGroup>
<ItemGroup>
@@ -645,6 +645,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>
+51
View File
@@ -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[]) {
+137 -93
View File
@@ -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,43 +113,52 @@ 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">
@@ -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,32 +239,18 @@ 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">
<div className="space-y-3">
<h2 className="text-sm font-semibold text-muted-foreground uppercase tracking-wide">
Shot Queue
{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 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>
</div>
</div>
);
}
@@ -51,14 +51,16 @@ 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) {
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 isAdmin = ["ADMIN", "PRODUCER", "SUPERVISOR"].includes(session?.user?.role ?? "");
const { data, isLoading, refetch, isFetching } = useQuery({
+14 -2
View File
@@ -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} />;
}
@@ -8,6 +8,7 @@ import {
Select,
SelectContent,
SelectItem,
SelectSeparator,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
@@ -28,8 +29,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 +52,7 @@ import {
ChevronsUpDown,
Clapperboard,
Scaling,
UserPlus,
} from "lucide-react";
import { format } from "date-fns";
import { shotThumbnail } from "@/lib/shot-thumbnail";
@@ -74,6 +77,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,6 +97,7 @@ interface ShotStatusClientProps {
selectedProject: Project | null;
shots: ShotRow[];
episodeDueDates: { episode: string; dueDate: Date | string }[];
artists: Artist[];
canManage: boolean;
}
@@ -225,6 +236,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 +709,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">
@@ -700,6 +809,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,6 +873,7 @@ export function ShotStatusClient({
selectedProject,
shots,
episodeDueDates,
artists,
canManage,
}: ShotStatusClientProps) {
const router = useRouter();
@@ -793,6 +922,7 @@ export function ShotStatusClient({
}
}, [selectedProjectId]);
const [dueDateDialogOpen, setDueDateDialogOpen] = useState(false);
const [assignDialogOpen, setAssignDialogOpen] = useState(false);
const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
const [movReviewDialogOpen, setMovReviewDialogOpen] = useState(false);
@@ -868,6 +998,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]);
@@ -1040,6 +1190,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 +1403,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}
+12 -1
View File
@@ -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
View File
@@ -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>
);
}
+123
View File
@@ -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&apos;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>
);
}
+111
View File
@@ -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>
);
}
+96
View File
@@ -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>
);
}
+74
View File
@@ -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>
);
}
+58 -40
View File
@@ -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}>
<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>
<p className="text-3xl font-bold text-white">
<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>
+70
View File
@@ -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>
);
}
+131
View File
@@ -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>
);
}
+67 -1
View File
@@ -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>
+11
View File
@@ -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}
+11
View File
@@ -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),
+106
View File
@@ -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();
});
});
+119
View File
@@ -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;
}
+87
View File
@@ -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");
});
});
+750
View File
@@ -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;
}
+7
View File
@@ -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;
+98
View File
@@ -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");
});
});
+51 -5
View File
@@ -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: {
+7 -18
View File
@@ -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: {
+1 -1
View File
@@ -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
View File
@@ -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 ────────────────────────────────────────────────────────