94792279c5
Requesting changes on a shot and then re-rendering it through the render queue left every layer of the app still showing the old verdict. Three independent causes, all on the pipeline path. finalizePreview inherited the superseded version's approvalStatus unconditionally. The carry-over exists so a re-export of a signed-off shot does not reappear as awaiting review, but it applied equally to NEEDS_CHANGES and REJECTED, so the render queued to address a note arrived already wearing that note and nothing registered that the work had been redone. carryApproval now carries only APPROVED. The pipeline never moved the task. One left on CHANGES by a review or a QC fail stayed there through every re-render, with no way out but a manual kanban drag. A genuinely new version now moves it to INTERNAL_REVIEW, as actions/versions.ts and batch-upload already did. A replaced version is excluded: regeneratePreview re-delivers the same version after a slate fix and is not a new submission. The pipeline never called recalcShotStatus at all, so shot boards went stale the moment a render changed a task. finalizePreview and the QC fail path both recalculate now; the latter already documented the REVISIONS derivation it was relying on and never triggering. Shot.status is derived from tasks and approval flags, but six call sites wrote it directly with the status they expected: internallyApproveShot, shareWithClient, unshareFromClient, clientApproveShot, unapproveShot and the client approve route. Rule 1 of the derivation is that any CHANGES task outranks an approval, so a shot could be pushed past open rework and then snap back to REVISIONS on the next unrelated recalc, which is close to unreportable as a bug. They now set the approval inputs and let recalcShotStatus derive. unshareFromClient additionally hardcoded READY_FOR_CLIENT even for a client-approved shot. updateShotStatus keeps its direct write as the deliberate manual override, now documented as transient for the same reason. markShotForRevisions replaces the duplicated change-request logic. Both copies marked all non-DONE tasks CHANGES, which matches nothing on the shot this is most often called for: one out for client review precisely because all its tasks are finished. The request then derived to INTERNAL_REVIEW and had no visible effect anywhere. When nothing is picked up it now reopens the task behind the shot's latest version, which is the deliverable the reviewer was looking at. A client's shot-level change request also marks the versions and writes Approval rows now. The dashboard counters, the version badges and the portal's own filters all read Version.approvalStatus, so a shot-level verdict was invisible everywhere those look. clearStaleShotApproval covers the reverse case: uploading a new version onto an approved shot moved the task to INTERNAL_REVIEW and changed nothing visible, because the derivation short-circuits on shotApprovalStatus. The shot kept reading COMPLETE while carrying work nobody had looked at. This is the one user-visible behaviour change here, so watch the boards on a live show: an approved shot now drops back to INTERNAL_REVIEW on a new upload. sharedWithClient is deliberately left alone, since revoking client access stays a separate act. submitApproval and unapproveVersion are transactional now. The verdict, the version, the task and the derived shot status are one decision, and a failure partway through left the three layers disagreeing with no way to tell which one was right. KanbanCard compared approvalStatus against "CHANGES_REQUESTED", which is not a member of the enum, so the changes-requested icon never rendered at all. Thirteen tests cover carryApproval, markShotForRevisions including the all-DONE regression, and clearStaleShotApproval. What is not covered is the pipeline transaction itself, which needs a database: queue a render against a shot in REVISIONS and confirm the task and shot both move before trusting this on a show. Version.reviewStatus is still written nowhere while being published through ext/shots/lookup and EXT_API_REFERENCE.md as a permanent "PENDING". Left alone deliberately: removing a field from that contract could break the connector. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
214 lines
6.8 KiB
TypeScript
214 lines
6.8 KiB
TypeScript
import { NextRequest, NextResponse } from "next/server";
|
||
import { auth } from "@/auth";
|
||
import { db } from "@/lib/db";
|
||
import { uploadToHetzner, deleteFromHetzner } from "@/lib/storage";
|
||
import { recalcShotStatus, clearStaleShotApproval } from "@/lib/shot-status";
|
||
|
||
export const maxDuration = 300; // 5 min — large .mov high-res files
|
||
|
||
/**
|
||
* POST /api/batch-upload/upload
|
||
*
|
||
* Handles a single file upload from the batch upload flow.
|
||
*
|
||
* FormData fields:
|
||
* file – the binary file
|
||
* action – "new-version" | "rename-and-upload" | "create-task" | "update-highres"
|
||
* shotId – shot DB id (required for all actions)
|
||
* projectId – project DB id
|
||
* taskId – required for "new-version" and "rename-and-upload"
|
||
* fallbackTaskId – optional: the "Comp" task id to rename for "create-task"
|
||
* newTaskTitle – desired task title (filename without extension)
|
||
*/
|
||
export async function POST(
|
||
req: NextRequest
|
||
): Promise<NextResponse> {
|
||
const session = await auth();
|
||
if (!session?.user) {
|
||
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
|
||
}
|
||
|
||
const formData = await req.formData();
|
||
const file = formData.get("file") as File | null;
|
||
const action = formData.get("action") as string | null;
|
||
const shotId = formData.get("shotId") as string | null;
|
||
const projectId = formData.get("projectId") as string | null;
|
||
const taskId = formData.get("taskId") as string | null;
|
||
const fallbackTaskId = formData.get("fallbackTaskId") as string | null;
|
||
const newTaskTitle = (formData.get("newTaskTitle") as string | null) ?? "";
|
||
|
||
if (!action || !shotId || !projectId) {
|
||
return NextResponse.json(
|
||
{ error: "Missing required fields: action, shotId, projectId" },
|
||
{ status: 400 }
|
||
);
|
||
}
|
||
|
||
// ── High-res (.mov) — file was uploaded directly to Hetzner via presigned URL ──
|
||
// The file never passes through this server or the Nginx proxy, avoiding
|
||
// HTTP 413 errors caused by client_max_body_size limits.
|
||
if (action === "update-highres") {
|
||
const preUploadedKey = formData.get("key") as string | null;
|
||
const preUploadedFileName = formData.get("fileName") as string | null;
|
||
|
||
if (!preUploadedKey || !preUploadedFileName) {
|
||
return NextResponse.json(
|
||
{ error: "key and fileName are required for update-highres" },
|
||
{ status: 400 }
|
||
);
|
||
}
|
||
|
||
const shot = await db.shot.findUnique({
|
||
where: { id: shotId },
|
||
select: { id: true, highResKey: true },
|
||
});
|
||
if (!shot) {
|
||
return NextResponse.json({ error: "Shot not found" }, { status: 404 });
|
||
}
|
||
|
||
if (shot.highResKey) {
|
||
await deleteFromHetzner(shot.highResKey).catch(() => {});
|
||
}
|
||
|
||
await db.shot.update({
|
||
where: { id: shotId },
|
||
data: { highResKey: preUploadedKey, highResFilename: preUploadedFileName },
|
||
});
|
||
|
||
return NextResponse.json({
|
||
success: true,
|
||
action: "update-highres",
|
||
fileName: preUploadedFileName,
|
||
});
|
||
}
|
||
|
||
// For all other actions (MP4 version uploads) a file is required.
|
||
if (!file) {
|
||
return NextResponse.json({ error: "file is required" }, { status: 400 });
|
||
}
|
||
|
||
const buffer = Buffer.from(await file.arrayBuffer());
|
||
|
||
// Browsers (especially on Windows) often send an empty MIME type for .mov
|
||
// files. Fall back to a safe content type based on the file extension.
|
||
const ext = file.name.split(".").pop()?.toLowerCase();
|
||
const contentType =
|
||
file.type ||
|
||
(ext === "mov" ? "video/quicktime" :
|
||
ext === "mp4" ? "video/mp4" :
|
||
"application/octet-stream");
|
||
|
||
// ── Version upload (.mp4) ─────────────────────────────────────────────────
|
||
let resolvedTaskId: string;
|
||
|
||
if (action === "new-version") {
|
||
if (!taskId) {
|
||
return NextResponse.json(
|
||
{ error: "taskId is required for new-version action" },
|
||
{ status: 400 }
|
||
);
|
||
}
|
||
resolvedTaskId = taskId;
|
||
} else if (action === "rename-and-upload") {
|
||
if (!taskId) {
|
||
return NextResponse.json(
|
||
{ error: "taskId is required for rename-and-upload action" },
|
||
{ status: 400 }
|
||
);
|
||
}
|
||
// Rename the task to reflect the new version number
|
||
await db.task.update({
|
||
where: { id: taskId },
|
||
data: { title: newTaskTitle },
|
||
});
|
||
resolvedTaskId = taskId;
|
||
} else if (action === "create-task") {
|
||
if (fallbackTaskId) {
|
||
// Rename the existing "Comp" (or similar) task and reuse it
|
||
await db.task.update({
|
||
where: { id: fallbackTaskId },
|
||
data: { title: newTaskTitle },
|
||
});
|
||
resolvedTaskId = fallbackTaskId;
|
||
} else {
|
||
// Create a brand-new task under the shot
|
||
const lastTask = await db.task.findFirst({
|
||
where: { shotId },
|
||
orderBy: { sortOrder: "desc" },
|
||
select: { sortOrder: true },
|
||
});
|
||
const task = await db.task.create({
|
||
data: {
|
||
title: newTaskTitle,
|
||
type: "COMP",
|
||
shotId,
|
||
projectId,
|
||
createdById: session.user.id,
|
||
sortOrder: (lastTask?.sortOrder ?? -1) + 1,
|
||
},
|
||
});
|
||
resolvedTaskId = task.id;
|
||
}
|
||
} else {
|
||
return NextResponse.json(
|
||
{ error: `Unknown action: ${action}` },
|
||
{ status: 400 }
|
||
);
|
||
}
|
||
|
||
// Upload the video to Hetzner object storage
|
||
const { key: videoKey } = await uploadToHetzner(buffer, file.name, contentType, "videos");
|
||
const result = { url: `/api/files/${videoKey}`, key: videoKey };
|
||
|
||
// Mark all existing versions for this task as no longer latest
|
||
await db.version.updateMany({
|
||
where: { taskId: resolvedTaskId },
|
||
data: { isLatest: false },
|
||
});
|
||
|
||
// Determine next sequential version number
|
||
const lastVersion = await db.version.findFirst({
|
||
where: { taskId: resolvedTaskId },
|
||
orderBy: { versionNumber: "desc" },
|
||
select: { versionNumber: true },
|
||
});
|
||
const versionNumber = (lastVersion?.versionNumber ?? 0) + 1;
|
||
|
||
// Create the version record
|
||
const version = await db.version.create({
|
||
data: {
|
||
versionNumber,
|
||
taskId: resolvedTaskId,
|
||
artistId: session.user.id,
|
||
fileUrl: result.url,
|
||
fileName: file.name,
|
||
fileSize: BigInt(file.size),
|
||
mimeType: file.type,
|
||
isLatest: true,
|
||
},
|
||
});
|
||
|
||
// Move the task to INTERNAL_REVIEW
|
||
await db.task.update({
|
||
where: { id: resolvedTaskId },
|
||
data: { status: "INTERNAL_REVIEW" },
|
||
});
|
||
|
||
// Recalculate the parent shot's status, clearing any stale sign-off first so
|
||
// the new version does not land under a shot still reading COMPLETE.
|
||
await db
|
||
.$transaction(async (tx) => {
|
||
await clearStaleShotApproval(tx, shotId);
|
||
await recalcShotStatus(shotId, tx);
|
||
})
|
||
.catch(() => {});
|
||
|
||
return NextResponse.json({
|
||
success: true,
|
||
action,
|
||
versionId: version.id,
|
||
versionNumber,
|
||
taskId: resolvedTaskId,
|
||
});
|
||
}
|