Compare commits
62 Commits
b151e8cc52
..
main
| Author | SHA1 | Date | |
|---|---|---|---|
| 633301c491 | |||
| 83aad38053 | |||
| a4d5777e1d | |||
| 3a7ba689ed | |||
| 41cf79abbe | |||
| 7a7088f2ad | |||
| 0aedc4b1fa | |||
| d7e37de18f | |||
| 06a4122ebb | |||
| 842a8fe036 | |||
| 34af26dfbf | |||
| 27d9618995 | |||
| 1d60a55b3c | |||
| 88112112d4 | |||
| 91e69f0bcb | |||
| 477aef7b27 | |||
| f30acef101 | |||
| 326d8cbefa | |||
| b596c97faf | |||
| 824695ef30 | |||
| 390d7a21ac | |||
| 5e29c3b88d | |||
| c2509512ff | |||
| 27f9f7ac64 | |||
| 9660cdc21c | |||
| bae46c2968 | |||
| 2e9fa45580 | |||
| 2817c7e815 | |||
| 428814b8b9 | |||
| 45459e4b12 | |||
| 2b373737d8 | |||
| 724b0cbefe | |||
| 0c4f94d56a | |||
| 40b99f3add | |||
| 33bc6a935c | |||
| 532ebd82d7 | |||
| 708e8a0d8f | |||
| 97246bcbc3 | |||
| 400cf3f6ea | |||
| 2dee1bf6fc | |||
| 469d782b4f | |||
| 6afbe82a29 | |||
| 6bfc013e35 | |||
| f6a7f0ef5a | |||
| fe420b9455 | |||
| 2a8888089f | |||
| a073f92da3 | |||
| 04e5eb123a | |||
| 75f9258b69 | |||
| 269a5cbfda | |||
| 59af7959e6 | |||
| a6ee1917e7 | |||
| 28e8c47907 | |||
| 94792279c5 | |||
| 93137cdcd2 | |||
| 6678721fb1 | |||
| bac525ddd0 | |||
| 7f066c1372 | |||
| ed9f9b13c1 | |||
| 1fad6a739d | |||
| 9cd7b0df6e | |||
| caaa333f02 |
@@ -0,0 +1,11 @@
|
|||||||
|
{
|
||||||
|
"version": "0.0.1",
|
||||||
|
"configurations": [
|
||||||
|
{
|
||||||
|
"name": "web",
|
||||||
|
"runtimeExecutable": "npm",
|
||||||
|
"runtimeArgs": ["run", "dev"],
|
||||||
|
"port": 3000
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
+1
-1
@@ -23,7 +23,7 @@ Dockerfile*
|
|||||||
.github
|
.github
|
||||||
migrations
|
migrations
|
||||||
README.md
|
README.md
|
||||||
uploads
|
uploads*
|
||||||
.git
|
.git
|
||||||
*.tar
|
*.tar
|
||||||
*.sql
|
*.sql
|
||||||
+138
-9
@@ -2,6 +2,11 @@
|
|||||||
|
|
||||||
How a finished shot becomes a dated folder ready to upload to the client.
|
How a finished shot becomes a dated folder ready to upload to the client.
|
||||||
|
|
||||||
|
There are two kinds of package. An **EXR delivery** is the shippable one and is
|
||||||
|
what most of this guide describes. A **MOV review** is a flat folder of preview
|
||||||
|
MOVs shared for a formal review — see
|
||||||
|
[MOV review packages](#mov-review-packages) at the end.
|
||||||
|
|
||||||
This is the operational guide. The design rationale and normative rules live in
|
This is the operational guide. The design rationale and normative rules live in
|
||||||
[RenderPipeline2.md](RenderPipeline2.md) §11.
|
[RenderPipeline2.md](RenderPipeline2.md) §11.
|
||||||
|
|
||||||
@@ -15,9 +20,14 @@ This is the operational guide. The design rationale and normative rules live in
|
|||||||
18 shots"*, click **Build delivery**.
|
18 shots"*, click **Build delivery**.
|
||||||
3. A render worker builds the folder on the delivery volume, verifies every
|
3. A render worker builds the folder on the delivery volume, verifies every
|
||||||
file, and writes a manifest and CSV report.
|
file, and writes a manifest and CSV report.
|
||||||
4. A human uploads that folder to the client, then clicks **Mark delivered**.
|
4. A human uploads that folder to the client and clicks **Record upload**,
|
||||||
|
pasting the link to where it now lives.
|
||||||
|
5. They send the client that link and click **Share link**, recording who it
|
||||||
|
went to. Only then is the package `DELIVERED`.
|
||||||
|
|
||||||
Nothing is ever sent to the client automatically. Step 4 is deliberately manual.
|
Nothing is ever sent to the client automatically. Steps 4 and 5 are deliberately
|
||||||
|
manual — but until both are recorded the package sits in **Awaiting delivery**
|
||||||
|
at the top of the dashboard.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -64,8 +74,8 @@ Watch the package status on the same page:
|
|||||||
|---|---|
|
|---|---|
|
||||||
| `QUEUED` | Waiting for a worker to pick it up |
|
| `QUEUED` | Waiting for a worker to pick it up |
|
||||||
| `BUILDING` | A worker is creating folders and linking files |
|
| `BUILDING` | A worker is creating folders and linking files |
|
||||||
| `READY` | Built and verified — upload it |
|
| `READY` | Built and verified. Shown as *Built — not uploaded*, then *Uploaded — link not shared* |
|
||||||
| `DELIVERED` | You confirmed the client has it |
|
| `DELIVERED` | The upload location and who the link was sent to are both on record |
|
||||||
| `FAILED` | Something did not verify — see the error and the per-shot list |
|
| `FAILED` | Something did not verify — see the error and the per-shot list |
|
||||||
| `CANCELLED` | Abandoned before delivery |
|
| `CANCELLED` | Abandoned before delivery |
|
||||||
|
|
||||||
@@ -161,11 +171,59 @@ so it is logged and the package continues without it.
|
|||||||
|
|
||||||
## Marking delivered
|
## Marking delivered
|
||||||
|
|
||||||
Once you have uploaded the folder, **Mark delivered** moves every packaged
|
A built package is not a delivered one, so delivery is two recorded steps. Both
|
||||||
export to `DELIVERED`. Requires admin, producer or supervisor.
|
require admin, producer or supervisor.
|
||||||
|
|
||||||
This is the end of the pipeline, and it is a human statement of fact — the app
|
1. **Record upload** — paste the link to the folder on the client's portal and
|
||||||
has no way to know the client received anything.
|
confirm it matches the shot, frame and MOV counts shown. The link can be
|
||||||
|
corrected until it is shared.
|
||||||
|
2. **Share link** — copy the generated message (link, shots, versions), send it,
|
||||||
|
and record who it went to. This moves every packaged export to `DELIVERED`.
|
||||||
|
|
||||||
|
The second step is refused until the first is on record. Meanwhile the package
|
||||||
|
is listed under **Awaiting delivery** on the dashboard, amber after a day and
|
||||||
|
red after two.
|
||||||
|
|
||||||
|
This is still a human statement of fact — the client's portal has no API, so
|
||||||
|
the app cannot see the upload itself. What it guarantees is that nothing reads
|
||||||
|
as delivered without a link, a recipient, a name and a time behind it. Packages
|
||||||
|
delivered before this existed show as delivered with no evidence recorded.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Delivery requests
|
||||||
|
|
||||||
|
When a client asks for something ("EXRs for 116"), log it so it cannot be
|
||||||
|
forgotten. Requires admin, producer or supervisor.
|
||||||
|
|
||||||
|
- **Dashboard → Awaiting delivery → Log request**, or the same button on
|
||||||
|
**Pipeline → Deliveries**: pick the project, then a whole episode or a pasted
|
||||||
|
list of shot codes (ours or the client's; a code that matches nothing is
|
||||||
|
refused rather than skipped).
|
||||||
|
- **Shot Status → Bulk Actions → Log Delivery Request** for a ticked selection.
|
||||||
|
|
||||||
|
The shot list is a snapshot taken when the request is logged. The request then
|
||||||
|
sits in **Awaiting delivery** showing *"3 of 9 delivered"*, and on the
|
||||||
|
deliveries page every shot shows where it stands: not through QC, in QC, ready
|
||||||
|
to package, building, built, uploaded, delivered. **Build N ready** packages
|
||||||
|
the shots that have passed QC.
|
||||||
|
|
||||||
|
A request has no "done" button. A shot's line closes only when:
|
||||||
|
|
||||||
|
- a package containing it is shared (step 2 of marking delivered) after the
|
||||||
|
request was logged, or
|
||||||
|
- it is marked **Delivered Outside Pipeline** with the upload link and who the
|
||||||
|
link was sent to, dated on or after the day the request was logged. For a
|
||||||
|
shot on an open request those two fields are required.
|
||||||
|
|
||||||
|
The request closes when every line has. A delivery made *before* the request
|
||||||
|
was logged does not count — a client asking again is asking for it again. The
|
||||||
|
only other way out is **Cancel request**, which needs a reason and stays in the
|
||||||
|
history.
|
||||||
|
|
||||||
|
The *Wanted* field (EXRs, MOVs, both) records what was asked for; it does not
|
||||||
|
change what closes a line. A MOV-only ask is closed through Delivered Outside
|
||||||
|
Pipeline, since a MOV review package has no delivered state.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -228,11 +286,82 @@ a different spec is a config change rather than a code change.
|
|||||||
| E16 | `POST` | `/api/deliveries` | Create a package and queue the build |
|
| E16 | `POST` | `/api/deliveries` | Create a package and queue the build |
|
||||||
| E17 | `GET` | `/api/deliveries` | List packages / history |
|
| E17 | `GET` | `/api/deliveries` | List packages / history |
|
||||||
| E18 | `GET` | `/api/deliveries/ready` | Ready exports grouped by episode |
|
| E18 | `GET` | `/api/deliveries/ready` | Ready exports grouped by episode |
|
||||||
| E19 | `POST` | `/api/deliveries/{id}/delivered` | Mark delivered |
|
| — | `POST` | `/api/deliveries/{id}/uploaded` | Record the upload: `{ uploadUrl, contentsConfirmed: true }` |
|
||||||
|
| E19 | `POST` | `/api/deliveries/{id}/delivered` | Record the share and mark delivered: `{ sharedWith, note? }` |
|
||||||
| — | `POST` | `/api/deliveries/{id}/cancel` | Cancel a package |
|
| — | `POST` | `/api/deliveries/{id}/cancel` | Cancel a package |
|
||||||
|
| — | `GET` | `/api/delivery-requests` | List requests with per-shot stages (`?projectId=`, `?open=1`) |
|
||||||
|
| — | `POST` | `/api/delivery-requests` | Log a request: `{ projectId, episode \| shotIds \| shotCodes, deliverable, requestedBy, dueDate?, note? }` |
|
||||||
|
| — | `POST` | `/api/delivery-requests/{id}/cancel` | Cancel a request: `{ reason }` |
|
||||||
| — | `POST` | `/api/ext/render/jobs/{jobId}/delivery` | Worker reports a build (API key) |
|
| — | `POST` | `/api/ext/render/jobs/{jobId}/delivery` | Worker reports a build (API key) |
|
||||||
|
|
||||||
`POST /api/deliveries` takes `{ projectId, episode?, exportIds?, options? }`.
|
`POST /api/deliveries` takes `{ projectId, episode?, exportIds?, options? }`.
|
||||||
Omit `exportIds` to take every ready export in the episode; `options` accepts
|
Omit `exportIds` to take every ready export in the episode; `options` accepts
|
||||||
`date`, `name`, `includeMovs` and `copyMode` to override the config for one
|
`date`, `name`, `includeMovs` and `copyMode` to override the config for one
|
||||||
build.
|
build.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## MOV review packages
|
||||||
|
|
||||||
|
For a formal review you share the preview MOVs, not the EXRs. That is its own
|
||||||
|
kind of package, built the same way and listed on the same page.
|
||||||
|
|
||||||
|
### Building one
|
||||||
|
|
||||||
|
**Shot Status**, tick the shots, then **Bulk Actions → Build MOV Review
|
||||||
|
Package**. A dialog shows exactly what would be built before anything happens:
|
||||||
|
the folder name, the version each shot contributes, and any shots being left
|
||||||
|
out. Requires **admin, producer or supervisor**.
|
||||||
|
|
||||||
|
The version each shot contributes is its **newest export that actually has a
|
||||||
|
preview MOV** — not necessarily its newest export. A shot whose latest version
|
||||||
|
is still rendering goes into the review as the version that can be watched.
|
||||||
|
A shot with no MOV at all is listed as left out, with the reason, rather than
|
||||||
|
quietly reducing the folder.
|
||||||
|
|
||||||
|
### What lands on disk
|
||||||
|
|
||||||
|
```
|
||||||
|
{deliveryRoot}/PRODUCER_REVIEWS/20260828_Producer_review/
|
||||||
|
├── EP6_VFX_012_v004.mov
|
||||||
|
├── EP6_VFX_013_v002.mov
|
||||||
|
└── UNG_106_010_040_cmp_TT_v001.mov
|
||||||
|
```
|
||||||
|
|
||||||
|
Flat — the MOVs sit beside each other so they can be scrubbed through in order.
|
||||||
|
Names follow the same client-naming rule as a delivery: the production's own
|
||||||
|
code where it has one, ours where it does not, so a shot reads identically in a
|
||||||
|
review folder and in the delivery that follows it.
|
||||||
|
|
||||||
|
The folder is **exactly the MOVs**: no CSV, no `manifest.json` beside them. The
|
||||||
|
manifest still goes back to the app, so the record of what was shared is kept
|
||||||
|
without cluttering the share.
|
||||||
|
|
||||||
|
Second review the same day is `20260828_Producer_review_02`, then `_03`. A
|
||||||
|
number is never reused, even if the package that took it was cancelled.
|
||||||
|
|
||||||
|
### What it does not do
|
||||||
|
|
||||||
|
**A review never moves a shot along.** Reviews happen throughout a shot's life,
|
||||||
|
long before QC passes it, and the same version is routinely shown twice — so
|
||||||
|
building one changes nothing about the exports in it, and there is no
|
||||||
|
**Mark delivered** on a review package. Shots stay exactly where they are in
|
||||||
|
the pipeline.
|
||||||
|
|
||||||
|
A **missing MOV fails the package** here, unlike in an EXR delivery where a
|
||||||
|
missing MOV is logged and the build continues. In a review the MOV is the
|
||||||
|
deliverable, and a review folder quietly one shot short is worse than one that
|
||||||
|
says so.
|
||||||
|
|
||||||
|
### Configuration
|
||||||
|
|
||||||
|
Two more keys in the same `deliveryConfig` (§11.6):
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"reviewNameTemplate": "{yyyymmdd}_Producer_review",
|
||||||
|
"layout": {
|
||||||
|
"reviewDir": "{deliveryRoot}/PRODUCER_REVIEWS/{packageName}"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|||||||
+77
-3
@@ -207,7 +207,7 @@ stateDiagram-v2
|
|||||||
| T9 | VALIDATION_FAILED | QUEUED | Retry (full re-render) | User | new attempt; old validation rows kept for history |
|
| T9 | VALIDATION_FAILED | QUEUED | Retry (full re-render) | User | new attempt; old validation rows kept for history |
|
||||||
| T10 | GENERATING_PREVIEW | PREVIEW_FAILED | ffmpeg/upload failure | Worker | error stored |
|
| T10 | GENERATING_PREVIEW | PREVIEW_FAILED | ffmpeg/upload failure | Worker | error stored |
|
||||||
| T11 | PREVIEW_FAILED | GENERATING_PREVIEW | Retry preview | User | validation is NOT re-run |
|
| T11 | PREVIEW_FAILED | GENERATING_PREVIEW | Retry preview | User | validation is NOT re-run |
|
||||||
| T12 | GENERATING_PREVIEW | READY_FOR_QC | `finalize` report | Worker | `Version` row created (isLatest, **never client-shared**), thumbnail set, metadata JSON key stored; **no task/shot status change** — QC typically runs on already client-approved shots and must not disturb review state (Section 10) |
|
| T12 | GENERATING_PREVIEW | READY_FOR_QC | `finalize` report | Worker | `Version` row created (isLatest, **never client-shared**), thumbnail set, metadata JSON key stored; `Shot.generatedThumbnailUrl` set when the project opts in (§9.1a) — never `Shot.thumbnailUrl`; **no task/shot status change** — QC typically runs on already client-approved shots and must not disturb review state (Section 10) |
|
||||||
| T13 | READY_FOR_QC | QC_FAILED | `POST .../qc {FAIL}` | Artist (AE) or user (web) | `QCReview` row; task → CHANGES (drives existing Shot REVISIONS derivation) |
|
| T13 | READY_FOR_QC | QC_FAILED | `POST .../qc {FAIL}` | Artist (AE) or user (web) | `QCReview` row; task → CHANGES (drives existing Shot REVISIONS derivation) |
|
||||||
| T14 | READY_FOR_QC | READY_FOR_DELIVERY | `POST .../qc {PASS}` | Artist / user | `QCReview` row |
|
| T14 | READY_FOR_QC | READY_FOR_DELIVERY | `POST .../qc {PASS}` | Artist / user | `QCReview` row |
|
||||||
| T15 | READY_FOR_DELIVERY | PACKAGED | Delivery build completes | Worker | `DeliveryItem` links Export to package |
|
| T15 | READY_FOR_DELIVERY | PACKAGED | Delivery build completes | Worker | `DeliveryItem` links Export to package |
|
||||||
@@ -268,6 +268,9 @@ model Export {
|
|||||||
shot Shot @relation(fields: [shotId], references: [id])
|
shot Shot @relation(fields: [shotId], references: [id])
|
||||||
projectId String
|
projectId String
|
||||||
taskId String? // comp task the preview Version attaches to
|
taskId String? // comp task the preview Version attaches to
|
||||||
|
// (E1 creates one named after the preview file
|
||||||
|
// when the shot has none, so the preview lands
|
||||||
|
// somewhere the app shows it)
|
||||||
versionId String? // preview Version created at READY_FOR_QC
|
versionId String? // preview Version created at READY_FOR_QC
|
||||||
versionNumber Int // 4
|
versionNumber Int // 4
|
||||||
versionString String // "v004"
|
versionString String // "v004"
|
||||||
@@ -448,6 +451,7 @@ model DeliveryPackage {
|
|||||||
projectId String
|
projectId String
|
||||||
episode String // "101"
|
episode String // "101"
|
||||||
name String // "260805_Delivery" (per 18.1-Q6 convention)
|
name String // "260805_Delivery" (per 18.1-Q6 convention)
|
||||||
|
kind DeliveryKind @default(EXR_DELIVERY) // EXR_DELIVERY | MOV_REVIEW (§11.6)
|
||||||
packageNumber Int // sequential per project → "Package #15"
|
packageNumber Int // sequential per project → "Package #15"
|
||||||
status DeliveryStatus @default(DRAFT)
|
status DeliveryStatus @default(DRAFT)
|
||||||
rootPath String? // final path on delivery volume
|
rootPath String? // final path on delivery volume
|
||||||
@@ -464,6 +468,7 @@ model DeliveryPackage {
|
|||||||
|
|
||||||
@@unique([projectId, packageNumber])
|
@@unique([projectId, packageNumber])
|
||||||
@@index([projectId, episode])
|
@@index([projectId, episode])
|
||||||
|
@@index([projectId, kind])
|
||||||
}
|
}
|
||||||
|
|
||||||
model DeliveryItem {
|
model DeliveryItem {
|
||||||
@@ -488,6 +493,8 @@ model DeliveryItem {
|
|||||||
|
|
||||||
**Version locking:** the package references `Export` rows, and items denormalise `shotCode`/`versionString` at creation. Later re-renders of a shot never mutate a package — delivery history is immutable by construction.
|
**Version locking:** the package references `Export` rows, and items denormalise `shotCode`/`versionString` at creation. Later re-renders of a shot never mutate a package — delivery history is immutable by construction.
|
||||||
|
|
||||||
|
**`kind`** distinguishes a shippable EXR delivery from a MOV review folder (§11.6). Both use these two models and the same `DELIVERY_BUILD` job; only a review leaves `exrPath` null, and only a delivery advances its exports to PACKAGED/DELIVERED.
|
||||||
|
|
||||||
### 5.8 Changes to existing models (additive only)
|
### 5.8 Changes to existing models (additive only)
|
||||||
|
|
||||||
| Model | Addition | Purpose |
|
| Model | Addition | Purpose |
|
||||||
@@ -1066,6 +1073,8 @@ Timecode is the check this engine exists for. It is validated **against the sour
|
|||||||
| 2 | Plate re-derived on the worker from the footage root + shot code (manifestVersion 1, or a timing plate that no longer resolves). If elements disagree, the one matching the render's frame count wins; still ambiguous → WARN, never PASS | PASS / FAIL, `reference: "derived"` |
|
| 2 | Plate re-derived on the worker from the footage root + shot code (manifestVersion 1, or a timing plate that no longer resolves). If elements disagree, the one matching the render's frame count wins; still ambiguous → WARN, never PASS | PASS / FAIL, `reference: "derived"` |
|
||||||
| 3 | API `Shot.timecodeStart` **minus `handleFrames`** | **WARN only, never PASS** — `reference: "api"`, message states the plate could not be read |
|
| 3 | API `Shot.timecodeStart` **minus `handleFrames`** | **WARN only, never PASS** — `reference: "api"`, message states the plate could not be read |
|
||||||
|
|
||||||
|
**Several delivered elements.** When the rank-1 timing plate does not match, the worker tries the manifest's other `plates[]` before failing — the panel's longest-duration pick is not always the element the comp was anchored to. A match against one of them is a PASS naming that element; no match still FAILs against the timing plate, listing the others tried. Only delivered footage qualifies: plates under a configured plate search root, or (with none configured) alongside the timing plate in its footage folder. `plates[]` also holds pre-renders, which agree with the render by construction and must never rescue it.
|
||||||
|
|
||||||
Rank 3 is a diagnostic, not a verification: it depends on the show's handle count being correct for that specific plate, which is exactly the assumption the defects above violate.
|
Rank 3 is a diagnostic, not a verification: it depends on the show's handle count being correct for that specific plate, which is exactly the assumption the defects above violate.
|
||||||
|
|
||||||
**Comparison, given the plate reference:**
|
**Comparison, given the plate reference:**
|
||||||
@@ -1100,18 +1109,36 @@ Runs on the worker after validation passes (Export = GENERATING_PREVIEW).
|
|||||||
### 9.1 Stages
|
### 9.1 Stages
|
||||||
|
|
||||||
1. **Build + render preview comp (AE, headless).** The worker launches `AfterFX.com -noui -r vfxr_build_preview.jsx`, passing a job-context JSON file (manifest + slate/overlay fields fetched from E3). The script is the connector's existing preview-comp code, packaged with the worker: it imports the *validated* EXR sequence, builds the preview comp from the studio template (head slate populated from API data, overlays/burn-ins throughout), applies the colour chain (linear → log → show LUT from `colorPipeline` config), queues it with the project's MOV output-module template, and renders the **delivery-grade preview MOV** to the SAN beside the EXRs (`Export.deliveryMovPath`). This is the "MOV LT Preview" that ships inside delivery packages (Section 11).
|
1. **Build + render preview comp (AE, headless).** The worker launches `AfterFX.com -noui -r vfxr_build_preview.jsx`, passing a job-context JSON file (manifest + slate/overlay fields fetched from E3). The script is the connector's existing preview-comp code, packaged with the worker: it imports the *validated* EXR sequence, builds the preview comp from the studio template (head slate populated from API data, overlays/burn-ins throughout), applies the colour chain (linear → log → show LUT from `colorPipeline` config), queues it with the project's MOV output-module template, and renders the **delivery-grade preview MOV** to the SAN beside the EXRs (`Export.deliveryMovPath`). This is the "MOV LT Preview" that ships inside delivery packages (Section 11).
|
||||||
2. **Web transcode (ffmpeg).** The delivery MOV is transcoded to a web-playable H.264 (1920-wide, CRF 18) and a thumbnail JPEG (frame at 25% duration, 960-wide), uploaded via E20 presign.
|
2. **Web transcode (ffmpeg).** The delivery MOV is transcoded to a web-playable H.264 (1920-wide, CRF 18) and a thumbnail JPEG (960-wide), uploaded via E20 presign. The thumbnail is taken at **25% of *picture* duration**, seeking past the head slate: the build script reports the SHOT layer's in-point as `pictureStartSeconds`, and the worker seeks to `pictureStart + 25%`. Builds that report no picture start fall back to scanning the whole file. (Until 2026-08-27 this used ffmpeg's `thumbnail` filter, which only considers the first 100 frames — on a slated preview, the slate card. Every thumbnail produced before then is a picture of the slate.)
|
||||||
3. **Metadata JSON.** Worker-composed (manifest + validation summary + render stats + checksums + tool/template versions), uploaded via E20.
|
3. **Metadata JSON.** Worker-composed (manifest + validation summary + render stats + checksums + tool/template versions), uploaded via E20.
|
||||||
|
|
||||||
| Artifact | Produced by | Destination |
|
| Artifact | Produced by | Destination |
|
||||||
|---|---|---|
|
|---|---|---|
|
||||||
| Delivery MOV (slate + burn-ins, graded via show LUT, delivery codec from AE output template) | AE headless render | SAN → `Export.deliveryMovPath`; copied/linked into delivery packages |
|
| Delivery MOV (slate + burn-ins, graded via show LUT, delivery codec from AE output template) | AE headless render | SAN → `Export.deliveryMovPath`; copied/linked into delivery packages |
|
||||||
| Web preview MOV (H.264) | ffmpeg transcode of the delivery MOV | object storage `videos/` → `Version.fileUrl` |
|
| Web preview MOV (H.264) | ffmpeg transcode of the delivery MOV | object storage `videos/` → `Version.fileUrl` |
|
||||||
| Thumbnail | ffmpeg | `image/` → `Version.thumbnailUrl` + `Export.thumbnailKey` |
|
| Thumbnail | ffmpeg | `image/` → `Version.thumbnailUrl` + `Export.thumbnailKey`; also `Shot.generatedThumbnailUrl` when the project opts in (§9.3) |
|
||||||
| Metadata JSON | worker | `renders/` → `Export.metadataKey` |
|
| Metadata JSON | worker | `renders/` → `Export.metadataKey` |
|
||||||
|
|
||||||
Because the web preview is a transcode of the AE-generated MOV, review media and delivery media are guaranteed to show identical slates, burn-ins, and colour — one source of truth.
|
Because the web preview is a transcode of the AE-generated MOV, review media and delivery media are guaranteed to show identical slates, burn-ins, and colour — one source of truth.
|
||||||
|
|
||||||
|
### 9.1a Render frames as shot thumbnails
|
||||||
|
|
||||||
|
Shots carry two stills, in two columns, and the distinction is the whole design:
|
||||||
|
|
||||||
|
| Column | Written by | Meaning |
|
||||||
|
|---|---|---|
|
||||||
|
| `Shot.thumbnailUrl` | humans only — single upload, batch upload, ext API | The reference frame that came with the brief. Editorial data. |
|
||||||
|
| `Shot.generatedThumbnailUrl` | the pipeline, and the manual promote action | A frame lifted from a finished export. |
|
||||||
|
|
||||||
|
Display resolution is `thumbnailUrl ?? generatedThumbnailUrl` (`lib/shot-thumbnail.ts`), applied at every shot surface: shot grid, kanban, schedule, shot status, storyboard (screen and PDF), shoot log, slate tab, client portal, and the ext APIs the Nuke/AE panel reads. **The reference always wins**, so the pipeline can only fill a gap and can never overwrite the brief — clearing the generated one always falls back.
|
||||||
|
|
||||||
|
Promotion happens two ways:
|
||||||
|
|
||||||
|
* **Automatically**, for projects with `pipelineConfig.autoShotThumbnail` set (Project Settings → *Use render frames as shot thumbnails*). Off by default and deliberately per-show: productions that ship a still with every shot already have a reference frame and the renders should not compete with it. It exists for shows that arrive with no stills at all, where the alternative is an empty grid. `finalizePreview` writes the column and notes it on the export timeline.
|
||||||
|
* **By hand**, via `promoteExportThumbnail` / `clearGeneratedThumbnail` (Shot Settings → Thumbnail → *From renders*), which work regardless of the project flag — one shot on an otherwise hands-off show. With no explicit export, the newest export of that shot that has a thumbnail is used.
|
||||||
|
|
||||||
|
Note this is the one place a render-derived artifact reaches the client portal. It is a still, not a `Version`, so §10.0 is intact — no technical render re-enters the review flow and no approval state moves — but a client viewing a shot with no supplied still now sees a frame from the render rather than a placeholder.
|
||||||
|
|
||||||
### 9.2 Colour configuration
|
### 9.2 Colour configuration
|
||||||
|
|
||||||
`Project.deliveryConfig.colorPipeline` (per 18.1-Q4/Q12) — **required and unique per project**; enabling the pipeline on a project without it is a validation error, and values must never be carried over from another show:
|
`Project.deliveryConfig.colorPipeline` (per 18.1-Q4/Q12) — **required and unique per project**; enabling the pipeline on a project without it is a validation error, and values must never be carried over from another show:
|
||||||
@@ -1152,6 +1179,27 @@ Not every export is framed like its review. A deliverable rendered unscaled or w
|
|||||||
|
|
||||||
With no earlier export to inherit from, the export still reaches READY_FOR_QC and the timeline records that it has no review media.
|
With no earlier export to inherit from, the export still reaches READY_FOR_QC and the timeline records that it has no review media.
|
||||||
|
|
||||||
|
### 9.5 Handles in review (metadata only)
|
||||||
|
|
||||||
|
Renders run past the cut at each end (8 + 8 by house convention). Handles ship with the EXRs and stay in the preview, but reviewers must be able to tell them from the cut, or a glitch in a handle gets flagged as a problem in the shot. **Nothing is trimmed or burned in** — this is deliberately not the reverted picture-lock trim (which desynced the overlay timecode); the render and every delivered file are unchanged.
|
||||||
|
|
||||||
|
- **Panel:** "Includes handles [8] frames each end" (default on, prefilled from Handle Frames) sends `manifest.review = { handleHead, handleTail }`; unticked sends 0/0. Manifests without `review` (older panels) fall back to `source.handleFrames` (`manifestHandles`, exports.ts).
|
||||||
|
- **Export → Version:** `createExport` stores `Export.handleHead/handleTail`; `finalizePreview` copies them onto the Version, plus `pictureStartFrame` = the head slate length from the build's `pictureStartSeconds` (worker ≥ 1.6.4). Left null, the player infers the slate as MP4 frames − `frameCount` (the EXR count), within 0–5 frames.
|
||||||
|
- **Player** (`lib/handles.ts` → `computeEditRange`): the timeline hatches the handles amber and labels them HANDLE (the slate, SLATE); while the playhead is in a handle the picture gets an amber frame and a "HEAD/TAIL HANDLE · NOT IN EDIT" tag; notes on handle frames carry a HANDLE badge. "Edit range only" (scissors) keeps play, reverse and go-to-start/end inside the cut — on by default in the client portal, off for staff.
|
||||||
|
- **Staff override:** the review page's Handles button edits a version's head/tail/slate — for manual uploads, or to correct a render.
|
||||||
|
- **Backfill** (`20260922000000_version_handles`): every existing export takes its manifest's `source.handleFrames` (else 8), and the Versions they produced take the same.
|
||||||
|
|
||||||
|
### 9.6 High quality playback and the ProRes download
|
||||||
|
|
||||||
|
The Standard review MP4 is AE's H.264 (UHD, ~35 Mbps). ProRes itself can't be the player's source — only Safari on a Mac decodes it in a web page, and UHD ProRes LT is ~280 Mbps — so the worker (≥ 1.7.0, when `preview.highQuality` is on) adds two things after the AE render, both **best-effort** (a failure costs the extras, never the preview):
|
||||||
|
|
||||||
|
- **High quality MP4:** ffmpeg re-encodes the delivery MOV as full-res H.264 High, CRF 14 capped at 100 Mbps, yuv420p, faststart → `Version.hqFileUrl`. The player shows an **HQ** switch when present; switching keeps frame, play state, speed and zoom, is remembered per browser (`review:quality`), and falls back to Standard if the file won't load. Same comp as the Standard MP4, so slate and handles line up frame for frame.
|
||||||
|
- **ProRes download:** the MOV itself is uploaded (presign kind `highres`) → `Version.highResKey/highResFilename/highResSize`. It is the version's **High Res** download in the client portal (named with the client code, `clientHighResFilename`) and a **ProRes** button on the staff review page. The shot's manually uploaded High Res remains the fallback for versions without one. Since worker 1.7.1 the MOV uploads **in the background after finalize** (`HighResUploader`, queue in `%ProgramData%\VFXReviewWorker\highres-queue`, resumes after a restart, 5 attempts) and attaches via `POST /api/ext/render/jobs/{id}/attach-highres` (E13b); a MOV from a preview that a newer preview has superseded is discarded. While a preview job uploads, the worker replaces the job's log tail with live upload status. Since 1.7.2, artifacts of 16 MB or more upload as S3 multipart: `artifact-presign` with `multipart: true, size` returns `uploadId`, `partSize` (8 MB minimum) and one presigned URL per part; the worker PUTs parts on `uploadConcurrency` connections (default 16), retries each part up to 4 times, then calls `artifact-complete` (E20b) to stitch them, or with `abort: true` to discard them. A single connection from the studio to nbg1 is capped near 0.1 MB/s.
|
||||||
|
|
||||||
|
A lease keep-alive runs during the encode and uploads (they can outlast the 300 s lease). The export timeline records what was attached.
|
||||||
|
|
||||||
|
**Housekeeping** (`lib/render-pipeline/high-res.ts`): a version keeps its HQ MP4 and ProRes while it is the task's latest, shared with the client, approved, or younger than `preview.highResRetentionDays` (14). Otherwise both are deleted from storage and the row gets `highResPrunedAt`; the Standard MP4 is never touched. It runs for the task after every finalize and studio-wide hourly from the reaper; deleting a version deletes its files. A reslate replaces (and deletes) the version's previous HQ/ProRes.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 10. QC Workflow
|
## 10. QC Workflow
|
||||||
@@ -1230,6 +1278,27 @@ Tokens: `{showId} {episode} {yymmdd} {yyyymmdd} {packageName} {packageDir} {shot
|
|||||||
|
|
||||||
The Delivery Packages page (Section 13) lists every package permanently: `#15 · 101/260805_Delivery · Episode 101 · 18 shots · built 2026-08-05 · delivered 2026-08-05 by Chris`, expandable to items → Export → full render/validation/QC history. Packages are never deleted; a mistaken package is CANCELLED (DRAFT/QUEUED/FAILED only) or superseded by building a new one.
|
The Delivery Packages page (Section 13) lists every package permanently: `#15 · 101/260805_Delivery · Episode 101 · 18 shots · built 2026-08-05 · delivered 2026-08-05 by Chris`, expandable to items → Export → full render/validation/QC history. Packages are never deleted; a mistaken package is CANCELLED (DRAFT/QUEUED/FAILED only) or superseded by building a new one.
|
||||||
|
|
||||||
|
### 11.6 MOV review packages (`DeliveryPackage.kind = MOV_REVIEW`)
|
||||||
|
|
||||||
|
A formal review is shared as a flat, dated folder of the preview MOVs — the same package/job/verification machinery as §11.1–11.5, a different shape on disk:
|
||||||
|
|
||||||
|
```
|
||||||
|
{deliveryRoot}/PRODUCER_REVIEWS/20260828_Producer_review/
|
||||||
|
├── EP6_VFX_012_v004.mov ← client naming where the production supplies it
|
||||||
|
├── EP6_VFX_013_v002.mov
|
||||||
|
└── UNG_106_010_040_cmp_TT_v001.mov ← ours where it does not
|
||||||
|
```
|
||||||
|
|
||||||
|
The second review that day is `_02`, the third `_03`; the first carries no suffix. Numbering counts every package built under that base — cancelled and failed ones included — so a number is never reused for a different folder. Config: `reviewNameTemplate` (default `{yyyymmdd}_Producer_review`) and `layout.reviewDir` (default `{deliveryRoot}/PRODUCER_REVIEWS/{packageName}`).
|
||||||
|
|
||||||
|
Three rules separate a review from a delivery:
|
||||||
|
|
||||||
|
- **It never advances an Export.** Reviews happen throughout a shot's life, long before QC passes it, and the same version is routinely shown twice. Nothing is marked PACKAGED or DELIVERED when the folder is built, and `Mark delivered` is refused on a review package.
|
||||||
|
- **Selection is by shot, not by export.** The user picks shots on Shot Status → *Bulk Actions → Build MOV Review Package*; the server resolves each to its **newest export that actually has a `deliveryMovPath`** — not necessarily its newest export, since a shot whose latest version is still rendering should go into the review as the version that can be watched. Shots with no MOV at all are listed in the confirm dialog and left out rather than silently dropped.
|
||||||
|
- **The folder is exactly the MOVs.** No CSV, no `manifest.json` written beside them. The manifest still returns to the server, so the record of what was shared is kept without cluttering the share.
|
||||||
|
|
||||||
|
Verification is proportional as in §11.3, adapted to a single file with no validation-time digest: a hard link is the source and needs nothing; a copy is checked against its source by length always, and by full hash under `"verifyMode": "always-hash"`. A missing MOV **fails the item** here — in an EXR delivery the MOV is a viewing copy beside the real deliverable, but in a review it *is* the deliverable, and a review folder quietly one shot short is worse than one that says so.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 12. AE Panel Changes
|
## 12. AE Panel Changes
|
||||||
@@ -1246,6 +1315,11 @@ The panel keeps all existing capabilities (episode/shot discovery, overlays, pic
|
|||||||
| Latest Export + QC status | new E2 `exports/latest` — e.g. `v004 — READY_FOR_QC`, `v004 — RENDERING 42% (ETA 1:36 on RENDER-01)`, `v003 — QC FAILED: "grain mismatch"` |
|
| Latest Export + QC status | new E2 `exports/latest` — e.g. `v004 — READY_FOR_QC`, `v004 — RENDERING 42% (ETA 1:36 on RENDER-01)`, `v003 — QC FAILED: "grain mismatch"` |
|
||||||
|
|
||||||
While an export is active the panel polls E2 every 15 s to live-update the header.
|
While an export is active the panel polls E2 every 15 s to live-update the header.
|
||||||
|
The poll stops when the export leaves an active status, and also when the panel is
|
||||||
|
closed or reloaded — `app.scheduleTask` outlives the panel instance that armed it,
|
||||||
|
so the task id is kept in ExtendScript global scope where the next instance can
|
||||||
|
still cancel it. The export is unaffected either way: it runs on the farm, and the
|
||||||
|
header picks its status back up on the next Refresh.
|
||||||
|
|
||||||
### 12.2 Buttons and their API calls
|
### 12.2 Buttons and their API calls
|
||||||
|
|
||||||
|
|||||||
@@ -208,6 +208,9 @@ read back from the assembly, so a machine can never report a version it is not r
|
|||||||
`pathMappings` translate the manifest's canonical UNC paths to this machine's drive
|
`pathMappings` translate the manifest's canonical UNC paths to this machine's drive
|
||||||
mappings. `plateSearchRoots` is optional: it is only consulted when a manifest carries no
|
mappings. `plateSearchRoots` is optional: it is only consulted when a manifest carries no
|
||||||
timing plate (older panel versions), to find the shot's plates for the timecode check.
|
timing plate (older panel versions), to find the shot's plates for the timecode check.
|
||||||
|
`uploadConcurrency` (default 16) is how many parallel connections a file of 16 MB or more
|
||||||
|
uploads over. Each connection to object storage is capped near 0.1 MB/s from the studio, so
|
||||||
|
throughput scales with it (measured 2026-10-01: 1 → 0.13 MB/s, 8 → 0.64, 24 → 1.69 MB/s).
|
||||||
Everything tunable (poll interval, lease, stall timeout, max attempts, validation) lives in
|
Everything tunable (poll interval, lease, stall timeout, max attempts, validation) lives in
|
||||||
the server's SystemConfig and arrives at registration — no per-machine tuning files.
|
the server's SystemConfig and arrives at registration — no per-machine tuning files.
|
||||||
|
|
||||||
|
|||||||
@@ -73,6 +73,46 @@ public class BlenderProgressParserTests
|
|||||||
Assert.Equal(1002, frames[^1]);
|
Assert.Equal(1002, frames[^1]);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Blender 5.x prefixes every line with elapsed time and a log category.
|
||||||
|
/// Anchored on "Saved:", the parser counted no frames from a render that
|
||||||
|
/// wrote every one, and the job failed as "saved no frames".
|
||||||
|
/// These lines are verbatim Blender 5.2 output.
|
||||||
|
/// </summary>
|
||||||
|
[Fact]
|
||||||
|
public void ParsesBlender5PrefixedOutput()
|
||||||
|
{
|
||||||
|
Assert.Equal(@"X:\renders\frame_0001.png",
|
||||||
|
BlenderProgressParser.ParseSaved(@"00:02.954 render | Saved: 'X:\renders\frame_0001.png'"));
|
||||||
|
Assert.Equal(1, BlenderProgressParser.ParseFrame("00:02.469 render | Fra: 1 | Mem: 0M | Synchronizing object | Cube"));
|
||||||
|
Assert.Null(BlenderProgressParser.ParseSaved("00:02.954 render | Time: 00:00.87 (Saving: 00:00.14)"));
|
||||||
|
Assert.Null(BlenderProgressParser.ParseFrame("00:02.079 render | Rendering frame 1"));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void RecognisesBlender5Errors()
|
||||||
|
{
|
||||||
|
const string unwritable = @"00:03.063 reports | ERROR Render error (No such file or directory) cannot save: 'Q:\out\f_0001.png'";
|
||||||
|
Assert.True(BlenderProgressParser.IsErrorLine(unwritable));
|
||||||
|
Assert.True(BlenderProgressParser.IsNonRetryableError(unwritable));
|
||||||
|
|
||||||
|
const string missing = @"00:13.250 reports | ERROR Cannot read file ""X:\gone.blend"": No such file or directory";
|
||||||
|
Assert.True(BlenderProgressParser.IsErrorLine(missing));
|
||||||
|
Assert.True(BlenderProgressParser.IsNonRetryableError(missing));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Add-ons print warnings on every launch; one must never become the
|
||||||
|
/// reported reason a render failed.
|
||||||
|
/// </summary>
|
||||||
|
[Theory]
|
||||||
|
[InlineData("Warning: add-on missing 'bl_info', this can cause poor performance!: 'G:\\addons\\x\\__init__.py'")]
|
||||||
|
[InlineData("00:01.000 addon | WARNING something harmless")]
|
||||||
|
public void WarningsAreNotErrors(string line)
|
||||||
|
{
|
||||||
|
Assert.False(BlenderProgressParser.IsErrorLine(line));
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary>Mirrors BlenderRunner.PumpAsync: CR and LF both end a line.</summary>
|
/// <summary>Mirrors BlenderRunner.PumpAsync: CR and LF both end a line.</summary>
|
||||||
private static List<string> SplitLikeThePump(string text)
|
private static List<string> SplitLikeThePump(string text)
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -0,0 +1,193 @@
|
|||||||
|
using Microsoft.Extensions.Logging.Abstractions;
|
||||||
|
using VFXReviewWorker;
|
||||||
|
using Xunit;
|
||||||
|
|
||||||
|
namespace VFXReviewWorker.Tests;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// MOV review packages (RenderPipeline2 §11.6). A review folder is opened
|
||||||
|
/// directly by a producer, so the things pinned here are the ones they would
|
||||||
|
/// notice: it is flat, it carries the client's own naming, and it contains the
|
||||||
|
/// MOVs and nothing else.
|
||||||
|
/// </summary>
|
||||||
|
public class MovReviewStageTests : IDisposable
|
||||||
|
{
|
||||||
|
private readonly string _root = Path.Combine(Path.GetTempPath(), $"vfxr_review_{Guid.NewGuid():N}");
|
||||||
|
private readonly string _renderDir;
|
||||||
|
private readonly string _reviewDir;
|
||||||
|
|
||||||
|
public MovReviewStageTests()
|
||||||
|
{
|
||||||
|
_renderDir = Path.Combine(_root, "renders", "SHOT_001", "v004");
|
||||||
|
_reviewDir = Path.Combine(_root, "DELIVERY", "PRODUCER_REVIEWS", "20260828_Producer_review");
|
||||||
|
Directory.CreateDirectory(_renderDir);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void Dispose()
|
||||||
|
{
|
||||||
|
try { Directory.Delete(_root, recursive: true); } catch { }
|
||||||
|
}
|
||||||
|
|
||||||
|
private string WriteMov(string shotCode, string version, string contents = "mov bytes")
|
||||||
|
{
|
||||||
|
var path = Path.Combine(_renderDir, $"{shotCode}_cmp_TT_{version}.mov");
|
||||||
|
File.WriteAllText(path, contents);
|
||||||
|
return path;
|
||||||
|
}
|
||||||
|
|
||||||
|
private DeliveryManifest Manifest(params DeliveryManifestItem[] items) => new()
|
||||||
|
{
|
||||||
|
Kind = "MOV_REVIEW",
|
||||||
|
PackageId = "pkg1",
|
||||||
|
PackageName = "20260828_Producer_review",
|
||||||
|
PackageNumber = 7,
|
||||||
|
Episode = "101",
|
||||||
|
PackageDir = _reviewDir,
|
||||||
|
// A review writes no report; the server keeps the record instead.
|
||||||
|
ReportFile = "",
|
||||||
|
Items = items.ToList(),
|
||||||
|
};
|
||||||
|
|
||||||
|
private DeliveryManifestItem Item(
|
||||||
|
string shotCode, string version, string? movPath, string? deliveredBase = null) => new()
|
||||||
|
{
|
||||||
|
ItemId = $"item_{shotCode}",
|
||||||
|
ExportId = $"exp_{shotCode}",
|
||||||
|
ShotCode = shotCode,
|
||||||
|
VersionString = version,
|
||||||
|
SourceDir = "",
|
||||||
|
OutputPattern = "",
|
||||||
|
FrameStart = 1001,
|
||||||
|
FrameEnd = 1050,
|
||||||
|
DeliveryMovPath = movPath,
|
||||||
|
// Flat: every item's folder is the package folder itself.
|
||||||
|
ShotDir = _reviewDir,
|
||||||
|
DeliveredBaseName = deliveredBase ?? $"{shotCode}_cmp_TT_{version}",
|
||||||
|
};
|
||||||
|
|
||||||
|
private DeliveryStage NewStage() => new(
|
||||||
|
new WorkerOptions { ServerUrl = "n/a", ApiKey = "n/a" },
|
||||||
|
new ApiClient(new WorkerOptions { ServerUrl = "http://localhost:1", ApiKey = "x" }, NullLogger<ApiClient>.Instance),
|
||||||
|
NullLogger<DeliveryStage>.Instance);
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task BuildsAFlatFolderOfMovsUnderTheClientFacingName()
|
||||||
|
{
|
||||||
|
var mov = WriteMov("SHOT_001", "v004");
|
||||||
|
var manifest = Manifest(Item("SHOT_001", "v004", mov, deliveredBase: "EP6_VFX_012_v004"));
|
||||||
|
|
||||||
|
var result = await NewStage().RunAsync(new ClaimedJob { Id = "job1" }, manifest, "machine1",
|
||||||
|
CancellationToken.None, CancellationToken.None);
|
||||||
|
|
||||||
|
Assert.True(result.Ok);
|
||||||
|
var item = Assert.Single(result.Items);
|
||||||
|
Assert.Equal("VERIFIED", item.Status);
|
||||||
|
Assert.Equal(1, item.FileCount);
|
||||||
|
// No shot subfolder: the MOVs sit beside each other to be scrubbed through.
|
||||||
|
Assert.Null(item.ExrPath);
|
||||||
|
Assert.Equal(Path.Combine(_reviewDir, "EP6_VFX_012_v004.mov"), item.MovPath);
|
||||||
|
Assert.Single(Directory.GetDirectories(_reviewDir).Concat(Directory.GetFiles(_reviewDir)));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task LeavesNoReportOrManifestBesideTheMovs()
|
||||||
|
{
|
||||||
|
var manifest = Manifest(Item("SHOT_001", "v004", WriteMov("SHOT_001", "v004")));
|
||||||
|
|
||||||
|
var result = await NewStage().RunAsync(new ClaimedJob { Id = "job1" }, manifest, "machine1",
|
||||||
|
CancellationToken.None, CancellationToken.None);
|
||||||
|
|
||||||
|
Assert.True(result.Ok);
|
||||||
|
Assert.Null(result.ReportPath);
|
||||||
|
// What a producer opens is exactly the MOVs — no manifest.json, no CSV.
|
||||||
|
Assert.False(File.Exists(Path.Combine(_reviewDir, "manifest.json")));
|
||||||
|
Assert.All(Directory.GetFiles(_reviewDir), f => Assert.EndsWith(".mov", f));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task HardLinksSoASeventyShotReviewCostsNoDisk()
|
||||||
|
{
|
||||||
|
var mov = WriteMov("SHOT_001", "v004");
|
||||||
|
var manifest = Manifest(Item("SHOT_001", "v004", mov));
|
||||||
|
|
||||||
|
var result = await NewStage().RunAsync(new ClaimedJob { Id = "job1" }, manifest, "machine1",
|
||||||
|
CancellationToken.None, CancellationToken.None);
|
||||||
|
|
||||||
|
Assert.Equal("hardlink", result.Items[0].LinkMode);
|
||||||
|
File.WriteAllText(mov, "rewritten");
|
||||||
|
Assert.Equal("rewritten", File.ReadAllText(result.Items[0].MovPath!));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task AlwaysCopyModeProducesAnIndependentFile()
|
||||||
|
{
|
||||||
|
var mov = WriteMov("SHOT_001", "v004");
|
||||||
|
var manifest = Manifest(Item("SHOT_001", "v004", mov));
|
||||||
|
manifest.CopyMode = "always-copy";
|
||||||
|
|
||||||
|
var result = await NewStage().RunAsync(new ClaimedJob { Id = "job1" }, manifest, "machine1",
|
||||||
|
CancellationToken.None, CancellationToken.None);
|
||||||
|
|
||||||
|
Assert.True(result.Ok);
|
||||||
|
Assert.Equal("copy", result.Items[0].LinkMode);
|
||||||
|
File.WriteAllText(mov, "rewritten");
|
||||||
|
Assert.NotEqual("rewritten", File.ReadAllText(result.Items[0].MovPath!));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task AMissingMovFailsTheReviewRatherThanShippingItShort()
|
||||||
|
{
|
||||||
|
// In an EXR delivery a missing MOV is a missing viewing copy and the
|
||||||
|
// package continues. In a review the MOV *is* the deliverable.
|
||||||
|
var manifest = Manifest(Item("SHOT_001", "v004", Path.Combine(_renderDir, "never_rendered.mov")));
|
||||||
|
|
||||||
|
var result = await NewStage().RunAsync(new ClaimedJob { Id = "job1" }, manifest, "machine1",
|
||||||
|
CancellationToken.None, CancellationToken.None);
|
||||||
|
|
||||||
|
Assert.False(result.Ok);
|
||||||
|
Assert.Equal("FAILED", result.Items[0].Status);
|
||||||
|
Assert.Contains("Preview MOV not found", result.Items[0].ErrorMessage!);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task AnItemWithNoRecordedMovFails()
|
||||||
|
{
|
||||||
|
var manifest = Manifest(Item("SHOT_001", "v004", null));
|
||||||
|
|
||||||
|
var result = await NewStage().RunAsync(new ClaimedJob { Id = "job1" }, manifest, "machine1",
|
||||||
|
CancellationToken.None, CancellationToken.None);
|
||||||
|
|
||||||
|
Assert.False(result.Ok);
|
||||||
|
Assert.Contains("No preview MOV", result.Items[0].ErrorMessage!);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task HashesEveryFileWhenTheConfigDemandsIt()
|
||||||
|
{
|
||||||
|
var manifest = Manifest(Item("SHOT_001", "v004", WriteMov("SHOT_001", "v004")));
|
||||||
|
manifest.VerifyMode = "always-hash";
|
||||||
|
|
||||||
|
var result = await NewStage().RunAsync(new ClaimedJob { Id = "job1" }, manifest, "machine1",
|
||||||
|
CancellationToken.None, CancellationToken.None);
|
||||||
|
|
||||||
|
Assert.True(result.Ok);
|
||||||
|
// A MOV has no validation-time digest of its own, so the one recorded
|
||||||
|
// here is the one this build computed.
|
||||||
|
Assert.False(string.IsNullOrWhiteSpace(result.Items[0].Checksum));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task OneBadShotFailsThePackageAndTheRestStillReport()
|
||||||
|
{
|
||||||
|
var manifest = Manifest(
|
||||||
|
Item("SHOT_001", "v004", WriteMov("SHOT_001", "v004")),
|
||||||
|
Item("SHOT_002", "v002", Path.Combine(_renderDir, "absent.mov")));
|
||||||
|
|
||||||
|
var result = await NewStage().RunAsync(new ClaimedJob { Id = "job1" }, manifest, "machine1",
|
||||||
|
CancellationToken.None, CancellationToken.None);
|
||||||
|
|
||||||
|
Assert.False(result.Ok);
|
||||||
|
Assert.Equal("VERIFIED", result.Items[0].Status);
|
||||||
|
Assert.Equal("FAILED", result.Items[1].Status);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,205 @@
|
|||||||
|
using System.Collections.Concurrent;
|
||||||
|
using System.Net;
|
||||||
|
using System.Net.Sockets;
|
||||||
|
using System.Text.Json;
|
||||||
|
using Microsoft.Extensions.Logging.Abstractions;
|
||||||
|
using VFXReviewWorker;
|
||||||
|
using Xunit;
|
||||||
|
|
||||||
|
namespace VFXReviewWorker.Tests;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Large artifacts go up as parallel multipart parts: from the studio a single
|
||||||
|
/// connection to object storage is capped near 0.1 MB/s, so a ProRes MOV could
|
||||||
|
/// not finish inside the 30 min request timeout. These drive the real upload
|
||||||
|
/// code against a local fake of the server + storage.
|
||||||
|
/// </summary>
|
||||||
|
public class MultipartUploadTests : IDisposable
|
||||||
|
{
|
||||||
|
private const int PartSize = 8 * 1024 * 1024;
|
||||||
|
|
||||||
|
private readonly HttpListener _listener = new();
|
||||||
|
private readonly string _base;
|
||||||
|
private readonly ConcurrentDictionary<int, byte[]> _parts = new();
|
||||||
|
private readonly ConcurrentDictionary<int, int> _failuresLeft = new();
|
||||||
|
private readonly ConcurrentBag<string> _completions = new();
|
||||||
|
private int _inFlight, _maxInFlight;
|
||||||
|
private bool _multipartSupported = true;
|
||||||
|
private byte[]? _singlePut;
|
||||||
|
|
||||||
|
public MultipartUploadTests()
|
||||||
|
{
|
||||||
|
var port = FreePort();
|
||||||
|
_base = $"http://localhost:{port}/";
|
||||||
|
_listener.Prefixes.Add(_base);
|
||||||
|
_listener.Start();
|
||||||
|
_ = Task.Run(Serve);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static int FreePort()
|
||||||
|
{
|
||||||
|
var l = new TcpListener(IPAddress.Loopback, 0);
|
||||||
|
l.Start();
|
||||||
|
var port = ((IPEndPoint)l.LocalEndpoint).Port;
|
||||||
|
l.Stop();
|
||||||
|
return port;
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task Serve()
|
||||||
|
{
|
||||||
|
while (_listener.IsListening)
|
||||||
|
{
|
||||||
|
HttpListenerContext ctx;
|
||||||
|
try { ctx = await _listener.GetContextAsync(); } catch { return; }
|
||||||
|
_ = Task.Run(() => Handle(ctx));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task Handle(HttpListenerContext ctx)
|
||||||
|
{
|
||||||
|
var path = ctx.Request.Url!.AbsolutePath;
|
||||||
|
using var ms = new MemoryStream();
|
||||||
|
await ctx.Request.InputStream.CopyToAsync(ms);
|
||||||
|
var body = ms.ToArray();
|
||||||
|
var res = ctx.Response;
|
||||||
|
|
||||||
|
if (path.EndsWith("/artifact-presign"))
|
||||||
|
{
|
||||||
|
var req = JsonDocument.Parse(body).RootElement;
|
||||||
|
var size = req.GetProperty("size").GetInt64();
|
||||||
|
object payload = _multipartSupported && req.GetProperty("multipart").GetBoolean()
|
||||||
|
? new
|
||||||
|
{
|
||||||
|
key = "highres/x.mov",
|
||||||
|
uploadId = "up1",
|
||||||
|
partSize = PartSize,
|
||||||
|
partUrls = Enumerable.Range(1, (int)((size + PartSize - 1) / PartSize))
|
||||||
|
.Select(n => $"{_base}part/{n}").ToList(),
|
||||||
|
}
|
||||||
|
: new { key = "highres/x.mov", presignedUrl = $"{_base}single" };
|
||||||
|
await Json(res, payload);
|
||||||
|
}
|
||||||
|
else if (path.StartsWith("/part/"))
|
||||||
|
{
|
||||||
|
var n = int.Parse(path["/part/".Length..]);
|
||||||
|
var now = Interlocked.Increment(ref _inFlight);
|
||||||
|
InterlockedMax(ref _maxInFlight, now);
|
||||||
|
await Task.Delay(50);
|
||||||
|
Interlocked.Decrement(ref _inFlight);
|
||||||
|
if (_failuresLeft.TryGetValue(n, out var left) && left > 0)
|
||||||
|
{
|
||||||
|
_failuresLeft[n] = left - 1;
|
||||||
|
res.StatusCode = 500;
|
||||||
|
res.Close();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
_parts[n] = body;
|
||||||
|
res.Headers["ETag"] = $"\"etag-{n}\"";
|
||||||
|
res.Close();
|
||||||
|
}
|
||||||
|
else if (path == "/single")
|
||||||
|
{
|
||||||
|
_singlePut = body;
|
||||||
|
res.Close();
|
||||||
|
}
|
||||||
|
else if (path.EndsWith("/artifact-complete"))
|
||||||
|
{
|
||||||
|
_completions.Add(System.Text.Encoding.UTF8.GetString(body));
|
||||||
|
await Json(res, new { ok = true });
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
res.StatusCode = 404;
|
||||||
|
res.Close();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void InterlockedMax(ref int target, int value)
|
||||||
|
{
|
||||||
|
int seen;
|
||||||
|
while ((seen = Volatile.Read(ref target)) < value && Interlocked.CompareExchange(ref target, value, seen) != seen) { }
|
||||||
|
}
|
||||||
|
|
||||||
|
private static async Task Json(HttpListenerResponse res, object payload)
|
||||||
|
{
|
||||||
|
var bytes = JsonSerializer.SerializeToUtf8Bytes(payload, WorkerOptions.JsonOpts);
|
||||||
|
res.ContentType = "application/json";
|
||||||
|
await res.OutputStream.WriteAsync(bytes);
|
||||||
|
res.Close();
|
||||||
|
}
|
||||||
|
|
||||||
|
private ApiClient Client(int concurrency = 4) =>
|
||||||
|
new(new WorkerOptions { ServerUrl = _base, ApiKey = "k", UploadConcurrency = concurrency },
|
||||||
|
NullLogger<ApiClient>.Instance);
|
||||||
|
|
||||||
|
private static string TempFile(int bytes)
|
||||||
|
{
|
||||||
|
var path = Path.GetTempFileName();
|
||||||
|
var data = new byte[bytes];
|
||||||
|
new Random(42).NextBytes(data);
|
||||||
|
File.WriteAllBytes(path, data);
|
||||||
|
return path;
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task Uploads_parts_in_parallel_and_stitches_them_in_order()
|
||||||
|
{
|
||||||
|
var file = TempFile(PartSize * 5 + 12345);
|
||||||
|
long lastProgress = 0;
|
||||||
|
var key = await Client(4).UploadArtifactAsync("job1", "m1", "highres", file, "video/quicktime",
|
||||||
|
CancellationToken.None, sent => Interlocked.Exchange(ref lastProgress, sent));
|
||||||
|
|
||||||
|
Assert.Equal("highres/x.mov", key);
|
||||||
|
var stitched = Enumerable.Range(1, 6).SelectMany(n => _parts[n]).ToArray();
|
||||||
|
Assert.Equal(File.ReadAllBytes(file), stitched);
|
||||||
|
Assert.True(_maxInFlight > 1, "parts should upload concurrently");
|
||||||
|
Assert.True(_maxInFlight <= 4, "concurrency is capped by UploadConcurrency");
|
||||||
|
Assert.Equal(new FileInfo(file).Length, Interlocked.Read(ref lastProgress));
|
||||||
|
|
||||||
|
var complete = JsonDocument.Parse(Assert.Single(_completions)).RootElement;
|
||||||
|
Assert.False(complete.TryGetProperty("abort", out _));
|
||||||
|
Assert.Equal(6, complete.GetProperty("parts").GetArrayLength());
|
||||||
|
Assert.Equal("\"etag-1\"", complete.GetProperty("parts")[0].GetProperty("etag").GetString());
|
||||||
|
File.Delete(file);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task A_failed_part_is_retried_on_its_own()
|
||||||
|
{
|
||||||
|
var file = TempFile(PartSize * 3);
|
||||||
|
_failuresLeft[2] = 2;
|
||||||
|
var key = await Client().UploadArtifactAsync("job1", "m1", "highres", file, "video/quicktime", CancellationToken.None);
|
||||||
|
|
||||||
|
Assert.NotNull(key);
|
||||||
|
Assert.Equal(File.ReadAllBytes(file), Enumerable.Range(1, 3).SelectMany(n => _parts[n]).ToArray());
|
||||||
|
File.Delete(file);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task A_part_that_keeps_failing_aborts_the_upload()
|
||||||
|
{
|
||||||
|
var file = TempFile(PartSize * 3);
|
||||||
|
_failuresLeft[3] = 99;
|
||||||
|
var key = await Client().UploadArtifactAsync("job1", "m1", "highres", file, "video/quicktime", CancellationToken.None);
|
||||||
|
|
||||||
|
Assert.Null(key);
|
||||||
|
var abort = JsonDocument.Parse(Assert.Single(_completions)).RootElement;
|
||||||
|
Assert.True(abort.GetProperty("abort").GetBoolean());
|
||||||
|
File.Delete(file);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task Falls_back_to_a_single_put_on_a_server_without_multipart()
|
||||||
|
{
|
||||||
|
_multipartSupported = false;
|
||||||
|
var file = TempFile(PartSize * 3);
|
||||||
|
var key = await Client().UploadArtifactAsync("job1", "m1", "highres", file, "video/quicktime", CancellationToken.None);
|
||||||
|
|
||||||
|
Assert.Equal("highres/x.mov", key);
|
||||||
|
Assert.Equal(File.ReadAllBytes(file), _singlePut);
|
||||||
|
Assert.Empty(_completions);
|
||||||
|
File.Delete(file);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void Dispose() => _listener.Close();
|
||||||
|
}
|
||||||
@@ -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]
|
[Fact]
|
||||||
public void CreatesMissingDirectory()
|
public void CreatesMissingDirectory()
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -117,4 +117,21 @@ public class LogTailTests
|
|||||||
for (var i = 1; i <= 5; i++) tail.Add($"line {i}");
|
for (var i = 1; i <= 5; i++) tail.Add($"line {i}");
|
||||||
Assert.Equal("line 3\nline 4\nline 5", tail.ToString());
|
Assert.Equal("line 3\nline 4\nline 5", tail.ToString());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task ReadingWhileAnotherThreadWritesDoesNotThrow()
|
||||||
|
{
|
||||||
|
// The Blender runner's output pumps add lines while its progress loop
|
||||||
|
// reads the tail; unsynchronised this threw "Collection was modified".
|
||||||
|
var tail = new LogTail(200);
|
||||||
|
using var stop = new CancellationTokenSource(TimeSpan.FromSeconds(1));
|
||||||
|
var writer = Task.Run(() =>
|
||||||
|
{
|
||||||
|
var i = 0;
|
||||||
|
while (!stop.IsCancellationRequested) tail.Add($"Fra:1001 Sample {i++}/128");
|
||||||
|
});
|
||||||
|
|
||||||
|
while (!stop.IsCancellationRequested) _ = tail.ToString();
|
||||||
|
await writer;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,54 @@
|
|||||||
|
using VFXReviewWorker;
|
||||||
|
using Xunit;
|
||||||
|
|
||||||
|
namespace VFXReviewWorker.Tests;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The preview MP4 opens on the Netflix slate. ffmpeg's <c>thumbnail</c> filter
|
||||||
|
/// only considers the first 100 frames, so every thumbnail the pipeline has ever
|
||||||
|
/// produced was a picture of the slate card rather than of the shot — invisible
|
||||||
|
/// while thumbnails were only decoration in the QC queue, and unacceptable now
|
||||||
|
/// they can become a shot's thumbnail.
|
||||||
|
///
|
||||||
|
/// The fix is to seek past the slate, so the seek arithmetic is worth pinning.
|
||||||
|
/// </summary>
|
||||||
|
public class ThumbnailSeekTests
|
||||||
|
{
|
||||||
|
private static PreviewBuildResult Build(double? pictureStart, int? frameCount) =>
|
||||||
|
new() { PictureStartSeconds = pictureStart, FrameCount = frameCount };
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void SeeksAQuarterIntoPictureNotIntoTheFile()
|
||||||
|
{
|
||||||
|
// 5s slate, then 96 frames (4s) of picture at 24fps → 5 + 1 = 6s.
|
||||||
|
var seek = PreviewStage.ThumbnailSeekSeconds(Build(5.0, 96), 24);
|
||||||
|
Assert.NotNull(seek);
|
||||||
|
Assert.Equal(6.0, seek!.Value, 3);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void HandlesATemplateWithNoSlateAtAll()
|
||||||
|
{
|
||||||
|
var seek = PreviewStage.ThumbnailSeekSeconds(Build(0.0, 240), 24);
|
||||||
|
Assert.Equal(2.5, seek!.Value, 3);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void FallsBackWhenTheBuildDidNotReportWherePictureStarts()
|
||||||
|
{
|
||||||
|
// Older worker, or a template with no SHOT layer: null means "keep the
|
||||||
|
// old whole-file behaviour" rather than guessing an offset.
|
||||||
|
Assert.Null(PreviewStage.ThumbnailSeekSeconds(Build(null, 96), 24));
|
||||||
|
Assert.Null(PreviewStage.ThumbnailSeekSeconds(null, 24));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData(-1.0, 96, 24)] // negative slate length
|
||||||
|
[InlineData(5.0, 0, 24)] // no picture frames
|
||||||
|
[InlineData(5.0, -5, 24)] // nonsense frame count
|
||||||
|
[InlineData(5.0, 96, 0)] // no fps to divide by
|
||||||
|
public void RefusesNumbersThatDoNotDescribeARealClip(double start, int frames, double fps)
|
||||||
|
{
|
||||||
|
Assert.Null(PreviewStage.ThumbnailSeekSeconds(Build(start, frames), fps));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -109,6 +109,74 @@ public class ValidationStageTests : IDisposable
|
|||||||
Assert.Contains("8-frame handle", tc.Message);
|
Assert.Contains("8-frame handle", tc.Message);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>Writes a one-frame plate into a footage-style element folder.</summary>
|
||||||
|
private string WritePlate(string element, string timecode, int fps = 24)
|
||||||
|
{
|
||||||
|
var plate = Path.Combine(_dir, "footage", $"UNG_107_051_010_{element}_TT_v001", $"UNG_107_051_010_{element}_TT_v001.01001.exr");
|
||||||
|
Directory.CreateDirectory(Path.GetDirectoryName(plate)!);
|
||||||
|
File.Move(ExrFixture.Write(timecode, 3840, 2160, new[] { ("B", 1), ("G", 1), ("R", 1) }, fps, 4), plate);
|
||||||
|
return plate;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static ManifestSource Source(string timingPlate, params string[] plates) => new()
|
||||||
|
{
|
||||||
|
TimingPlate = new PlateRef { Path = timingPlate, FrameStart = 1001 },
|
||||||
|
Plates = plates.Select(p => new PlateRef { Path = p, FrameStart = 1001 }).ToList(),
|
||||||
|
HandleFrames = 8,
|
||||||
|
};
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void AnotherDeliveredPlatePassesWhenTheTimingPlateDoesNot()
|
||||||
|
{
|
||||||
|
// The comp was anchored to FG01, but the panel named BG01 (longest) as
|
||||||
|
// the timing plate — the two carry unrelated camera timecodes.
|
||||||
|
WriteSequence(105, "09:12:00:00");
|
||||||
|
var bg = WritePlate("BG01", "14:26:31:08");
|
||||||
|
var fg = WritePlate("FG01", "09:12:00:00");
|
||||||
|
|
||||||
|
var manifest = Manifest(_dir, null, 1001);
|
||||||
|
manifest.Source = Source(bg, bg, fg);
|
||||||
|
|
||||||
|
var tc = Check(NewStage().Run(manifest, _dir, new ServerConfig()), "timecode_plate_match");
|
||||||
|
Assert.Equal("PASS", tc.Status);
|
||||||
|
Assert.Contains("UNG_107_051_010_FG01_TT_v001.01001.exr", tc.Message);
|
||||||
|
Assert.Contains("BG01", tc.Message);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void NoMatchingPlateStillFailsAgainstTheTimingPlate()
|
||||||
|
{
|
||||||
|
WriteSequence(105, "14:26:31:16");
|
||||||
|
var bg = WritePlate("BG01", "14:26:31:08");
|
||||||
|
var fg = WritePlate("FG01", "09:12:00:00");
|
||||||
|
|
||||||
|
var manifest = Manifest(_dir, null, 1001);
|
||||||
|
manifest.Source = Source(bg, bg, fg);
|
||||||
|
|
||||||
|
var tc = Check(NewStage().Run(manifest, _dir, new ServerConfig()), "timecode_plate_match");
|
||||||
|
Assert.Equal("FAIL", tc.Status);
|
||||||
|
Assert.Equal("14:26:31:08", tc.Expected);
|
||||||
|
Assert.Contains("8-frame handle", tc.Message);
|
||||||
|
Assert.Contains("1 other delivered plate", tc.Message);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void APreRenderIsNeverUsedAsTheFallbackPlate()
|
||||||
|
{
|
||||||
|
// plates[] is every file in the comp. A pre-render was rendered from
|
||||||
|
// this comp, so it agrees with the render whether or not either is right.
|
||||||
|
WriteSequence(105, "14:26:31:16");
|
||||||
|
var bg = WritePlate("BG01", "14:26:31:08");
|
||||||
|
var preRender = Path.Combine(_dir, "renders", "prerender", "UNG_107_051_010_PRERENDER_01001.exr");
|
||||||
|
Directory.CreateDirectory(Path.GetDirectoryName(preRender)!);
|
||||||
|
File.Move(ExrFixture.Write("14:26:31:16", 3840, 2160, new[] { ("B", 1), ("G", 1), ("R", 1) }, 24, 4), preRender);
|
||||||
|
|
||||||
|
var manifest = Manifest(_dir, null, 1001);
|
||||||
|
manifest.Source = Source(bg, bg, preRender);
|
||||||
|
|
||||||
|
Assert.Equal("FAIL", Check(NewStage().Run(manifest, _dir, new ServerConfig()), "timecode_plate_match").Status);
|
||||||
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public void APlateAtADifferentRateFailsPlateFps()
|
public void APlateAtADifferentRateFailsPlateFps()
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -234,26 +234,30 @@ public sealed class AerenderRunner
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// §7.3: outputDir is created before launch; a pre-existing non-empty dir
|
/// §7.3: outputDir is created before launch; a pre-existing dir can hold
|
||||||
/// can only hold output from a previous crashed attempt of this same
|
/// frames from a previous crashed attempt, which aerender would otherwise
|
||||||
/// immutable version. Safety guard: only files matching the job's own
|
/// leave interleaved with this attempt's. Safety guard: only files matching
|
||||||
/// output pattern prefix are ever deleted.
|
/// 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>
|
||||||
/// <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)
|
internal static void PrepareOutputDir(string outputDirLocal, string outputPattern)
|
||||||
{
|
{
|
||||||
Directory.CreateDirectory(outputDirLocal);
|
Directory.CreateDirectory(outputDirLocal);
|
||||||
var prefix = OutputPatternPrefix(outputPattern);
|
var pattern = SequencePattern.FromOutputPattern(outputPattern);
|
||||||
if (string.IsNullOrEmpty(prefix)) return;
|
if (string.IsNullOrEmpty(pattern.Prefix)) return;
|
||||||
foreach (var file in Directory.EnumerateFiles(outputDirLocal))
|
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 */ }
|
try { File.Delete(file); } catch { /* locked leftovers surface as an aerender error */ }
|
||||||
}
|
}
|
||||||
@@ -276,11 +280,19 @@ public sealed class AerenderRunner
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>Ring buffer of the last N output lines (§5.3 logTail).</summary>
|
/// <summary>
|
||||||
|
/// Ring buffer of the last N output lines (§5.3 logTail).
|
||||||
|
///
|
||||||
|
/// Thread-safe: output readers add lines while the progress loop reads the
|
||||||
|
/// tail for its report. Unsynchronised, ToString enumerates the queue while a
|
||||||
|
/// reader enqueues and throws "Collection was modified" — Blender, which
|
||||||
|
/// writes a status line many times a second, hit this on every job.
|
||||||
|
/// </summary>
|
||||||
public sealed class LogTail
|
public sealed class LogTail
|
||||||
{
|
{
|
||||||
private readonly Queue<string> _lines;
|
private readonly Queue<string> _lines;
|
||||||
private readonly int _capacity;
|
private readonly int _capacity;
|
||||||
|
private readonly object _gate = new();
|
||||||
|
|
||||||
public LogTail(int capacity)
|
public LogTail(int capacity)
|
||||||
{
|
{
|
||||||
@@ -290,9 +302,15 @@ public sealed class LogTail
|
|||||||
|
|
||||||
public void Add(string line)
|
public void Add(string line)
|
||||||
{
|
{
|
||||||
_lines.Enqueue(line);
|
lock (_gate)
|
||||||
while (_lines.Count > _capacity) _lines.Dequeue();
|
{
|
||||||
|
_lines.Enqueue(line);
|
||||||
|
while (_lines.Count > _capacity) _lines.Dequeue();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public override string ToString() => string.Join('\n', _lines);
|
public override string ToString()
|
||||||
|
{
|
||||||
|
lock (_gate) return string.Join('\n', _lines);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -13,10 +13,16 @@ namespace VFXReviewWorker;
|
|||||||
public sealed class ApiClient
|
public sealed class ApiClient
|
||||||
{
|
{
|
||||||
private readonly HttpClient _http;
|
private readonly HttpClient _http;
|
||||||
|
private readonly WorkerOptions _options;
|
||||||
private readonly ILogger<ApiClient> _log;
|
private readonly ILogger<ApiClient> _log;
|
||||||
|
|
||||||
|
// Presigned uploads: a separate client so the URL is not sent with our
|
||||||
|
// Authorization header, and a generous per-request timeout for media.
|
||||||
|
private static readonly HttpClient _upload = new() { Timeout = TimeSpan.FromMinutes(30) };
|
||||||
|
|
||||||
public ApiClient(WorkerOptions options, ILogger<ApiClient> log)
|
public ApiClient(WorkerOptions options, ILogger<ApiClient> log)
|
||||||
{
|
{
|
||||||
|
_options = options;
|
||||||
_log = log;
|
_log = log;
|
||||||
_http = new HttpClient
|
_http = new HttpClient
|
||||||
{
|
{
|
||||||
@@ -124,6 +130,7 @@ public sealed class ApiClient
|
|||||||
"validation" => $"api/ext/render/jobs/{jobId}/validation",
|
"validation" => $"api/ext/render/jobs/{jobId}/validation",
|
||||||
"delivery" => $"api/ext/render/jobs/{jobId}/delivery",
|
"delivery" => $"api/ext/render/jobs/{jobId}/delivery",
|
||||||
"finalize" => $"api/ext/render/jobs/{jobId}/finalize",
|
"finalize" => $"api/ext/render/jobs/{jobId}/finalize",
|
||||||
|
"attach-highres" => $"api/ext/render/jobs/{jobId}/attach-highres",
|
||||||
_ => throw new ArgumentOutOfRangeException(nameof(kind), kind, "unknown lifecycle report kind"),
|
_ => throw new ArgumentOutOfRangeException(nameof(kind), kind, "unknown lifecycle report kind"),
|
||||||
};
|
};
|
||||||
var res = await _http.PostAsJsonAsync(path, payload, Json, ct);
|
var res = await _http.PostAsJsonAsync(path, payload, Json, ct);
|
||||||
@@ -143,8 +150,10 @@ public sealed class ApiClient
|
|||||||
}
|
}
|
||||||
|
|
||||||
// E20 + PUT upload. Returns the storage key, or null when the upload failed.
|
// E20 + PUT upload. Returns the storage key, or null when the upload failed.
|
||||||
|
// onProgress receives the bytes sent so far, for status lines in the app.
|
||||||
public async Task<string?> UploadArtifactAsync(
|
public async Task<string?> UploadArtifactAsync(
|
||||||
string jobId, string machineId, string kind, string filePath, string contentType, CancellationToken ct)
|
string jobId, string machineId, string kind, string filePath, string contentType, CancellationToken ct,
|
||||||
|
Action<long>? onProgress = null)
|
||||||
{
|
{
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
@@ -153,6 +162,13 @@ public sealed class ApiClient
|
|||||||
_log.LogWarning("Artifact {Kind} not found at {Path}", kind, filePath);
|
_log.LogWarning("Artifact {Kind} not found at {Path}", kind, filePath);
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
var size = new FileInfo(filePath).Length;
|
||||||
|
var sw = System.Diagnostics.Stopwatch.StartNew();
|
||||||
|
// Uploads can run for many minutes on a slow uplink; without these two
|
||||||
|
// lines the log goes silent and a busy worker looks hung.
|
||||||
|
if (kind != "log")
|
||||||
|
_log.LogInformation("Uploading {Kind} for job {JobId}: {File} ({MB:F1} MB)",
|
||||||
|
kind, jobId, Path.GetFileName(filePath), size / 1048576.0);
|
||||||
|
|
||||||
var presignRes = await _http.PostAsJsonAsync($"api/ext/render/jobs/{jobId}/artifact-presign", new
|
var presignRes = await _http.PostAsJsonAsync($"api/ext/render/jobs/{jobId}/artifact-presign", new
|
||||||
{
|
{
|
||||||
@@ -160,6 +176,8 @@ public sealed class ApiClient
|
|||||||
kind,
|
kind,
|
||||||
fileName = Path.GetFileName(filePath),
|
fileName = Path.GetFileName(filePath),
|
||||||
contentType,
|
contentType,
|
||||||
|
multipart = size >= MultipartThreshold,
|
||||||
|
size,
|
||||||
}, Json, ct);
|
}, Json, ct);
|
||||||
if (!presignRes.IsSuccessStatusCode)
|
if (!presignRes.IsSuccessStatusCode)
|
||||||
{
|
{
|
||||||
@@ -169,18 +187,27 @@ public sealed class ApiClient
|
|||||||
var presign = await presignRes.Content.ReadFromJsonAsync<PresignResponse>(Json, ct);
|
var presign = await presignRes.Content.ReadFromJsonAsync<PresignResponse>(Json, ct);
|
||||||
if (presign is null) return null;
|
if (presign is null) return null;
|
||||||
|
|
||||||
// Media files can be large — generous timeout, separate client so the
|
if (presign.UploadId is not null && presign.PartUrls is { Count: > 0 } && presign.PartSize > 0)
|
||||||
// presigned URL is not sent with our Authorization header.
|
|
||||||
using var upload = new HttpClient { Timeout = TimeSpan.FromMinutes(30) };
|
|
||||||
await using var stream = File.OpenRead(filePath);
|
|
||||||
var content = new StreamContent(stream);
|
|
||||||
content.Headers.ContentType = new MediaTypeHeaderValue(contentType);
|
|
||||||
var putRes = await upload.PutAsync(presign.PresignedUrl, content, ct);
|
|
||||||
if (!putRes.IsSuccessStatusCode)
|
|
||||||
{
|
{
|
||||||
_log.LogWarning("Upload of {Kind} failed: {Status}", kind, (int)putRes.StatusCode);
|
if (!await UploadMultipartAsync(jobId, machineId, kind, filePath, size, presign, onProgress, ct))
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
// Single PUT: small files, or a server that predates multipart.
|
||||||
|
await using var stream = File.OpenRead(filePath);
|
||||||
|
var content = new ProgressStreamContent(stream, onProgress);
|
||||||
|
content.Headers.ContentType = new MediaTypeHeaderValue(contentType);
|
||||||
|
var putRes = await _upload.PutAsync(presign.PresignedUrl, content, ct);
|
||||||
|
if (!putRes.IsSuccessStatusCode)
|
||||||
|
{
|
||||||
|
_log.LogWarning("Upload of {Kind} failed after {Sec:F0}s: {Status}", kind, sw.Elapsed.TotalSeconds, (int)putRes.StatusCode);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (kind != "log")
|
||||||
|
_log.LogInformation("Uploaded {Kind} for job {JobId} in {Sec:F0}s ({Speed:F1} MB/s)",
|
||||||
|
kind, jobId, sw.Elapsed.TotalSeconds, size / 1048576.0 / Math.Max(0.001, sw.Elapsed.TotalSeconds));
|
||||||
return presign.Key;
|
return presign.Key;
|
||||||
}
|
}
|
||||||
catch (Exception ex)
|
catch (Exception ex)
|
||||||
@@ -190,6 +217,117 @@ public sealed class ApiClient
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Files at least this big go up as parallel multipart parts (E20b).
|
||||||
|
private const long MultipartThreshold = 16L * 1024 * 1024;
|
||||||
|
private const int PartAttempts = 4;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Uploads the parts concurrently (UploadConcurrency connections), each
|
||||||
|
/// retried on its own so a dropped connection costs one part, not the
|
||||||
|
/// file; then asks the server to stitch them. Aborts on failure so the
|
||||||
|
/// stored parts don't linger in the bucket.
|
||||||
|
/// </summary>
|
||||||
|
private async Task<bool> UploadMultipartAsync(string jobId, string machineId, string kind, string filePath,
|
||||||
|
long size, PresignResponse presign, Action<long>? onProgress, CancellationToken ct)
|
||||||
|
{
|
||||||
|
var partUrls = presign.PartUrls!;
|
||||||
|
var partSize = presign.PartSize;
|
||||||
|
var etags = new string?[partUrls.Count];
|
||||||
|
var sentPerPart = new long[partUrls.Count];
|
||||||
|
long sentTotal = 0;
|
||||||
|
var next = -1;
|
||||||
|
|
||||||
|
using var handle = File.OpenHandle(filePath, FileMode.Open, FileAccess.Read, FileShare.Read, FileOptions.Asynchronous);
|
||||||
|
using var failed = CancellationTokenSource.CreateLinkedTokenSource(ct);
|
||||||
|
|
||||||
|
async Task Worker()
|
||||||
|
{
|
||||||
|
int i;
|
||||||
|
while ((i = Interlocked.Increment(ref next)) < partUrls.Count && !failed.IsCancellationRequested)
|
||||||
|
{
|
||||||
|
var offset = i * partSize;
|
||||||
|
var len = (int)Math.Min(partSize, size - offset);
|
||||||
|
var buffer = new byte[len];
|
||||||
|
var read = 0;
|
||||||
|
while (read < len) read += await RandomAccess.ReadAsync(handle, buffer.AsMemory(read), offset + read, failed.Token);
|
||||||
|
|
||||||
|
for (var attempt = 1; ; attempt++)
|
||||||
|
{
|
||||||
|
var part = i;
|
||||||
|
// Progress restarts from zero for a retried part.
|
||||||
|
Interlocked.Add(ref sentTotal, -Interlocked.Exchange(ref sentPerPart[part], 0));
|
||||||
|
var content = new ProgressStreamContent(new MemoryStream(buffer, writable: false), sent =>
|
||||||
|
{
|
||||||
|
var delta = sent - Interlocked.Exchange(ref sentPerPart[part], sent);
|
||||||
|
onProgress?.Invoke(Interlocked.Add(ref sentTotal, delta));
|
||||||
|
});
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var res = await _upload.PutAsync(partUrls[i], content, failed.Token);
|
||||||
|
var etag = res.Headers.ETag?.Tag
|
||||||
|
?? (res.Headers.TryGetValues("ETag", out var v) ? v.FirstOrDefault() : null);
|
||||||
|
if (res.IsSuccessStatusCode && etag is not null)
|
||||||
|
{
|
||||||
|
etags[i] = etag;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
_log.LogWarning("Part {Part}/{Count} of {Kind} for job {JobId} failed: {Status} (attempt {N}/{Max})",
|
||||||
|
i + 1, partUrls.Count, kind, jobId, (int)res.StatusCode, attempt, PartAttempts);
|
||||||
|
}
|
||||||
|
catch (Exception ex) when (!failed.IsCancellationRequested)
|
||||||
|
{
|
||||||
|
_log.LogWarning("Part {Part}/{Count} of {Kind} for job {JobId} failed: {Error} (attempt {N}/{Max})",
|
||||||
|
i + 1, partUrls.Count, kind, jobId, ex.Message, attempt, PartAttempts);
|
||||||
|
}
|
||||||
|
if (attempt >= PartAttempts)
|
||||||
|
{
|
||||||
|
failed.Cancel(); // no point finishing the other parts
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
await Task.Delay(TimeSpan.FromSeconds(5 * attempt), failed.Token);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var concurrency = Math.Clamp(_options.UploadConcurrency, 1, 64);
|
||||||
|
try
|
||||||
|
{
|
||||||
|
await Task.WhenAll(Enumerable.Range(0, Math.Min(concurrency, partUrls.Count)).Select(_ => Task.Run(Worker)));
|
||||||
|
}
|
||||||
|
catch (OperationCanceledException)
|
||||||
|
{
|
||||||
|
// a part gave up, or shutdown — either way the upload is aborted below
|
||||||
|
}
|
||||||
|
|
||||||
|
var complete = !failed.IsCancellationRequested && etags.All(e => e is not null);
|
||||||
|
if (complete)
|
||||||
|
{
|
||||||
|
var res = await _http.PostAsJsonAsync($"api/ext/render/jobs/{jobId}/artifact-complete", new
|
||||||
|
{
|
||||||
|
machineId,
|
||||||
|
key = presign.Key,
|
||||||
|
uploadId = presign.UploadId,
|
||||||
|
parts = etags.Select((etag, i) => new { partNumber = i + 1, etag }),
|
||||||
|
}, Json, ct);
|
||||||
|
if (res.IsSuccessStatusCode) return true;
|
||||||
|
_log.LogWarning("Completing multipart {Kind} for job {JobId} failed: {Status} {Body}",
|
||||||
|
kind, jobId, (int)res.StatusCode, await res.Content.ReadAsStringAsync(ct));
|
||||||
|
}
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
await _http.PostAsJsonAsync($"api/ext/render/jobs/{jobId}/artifact-complete", new
|
||||||
|
{
|
||||||
|
machineId,
|
||||||
|
key = presign.Key,
|
||||||
|
uploadId = presign.UploadId,
|
||||||
|
abort = true,
|
||||||
|
}, Json, CancellationToken.None);
|
||||||
|
}
|
||||||
|
catch { /* parts expire on their own */ }
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
public Task<string?> UploadLogAsync(string jobId, string machineId, string logFilePath, CancellationToken ct) =>
|
public Task<string?> UploadLogAsync(string jobId, string machineId, string logFilePath, CancellationToken ct) =>
|
||||||
UploadArtifactAsync(jobId, machineId, "log", logFilePath, "text/plain", ct);
|
UploadArtifactAsync(jobId, machineId, "log", logFilePath, "text/plain", ct);
|
||||||
|
|
||||||
|
|||||||
@@ -8,18 +8,36 @@ namespace VFXReviewWorker;
|
|||||||
/// with "Saved: '...'". The saved lines are the reliable signal — a frame can
|
/// with "Saved: '...'". The saved lines are the reliable signal — a frame can
|
||||||
/// be reported for a long time while it renders — so progress counts those and
|
/// be reported for a long time while it renders — so progress counts those and
|
||||||
/// falls back to Fra: for a first sign of life.
|
/// falls back to Fra: for a first sign of life.
|
||||||
|
///
|
||||||
|
/// Blender 5.x logs through CLOG, which prefixes every line with an elapsed
|
||||||
|
/// time and a category ("00:02.954 render | Saved: '...'") and
|
||||||
|
/// reports errors as "ERROR ..." rather than "Error: ...". The prefix is
|
||||||
|
/// stripped before matching, so both formats parse the same way.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public static partial class BlenderProgressParser
|
public static partial class BlenderProgressParser
|
||||||
{
|
{
|
||||||
[GeneratedRegex(@"^Fra:(\d+)", RegexOptions.Compiled)]
|
[GeneratedRegex(@"^(?:\d+:)?\d{2}:\d{2}\.\d{3}\s+\S+\s*\| ?", RegexOptions.Compiled)]
|
||||||
|
private static partial Regex LogPrefix();
|
||||||
|
|
||||||
|
[GeneratedRegex(@"^Fra:\s*(\d+)", RegexOptions.Compiled)]
|
||||||
private static partial Regex FrameLine();
|
private static partial Regex FrameLine();
|
||||||
|
|
||||||
[GeneratedRegex(@"^Saved:\s*'(.+)'", RegexOptions.Compiled)]
|
[GeneratedRegex(@"^Saved:\s*'(.+)'", RegexOptions.Compiled)]
|
||||||
private static partial Regex SavedLine();
|
private static partial Regex SavedLine();
|
||||||
|
|
||||||
[GeneratedRegex(@"^(Error|Warning): |^Error: ", RegexOptions.Compiled | RegexOptions.IgnoreCase)]
|
// Errors only. Warnings are not failures, and add-ons print them on every
|
||||||
|
// launch ("Warning: add-on missing 'bl_info'"), so counting them made an
|
||||||
|
// add-on's complaint the reported reason for a failed render.
|
||||||
|
[GeneratedRegex(@"(?i:^Error: )|^(ERROR|FATAL) ", RegexOptions.Compiled)]
|
||||||
private static partial Regex ErrorLine();
|
private static partial Regex ErrorLine();
|
||||||
|
|
||||||
|
/// <summary>The line without Blender 5.x's "elapsed category | " prefix.</summary>
|
||||||
|
private static string Message(string line)
|
||||||
|
{
|
||||||
|
var m = LogPrefix().Match(line);
|
||||||
|
return m.Success ? line[m.Length..] : line;
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Failures that will repeat identically on another machine — a missing
|
/// Failures that will repeat identically on another machine — a missing
|
||||||
/// file, an unknown scene, an unwritable output. Retrying these burns the
|
/// file, an unknown scene, an unwritable output. Retrying these burns the
|
||||||
@@ -35,7 +53,9 @@ public static partial class BlenderProgressParser
|
|||||||
"unknown scene",
|
"unknown scene",
|
||||||
"scene not found",
|
"scene not found",
|
||||||
"unable to create directory",
|
"unable to create directory",
|
||||||
|
"couldn't create directory",
|
||||||
"cannot write file",
|
"cannot write file",
|
||||||
|
"cannot save:",
|
||||||
"no camera",
|
"no camera",
|
||||||
"python script fail",
|
"python script fail",
|
||||||
"unknown argument",
|
"unknown argument",
|
||||||
@@ -44,18 +64,18 @@ public static partial class BlenderProgressParser
|
|||||||
/// <summary>The frame Blender is currently working on, or null.</summary>
|
/// <summary>The frame Blender is currently working on, or null.</summary>
|
||||||
public static int? ParseFrame(string line)
|
public static int? ParseFrame(string line)
|
||||||
{
|
{
|
||||||
var m = FrameLine().Match(line);
|
var m = FrameLine().Match(Message(line));
|
||||||
return m.Success && int.TryParse(m.Groups[1].Value, out var f) ? f : null;
|
return m.Success && int.TryParse(m.Groups[1].Value, out var f) ? f : null;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>The path of a frame Blender has just written, or null.</summary>
|
/// <summary>The path of a frame Blender has just written, or null.</summary>
|
||||||
public static string? ParseSaved(string line)
|
public static string? ParseSaved(string line)
|
||||||
{
|
{
|
||||||
var m = SavedLine().Match(line);
|
var m = SavedLine().Match(Message(line));
|
||||||
return m.Success ? m.Groups[1].Value : null;
|
return m.Success ? m.Groups[1].Value : null;
|
||||||
}
|
}
|
||||||
|
|
||||||
public static bool IsErrorLine(string line) => ErrorLine().IsMatch(line);
|
public static bool IsErrorLine(string line) => ErrorLine().IsMatch(Message(line));
|
||||||
|
|
||||||
public static bool IsNonRetryableError(string line)
|
public static bool IsNonRetryableError(string line)
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -190,75 +190,93 @@ public sealed class BlenderRunner
|
|||||||
PumpAsync(process.StandardError, line => HandleLine(line, isStderr: true)),
|
PumpAsync(process.StandardError, line => HandleLine(line, isStderr: true)),
|
||||||
};
|
};
|
||||||
|
|
||||||
while (!process.HasExited)
|
try
|
||||||
{
|
{
|
||||||
await Task.Delay(TimeSpan.FromSeconds(2), CancellationToken.None);
|
return await MonitorAsync();
|
||||||
|
}
|
||||||
|
catch
|
||||||
|
{
|
||||||
|
// Disposing a Process does not end it: without this, any exception
|
||||||
|
// in the monitor loop leaves Blender rendering on the node,
|
||||||
|
// unsupervised, while the job is retried alongside it.
|
||||||
|
KillTree(process);
|
||||||
|
throw;
|
||||||
|
}
|
||||||
|
|
||||||
if (cancelJob.IsCancellationRequested || shutdown.IsCancellationRequested)
|
async Task<RenderResult> MonitorAsync()
|
||||||
|
{
|
||||||
|
while (!process.HasExited)
|
||||||
{
|
{
|
||||||
_log.LogWarning("Cancellation requested — killing Blender tree for job {JobId}", jobId);
|
await Task.Delay(TimeSpan.FromSeconds(2), CancellationToken.None);
|
||||||
KillTree(process);
|
|
||||||
cancelledByServer = cancelJob.IsCancellationRequested;
|
if (cancelJob.IsCancellationRequested || shutdown.IsCancellationRequested)
|
||||||
break;
|
{
|
||||||
|
_log.LogWarning("Cancellation requested — killing Blender tree for job {JobId}", jobId);
|
||||||
|
KillTree(process);
|
||||||
|
cancelledByServer = cancelJob.IsCancellationRequested;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ((DateTimeOffset.UtcNow - lastProgressAt).TotalSeconds > config.StallTimeoutSeconds)
|
||||||
|
{
|
||||||
|
_log.LogError("Blender stalled ({Sec}s without output) — killing job {JobId}", config.StallTimeoutSeconds, jobId);
|
||||||
|
KillTree(process);
|
||||||
|
await WaitForExitSafe(process);
|
||||||
|
return new RenderResult(false, -2, Retryable: true,
|
||||||
|
$"Blender produced no output for {config.StallTimeoutSeconds}s (stall timeout)",
|
||||||
|
tail.ToString(), fullLogPath, sw.Elapsed.TotalSeconds);
|
||||||
|
}
|
||||||
|
|
||||||
|
if ((DateTimeOffset.UtcNow - lastReportAt).TotalSeconds >= 10)
|
||||||
|
{
|
||||||
|
lastReportAt = DateTimeOffset.UtcNow;
|
||||||
|
var progress = totalFrames > 0 ? Math.Min(1.0, (double)framesSaved / totalFrames) : 0;
|
||||||
|
var resp = await _api.ProgressAsync(jobId, machineId, progress, currentFrame, totalFrames,
|
||||||
|
eta.EstimateSeconds(totalFrames - framesSaved), tail.ToString(), shutdown);
|
||||||
|
if (resp?.CancelRequested == true)
|
||||||
|
{
|
||||||
|
_log.LogWarning("Server requested cancel for job {JobId}", jobId);
|
||||||
|
KillTree(process);
|
||||||
|
cancelledByServer = true;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if ((DateTimeOffset.UtcNow - lastProgressAt).TotalSeconds > config.StallTimeoutSeconds)
|
await WaitForExitSafe(process);
|
||||||
|
// Let the readers drain what is still buffered before judging the run —
|
||||||
|
// the last frame's "Saved:" often arrives after the process exits.
|
||||||
|
try { await Task.WhenAll(pumps).WaitAsync(TimeSpan.FromSeconds(10)); } catch { }
|
||||||
|
sw.Stop();
|
||||||
|
lock (logLock) { fullLog.Flush(); }
|
||||||
|
|
||||||
|
if (cancelledByServer)
|
||||||
{
|
{
|
||||||
_log.LogError("Blender stalled ({Sec}s without output) — killing job {JobId}", config.StallTimeoutSeconds, jobId);
|
return new RenderResult(false, -3, Retryable: false, "Cancelled", tail.ToString(), fullLogPath, sw.Elapsed.TotalSeconds);
|
||||||
KillTree(process);
|
}
|
||||||
await WaitForExitSafe(process);
|
|
||||||
return new RenderResult(false, -2, Retryable: true,
|
var exitCode = process.ExitCode;
|
||||||
$"Blender produced no output for {config.StallTimeoutSeconds}s (stall timeout)",
|
if (exitCode != 0)
|
||||||
|
{
|
||||||
|
return new RenderResult(false, exitCode, Retryable: !nonRetryable,
|
||||||
|
firstError ?? $"Blender exited with code {exitCode}",
|
||||||
tail.ToString(), fullLogPath, sw.Elapsed.TotalSeconds);
|
tail.ToString(), fullLogPath, sw.Elapsed.TotalSeconds);
|
||||||
}
|
}
|
||||||
|
|
||||||
if ((DateTimeOffset.UtcNow - lastReportAt).TotalSeconds >= 10)
|
// Blender exits 0 having rendered nothing if the range is empty or the
|
||||||
|
// output path is unwritable, so a silent success is treated as failure.
|
||||||
|
if (framesSaved == 0)
|
||||||
{
|
{
|
||||||
lastReportAt = DateTimeOffset.UtcNow;
|
return new RenderResult(false, 0, Retryable: false,
|
||||||
var progress = totalFrames > 0 ? Math.Min(1.0, (double)framesSaved / totalFrames) : 0;
|
firstError is not null
|
||||||
var resp = await _api.ProgressAsync(jobId, machineId, progress, currentFrame, totalFrames,
|
? $"Blender exited cleanly but saved no frames: {firstError}"
|
||||||
eta.EstimateSeconds(totalFrames - framesSaved), tail.ToString(), shutdown);
|
: "Blender exited cleanly but saved no frames — check the output path and frame range in the .blend",
|
||||||
if (resp?.CancelRequested == true)
|
tail.ToString(), fullLogPath, sw.Elapsed.TotalSeconds);
|
||||||
{
|
|
||||||
_log.LogWarning("Server requested cancel for job {JobId}", jobId);
|
|
||||||
KillTree(process);
|
|
||||||
cancelledByServer = true;
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
_log.LogInformation("Job {JobId}: {Saved}/{Total} frames in {Sec:F0}s", jobId, framesSaved, totalFrames, sw.Elapsed.TotalSeconds);
|
||||||
|
return new RenderResult(true, 0, true, null, tail.ToString(), fullLogPath, sw.Elapsed.TotalSeconds);
|
||||||
}
|
}
|
||||||
|
|
||||||
await WaitForExitSafe(process);
|
|
||||||
// Let the readers drain what is still buffered before judging the run —
|
|
||||||
// the last frame's "Saved:" often arrives after the process exits.
|
|
||||||
try { await Task.WhenAll(pumps).WaitAsync(TimeSpan.FromSeconds(10)); } catch { }
|
|
||||||
sw.Stop();
|
|
||||||
lock (logLock) { fullLog.Flush(); }
|
|
||||||
|
|
||||||
if (cancelledByServer)
|
|
||||||
{
|
|
||||||
return new RenderResult(false, -3, Retryable: false, "Cancelled", tail.ToString(), fullLogPath, sw.Elapsed.TotalSeconds);
|
|
||||||
}
|
|
||||||
|
|
||||||
var exitCode = process.ExitCode;
|
|
||||||
if (exitCode != 0)
|
|
||||||
{
|
|
||||||
return new RenderResult(false, exitCode, Retryable: !nonRetryable,
|
|
||||||
firstError ?? $"Blender exited with code {exitCode}",
|
|
||||||
tail.ToString(), fullLogPath, sw.Elapsed.TotalSeconds);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Blender exits 0 having rendered nothing if the range is empty or the
|
|
||||||
// output path is unwritable, so a silent success is treated as failure.
|
|
||||||
if (framesSaved == 0)
|
|
||||||
{
|
|
||||||
return new RenderResult(false, 0, Retryable: false,
|
|
||||||
"Blender exited cleanly but saved no frames — check the output path and frame range in the .blend",
|
|
||||||
tail.ToString(), fullLogPath, sw.Elapsed.TotalSeconds);
|
|
||||||
}
|
|
||||||
|
|
||||||
_log.LogInformation("Job {JobId}: {Saved}/{Total} frames in {Sec:F0}s", jobId, framesSaved, totalFrames, sw.Elapsed.TotalSeconds);
|
|
||||||
return new RenderResult(true, 0, true, null, tail.ToString(), fullLogPath, sw.Elapsed.TotalSeconds);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
|
|||||||
@@ -11,6 +11,10 @@ namespace VFXReviewWorker;
|
|||||||
/// hard-links (or copies) each shot's EXRs and delivery MOV into it, verifies
|
/// hard-links (or copies) each shot's EXRs and delivery MOV into it, verifies
|
||||||
/// what it wrote, and leaves a manifest + CSV report beside the shots.
|
/// what it wrote, and leaves a manifest + CSV report beside the shots.
|
||||||
///
|
///
|
||||||
|
/// A MOV_REVIEW package (§11.6) runs the same path for a different shape: one
|
||||||
|
/// flat folder, one preview MOV per shot, and nothing written into it but the
|
||||||
|
/// MOVs themselves — it is shared with a producer, not filed as a delivery.
|
||||||
|
///
|
||||||
/// Hard links make an 18-shot EXR package near-instant and cost no extra disk.
|
/// Hard links make an 18-shot EXR package near-instant and cost no extra disk.
|
||||||
/// They are safe here because rendered versions are immutable by pipeline
|
/// They are safe here because rendered versions are immutable by pipeline
|
||||||
/// design — a new version is a new directory, nothing ever rewrites an EXR in
|
/// design — a new version is a new directory, nothing ever rewrites an EXR in
|
||||||
@@ -38,9 +42,10 @@ public sealed class DeliveryStage
|
|||||||
var manifestFiles = new List<object>();
|
var manifestFiles = new List<object>();
|
||||||
var alwaysCopy = string.Equals(manifest.CopyMode, "always-copy", StringComparison.OrdinalIgnoreCase);
|
var alwaysCopy = string.Equals(manifest.CopyMode, "always-copy", StringComparison.OrdinalIgnoreCase);
|
||||||
var alwaysHash = string.Equals(manifest.VerifyMode, "always-hash", StringComparison.OrdinalIgnoreCase);
|
var alwaysHash = string.Equals(manifest.VerifyMode, "always-hash", StringComparison.OrdinalIgnoreCase);
|
||||||
|
var isReview = string.Equals(manifest.Kind, "MOV_REVIEW", StringComparison.OrdinalIgnoreCase);
|
||||||
|
|
||||||
_log.LogInformation("Building delivery package {Name} ({Count} shots) at {Dir}",
|
_log.LogInformation("Building {What} {Name} ({Count} shots) at {Dir}",
|
||||||
manifest.PackageName, manifest.Items.Count, packageDir);
|
isReview ? "MOV review" : "delivery package", manifest.PackageName, manifest.Items.Count, packageDir);
|
||||||
Directory.CreateDirectory(packageDir);
|
Directory.CreateDirectory(packageDir);
|
||||||
|
|
||||||
for (var i = 0; i < manifest.Items.Count; i++)
|
for (var i = 0; i < manifest.Items.Count; i++)
|
||||||
@@ -51,7 +56,9 @@ public sealed class DeliveryStage
|
|||||||
await _api.ProgressAsync(job.Id, machineId, (double)i / manifest.Items.Count, i, manifest.Items.Count, null,
|
await _api.ProgressAsync(job.Id, machineId, (double)i / manifest.Items.Count, i, manifest.Items.Count, null,
|
||||||
$"Packaging {item.ShotCode} {item.VersionString} ({i + 1}/{manifest.Items.Count})", shutdown);
|
$"Packaging {item.ShotCode} {item.VersionString} ({i + 1}/{manifest.Items.Count})", shutdown);
|
||||||
|
|
||||||
var result = BuildItem(item, mapper, alwaysCopy, alwaysHash, manifestFiles);
|
var result = isReview
|
||||||
|
? BuildReviewItem(item, mapper, alwaysCopy, alwaysHash, manifestFiles)
|
||||||
|
: BuildItem(item, mapper, alwaysCopy, alwaysHash, manifestFiles);
|
||||||
results.Add(result);
|
results.Add(result);
|
||||||
if (result.Status == "FAILED")
|
if (result.Status == "FAILED")
|
||||||
{
|
{
|
||||||
@@ -63,15 +70,22 @@ public sealed class DeliveryStage
|
|||||||
|
|
||||||
// The report is the client-facing document, so it is written even for a
|
// The report is the client-facing document, so it is written even for a
|
||||||
// partial build — it is the fastest way to see what did and did not land.
|
// partial build — it is the fastest way to see what did and did not land.
|
||||||
|
//
|
||||||
|
// A review folder gets neither: it is opened by a producer who wants the
|
||||||
|
// MOVs and nothing else. The manifest still travels back to the server,
|
||||||
|
// so the record of what was shared is kept without cluttering the share.
|
||||||
string? reportPath = null;
|
string? reportPath = null;
|
||||||
try
|
if (!isReview)
|
||||||
{
|
{
|
||||||
reportPath = WriteReport(manifest, results, mapper);
|
try
|
||||||
WriteManifestJson(manifest, results, manifestFiles, packageDir);
|
{
|
||||||
}
|
reportPath = WriteReport(manifest, results, mapper);
|
||||||
catch (Exception ex)
|
WriteManifestJson(manifest, results, manifestFiles, packageDir);
|
||||||
{
|
}
|
||||||
_log.LogWarning(ex, "Could not write delivery report/manifest for {Name}", manifest.PackageName);
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
_log.LogWarning(ex, "Could not write delivery report/manifest for {Name}", manifest.PackageName);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return new DeliveryResult(ok, results, packageDir, reportPath, manifestFiles);
|
return new DeliveryResult(ok, results, packageDir, reportPath, manifestFiles);
|
||||||
@@ -234,6 +248,108 @@ public sealed class DeliveryStage
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// One shot of a MOV review package: place its preview MOV straight into
|
||||||
|
/// the (flat) review folder under the client-facing name.
|
||||||
|
///
|
||||||
|
/// A missing MOV is fatal here, unlike in an EXR delivery where the MOV is
|
||||||
|
/// a viewing copy beside the real deliverable — in a review it *is* the
|
||||||
|
/// deliverable, and a review folder quietly one shot short is worse than
|
||||||
|
/// one that says so.
|
||||||
|
/// </summary>
|
||||||
|
private DeliveryItemResult BuildReviewItem(
|
||||||
|
DeliveryManifestItem item, PathMapper mapper, bool alwaysCopy, bool alwaysHash, List<object> manifestFiles)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
if (string.IsNullOrWhiteSpace(item.DeliveryMovPath))
|
||||||
|
{
|
||||||
|
return DeliveryItemResult.Failed(item, "No preview MOV is recorded for this version");
|
||||||
|
}
|
||||||
|
|
||||||
|
var movSrc = mapper.Map(item.DeliveryMovPath!);
|
||||||
|
if (!File.Exists(movSrc))
|
||||||
|
{
|
||||||
|
return DeliveryItemResult.Failed(item, $"Preview MOV not found: {movSrc}");
|
||||||
|
}
|
||||||
|
|
||||||
|
// ShotDir is the package folder itself for a review — the MOVs sit
|
||||||
|
// beside each other so a producer can scrub through them in order.
|
||||||
|
var reviewDir = mapper.Map(item.ShotDir);
|
||||||
|
Directory.CreateDirectory(reviewDir);
|
||||||
|
|
||||||
|
var name = string.IsNullOrWhiteSpace(item.DeliveredBaseName)
|
||||||
|
? Path.GetFileName(movSrc)
|
||||||
|
: item.DeliveredBaseName + Path.GetExtension(movSrc);
|
||||||
|
var dest = Path.Combine(reviewDir, name);
|
||||||
|
|
||||||
|
if (Place(movSrc, dest, alwaysCopy, out var copied) is string error)
|
||||||
|
{
|
||||||
|
return DeliveryItemResult.Failed(item, error);
|
||||||
|
}
|
||||||
|
|
||||||
|
var sourceLength = new FileInfo(movSrc).Length;
|
||||||
|
var destLength = new FileInfo(dest).Length;
|
||||||
|
|
||||||
|
// There is no validation-time digest for a MOV to check against, so
|
||||||
|
// a copy is proved against the source it came from: length always
|
||||||
|
// (it catches the truncation a full disk causes, for free), and the
|
||||||
|
// full hash when the config asks for it. A hard link is the source.
|
||||||
|
string? digest = null;
|
||||||
|
if (copied)
|
||||||
|
{
|
||||||
|
if (destLength != sourceLength)
|
||||||
|
{
|
||||||
|
return DeliveryItemResult.Failed(item,
|
||||||
|
$"Copied MOV is {destLength} bytes but the source is {sourceLength} — the copy is incomplete");
|
||||||
|
}
|
||||||
|
if (alwaysHash)
|
||||||
|
{
|
||||||
|
digest = XxHash64.HashFile(dest);
|
||||||
|
var sourceDigest = XxHash64.HashFile(movSrc);
|
||||||
|
if (!string.Equals(digest, sourceDigest, StringComparison.OrdinalIgnoreCase))
|
||||||
|
{
|
||||||
|
return DeliveryItemResult.Failed(item,
|
||||||
|
$"Copied MOV does not match its source: expected {sourceDigest}, got {digest}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else if (alwaysHash)
|
||||||
|
{
|
||||||
|
digest = XxHash64.HashFile(dest);
|
||||||
|
}
|
||||||
|
|
||||||
|
manifestFiles.Add(new
|
||||||
|
{
|
||||||
|
shotCode = item.ShotCode,
|
||||||
|
relativePath = name,
|
||||||
|
bytes = destLength,
|
||||||
|
exportId = item.ExportId,
|
||||||
|
});
|
||||||
|
|
||||||
|
return new DeliveryItemResult
|
||||||
|
{
|
||||||
|
ItemId = item.ItemId,
|
||||||
|
ShotCode = item.ShotCode,
|
||||||
|
VersionString = item.VersionString,
|
||||||
|
Status = "VERIFIED",
|
||||||
|
// No EXR sequence is involved, so there is no shot folder to record.
|
||||||
|
ExrPath = null,
|
||||||
|
MovPath = dest,
|
||||||
|
FileCount = 1,
|
||||||
|
TotalBytes = destLength,
|
||||||
|
Checksum = digest,
|
||||||
|
LinkMode = copied ? "copy" : "hardlink",
|
||||||
|
FrameStart = item.FrameStart,
|
||||||
|
FrameEnd = item.FrameEnd,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
return DeliveryItemResult.Failed(item, $"{ex.GetType().Name}: {ex.Message}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Hard-link when possible, copy when not. Returns null on success or the
|
/// Hard-link when possible, copy when not. Returns null on success or the
|
||||||
/// error message. `copied` reports which happened, so the package records
|
/// error message. `copied` reports which happened, so the package records
|
||||||
|
|||||||
@@ -100,6 +100,12 @@ public sealed class BlenderManifest
|
|||||||
public sealed class DeliveryManifest
|
public sealed class DeliveryManifest
|
||||||
{
|
{
|
||||||
public string Stage { get; set; } = "DELIVERY";
|
public string Stage { get; set; } = "DELIVERY";
|
||||||
|
/// <summary>
|
||||||
|
/// "EXR_DELIVERY" builds the per-shot folders of EXRs + MOVs; "MOV_REVIEW"
|
||||||
|
/// builds a flat folder of preview MOVs for a formal review (§11.6). One
|
||||||
|
/// job type and one claim path either way — only what lands on disk differs.
|
||||||
|
/// </summary>
|
||||||
|
public string Kind { get; set; } = "EXR_DELIVERY";
|
||||||
public string PackageId { get; set; } = "";
|
public string PackageId { get; set; } = "";
|
||||||
public string PackageName { get; set; } = "";
|
public string PackageName { get; set; } = "";
|
||||||
public int PackageNumber { get; set; }
|
public int PackageNumber { get; set; }
|
||||||
@@ -138,6 +144,13 @@ public sealed class DeliveryManifestItem
|
|||||||
public string DeliveredBaseName { get; set; } = "";
|
public string DeliveredBaseName { get; set; } = "";
|
||||||
/// <summary>When this export's validation ran — lets a linked package detect a source changed since QC.</summary>
|
/// <summary>When this export's validation ran — lets a linked package detect a source changed since QC.</summary>
|
||||||
public DateTimeOffset? ValidatedAt { get; set; }
|
public DateTimeOffset? ValidatedAt { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// True on a MOV_REVIEW item: there is no EXR sequence, so SourceDir,
|
||||||
|
/// OutputPattern, FileCount and Checksum are empty and DeliveryMovPath is
|
||||||
|
/// the whole deliverable.
|
||||||
|
/// </summary>
|
||||||
|
public bool IsMovOnly => string.IsNullOrWhiteSpace(SourceDir);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>PREVIEW_ONLY manifest (server-built, RenderPipeline2 §9).</summary>
|
/// <summary>PREVIEW_ONLY manifest (server-built, RenderPipeline2 §9).</summary>
|
||||||
@@ -162,6 +175,11 @@ public sealed class PreviewManifest
|
|||||||
public string Mp4Output { get; set; } = "";
|
public string Mp4Output { get; set; } = "";
|
||||||
public string? SlateScopeProp { get; set; }
|
public string? SlateScopeProp { get; set; }
|
||||||
public string? SlateSubmissionProp { get; set; }
|
public string? SlateSubmissionProp { get; set; }
|
||||||
|
/// <summary>
|
||||||
|
/// Also encode the High quality MP4 from the MOV and upload the MOV itself
|
||||||
|
/// as the version's High Res file (server "preview.highQuality").
|
||||||
|
/// </summary>
|
||||||
|
public bool HighQuality { get; set; }
|
||||||
public SlateInfo Slate { get; set; } = new();
|
public SlateInfo Slate { get; set; } = new();
|
||||||
|
|
||||||
public int TotalFrames => FrameEnd - FrameStart + 1;
|
public int TotalFrames => FrameEnd - FrameStart + 1;
|
||||||
@@ -193,6 +211,12 @@ public sealed class PreviewBuildResult
|
|||||||
public int? FrameCount { get; set; }
|
public int? FrameCount { get; set; }
|
||||||
public int? Width { get; set; }
|
public int? Width { get; set; }
|
||||||
public int? Height { get; set; }
|
public int? Height { get; set; }
|
||||||
|
/// <summary>
|
||||||
|
/// Seconds of slate ahead of picture in the preview comp (the SHOT layer's
|
||||||
|
/// in-point). Null on builds predating this field, or when the template has
|
||||||
|
/// no SHOT layer — the thumbnail then falls back to scanning from frame 0.
|
||||||
|
/// </summary>
|
||||||
|
public double? PictureStartSeconds { get; set; }
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>The Render Manifest (§6.2) — the fields the render and validation stages need; the rest is preserved raw.</summary>
|
/// <summary>The Render Manifest (§6.2) — the fields the render and validation stages need; the rest is preserved raw.</summary>
|
||||||
@@ -280,6 +304,11 @@ public sealed class PresignResponse
|
|||||||
public string PresignedUrl { get; set; } = "";
|
public string PresignedUrl { get; set; } = "";
|
||||||
public string Key { get; set; } = "";
|
public string Key { get; set; } = "";
|
||||||
public string Url { get; set; } = "";
|
public string Url { get; set; } = "";
|
||||||
|
// Multipart (server ≥ 1.7.2 contract) — absent from older servers, which
|
||||||
|
// only ever return PresignedUrl.
|
||||||
|
public string? UploadId { get; set; }
|
||||||
|
public long PartSize { get; set; }
|
||||||
|
public List<string>? PartUrls { get; set; }
|
||||||
}
|
}
|
||||||
|
|
||||||
public sealed class ExportDetailResponse
|
public sealed class ExportDetailResponse
|
||||||
|
|||||||
@@ -0,0 +1,143 @@
|
|||||||
|
using System.Text.Json;
|
||||||
|
using Microsoft.Extensions.Logging;
|
||||||
|
|
||||||
|
namespace VFXReviewWorker;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Uploads each preview's ProRes MOV (the version's High Res download) in the
|
||||||
|
/// background, after the job has already been finalized.
|
||||||
|
///
|
||||||
|
/// The MOV is by far the largest upload — hundreds of MB — and on a slow or
|
||||||
|
/// flaky uplink it held every preview job open for 10+ minutes, during which
|
||||||
|
/// the job looked stuck in the app and a worker restart threw the whole
|
||||||
|
/// preview away. Now the job completes as soon as the review MP4s are up, the
|
||||||
|
/// worker moves on to the next job, and the MOV follows; an "attach-highres"
|
||||||
|
/// report (through the ordered spooler, so always after its finalize) attaches
|
||||||
|
/// it to the version.
|
||||||
|
///
|
||||||
|
/// Pending uploads are files in highres-queue/, so a restart resumes them. The
|
||||||
|
/// MOV itself lives on the SAN beside the EXRs, never in scratch.
|
||||||
|
/// </summary>
|
||||||
|
public sealed class HighResUploader
|
||||||
|
{
|
||||||
|
private const int MaxAttempts = 5;
|
||||||
|
|
||||||
|
private readonly ApiClient _api;
|
||||||
|
private readonly ReportSpooler _spooler;
|
||||||
|
private readonly ILogger<HighResUploader> _log;
|
||||||
|
private readonly string _dir;
|
||||||
|
private readonly SemaphoreSlim _wake = new(0);
|
||||||
|
|
||||||
|
public HighResUploader(ApiClient api, ReportSpooler spooler, ILogger<HighResUploader> log)
|
||||||
|
{
|
||||||
|
_api = api;
|
||||||
|
_spooler = spooler;
|
||||||
|
_log = log;
|
||||||
|
_dir = Path.Combine(WorkerOptions.DataDir, "highres-queue");
|
||||||
|
Directory.CreateDirectory(_dir);
|
||||||
|
}
|
||||||
|
|
||||||
|
private sealed class Pending
|
||||||
|
{
|
||||||
|
public string JobId { get; set; } = "";
|
||||||
|
public string MachineId { get; set; } = "";
|
||||||
|
public string MovPath { get; set; } = "";
|
||||||
|
public int Attempts { get; set; }
|
||||||
|
}
|
||||||
|
|
||||||
|
public void Enqueue(string jobId, string machineId, string movPath)
|
||||||
|
{
|
||||||
|
var item = new Pending { JobId = jobId, MachineId = machineId, MovPath = movPath };
|
||||||
|
var name = $"{DateTimeOffset.UtcNow.UtcTicks:D20}_{jobId}.json";
|
||||||
|
var tmp = Path.Combine(_dir, name + ".tmp");
|
||||||
|
File.WriteAllText(tmp, JsonSerializer.Serialize(item, WorkerOptions.JsonOpts));
|
||||||
|
File.Move(tmp, Path.Combine(_dir, name));
|
||||||
|
_log.LogInformation("ProRes for job {JobId} queued for background upload ({MB:F0} MB)",
|
||||||
|
jobId, File.Exists(movPath) ? new FileInfo(movPath).Length / 1048576.0 : 0);
|
||||||
|
_wake.Release();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Long-running loop; started once by the worker service.</summary>
|
||||||
|
public async Task RunAsync(CancellationToken ct)
|
||||||
|
{
|
||||||
|
var backoff = TimeSpan.FromSeconds(30);
|
||||||
|
while (!ct.IsCancellationRequested)
|
||||||
|
{
|
||||||
|
var next = Directory.EnumerateFiles(_dir, "*.json").OrderBy(f => f, StringComparer.Ordinal).FirstOrDefault();
|
||||||
|
if (next is null)
|
||||||
|
{
|
||||||
|
try { await _wake.WaitAsync(TimeSpan.FromSeconds(30), ct); } catch (OperationCanceledException) { break; }
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
Pending? item;
|
||||||
|
try { item = JsonSerializer.Deserialize<Pending>(File.ReadAllText(next), WorkerOptions.JsonOpts); }
|
||||||
|
catch { item = null; }
|
||||||
|
if (item is null || string.IsNullOrEmpty(item.JobId))
|
||||||
|
{
|
||||||
|
_log.LogWarning("Discarding unreadable ProRes queue file {File}", next);
|
||||||
|
TryDelete(next);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!File.Exists(item.MovPath))
|
||||||
|
{
|
||||||
|
_log.LogWarning("ProRes for job {JobId} is gone ({Path}) — not uploading", item.JobId, item.MovPath);
|
||||||
|
Report(item, null, $"MOV not found at {item.MovPath}");
|
||||||
|
TryDelete(next);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
string? key;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
key = await _api.UploadArtifactAsync(item.JobId, item.MachineId, "highres", item.MovPath, "video/quicktime", ct);
|
||||||
|
}
|
||||||
|
catch (OperationCanceledException) when (ct.IsCancellationRequested)
|
||||||
|
{
|
||||||
|
_log.LogInformation("Worker stopping — ProRes upload for job {JobId} resumes on next start", item.JobId);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (key is not null)
|
||||||
|
{
|
||||||
|
Report(item, key, null);
|
||||||
|
TryDelete(next);
|
||||||
|
backoff = TimeSpan.FromSeconds(30);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
item.Attempts++;
|
||||||
|
if (item.Attempts >= MaxAttempts)
|
||||||
|
{
|
||||||
|
_log.LogWarning("ProRes upload for job {JobId} failed {N} times — giving up", item.JobId, item.Attempts);
|
||||||
|
Report(item, null, $"upload failed {item.Attempts} times (see the worker log)");
|
||||||
|
TryDelete(next);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
_log.LogWarning("ProRes upload for job {JobId} failed (attempt {N}/{Max}); retrying in {Sec}s",
|
||||||
|
item.JobId, item.Attempts, MaxAttempts, backoff.TotalSeconds);
|
||||||
|
try { File.WriteAllText(next, JsonSerializer.Serialize(item, WorkerOptions.JsonOpts)); } catch { /* retried anyway */ }
|
||||||
|
try { await Task.Delay(backoff, ct); } catch (OperationCanceledException) { break; }
|
||||||
|
backoff = TimeSpan.FromSeconds(Math.Min(backoff.TotalSeconds * 2, 600));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void Report(Pending item, string? key, string? error)
|
||||||
|
{
|
||||||
|
_spooler.Enqueue("attach-highres", item.JobId, new Dictionary<string, object?>
|
||||||
|
{
|
||||||
|
["machineId"] = item.MachineId,
|
||||||
|
["highResKey"] = key,
|
||||||
|
["highResFileName"] = key is null ? null : Path.GetFileName(item.MovPath),
|
||||||
|
["highResSize"] = key is null ? null : new FileInfo(item.MovPath).Length,
|
||||||
|
["error"] = error,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void TryDelete(string path)
|
||||||
|
{
|
||||||
|
try { File.Delete(path); } catch { /* next pass */ }
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -18,11 +18,14 @@ public sealed class JobExecutor
|
|||||||
private readonly DeliveryStage _delivery;
|
private readonly DeliveryStage _delivery;
|
||||||
private readonly BlenderRunner _blender;
|
private readonly BlenderRunner _blender;
|
||||||
private readonly ReportSpooler _spooler;
|
private readonly ReportSpooler _spooler;
|
||||||
|
private readonly HighResUploader _highRes;
|
||||||
private readonly ILogger<JobExecutor> _log;
|
private readonly ILogger<JobExecutor> _log;
|
||||||
|
|
||||||
public JobExecutor(WorkerOptions options, ApiClient api, AerenderRunner runner, PreviewStage preview,
|
public JobExecutor(WorkerOptions options, ApiClient api, AerenderRunner runner, PreviewStage preview,
|
||||||
ValidationStage validation, DeliveryStage delivery, BlenderRunner blender, ReportSpooler spooler, ILogger<JobExecutor> log)
|
ValidationStage validation, DeliveryStage delivery, BlenderRunner blender, ReportSpooler spooler,
|
||||||
|
HighResUploader highRes, ILogger<JobExecutor> log)
|
||||||
{
|
{
|
||||||
|
_highRes = highRes;
|
||||||
_options = options;
|
_options = options;
|
||||||
_api = api;
|
_api = api;
|
||||||
_runner = runner;
|
_runner = runner;
|
||||||
@@ -76,12 +79,15 @@ public sealed class JobExecutor
|
|||||||
{
|
{
|
||||||
long totalBytes = 0;
|
long totalBytes = 0;
|
||||||
int fileCount = 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
|
try
|
||||||
{
|
{
|
||||||
foreach (var f in Directory.EnumerateFiles(outputDirLocal))
|
foreach (var f in Directory.EnumerateFiles(outputDirLocal))
|
||||||
{
|
{
|
||||||
if (!Path.GetFileName(f).StartsWith(prefix, StringComparison.OrdinalIgnoreCase)) continue;
|
if (!pattern.MatchesOutputFile(Path.GetFileName(f))) continue;
|
||||||
fileCount++;
|
fileCount++;
|
||||||
totalBytes += new FileInfo(f).Length;
|
totalBytes += new FileInfo(f).Length;
|
||||||
}
|
}
|
||||||
@@ -94,8 +100,8 @@ public sealed class JobExecutor
|
|||||||
// range, template mismatch, silently swallowed error).
|
// range, template mismatch, silently swallowed error).
|
||||||
// Until Phase 3 validation exists, an empty output dir must
|
// Until Phase 3 validation exists, an empty output dir must
|
||||||
// never become READY_FOR_QC.
|
// never become READY_FOR_QC.
|
||||||
_log.LogError("Job {JobId}: aerender exited 0 but no \"{Prefix}*\" files exist in {Dir} — reporting failure",
|
_log.LogError("Job {JobId}: aerender exited 0 but no \"{Prefix}*{Ext}\" files exist in {Dir} — reporting failure",
|
||||||
job.Id, prefix, outputDirLocal);
|
job.Id, pattern.Prefix, pattern.Extension, outputDirLocal);
|
||||||
_spooler.Enqueue("fail", job.Id, new Dictionary<string, object?>
|
_spooler.Enqueue("fail", job.Id, new Dictionary<string, object?>
|
||||||
{
|
{
|
||||||
["machineId"] = machineId,
|
["machineId"] = machineId,
|
||||||
@@ -415,8 +421,15 @@ public sealed class JobExecutor
|
|||||||
return; // temp AEP is deliberately kept for debugging
|
return; // temp AEP is deliberately kept for debugging
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// From here on aerender is done and the app would keep showing its
|
||||||
|
// last frame line; this reports what the worker is doing instead,
|
||||||
|
// and renews the lease through the encode and uploads.
|
||||||
|
await using var status = new LeaseKeepAlive(_api, job.Id, machineId, TimeSpan.FromSeconds(10), shutdown);
|
||||||
|
status.Line($"Preview rendered in {result.Seconds:F0}s — uploading review media");
|
||||||
|
|
||||||
var previewKey = await _api.UploadArtifactAsync(
|
var previewKey = await _api.UploadArtifactAsync(
|
||||||
job.Id, machineId, "preview", result.Mp4Path!, "video/mp4", shutdown);
|
job.Id, machineId, "preview", result.Mp4Path!, "video/mp4", shutdown,
|
||||||
|
status.Track("preview MP4", result.Mp4Path!));
|
||||||
if (previewKey is null)
|
if (previewKey is null)
|
||||||
{
|
{
|
||||||
// The renders are on the SAN and fine — only the upload failed,
|
// The renders are on the SAN and fine — only the upload failed,
|
||||||
@@ -430,6 +443,7 @@ public sealed class JobExecutor
|
|||||||
});
|
});
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
status.Line("Preview MP4 uploaded");
|
||||||
|
|
||||||
string? thumbKey = null;
|
string? thumbKey = null;
|
||||||
if (result.ThumbnailPath is not null)
|
if (result.ThumbnailPath is not null)
|
||||||
@@ -438,6 +452,30 @@ public sealed class JobExecutor
|
|||||||
job.Id, machineId, "thumbnail", result.ThumbnailPath, "image/jpeg", shutdown);
|
job.Id, machineId, "thumbnail", result.ThumbnailPath, "image/jpeg", shutdown);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// High quality MP4 + the MOV as the version's High Res download
|
||||||
|
// (§9.6). Both optional: a failure here costs the extras, never the
|
||||||
|
// preview, which is already safely uploaded. The MOV is uploaded in
|
||||||
|
// the background after finalize (HighResUploader) — it is the big
|
||||||
|
// one and used to hold the job open for many minutes.
|
||||||
|
string? hqKey = null;
|
||||||
|
var highResPending = false;
|
||||||
|
if (manifest.HighQuality)
|
||||||
|
{
|
||||||
|
status.Line("Encoding High quality MP4");
|
||||||
|
var hqPath = await _preview.TryMakeHighQualityAsync(job.Id, result.MovPath!, result.Mp4Path!, shutdown);
|
||||||
|
if (hqPath is not null)
|
||||||
|
{
|
||||||
|
hqKey = await _api.UploadArtifactAsync(job.Id, machineId, "preview", hqPath, "video/mp4", shutdown,
|
||||||
|
status.Track("High quality MP4", hqPath));
|
||||||
|
if (hqKey is null) _log.LogWarning("High quality MP4 upload failed for job {JobId}", job.Id);
|
||||||
|
status.Line(hqKey is null ? "High quality MP4 upload FAILED (see worker log)" : "High quality MP4 uploaded");
|
||||||
|
}
|
||||||
|
|
||||||
|
highResPending = result.MovPath is not null && File.Exists(result.MovPath);
|
||||||
|
if (highResPending)
|
||||||
|
status.Line("ProRes MOV queued for background upload — completing the job now");
|
||||||
|
}
|
||||||
|
|
||||||
_spooler.Enqueue("finalize", job.Id, new Dictionary<string, object?>
|
_spooler.Enqueue("finalize", job.Id, new Dictionary<string, object?>
|
||||||
{
|
{
|
||||||
["machineId"] = machineId,
|
["machineId"] = machineId,
|
||||||
@@ -446,6 +484,8 @@ public sealed class JobExecutor
|
|||||||
["deliveryMovPath"] = manifest.MovOutput,
|
["deliveryMovPath"] = manifest.MovOutput,
|
||||||
["previewMovKey"] = previewKey,
|
["previewMovKey"] = previewKey,
|
||||||
["thumbnailKey"] = thumbKey,
|
["thumbnailKey"] = thumbKey,
|
||||||
|
["hqPreviewKey"] = hqKey,
|
||||||
|
["highResPending"] = highResPending,
|
||||||
},
|
},
|
||||||
["renderStats"] = new Dictionary<string, object?>
|
["renderStats"] = new Dictionary<string, object?>
|
||||||
{
|
{
|
||||||
@@ -458,9 +498,16 @@ public sealed class JobExecutor
|
|||||||
["frameCount"] = result.Build?.FrameCount,
|
["frameCount"] = result.Build?.FrameCount,
|
||||||
["fps"] = manifest.Fps,
|
["fps"] = manifest.Fps,
|
||||||
["fileName"] = Path.GetFileName(result.Mp4Path!),
|
["fileName"] = Path.GetFileName(result.Mp4Path!),
|
||||||
|
// Slate length, so the review player can place the handle
|
||||||
|
// markers exactly instead of inferring it (server ≥ 2026-09-22).
|
||||||
|
["pictureStartSeconds"] = result.Build?.PictureStartSeconds,
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// Enqueued after finalize: its attach report must reach the spooler
|
||||||
|
// behind finalize, which creates the version it attaches to.
|
||||||
|
if (highResPending) _highRes.Enqueue(job.Id, machineId, result.MovPath!);
|
||||||
|
|
||||||
// Only clean up once the outputs are safely reported.
|
// Only clean up once the outputs are safely reported.
|
||||||
CleanScratch(job.Id, result.TempAep);
|
CleanScratch(job.Id, result.TempAep);
|
||||||
}
|
}
|
||||||
@@ -488,6 +535,12 @@ public sealed class JobExecutor
|
|||||||
PreviewStage.TryDelete(Path.Combine(WorkerOptions.ScratchDir, $"job_{jobId}_run.jsx"));
|
PreviewStage.TryDelete(Path.Combine(WorkerOptions.ScratchDir, $"job_{jobId}_run.jsx"));
|
||||||
PreviewStage.TryDelete(Path.Combine(WorkerOptions.ScratchDir, $"job_{jobId}_thumb.jpg"));
|
PreviewStage.TryDelete(Path.Combine(WorkerOptions.ScratchDir, $"job_{jobId}_thumb.jpg"));
|
||||||
if (tempAep is not null) PreviewStage.TryDelete(tempAep);
|
if (tempAep is not null) PreviewStage.TryDelete(tempAep);
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var hqDir = PreviewStage.HighQualityDir(jobId);
|
||||||
|
if (Directory.Exists(hqDir)) Directory.Delete(hqDir, recursive: true);
|
||||||
|
}
|
||||||
|
catch { /* scratch only */ }
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
|
|||||||
@@ -0,0 +1,103 @@
|
|||||||
|
using System.Diagnostics;
|
||||||
|
using System.Text;
|
||||||
|
|
||||||
|
namespace VFXReviewWorker;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Renews a job's lease with progress reports while the worker does something
|
||||||
|
/// long that reports nothing on its own — the High quality encode and the
|
||||||
|
/// uploads can each outlast a 300 s lease, and an expired lease lets the
|
||||||
|
/// reaper hand the job to another machine mid-upload.
|
||||||
|
///
|
||||||
|
/// Each report also replaces the job's log tail with what the worker is doing
|
||||||
|
/// now ("Uploading High quality MP4: 12.0 / 34.0 MB…"). Without it the app
|
||||||
|
/// keeps showing aerender's last frame line and a busy job looks hung.
|
||||||
|
/// </summary>
|
||||||
|
internal sealed class LeaseKeepAlive : IAsyncDisposable
|
||||||
|
{
|
||||||
|
private readonly ApiClient _api;
|
||||||
|
private readonly string _jobId;
|
||||||
|
private readonly string _machineId;
|
||||||
|
private readonly CancellationTokenSource _cts;
|
||||||
|
private readonly SemaphoreSlim _wake = new(0);
|
||||||
|
private readonly Task _loop;
|
||||||
|
private readonly object _lock = new();
|
||||||
|
private readonly List<string> _lines = new();
|
||||||
|
private string? _current;
|
||||||
|
|
||||||
|
public LeaseKeepAlive(ApiClient api, string jobId, string machineId, TimeSpan interval, CancellationToken shutdown)
|
||||||
|
{
|
||||||
|
_api = api;
|
||||||
|
_jobId = jobId;
|
||||||
|
_machineId = machineId;
|
||||||
|
_cts = CancellationTokenSource.CreateLinkedTokenSource(shutdown);
|
||||||
|
var token = _cts.Token;
|
||||||
|
_loop = Task.Run(async () =>
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
while (!token.IsCancellationRequested)
|
||||||
|
{
|
||||||
|
// Best-effort by contract (ApiClient.ProgressAsync never throws
|
||||||
|
// on transport errors); progress stays at 1.0 — the render is done.
|
||||||
|
await _api.ProgressAsync(_jobId, _machineId, 1.0, null, null, null, Render(), token);
|
||||||
|
await _wake.WaitAsync(interval, token);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch (OperationCanceledException)
|
||||||
|
{
|
||||||
|
// stopped
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Adds a finished step to the status shown in the app.</summary>
|
||||||
|
public void Line(string text)
|
||||||
|
{
|
||||||
|
lock (_lock)
|
||||||
|
{
|
||||||
|
_current = null;
|
||||||
|
_lines.Add($"{DateTime.Now:HH:mm:ss} {text}");
|
||||||
|
}
|
||||||
|
_wake.Release();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Progress callback for <see cref="ApiClient.UploadArtifactAsync"/>: keeps
|
||||||
|
/// one live line ("Uploading X: 12.0 / 34.0 MB (35%, 2.1 MB/s)") up to date.
|
||||||
|
/// </summary>
|
||||||
|
public Action<long> Track(string label, string filePath)
|
||||||
|
{
|
||||||
|
long total = File.Exists(filePath) ? new FileInfo(filePath).Length : 0;
|
||||||
|
var sw = Stopwatch.StartNew();
|
||||||
|
lock (_lock) _current = $"Uploading {label}: 0.0 / {Mb(total)} MB";
|
||||||
|
_wake.Release();
|
||||||
|
return sent =>
|
||||||
|
{
|
||||||
|
var pct = total > 0 ? 100.0 * sent / total : 0;
|
||||||
|
var speed = sent / 1048576.0 / Math.Max(0.001, sw.Elapsed.TotalSeconds);
|
||||||
|
lock (_lock) _current = $"Uploading {label}: {Mb(sent)} / {Mb(total)} MB ({pct:F0}%, {speed:F1} MB/s)";
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string Mb(long bytes) => (bytes / 1048576.0).ToString("F1");
|
||||||
|
|
||||||
|
private string Render()
|
||||||
|
{
|
||||||
|
lock (_lock)
|
||||||
|
{
|
||||||
|
var sb = new StringBuilder();
|
||||||
|
foreach (var l in _lines) sb.AppendLine(l);
|
||||||
|
if (_current is not null) sb.AppendLine($"{DateTime.Now:HH:mm:ss} {_current}");
|
||||||
|
return sb.ToString();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public async ValueTask DisposeAsync()
|
||||||
|
{
|
||||||
|
_cts.Cancel();
|
||||||
|
try { await _loop; } catch { /* already reported */ }
|
||||||
|
_cts.Dispose();
|
||||||
|
_wake.Dispose();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -179,7 +179,7 @@ public sealed class PreviewStage
|
|||||||
null, null, null, build.TempAep, build, sw.Elapsed.TotalSeconds);
|
null, null, null, build.TempAep, build, sw.Elapsed.TotalSeconds);
|
||||||
}
|
}
|
||||||
|
|
||||||
var thumbnail = await TryMakeThumbnailAsync(job.Id, mp4Local, shutdown);
|
var thumbnail = await TryMakeThumbnailAsync(job.Id, mp4Local, build, manifest.Fps, shutdown);
|
||||||
|
|
||||||
sw.Stop();
|
sw.Stop();
|
||||||
_log.LogInformation("Preview complete for job {JobId} in {Sec:F0}s (mov + mp4{Thumb})",
|
_log.LogInformation("Preview complete for job {JobId} in {Sec:F0}s (mov + mp4{Thumb})",
|
||||||
@@ -231,14 +231,197 @@ public sealed class PreviewStage
|
|||||||
return process.ExitCode;
|
return process.ExitCode;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>Optional 960-wide poster frame at 25% duration (§9.1). Never fatal.</summary>
|
/// <summary>
|
||||||
private async Task<string?> TryMakeThumbnailAsync(string jobId, string mp4Path, CancellationToken ct)
|
/// Optional 960-wide poster frame at 25% of <em>picture</em> duration
|
||||||
|
/// (§9.1). Never fatal.
|
||||||
|
/// </summary>
|
||||||
|
/// <remarks>
|
||||||
|
/// The preview MP4 opens on the Netflix slate, so the frame has to be taken
|
||||||
|
/// relative to picture rather than to the file. This previously used
|
||||||
|
/// ffmpeg's <c>thumbnail</c> filter, which considers only the first 100
|
||||||
|
/// frames — on a slated preview that is the slate card, which is what every
|
||||||
|
/// thumbnail in the system was until now. Seeking to
|
||||||
|
/// <c>pictureStart + 25%</c> matches what §9.1 always documented and is what
|
||||||
|
/// makes these frames usable as shot thumbnails.
|
||||||
|
///
|
||||||
|
/// A build that reports no picture start (older worker, or a template with
|
||||||
|
/// no SHOT layer) keeps the old whole-file behaviour rather than guessing.
|
||||||
|
/// </remarks>
|
||||||
|
private async Task<string?> TryMakeThumbnailAsync(
|
||||||
|
string jobId, string mp4Path, PreviewBuildResult? build, double fps, CancellationToken ct)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrWhiteSpace(_options.FfmpegPath))
|
||||||
|
{
|
||||||
|
_log.LogWarning(
|
||||||
|
"No thumbnail for job {JobId}: ffmpegPath is not set in config.json. " +
|
||||||
|
"Thumbnails are skipped, and shots cannot take a frame from this render.",
|
||||||
|
jobId);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
if (!File.Exists(_options.FfmpegPath))
|
||||||
|
{
|
||||||
|
_log.LogWarning(
|
||||||
|
"No thumbnail for job {JobId}: ffmpegPath points at {Path}, which does not exist.",
|
||||||
|
jobId, _options.FfmpegPath);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
var outPath = Path.Combine(WorkerOptions.ScratchDir, $"job_{jobId}_thumb.jpg");
|
||||||
|
var seek = ThumbnailSeekSeconds(build, fps);
|
||||||
|
|
||||||
|
if (seek is { } t)
|
||||||
|
{
|
||||||
|
_log.LogInformation(
|
||||||
|
"Thumbnail for job {JobId}: seeking to {Seek:F2}s (slate {Start:F2}s + 25% of {Frames} frames @ {Fps}fps)",
|
||||||
|
jobId, t, build!.PictureStartSeconds, build.FrameCount, fps);
|
||||||
|
|
||||||
|
var attempt = await RunFfmpegThumbnailAsync(jobId, mp4Path, outPath, t, ct);
|
||||||
|
if (attempt == ThumbAttempt.Wrote) return outPath;
|
||||||
|
// A hung or unstartable ffmpeg will hang the same way a second
|
||||||
|
// time, and each attempt costs the full two-minute cap.
|
||||||
|
if (attempt == ThumbAttempt.Broken) return null;
|
||||||
|
|
||||||
|
// The seek is derived from what the AE build reported; if those
|
||||||
|
// numbers disagree with the rendered file, ffmpeg lands past the
|
||||||
|
// end and writes nothing. Falling back to the whole-file scan means
|
||||||
|
// a wrong seek costs picture content, never the thumbnail itself.
|
||||||
|
_log.LogWarning(
|
||||||
|
"Thumbnail seek to {Seek:F2}s produced nothing for job {JobId} — retrying across the whole file. " +
|
||||||
|
"The frame will likely be the slate.", t, jobId);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
_log.LogInformation(
|
||||||
|
"Thumbnail for job {JobId}: build reported no picture start, scanning the whole file " +
|
||||||
|
"(the frame will likely be the slate).", jobId);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (await RunFfmpegThumbnailAsync(jobId, mp4Path, outPath, null, ct) == ThumbAttempt.Wrote) return outPath;
|
||||||
|
|
||||||
|
_log.LogWarning("No thumbnail produced for job {JobId} — see the ffmpeg output above.", jobId);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Scratch folder for a job's High quality encode.</summary>
|
||||||
|
internal static string HighQualityDir(string jobId) =>
|
||||||
|
Path.Combine(WorkerOptions.ScratchDir, $"job_{jobId}_hq");
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// High quality review MP4 (§9.6): the delivery MOV re-encoded as
|
||||||
|
/// full-resolution, high-bitrate H.264 High — the player's "High" quality.
|
||||||
|
/// ProRes itself only plays in Safari on a Mac, so the MOV is offered as a
|
||||||
|
/// download and this is what streams. Never fatal: without it the version
|
||||||
|
/// simply has Standard quality only.
|
||||||
|
/// </summary>
|
||||||
|
public async Task<string?> TryMakeHighQualityAsync(
|
||||||
|
string jobId, string movPath, string mp4Path, CancellationToken ct)
|
||||||
{
|
{
|
||||||
if (string.IsNullOrWhiteSpace(_options.FfmpegPath) || !File.Exists(_options.FfmpegPath))
|
if (string.IsNullOrWhiteSpace(_options.FfmpegPath) || !File.Exists(_options.FfmpegPath))
|
||||||
{
|
{
|
||||||
|
_log.LogWarning("No High quality MP4 for job {JobId}: ffmpegPath is not set or missing.", jobId);
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
var outPath = Path.Combine(WorkerOptions.ScratchDir, $"job_{jobId}_thumb.jpg");
|
if (!File.Exists(movPath))
|
||||||
|
{
|
||||||
|
_log.LogWarning("No High quality MP4 for job {JobId}: MOV not found at {Path}.", jobId, movPath);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
var dir = HighQualityDir(jobId);
|
||||||
|
Directory.CreateDirectory(dir);
|
||||||
|
// Named after the review MP4 so the stored object reads as its sibling.
|
||||||
|
var outPath = Path.Combine(dir, Path.GetFileNameWithoutExtension(mp4Path) + "_HQ.mp4");
|
||||||
|
TryDelete(outPath);
|
||||||
|
|
||||||
|
var args = new List<string>
|
||||||
|
{
|
||||||
|
"-y", "-i", movPath,
|
||||||
|
"-map", "0:v:0", "-map", "0:a?",
|
||||||
|
// Visually lossless for review, capped so a busy shot can't balloon
|
||||||
|
// past what a good connection streams. yuv420p 8-bit High profile
|
||||||
|
// is the combination every browser decodes.
|
||||||
|
"-c:v", "libx264", "-profile:v", "high", "-preset", "medium", "-crf", "14",
|
||||||
|
"-maxrate", "100M", "-bufsize", "200M", "-pix_fmt", "yuv420p",
|
||||||
|
"-c:a", "aac", "-b:a", "256k",
|
||||||
|
// Index at the front so the player can start before it's all loaded
|
||||||
|
"-movflags", "+faststart",
|
||||||
|
outPath,
|
||||||
|
};
|
||||||
|
var psi = new ProcessStartInfo
|
||||||
|
{
|
||||||
|
FileName = _options.FfmpegPath,
|
||||||
|
RedirectStandardOutput = true,
|
||||||
|
RedirectStandardError = true,
|
||||||
|
UseShellExecute = false,
|
||||||
|
CreateNoWindow = true,
|
||||||
|
};
|
||||||
|
foreach (var a in args) psi.ArgumentList.Add(a);
|
||||||
|
|
||||||
|
var sw = Stopwatch.StartNew();
|
||||||
|
try
|
||||||
|
{
|
||||||
|
using var process = Process.Start(psi);
|
||||||
|
if (process is null)
|
||||||
|
{
|
||||||
|
_log.LogWarning("Could not start ffmpeg for the High quality MP4 (job {JobId})", jobId);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
// Drain both pipes (see RunFfmpegThumbnailAsync — an unread pipe deadlocks ffmpeg).
|
||||||
|
var stderrTask = process.StandardError.ReadToEndAsync();
|
||||||
|
var stdoutTask = process.StandardOutput.ReadToEndAsync();
|
||||||
|
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(ct);
|
||||||
|
timeout.CancelAfter(TimeSpan.FromMinutes(30));
|
||||||
|
try
|
||||||
|
{
|
||||||
|
await process.WaitForExitAsync(timeout.Token);
|
||||||
|
}
|
||||||
|
catch (OperationCanceledException)
|
||||||
|
{
|
||||||
|
_log.LogWarning("High quality encode for job {JobId} timed out or was cancelled — killing ffmpeg", jobId);
|
||||||
|
try { process.Kill(entireProcessTree: true); } catch { }
|
||||||
|
TryDelete(outPath);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
var stderr = await stderrTask;
|
||||||
|
await stdoutTask;
|
||||||
|
|
||||||
|
if (process.ExitCode == 0 && File.Exists(outPath) && new FileInfo(outPath).Length > 0)
|
||||||
|
{
|
||||||
|
_log.LogInformation("High quality MP4 for job {JobId} encoded in {Sec:F0}s ({MB:F0} MB)",
|
||||||
|
jobId, sw.Elapsed.TotalSeconds, new FileInfo(outPath).Length / 1e6);
|
||||||
|
return outPath;
|
||||||
|
}
|
||||||
|
_log.LogWarning("High quality encode failed for job {JobId} (exit {Exit}): {Stderr}",
|
||||||
|
jobId, process.ExitCode, Tail(stderr, 1200));
|
||||||
|
TryDelete(outPath);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
_log.LogWarning(ex, "High quality encode failed for job {JobId} (non-fatal)", jobId);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>How one ffmpeg attempt ended.</summary>
|
||||||
|
private enum ThumbAttempt
|
||||||
|
{
|
||||||
|
/// <summary>A thumbnail was written.</summary>
|
||||||
|
Wrote,
|
||||||
|
/// <summary>ffmpeg ran and wrote nothing — a different attempt may work.</summary>
|
||||||
|
NoOutput,
|
||||||
|
/// <summary>ffmpeg hung or could not start — retrying costs minutes and fixes nothing.</summary>
|
||||||
|
Broken,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// One ffmpeg invocation. <paramref name="seekSeconds"/> null means the old
|
||||||
|
/// whole-file <c>thumbnail</c> filter. Logs ffmpeg's own diagnosis when no
|
||||||
|
/// file is produced.
|
||||||
|
/// </summary>
|
||||||
|
private async Task<ThumbAttempt> RunFfmpegThumbnailAsync(
|
||||||
|
string jobId, string mp4Path, string outPath, double? seekSeconds, CancellationToken ct)
|
||||||
|
{
|
||||||
TryDelete(outPath);
|
TryDelete(outPath);
|
||||||
|
|
||||||
var psi = new ProcessStartInfo
|
var psi = new ProcessStartInfo
|
||||||
@@ -249,27 +432,102 @@ public sealed class PreviewStage
|
|||||||
UseShellExecute = false,
|
UseShellExecute = false,
|
||||||
CreateNoWindow = true,
|
CreateNoWindow = true,
|
||||||
};
|
};
|
||||||
foreach (var a in new[] { "-y", "-i", mp4Path, "-vf", "thumbnail,scale=960:-1", "-frames:v", "1", outPath })
|
|
||||||
|
var args = new List<string> { "-y" };
|
||||||
|
if (seekSeconds is { } t)
|
||||||
{
|
{
|
||||||
psi.ArgumentList.Add(a);
|
// Before -i: ffmpeg seeks by keyframe, which is fast and accurate
|
||||||
|
// enough for a poster frame.
|
||||||
|
args.Add("-ss");
|
||||||
|
args.Add(t.ToString("0.###", System.Globalization.CultureInfo.InvariantCulture));
|
||||||
|
args.Add("-i");
|
||||||
|
args.Add(mp4Path);
|
||||||
|
args.Add("-vf");
|
||||||
|
args.Add("scale=960:-1");
|
||||||
}
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
args.Add("-i");
|
||||||
|
args.Add(mp4Path);
|
||||||
|
args.Add("-vf");
|
||||||
|
args.Add("thumbnail,scale=960:-1");
|
||||||
|
}
|
||||||
|
args.Add("-frames:v");
|
||||||
|
args.Add("1");
|
||||||
|
args.Add(outPath);
|
||||||
|
|
||||||
|
foreach (var a in args) psi.ArgumentList.Add(a);
|
||||||
|
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
using var process = Process.Start(psi);
|
using var process = Process.Start(psi);
|
||||||
if (process is null) return null;
|
if (process is null)
|
||||||
|
{
|
||||||
|
_log.LogWarning("Could not start ffmpeg at {Path} for job {JobId}", _options.FfmpegPath, jobId);
|
||||||
|
return ThumbAttempt.Broken;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Drain BOTH pipes while the process runs. Windows gives an
|
||||||
|
// anonymous pipe a ~4 KB buffer; ffmpeg's banner and stream summary
|
||||||
|
// exceed that on their own, so a redirected-but-unread pipe fills,
|
||||||
|
// ffmpeg blocks forever on the write, and the wait below times out
|
||||||
|
// with the process still alive. That is a deadlock, not a slow
|
||||||
|
// encode, and it is why this step failed with nothing but a
|
||||||
|
// cancellation to show for it.
|
||||||
|
var stderrTask = process.StandardError.ReadToEndAsync();
|
||||||
|
var stdoutTask = process.StandardOutput.ReadToEndAsync();
|
||||||
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(ct);
|
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(ct);
|
||||||
timeout.CancelAfter(TimeSpan.FromMinutes(2));
|
timeout.CancelAfter(TimeSpan.FromMinutes(2));
|
||||||
await process.WaitForExitAsync(timeout.Token);
|
try
|
||||||
return File.Exists(outPath) ? outPath : null;
|
{
|
||||||
|
await process.WaitForExitAsync(timeout.Token);
|
||||||
|
}
|
||||||
|
catch (OperationCanceledException) when (!ct.IsCancellationRequested)
|
||||||
|
{
|
||||||
|
// Our own 2-minute cap, not a shutdown: leaving ffmpeg running
|
||||||
|
// would hold the scratch file open and leak a process per job.
|
||||||
|
_log.LogWarning(
|
||||||
|
"ffmpeg timed out after 2 minutes for job {JobId} — killing it. Command: {Args}",
|
||||||
|
jobId, string.Join(" ", args));
|
||||||
|
try { process.Kill(entireProcessTree: true); } catch { }
|
||||||
|
return ThumbAttempt.Broken;
|
||||||
|
}
|
||||||
|
var stderr = await stderrTask;
|
||||||
|
await stdoutTask;
|
||||||
|
|
||||||
|
if (File.Exists(outPath) && new FileInfo(outPath).Length > 0) return ThumbAttempt.Wrote;
|
||||||
|
|
||||||
|
_log.LogWarning(
|
||||||
|
"ffmpeg wrote no thumbnail for job {JobId} (exit {Exit}). Command: {Args} -- ffmpeg said: {Stderr}",
|
||||||
|
jobId, process.ExitCode, string.Join(" ", args), Tail(stderr, 1200));
|
||||||
|
return ThumbAttempt.NoOutput;
|
||||||
}
|
}
|
||||||
catch (Exception ex)
|
catch (Exception ex)
|
||||||
{
|
{
|
||||||
_log.LogWarning(ex, "Thumbnail generation failed (non-fatal)");
|
_log.LogWarning(ex, "Thumbnail generation failed for job {JobId} (non-fatal)", jobId);
|
||||||
return null;
|
return ThumbAttempt.Broken;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>Last <paramref name="max"/> characters — ffmpeg puts the error at the end.</summary>
|
||||||
|
private static string Tail(string? text, int max) =>
|
||||||
|
string.IsNullOrEmpty(text) ? "(no output)"
|
||||||
|
: text.Length <= max ? text
|
||||||
|
: text[^max..];
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Timestamp for the poster frame: a quarter of the way into picture,
|
||||||
|
/// skipping the slate. Null when the build did not report where picture
|
||||||
|
/// starts, or when the numbers do not describe a real clip.
|
||||||
|
/// </summary>
|
||||||
|
internal static double? ThumbnailSeekSeconds(PreviewBuildResult? build, double fps)
|
||||||
|
{
|
||||||
|
if (build?.PictureStartSeconds is not { } start || start < 0) return null;
|
||||||
|
if (build.FrameCount is not { } frames || frames <= 0) return null;
|
||||||
|
if (fps <= 0) return null;
|
||||||
|
return start + (frames / fps) * 0.25;
|
||||||
|
}
|
||||||
|
|
||||||
private static PreviewStageResult Fail(string message, bool retryable, Stopwatch sw, PreviewBuildResult? build = null)
|
private static PreviewStageResult Fail(string message, bool retryable, Stopwatch sw, PreviewBuildResult? build = null)
|
||||||
{
|
{
|
||||||
sw.Stop();
|
sw.Stop();
|
||||||
|
|||||||
@@ -37,6 +37,7 @@ builder.Logging.AddProvider(new FileLoggerProvider());
|
|||||||
builder.Services.AddSingleton(options);
|
builder.Services.AddSingleton(options);
|
||||||
builder.Services.AddSingleton<ApiClient>();
|
builder.Services.AddSingleton<ApiClient>();
|
||||||
builder.Services.AddSingleton<ReportSpooler>();
|
builder.Services.AddSingleton<ReportSpooler>();
|
||||||
|
builder.Services.AddSingleton<HighResUploader>();
|
||||||
builder.Services.AddSingleton<AerenderRunner>();
|
builder.Services.AddSingleton<AerenderRunner>();
|
||||||
builder.Services.AddSingleton<PreviewStage>();
|
builder.Services.AddSingleton<PreviewStage>();
|
||||||
builder.Services.AddSingleton<ValidationStage>();
|
builder.Services.AddSingleton<ValidationStage>();
|
||||||
|
|||||||
@@ -0,0 +1,42 @@
|
|||||||
|
using System.Net;
|
||||||
|
|
||||||
|
namespace VFXReviewWorker;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// StreamContent that reports bytes sent, so a long upload can show progress.
|
||||||
|
/// Length is computed from the stream, so the PUT still carries Content-Length
|
||||||
|
/// (presigned S3 uploads reject chunked bodies).
|
||||||
|
/// </summary>
|
||||||
|
internal sealed class ProgressStreamContent : HttpContent
|
||||||
|
{
|
||||||
|
private readonly Stream _source;
|
||||||
|
private readonly Action<long>? _onProgress;
|
||||||
|
|
||||||
|
public ProgressStreamContent(Stream source, Action<long>? onProgress)
|
||||||
|
{
|
||||||
|
_source = source;
|
||||||
|
_onProgress = onProgress;
|
||||||
|
}
|
||||||
|
|
||||||
|
protected override Task SerializeToStreamAsync(Stream stream, TransportContext? context) =>
|
||||||
|
SerializeToStreamAsync(stream, context, CancellationToken.None);
|
||||||
|
|
||||||
|
protected override async Task SerializeToStreamAsync(Stream stream, TransportContext? context, CancellationToken ct)
|
||||||
|
{
|
||||||
|
var buffer = new byte[81920];
|
||||||
|
long sent = 0;
|
||||||
|
int read;
|
||||||
|
while ((read = await _source.ReadAsync(buffer, ct)) > 0)
|
||||||
|
{
|
||||||
|
await stream.WriteAsync(buffer.AsMemory(0, read), ct);
|
||||||
|
sent += read;
|
||||||
|
_onProgress?.Invoke(sent);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
protected override bool TryComputeLength(out long length)
|
||||||
|
{
|
||||||
|
length = _source.Length;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -15,7 +15,7 @@
|
|||||||
every change that gets published. publish.ps1 appends the git SHA via
|
every change that gets published. publish.ps1 appends the git SHA via
|
||||||
SourceRevisionId, giving "1.1.0+feb1c7b".
|
SourceRevisionId, giving "1.1.0+feb1c7b".
|
||||||
-->
|
-->
|
||||||
<Version>1.5.1</Version>
|
<Version>1.7.2</Version>
|
||||||
</PropertyGroup>
|
</PropertyGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
|
|||||||
@@ -350,6 +350,31 @@ public sealed class ValidationStage
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
var deltaOf = (TimecodeReference r) =>
|
||||||
|
renderTc.ToFrames(fps) - (r.PlateTimecode.ToFrames(fps) + (renderFirstFrame - r.PlateFirstFrame));
|
||||||
|
|
||||||
|
// A shot with several delivered elements: the panel names the longest
|
||||||
|
// as the timing plate, but the comp may have been anchored to another
|
||||||
|
// (BG01 and FG01 carry unrelated camera timecodes). When the timing
|
||||||
|
// plate disagrees, the manifest's other delivered plates are tried
|
||||||
|
// before failing. The comparison is unchanged — it is still a plate, so
|
||||||
|
// a match is a real PASS and no match still FAILs against the timing plate.
|
||||||
|
var timingPlate = reference;
|
||||||
|
var alternatesTried = new List<object>();
|
||||||
|
if (reference.Kind == "manifest" && deltaOf(reference) != 0)
|
||||||
|
{
|
||||||
|
foreach (var alternate in ResolveAlternatePlates(m, renderFirstFrame, reference))
|
||||||
|
{
|
||||||
|
var altDelta = deltaOf(alternate);
|
||||||
|
alternatesTried.Add(new { platePath = alternate.PlatePath, plateTimecode = alternate.PlateTimecode.ToString(), deltaFrames = altDelta });
|
||||||
|
if (altDelta == 0)
|
||||||
|
{
|
||||||
|
reference = alternate;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// plate_fps — the render's rate against the plate's own.
|
// plate_fps — the render's rate against the plate's own.
|
||||||
//
|
//
|
||||||
// timecode_fps only compares the render to the manifest, and both come
|
// timecode_fps only compares the render to the manifest, and both come
|
||||||
@@ -377,8 +402,8 @@ public sealed class ValidationStage
|
|||||||
|
|
||||||
var expectedFrames = reference.PlateTimecode.ToFrames(fps) + (renderFirstFrame - reference.PlateFirstFrame);
|
var expectedFrames = reference.PlateTimecode.ToFrames(fps) + (renderFirstFrame - reference.PlateFirstFrame);
|
||||||
var expected = Timecode.FromFrames(expectedFrames, fps);
|
var expected = Timecode.FromFrames(expectedFrames, fps);
|
||||||
var actualFrames = renderTc.ToFrames(fps);
|
var deltaFrames = deltaOf(reference);
|
||||||
var deltaFrames = actualFrames - expectedFrames;
|
var matchedAlternate = !ReferenceEquals(reference, timingPlate);
|
||||||
var details = new
|
var details = new
|
||||||
{
|
{
|
||||||
reference = reference.Kind,
|
reference = reference.Kind,
|
||||||
@@ -387,10 +412,14 @@ public sealed class ValidationStage
|
|||||||
plateFirstFrame = reference.PlateFirstFrame,
|
plateFirstFrame = reference.PlateFirstFrame,
|
||||||
renderFirstFrame,
|
renderFirstFrame,
|
||||||
deltaFrames,
|
deltaFrames,
|
||||||
|
timingPlatePath = timingPlate.PlatePath,
|
||||||
|
matchedAlternate,
|
||||||
|
alternatesTried,
|
||||||
};
|
};
|
||||||
|
|
||||||
if (deltaFrames == 0)
|
if (deltaFrames == 0)
|
||||||
{
|
{
|
||||||
|
var timingDelta = deltaOf(timingPlate);
|
||||||
// The API fallback proves nothing on its own (§8.1a): it is the
|
// The API fallback proves nothing on its own (§8.1a): it is the
|
||||||
// editorial in-point minus a handle count that may not be this
|
// editorial in-point minus a handle count that may not be this
|
||||||
// plate's, so a match is reported as a WARN, never a PASS.
|
// plate's, so a match is reported as a WARN, never a PASS.
|
||||||
@@ -398,7 +427,11 @@ public sealed class ValidationStage
|
|||||||
? ValidationCheck.Warn("timecode_plate_match", expected.ToString(), renderTc.ToString(),
|
? ValidationCheck.Warn("timecode_plate_match", expected.ToString(), renderTc.ToString(),
|
||||||
"Matches the API timecode less handles, but the plate itself could not be read — unverified.", details)
|
"Matches the API timecode less handles, but the plate itself could not be read — unverified.", details)
|
||||||
: ValidationCheck.Pass("timecode_plate_match", expected.ToString(), renderTc.ToString(),
|
: ValidationCheck.Pass("timecode_plate_match", expected.ToString(), renderTc.ToString(),
|
||||||
$"Matches {reference.Kind} plate {Path.GetFileName(reference.PlatePath ?? "")}", details));
|
$"Matches {reference.Kind} plate {Path.GetFileName(reference.PlatePath ?? "")}" +
|
||||||
|
(matchedAlternate
|
||||||
|
? $" (the timing plate {Path.GetFileName(timingPlate.PlatePath ?? "")} is {(timingDelta > 0 ? "+" : "")}{timingDelta} frames off — the comp was anchored to this element instead)"
|
||||||
|
: ""),
|
||||||
|
details));
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -409,7 +442,10 @@ public sealed class ValidationStage
|
|||||||
? $"That is exactly the {reference.HandleFrames}-frame handle: the comp was anchored to the editorial in-point instead of the plate's first frame."
|
? $"That is exactly the {reference.HandleFrames}-frame handle: the comp was anchored to the editorial in-point instead of the plate's first frame."
|
||||||
: renderTc.Hours == 0 && renderTc.Minutes == 0
|
: renderTc.Hours == 0 && renderTc.Minutes == 0
|
||||||
? "A near-zero timecode means the comp had no source timecode at all and AE derived it from the frame number."
|
? "A near-zero timecode means the comp had no source timecode at all and AE derived it from the frame number."
|
||||||
: "");
|
: "") +
|
||||||
|
(alternatesTried.Count > 0
|
||||||
|
? $" Also checked {alternatesTried.Count} other delivered plate{(alternatesTried.Count == 1 ? "" : "s")} in the manifest: none match."
|
||||||
|
: "");
|
||||||
|
|
||||||
checks.Add(reference.Kind == "api"
|
checks.Add(reference.Kind == "api"
|
||||||
? ValidationCheck.Warn("timecode_plate_match", expected.ToString(), renderTc.ToString(),
|
? ValidationCheck.Warn("timecode_plate_match", expected.ToString(), renderTc.ToString(),
|
||||||
@@ -430,20 +466,9 @@ public sealed class ValidationStage
|
|||||||
var timing = m.Source?.TimingPlate;
|
var timing = m.Source?.TimingPlate;
|
||||||
if (timing is not null && !string.IsNullOrWhiteSpace(timing.Path))
|
if (timing is not null && !string.IsNullOrWhiteSpace(timing.Path))
|
||||||
{
|
{
|
||||||
var local = mapper.Map(timing.Path);
|
var manifestPlate = ReadManifestPlate(timing, mapper, handleFrames, renderFirstFrame);
|
||||||
var header = File.Exists(local) ? ExrHeader.TryRead(local) : null;
|
if (manifestPlate is not null) return manifestPlate;
|
||||||
if (header?.Timecode is not null)
|
_log.LogWarning("Timing plate from manifest is unreadable: {Path}", mapper.Map(timing.Path));
|
||||||
{
|
|
||||||
// The plate's own file numbering, never the comp's frame range:
|
|
||||||
// the render's first frame is in output numbering, so anchoring
|
|
||||||
// on a comp frame skews the comparison by the gap between them.
|
|
||||||
var frame = SequencePattern.FrameFromName(Path.GetFileName(local))
|
|
||||||
?? timing.FrameStart
|
|
||||||
?? renderFirstFrame;
|
|
||||||
return new TimecodeReference("manifest", local, header.Timecode.Value, frame, handleFrames,
|
|
||||||
header.FramesPerSecond);
|
|
||||||
}
|
|
||||||
_log.LogWarning("Timing plate from manifest is unreadable: {Path}", local);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Rank 2 — derive the plate from a configured search root.
|
// Rank 2 — derive the plate from a configured search root.
|
||||||
@@ -469,6 +494,63 @@ public sealed class ValidationStage
|
|||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private static TimecodeReference? ReadManifestPlate(PlateRef plate, PathMapper mapper, int handleFrames, int renderFirstFrame)
|
||||||
|
{
|
||||||
|
var local = mapper.Map(plate.Path);
|
||||||
|
var header = File.Exists(local) ? ExrHeader.TryRead(local) : null;
|
||||||
|
if (header?.Timecode is null) return null;
|
||||||
|
|
||||||
|
// The plate's own file numbering, never the comp's frame range: the
|
||||||
|
// render's first frame is in output numbering, so anchoring on a comp
|
||||||
|
// frame skews the comparison by the gap between them.
|
||||||
|
var frame = SequencePattern.FrameFromName(Path.GetFileName(local))
|
||||||
|
?? plate.FrameStart
|
||||||
|
?? renderFirstFrame;
|
||||||
|
return new TimecodeReference("manifest", local, header.Timecode.Value, frame, handleFrames,
|
||||||
|
header.FramesPerSecond);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The manifest's other delivered plates, tried when the timing plate does
|
||||||
|
/// not match. Only real footage qualifies — under a configured plate search
|
||||||
|
/// root or, with none configured, alongside the timing plate in its footage
|
||||||
|
/// folder — because plates[] is every file in the comp, and a pre-render
|
||||||
|
/// agrees with the render whether or not either is right.
|
||||||
|
/// </summary>
|
||||||
|
private IEnumerable<TimecodeReference> ResolveAlternatePlates(RenderManifest m, int renderFirstFrame, TimecodeReference timingPlate)
|
||||||
|
{
|
||||||
|
var plates = m.Source?.Plates;
|
||||||
|
if (plates is null || plates.Count == 0 || timingPlate.PlatePath is null) yield break;
|
||||||
|
|
||||||
|
var mapper = new PathMapper(_options.PathMappings);
|
||||||
|
static string AsFolder(string dir) => Path.TrimEndingDirectorySeparator(Path.GetFullPath(dir)) + Path.DirectorySeparatorChar;
|
||||||
|
|
||||||
|
var deliveredRoots = _options.PlateSearchRoots.Count > 0
|
||||||
|
? _options.PlateSearchRoots.Select(r => AsFolder(mapper.Map(r))).ToList()
|
||||||
|
// {footage}/{shot}_{element}/file.exr or {footage}/{shot}/{element}/file.exr:
|
||||||
|
// two levels up from the timing plate is the folder its siblings share.
|
||||||
|
: Path.GetDirectoryName(Path.GetDirectoryName(Path.GetFullPath(timingPlate.PlatePath))) is { } footage
|
||||||
|
? new List<string> { AsFolder(footage) }
|
||||||
|
: new List<string>();
|
||||||
|
|
||||||
|
var seen = new HashSet<string>(StringComparer.OrdinalIgnoreCase) { Path.GetFullPath(timingPlate.PlatePath) };
|
||||||
|
foreach (var plate in plates)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrWhiteSpace(plate.Path)) continue;
|
||||||
|
var local = Path.GetFullPath(mapper.Map(plate.Path));
|
||||||
|
if (!seen.Add(local)) continue;
|
||||||
|
if (!deliveredRoots.Any(root => local.StartsWith(root, StringComparison.OrdinalIgnoreCase))) continue;
|
||||||
|
|
||||||
|
var reference = ReadManifestPlate(plate, mapper, timingPlate.HandleFrames, renderFirstFrame);
|
||||||
|
if (reference is null)
|
||||||
|
{
|
||||||
|
_log.LogWarning("Alternate plate from manifest is unreadable: {Path}", local);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
yield return reference;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Rank 2: look for the shot's plate folders under the configured roots,
|
/// Rank 2: look for the shot's plate folders under the configured roots,
|
||||||
/// mirroring the panel's two on-disk layouts ({shotCode}/{element}/ and
|
/// mirroring the panel's two on-disk layouts ({shotCode}/{element}/ and
|
||||||
@@ -645,6 +727,16 @@ public sealed class SequencePattern
|
|||||||
return new SequencePattern { Prefix = prefix, Extension = ext, Padding = padding };
|
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);
|
public int? FrameNumberOf(string fileName) => FrameFromName(fileName);
|
||||||
|
|
||||||
/// <summary>`UNG_102_019_010_cmp_TT_v005.01001.exr` → 1001.</summary>
|
/// <summary>`UNG_102_019_010_cmp_TT_v005.01001.exr` → 1001.</summary>
|
||||||
|
|||||||
@@ -35,6 +35,12 @@ public sealed class WorkerOptions
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
public List<string> PlateSearchRoots { get; set; } = new();
|
public List<string> PlateSearchRoots { get; set; } = new();
|
||||||
/// <summary>
|
/// <summary>
|
||||||
|
/// Parallel connections per large upload. From the studio each connection
|
||||||
|
/// to object storage is capped near 0.1 MB/s, so throughput scales with
|
||||||
|
/// this (measured: 1 → 0.13 MB/s, 8 → 0.64, 24 → 1.69).
|
||||||
|
/// </summary>
|
||||||
|
public int UploadConcurrency { get; set; } = 16;
|
||||||
|
/// <summary>
|
||||||
/// Read from the assembly, not from config.json: a hand-maintained version
|
/// Read from the assembly, not from config.json: a hand-maintained version
|
||||||
/// string is exactly the thing that goes stale, and a machine reporting a
|
/// string is exactly the thing that goes stale, and a machine reporting a
|
||||||
/// version it is not running is worse than no version at all.
|
/// version it is not running is worse than no version at all.
|
||||||
|
|||||||
@@ -15,6 +15,7 @@ public sealed class WorkerService : BackgroundService
|
|||||||
private readonly ApiClient _api;
|
private readonly ApiClient _api;
|
||||||
private readonly JobExecutor _executor;
|
private readonly JobExecutor _executor;
|
||||||
private readonly ReportSpooler _spooler;
|
private readonly ReportSpooler _spooler;
|
||||||
|
private readonly HighResUploader _highRes;
|
||||||
private readonly ILogger<WorkerService> _log;
|
private readonly ILogger<WorkerService> _log;
|
||||||
|
|
||||||
private string? _machineId;
|
private string? _machineId;
|
||||||
@@ -23,8 +24,10 @@ public sealed class WorkerService : BackgroundService
|
|||||||
private CancellationTokenSource? _cancelCurrentJob;
|
private CancellationTokenSource? _cancelCurrentJob;
|
||||||
private bool? _lastAeOpen;
|
private bool? _lastAeOpen;
|
||||||
|
|
||||||
public WorkerService(WorkerOptions options, ApiClient api, JobExecutor executor, ReportSpooler spooler, ILogger<WorkerService> log)
|
public WorkerService(WorkerOptions options, ApiClient api, JobExecutor executor, ReportSpooler spooler,
|
||||||
|
HighResUploader highRes, ILogger<WorkerService> log)
|
||||||
{
|
{
|
||||||
|
_highRes = highRes;
|
||||||
_options = options;
|
_options = options;
|
||||||
_api = api;
|
_api = api;
|
||||||
_executor = executor;
|
_executor = executor;
|
||||||
@@ -40,6 +43,7 @@ public sealed class WorkerService : BackgroundService
|
|||||||
_ = Task.Run(() => _spooler.RunAsync(stoppingToken), stoppingToken);
|
_ = Task.Run(() => _spooler.RunAsync(stoppingToken), stoppingToken);
|
||||||
|
|
||||||
await RegisterWithRetryAsync(stoppingToken);
|
await RegisterWithRetryAsync(stoppingToken);
|
||||||
|
_ = Task.Run(() => _highRes.RunAsync(stoppingToken), stoppingToken);
|
||||||
await _api.ReportVersionAsync(_options, stoppingToken);
|
await _api.ReportVersionAsync(_options, stoppingToken);
|
||||||
await _executor.ReconcileAsync(_machineId!, stoppingToken);
|
await _executor.ReconcileAsync(_machineId!, stoppingToken);
|
||||||
|
|
||||||
|
|||||||
@@ -30,7 +30,11 @@
|
|||||||
queued: [],
|
queued: [],
|
||||||
frameCount: null,
|
frameCount: null,
|
||||||
width: null,
|
width: null,
|
||||||
height: null
|
height: null,
|
||||||
|
// Seconds of slate ahead of picture in the preview comp — the SHOT
|
||||||
|
// layer's in-point. The worker needs it to grab a thumbnail from
|
||||||
|
// picture rather than from the slate card.
|
||||||
|
pictureStartSeconds: null
|
||||||
};
|
};
|
||||||
var resultPath = null;
|
var resultPath = null;
|
||||||
|
|
||||||
@@ -512,6 +516,8 @@
|
|||||||
|
|
||||||
var shotLayer = previewComp.layer("SHOT");
|
var shotLayer = previewComp.layer("SHOT");
|
||||||
var targetOutPoint = shotLayer.inPoint + shotComp.duration;
|
var targetOutPoint = shotLayer.inPoint + shotComp.duration;
|
||||||
|
// Everything before this is slate; the thumbnail has to start after it.
|
||||||
|
result.pictureStartSeconds = shotLayer.inPoint;
|
||||||
if (targetOutPoint > previewComp.duration) {
|
if (targetOutPoint > previewComp.duration) {
|
||||||
previewComp.duration = targetOutPoint;
|
previewComp.duration = targetOutPoint;
|
||||||
}
|
}
|
||||||
|
|||||||
+323
-25
@@ -32,7 +32,7 @@ var SETTINGS_KEY = "cfg";
|
|||||||
// Bump on every change deployed to a workstation. The panel reports this to
|
// Bump on every change deployed to a workstation. The panel reports this to
|
||||||
// the server on load, so Pipeline → Machines shows which version each machine
|
// the server on load, so Pipeline → Machines shows which version each machine
|
||||||
// is actually running and flags the ones left behind.
|
// is actually running and flags the ones left behind.
|
||||||
var PANEL_VERSION = "2.5.0";
|
var PANEL_VERSION = "2.7.1";
|
||||||
|
|
||||||
(function VFXReviewConnector(thisObj) {
|
(function VFXReviewConnector(thisObj) {
|
||||||
var uiState = {
|
var uiState = {
|
||||||
@@ -45,6 +45,8 @@ var PANEL_VERSION = "2.5.0";
|
|||||||
pipelineStatusText: null,
|
pipelineStatusText: null,
|
||||||
urgentCheckbox: null,
|
urgentCheckbox: null,
|
||||||
skipPreviewCheckbox: null,
|
skipPreviewCheckbox: null,
|
||||||
|
handlesCheckbox: null,
|
||||||
|
handleFramesField: null,
|
||||||
submissionNoteField: null,
|
submissionNoteField: null,
|
||||||
qcList: null,
|
qcList: null,
|
||||||
qcNotesField: null,
|
qcNotesField: null,
|
||||||
@@ -65,7 +67,6 @@ var PANEL_VERSION = "2.5.0";
|
|||||||
|
|
||||||
var pipelineState = {
|
var pipelineState = {
|
||||||
pollShotCode: null,
|
pollShotCode: null,
|
||||||
pollTaskId: 0,
|
|
||||||
prefilledShotCode: null
|
prefilledShotCode: null
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -958,17 +959,29 @@ var PANEL_VERSION = "2.5.0";
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Assigning displayStartFrame on a version of AE that does not have the
|
||||||
|
// property is ignored silently rather than throwing, which is one of the
|
||||||
|
// ways a comp ends up back at 00:00:00:00. Read the value back and fall
|
||||||
|
// through to displayStartTime when it did not take, and tell the caller
|
||||||
|
// whether anything stuck.
|
||||||
function setCompStartFrame(comp, frameNumber) {
|
function setCompStartFrame(comp, frameNumber) {
|
||||||
|
var wanted = Math.round(frameNumber);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
comp.displayStartFrame = frameNumber;
|
comp.displayStartFrame = frameNumber;
|
||||||
return;
|
if (Math.round(comp.displayStartFrame) === wanted) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
} catch (frameError) {
|
} catch (frameError) {
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
comp.displayStartTime = frameNumber / comp.frameRate;
|
comp.displayStartTime = frameNumber / comp.frameRate;
|
||||||
|
return Math.round(comp.displayStartTime * comp.frameRate) === wanted;
|
||||||
} catch (timeError) {
|
} catch (timeError) {
|
||||||
}
|
}
|
||||||
|
|
||||||
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
function deselectAllProjectItems() {
|
function deselectAllProjectItems() {
|
||||||
@@ -1051,13 +1064,220 @@ var PANEL_VERSION = "2.5.0";
|
|||||||
return frames;
|
return frames;
|
||||||
}
|
}
|
||||||
|
|
||||||
// The plate's own start timecode: AE metadata when we can read it,
|
// The first file of an imported sequence: the frame whose header carries the
|
||||||
// otherwise the API's source clip timecode less the handle frames — the
|
// plate's start timecode. importEXRSequence sorts before importing, so this
|
||||||
// same convention the Set Start Timecode button uses.
|
// is the sequence's first frame and not an arbitrary one.
|
||||||
|
function getFootageFirstFile(footageItem) {
|
||||||
|
try {
|
||||||
|
if (footageItem && footageItem.mainSource && footageItem.mainSource.file) {
|
||||||
|
return footageItem.mainSource.file;
|
||||||
|
}
|
||||||
|
} catch (fileError) {
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
function readUInt32LE(buf, offset) {
|
||||||
|
return (buf.charCodeAt(offset) & 0xFF) +
|
||||||
|
(buf.charCodeAt(offset + 1) & 0xFF) * 256 +
|
||||||
|
(buf.charCodeAt(offset + 2) & 0xFF) * 65536 +
|
||||||
|
(buf.charCodeAt(offset + 3) & 0xFF) * 16777216;
|
||||||
|
}
|
||||||
|
|
||||||
|
function readInt32LE(buf, offset) {
|
||||||
|
var value = readUInt32LE(buf, offset);
|
||||||
|
|
||||||
|
return value >= 2147483648 ? value - 4294967296 : value;
|
||||||
|
}
|
||||||
|
|
||||||
|
// A null-terminated header string. Returns null when the terminator is not
|
||||||
|
// found within a sane distance, which means the bytes are not a header we
|
||||||
|
// understand and parsing should stop rather than guess.
|
||||||
|
function readExrString(buf, offset) {
|
||||||
|
var end = offset;
|
||||||
|
var limit = Math.min(buf.length, offset + 256);
|
||||||
|
|
||||||
|
while (end < limit && buf.charCodeAt(end) !== 0) {
|
||||||
|
end += 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (end >= limit) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
return buf.substring(offset, end);
|
||||||
|
}
|
||||||
|
|
||||||
|
function pad2(value) {
|
||||||
|
return (value < 10 ? "0" : "") + value;
|
||||||
|
}
|
||||||
|
|
||||||
|
function makeTimecode(hours, minutes, seconds, frames, dropFrame) {
|
||||||
|
if (hours > 23 || minutes > 59 || seconds > 59) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
hours: hours,
|
||||||
|
minutes: minutes,
|
||||||
|
seconds: seconds,
|
||||||
|
frames: frames,
|
||||||
|
dropFrame: dropFrame,
|
||||||
|
text: pad2(hours) + ":" + pad2(minutes) + ":" + pad2(seconds) +
|
||||||
|
(dropFrame ? ";" : ":") + pad2(frames)
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// SMPTE 12M as stored in the EXR timeCode attribute: BCD-packed, which is
|
||||||
|
// why the raw value reads back as its own hex digits (0x18585712 is
|
||||||
|
// 18:58:57:12). Every field sits inside a single byte, so the nibbles can be
|
||||||
|
// picked off per byte and never touch the sign bit.
|
||||||
|
function decodePackedTimecode(buf, offset) {
|
||||||
|
var b0 = buf.charCodeAt(offset) & 0xFF; // frames, drop-frame flag
|
||||||
|
var b1 = buf.charCodeAt(offset + 1) & 0xFF; // seconds
|
||||||
|
var b2 = buf.charCodeAt(offset + 2) & 0xFF; // minutes
|
||||||
|
var b3 = buf.charCodeAt(offset + 3) & 0xFF; // hours
|
||||||
|
|
||||||
|
return makeTimecode(
|
||||||
|
(b3 & 0x0F) + ((b3 >> 4) & 0x03) * 10,
|
||||||
|
(b2 & 0x0F) + ((b2 >> 4) & 0x07) * 10,
|
||||||
|
(b1 & 0x0F) + ((b1 >> 4) & 0x07) * 10,
|
||||||
|
(b0 & 0x0F) + ((b0 >> 4) & 0x03) * 10,
|
||||||
|
((b0 >> 6) & 0x01) === 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
function parseTimecodeText(text) {
|
||||||
|
var parts = String(text).split(/[:;]/);
|
||||||
|
|
||||||
|
if (parts.length < 4) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
return makeTimecode(
|
||||||
|
parseInt(parts[0], 10) || 0,
|
||||||
|
parseInt(parts[1], 10) || 0,
|
||||||
|
parseInt(parts[2], 10) || 0,
|
||||||
|
parseInt(parts[3], 10) || 0,
|
||||||
|
String(text).indexOf(";") !== -1);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Reads the plate's timecode straight out of the OpenEXR header, the way the
|
||||||
|
// worker's ExrHeader.cs does, so the panel anchors comps on exactly the
|
||||||
|
// value validation later checks them against. Header layout is
|
||||||
|
// magic(4) version(4) then attributes as `name\0 type\0 int32 size data`,
|
||||||
|
// terminated by an empty name — one short read, no pixel decode.
|
||||||
|
//
|
||||||
|
// Returns null when the file is unreadable or carries no timecode at all.
|
||||||
|
function readExrTimecode(file) {
|
||||||
|
var EXR_HEADER_BYTES = 65536;
|
||||||
|
var EXR_MAGIC = 20000630;
|
||||||
|
var buf = null;
|
||||||
|
var opened = false;
|
||||||
|
var pos = 8;
|
||||||
|
var packed = null;
|
||||||
|
var text = null;
|
||||||
|
var name;
|
||||||
|
var type;
|
||||||
|
var size;
|
||||||
|
|
||||||
|
if (!file || !file.exists) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
file.encoding = "BINARY";
|
||||||
|
opened = file.open("r");
|
||||||
|
if (opened) {
|
||||||
|
buf = file.read(EXR_HEADER_BYTES);
|
||||||
|
}
|
||||||
|
} catch (readError) {
|
||||||
|
buf = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
if (opened) {
|
||||||
|
file.close();
|
||||||
|
}
|
||||||
|
} catch (closeError) {
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!buf || buf.length < 16 || readUInt32LE(buf, 0) !== EXR_MAGIC) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
while (pos < buf.length) {
|
||||||
|
name = readExrString(buf, pos);
|
||||||
|
if (name === null) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
pos += name.length + 1;
|
||||||
|
if (name.length === 0) {
|
||||||
|
break; // an empty name ends the header
|
||||||
|
}
|
||||||
|
|
||||||
|
type = readExrString(buf, pos);
|
||||||
|
if (type === null) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
pos += type.length + 1;
|
||||||
|
|
||||||
|
if (pos + 4 > buf.length) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
size = readInt32LE(buf, pos);
|
||||||
|
pos += 4;
|
||||||
|
if (size < 0 || pos + size > buf.length) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (name === "timeCode" && size >= 8) {
|
||||||
|
packed = decodePackedTimecode(buf, pos);
|
||||||
|
} else if (name === "timeCodeString" && size >= 11) {
|
||||||
|
text = parseTimecodeText(buf.substr(pos, size).replace(/\0+$/, ""));
|
||||||
|
}
|
||||||
|
|
||||||
|
pos += size;
|
||||||
|
}
|
||||||
|
|
||||||
|
// The packed attribute is the authoritative one; timeCodeString is a
|
||||||
|
// convenience copy that some writers emit and others omit.
|
||||||
|
return packed || text;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Non-drop frame count, mirroring Timecode.ToFrames in the worker. The show
|
||||||
|
// rate is the authority — a plate's own rate is whatever happens to be on
|
||||||
|
// disk, and plates are conformed to the show rate on import.
|
||||||
|
function timecodeToFrames(tc, fps) {
|
||||||
|
var rate = Math.round(resolveFps(fps));
|
||||||
|
|
||||||
|
return ((tc.hours * 60 + tc.minutes) * 60 + tc.seconds) * rate + tc.frames;
|
||||||
|
}
|
||||||
|
|
||||||
|
// The plate's own start timecode, ranked the way validation ranks it
|
||||||
|
// (RenderPipeline2 §8.1a): the EXR header's embedded timecode first, then
|
||||||
|
// AE's own read of the footage metadata, and only then the API's source clip
|
||||||
|
// timecode less the handle frames — the convention the Set Start Timecode
|
||||||
|
// button uses. The API value is the editorial in-point and sits a
|
||||||
|
// handle-length ahead of the plate by design, so it is the last resort
|
||||||
|
// rather than the first.
|
||||||
function getFootageStartFrames(footageItem, apiShot, fps) {
|
function getFootageStartFrames(footageItem, apiShot, fps) {
|
||||||
var probed = probeFootageStartFrames(footageItem, fps);
|
var exrTc = readExrTimecode(getFootageFirstFile(footageItem));
|
||||||
|
var probed;
|
||||||
var frames;
|
var frames;
|
||||||
|
|
||||||
|
if (exrTc) {
|
||||||
|
frames = timecodeToFrames(exrTc, fps);
|
||||||
|
if (frames > 0) {
|
||||||
|
return {
|
||||||
|
frames: frames,
|
||||||
|
source: "EXR timecode " + exrTc.text +
|
||||||
|
(exrTc.dropFrame ? " (drop-frame flag set on the plate)" : "")
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
probed = probeFootageStartFrames(footageItem, fps);
|
||||||
if (probed !== null && probed > 0) {
|
if (probed !== null && probed > 0) {
|
||||||
return { frames: probed, source: "footage metadata" };
|
return { frames: probed, source: "footage metadata" };
|
||||||
}
|
}
|
||||||
@@ -1069,7 +1289,10 @@ var PANEL_VERSION = "2.5.0";
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return { frames: 0, source: probed === 0 ? "footage starts at 00:00:00:00" : "no timecode found" };
|
return {
|
||||||
|
frames: 0,
|
||||||
|
source: (exrTc || probed === 0) ? "the plate starts at 00:00:00:00" : "no timecode found"
|
||||||
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
function findComp(name) {
|
function findComp(name) {
|
||||||
@@ -1914,7 +2137,9 @@ var PANEL_VERSION = "2.5.0";
|
|||||||
diagLog("start frame " + startInfo.frames + " from " + startInfo.source);
|
diagLog("start frame " + startInfo.frames + " from " + startInfo.source);
|
||||||
|
|
||||||
footageComp = app.project.items.addComp(shotCode + "_FOOTAGE", width, height, 1, maxDuration, fps);
|
footageComp = app.project.items.addComp(shotCode + "_FOOTAGE", width, height, 1, maxDuration, fps);
|
||||||
setCompStartFrame(footageComp, startInfo.frames);
|
if (!setCompStartFrame(footageComp, startInfo.frames)) {
|
||||||
|
diagLog("could not set the start frame on " + footageComp.name + " - it will read 00:00:00:00");
|
||||||
|
}
|
||||||
if (precompFolder) {
|
if (precompFolder) {
|
||||||
footageComp.parentFolder = precompFolder;
|
footageComp.parentFolder = precompFolder;
|
||||||
}
|
}
|
||||||
@@ -1925,7 +2150,9 @@ var PANEL_VERSION = "2.5.0";
|
|||||||
}
|
}
|
||||||
|
|
||||||
shotComp = app.project.items.addComp(shotCode, width, height, 1, maxDuration, fps);
|
shotComp = app.project.items.addComp(shotCode, width, height, 1, maxDuration, fps);
|
||||||
setCompStartFrame(shotComp, startInfo.frames);
|
if (!setCompStartFrame(shotComp, startInfo.frames)) {
|
||||||
|
diagLog("could not set the start frame on " + shotComp.name + " - it will read 00:00:00:00");
|
||||||
|
}
|
||||||
if (episodeProjectFolder) {
|
if (episodeProjectFolder) {
|
||||||
shotComp.parentFolder = episodeProjectFolder;
|
shotComp.parentFolder = episodeProjectFolder;
|
||||||
} else {
|
} else {
|
||||||
@@ -3251,6 +3478,9 @@ var PANEL_VERSION = "2.5.0";
|
|||||||
CONFIG.bannerImagePath = trimText(fBanner.text);
|
CONFIG.bannerImagePath = trimText(fBanner.text);
|
||||||
CONFIG.artistEmail = trimText(fEmail.text);
|
CONFIG.artistEmail = trimText(fEmail.text);
|
||||||
CONFIG.handleFrames = parseInt(fHandles.text, 10) || 8;
|
CONFIG.handleFrames = parseInt(fHandles.text, 10) || 8;
|
||||||
|
if (uiState.handleFramesField) {
|
||||||
|
uiState.handleFramesField.text = String(CONFIG.handleFrames);
|
||||||
|
}
|
||||||
CONFIG.pathMappings = trimText(fMappings.text);
|
CONFIG.pathMappings = trimText(fMappings.text);
|
||||||
CONFIG.sequenceStart = parseInt(fSeqStart.text, 10) || 1001;
|
CONFIG.sequenceStart = parseInt(fSeqStart.text, 10) || 1001;
|
||||||
saveConfig();
|
saveConfig();
|
||||||
@@ -3636,13 +3866,34 @@ var PANEL_VERSION = "2.5.0";
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// A scheduled task outlives the panel instance that armed it. Held only in
|
||||||
|
// this closure, the id of a repeating task goes with the instance when the
|
||||||
|
// panel is closed or reloaded, and nothing can cancel it again: it fires
|
||||||
|
// every 15 s for the rest of the AE session, and every tick that lands
|
||||||
|
// while a modal dialog is open raises "Cannot run a script while a modal
|
||||||
|
// dialog is waiting for response." The id therefore lives beside the tick
|
||||||
|
// in global scope, where the next instance can still reach it.
|
||||||
|
var POLL_TASK_ID_KEY = "__vfxrExportPollTaskId";
|
||||||
|
|
||||||
|
function getPollTaskId() {
|
||||||
|
var taskId = $.global[POLL_TASK_ID_KEY];
|
||||||
|
|
||||||
|
return (typeof taskId === "number" && taskId > 0) ? taskId : 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
function setPollTaskId(taskId) {
|
||||||
|
$.global[POLL_TASK_ID_KEY] = taskId || 0;
|
||||||
|
}
|
||||||
|
|
||||||
function stopExportPolling() {
|
function stopExportPolling() {
|
||||||
if (pipelineState.pollTaskId) {
|
var taskId = getPollTaskId();
|
||||||
|
|
||||||
|
if (taskId) {
|
||||||
try {
|
try {
|
||||||
app.cancelTask(pipelineState.pollTaskId);
|
app.cancelTask(taskId);
|
||||||
} catch (cancelError) {
|
} catch (cancelError) {
|
||||||
}
|
}
|
||||||
pipelineState.pollTaskId = 0;
|
setPollTaskId(0);
|
||||||
}
|
}
|
||||||
pipelineState.pollShotCode = null;
|
pipelineState.pollShotCode = null;
|
||||||
}
|
}
|
||||||
@@ -3676,9 +3927,9 @@ var PANEL_VERSION = "2.5.0";
|
|||||||
stopExportPolling();
|
stopExportPolling();
|
||||||
pipelineState.pollShotCode = shotCode;
|
pipelineState.pollShotCode = shotCode;
|
||||||
try {
|
try {
|
||||||
pipelineState.pollTaskId = app.scheduleTask("__vfxrExportPollTick()", 15000, true);
|
setPollTaskId(app.scheduleTask("__vfxrExportPollTick()", 15000, true));
|
||||||
} catch (scheduleError) {
|
} catch (scheduleError) {
|
||||||
pipelineState.pollTaskId = 0;
|
setPollTaskId(0);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -3950,7 +4201,23 @@ var PANEL_VERSION = "2.5.0";
|
|||||||
return manifest;
|
return manifest;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Handles the render carries past the cut. Review metadata only: the web
|
||||||
|
// player marks these frames as "not in edit". Nothing in the comp or the
|
||||||
|
// render changes — unticked just means the frames are all in the edit.
|
||||||
|
function reviewHandles() {
|
||||||
|
var frames;
|
||||||
|
if (!uiState.handlesCheckbox || !uiState.handlesCheckbox.value) {
|
||||||
|
return { handleHead: 0, handleTail: 0 };
|
||||||
|
}
|
||||||
|
frames = parseInt(uiState.handleFramesField ? uiState.handleFramesField.text : "", 10);
|
||||||
|
if (isNaN(frames) || frames < 0) {
|
||||||
|
frames = CONFIG.handleFrames;
|
||||||
|
}
|
||||||
|
return { handleHead: frames, handleTail: frames };
|
||||||
|
}
|
||||||
|
|
||||||
function submitExport(manifest, urgent, force) {
|
function submitExport(manifest, urgent, force) {
|
||||||
|
manifest.review = reviewHandles();
|
||||||
var body = {
|
var body = {
|
||||||
manifest: manifest,
|
manifest: manifest,
|
||||||
force: force ? true : false
|
force: force ? true : false
|
||||||
@@ -4174,8 +4441,13 @@ var PANEL_VERSION = "2.5.0";
|
|||||||
// catching mask slips, export glitches and metadata faults at full res, so
|
// catching mask slips, export glitches and metadata faults at full res, so
|
||||||
// selecting a queue entry imports the real sequence.
|
// selecting a queue entry imports the real sequence.
|
||||||
|
|
||||||
|
// The queue endpoint defaults to 50 rows and refuses anything above 200, so
|
||||||
|
// ask for the ceiling: a busy project can have well over 50 exports sitting
|
||||||
|
// in READY_FOR_QC, and the panel silently showed only the oldest 50.
|
||||||
|
var QC_QUEUE_LIMIT = 200;
|
||||||
|
|
||||||
function loadQCQueue() {
|
function loadQCQueue() {
|
||||||
var url = CONFIG.baseUrl + "/api/ext/qc/queue";
|
var url = CONFIG.baseUrl + "/api/ext/qc/queue?limit=" + QC_QUEUE_LIMIT;
|
||||||
var data;
|
var data;
|
||||||
var entries;
|
var entries;
|
||||||
var i;
|
var i;
|
||||||
@@ -4186,7 +4458,7 @@ var PANEL_VERSION = "2.5.0";
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (CURRENT_PROJECT) {
|
if (CURRENT_PROJECT) {
|
||||||
url += "?projectCode=" + encodeURIComponent(CURRENT_PROJECT.code);
|
url += "&projectCode=" + encodeURIComponent(CURRENT_PROJECT.code);
|
||||||
}
|
}
|
||||||
|
|
||||||
setQCStatus("Loading QC queue...");
|
setQCStatus("Loading QC queue...");
|
||||||
@@ -4211,7 +4483,8 @@ var PANEL_VERSION = "2.5.0";
|
|||||||
|
|
||||||
if (entries.length) {
|
if (entries.length) {
|
||||||
uiState.qcList.selection = 0;
|
uiState.qcList.selection = 0;
|
||||||
setQCStatus(entries.length + " export(s) awaiting QC");
|
setQCStatus(entries.length + " export(s) awaiting QC" +
|
||||||
|
(entries.length >= QC_QUEUE_LIMIT ? " (list is capped — QC some and reload)" : ""));
|
||||||
} else {
|
} else {
|
||||||
setQCStatus("Nothing waiting for QC");
|
setQCStatus("Nothing waiting for QC");
|
||||||
}
|
}
|
||||||
@@ -4437,7 +4710,6 @@ var PANEL_VERSION = "2.5.0";
|
|||||||
var importRendersButton;
|
var importRendersButton;
|
||||||
var btnRow6;
|
var btnRow6;
|
||||||
var pictureLockButton;
|
var pictureLockButton;
|
||||||
var btnRow7;
|
|
||||||
var incrementVersionButton;
|
var incrementVersionButton;
|
||||||
var btnRow6b;
|
var btnRow6b;
|
||||||
var setStartTCButton;
|
var setStartTCButton;
|
||||||
@@ -4551,6 +4823,25 @@ var PANEL_VERSION = "2.5.0";
|
|||||||
"un-punched-in EXRs — where a preview rebuilt from these frames\n" +
|
"un-punched-in EXRs — where a preview rebuilt from these frames\n" +
|
||||||
"would be the wrong picture.";
|
"would be the wrong picture.";
|
||||||
|
|
||||||
|
var handlesGroup = pipelinePanel.add("group");
|
||||||
|
handlesGroup.orientation = "row";
|
||||||
|
handlesGroup.alignChildren = ["left", "center"];
|
||||||
|
handlesGroup.spacing = 6;
|
||||||
|
uiState.handlesCheckbox = handlesGroup.add("checkbox", undefined, "Includes handles");
|
||||||
|
uiState.handlesCheckbox.value = true;
|
||||||
|
uiState.handleFramesField = handlesGroup.add("edittext", undefined, String(CONFIG.handleFrames));
|
||||||
|
uiState.handleFramesField.characters = 3;
|
||||||
|
handlesGroup.add("statictext", undefined, "frames each end");
|
||||||
|
uiState.handlesCheckbox.helpTip =
|
||||||
|
"The render runs past the cut at both ends (handles). The review\n" +
|
||||||
|
"player marks those frames HANDLE / NOT IN EDIT so a glitch in a\n" +
|
||||||
|
"handle isn't mistaken for a problem in the shot.\n\n" +
|
||||||
|
"Review-only: nothing is burned in and the EXRs are unchanged.\n" +
|
||||||
|
"Untick for a render cut exactly to the edit.";
|
||||||
|
uiState.handlesCheckbox.onClick = function () {
|
||||||
|
uiState.handleFramesField.enabled = uiState.handlesCheckbox.value;
|
||||||
|
};
|
||||||
|
|
||||||
var slateNoteGroup = pipelinePanel.add("group");
|
var slateNoteGroup = pipelinePanel.add("group");
|
||||||
slateNoteGroup.orientation = "row";
|
slateNoteGroup.orientation = "row";
|
||||||
slateNoteGroup.alignChildren = ["fill", "top"];
|
slateNoteGroup.alignChildren = ["fill", "top"];
|
||||||
@@ -4576,6 +4867,7 @@ var PANEL_VERSION = "2.5.0";
|
|||||||
"Rebuild the MOV/MP4 slate and burn-ins for the delivered version.\n" +
|
"Rebuild the MOV/MP4 slate and burn-ins for the delivered version.\n" +
|
||||||
"Reuses the rendered EXRs and keeps the version number. Slate text is\n" +
|
"Reuses the rendered EXRs and keeps the version number. Slate text is\n" +
|
||||||
"re-read from the shot, so fix it on the web app's Slate tab first.";
|
"re-read from the shot, so fix it on the web app's Slate tab first.";
|
||||||
|
incrementVersionButton = pipelineRow3.add("button", undefined, "Increment Shot Version");
|
||||||
|
|
||||||
qcPanel = scrollContent.add("panel", undefined, "QC");
|
qcPanel = scrollContent.add("panel", undefined, "QC");
|
||||||
qcPanel.orientation = "column";
|
qcPanel.orientation = "column";
|
||||||
@@ -4682,12 +4974,6 @@ var PANEL_VERSION = "2.5.0";
|
|||||||
btnRow6b.spacing = 6;
|
btnRow6b.spacing = 6;
|
||||||
setStartTCButton = btnRow6b.add("button", undefined, "Set Start Timecode");
|
setStartTCButton = btnRow6b.add("button", undefined, "Set Start Timecode");
|
||||||
|
|
||||||
btnRow7 = buttonsPanel.add("group");
|
|
||||||
btnRow7.orientation = "row";
|
|
||||||
btnRow7.alignChildren = ["fill", "center"];
|
|
||||||
btnRow7.spacing = 6;
|
|
||||||
incrementVersionButton = btnRow7.add("button", undefined, "Increment Shot Version");
|
|
||||||
|
|
||||||
workspacePanel = scrollContent.add("panel", undefined, "Workspace");
|
workspacePanel = scrollContent.add("panel", undefined, "Workspace");
|
||||||
workspacePanel.orientation = "column";
|
workspacePanel.orientation = "column";
|
||||||
workspacePanel.alignChildren = ["fill", "top"];
|
workspacePanel.alignChildren = ["fill", "top"];
|
||||||
@@ -4797,6 +5083,11 @@ var PANEL_VERSION = "2.5.0";
|
|||||||
return win;
|
return win;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// A previous instance may have left a repeating poll armed, and its shot
|
||||||
|
// code went with that closure. Cancel it before the tick is pointed at this
|
||||||
|
// instance, rather than letting it fire into a fresh, empty state.
|
||||||
|
stopExportPolling();
|
||||||
|
|
||||||
// app.scheduleTask evaluates in global scope — expose the poll tick there
|
// app.scheduleTask evaluates in global scope — expose the poll tick there
|
||||||
$.global.__vfxrExportPollTick = pollExportTick;
|
$.global.__vfxrExportPollTick = pollExportTick;
|
||||||
|
|
||||||
@@ -4807,6 +5098,13 @@ var PANEL_VERSION = "2.5.0";
|
|||||||
diagLog("panel v" + PANEL_VERSION + " loaded on " + getHostName());
|
diagLog("panel v" + PANEL_VERSION + " loaded on " + getHostName());
|
||||||
reportPanelVersion();
|
reportPanelVersion();
|
||||||
|
|
||||||
|
// Closing the panel leaves an armed task running with no UI left to update.
|
||||||
|
// The export itself is unaffected: it runs on the farm, and the panel picks
|
||||||
|
// its status back up from the server on the next Refresh.
|
||||||
|
panel.onClose = function () {
|
||||||
|
stopExportPolling();
|
||||||
|
};
|
||||||
|
|
||||||
if (panel instanceof Window) {
|
if (panel instanceof Window) {
|
||||||
panel.center();
|
panel.center();
|
||||||
panel.show();
|
panel.show();
|
||||||
|
|||||||
+26
-5
@@ -178,7 +178,7 @@ Same applies to `footageRoot`: change `V:/_FOOTAGE/UNG` → `V:/_FOOTAGE`.
|
|||||||
The panel is divided into seven sections:
|
The panel is divided into seven sections:
|
||||||
|
|
||||||
1. **Shot Builder** — Episode/shot selection and comp creation
|
1. **Shot Builder** — Episode/shot selection and comp creation
|
||||||
2. **Render Pipeline** — Queue Export, status polling, retry, regenerate previews
|
2. **Render Pipeline** — Queue Export, status polling, retry, regenerate previews, increment shot version
|
||||||
3. **QC** — Technical QC queue for rendered exports
|
3. **QC** — Technical QC queue for rendered exports
|
||||||
4. **Actions** — Per-shot and batch operations
|
4. **Actions** — Per-shot and batch operations
|
||||||
5. **Workspace** — One-time project initialisation
|
5. **Workspace** — One-time project initialisation
|
||||||
@@ -201,16 +201,37 @@ Constructs a full shot composite in the open AE project from the episode and sho
|
|||||||
**Process:**
|
**Process:**
|
||||||
1. Calls the shot lookup API to retrieve metadata (description, notes, episode, scene, etc.).
|
1. Calls the shot lookup API to retrieve metadata (description, notes, episode, scene, etc.).
|
||||||
2. If a comp with the shot code already exists, updates its overlay instead of rebuilding.
|
2. If a comp with the shot code already exists, updates its overlay instead of rebuilding.
|
||||||
3. Scans `FOOTAGE_ROOT/{episodeCode}/` for subfolders matching `{shotCode}_*` and imports each as an EXR image sequence at 24 fps.
|
3. Scans `FOOTAGE_ROOT/{episodeCode}/` for subfolders matching `{shotCode}_*` and imports each as an EXR image sequence, conformed to the shot's frame rate.
|
||||||
4. Creates a `{shotCode}_FOOTAGE` precomp containing all imported sequences, each with an OCIO Color Space Transform effect added (disabled by default).
|
4. Creates a `{shotCode}_FOOTAGE` precomp containing all imported sequences, each with an OCIO Color Space Transform effect added (disabled by default).
|
||||||
5. Creates the main `{shotCode}` comp and places the footage precomp inside it.
|
5. Creates the main `{shotCode}` comp and places the footage precomp inside it.
|
||||||
6. If a `_SHOW LUT` comp exists in the project, adds it as a collapsed layer on top.
|
6. Anchors both comps on the plate's start timecode — see [Start timecode](#start-timecode).
|
||||||
7. Calls **Add Overlay** logic to attach the `UNG_VFX_OVERLAY` comp.
|
7. If a `_SHOW LUT` comp exists in the project, adds it as a collapsed layer on top.
|
||||||
8. Organises items into `__SHOTS/{episodeCode}`, `_FOOTAGE_4K`, and `_PRECOMPS` project folders.
|
8. Calls **Add Overlay** logic to attach the `UNG_VFX_OVERLAY` comp.
|
||||||
|
9. Organises items into `__SHOTS/{episodeCode}`, `_FOOTAGE_4K`, and `_PRECOMPS` project folders.
|
||||||
|
|
||||||
If any step fails, the status line names the stage and a copyable report opens —
|
If any step fails, the status line names the stage and a copyable report opens —
|
||||||
see [Diagnostics and logging](#diagnostics-and-logging).
|
see [Diagnostics and logging](#diagnostics-and-logging).
|
||||||
|
|
||||||
|
#### Start timecode
|
||||||
|
|
||||||
|
Neither comp starts at `00:00:00:00`. Both are anchored on the plate's own start
|
||||||
|
timecode, taken from the first source that has one:
|
||||||
|
|
||||||
|
| Rank | Source | Notes |
|
||||||
|
|---|---|---|
|
||||||
|
| 1 | The first EXR's header | The `timeCode` attribute, or `timeCodeString` where the packed one is absent. Read straight off disk — no pixel decode, and no dependency on what AE chose to expose. |
|
||||||
|
| 2 | AE's footage metadata | What "New Comp from Selection" would have inherited. |
|
||||||
|
| 3 | API `timecodeStart` less `handleFrames` | The convention **Set Start Timecode** uses. Last resort: the API stores the *editorial* in-point, which is a handle-length ahead of the plate by design. |
|
||||||
|
|
||||||
|
This is the same ranking the render worker's validation uses (RenderPipeline2
|
||||||
|
§8.1a), so a comp is anchored on exactly the value its EXRs are later checked
|
||||||
|
against — a shot built from rank 3 and validated against rank 1 is how a
|
||||||
|
timecode desync gets into a delivery.
|
||||||
|
|
||||||
|
The status line and the diagnostics log both name the rank that was used, e.g.
|
||||||
|
`start frame 864108 from EXR timecode 10:00:04:12`. A plate carrying no timecode
|
||||||
|
in any rank leaves the comp at `00:00:00:00` and says so.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## Render Pipeline
|
## Render Pipeline
|
||||||
|
|||||||
@@ -14,7 +14,7 @@ const saveAnnotationSchema = z.object({
|
|||||||
shapes: z.array(z.any()),
|
shapes: z.array(z.any()),
|
||||||
canvasWidth: z.number(),
|
canvasWidth: z.number(),
|
||||||
canvasHeight: z.number(),
|
canvasHeight: z.number(),
|
||||||
version: z.literal("1.0"),
|
version: z.enum(["1.0", "2.0"]),
|
||||||
}),
|
}),
|
||||||
color: z.string().default("#ef4444"),
|
color: z.string().default("#ef4444"),
|
||||||
});
|
});
|
||||||
|
|||||||
+82
-72
@@ -5,7 +5,7 @@ import { db } from "@/lib/db";
|
|||||||
import { revalidatePath } from "next/cache";
|
import { revalidatePath } from "next/cache";
|
||||||
import { z } from "zod";
|
import { z } from "zod";
|
||||||
import { ApprovalStatus } from "@prisma/client";
|
import { ApprovalStatus } from "@prisma/client";
|
||||||
import { recalcShotStatus } from "@/lib/shot-status";
|
import { recalcShotStatus, clearStaleShotApproval } from "@/lib/shot-status";
|
||||||
import { notifyApprovalChange } from "@/lib/notifications";
|
import { notifyApprovalChange } from "@/lib/notifications";
|
||||||
import { slackNotifyApproval } from "@/lib/slack";
|
import { slackNotifyApproval } from "@/lib/slack";
|
||||||
import { versionLabel } from "@/lib/utils";
|
import { versionLabel } from "@/lib/utils";
|
||||||
@@ -29,57 +29,62 @@ export async function submitApproval(data: z.infer<typeof approvalSchema>) {
|
|||||||
throw new Error("Insufficient permissions to review versions");
|
throw new Error("Insufficient permissions to review versions");
|
||||||
}
|
}
|
||||||
|
|
||||||
// Create the approval record
|
// The verdict, the version, the task and the derived shot status are one
|
||||||
const approval = await db.approval.create({
|
// decision and are written as one: a failure partway through used to leave the
|
||||||
data: {
|
// three layers disagreeing, with no way to tell which one was right.
|
||||||
versionId: parsed.versionId,
|
const { approval, version } = await db.$transaction(async (tx) => {
|
||||||
userId: session.user.id,
|
const approval = await tx.approval.create({
|
||||||
status: parsed.status,
|
data: {
|
||||||
notes: parsed.notes,
|
versionId: parsed.versionId,
|
||||||
},
|
userId: session.user.id,
|
||||||
});
|
status: parsed.status,
|
||||||
|
notes: parsed.notes,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
// Update version approval status
|
await tx.version.update({
|
||||||
await db.version.update({
|
where: { id: parsed.versionId },
|
||||||
where: { id: parsed.versionId },
|
data: { approvalStatus: parsed.status },
|
||||||
data: { approvalStatus: parsed.status },
|
});
|
||||||
});
|
|
||||||
|
|
||||||
// Load version + task + shot + project for downstream effects
|
// Load version + task + shot + project for downstream effects
|
||||||
const version = await db.version.findUnique({
|
const version = await tx.version.findUnique({
|
||||||
where: { id: parsed.versionId },
|
where: { id: parsed.versionId },
|
||||||
include: {
|
include: {
|
||||||
task: {
|
task: {
|
||||||
include: {
|
include: {
|
||||||
shot: true,
|
shot: true,
|
||||||
project: true,
|
project: true,
|
||||||
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
},
|
});
|
||||||
|
|
||||||
|
if (!version) throw new Error("Version not found");
|
||||||
|
|
||||||
|
// Update task status based on approval result
|
||||||
|
if (version.task && parsed.status !== "PENDING_REVIEW") {
|
||||||
|
if (parsed.status === "APPROVED") {
|
||||||
|
await tx.task.update({
|
||||||
|
where: { id: version.task.id },
|
||||||
|
data: { status: "DONE" },
|
||||||
|
});
|
||||||
|
} else if (parsed.status === "REJECTED" || parsed.status === "NEEDS_CHANGES") {
|
||||||
|
await tx.task.update({
|
||||||
|
where: { id: version.task.id },
|
||||||
|
data: { status: "CHANGES" },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Recalculate shot status from updated task states
|
||||||
|
if (version.task.shot) {
|
||||||
|
await recalcShotStatus(version.task.shot.id, tx);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return { approval, version };
|
||||||
});
|
});
|
||||||
|
|
||||||
if (!version) throw new Error("Version not found");
|
|
||||||
|
|
||||||
// Update task status based on approval result
|
|
||||||
if (version.task && parsed.status !== "PENDING_REVIEW") {
|
|
||||||
if (parsed.status === "APPROVED") {
|
|
||||||
await db.task.update({
|
|
||||||
where: { id: version.task.id },
|
|
||||||
data: { status: "DONE" },
|
|
||||||
});
|
|
||||||
} else if (parsed.status === "REJECTED" || parsed.status === "NEEDS_CHANGES") {
|
|
||||||
await db.task.update({
|
|
||||||
where: { id: version.task.id },
|
|
||||||
data: { status: "CHANGES" },
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
// Recalculate shot status from updated task states
|
|
||||||
if (version.task.shot) {
|
|
||||||
await recalcShotStatus(version.task.shot.id).catch(() => {});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Notifications
|
// Notifications
|
||||||
const reviewer = await db.user.findUnique({ where: { id: session.user.id } });
|
const reviewer = await db.user.findUnique({ where: { id: session.user.id } });
|
||||||
const reviewerName = reviewer?.name ?? "Reviewer";
|
const reviewerName = reviewer?.name ?? "Reviewer";
|
||||||
@@ -166,34 +171,39 @@ export async function unapproveVersion(versionId: string) {
|
|||||||
throw new Error("Only approved versions can be unapproved");
|
throw new Error("Only approved versions can be unapproved");
|
||||||
}
|
}
|
||||||
|
|
||||||
// Create an audit record for the unapproval
|
// One decision, one write — same reasoning as submitApproval.
|
||||||
await db.approval.create({
|
await db.$transaction(async (tx) => {
|
||||||
data: {
|
// Create an audit record for the unapproval
|
||||||
versionId,
|
await tx.approval.create({
|
||||||
userId: session.user.id,
|
data: {
|
||||||
status: "PENDING_REVIEW",
|
versionId,
|
||||||
notes: "Approval undone",
|
userId: session.user.id,
|
||||||
},
|
status: "PENDING_REVIEW",
|
||||||
});
|
notes: "Approval undone",
|
||||||
|
},
|
||||||
// Reset version approval status
|
|
||||||
await db.version.update({
|
|
||||||
where: { id: versionId },
|
|
||||||
data: { approvalStatus: "PENDING_REVIEW" },
|
|
||||||
});
|
|
||||||
|
|
||||||
// Reset task back to INTERNAL_REVIEW if it was moved to DONE
|
|
||||||
if (version.task && version.task.status === "DONE") {
|
|
||||||
await db.task.update({
|
|
||||||
where: { id: version.task.id },
|
|
||||||
data: { status: "INTERNAL_REVIEW" },
|
|
||||||
});
|
});
|
||||||
}
|
|
||||||
|
|
||||||
// Recalculate shot status
|
// Reset version approval status
|
||||||
if (version.task?.shot) {
|
await tx.version.update({
|
||||||
await recalcShotStatus(version.task.shot.id).catch(() => {});
|
where: { id: versionId },
|
||||||
}
|
data: { approvalStatus: "PENDING_REVIEW" },
|
||||||
|
});
|
||||||
|
|
||||||
|
// Reset task back to INTERNAL_REVIEW if it was moved to DONE
|
||||||
|
if (version.task && version.task.status === "DONE") {
|
||||||
|
await tx.task.update({
|
||||||
|
where: { id: version.task.id },
|
||||||
|
data: { status: "INTERNAL_REVIEW" },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Undoing a version approval also invalidates any shot-level sign-off that
|
||||||
|
// rested on it, otherwise the shot keeps reading COMPLETE / READY_FOR_CLIENT.
|
||||||
|
if (version.task?.shot) {
|
||||||
|
await clearStaleShotApproval(tx, version.task.shot.id);
|
||||||
|
await recalcShotStatus(version.task.shot.id, tx);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
revalidatePath(`/review/${versionId}`);
|
revalidatePath(`/review/${versionId}`);
|
||||||
if (version.task) {
|
if (version.task) {
|
||||||
|
|||||||
@@ -0,0 +1,196 @@
|
|||||||
|
"use server";
|
||||||
|
|
||||||
|
import { auth } from "@/auth";
|
||||||
|
import { db } from "@/lib/db";
|
||||||
|
import { revalidatePath } from "next/cache";
|
||||||
|
import { z } from "zod";
|
||||||
|
import { findShot, parseBoardText } from "@/lib/board-parse";
|
||||||
|
|
||||||
|
// The board is studio-internal. Anyone on staff can add and tick off lines;
|
||||||
|
// it is a shared to-do list, not an approval surface.
|
||||||
|
async function requireStaff() {
|
||||||
|
const session = await auth();
|
||||||
|
if (!session?.user) throw new Error("Unauthorized");
|
||||||
|
if (session.user.role === "CLIENT") throw new Error("Insufficient permissions");
|
||||||
|
return session.user;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function boardContext(projectId: string) {
|
||||||
|
const [shots, users] = await Promise.all([
|
||||||
|
db.shot.findMany({
|
||||||
|
where: { projectId },
|
||||||
|
select: { id: true, shotCode: true, clientCode: true },
|
||||||
|
}),
|
||||||
|
db.user.findMany({
|
||||||
|
where: { isActive: true, role: { not: "CLIENT" } },
|
||||||
|
select: { id: true, name: true, email: true },
|
||||||
|
}),
|
||||||
|
]);
|
||||||
|
return { shots, users };
|
||||||
|
}
|
||||||
|
|
||||||
|
const addSchema = z.object({
|
||||||
|
projectId: z.string().cuid(),
|
||||||
|
input: z.string().min(1).max(20000),
|
||||||
|
group: z.string().max(100).optional(),
|
||||||
|
});
|
||||||
|
|
||||||
|
/** Adds one line, or a pasted block of lines, to a project's board. */
|
||||||
|
export async function addBoardItems(data: z.infer<typeof addSchema>) {
|
||||||
|
const user = await requireStaff();
|
||||||
|
const parsed = addSchema.parse(data);
|
||||||
|
|
||||||
|
const items = parseBoardText(parsed.input, {
|
||||||
|
...(await boardContext(parsed.projectId)),
|
||||||
|
group: parsed.group,
|
||||||
|
});
|
||||||
|
if (items.length === 0) return { success: true, added: 0, unmatched: [] as string[] };
|
||||||
|
|
||||||
|
const last = await db.boardItem.findFirst({
|
||||||
|
where: { projectId: parsed.projectId },
|
||||||
|
orderBy: { sortOrder: "desc" },
|
||||||
|
select: { sortOrder: true },
|
||||||
|
});
|
||||||
|
const base = (last?.sortOrder ?? -1) + 1;
|
||||||
|
|
||||||
|
await db.boardItem.createMany({
|
||||||
|
data: items.map((item, i) => ({
|
||||||
|
projectId: parsed.projectId,
|
||||||
|
shotId: item.shotId,
|
||||||
|
code: item.code,
|
||||||
|
text: item.text,
|
||||||
|
group: item.group,
|
||||||
|
assigneeId: item.assigneeId,
|
||||||
|
waitingOn: item.waitingOn,
|
||||||
|
sortOrder: base + i,
|
||||||
|
createdById: user.id,
|
||||||
|
})),
|
||||||
|
});
|
||||||
|
|
||||||
|
revalidatePath("/board");
|
||||||
|
return {
|
||||||
|
success: true,
|
||||||
|
added: items.length,
|
||||||
|
unmatched: items.filter((i) => i.code && !i.shotId).map((i) => i.code as string),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const updateSchema = z.object({
|
||||||
|
text: z.string().max(5000).optional(),
|
||||||
|
code: z.string().max(100).nullable().optional(),
|
||||||
|
group: z.string().max(100).optional(),
|
||||||
|
assigneeId: z.string().cuid().nullable().optional(),
|
||||||
|
waitingOn: z.string().max(500).nullable().optional(),
|
||||||
|
});
|
||||||
|
|
||||||
|
export async function updateBoardItem(id: string, data: z.infer<typeof updateSchema>) {
|
||||||
|
await requireStaff();
|
||||||
|
const parsed = updateSchema.parse(data);
|
||||||
|
const item = await db.boardItem.findUnique({ where: { id }, select: { projectId: true } });
|
||||||
|
if (!item) throw new Error("Board item not found");
|
||||||
|
|
||||||
|
// Changing the code re-links the line; a code that matches nothing is kept
|
||||||
|
// as a flag, exactly as when it was first typed.
|
||||||
|
let link: { code: string | null; shotId: string | null } | undefined;
|
||||||
|
if (parsed.code !== undefined) {
|
||||||
|
const code = parsed.code?.trim() || null;
|
||||||
|
const shot = code ? findShot(code, (await boardContext(item.projectId)).shots) : null;
|
||||||
|
link = { code: shot?.shotCode ?? code?.toUpperCase() ?? null, shotId: shot?.id ?? null };
|
||||||
|
}
|
||||||
|
|
||||||
|
await db.boardItem.update({
|
||||||
|
where: { id },
|
||||||
|
data: {
|
||||||
|
...(parsed.text !== undefined && { text: parsed.text.trim() }),
|
||||||
|
...(parsed.group !== undefined && { group: parsed.group.trim() }),
|
||||||
|
...(parsed.assigneeId !== undefined && { assigneeId: parsed.assigneeId }),
|
||||||
|
...(parsed.waitingOn !== undefined && { waitingOn: parsed.waitingOn?.trim() || null }),
|
||||||
|
...link,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
revalidatePath("/board");
|
||||||
|
return { success: true };
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function setBoardItemDone(id: string, done: boolean) {
|
||||||
|
const user = await requireStaff();
|
||||||
|
const item = await db.boardItem.update({
|
||||||
|
where: { id },
|
||||||
|
data: done ? { doneAt: new Date(), doneById: user.id } : { doneAt: null, doneById: null },
|
||||||
|
select: { commentId: true },
|
||||||
|
});
|
||||||
|
// A line from pasted feedback is that client note: ticking it off resolves
|
||||||
|
// the comment in the player too. (The comment may have been deleted there.)
|
||||||
|
if (item.commentId) {
|
||||||
|
const comment = await db.comment.updateMany({
|
||||||
|
where: { id: item.commentId },
|
||||||
|
data: { isResolved: done },
|
||||||
|
});
|
||||||
|
if (comment.count) {
|
||||||
|
const c = await db.comment.findUnique({ where: { id: item.commentId }, select: { versionId: true } });
|
||||||
|
if (c) revalidatePath(`/review/${c.versionId}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
revalidatePath("/board");
|
||||||
|
return { success: true };
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function deleteBoardItem(id: string) {
|
||||||
|
await requireStaff();
|
||||||
|
await db.boardItem.delete({ where: { id } });
|
||||||
|
revalidatePath("/board");
|
||||||
|
return { success: true };
|
||||||
|
}
|
||||||
|
|
||||||
|
const statusSchema = z.object({
|
||||||
|
projectId: z.string().cuid(),
|
||||||
|
status: z.string().max(2000),
|
||||||
|
});
|
||||||
|
|
||||||
|
export async function setProjectBoardStatus(data: z.infer<typeof statusSchema>) {
|
||||||
|
await requireStaff();
|
||||||
|
const parsed = statusSchema.parse(data);
|
||||||
|
const status = parsed.status.trim() || null;
|
||||||
|
await db.project.update({
|
||||||
|
where: { id: parsed.projectId },
|
||||||
|
data: { boardStatus: status, boardStatusAt: status ? new Date() : null },
|
||||||
|
});
|
||||||
|
revalidatePath("/board");
|
||||||
|
return { success: true };
|
||||||
|
}
|
||||||
|
|
||||||
|
const milestoneSchema = z.object({
|
||||||
|
projectId: z.string().cuid(),
|
||||||
|
label: z.string().min(1).max(200),
|
||||||
|
date: z.string().min(1),
|
||||||
|
});
|
||||||
|
|
||||||
|
export async function addMilestone(data: z.infer<typeof milestoneSchema>) {
|
||||||
|
await requireStaff();
|
||||||
|
const parsed = milestoneSchema.parse(data);
|
||||||
|
const date = new Date(parsed.date);
|
||||||
|
if (isNaN(date.getTime())) throw new Error("Invalid date");
|
||||||
|
await db.projectMilestone.create({
|
||||||
|
data: { projectId: parsed.projectId, label: parsed.label.trim(), date },
|
||||||
|
});
|
||||||
|
revalidatePath("/board");
|
||||||
|
return { success: true };
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function setMilestoneDone(id: string, done: boolean) {
|
||||||
|
await requireStaff();
|
||||||
|
await db.projectMilestone.update({
|
||||||
|
where: { id },
|
||||||
|
data: { doneAt: done ? new Date() : null },
|
||||||
|
});
|
||||||
|
revalidatePath("/board");
|
||||||
|
return { success: true };
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function deleteMilestone(id: string) {
|
||||||
|
await requireStaff();
|
||||||
|
await db.projectMilestone.delete({ where: { id } });
|
||||||
|
revalidatePath("/board");
|
||||||
|
return { success: true };
|
||||||
|
}
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
"use server";
|
||||||
|
|
||||||
|
import { auth } from "@/auth";
|
||||||
|
import { revalidatePath } from "next/cache";
|
||||||
|
import { z } from "zod";
|
||||||
|
import {
|
||||||
|
getUnreadCommentsForShot,
|
||||||
|
getUnreadCommentSummaries,
|
||||||
|
markShotCommentsRead as markRead,
|
||||||
|
} from "@/lib/comment-reads";
|
||||||
|
|
||||||
|
export async function listUnreadShotComments(shotId: string) {
|
||||||
|
const session = await auth();
|
||||||
|
if (!session?.user) throw new Error("Unauthorized");
|
||||||
|
return getUnreadCommentsForShot(session.user.id, z.string().min(1).parse(shotId));
|
||||||
|
}
|
||||||
|
|
||||||
|
const markSchema = z.object({
|
||||||
|
shotId: z.string().min(1),
|
||||||
|
upTo: z.string().datetime(),
|
||||||
|
});
|
||||||
|
|
||||||
|
export async function markShotCommentsRead(shotId: string, upTo: string) {
|
||||||
|
const session = await auth();
|
||||||
|
if (!session?.user) throw new Error("Unauthorized");
|
||||||
|
const parsed = markSchema.parse({ shotId, upTo });
|
||||||
|
await markRead(session.user.id, parsed.shotId, new Date(parsed.upTo));
|
||||||
|
revalidatePath("/shot-status");
|
||||||
|
return { success: true };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Mark every flagged shot in a project read, up to what each one had when checked. */
|
||||||
|
export async function markProjectCommentsRead(projectId: string) {
|
||||||
|
const session = await auth();
|
||||||
|
if (!session?.user) throw new Error("Unauthorized");
|
||||||
|
const summaries = await getUnreadCommentSummaries(session.user.id, z.string().min(1).parse(projectId));
|
||||||
|
for (const [shotId, s] of Object.entries(summaries)) {
|
||||||
|
await markRead(session.user.id, shotId, new Date(s.latestAt));
|
||||||
|
}
|
||||||
|
revalidatePath("/shot-status");
|
||||||
|
return { success: true, count: Object.keys(summaries).length };
|
||||||
|
}
|
||||||
+13
-11
@@ -4,7 +4,7 @@ import { auth } from "@/auth";
|
|||||||
import { db } from "@/lib/db";
|
import { db } from "@/lib/db";
|
||||||
import { revalidatePath } from "next/cache";
|
import { revalidatePath } from "next/cache";
|
||||||
import { z } from "zod";
|
import { z } from "zod";
|
||||||
import { notifyFeedbackAdded, notifyCommentReply } from "@/lib/notifications";
|
import { notifyCommentsAdded, notifyCommentReply } from "@/lib/notifications";
|
||||||
import { slackNotifyNewFeedback } from "@/lib/slack";
|
import { slackNotifyNewFeedback } from "@/lib/slack";
|
||||||
import { createDisplayEvent } from "@/lib/display-events";
|
import { createDisplayEvent } from "@/lib/display-events";
|
||||||
|
|
||||||
@@ -36,7 +36,6 @@ export async function addComment(data: z.infer<typeof addCommentSchema>) {
|
|||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
// Notify the shot artist if commenter is not the artist
|
|
||||||
const version = await db.version.findUnique({
|
const version = await db.version.findUnique({
|
||||||
where: { id: parsed.versionId },
|
where: { id: parsed.versionId },
|
||||||
include: {
|
include: {
|
||||||
@@ -56,16 +55,19 @@ export async function addComment(data: z.infer<typeof addCommentSchema>) {
|
|||||||
version?.task?.title ??
|
version?.task?.title ??
|
||||||
"Task";
|
"Task";
|
||||||
|
|
||||||
if (version?.shot?.artistId && version.shot.artistId !== session.user.id) {
|
// Staff and the shot's artist — never the commenter. A failed notification
|
||||||
const user = await db.user.findUnique({ where: { id: session.user.id } });
|
// must not fail a comment that is already saved.
|
||||||
await notifyFeedbackAdded({
|
const user = await db.user.findUnique({ where: { id: session.user.id }, select: { name: true } });
|
||||||
artistId: version.shot.artistId,
|
await notifyCommentsAdded({
|
||||||
shotCode: version.shot.shotCode,
|
notes: [{
|
||||||
frameNumber: parsed.frameNumber,
|
|
||||||
versionId: parsed.versionId,
|
versionId: parsed.versionId,
|
||||||
authorName: user?.name ?? session.user.email ?? "Someone",
|
shotCode,
|
||||||
});
|
frameNumber: parsed.frameNumber,
|
||||||
}
|
artistIds: [version?.shot?.artistId, version?.task?.assignedArtistId],
|
||||||
|
}],
|
||||||
|
authorId: session.user.id,
|
||||||
|
authorName: user?.name ?? session.user.email ?? "Someone",
|
||||||
|
}).catch((err) => console.error("[comments] notify failed", err));
|
||||||
|
|
||||||
// Slack notification
|
// Slack notification
|
||||||
if (slackWebhook) {
|
if (slackWebhook) {
|
||||||
|
|||||||
@@ -0,0 +1,43 @@
|
|||||||
|
"use server";
|
||||||
|
|
||||||
|
import { revalidatePath } from "next/cache";
|
||||||
|
import { requirePipelineAdmin } from "@/lib/render-pipeline/session-auth";
|
||||||
|
import { PipelineError } from "@/lib/render-pipeline/errors";
|
||||||
|
import {
|
||||||
|
createMovReviewPackage,
|
||||||
|
previewMovReviewPackage,
|
||||||
|
} from "@/lib/render-pipeline/reviews";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Server actions behind "Build MOV Review Package" on the shot-status page
|
||||||
|
* (RenderPipeline2 §11.6). The heavy lifting lives in lib/render-pipeline;
|
||||||
|
* these only carry the session and turn service errors into messages a toast
|
||||||
|
* can show.
|
||||||
|
*/
|
||||||
|
|
||||||
|
function message(err: unknown): string {
|
||||||
|
if (err instanceof PipelineError) return err.message;
|
||||||
|
return err instanceof Error ? err.message : "Unknown error";
|
||||||
|
}
|
||||||
|
|
||||||
|
/** What the confirm dialog shows: the folder, the resolved versions, the gaps. */
|
||||||
|
export async function previewMovReview(shotIds: string[]) {
|
||||||
|
try {
|
||||||
|
await requirePipelineAdmin();
|
||||||
|
const preview = await previewMovReviewPackage(shotIds);
|
||||||
|
return { ok: true as const, ...preview };
|
||||||
|
} catch (err) {
|
||||||
|
return { ok: false as const, error: message(err) };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function buildMovReview(shotIds: string[]) {
|
||||||
|
try {
|
||||||
|
const user = await requirePipelineAdmin();
|
||||||
|
const result = await createMovReviewPackage({ shotIds }, user.id);
|
||||||
|
revalidatePath("/pipeline/deliveries");
|
||||||
|
return { ok: true as const, ...result };
|
||||||
|
} catch (err) {
|
||||||
|
return { ok: false as const, error: message(err) };
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,277 @@
|
|||||||
|
"use server";
|
||||||
|
|
||||||
|
import { auth } from "@/auth";
|
||||||
|
import { db } from "@/lib/db";
|
||||||
|
import { revalidatePath } from "next/cache";
|
||||||
|
import { z } from "zod";
|
||||||
|
import { findShot, suggestShot, type BoardShot } from "@/lib/board-parse";
|
||||||
|
import { parseFeedback, slateFrames, toPlayerFrame } from "@/lib/feedback-parse";
|
||||||
|
import { updateTaskStatus } from "@/actions/tasks";
|
||||||
|
import { notifyCommentsAdded, type NewCommentNote } from "@/lib/notifications";
|
||||||
|
|
||||||
|
/** Comment.source for notes pasted from a client message */
|
||||||
|
const SOURCE = "WHATSAPP";
|
||||||
|
|
||||||
|
async function requireStaff() {
|
||||||
|
const session = await auth();
|
||||||
|
if (!session?.user) throw new Error("Unauthorized");
|
||||||
|
if (session.user.role === "CLIENT") throw new Error("Insufficient permissions");
|
||||||
|
return session.user;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The shot a pasted code means: exact code or client alias first, then a code
|
||||||
|
* the client shortened by dropping the show prefix ("113_018_040" for
|
||||||
|
* "UNG_113_018_040") when exactly one shot ends with it.
|
||||||
|
*/
|
||||||
|
function resolveShot<T extends BoardShot>(code: string, shots: T[]): T | null {
|
||||||
|
const exact = findShot(code, shots) as T | null;
|
||||||
|
if (exact) return exact;
|
||||||
|
const tail = `_${code.toUpperCase()}`;
|
||||||
|
const hits = shots.filter((s) => s.shotCode.toUpperCase().endsWith(tail));
|
||||||
|
return hits.length === 1 ? hits[0] : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface FeedbackVersionOption {
|
||||||
|
id: string;
|
||||||
|
label: string;
|
||||||
|
sent: boolean;
|
||||||
|
sharedAt: string | null;
|
||||||
|
taskId: string | null;
|
||||||
|
taskStatus: string | null;
|
||||||
|
/** The note's quoted frame converted for this version's media; null = no frame quoted */
|
||||||
|
playerFrame: number | null;
|
||||||
|
fromComp: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface FeedbackPreviewNote {
|
||||||
|
key: string;
|
||||||
|
code: string;
|
||||||
|
text: string;
|
||||||
|
quotedFrame: number | null;
|
||||||
|
shot: { id: string; shotCode: string } | null;
|
||||||
|
suggestion: string | null;
|
||||||
|
versions: FeedbackVersionOption[];
|
||||||
|
defaultVersionId: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface FeedbackPreview {
|
||||||
|
rounds: { title: string; dueText: string | null; notes: FeedbackPreviewNote[] }[];
|
||||||
|
ignored: string[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function previewFeedback(projectId: string, input: string): Promise<FeedbackPreview> {
|
||||||
|
await requireStaff();
|
||||||
|
z.string().cuid().parse(projectId);
|
||||||
|
const parsed = parseFeedback(z.string().max(50000).parse(input));
|
||||||
|
|
||||||
|
const shots = await db.shot.findMany({
|
||||||
|
where: { projectId },
|
||||||
|
select: { id: true, shotCode: true, clientCode: true, frameStart: true },
|
||||||
|
});
|
||||||
|
|
||||||
|
const matched = new Map<string, (typeof shots)[number] | null>();
|
||||||
|
for (const r of parsed.rounds) for (const n of r.notes) {
|
||||||
|
const code = n.codes[0];
|
||||||
|
if (!matched.has(code)) matched.set(code, resolveShot(code, shots));
|
||||||
|
}
|
||||||
|
const shotIds = [...new Set([...matched.values()].filter(Boolean).map((s) => s!.id))];
|
||||||
|
|
||||||
|
// Recent versions per shot, whether hung off the shot or its task
|
||||||
|
const versions = shotIds.length
|
||||||
|
? await db.version.findMany({
|
||||||
|
where: { OR: [{ shotId: { in: shotIds } }, { task: { shotId: { in: shotIds } } }] },
|
||||||
|
orderBy: { createdAt: "desc" },
|
||||||
|
select: {
|
||||||
|
id: true,
|
||||||
|
versionNumber: true,
|
||||||
|
shotId: true,
|
||||||
|
isClientVisible: true,
|
||||||
|
sharedAt: true,
|
||||||
|
frameCount: true,
|
||||||
|
pictureStartFrame: true,
|
||||||
|
task: { select: { id: true, status: true, shotId: true } },
|
||||||
|
},
|
||||||
|
})
|
||||||
|
: [];
|
||||||
|
const byShot = new Map<string, typeof versions>();
|
||||||
|
for (const v of versions) {
|
||||||
|
const sid = v.shotId ?? v.task?.shotId;
|
||||||
|
if (!sid) continue;
|
||||||
|
const list = byShot.get(sid) ?? [];
|
||||||
|
if (list.length < 6) list.push(v);
|
||||||
|
byShot.set(sid, list);
|
||||||
|
}
|
||||||
|
|
||||||
|
let k = 0;
|
||||||
|
return {
|
||||||
|
ignored: parsed.ignored,
|
||||||
|
rounds: parsed.rounds.map((r) => ({
|
||||||
|
title: r.title,
|
||||||
|
dueText: r.dueText,
|
||||||
|
notes: r.notes.map((n) => {
|
||||||
|
const code = n.codes[0];
|
||||||
|
const shot = matched.get(code) ?? null;
|
||||||
|
const options: FeedbackVersionOption[] = (shot ? byShot.get(shot.id) ?? [] : []).map((v) => {
|
||||||
|
const conv = n.frame != null
|
||||||
|
? toPlayerFrame(n.frame, {
|
||||||
|
shotFrameStart: shot!.frameStart,
|
||||||
|
pictureStart: slateFrames(v),
|
||||||
|
frameCount: v.frameCount,
|
||||||
|
})
|
||||||
|
: null;
|
||||||
|
return {
|
||||||
|
id: v.id,
|
||||||
|
label: `v${String(v.versionNumber).padStart(3, "0")}`,
|
||||||
|
sent: v.isClientVisible,
|
||||||
|
sharedAt: v.sharedAt?.toISOString() ?? null,
|
||||||
|
taskId: v.task?.id ?? null,
|
||||||
|
taskStatus: v.task?.status ?? null,
|
||||||
|
playerFrame: conv?.frame ?? null,
|
||||||
|
fromComp: conv?.fromComp ?? false,
|
||||||
|
};
|
||||||
|
});
|
||||||
|
// The client is commenting on what they were sent
|
||||||
|
const def = options.find((o) => o.sent) ?? options[0] ?? null;
|
||||||
|
return {
|
||||||
|
key: `n${k++}`,
|
||||||
|
code: shot?.shotCode ?? code,
|
||||||
|
text: n.text,
|
||||||
|
quotedFrame: n.frame,
|
||||||
|
shot: shot ? { id: shot.id, shotCode: shot.shotCode } : null,
|
||||||
|
suggestion: shot ? null : suggestShot(code, shots)?.shotCode ?? null,
|
||||||
|
versions: options,
|
||||||
|
defaultVersionId: def?.id ?? null,
|
||||||
|
};
|
||||||
|
}),
|
||||||
|
})),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const commitSchema = z.object({
|
||||||
|
projectId: z.string().cuid(),
|
||||||
|
rounds: z.array(z.object({
|
||||||
|
title: z.string().max(200),
|
||||||
|
dueAt: z.string().datetime().nullable(),
|
||||||
|
notes: z.array(z.object({
|
||||||
|
code: z.string().min(1).max(100),
|
||||||
|
shotId: z.string().cuid().nullable(),
|
||||||
|
text: z.string().min(1).max(5000),
|
||||||
|
versionId: z.string().cuid().nullable(),
|
||||||
|
frame: z.number().int().min(0).nullable(),
|
||||||
|
setChanges: z.boolean(),
|
||||||
|
})).min(1),
|
||||||
|
})).min(1),
|
||||||
|
});
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Saves pasted client feedback: one FeedbackRound per round, each note as a
|
||||||
|
* player comment (tagged as client feedback) and a board line, and — where
|
||||||
|
* ticked — the version's task moved to Changes.
|
||||||
|
*/
|
||||||
|
export async function commitFeedback(data: z.infer<typeof commitSchema>) {
|
||||||
|
const user = await requireStaff();
|
||||||
|
const parsed = commitSchema.parse(data);
|
||||||
|
|
||||||
|
const notes = parsed.rounds.flatMap((r) => r.notes);
|
||||||
|
const versionIds = [...new Set(notes.map((n) => n.versionId).filter(Boolean) as string[])];
|
||||||
|
const versions = await db.version.findMany({
|
||||||
|
where: { id: { in: versionIds } },
|
||||||
|
select: {
|
||||||
|
id: true,
|
||||||
|
fps: true,
|
||||||
|
shotId: true,
|
||||||
|
task: { select: { id: true, shotId: true, status: true, projectId: true, assignedArtistId: true, shot: { select: { shotCode: true } } } },
|
||||||
|
shot: { select: { projectId: true, shotCode: true, artistId: true } },
|
||||||
|
},
|
||||||
|
});
|
||||||
|
const vById = new Map(versions.map((v) => [v.id, v]));
|
||||||
|
for (const n of notes) {
|
||||||
|
if (!n.versionId) continue;
|
||||||
|
const v = vById.get(n.versionId);
|
||||||
|
const projectOk = v && (v.shot?.projectId ?? v.task?.projectId) === parsed.projectId;
|
||||||
|
const shotOk = v && (v.shotId ?? v.task?.shotId) === n.shotId;
|
||||||
|
if (!projectOk || !shotOk) throw new Error(`Version does not belong to ${n.code}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
const last = await db.boardItem.findFirst({
|
||||||
|
where: { projectId: parsed.projectId },
|
||||||
|
orderBy: { sortOrder: "desc" },
|
||||||
|
select: { sortOrder: true },
|
||||||
|
});
|
||||||
|
let sort = (last?.sortOrder ?? -1) + 1;
|
||||||
|
|
||||||
|
let comments = 0;
|
||||||
|
const saved: NewCommentNote[] = [];
|
||||||
|
await db.$transaction(async (tx) => {
|
||||||
|
for (const r of parsed.rounds) {
|
||||||
|
const round = await tx.feedbackRound.create({
|
||||||
|
data: {
|
||||||
|
projectId: parsed.projectId,
|
||||||
|
title: r.title.trim() || "Client feedback",
|
||||||
|
dueAt: r.dueAt ? new Date(r.dueAt) : null,
|
||||||
|
createdById: user.id,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
for (const n of r.notes) {
|
||||||
|
const v = n.versionId ? vById.get(n.versionId)! : null;
|
||||||
|
const frame = n.frame ?? 0;
|
||||||
|
const comment = v
|
||||||
|
? await tx.comment.create({
|
||||||
|
data: {
|
||||||
|
versionId: v.id,
|
||||||
|
authorId: user.id,
|
||||||
|
frameNumber: frame,
|
||||||
|
timestamp: frame / v.fps,
|
||||||
|
text: n.text.trim(),
|
||||||
|
source: SOURCE,
|
||||||
|
},
|
||||||
|
select: { id: true },
|
||||||
|
})
|
||||||
|
: null;
|
||||||
|
if (comment && v) {
|
||||||
|
comments++;
|
||||||
|
saved.push({
|
||||||
|
versionId: v.id,
|
||||||
|
shotCode: v.shot?.shotCode ?? v.task?.shot?.shotCode ?? n.code.toUpperCase(),
|
||||||
|
frameNumber: frame,
|
||||||
|
artistIds: [v.shot?.artistId, v.task?.assignedArtistId],
|
||||||
|
});
|
||||||
|
}
|
||||||
|
await tx.boardItem.create({
|
||||||
|
data: {
|
||||||
|
projectId: parsed.projectId,
|
||||||
|
shotId: n.shotId,
|
||||||
|
code: n.code.toUpperCase(),
|
||||||
|
text: n.text.trim(),
|
||||||
|
roundId: round.id,
|
||||||
|
commentId: comment?.id ?? null,
|
||||||
|
sortOrder: sort++,
|
||||||
|
createdById: user.id,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// Outside the transaction: updateTaskStatus notifies the artist and
|
||||||
|
// recalculates shot status, exactly as moving the task by hand does.
|
||||||
|
const tasks = new Set<string>();
|
||||||
|
for (const n of notes) {
|
||||||
|
const task = n.versionId ? vById.get(n.versionId)?.task : null;
|
||||||
|
if (n.setChanges && task && task.status !== "CHANGES") tasks.add(task.id);
|
||||||
|
}
|
||||||
|
for (const taskId of tasks) await updateTaskStatus(taskId, "CHANGES");
|
||||||
|
|
||||||
|
// Only after the transaction commits — a rolled-back paste notifies no one.
|
||||||
|
await notifyCommentsAdded({
|
||||||
|
notes: saved,
|
||||||
|
authorId: user.id,
|
||||||
|
authorName: user.name ?? user.email ?? "Someone",
|
||||||
|
origin: "whatsapp",
|
||||||
|
}).catch((err) => console.error("[feedback] notify failed", err));
|
||||||
|
|
||||||
|
for (const id of versionIds) revalidatePath(`/review/${id}`);
|
||||||
|
revalidatePath("/board");
|
||||||
|
return { success: true, notes: notes.length, comments, tasksChanged: tasks.size };
|
||||||
|
}
|
||||||
+5
-1
@@ -108,10 +108,14 @@ export async function updateProject(data: z.infer<typeof updateProjectSchema>) {
|
|||||||
...(rest.slackChannel !== undefined && { slackChannel: rest.slackChannel || null }),
|
...(rest.slackChannel !== undefined && { slackChannel: rest.slackChannel || null }),
|
||||||
// Blank fields are dropped rather than stored as empty strings, so a comp
|
// Blank fields are dropped rather than stored as empty strings, so a comp
|
||||||
// name left blank keeps following the convention instead of pinning "".
|
// name left blank keeps following the convention instead of pinning "".
|
||||||
|
// Booleans are kept as-is: `false` is a meaningful stored value, and the
|
||||||
|
// blank-string test would otherwise discard every non-string setting.
|
||||||
...(rest.pipelineConfig !== undefined && {
|
...(rest.pipelineConfig !== undefined && {
|
||||||
pipelineConfig: rest.pipelineConfig
|
pipelineConfig: rest.pipelineConfig
|
||||||
? (Object.fromEntries(
|
? (Object.fromEntries(
|
||||||
Object.entries(rest.pipelineConfig).filter(([, v]) => typeof v === "string" && v.trim())
|
Object.entries(rest.pipelineConfig).filter(([, v]) =>
|
||||||
|
typeof v === "boolean" ? true : typeof v === "string" && !!v.trim()
|
||||||
|
)
|
||||||
) as Prisma.InputJsonValue)
|
) as Prisma.InputJsonValue)
|
||||||
: Prisma.DbNull,
|
: Prisma.DbNull,
|
||||||
}),
|
}),
|
||||||
|
|||||||
+366
-47
@@ -4,8 +4,9 @@ import { auth } from "@/auth";
|
|||||||
import { db } from "@/lib/db";
|
import { db } from "@/lib/db";
|
||||||
import { revalidatePath } from "next/cache";
|
import { revalidatePath } from "next/cache";
|
||||||
import { z } from "zod";
|
import { z } from "zod";
|
||||||
import { ShotStatus, ShotPriority, ShotApprovalStatus } from "@prisma/client";
|
import { ShotStatus, ShotPriority, ShotApprovalStatus, Prisma } from "@prisma/client";
|
||||||
import { recalcShotStatus } from "@/lib/shot-status";
|
import { recalcShotStatus, markShotForRevisions } from "@/lib/shot-status";
|
||||||
|
import { countShotsOnOpenRequests } from "@/lib/render-pipeline/delivery-requests";
|
||||||
|
|
||||||
const createShotSchema = z.object({
|
const createShotSchema = z.object({
|
||||||
scene: z.string().min(1).max(50).regex(/^[A-Z0-9_]+$/i, "Alphanumeric and underscore only"),
|
scene: z.string().min(1).max(50).regex(/^[A-Z0-9_]+$/i, "Alphanumeric and underscore only"),
|
||||||
@@ -341,6 +342,15 @@ export async function importShotsFromCsv(
|
|||||||
return { success: true, created, errors };
|
return { success: true, created, errors };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Manual override of the shot's status.
|
||||||
|
*
|
||||||
|
* Deliberately the one place that writes Shot.status without deriving it — but
|
||||||
|
* note the override is transient: Shot.status is a derived field, so the next
|
||||||
|
* recalc (any task move, approval, upload or render) recomputes it from the
|
||||||
|
* tasks and approval flags and discards whatever was set here. Change the
|
||||||
|
* underlying task states if the new status needs to stick.
|
||||||
|
*/
|
||||||
export async function updateShotStatus(
|
export async function updateShotStatus(
|
||||||
shotId: string,
|
shotId: string,
|
||||||
status: ShotStatus
|
status: ShotStatus
|
||||||
@@ -550,6 +560,34 @@ export async function toggleKeyShot(shotId: string, isKeyShot: boolean) {
|
|||||||
return { success: true };
|
return { success: true };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Scaled in the edit: the plate is not used at its native size, which changes
|
||||||
|
* how the shot is comped and reviewed. Same shape as toggleKeyShot — a standing
|
||||||
|
* property of the shot, flipped from the shot-status board.
|
||||||
|
*/
|
||||||
|
export async function toggleScaledShot(shotId: string, isScaled: boolean) {
|
||||||
|
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 shot = await db.shot.findUnique({
|
||||||
|
where: { id: shotId },
|
||||||
|
select: { projectId: true },
|
||||||
|
});
|
||||||
|
if (!shot) throw new Error("Shot not found");
|
||||||
|
|
||||||
|
await db.shot.update({
|
||||||
|
where: { id: shotId },
|
||||||
|
data: { isScaled },
|
||||||
|
});
|
||||||
|
|
||||||
|
revalidatePath(`/projects/${shot.projectId}`);
|
||||||
|
revalidatePath(`/shot-status`);
|
||||||
|
return { success: true };
|
||||||
|
}
|
||||||
|
|
||||||
export async function deleteShot(shotId: string) {
|
export async function deleteShot(shotId: string) {
|
||||||
const session = await auth();
|
const session = await auth();
|
||||||
if (!session?.user) throw new Error("Unauthorized");
|
if (!session?.user) throw new Error("Unauthorized");
|
||||||
@@ -615,6 +653,203 @@ export async function bulkUpdateDueDates(
|
|||||||
return { success: true, updated: shots.length };
|
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 Manual Delivery ──────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Record that a selection of shots was delivered outside the render pipeline
|
||||||
|
* (by hand, before packages existed), or clear that record when
|
||||||
|
* `deliveredOn` is null. The delivery countdown counts these alongside
|
||||||
|
* DELIVERED EXR packages (lib/dashboard/ops.ts).
|
||||||
|
*
|
||||||
|
* `deliveredOn` is the day the frames went out ("yyyy-MM-dd"), stored at
|
||||||
|
* noon UTC so the calendar day survives any timezone it is shown in.
|
||||||
|
*/
|
||||||
|
export async function bulkSetManualDelivery(
|
||||||
|
shotIds: string[],
|
||||||
|
deliveredOn: string | null,
|
||||||
|
note?: string,
|
||||||
|
/** Where it was uploaded and who was sent the link. */
|
||||||
|
evidence?: { uploadUrl?: string; sharedWith?: string },
|
||||||
|
) {
|
||||||
|
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 as const, updated: 0 };
|
||||||
|
|
||||||
|
let deliveredAt: Date | null = null;
|
||||||
|
if (deliveredOn) {
|
||||||
|
const day = z.string().regex(/^\d{4}-\d{2}-\d{2}$/).parse(deliveredOn);
|
||||||
|
deliveredAt = new Date(`${day}T12:00:00.000Z`);
|
||||||
|
if (Number.isNaN(deliveredAt.getTime())) throw new Error("Invalid delivery date");
|
||||||
|
if (deliveredAt.getTime() > Date.now() + 24 * 60 * 60 * 1000) {
|
||||||
|
throw new Error("A delivery date can't be in the future");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
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");
|
||||||
|
|
||||||
|
const trimmedNote = note?.trim() || null;
|
||||||
|
const uploadUrl = evidence?.uploadUrl?.trim() || null;
|
||||||
|
const sharedWith = evidence?.sharedWith?.trim() || null;
|
||||||
|
if (uploadUrl && !/^https?:\/\/\S+$/i.test(uploadUrl)) {
|
||||||
|
return { success: false as const, error: "The upload link must be a full http(s) link" };
|
||||||
|
}
|
||||||
|
|
||||||
|
// A backfill of old deliveries may have no link to give. A shot a client is
|
||||||
|
// waiting on is different: without the link and recipient the request it
|
||||||
|
// answers would stay open, so say so now rather than leave it unexplained.
|
||||||
|
if (deliveredAt && (!uploadUrl || !sharedWith)) {
|
||||||
|
const owed = await countShotsOnOpenRequests(ids);
|
||||||
|
if (owed > 0) {
|
||||||
|
// Returned, not thrown: a production build replaces a thrown action
|
||||||
|
// error with a generic message, and this one has to reach the person.
|
||||||
|
return {
|
||||||
|
success: false as const,
|
||||||
|
error: `${owed} of these shots ${owed === 1 ? "is" : "are"} on an open delivery request — add the upload link and who it was sent to`,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
await db.shot.updateMany({
|
||||||
|
where: { id: { in: ids } },
|
||||||
|
data: deliveredAt
|
||||||
|
? {
|
||||||
|
manualDeliveredAt: deliveredAt,
|
||||||
|
manualDeliveredById: session.user.id,
|
||||||
|
manualDeliveryNote: trimmedNote,
|
||||||
|
manualDeliveryUrl: uploadUrl,
|
||||||
|
manualDeliverySharedWith: sharedWith,
|
||||||
|
}
|
||||||
|
: {
|
||||||
|
manualDeliveredAt: null,
|
||||||
|
manualDeliveredById: null,
|
||||||
|
manualDeliveryNote: null,
|
||||||
|
manualDeliveryUrl: null,
|
||||||
|
manualDeliverySharedWith: null,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
for (const pid of [...new Set(shots.map((s) => s.projectId))]) {
|
||||||
|
revalidatePath(`/projects/${pid}`);
|
||||||
|
}
|
||||||
|
revalidatePath(`/shot-status`);
|
||||||
|
revalidatePath(`/dashboard`);
|
||||||
|
|
||||||
|
return { success: true as const, updated: shots.length };
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Bulk Delete Shots ─────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
export async function bulkDeleteShots(shotIds: string[]) {
|
||||||
|
const session = await auth();
|
||||||
|
if (!session?.user) throw new Error("Unauthorized");
|
||||||
|
if (!["ADMIN", "PRODUCER", "SUPERVISOR"].includes(session.user.role)) {
|
||||||
|
throw new Error("Insufficient permissions");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!shotIds.length) return { success: true, deleted: 0, failed: [] as { shotId: string; shotCode: string; reason: string }[] };
|
||||||
|
|
||||||
|
const shots = await db.shot.findMany({
|
||||||
|
where: { id: { in: shotIds } },
|
||||||
|
select: { id: true, shotCode: true, projectId: true },
|
||||||
|
});
|
||||||
|
|
||||||
|
const projectIds = [...new Set(shots.map((s) => s.projectId))];
|
||||||
|
const failed: { shotId: string; shotCode: string; reason: string }[] = [];
|
||||||
|
let deleted = 0;
|
||||||
|
|
||||||
|
// One at a time, not deleteMany: a shot with renders or deliveries is
|
||||||
|
// protected at the database level (exports_shotId_fkey is ON DELETE
|
||||||
|
// RESTRICT, deliberately — delivery history must never be destroyable by
|
||||||
|
// deleting the shot underneath it). A single bulk statement would abort
|
||||||
|
// entirely on the first shot it hits; deleting individually means every
|
||||||
|
// shot that *can* go still does, and the ones that can't are reported by
|
||||||
|
// name instead of failing the whole selection.
|
||||||
|
for (const shot of shots) {
|
||||||
|
try {
|
||||||
|
await db.shot.delete({ where: { id: shot.id } });
|
||||||
|
deleted += 1;
|
||||||
|
} catch (e) {
|
||||||
|
failed.push({
|
||||||
|
shotId: shot.id,
|
||||||
|
shotCode: shot.shotCode,
|
||||||
|
reason:
|
||||||
|
e instanceof Prisma.PrismaClientKnownRequestError && e.code === "P2003"
|
||||||
|
? "has renders or deliveries — delete those first"
|
||||||
|
: e instanceof Error
|
||||||
|
? e.message
|
||||||
|
: "unknown error",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
for (const pid of projectIds) {
|
||||||
|
revalidatePath(`/projects/${pid}`);
|
||||||
|
}
|
||||||
|
revalidatePath(`/shot-status`);
|
||||||
|
|
||||||
|
return { success: true, deleted, failed };
|
||||||
|
}
|
||||||
|
|
||||||
export async function renameFootagePlate(plateId: string, label: string) {
|
export async function renameFootagePlate(plateId: string, label: string) {
|
||||||
const session = await auth();
|
const session = await auth();
|
||||||
if (!session?.user) throw new Error("Unauthorized");
|
if (!session?.user) throw new Error("Unauthorized");
|
||||||
@@ -656,13 +891,19 @@ export async function internallyApproveShot(shotId: string) {
|
|||||||
});
|
});
|
||||||
if (!shot) throw new Error("Shot not found");
|
if (!shot) throw new Error("Shot not found");
|
||||||
|
|
||||||
await db.shot.update({
|
// Set the approval inputs and let the derivation pick the status. Writing
|
||||||
where: { id: shotId },
|
// READY_FOR_CLIENT directly skipped the rule that an outstanding CHANGES task
|
||||||
data: {
|
// outranks any approval, so a shot could be pushed past open rework and then
|
||||||
shotApprovalStatus: "INTERNALLY_APPROVED",
|
// snap back to REVISIONS on the next unrelated recalc.
|
||||||
sharedWithClient: false,
|
await db.$transaction(async (tx) => {
|
||||||
status: "READY_FOR_CLIENT",
|
await tx.shot.update({
|
||||||
},
|
where: { id: shotId },
|
||||||
|
data: {
|
||||||
|
shotApprovalStatus: "INTERNALLY_APPROVED",
|
||||||
|
sharedWithClient: false,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
await recalcShotStatus(shotId, tx);
|
||||||
});
|
});
|
||||||
|
|
||||||
revalidatePath(`/projects/${shot.projectId}`);
|
revalidatePath(`/projects/${shot.projectId}`);
|
||||||
@@ -705,7 +946,7 @@ export async function shareWithClient(shotId: string) {
|
|||||||
// Mark shot as shared
|
// Mark shot as shared
|
||||||
await tx.shot.update({
|
await tx.shot.update({
|
||||||
where: { id: shotId },
|
where: { id: shotId },
|
||||||
data: { sharedWithClient: true, status: "CLIENT_REVIEW" },
|
data: { sharedWithClient: true },
|
||||||
});
|
});
|
||||||
|
|
||||||
// For each task, make the latest version client-visible
|
// For each task, make the latest version client-visible
|
||||||
@@ -725,6 +966,8 @@ export async function shareWithClient(shotId: string) {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
await recalcShotStatus(shotId, tx);
|
||||||
});
|
});
|
||||||
|
|
||||||
revalidatePath(`/projects/${shot.projectId}`);
|
revalidatePath(`/projects/${shot.projectId}`);
|
||||||
@@ -757,7 +1000,7 @@ export async function unshareFromClient(shotId: string) {
|
|||||||
await db.$transaction(async (tx) => {
|
await db.$transaction(async (tx) => {
|
||||||
await tx.shot.update({
|
await tx.shot.update({
|
||||||
where: { id: shotId },
|
where: { id: shotId },
|
||||||
data: { sharedWithClient: false, status: "READY_FOR_CLIENT" },
|
data: { sharedWithClient: false },
|
||||||
});
|
});
|
||||||
|
|
||||||
// Hide all client-visible versions on this shot's tasks
|
// Hide all client-visible versions on this shot's tasks
|
||||||
@@ -768,6 +1011,8 @@ export async function unshareFromClient(shotId: string) {
|
|||||||
data: { isClientVisible: false },
|
data: { isClientVisible: false },
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
await recalcShotStatus(shotId, tx);
|
||||||
});
|
});
|
||||||
|
|
||||||
revalidatePath(`/projects/${shot.projectId}`);
|
revalidatePath(`/projects/${shot.projectId}`);
|
||||||
@@ -796,9 +1041,12 @@ export async function clientApproveShot(shotId: string) {
|
|||||||
if (!shot) throw new Error("Shot not found");
|
if (!shot) throw new Error("Shot not found");
|
||||||
if (!shot.sharedWithClient) throw new Error("Shot is not shared with client");
|
if (!shot.sharedWithClient) throw new Error("Shot is not shared with client");
|
||||||
|
|
||||||
await db.shot.update({
|
await db.$transaction(async (tx) => {
|
||||||
where: { id: shotId },
|
await tx.shot.update({
|
||||||
data: { shotApprovalStatus: "CLIENT_APPROVED", status: "COMPLETE" },
|
where: { id: shotId },
|
||||||
|
data: { shotApprovalStatus: "CLIENT_APPROVED" },
|
||||||
|
});
|
||||||
|
await recalcShotStatus(shotId, tx);
|
||||||
});
|
});
|
||||||
|
|
||||||
revalidatePath(`/projects/${shot.projectId}`);
|
revalidatePath(`/projects/${shot.projectId}`);
|
||||||
@@ -828,14 +1076,15 @@ export async function unapproveShot(shotId: string) {
|
|||||||
throw new Error("Shot is not client-approved");
|
throw new Error("Shot is not client-approved");
|
||||||
}
|
}
|
||||||
|
|
||||||
const newStatus = shot.sharedWithClient ? "CLIENT_REVIEW" : "READY_FOR_CLIENT";
|
// The derivation already encodes "CLIENT_REVIEW if still shared, else
|
||||||
|
// READY_FOR_CLIENT" for an INTERNALLY_APPROVED shot, and additionally honours
|
||||||
await db.shot.update({
|
// any open CHANGES task.
|
||||||
where: { id: shotId },
|
await db.$transaction(async (tx) => {
|
||||||
data: {
|
await tx.shot.update({
|
||||||
shotApprovalStatus: "INTERNALLY_APPROVED",
|
where: { id: shotId },
|
||||||
status: newStatus,
|
data: { shotApprovalStatus: "INTERNALLY_APPROVED" },
|
||||||
},
|
});
|
||||||
|
await recalcShotStatus(shotId, tx);
|
||||||
});
|
});
|
||||||
|
|
||||||
revalidatePath(`/projects/${shot.projectId}`);
|
revalidatePath(`/projects/${shot.projectId}`);
|
||||||
@@ -1136,9 +1385,12 @@ export async function assignShotGroups(
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Internal: handle client requesting changes on a shot.
|
* Session-authenticated wrapper for requesting changes on a shot — a supervisor
|
||||||
* Resets shotApprovalStatus = PENDING, sharedWithClient = false.
|
* or producer relaying a client note from inside the app.
|
||||||
* Recalculates shot status (will become REVISIONS if tasks set to CHANGES).
|
*
|
||||||
|
* The client portal cannot use this: it runs on a review token, not a session,
|
||||||
|
* so it calls markShotForRevisions directly from its route. Both go through that
|
||||||
|
* one helper so the two entry points cannot drift apart again.
|
||||||
*/
|
*/
|
||||||
export async function clientRequestShotChanges(shotId: string, taskId?: string) {
|
export async function clientRequestShotChanges(shotId: string, taskId?: string) {
|
||||||
const session = await auth();
|
const session = await auth();
|
||||||
@@ -1153,28 +1405,7 @@ export async function clientRequestShotChanges(shotId: string, taskId?: string)
|
|||||||
});
|
});
|
||||||
if (!shot) throw new Error("Shot not found");
|
if (!shot) throw new Error("Shot not found");
|
||||||
|
|
||||||
await db.$transaction(async (tx) => {
|
await db.$transaction((tx) => markShotForRevisions(tx, shotId, taskId));
|
||||||
// Reset shot approval
|
|
||||||
await tx.shot.update({
|
|
||||||
where: { id: shotId },
|
|
||||||
data: { shotApprovalStatus: "PENDING", sharedWithClient: false },
|
|
||||||
});
|
|
||||||
|
|
||||||
// If a specific task is called out, mark it CHANGES; otherwise mark all non-DONE tasks
|
|
||||||
if (taskId) {
|
|
||||||
await tx.task.update({
|
|
||||||
where: { id: taskId },
|
|
||||||
data: { status: "CHANGES" },
|
|
||||||
});
|
|
||||||
} else {
|
|
||||||
await tx.task.updateMany({
|
|
||||||
where: { shotId, status: { not: "DONE" } },
|
|
||||||
data: { status: "CHANGES" },
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
await recalcShotStatus(shotId, tx);
|
|
||||||
});
|
|
||||||
|
|
||||||
revalidatePath(`/projects/${shot.projectId}`);
|
revalidatePath(`/projects/${shot.projectId}`);
|
||||||
revalidatePath(`/projects/${shot.projectId}/shots/${shotId}`);
|
revalidatePath(`/projects/${shot.projectId}/shots/${shotId}`);
|
||||||
@@ -1213,3 +1444,91 @@ export async function updateShotVersion(shotId: string, version: string) {
|
|||||||
revalidatePath(`/projects/${shot.projectId}/shots/${shotId}`);
|
revalidatePath(`/projects/${shot.projectId}/shots/${shotId}`);
|
||||||
return { success: true, shotVersion: version };
|
return { success: true, shotVersion: version };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ── Generated (render-derived) shot thumbnails ───────────────────────────────
|
||||||
|
//
|
||||||
|
// A shot can carry two stills: `thumbnailUrl`, the reference frame that came
|
||||||
|
// with the brief, and `generatedThumbnailUrl`, a frame promoted from a render
|
||||||
|
// export. The reference always wins on display (lib/shot-thumbnail.ts), so
|
||||||
|
// these actions can only ever fill a gap — a promotion never overwrites the
|
||||||
|
// brief, and clearing one always falls back to it.
|
||||||
|
//
|
||||||
|
// Shows with `pipelineConfig.autoShotThumbnail` promote on every finished
|
||||||
|
// export automatically (lib/render-pipeline/preview.ts). These actions are the
|
||||||
|
// manual equivalent, and work regardless of that flag: a supervisor can pull a
|
||||||
|
// frame onto one shot on a project that is otherwise hands-off.
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Promote a render export's thumbnail onto its shot.
|
||||||
|
*
|
||||||
|
* With no `exportId`, uses the newest export of that shot which actually has a
|
||||||
|
* thumbnail — "use the latest render frame".
|
||||||
|
*/
|
||||||
|
export async function promoteExportThumbnail(shotId: string, exportId?: string) {
|
||||||
|
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 shot = await db.shot.findUnique({
|
||||||
|
where: { id: shotId },
|
||||||
|
select: { id: true, projectId: true },
|
||||||
|
});
|
||||||
|
if (!shot) throw new Error("Shot not found");
|
||||||
|
|
||||||
|
const exportRow = await db.export.findFirst({
|
||||||
|
where: {
|
||||||
|
shotId,
|
||||||
|
thumbnailKey: { not: null },
|
||||||
|
...(exportId ? { id: exportId } : {}),
|
||||||
|
},
|
||||||
|
orderBy: { versionNumber: "desc" },
|
||||||
|
select: { id: true, thumbnailKey: true, versionString: true },
|
||||||
|
});
|
||||||
|
if (!exportRow?.thumbnailKey) {
|
||||||
|
throw new Error(
|
||||||
|
exportId
|
||||||
|
? "That export has no thumbnail — its preview may have been skipped, or the worker had no ffmpeg configured"
|
||||||
|
: "No render of this shot has produced a thumbnail yet"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const generatedThumbnailUrl = `/api/files/${exportRow.thumbnailKey}`;
|
||||||
|
await db.shot.update({
|
||||||
|
where: { id: shotId },
|
||||||
|
data: { generatedThumbnailUrl, generatedThumbnailFrom: exportRow.versionString },
|
||||||
|
});
|
||||||
|
|
||||||
|
revalidatePath(`/projects/${shot.projectId}`);
|
||||||
|
revalidatePath(`/projects/${shot.projectId}/shots/${shotId}`);
|
||||||
|
return {
|
||||||
|
success: true,
|
||||||
|
generatedThumbnailUrl,
|
||||||
|
generatedThumbnailFrom: exportRow.versionString,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Drop the render-derived still. The reference frame, if any, comes back. */
|
||||||
|
export async function clearGeneratedThumbnail(shotId: string) {
|
||||||
|
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 shot = await db.shot.findUnique({
|
||||||
|
where: { id: shotId },
|
||||||
|
select: { id: true, projectId: true },
|
||||||
|
});
|
||||||
|
if (!shot) throw new Error("Shot not found");
|
||||||
|
|
||||||
|
await db.shot.update({
|
||||||
|
where: { id: shotId },
|
||||||
|
data: { generatedThumbnailUrl: null, generatedThumbnailFrom: null },
|
||||||
|
});
|
||||||
|
|
||||||
|
revalidatePath(`/projects/${shot.projectId}`);
|
||||||
|
revalidatePath(`/projects/${shot.projectId}/shots/${shotId}`);
|
||||||
|
return { success: true };
|
||||||
|
}
|
||||||
|
|||||||
+47
-3
@@ -4,9 +4,10 @@ import { auth } from "@/auth";
|
|||||||
import { db } from "@/lib/db";
|
import { db } from "@/lib/db";
|
||||||
import { revalidatePath } from "next/cache";
|
import { revalidatePath } from "next/cache";
|
||||||
import { z } from "zod";
|
import { z } from "zod";
|
||||||
import { recalcShotStatus } from "@/lib/shot-status";
|
import { recalcShotStatus, clearStaleShotApproval } from "@/lib/shot-status";
|
||||||
import { notifyNewVersionUploaded } from "@/lib/notifications";
|
import { notifyNewVersionUploaded } from "@/lib/notifications";
|
||||||
import { slackNotifyVersionUploaded } from "@/lib/slack";
|
import { slackNotifyVersionUploaded } from "@/lib/slack";
|
||||||
|
import { deleteStorageKeys, highResStorageKeys } from "@/lib/render-pipeline/high-res";
|
||||||
|
|
||||||
const createVersionSchema = z.object({
|
const createVersionSchema = z.object({
|
||||||
taskId: z.string().cuid(),
|
taskId: z.string().cuid(),
|
||||||
@@ -50,9 +51,16 @@ export async function createVersion(data: z.infer<typeof createVersionSchema>) {
|
|||||||
data: { status: "INTERNAL_REVIEW" },
|
data: { status: "INTERNAL_REVIEW" },
|
||||||
});
|
});
|
||||||
|
|
||||||
// Recalculate shot status
|
// Recalculate shot status — clearing any stale sign-off first, so a new
|
||||||
|
// version does not land under a shot still reading COMPLETE.
|
||||||
if (task.shot) {
|
if (task.shot) {
|
||||||
await recalcShotStatus(task.shot.id).catch(() => {});
|
const shotId = task.shot.id;
|
||||||
|
await db
|
||||||
|
.$transaction(async (tx) => {
|
||||||
|
await clearStaleShotApproval(tx, shotId);
|
||||||
|
await recalcShotStatus(shotId, tx);
|
||||||
|
})
|
||||||
|
.catch(() => {});
|
||||||
}
|
}
|
||||||
|
|
||||||
// Get the next version number for this task
|
// Get the next version number for this task
|
||||||
@@ -178,6 +186,8 @@ export async function deleteVersion(versionId: string) {
|
|||||||
id: true,
|
id: true,
|
||||||
isLatest: true,
|
isLatest: true,
|
||||||
taskId: true,
|
taskId: true,
|
||||||
|
hqFileUrl: true,
|
||||||
|
highResKey: true,
|
||||||
task: { select: { projectId: true, shotId: true } },
|
task: { select: { projectId: true, shotId: true } },
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
@@ -196,6 +206,8 @@ export async function deleteVersion(versionId: string) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
await db.version.delete({ where: { id: versionId } });
|
await db.version.delete({ where: { id: versionId } });
|
||||||
|
// Its High quality MP4 and ProRes are large and referenced by nothing else.
|
||||||
|
await deleteStorageKeys(highResStorageKeys(version));
|
||||||
|
|
||||||
const projectId = version.task?.projectId;
|
const projectId = version.task?.projectId;
|
||||||
const shotId = version.task?.shotId;
|
const shotId = version.task?.shotId;
|
||||||
@@ -252,3 +264,35 @@ export async function getVersionComments(versionId: string) {
|
|||||||
orderBy: { frameNumber: "asc" },
|
orderBy: { frameNumber: "asc" },
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const updateVersionHandlesSchema = z.object({
|
||||||
|
versionId: z.string().cuid(),
|
||||||
|
/** 0/0 = no handles (every frame is in the edit). */
|
||||||
|
handleHead: z.number().int().min(0).max(1000),
|
||||||
|
handleTail: z.number().int().min(0).max(1000),
|
||||||
|
/** Slate frames before the picture; null = infer from the media. */
|
||||||
|
pictureStartFrame: z.number().int().min(0).max(1000).nullable(),
|
||||||
|
});
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Marks which frames of a version are handles (past the cut at each end), so
|
||||||
|
* the review player can flag them. Review metadata only — the media and any
|
||||||
|
* delivered files are untouched. Staff only: a client can't redefine the cut.
|
||||||
|
*/
|
||||||
|
export async function updateVersionHandles(data: z.infer<typeof updateVersionHandlesSchema>) {
|
||||||
|
const session = await auth();
|
||||||
|
if (!session?.user) throw new Error("Unauthorized");
|
||||||
|
if (session.user.role === "CLIENT") throw new Error("Forbidden");
|
||||||
|
|
||||||
|
const parsed = updateVersionHandlesSchema.parse(data);
|
||||||
|
const none = parsed.handleHead === 0 && parsed.handleTail === 0;
|
||||||
|
await db.version.update({
|
||||||
|
where: { id: parsed.versionId },
|
||||||
|
data: {
|
||||||
|
handleHead: none ? null : parsed.handleHead,
|
||||||
|
handleTail: none ? null : parsed.handleTail,
|
||||||
|
pictureStartFrame: parsed.pictureStartFrame,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
revalidatePath(`/review/${parsed.versionId}`);
|
||||||
|
}
|
||||||
|
|||||||
@@ -0,0 +1,689 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useEffect, useRef, useState, useTransition } from "react";
|
||||||
|
import { useRouter } from "next/navigation";
|
||||||
|
import Link from "next/link";
|
||||||
|
import { differenceInCalendarDays, format, formatDistanceToNowStrict } from "date-fns";
|
||||||
|
import {
|
||||||
|
AlertTriangle,
|
||||||
|
Check,
|
||||||
|
ChevronDown,
|
||||||
|
ChevronRight,
|
||||||
|
Clock,
|
||||||
|
Flag,
|
||||||
|
Link2,
|
||||||
|
MessageSquareText,
|
||||||
|
Pencil,
|
||||||
|
Plus,
|
||||||
|
Trash2,
|
||||||
|
X,
|
||||||
|
} from "lucide-react";
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
|
||||||
|
import { useToast } from "@/components/ui/use-toast";
|
||||||
|
import { cn, getInitials } from "@/lib/utils";
|
||||||
|
import {
|
||||||
|
addBoardItems,
|
||||||
|
addMilestone,
|
||||||
|
deleteBoardItem,
|
||||||
|
deleteMilestone,
|
||||||
|
setBoardItemDone,
|
||||||
|
setMilestoneDone,
|
||||||
|
setProjectBoardStatus,
|
||||||
|
updateBoardItem,
|
||||||
|
} from "@/actions/board";
|
||||||
|
import { FeedbackPasteDialog } from "./FeedbackPasteDialog";
|
||||||
|
|
||||||
|
type User = { id: string; name: string | null; email: string; image: string | null };
|
||||||
|
|
||||||
|
type BoardItem = {
|
||||||
|
id: string;
|
||||||
|
text: string;
|
||||||
|
code: string | null;
|
||||||
|
group: string;
|
||||||
|
waitingOn: string | null;
|
||||||
|
round: { id: string; title: string; dueAt: string | null } | null;
|
||||||
|
/** The player comment a pasted-feedback line was saved as */
|
||||||
|
comment: { versionId: string; frame: number } | null;
|
||||||
|
doneAt: string | null;
|
||||||
|
assignee: { id: string; name: string | null; image: string | null } | null;
|
||||||
|
shot: {
|
||||||
|
id: string;
|
||||||
|
shotCode: string;
|
||||||
|
status: string;
|
||||||
|
latest: { id: string; versionNumber: number; approvalStatus: string; isClientVisible: boolean } | null;
|
||||||
|
} | null;
|
||||||
|
relinkTo: string | null;
|
||||||
|
relinkIsExact: boolean;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type BoardProject = {
|
||||||
|
id: string;
|
||||||
|
name: string;
|
||||||
|
code: string;
|
||||||
|
status: string;
|
||||||
|
boardStatus: string | null;
|
||||||
|
boardStatusAt: string | null;
|
||||||
|
shotTotal: number;
|
||||||
|
shotComplete: number;
|
||||||
|
milestones: { id: string; label: string; date: string; doneAt: string | null }[];
|
||||||
|
items: BoardItem[];
|
||||||
|
};
|
||||||
|
|
||||||
|
const SHOT_STATUS: Record<string, { label: string; color: string }> = {
|
||||||
|
WAITING: { label: "Waiting", color: "bg-zinc-500/10 text-zinc-400 border-zinc-500/20" },
|
||||||
|
IN_PROGRESS: { label: "In Progress", color: "bg-blue-500/10 text-blue-400 border-blue-500/20" },
|
||||||
|
INTERNAL_REVIEW: { label: "Internal Review", color: "bg-purple-500/10 text-purple-400 border-purple-500/20" },
|
||||||
|
READY_FOR_CLIENT: { label: "Ready for Client", color: "bg-cyan-500/10 text-cyan-400 border-cyan-500/20" },
|
||||||
|
CLIENT_REVIEW: { label: "Client Review", color: "bg-indigo-500/10 text-indigo-400 border-indigo-500/20" },
|
||||||
|
REVISIONS: { label: "Revisions", color: "bg-orange-500/10 text-orange-400 border-orange-500/20" },
|
||||||
|
COMPLETE: { label: "Complete", color: "bg-green-500/10 text-green-400 border-green-500/20" },
|
||||||
|
};
|
||||||
|
|
||||||
|
const APPROVAL: Record<string, { label: string; color: string }> = {
|
||||||
|
PENDING_REVIEW: { label: "pending", color: "text-zinc-500" },
|
||||||
|
APPROVED: { label: "approved", color: "text-green-400" },
|
||||||
|
REJECTED: { label: "rejected", color: "text-red-400" },
|
||||||
|
NEEDS_CHANGES: { label: "changes", color: "text-orange-400" },
|
||||||
|
};
|
||||||
|
|
||||||
|
export function BoardClient({
|
||||||
|
projects,
|
||||||
|
users,
|
||||||
|
who,
|
||||||
|
}: {
|
||||||
|
projects: BoardProject[];
|
||||||
|
users: User[];
|
||||||
|
who: string | null;
|
||||||
|
}) {
|
||||||
|
const router = useRouter();
|
||||||
|
|
||||||
|
const filters = [
|
||||||
|
{ key: null, label: "Everyone" },
|
||||||
|
...users.map((u) => ({ key: u.id, label: u.name?.split(" ")[0] ?? u.email })),
|
||||||
|
{ key: "none", label: "Unassigned" },
|
||||||
|
];
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="p-4 md:p-8 max-w-5xl">
|
||||||
|
<div className="mb-6 flex flex-wrap items-end justify-between gap-4">
|
||||||
|
<div>
|
||||||
|
<h1 className="text-3xl font-bold text-white">Board</h1>
|
||||||
|
<p className="text-zinc-400 mt-1">{format(new Date(), "EEEE, d MMMM yyyy")}</p>
|
||||||
|
</div>
|
||||||
|
<div className="flex flex-wrap gap-1 rounded-lg border border-zinc-800 bg-zinc-900 p-1">
|
||||||
|
{filters.map((f) => (
|
||||||
|
<button
|
||||||
|
key={f.key ?? "all"}
|
||||||
|
type="button"
|
||||||
|
onClick={() => router.push(f.key ? `/board?who=${f.key}` : "/board")}
|
||||||
|
className={cn(
|
||||||
|
"rounded-md px-3 py-1 text-xs font-medium transition-colors",
|
||||||
|
who === f.key ? "bg-amber-500/10 text-amber-400" : "text-zinc-400 hover:text-white",
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
{f.label}
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{projects.length === 0 && (
|
||||||
|
<p className="text-sm text-zinc-500">No active or on-hold projects.</p>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<div className="space-y-6">
|
||||||
|
{projects.map((p) => (
|
||||||
|
<ProjectSection key={p.id} project={p} users={users} who={who} />
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function ProjectSection({ project, users, who }: { project: BoardProject; users: User[]; who: string | null }) {
|
||||||
|
const [showDone, setShowDone] = useState(false);
|
||||||
|
const [pasting, setPasting] = useState(false);
|
||||||
|
|
||||||
|
const visible = project.items.filter((i) =>
|
||||||
|
who === null ? true : who === "none" ? !i.assignee : i.assignee?.id === who,
|
||||||
|
);
|
||||||
|
const open = visible.filter((i) => !i.doneAt);
|
||||||
|
const done = visible.filter((i) => i.doneAt);
|
||||||
|
// Pasted feedback stays together under its round, flags and all
|
||||||
|
const rounds: { round: NonNullable<BoardItem["round"]>; items: BoardItem[] }[] = [];
|
||||||
|
for (const item of open) {
|
||||||
|
if (!item.round) continue;
|
||||||
|
let r = rounds.find((x) => x.round.id === item.round!.id);
|
||||||
|
if (!r) rounds.push((r = { round: item.round, items: [] }));
|
||||||
|
r.items.push(item);
|
||||||
|
}
|
||||||
|
rounds.sort((a, b) => (a.round.dueAt ?? "9").localeCompare(b.round.dueAt ?? "9"));
|
||||||
|
const loose = open.filter((i) => !i.round);
|
||||||
|
const flagged = loose.filter((i) => i.code && !i.shot);
|
||||||
|
const waiting = loose.filter((i) => i.waitingOn && !(i.code && !i.shot));
|
||||||
|
const rest = loose.filter((i) => !flagged.includes(i) && !waiting.includes(i));
|
||||||
|
|
||||||
|
// Groups keep the order they were first typed in
|
||||||
|
const groups: { name: string; items: BoardItem[] }[] = [];
|
||||||
|
for (const item of rest) {
|
||||||
|
let g = groups.find((x) => x.name === item.group);
|
||||||
|
if (!g) groups.push((g = { name: item.group, items: [] }));
|
||||||
|
g.items.push(item);
|
||||||
|
}
|
||||||
|
groups.sort((a, b) => (a.name === "" ? -1 : b.name === "" ? 1 : 0));
|
||||||
|
|
||||||
|
const pct = project.shotTotal ? Math.round((project.shotComplete / project.shotTotal) * 100) : 0;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<section className="rounded-xl border border-zinc-800 bg-zinc-900">
|
||||||
|
<header className="flex flex-wrap items-center gap-x-3 gap-y-1 border-b border-zinc-800 px-4 py-3">
|
||||||
|
<Link href={`/projects/${project.id}`} className="text-lg font-semibold text-white hover:text-amber-400">
|
||||||
|
{project.name}
|
||||||
|
</Link>
|
||||||
|
<span className="text-xs text-zinc-500">{project.code}</span>
|
||||||
|
{project.status === "ON_HOLD" && (
|
||||||
|
<span className="rounded border border-yellow-500/20 bg-yellow-500/10 px-1.5 py-0.5 text-[10px] font-medium text-yellow-400">
|
||||||
|
On hold
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
<Button
|
||||||
|
size="sm"
|
||||||
|
variant="outline"
|
||||||
|
className="ml-auto h-7"
|
||||||
|
onClick={() => setPasting(true)}
|
||||||
|
title="Paste a client's feedback message"
|
||||||
|
>
|
||||||
|
<MessageSquareText /> Paste feedback
|
||||||
|
</Button>
|
||||||
|
{project.shotTotal > 0 && (
|
||||||
|
<div className="flex items-center gap-2 text-xs text-zinc-400">
|
||||||
|
<div className="h-1.5 w-24 overflow-hidden rounded-full bg-zinc-800">
|
||||||
|
<div className="h-full bg-green-500/70" style={{ width: `${pct}%` }} />
|
||||||
|
</div>
|
||||||
|
{project.shotComplete}/{project.shotTotal} shots complete
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</header>
|
||||||
|
|
||||||
|
<div className="space-y-4 px-4 py-3">
|
||||||
|
<StatusLine project={project} />
|
||||||
|
<Milestones project={project} />
|
||||||
|
|
||||||
|
{rounds.map(({ round, items }) => (
|
||||||
|
<RoundBlock key={round.id} round={round} count={items.length}>
|
||||||
|
{items.map((i) => <ItemRow key={i.id} item={i} users={users} projectId={project.id} />)}
|
||||||
|
</RoundBlock>
|
||||||
|
))}
|
||||||
|
{flagged.length > 0 && (
|
||||||
|
<ItemBlock title="Flags" icon={<Flag className="h-3.5 w-3.5 text-red-400" />}>
|
||||||
|
{flagged.map((i) => <ItemRow key={i.id} item={i} users={users} projectId={project.id} />)}
|
||||||
|
</ItemBlock>
|
||||||
|
)}
|
||||||
|
{waiting.length > 0 && (
|
||||||
|
<ItemBlock title="Waiting on" icon={<Clock className="h-3.5 w-3.5 text-amber-400" />}>
|
||||||
|
{waiting.map((i) => <ItemRow key={i.id} item={i} users={users} projectId={project.id} />)}
|
||||||
|
</ItemBlock>
|
||||||
|
)}
|
||||||
|
{groups.map((g) => (
|
||||||
|
<ItemBlock key={g.name || "_"} title={g.name}>
|
||||||
|
{g.items.map((i) => <ItemRow key={i.id} item={i} users={users} projectId={project.id} />)}
|
||||||
|
</ItemBlock>
|
||||||
|
))}
|
||||||
|
|
||||||
|
<QuickAdd projectId={project.id} />
|
||||||
|
|
||||||
|
{done.length > 0 && (
|
||||||
|
<div>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => setShowDone(!showDone)}
|
||||||
|
className="flex items-center gap-1 text-xs text-zinc-500 hover:text-zinc-300"
|
||||||
|
>
|
||||||
|
{showDone ? <ChevronDown className="h-3.5 w-3.5" /> : <ChevronRight className="h-3.5 w-3.5" />}
|
||||||
|
Done this week ({done.length})
|
||||||
|
</button>
|
||||||
|
{showDone && (
|
||||||
|
<div className="mt-1">
|
||||||
|
{done.map((i) => <ItemRow key={i.id} item={i} users={users} projectId={project.id} />)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<FeedbackPasteDialog
|
||||||
|
projectId={project.id}
|
||||||
|
projectName={project.name}
|
||||||
|
open={pasting}
|
||||||
|
onOpenChange={setPasting}
|
||||||
|
/>
|
||||||
|
</section>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function RoundBlock({
|
||||||
|
round,
|
||||||
|
count,
|
||||||
|
children,
|
||||||
|
}: {
|
||||||
|
round: NonNullable<BoardItem["round"]>;
|
||||||
|
count: number;
|
||||||
|
children: React.ReactNode;
|
||||||
|
}) {
|
||||||
|
const due = round.dueAt ? new Date(round.dueAt) : null;
|
||||||
|
const late = due && due.getTime() < Date.now();
|
||||||
|
const days = due ? differenceInCalendarDays(due, new Date()) : null;
|
||||||
|
const when = due
|
||||||
|
? days === 0 ? `today ${format(due, "HH:mm")}` : days === 1 ? `tomorrow ${format(due, "HH:mm")}` : format(due, "d MMM HH:mm")
|
||||||
|
: null;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div>
|
||||||
|
<div className="mb-1 flex flex-wrap items-center gap-1.5 text-xs uppercase tracking-wider text-zinc-500">
|
||||||
|
<MessageSquareText className="h-3.5 w-3.5 text-indigo-400" />
|
||||||
|
{round.title}
|
||||||
|
{when && (
|
||||||
|
<span
|
||||||
|
className={cn(
|
||||||
|
"rounded px-1.5 py-px normal-case tracking-normal",
|
||||||
|
late ? "bg-red-500/10 text-red-300" : days !== null && days <= 1 ? "bg-amber-500/10 text-amber-300" : "text-zinc-400",
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
{late ? "overdue · " : "due "}{when}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
<span className="normal-case tracking-normal text-zinc-600">{count} open</span>
|
||||||
|
</div>
|
||||||
|
<div className="divide-y divide-zinc-800/60">{children}</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function ItemBlock({ title, icon, children }: { title: string; icon?: React.ReactNode; children: React.ReactNode }) {
|
||||||
|
return (
|
||||||
|
<div>
|
||||||
|
{title && (
|
||||||
|
<div className="mb-1 flex items-center gap-1.5 text-xs uppercase tracking-wider text-zinc-500">
|
||||||
|
{icon}
|
||||||
|
{title}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
<div className="divide-y divide-zinc-800/60">{children}</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function useAction() {
|
||||||
|
const router = useRouter();
|
||||||
|
const { toast } = useToast();
|
||||||
|
const [isPending, startTransition] = useTransition();
|
||||||
|
const run = (fn: () => Promise<unknown>, after?: () => void) =>
|
||||||
|
startTransition(async () => {
|
||||||
|
try {
|
||||||
|
await fn();
|
||||||
|
after?.();
|
||||||
|
router.refresh();
|
||||||
|
} catch (e) {
|
||||||
|
toast({ title: "Couldn't save", description: (e as Error).message, variant: "destructive" });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
return { run, isPending };
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Status line ──────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
function StatusLine({ project }: { project: BoardProject }) {
|
||||||
|
const [editing, setEditing] = useState(false);
|
||||||
|
const [value, setValue] = useState(project.boardStatus ?? "");
|
||||||
|
const { run, isPending } = useAction();
|
||||||
|
|
||||||
|
const save = () =>
|
||||||
|
run(() => setProjectBoardStatus({ projectId: project.id, status: value }), () => setEditing(false));
|
||||||
|
|
||||||
|
if (editing) {
|
||||||
|
return (
|
||||||
|
<div className="space-y-1.5">
|
||||||
|
<textarea
|
||||||
|
autoFocus
|
||||||
|
value={value}
|
||||||
|
onChange={(e) => setValue(e.target.value)}
|
||||||
|
onKeyDown={(e) => {
|
||||||
|
if (e.key === "Enter" && !e.shiftKey) { e.preventDefault(); save(); }
|
||||||
|
if (e.key === "Escape") { setValue(project.boardStatus ?? ""); setEditing(false); }
|
||||||
|
}}
|
||||||
|
rows={2}
|
||||||
|
placeholder="Where things stand — e.g. Awaiting feedback on pick-ups"
|
||||||
|
className="w-full resize-y rounded-lg border border-zinc-700 bg-zinc-950 px-3 py-2 text-sm text-white placeholder:text-zinc-600 focus:border-amber-500/50 focus:outline-none"
|
||||||
|
/>
|
||||||
|
<div className="flex gap-2">
|
||||||
|
<Button size="sm" onClick={save} disabled={isPending}>Save</Button>
|
||||||
|
<Button size="sm" variant="ghost" onClick={() => { setValue(project.boardStatus ?? ""); setEditing(false); }}>
|
||||||
|
Cancel
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => setEditing(true)}
|
||||||
|
className="group block w-full text-left"
|
||||||
|
>
|
||||||
|
{project.boardStatus ? (
|
||||||
|
<p className="whitespace-pre-wrap text-sm text-zinc-200">
|
||||||
|
{project.boardStatus}
|
||||||
|
{project.boardStatusAt && (
|
||||||
|
<span className="ml-2 text-xs text-zinc-600">
|
||||||
|
{formatDistanceToNowStrict(new Date(project.boardStatusAt), { addSuffix: true })}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
<Pencil className="ml-2 inline h-3 w-3 text-zinc-600 opacity-0 group-hover:opacity-100" />
|
||||||
|
</p>
|
||||||
|
) : (
|
||||||
|
<p className="text-sm text-zinc-600 group-hover:text-zinc-400">+ Add a status line</p>
|
||||||
|
)}
|
||||||
|
</button>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Milestones ───────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
function Milestones({ project }: { project: BoardProject }) {
|
||||||
|
const [adding, setAdding] = useState(false);
|
||||||
|
const [label, setLabel] = useState("");
|
||||||
|
const [date, setDate] = useState("");
|
||||||
|
const { run, isPending } = useAction();
|
||||||
|
|
||||||
|
const add = () => {
|
||||||
|
if (!label.trim() || !date) return;
|
||||||
|
// Noon keeps the calendar day stable across the studio/server time zones
|
||||||
|
run(() => addMilestone({ projectId: project.id, label, date: `${date}T12:00:00` }), () => {
|
||||||
|
setLabel("");
|
||||||
|
setDate("");
|
||||||
|
setAdding(false);
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="flex flex-wrap items-center gap-1.5">
|
||||||
|
{project.milestones.map((m) => <MilestoneChip key={m.id} m={m} />)}
|
||||||
|
{adding ? (
|
||||||
|
<div className="flex flex-wrap items-center gap-1.5">
|
||||||
|
<input
|
||||||
|
autoFocus
|
||||||
|
value={label}
|
||||||
|
onChange={(e) => setLabel(e.target.value)}
|
||||||
|
onKeyDown={(e) => e.key === "Enter" && add()}
|
||||||
|
placeholder="e.g. Final delivery"
|
||||||
|
className="h-7 w-40 rounded-md border border-zinc-700 bg-zinc-950 px-2 text-xs text-white placeholder:text-zinc-600 focus:outline-none"
|
||||||
|
/>
|
||||||
|
<input
|
||||||
|
type="date"
|
||||||
|
value={date}
|
||||||
|
onChange={(e) => setDate(e.target.value)}
|
||||||
|
onKeyDown={(e) => e.key === "Enter" && add()}
|
||||||
|
className="h-7 rounded-md border border-zinc-700 bg-zinc-950 px-2 text-xs text-white [color-scheme:dark] focus:outline-none"
|
||||||
|
/>
|
||||||
|
<Button size="sm" className="h-7" onClick={add} disabled={isPending || !label.trim() || !date}>Add</Button>
|
||||||
|
<Button size="sm" variant="ghost" className="h-7" onClick={() => setAdding(false)}>Cancel</Button>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => setAdding(true)}
|
||||||
|
className="flex h-7 items-center gap-1 rounded-md px-2 text-xs text-zinc-600 hover:bg-zinc-800 hover:text-zinc-300"
|
||||||
|
>
|
||||||
|
<Plus className="h-3 w-3" /> Date
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function MilestoneChip({ m }: { m: BoardProject["milestones"][number] }) {
|
||||||
|
const { run } = useAction();
|
||||||
|
const days = differenceInCalendarDays(new Date(m.date), new Date());
|
||||||
|
const done = !!m.doneAt;
|
||||||
|
const late = !done && days < 0;
|
||||||
|
const soon = !done && days >= 0 && days <= 7;
|
||||||
|
const when = done ? "done" : days === 0 ? "today" : days === 1 ? "tomorrow" : days > 0 ? `in ${days}d` : `${-days}d late`;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
className={cn(
|
||||||
|
"group flex h-7 items-center gap-1.5 rounded-md border px-2 text-xs",
|
||||||
|
done ? "border-zinc-800 text-zinc-600" :
|
||||||
|
late ? "border-red-500/30 bg-red-500/10 text-red-300" :
|
||||||
|
soon ? "border-amber-500/30 bg-amber-500/10 text-amber-300" :
|
||||||
|
"border-zinc-700 text-zinc-300",
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
title={done ? "Mark not done" : "Mark done"}
|
||||||
|
onClick={() => run(() => setMilestoneDone(m.id, !done))}
|
||||||
|
className={cn(
|
||||||
|
"flex h-3.5 w-3.5 items-center justify-center rounded-sm border",
|
||||||
|
done ? "border-green-500/50 bg-green-500/20 text-green-400" : "border-current opacity-60 hover:opacity-100",
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
{done && <Check className="h-2.5 w-2.5" />}
|
||||||
|
</button>
|
||||||
|
<span className={cn(done && "line-through")}>{m.label}</span>
|
||||||
|
<span className="opacity-70">{format(new Date(m.date), "d MMM")}</span>
|
||||||
|
<span className="font-medium">· {when}</span>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
title="Remove"
|
||||||
|
onClick={() => { if (confirm(`Remove "${m.label}"?`)) run(() => deleteMilestone(m.id)); }}
|
||||||
|
className="hidden text-zinc-500 hover:text-red-400 group-hover:block"
|
||||||
|
>
|
||||||
|
<X className="h-3 w-3" />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Items ────────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
function ItemRow({ item, users, projectId }: { item: BoardItem; users: User[]; projectId: string }) {
|
||||||
|
const [editing, setEditing] = useState(false);
|
||||||
|
const { run, isPending } = useAction();
|
||||||
|
const done = !!item.doneAt;
|
||||||
|
const flagged = !!item.code && !item.shot;
|
||||||
|
|
||||||
|
if (editing) return <ItemEditor item={item} users={users} onClose={() => setEditing(false)} />;
|
||||||
|
|
||||||
|
const st = item.shot ? SHOT_STATUS[item.shot.status] : null;
|
||||||
|
const v = item.shot?.latest;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className={cn("group flex items-start gap-2.5 py-1.5", isPending && "opacity-50")}>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
title={done ? "Mark not done" : "Mark done"}
|
||||||
|
onClick={() => run(() => setBoardItemDone(item.id, !done))}
|
||||||
|
className={cn(
|
||||||
|
"mt-0.5 flex h-4 w-4 shrink-0 items-center justify-center rounded border",
|
||||||
|
done ? "border-green-500/50 bg-green-500/20 text-green-400" : "border-zinc-600 hover:border-zinc-400",
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
{done && <Check className="h-3 w-3" />}
|
||||||
|
</button>
|
||||||
|
|
||||||
|
<div className="min-w-0 flex-1">
|
||||||
|
<div className="flex flex-wrap items-center gap-x-2 gap-y-1 text-sm">
|
||||||
|
{item.shot && (
|
||||||
|
<Link
|
||||||
|
href={`/projects/${projectId}/shots/${item.shot.id}`}
|
||||||
|
className="font-mono text-xs text-amber-400 hover:underline"
|
||||||
|
>
|
||||||
|
{item.shot.shotCode}
|
||||||
|
</Link>
|
||||||
|
)}
|
||||||
|
{flagged && (
|
||||||
|
<span className="flex items-center gap-1 font-mono text-xs text-red-400" title="Not a shot in this project">
|
||||||
|
<AlertTriangle className="h-3 w-3" />
|
||||||
|
{item.code}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
{st && !done && (
|
||||||
|
<span className={cn("rounded border px-1.5 py-px text-[10px] font-medium", st.color)}>{st.label}</span>
|
||||||
|
)}
|
||||||
|
{v && !done && (
|
||||||
|
<Link href={`/review/${v.id}`} className="text-[11px] text-zinc-500 hover:text-zinc-300">
|
||||||
|
v{String(v.versionNumber).padStart(3, "0")}{" "}
|
||||||
|
<span className={APPROVAL[v.approvalStatus]?.color}>{APPROVAL[v.approvalStatus]?.label}</span>
|
||||||
|
{v.isClientVisible && <span className="text-indigo-400"> · sent</span>}
|
||||||
|
</Link>
|
||||||
|
)}
|
||||||
|
<span className={cn("text-zinc-200", done && "text-zinc-600 line-through")}>{item.text}</span>
|
||||||
|
{item.comment && (
|
||||||
|
<Link
|
||||||
|
href={`/review/${item.comment.versionId}`}
|
||||||
|
className="text-[11px] text-indigo-400/80 hover:text-indigo-300"
|
||||||
|
title="Open the note in the player"
|
||||||
|
>
|
||||||
|
note @ F{item.comment.frame}
|
||||||
|
</Link>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{(item.waitingOn || (flagged && !done)) && (
|
||||||
|
<div className="mt-1 flex flex-wrap items-center gap-2 text-xs">
|
||||||
|
{item.waitingOn && (
|
||||||
|
<span className="flex items-center gap-1 rounded bg-amber-500/10 px-1.5 py-0.5 text-amber-300">
|
||||||
|
<Clock className="h-3 w-3" /> Waiting on {item.waitingOn}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
{flagged && !done && (
|
||||||
|
item.relinkTo ? (
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => run(() => updateBoardItem(item.id, { code: item.relinkTo }))}
|
||||||
|
className="flex items-center gap-1 text-zinc-400 hover:text-amber-400"
|
||||||
|
>
|
||||||
|
<Link2 className="h-3 w-3" />
|
||||||
|
{item.relinkIsExact ? `${item.relinkTo} exists now. Link it` : `Did you mean ${item.relinkTo}?`}
|
||||||
|
</button>
|
||||||
|
) : (
|
||||||
|
<span className="text-zinc-500">Not a shot in this project</span>
|
||||||
|
)
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{item.assignee && (
|
||||||
|
<span className="flex shrink-0 items-center gap-1.5 text-xs text-zinc-400" title={item.assignee.name ?? ""}>
|
||||||
|
<Avatar className="h-5 w-5">
|
||||||
|
{item.assignee.image && <AvatarImage src={item.assignee.image} />}
|
||||||
|
<AvatarFallback className="text-[9px]">{getInitials(item.assignee.name)}</AvatarFallback>
|
||||||
|
</Avatar>
|
||||||
|
<span className="hidden sm:inline">{item.assignee.name?.split(" ")[0]}</span>
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<div className="flex shrink-0 gap-0.5 opacity-100 md:opacity-0 md:group-hover:opacity-100">
|
||||||
|
<button type="button" title="Edit" onClick={() => setEditing(true)} className="rounded p-1 text-zinc-500 hover:bg-zinc-800 hover:text-white">
|
||||||
|
<Pencil className="h-3.5 w-3.5" />
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
title="Delete"
|
||||||
|
onClick={() => { if (confirm("Delete this line?")) run(() => deleteBoardItem(item.id)); }}
|
||||||
|
className="rounded p-1 text-zinc-500 hover:bg-zinc-800 hover:text-red-400"
|
||||||
|
>
|
||||||
|
<Trash2 className="h-3.5 w-3.5" />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function ItemEditor({ item, users, onClose }: { item: BoardItem; users: User[]; onClose: () => void }) {
|
||||||
|
const [code, setCode] = useState(item.shot?.shotCode ?? item.code ?? "");
|
||||||
|
const [text, setText] = useState(item.text);
|
||||||
|
const [assigneeId, setAssigneeId] = useState(item.assignee?.id ?? "");
|
||||||
|
const [waitingOn, setWaitingOn] = useState(item.waitingOn ?? "");
|
||||||
|
const [group, setGroup] = useState(item.group);
|
||||||
|
const { run, isPending } = useAction();
|
||||||
|
|
||||||
|
const save = () =>
|
||||||
|
run(
|
||||||
|
() => updateBoardItem(item.id, { code, text, assigneeId: assigneeId || null, waitingOn, group }),
|
||||||
|
onClose,
|
||||||
|
);
|
||||||
|
|
||||||
|
const field = "h-8 rounded-md border border-zinc-700 bg-zinc-950 px-2 text-xs text-white placeholder:text-zinc-600 focus:border-amber-500/50 focus:outline-none";
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
className="my-1 grid grid-cols-1 gap-2 rounded-lg border border-zinc-700 bg-zinc-950/50 p-2 sm:grid-cols-[10rem_1fr]"
|
||||||
|
onKeyDown={(e) => {
|
||||||
|
if (e.key === "Enter") { e.preventDefault(); save(); }
|
||||||
|
if (e.key === "Escape") onClose();
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<input value={code} onChange={(e) => setCode(e.target.value)} placeholder="Shot code" className={cn(field, "font-mono")} />
|
||||||
|
<input autoFocus value={text} onChange={(e) => setText(e.target.value)} placeholder="Note" className={field} />
|
||||||
|
<select value={assigneeId} onChange={(e) => setAssigneeId(e.target.value)} className={field}>
|
||||||
|
<option value="">Unassigned</option>
|
||||||
|
{users.map((u) => <option key={u.id} value={u.id}>{u.name ?? u.email}</option>)}
|
||||||
|
</select>
|
||||||
|
<input value={waitingOn} onChange={(e) => setWaitingOn(e.target.value)} placeholder="Waiting on (blank = not blocked)" className={field} />
|
||||||
|
<input value={group} onChange={(e) => setGroup(e.target.value)} placeholder="Heading (optional)" className={field} />
|
||||||
|
<div className="flex justify-end gap-2">
|
||||||
|
<Button size="sm" variant="ghost" onClick={onClose}>Cancel</Button>
|
||||||
|
<Button size="sm" onClick={save} disabled={isPending}>Save</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function QuickAdd({ projectId }: { projectId: string }) {
|
||||||
|
const [value, setValue] = useState("");
|
||||||
|
const ref = useRef<HTMLTextAreaElement>(null);
|
||||||
|
const { toast } = useToast();
|
||||||
|
const { run, isPending } = useAction();
|
||||||
|
|
||||||
|
// Grow with pasted blocks
|
||||||
|
useEffect(() => {
|
||||||
|
const el = ref.current;
|
||||||
|
if (!el) return;
|
||||||
|
el.style.height = "auto";
|
||||||
|
el.style.height = `${Math.min(el.scrollHeight, 320)}px`;
|
||||||
|
}, [value]);
|
||||||
|
|
||||||
|
const submit = () => {
|
||||||
|
if (!value.trim()) return;
|
||||||
|
run(async () => {
|
||||||
|
const res = await addBoardItems({ projectId, input: value });
|
||||||
|
if (res.unmatched.length) {
|
||||||
|
toast({
|
||||||
|
title: `${res.unmatched.length} code${res.unmatched.length === 1 ? "" : "s"} not in this project`,
|
||||||
|
description: `${res.unmatched.join(", ")}: flagged on the board.`,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}, () => setValue(""));
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div>
|
||||||
|
<textarea
|
||||||
|
ref={ref}
|
||||||
|
value={value}
|
||||||
|
onChange={(e) => setValue(e.target.value)}
|
||||||
|
onKeyDown={(e) => {
|
||||||
|
if (e.key === "Enter" && !e.shiftKey) { e.preventDefault(); submit(); }
|
||||||
|
}}
|
||||||
|
rows={1}
|
||||||
|
disabled={isPending}
|
||||||
|
placeholder="Add a line, e.g. SHOT_CODE finalise (Chris) wait: client GFX, or paste a list"
|
||||||
|
className="w-full resize-none rounded-lg border border-dashed border-zinc-700 bg-transparent px-3 py-2 text-sm text-white placeholder:text-zinc-600 focus:border-solid focus:border-amber-500/50 focus:outline-none"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,342 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useState, useTransition } from "react";
|
||||||
|
import { useRouter } from "next/navigation";
|
||||||
|
import { format } from "date-fns";
|
||||||
|
import { AlertTriangle, ArrowLeft, Link2, MessageSquareText } from "lucide-react";
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from "@/components/ui/dialog";
|
||||||
|
import { useToast } from "@/components/ui/use-toast";
|
||||||
|
import { cn } from "@/lib/utils";
|
||||||
|
import { parseDue } from "@/lib/feedback-parse";
|
||||||
|
import { commitFeedback, previewFeedback, type FeedbackPreview, type FeedbackPreviewNote } from "@/actions/feedback";
|
||||||
|
|
||||||
|
type NoteState = {
|
||||||
|
include: boolean;
|
||||||
|
text: string;
|
||||||
|
versionId: string | null;
|
||||||
|
/** Typed frame; null = use the selected version's converted frame */
|
||||||
|
frame: string | null;
|
||||||
|
setChanges: boolean;
|
||||||
|
};
|
||||||
|
type RoundState = { title: string; due: string; notes: Record<string, NoteState> };
|
||||||
|
|
||||||
|
const LOCAL_DT = "yyyy-MM-dd'T'HH:mm";
|
||||||
|
|
||||||
|
function initialState(preview: FeedbackPreview): RoundState[] {
|
||||||
|
return preview.rounds.map((r) => {
|
||||||
|
const due = parseDue(r.dueText);
|
||||||
|
return {
|
||||||
|
title: r.title || `Feedback ${format(new Date(), "d MMM")}`,
|
||||||
|
due: due ? format(due, LOCAL_DT) : "",
|
||||||
|
notes: Object.fromEntries(
|
||||||
|
r.notes.map((n) => [
|
||||||
|
n.key,
|
||||||
|
{ include: true, text: n.text, versionId: n.defaultVersionId, frame: null, setChanges: true },
|
||||||
|
]),
|
||||||
|
),
|
||||||
|
};
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export function FeedbackPasteDialog({
|
||||||
|
projectId,
|
||||||
|
projectName,
|
||||||
|
open,
|
||||||
|
onOpenChange,
|
||||||
|
}: {
|
||||||
|
projectId: string;
|
||||||
|
projectName: string;
|
||||||
|
open: boolean;
|
||||||
|
onOpenChange: (open: boolean) => void;
|
||||||
|
}) {
|
||||||
|
const router = useRouter();
|
||||||
|
const { toast } = useToast();
|
||||||
|
const [input, setInput] = useState("");
|
||||||
|
const [preview, setPreview] = useState<FeedbackPreview | null>(null);
|
||||||
|
const [rounds, setRounds] = useState<RoundState[]>([]);
|
||||||
|
const [isPending, startTransition] = useTransition();
|
||||||
|
|
||||||
|
const reset = () => {
|
||||||
|
setInput("");
|
||||||
|
setPreview(null);
|
||||||
|
setRounds([]);
|
||||||
|
};
|
||||||
|
|
||||||
|
const read = (text: string) =>
|
||||||
|
startTransition(async () => {
|
||||||
|
try {
|
||||||
|
const p = await previewFeedback(projectId, text);
|
||||||
|
if (p.rounds.length === 0) {
|
||||||
|
toast({ title: "No shot notes found", description: "Each note needs to start with a shot code.", variant: "destructive" });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setPreview(p);
|
||||||
|
setRounds(initialState(p));
|
||||||
|
} catch (e) {
|
||||||
|
toast({ title: "Couldn't read feedback", description: (e as Error).message, variant: "destructive" });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// Accepting a suggested code rewrites the paste and reads it again, so
|
||||||
|
// everything downstream (versions, frames) comes from the real shot.
|
||||||
|
const applySuggestion = (code: string, suggestion: string) => {
|
||||||
|
const next = input.split(code).join(suggestion);
|
||||||
|
setInput(next);
|
||||||
|
read(next);
|
||||||
|
};
|
||||||
|
|
||||||
|
const updateNote = (ri: number, key: string, patch: Partial<NoteState>) =>
|
||||||
|
setRounds((rs) => rs.map((r, i) => (i === ri ? { ...r, notes: { ...r.notes, [key]: { ...r.notes[key], ...patch } } } : r)));
|
||||||
|
|
||||||
|
const frameFor = (n: FeedbackPreviewNote, s: NoteState): number | null => {
|
||||||
|
if (s.frame !== null) return s.frame.trim() === "" ? null : Number(s.frame);
|
||||||
|
return n.versions.find((v) => v.id === s.versionId)?.playerFrame ?? null;
|
||||||
|
};
|
||||||
|
|
||||||
|
const included = preview
|
||||||
|
? preview.rounds.flatMap((r, ri) => r.notes.filter((n) => rounds[ri]?.notes[n.key]?.include && rounds[ri].notes[n.key].text.trim()))
|
||||||
|
: [];
|
||||||
|
|
||||||
|
const save = () => {
|
||||||
|
if (!preview) return;
|
||||||
|
const payload = preview.rounds
|
||||||
|
.map((r, ri) => {
|
||||||
|
const rs = rounds[ri];
|
||||||
|
return {
|
||||||
|
title: rs.title,
|
||||||
|
dueAt: rs.due ? new Date(rs.due).toISOString() : null,
|
||||||
|
notes: r.notes
|
||||||
|
.filter((n) => rs.notes[n.key].include && rs.notes[n.key].text.trim())
|
||||||
|
.map((n) => {
|
||||||
|
const s = rs.notes[n.key];
|
||||||
|
const frame = frameFor(n, s);
|
||||||
|
return {
|
||||||
|
code: n.code,
|
||||||
|
shotId: n.shot?.id ?? null,
|
||||||
|
text: s.text.trim(),
|
||||||
|
versionId: n.shot ? s.versionId : null,
|
||||||
|
frame: frame != null && Number.isFinite(frame) && frame >= 0 ? Math.floor(frame) : null,
|
||||||
|
setChanges: !!s.versionId && s.setChanges,
|
||||||
|
};
|
||||||
|
}),
|
||||||
|
};
|
||||||
|
})
|
||||||
|
.filter((r) => r.notes.length > 0);
|
||||||
|
if (payload.length === 0) return;
|
||||||
|
|
||||||
|
startTransition(async () => {
|
||||||
|
try {
|
||||||
|
const res = await commitFeedback({ projectId, rounds: payload });
|
||||||
|
toast({
|
||||||
|
title: `${res.notes} note${res.notes === 1 ? "" : "s"} logged`,
|
||||||
|
description: `${res.comments} in the player · ${res.tasksChanged} task${res.tasksChanged === 1 ? "" : "s"} moved to Changes`,
|
||||||
|
});
|
||||||
|
reset();
|
||||||
|
onOpenChange(false);
|
||||||
|
router.refresh();
|
||||||
|
} catch (e) {
|
||||||
|
toast({ title: "Couldn't save feedback", description: (e as Error).message, variant: "destructive" });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
const field = "rounded-md border border-zinc-700 bg-zinc-950 px-2 text-xs text-white placeholder:text-zinc-600 focus:border-amber-500/50 focus:outline-none";
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Dialog open={open} onOpenChange={(o) => { if (!o) reset(); onOpenChange(o); }}>
|
||||||
|
<DialogContent className="max-h-[90vh] max-w-4xl overflow-y-auto">
|
||||||
|
<DialogHeader>
|
||||||
|
<DialogTitle className="flex items-center gap-2">
|
||||||
|
<MessageSquareText className="h-4 w-4 text-amber-400" />
|
||||||
|
Paste client feedback · {projectName}
|
||||||
|
</DialogTitle>
|
||||||
|
<DialogDescription>
|
||||||
|
{preview
|
||||||
|
? "Check where each note will go. Notes are saved in the player as client feedback and added to the board."
|
||||||
|
: "Paste the message as it arrived. Each note should start with a shot code; a line like “FEEDBACK 113 DUE Oct 7 12:00 PM” starts a round."}
|
||||||
|
</DialogDescription>
|
||||||
|
</DialogHeader>
|
||||||
|
|
||||||
|
{!preview ? (
|
||||||
|
<div className="space-y-3">
|
||||||
|
<textarea
|
||||||
|
autoFocus
|
||||||
|
value={input}
|
||||||
|
onChange={(e) => setInput(e.target.value)}
|
||||||
|
rows={12}
|
||||||
|
placeholder={"FEEDBACK 113 DUE Oct 7, 2026 12:00 PM\nUNG_113_008_040 The screen is partially peeking under the mask\nUNG_113_018_050 At frame 1018, the mask is still slipping"}
|
||||||
|
className={cn(field, "w-full resize-y py-2 font-mono text-[13px] leading-relaxed")}
|
||||||
|
/>
|
||||||
|
<div className="flex justify-end">
|
||||||
|
<Button onClick={() => read(input)} disabled={isPending || !input.trim()}>
|
||||||
|
{isPending ? "Reading…" : "Read feedback"}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<div className="space-y-5">
|
||||||
|
{preview.ignored.length > 0 && (
|
||||||
|
<p className="text-xs text-zinc-500">
|
||||||
|
Skipped (no shot code): {preview.ignored.map((l) => `“${l}”`).join(", ")}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{preview.rounds.map((r, ri) => {
|
||||||
|
const rs = rounds[ri];
|
||||||
|
if (!rs) return null;
|
||||||
|
return (
|
||||||
|
<div key={ri} className="space-y-2">
|
||||||
|
<div className="flex flex-wrap items-center gap-2">
|
||||||
|
<input
|
||||||
|
value={rs.title}
|
||||||
|
onChange={(e) => setRounds((all) => all.map((x, i) => (i === ri ? { ...x, title: e.target.value } : x)))}
|
||||||
|
className={cn(field, "h-8 w-56 text-sm font-medium")}
|
||||||
|
/>
|
||||||
|
<span className="text-xs text-zinc-500">due</span>
|
||||||
|
<input
|
||||||
|
type="datetime-local"
|
||||||
|
value={rs.due}
|
||||||
|
onChange={(e) => setRounds((all) => all.map((x, i) => (i === ri ? { ...x, due: e.target.value } : x)))}
|
||||||
|
className={cn(field, "h-8 [color-scheme:dark]")}
|
||||||
|
/>
|
||||||
|
{r.dueText && !rs.due && (
|
||||||
|
<span className="text-xs text-amber-400">Couldn’t read “{r.dueText}”, set it by hand</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="overflow-x-auto rounded-lg border border-zinc-800">
|
||||||
|
<table className="w-full text-xs">
|
||||||
|
<thead className="bg-zinc-950 text-left uppercase tracking-wider text-zinc-500">
|
||||||
|
<tr>
|
||||||
|
<th className="w-8 px-2 py-2" />
|
||||||
|
<th className="px-2 py-2">Shot</th>
|
||||||
|
<th className="px-2 py-2">Note</th>
|
||||||
|
<th className="px-2 py-2">Version</th>
|
||||||
|
<th className="px-2 py-2">Frame</th>
|
||||||
|
<th className="px-2 py-2" title="Move the task to Changes">Changes</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody className="divide-y divide-zinc-800">
|
||||||
|
{r.notes.map((n) => {
|
||||||
|
const s = rs.notes[n.key];
|
||||||
|
const v = n.versions.find((x) => x.id === s.versionId) ?? null;
|
||||||
|
const frame = frameFor(n, s);
|
||||||
|
return (
|
||||||
|
<tr key={n.key} className={cn("align-top", !s.include && "opacity-40")}>
|
||||||
|
<td className="px-2 py-2">
|
||||||
|
<input
|
||||||
|
type="checkbox"
|
||||||
|
checked={s.include}
|
||||||
|
onChange={(e) => updateNote(ri, n.key, { include: e.target.checked })}
|
||||||
|
className="mt-1 accent-amber-500"
|
||||||
|
/>
|
||||||
|
</td>
|
||||||
|
<td className="whitespace-nowrap px-2 py-2 font-mono">
|
||||||
|
{n.shot ? (
|
||||||
|
<span className="text-amber-400">{n.shot.shotCode}</span>
|
||||||
|
) : (
|
||||||
|
<div className="space-y-1">
|
||||||
|
<span className="flex items-center gap-1 text-red-400">
|
||||||
|
<AlertTriangle className="h-3 w-3" /> {n.code}
|
||||||
|
</span>
|
||||||
|
{n.suggestion ? (
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => applySuggestion(n.code, n.suggestion!)}
|
||||||
|
className="flex items-center gap-1 font-sans text-zinc-400 hover:text-amber-400"
|
||||||
|
>
|
||||||
|
<Link2 className="h-3 w-3" /> Use {n.suggestion}
|
||||||
|
</button>
|
||||||
|
) : (
|
||||||
|
<span className="block font-sans text-zinc-500">Not in project; flag only</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</td>
|
||||||
|
<td className="min-w-[16rem] px-2 py-2">
|
||||||
|
<textarea
|
||||||
|
value={s.text}
|
||||||
|
onChange={(e) => updateNote(ri, n.key, { text: e.target.value })}
|
||||||
|
rows={Math.min(5, Math.max(1, Math.ceil(s.text.length / 60)))}
|
||||||
|
className={cn(field, "w-full resize-y py-1 leading-snug")}
|
||||||
|
/>
|
||||||
|
</td>
|
||||||
|
<td className="px-2 py-2">
|
||||||
|
{n.versions.length > 0 ? (
|
||||||
|
<select
|
||||||
|
value={s.versionId ?? ""}
|
||||||
|
onChange={(e) => updateNote(ri, n.key, { versionId: e.target.value || null, frame: null })}
|
||||||
|
className={cn(field, "h-7")}
|
||||||
|
>
|
||||||
|
{n.versions.map((o) => (
|
||||||
|
<option key={o.id} value={o.id}>
|
||||||
|
{o.label}
|
||||||
|
{o.sent ? ` · sent${o.sharedAt ? " " + format(new Date(o.sharedAt), "d MMM") : ""}` : " · not sent"}
|
||||||
|
</option>
|
||||||
|
))}
|
||||||
|
<option value="">Board only</option>
|
||||||
|
</select>
|
||||||
|
) : (
|
||||||
|
<span className="text-zinc-500">{n.shot ? "No versions; board only" : "—"}</span>
|
||||||
|
)}
|
||||||
|
{v && !v.sent && <span className="mt-1 block text-amber-400/80">Not sent to client</span>}
|
||||||
|
</td>
|
||||||
|
<td className="px-2 py-2">
|
||||||
|
{s.versionId ? (
|
||||||
|
<>
|
||||||
|
<input
|
||||||
|
inputMode="numeric"
|
||||||
|
value={s.frame ?? (frame != null ? String(frame) : "")}
|
||||||
|
onChange={(e) => updateNote(ri, n.key, { frame: e.target.value.replace(/\D/g, "") })}
|
||||||
|
placeholder="0"
|
||||||
|
className={cn(field, "h-7 w-16 font-mono")}
|
||||||
|
/>
|
||||||
|
{n.quotedFrame != null && s.frame === null && v && (
|
||||||
|
<span className="mt-1 block whitespace-nowrap text-zinc-500">
|
||||||
|
{v.fromComp ? `comp ${n.quotedFrame}` : `as quoted`}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
<span className="text-zinc-600">—</span>
|
||||||
|
)}
|
||||||
|
</td>
|
||||||
|
<td className="px-2 py-2 text-center">
|
||||||
|
{v?.taskId ? (
|
||||||
|
<input
|
||||||
|
type="checkbox"
|
||||||
|
checked={s.setChanges}
|
||||||
|
disabled={v.taskStatus === "CHANGES"}
|
||||||
|
title={v.taskStatus === "CHANGES" ? "Already in Changes" : "Move the task to Changes"}
|
||||||
|
onChange={(e) => updateNote(ri, n.key, { setChanges: e.target.checked })}
|
||||||
|
className="mt-1 accent-amber-500"
|
||||||
|
/>
|
||||||
|
) : (
|
||||||
|
<span className="text-zinc-600">—</span>
|
||||||
|
)}
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
|
||||||
|
<div className="flex flex-wrap items-center justify-between gap-2">
|
||||||
|
<Button variant="ghost" onClick={() => setPreview(null)} disabled={isPending}>
|
||||||
|
<ArrowLeft /> Edit paste
|
||||||
|
</Button>
|
||||||
|
<Button onClick={save} disabled={isPending || included.length === 0}>
|
||||||
|
{isPending ? "Saving…" : `Save ${included.length} note${included.length === 1 ? "" : "s"}`}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</DialogContent>
|
||||||
|
</Dialog>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,169 @@
|
|||||||
|
import { auth } from "@/auth";
|
||||||
|
import { db } from "@/lib/db";
|
||||||
|
import { redirect } from "next/navigation";
|
||||||
|
import { suggestShot } from "@/lib/board-parse";
|
||||||
|
import { BoardClient, type BoardProject } from "./BoardClient";
|
||||||
|
|
||||||
|
export const metadata = { title: "Board" };
|
||||||
|
|
||||||
|
// Done lines stay visible this long so "what did we get through" is answerable
|
||||||
|
const DONE_WINDOW_MS = 7 * 86400000;
|
||||||
|
|
||||||
|
export default async function BoardPage({
|
||||||
|
searchParams,
|
||||||
|
}: {
|
||||||
|
searchParams: Promise<{ who?: string }>;
|
||||||
|
}) {
|
||||||
|
const session = await auth();
|
||||||
|
if (!session?.user) redirect("/login");
|
||||||
|
if (session.user.role === "CLIENT") redirect("/dashboard");
|
||||||
|
|
||||||
|
const { who } = await searchParams;
|
||||||
|
const doneSince = new Date(Date.now() - DONE_WINDOW_MS);
|
||||||
|
|
||||||
|
const [projects, users] = await Promise.all([
|
||||||
|
db.project.findMany({
|
||||||
|
where: { status: { in: ["ACTIVE", "ON_HOLD"] } },
|
||||||
|
orderBy: [{ status: "asc" }, { name: "asc" }],
|
||||||
|
select: {
|
||||||
|
id: true,
|
||||||
|
name: true,
|
||||||
|
code: true,
|
||||||
|
status: true,
|
||||||
|
boardStatus: true,
|
||||||
|
boardStatusAt: true,
|
||||||
|
milestones: { orderBy: { date: "asc" } },
|
||||||
|
boardItems: {
|
||||||
|
where: { OR: [{ doneAt: null }, { doneAt: { gte: doneSince } }] },
|
||||||
|
orderBy: { sortOrder: "asc" },
|
||||||
|
include: {
|
||||||
|
assignee: { select: { id: true, name: true, image: true } },
|
||||||
|
round: { select: { id: true, title: true, dueAt: true } },
|
||||||
|
shot: {
|
||||||
|
select: {
|
||||||
|
id: true,
|
||||||
|
shotCode: true,
|
||||||
|
status: true,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
db.user.findMany({
|
||||||
|
where: { isActive: true, role: { not: "CLIENT" } },
|
||||||
|
select: { id: true, name: true, email: true, image: true },
|
||||||
|
orderBy: { name: "asc" },
|
||||||
|
}),
|
||||||
|
]);
|
||||||
|
|
||||||
|
const projectIds = projects.map((p) => p.id);
|
||||||
|
|
||||||
|
// Latest version per linked shot — versions hang off the shot or its task
|
||||||
|
const linkedShotIds = [...new Set(projects.flatMap((p) => p.boardItems.map((i) => i.shotId).filter(Boolean) as string[]))];
|
||||||
|
const latestByShot = new Map<string, { id: string; versionNumber: number; approvalStatus: string; isClientVisible: boolean }>();
|
||||||
|
if (linkedShotIds.length) {
|
||||||
|
const versions = await db.version.findMany({
|
||||||
|
where: { OR: [{ shotId: { in: linkedShotIds } }, { task: { shotId: { in: linkedShotIds } } }] },
|
||||||
|
orderBy: { createdAt: "desc" },
|
||||||
|
select: {
|
||||||
|
id: true, versionNumber: true, approvalStatus: true, isClientVisible: true,
|
||||||
|
shotId: true, task: { select: { shotId: true } },
|
||||||
|
},
|
||||||
|
});
|
||||||
|
for (const v of versions) {
|
||||||
|
const sid = v.shotId ?? v.task?.shotId;
|
||||||
|
if (sid && !latestByShot.has(sid)) latestByShot.set(sid, v);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Pasted-feedback lines link to the comment they were saved as
|
||||||
|
const commentIds = projects.flatMap((p) => p.boardItems.map((i) => i.commentId).filter(Boolean) as string[]);
|
||||||
|
const commentVersion = new Map(
|
||||||
|
(commentIds.length
|
||||||
|
? await db.comment.findMany({ where: { id: { in: commentIds } }, select: { id: true, versionId: true, frameNumber: true } })
|
||||||
|
: []
|
||||||
|
).map((c) => [c.id, c]),
|
||||||
|
);
|
||||||
|
const shotCounts = await db.shot.groupBy({
|
||||||
|
by: ["projectId", "status"],
|
||||||
|
where: { projectId: { in: projectIds } },
|
||||||
|
_count: { _all: true },
|
||||||
|
});
|
||||||
|
|
||||||
|
// Lines whose code did not match a shot when typed: the shot may exist now,
|
||||||
|
// or there may be an obvious near-miss (DH2_004_100 → DH2_VFX_004_100).
|
||||||
|
const flaggedProjects = projects.filter((p) => p.boardItems.some((i) => i.code && !i.shotId));
|
||||||
|
const shotsByProject = new Map(
|
||||||
|
await Promise.all(
|
||||||
|
flaggedProjects.map(async (p) => [
|
||||||
|
p.id,
|
||||||
|
await db.shot.findMany({
|
||||||
|
where: { projectId: p.id },
|
||||||
|
select: { id: true, shotCode: true, clientCode: true },
|
||||||
|
}),
|
||||||
|
] as const),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
const data: BoardProject[] = projects.map((p) => {
|
||||||
|
const counts = shotCounts.filter((c) => c.projectId === p.id);
|
||||||
|
const shots = shotsByProject.get(p.id) ?? [];
|
||||||
|
return {
|
||||||
|
id: p.id,
|
||||||
|
name: p.name,
|
||||||
|
code: p.code,
|
||||||
|
status: p.status,
|
||||||
|
boardStatus: p.boardStatus,
|
||||||
|
boardStatusAt: p.boardStatusAt?.toISOString() ?? null,
|
||||||
|
shotTotal: counts.reduce((n, c) => n + c._count._all, 0),
|
||||||
|
shotComplete: counts.find((c) => c.status === "COMPLETE")?._count._all ?? 0,
|
||||||
|
milestones: p.milestones.map((m) => ({
|
||||||
|
id: m.id,
|
||||||
|
label: m.label,
|
||||||
|
date: m.date.toISOString(),
|
||||||
|
doneAt: m.doneAt?.toISOString() ?? null,
|
||||||
|
})),
|
||||||
|
items: p.boardItems.map((i) => {
|
||||||
|
const v = i.shot ? latestByShot.get(i.shot.id) : undefined;
|
||||||
|
const nowMatches = !i.shotId && i.code
|
||||||
|
? shots.find((s) => s.shotCode.toUpperCase() === i.code!.toUpperCase())
|
||||||
|
: undefined;
|
||||||
|
const suggestion = !i.shotId && i.code && !nowMatches ? suggestShot(i.code, shots) : null;
|
||||||
|
return {
|
||||||
|
id: i.id,
|
||||||
|
text: i.text,
|
||||||
|
code: i.code,
|
||||||
|
group: i.group,
|
||||||
|
waitingOn: i.waitingOn,
|
||||||
|
round: i.round ? { id: i.round.id, title: i.round.title, dueAt: i.round.dueAt?.toISOString() ?? null } : null,
|
||||||
|
comment: i.commentId && commentVersion.has(i.commentId)
|
||||||
|
? { versionId: commentVersion.get(i.commentId)!.versionId, frame: commentVersion.get(i.commentId)!.frameNumber }
|
||||||
|
: null,
|
||||||
|
doneAt: i.doneAt?.toISOString() ?? null,
|
||||||
|
assignee: i.assignee,
|
||||||
|
shot: i.shot
|
||||||
|
? {
|
||||||
|
id: i.shot.id,
|
||||||
|
shotCode: i.shot.shotCode,
|
||||||
|
status: i.shot.status,
|
||||||
|
latest: v
|
||||||
|
? {
|
||||||
|
id: v.id,
|
||||||
|
versionNumber: v.versionNumber,
|
||||||
|
approvalStatus: v.approvalStatus,
|
||||||
|
isClientVisible: v.isClientVisible,
|
||||||
|
}
|
||||||
|
: null,
|
||||||
|
}
|
||||||
|
: null,
|
||||||
|
// Shot created since the line was typed: offer to link it
|
||||||
|
relinkTo: nowMatches?.shotCode ?? suggestion?.shotCode ?? null,
|
||||||
|
relinkIsExact: !!nowMatches,
|
||||||
|
};
|
||||||
|
}),
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
return <BoardClient projects={data} users={users} who={who ?? null} />;
|
||||||
|
}
|
||||||
@@ -59,7 +59,7 @@ export default async function ClientDetailPage({
|
|||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="p-6 max-w-5xl mx-auto space-y-6">
|
<div className="p-4 md:p-6 max-w-5xl mx-auto space-y-6">
|
||||||
{/* Back */}
|
{/* Back */}
|
||||||
<Link
|
<Link
|
||||||
href="/clients"
|
href="/clients"
|
||||||
|
|||||||
@@ -26,7 +26,7 @@ export default async function ClientsPage() {
|
|||||||
const clients = await getClients();
|
const clients = await getClients();
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="p-6 max-w-5xl mx-auto space-y-6">
|
<div className="p-4 md:p-6 max-w-5xl mx-auto space-y-6">
|
||||||
{/* Header */}
|
{/* Header */}
|
||||||
<div className="flex items-center justify-between">
|
<div className="flex items-center justify-between">
|
||||||
<div>
|
<div>
|
||||||
|
|||||||
@@ -1,58 +1,69 @@
|
|||||||
import { auth } from "@/auth";
|
import { auth } from "@/auth";
|
||||||
import { db } from "@/lib/db";
|
import { db } from "@/lib/db";
|
||||||
import { StatsCards } from "@/components/dashboard/StatsCards";
|
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 { AwaitingDelivery } from "@/components/dashboard/AwaitingDelivery";
|
||||||
|
import { LogRequestButton } from "@/components/dashboard/LogRequestButton";
|
||||||
|
import { RecentDeliveries } from "@/components/dashboard/RecentDeliveries";
|
||||||
|
import { WhoseCourt } from "@/components/dashboard/WhoseCourt";
|
||||||
import { ShotQueue } from "@/components/dashboard/ShotQueue";
|
import { ShotQueue } from "@/components/dashboard/ShotQueue";
|
||||||
import { RecentActivity } from "@/components/dashboard/RecentActivity";
|
|
||||||
import { TaskWidgets } from "@/components/dashboard/TaskWidgets";
|
import { TaskWidgets } from "@/components/dashboard/TaskWidgets";
|
||||||
import { ScheduleWidgets } from "@/components/dashboard/ScheduleWidgets";
|
import { ScheduleWidgets } from "@/components/dashboard/ScheduleWidgets";
|
||||||
|
import {
|
||||||
|
getAwaitingDelivery,
|
||||||
|
getBlockedExports,
|
||||||
|
getDeliveryCountdown,
|
||||||
|
getFarmStatus,
|
||||||
|
getOpsCounts,
|
||||||
|
getQcQueue,
|
||||||
|
getQcStaleHours,
|
||||||
|
getRecentDeliveries,
|
||||||
|
getWhoseCourt,
|
||||||
|
} from "@/lib/dashboard/ops";
|
||||||
|
import { listDeliveryRequests } from "@/lib/render-pipeline/delivery-requests";
|
||||||
import type { DashboardStats } from "@/types";
|
import type { DashboardStats } from "@/types";
|
||||||
|
|
||||||
export const metadata = { title: "Dashboard" };
|
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) {
|
async function getDashboardData(userId: string, role: string) {
|
||||||
const isArtist = role === "ARTIST";
|
const isArtist = role === "ARTIST";
|
||||||
const isClient = role === "CLIENT";
|
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,
|
// Producers see the floor; an artist sees the failures that are theirs.
|
||||||
tasksDueToday, tasksInReview, tasksOverdue, myTasksCount] =
|
const [counts, blocked, farm, episodes, qcQueue, qcStaleHours, deliveries, awaitingDelivery, openRequests, court] =
|
||||||
await Promise.all([
|
await Promise.all([
|
||||||
db.version.count({ where: { approvalStatus: "PENDING_REVIEW" } }),
|
getOpsCounts(isArtist ? userId : undefined),
|
||||||
db.version.count({ where: { approvalStatus: "NEEDS_CHANGES" } }),
|
getBlockedExports(isArtist ? { artistId: userId } : {}),
|
||||||
db.version.count({ where: { approvalStatus: "APPROVED" } }),
|
getFarmStatus(),
|
||||||
db.project.count({ where: { status: "ACTIVE" } }),
|
getDeliveryCountdown(),
|
||||||
db.task.count({
|
isArtist || isClient ? [] : getQcQueue(),
|
||||||
where: {
|
getQcStaleHours(),
|
||||||
dueDate: { gte: todayStart, lt: todayEnd },
|
isArtist || isClient ? [] : getRecentDeliveries(),
|
||||||
status: { not: "DONE" },
|
isArtist || isClient ? [] : getAwaitingDelivery(),
|
||||||
...(isArtist ? { assignedArtistId: userId } : {}),
|
isArtist || isClient ? [] : listDeliveryRequests({ openOnly: true }),
|
||||||
},
|
isArtist || isClient ? null : getWhoseCourt(),
|
||||||
}),
|
|
||||||
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" } },
|
|
||||||
}),
|
|
||||||
]);
|
]);
|
||||||
|
|
||||||
const shotsWhere = isArtist ? { artistId: userId } : {};
|
// An artist's own shots come first; everyone else sees the floor.
|
||||||
const shots = await db.shot.findMany({
|
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,
|
take: 15,
|
||||||
orderBy: { updatedAt: "desc" },
|
orderBy: [{ dueDate: { sort: "asc", nulls: "last" } }, { updatedAt: "desc" }],
|
||||||
include: {
|
include: {
|
||||||
artist: { select: { id: true, name: true, image: true, email: true } },
|
artist: { select: { id: true, name: true, image: true, email: true } },
|
||||||
versions: {
|
versions: {
|
||||||
@@ -63,12 +74,8 @@ async function getDashboardData(userId: string, role: string) {
|
|||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
// My tasks (for widget)
|
|
||||||
const myTasks = await db.task.findMany({
|
const myTasks = await db.task.findMany({
|
||||||
where: {
|
where: { assignedArtistId: userId, status: { not: "DONE" } },
|
||||||
assignedArtistId: userId,
|
|
||||||
status: { not: "DONE" },
|
|
||||||
},
|
|
||||||
take: 8,
|
take: 8,
|
||||||
orderBy: [{ dueDate: "asc" }, { priority: "desc" }],
|
orderBy: [{ dueDate: "asc" }, { priority: "desc" }],
|
||||||
include: {
|
include: {
|
||||||
@@ -78,7 +85,6 @@ async function getDashboardData(userId: string, role: string) {
|
|||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
// Tasks in review (for supervisors/producers)
|
|
||||||
const reviewTasks = isArtist || isClient ? [] : await db.task.findMany({
|
const reviewTasks = isArtist || isClient ? [] : await db.task.findMany({
|
||||||
where: { status: { in: ["INTERNAL_REVIEW", "CLIENT_REVIEW"] } },
|
where: { status: { in: ["INTERNAL_REVIEW", "CLIENT_REVIEW"] } },
|
||||||
take: 8,
|
take: 8,
|
||||||
@@ -91,14 +97,8 @@ async function getDashboardData(userId: string, role: string) {
|
|||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
const activity = await db.notification.findMany({
|
// Schedule overview (producers/supervisors/admins) — unchanged; it reads the
|
||||||
where: isClient ? { userId } : {},
|
// schedule page's own data rather than anything the pipeline owns.
|
||||||
take: 20,
|
|
||||||
orderBy: { createdAt: "desc" },
|
|
||||||
include: { user: { select: { name: true, image: true } } },
|
|
||||||
});
|
|
||||||
|
|
||||||
// Schedule data (for producers/supervisors/admins)
|
|
||||||
const scheduledTasks =
|
const scheduledTasks =
|
||||||
!isArtist && !isClient
|
!isArtist && !isClient
|
||||||
? await db.task.findMany({
|
? await db.task.findMany({
|
||||||
@@ -119,46 +119,59 @@ async function getDashboardData(userId: string, role: string) {
|
|||||||
!isArtist && !isClient
|
!isArtist && !isClient
|
||||||
? await db.user.findMany({
|
? await db.user.findMany({
|
||||||
where: { isActive: true, role: { not: "CLIENT" } },
|
where: { isActive: true, role: { not: "CLIENT" } },
|
||||||
select: {
|
select: { id: true, name: true, email: true, image: true, role: true },
|
||||||
id: true,
|
|
||||||
name: true,
|
|
||||||
email: true,
|
|
||||||
image: true,
|
|
||||||
role: true,
|
|
||||||
},
|
|
||||||
orderBy: { name: "asc" },
|
orderBy: { name: "asc" },
|
||||||
})
|
})
|
||||||
: [];
|
: [];
|
||||||
|
|
||||||
const stats: DashboardStats = {
|
const stats: DashboardStats = counts;
|
||||||
awaitingReview,
|
|
||||||
needsRevisions,
|
|
||||||
approved,
|
|
||||||
overdue: tasksOverdue,
|
|
||||||
activeProjects,
|
|
||||||
tasksDueToday,
|
|
||||||
tasksInReview,
|
|
||||||
tasksOverdue,
|
|
||||||
myTasksCount,
|
|
||||||
};
|
|
||||||
|
|
||||||
return { stats, shots, activity, myTasks, reviewTasks, scheduledTasks, scheduleArtists };
|
return {
|
||||||
|
stats,
|
||||||
|
blocked,
|
||||||
|
farm,
|
||||||
|
episodes,
|
||||||
|
qcQueue,
|
||||||
|
qcStaleHours,
|
||||||
|
deliveries,
|
||||||
|
awaitingDelivery,
|
||||||
|
openRequests,
|
||||||
|
court,
|
||||||
|
shots,
|
||||||
|
myTasks,
|
||||||
|
reviewTasks,
|
||||||
|
scheduledTasks,
|
||||||
|
scheduleArtists,
|
||||||
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
export default async function DashboardPage() {
|
export default async function DashboardPage() {
|
||||||
const session = await auth();
|
const session = await auth();
|
||||||
if (!session?.user) return null;
|
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 isClient = session.user.role === "CLIENT";
|
||||||
const canSeeSchedule = ["ADMIN", "PRODUCER", "SUPERVISOR"].includes(
|
const isArtistRole = session.user.role === "ARTIST";
|
||||||
session.user.role
|
const canSeeSchedule = ["ADMIN", "PRODUCER", "SUPERVISOR"].includes(session.user.role);
|
||||||
);
|
const {
|
||||||
|
stats,
|
||||||
|
blocked,
|
||||||
|
farm,
|
||||||
|
episodes,
|
||||||
|
qcQueue,
|
||||||
|
qcStaleHours,
|
||||||
|
deliveries,
|
||||||
|
awaitingDelivery,
|
||||||
|
openRequests,
|
||||||
|
court,
|
||||||
|
shots,
|
||||||
|
myTasks,
|
||||||
|
reviewTasks,
|
||||||
|
scheduledTasks,
|
||||||
|
scheduleArtists,
|
||||||
|
} = await getDashboardData(session.user.id, session.user.role);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="p-8 space-y-6 max-w-[1600px] mx-auto">
|
<div className="p-4 md:p-8 space-y-6 max-w-[1600px] mx-auto">
|
||||||
<div className="mb-4">
|
<div className="mb-4">
|
||||||
<h1 className="text-3xl font-bold text-white">Dashboard</h1>
|
<h1 className="text-3xl font-bold text-white">Dashboard</h1>
|
||||||
<p className="text-zinc-400 mt-1">
|
<p className="text-zinc-400 mt-1">
|
||||||
@@ -166,7 +179,82 @@ export default async function DashboardPage() {
|
|||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<StatsCards stats={stats} />
|
{!isClient && <StatsCards stats={stats} />}
|
||||||
|
|
||||||
|
{/* Rows only clear by being dealt with; the heading stays so there is
|
||||||
|
always somewhere to log what a client just asked for. */}
|
||||||
|
{!isClient && !isArtistRole && (
|
||||||
|
<div className="space-y-3">
|
||||||
|
<div className="flex items-center justify-between gap-3">
|
||||||
|
<h2
|
||||||
|
className={
|
||||||
|
openRequests.length + awaitingDelivery.length > 0
|
||||||
|
? "text-sm font-semibold text-amber-400 uppercase tracking-wide"
|
||||||
|
: "text-sm font-semibold text-muted-foreground uppercase tracking-wide"
|
||||||
|
}
|
||||||
|
>
|
||||||
|
Awaiting delivery
|
||||||
|
</h2>
|
||||||
|
{canSeeSchedule && <LogRequestButton />}
|
||||||
|
</div>
|
||||||
|
<AwaitingDelivery requests={openRequests} packages={awaitingDelivery} />
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{!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 && (
|
{!isClient && (
|
||||||
<TaskWidgets
|
<TaskWidgets
|
||||||
@@ -181,30 +269,16 @@ export default async function DashboardPage() {
|
|||||||
<h2 className="text-sm font-semibold text-muted-foreground uppercase tracking-wide">
|
<h2 className="text-sm font-semibold text-muted-foreground uppercase tracking-wide">
|
||||||
Schedule Overview
|
Schedule Overview
|
||||||
</h2>
|
</h2>
|
||||||
<ScheduleWidgets
|
<ScheduleWidgets scheduledTasks={scheduledTasks as any} artists={scheduleArtists} />
|
||||||
scheduledTasks={scheduledTasks as any}
|
|
||||||
artists={scheduleArtists}
|
|
||||||
/>
|
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
<div className="grid grid-cols-1 xl:grid-cols-3 gap-6">
|
<div className="space-y-3">
|
||||||
<div className="xl:col-span-2 space-y-3">
|
<h2 className="text-sm font-semibold text-muted-foreground uppercase tracking-wide">
|
||||||
<h2 className="text-sm font-semibold text-muted-foreground uppercase tracking-wide">
|
{session.user.role === "ARTIST" ? "My shots" : "Shots in flight"}
|
||||||
Shot Queue
|
</h2>
|
||||||
</h2>
|
<div className="rounded-lg border border-border bg-card p-1">
|
||||||
<div className="rounded-lg border border-border bg-card p-1">
|
<ShotQueue shots={shots as any} />
|
||||||
<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>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
+13
-10
@@ -2,6 +2,7 @@ import { auth } from "@/auth";
|
|||||||
import { redirect } from "next/navigation";
|
import { redirect } from "next/navigation";
|
||||||
import { Sidebar } from "@/components/layout/Sidebar";
|
import { Sidebar } from "@/components/layout/Sidebar";
|
||||||
import { Header } from "@/components/layout/Header";
|
import { Header } from "@/components/layout/Header";
|
||||||
|
import { MobileNavProvider } from "@/components/layout/MobileNav";
|
||||||
|
|
||||||
export default async function DashboardLayout({
|
export default async function DashboardLayout({
|
||||||
children,
|
children,
|
||||||
@@ -12,18 +13,20 @@ export default async function DashboardLayout({
|
|||||||
if (!session?.user) redirect("/login");
|
if (!session?.user) redirect("/login");
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="flex h-screen bg-zinc-950 overflow-hidden print:block print:h-auto print:overflow-visible">
|
<MobileNavProvider>
|
||||||
<div className="print:hidden">
|
<div className="flex h-screen bg-zinc-950 overflow-hidden print:block print:h-auto print:overflow-visible">
|
||||||
<Sidebar />
|
|
||||||
</div>
|
|
||||||
<div className="flex-1 flex flex-col overflow-hidden print:block print:overflow-visible">
|
|
||||||
<div className="print:hidden">
|
<div className="print:hidden">
|
||||||
<Header />
|
<Sidebar />
|
||||||
|
</div>
|
||||||
|
<div className="flex-1 flex flex-col overflow-hidden print:block print:overflow-visible">
|
||||||
|
<div className="print:hidden">
|
||||||
|
<Header />
|
||||||
|
</div>
|
||||||
|
<main className="flex-1 overflow-auto print:overflow-visible">
|
||||||
|
{children}
|
||||||
|
</main>
|
||||||
</div>
|
</div>
|
||||||
<main className="flex-1 overflow-auto print:overflow-visible">
|
|
||||||
{children}
|
|
||||||
</main>
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</MobileNavProvider>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,12 +1,14 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import { useState } from "react";
|
import { useEffect, useState } from "react";
|
||||||
import Link from "next/link";
|
import Link from "next/link";
|
||||||
import { useQuery, useQueryClient } from "@tanstack/react-query";
|
import { useQuery, useQueryClient } from "@tanstack/react-query";
|
||||||
import { useSession } from "next-auth/react";
|
import { useSession } from "next-auth/react";
|
||||||
import { RefreshCw, RotateCcw, XCircle, CheckCircle2, Server, Package } from "lucide-react";
|
import { RefreshCw, RotateCcw, XCircle, CheckCircle2, Server, Package, ChevronLeft, ChevronRight, Search, X } from "lucide-react";
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
|
import { Input } from "@/components/ui/input";
|
||||||
import { Progress } from "@/components/ui/progress";
|
import { Progress } from "@/components/ui/progress";
|
||||||
|
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
|
||||||
import {
|
import {
|
||||||
Select,
|
Select,
|
||||||
SelectContent,
|
SelectContent,
|
||||||
@@ -51,37 +53,79 @@ interface QueueExport {
|
|||||||
|
|
||||||
interface Props {
|
interface Props {
|
||||||
projects: { id: string; name: string; code: string }[];
|
projects: { id: string; name: string; code: string }[];
|
||||||
|
/** Status to open filtered to, from `?status=` (see page.tsx). */
|
||||||
|
initialStatus?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function PipelineQueueClient({ projects }: Props) {
|
const PAGE_SIZE = 25;
|
||||||
|
|
||||||
|
const BLENDER_ACTIVE = ["QUEUED", "CLAIMED", "RUNNING"];
|
||||||
|
|
||||||
|
export function PipelineQueueClient({ projects, initialStatus = "all" }: Props) {
|
||||||
const { data: session } = useSession();
|
const { data: session } = useSession();
|
||||||
const { toast } = useToast();
|
const { toast } = useToast();
|
||||||
const queryClient = useQueryClient();
|
const queryClient = useQueryClient();
|
||||||
const [projectId, setProjectId] = useState<string>("all");
|
const [projectId, setProjectId] = useState<string>("all");
|
||||||
const [statusFilter, setStatusFilter] = useState<string>("all");
|
const [statusFilter, setStatusFilter] = useState<string>(initialStatus);
|
||||||
|
const [page, setPage] = useState(1);
|
||||||
|
const [searchInput, setSearchInput] = useState("");
|
||||||
|
const [search, setSearch] = useState("");
|
||||||
const isAdmin = ["ADMIN", "PRODUCER", "SUPERVISOR"].includes(session?.user?.role ?? "");
|
const isAdmin = ["ADMIN", "PRODUCER", "SUPERVISOR"].includes(session?.user?.role ?? "");
|
||||||
|
|
||||||
|
// Searched on the server (the table is paged there), so typing is debounced
|
||||||
|
// rather than firing a request per keystroke.
|
||||||
|
useEffect(() => {
|
||||||
|
const next = searchInput.trim();
|
||||||
|
if (next === search) return;
|
||||||
|
const t = setTimeout(() => {
|
||||||
|
setSearch(next);
|
||||||
|
setPage(1);
|
||||||
|
}, 300);
|
||||||
|
return () => clearTimeout(t);
|
||||||
|
}, [searchInput, search]);
|
||||||
|
|
||||||
const { data, isLoading, refetch, isFetching } = useQuery({
|
const { data, isLoading, refetch, isFetching } = useQuery({
|
||||||
queryKey: ["pipeline-queue", projectId, statusFilter],
|
queryKey: ["pipeline-queue", projectId, statusFilter, search, page],
|
||||||
queryFn: async () => {
|
queryFn: async () => {
|
||||||
const params = new URLSearchParams({ limit: "200" });
|
const params = new URLSearchParams({ limit: String(PAGE_SIZE), page: String(page) });
|
||||||
if (projectId !== "all") params.set("projectId", projectId);
|
if (projectId !== "all") params.set("projectId", projectId);
|
||||||
if (statusFilter !== "all") params.set("status", statusFilter);
|
if (statusFilter !== "all") params.set("status", statusFilter);
|
||||||
|
if (search) params.set("q", search);
|
||||||
const res = await fetch(`/api/render/queue?${params}`);
|
const res = await fetch(`/api/render/queue?${params}`);
|
||||||
if (!res.ok) throw new Error("Failed to load queue");
|
if (!res.ok) throw new Error("Failed to load queue");
|
||||||
return res.json() as Promise<{ exports: QueueExport[]; pagination: { total: number } }>;
|
return res.json() as Promise<{
|
||||||
|
exports: QueueExport[];
|
||||||
|
pagination: { page: number; total: number; pages: number };
|
||||||
|
statusCounts: Record<string, number>;
|
||||||
|
}>;
|
||||||
|
},
|
||||||
|
refetchInterval: 5000,
|
||||||
|
// Keep the current page on screen while the next one loads, instead of
|
||||||
|
// flashing "Loading…" on every page turn.
|
||||||
|
placeholderData: (previous) => previous,
|
||||||
|
});
|
||||||
|
|
||||||
|
// Fetched here rather than in the tab so the tab label can say how many are
|
||||||
|
// running: a Blender render must not become invisible by sitting in a tab.
|
||||||
|
const { data: blenderData } = useQuery({
|
||||||
|
queryKey: ["blender-jobs", projectId],
|
||||||
|
queryFn: async () => {
|
||||||
|
const qs = projectId !== "all" ? `?projectId=${encodeURIComponent(projectId)}` : "";
|
||||||
|
const res = await fetch(`/api/render/blender${qs}`);
|
||||||
|
if (!res.ok) throw new Error("Failed to load Blender jobs");
|
||||||
|
return res.json() as Promise<{ jobs: BlenderJobRow[] }>;
|
||||||
},
|
},
|
||||||
refetchInterval: 5000,
|
refetchInterval: 5000,
|
||||||
});
|
});
|
||||||
|
|
||||||
const exports = data?.exports ?? [];
|
const exports = data?.exports ?? [];
|
||||||
const counts = {
|
const pagination = data?.pagination;
|
||||||
queued: exports.filter((e) => e.status === "QUEUED").length,
|
const statusCounts = data?.statusCounts ?? {};
|
||||||
rendering: exports.filter((e) => e.status === "RENDERING").length,
|
const countOf = (statuses: string[]) => statuses.reduce((n, s) => n + (statusCounts[s] ?? 0), 0);
|
||||||
failed: exports.filter((e) => FAILED_STATUSES.includes(e.status)).length,
|
const totalExports = Object.values(statusCounts).reduce((n, c) => n + c, 0);
|
||||||
readyForQc: exports.filter((e) => e.status === "READY_FOR_QC").length,
|
const blenderJobs = blenderData?.jobs ?? [];
|
||||||
readyForDelivery: exports.filter((e) => e.status === "READY_FOR_DELIVERY").length,
|
const blenderActive = blenderJobs.filter((j) => BLENDER_ACTIVE.includes(j.status)).length;
|
||||||
};
|
const blenderFailed = blenderJobs.filter((j) => ["FAILED", "EXPIRED"].includes(j.status)).length;
|
||||||
|
|
||||||
async function action(exportId: string, verb: "retry" | "cancel" | "mark-done") {
|
async function action(exportId: string, verb: "retry" | "cancel" | "mark-done") {
|
||||||
const res = await fetch(`/api/render/exports/${exportId}/${verb}`, { method: "POST" });
|
const res = await fetch(`/api/render/exports/${exportId}/${verb}`, { method: "POST" });
|
||||||
@@ -94,30 +138,56 @@ export function PipelineQueueClient({ projects }: Props) {
|
|||||||
queryClient.invalidateQueries({ queryKey: ["pipeline-queue"] });
|
queryClient.invalidateQueries({ queryKey: ["pipeline-queue"] });
|
||||||
}
|
}
|
||||||
|
|
||||||
const cards: { label: string; value: number; className?: string }[] = [
|
const cards: { label: string; value: number; status?: string; className?: string }[] = [
|
||||||
{ label: "Queued", value: counts.queued },
|
{ label: "Queued", value: countOf(["QUEUED"]), status: "QUEUED" },
|
||||||
{ label: "Rendering", value: counts.rendering, className: "text-blue-400" },
|
{ label: "Rendering", value: countOf(["RENDERING"]), status: "RENDERING", className: "text-blue-400" },
|
||||||
{ label: "Failed", value: counts.failed, className: "text-red-400" },
|
// Several statuses count as failed and the filter takes one, so this card
|
||||||
{ label: "Ready for QC", value: counts.readyForQc, className: "text-amber-400" },
|
// is a figure only.
|
||||||
{ label: "Ready for Delivery", value: counts.readyForDelivery, className: "text-green-400" },
|
{ label: "Failed", value: countOf(FAILED_STATUSES), className: "text-red-400" },
|
||||||
|
{ label: "Ready for QC", value: countOf(["READY_FOR_QC"]), status: "READY_FOR_QC", className: "text-amber-400" },
|
||||||
|
{
|
||||||
|
label: "Ready for Delivery",
|
||||||
|
value: countOf(["READY_FOR_DELIVERY"]),
|
||||||
|
status: "READY_FOR_DELIVERY",
|
||||||
|
className: "text-green-400",
|
||||||
|
},
|
||||||
];
|
];
|
||||||
|
|
||||||
|
const changeProject = (id: string) => {
|
||||||
|
setProjectId(id);
|
||||||
|
setPage(1);
|
||||||
|
};
|
||||||
|
const changeStatus = (status: string) => {
|
||||||
|
setStatusFilter(status);
|
||||||
|
setPage(1);
|
||||||
|
};
|
||||||
|
|
||||||
|
const firstRow = pagination && pagination.total > 0 ? (pagination.page - 1) * PAGE_SIZE + 1 : 0;
|
||||||
|
const lastRow = pagination ? Math.min(pagination.page * PAGE_SIZE, pagination.total) : 0;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="p-6 space-y-6">
|
<div className="p-4 md:p-6 space-y-6">
|
||||||
<div className="flex items-center justify-between gap-4 flex-wrap">
|
<div className="flex items-center justify-between gap-4 flex-wrap">
|
||||||
<div>
|
<div>
|
||||||
<h1 className="text-2xl font-semibold text-white">Render Queue</h1>
|
<h1 className="text-2xl font-semibold text-white">Render Queue</h1>
|
||||||
<p className="text-sm text-zinc-400 mt-1">
|
<p className="text-sm text-zinc-400 mt-1">
|
||||||
Exports queued from the AE panel — live status, retries and history
|
After Effects exports and Blender renders — live status, retries and history
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
<div className="flex items-center gap-2">
|
<div className="flex items-center gap-2 flex-wrap">
|
||||||
<Link href="/pipeline/deliveries">
|
<Select value={projectId} onValueChange={changeProject}>
|
||||||
<Button variant="outline" size="sm">
|
<SelectTrigger className="w-56">
|
||||||
<Package className="h-4 w-4 mr-2" />
|
<SelectValue placeholder="All projects" />
|
||||||
Deliveries
|
</SelectTrigger>
|
||||||
</Button>
|
<SelectContent>
|
||||||
</Link>
|
<SelectItem value="all">All projects</SelectItem>
|
||||||
|
{projects.map((p) => (
|
||||||
|
<SelectItem key={p.id} value={p.id}>
|
||||||
|
{p.name}
|
||||||
|
</SelectItem>
|
||||||
|
))}
|
||||||
|
</SelectContent>
|
||||||
|
</Select>
|
||||||
<Link href="/pipeline/deliveries">
|
<Link href="/pipeline/deliveries">
|
||||||
<Button variant="outline" size="sm">
|
<Button variant="outline" size="sm">
|
||||||
<Package className="h-4 w-4 mr-2" />
|
<Package className="h-4 w-4 mr-2" />
|
||||||
@@ -136,152 +206,231 @@ export function PipelineQueueClient({ projects }: Props) {
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Summary cards */}
|
<Tabs defaultValue="exports" className="space-y-4">
|
||||||
<div className="grid grid-cols-2 sm:grid-cols-5 gap-3">
|
<TabsList className="bg-zinc-900 border border-zinc-800">
|
||||||
{cards.map((c) => (
|
<TabsTrigger value="exports">
|
||||||
<div key={c.label} className="rounded-lg border border-zinc-800 bg-zinc-900 px-4 py-3">
|
After Effects exports
|
||||||
<div className={cn("text-2xl font-semibold text-white", c.className)}>{c.value}</div>
|
<span className="ml-2 text-xs text-zinc-500">{totalExports}</span>
|
||||||
<div className="text-xs text-zinc-400 mt-0.5">{c.label}</div>
|
</TabsTrigger>
|
||||||
</div>
|
<TabsTrigger value="blender">
|
||||||
))}
|
Blender renders
|
||||||
</div>
|
{blenderActive > 0 ? (
|
||||||
|
<span className="ml-2 rounded-full bg-blue-500/20 px-1.5 text-xs text-blue-400">
|
||||||
{/* Filters */}
|
{blenderActive} active
|
||||||
<div className="flex items-center gap-3 flex-wrap">
|
</span>
|
||||||
<Select value={projectId} onValueChange={setProjectId}>
|
) : blenderFailed > 0 ? (
|
||||||
<SelectTrigger className="w-56">
|
<span className="ml-2 rounded-full bg-red-500/20 px-1.5 text-xs text-red-400">
|
||||||
<SelectValue placeholder="All projects" />
|
{blenderFailed} failed
|
||||||
</SelectTrigger>
|
</span>
|
||||||
<SelectContent>
|
|
||||||
<SelectItem value="all">All projects</SelectItem>
|
|
||||||
{projects.map((p) => (
|
|
||||||
<SelectItem key={p.id} value={p.id}>
|
|
||||||
{p.name}
|
|
||||||
</SelectItem>
|
|
||||||
))}
|
|
||||||
</SelectContent>
|
|
||||||
</Select>
|
|
||||||
<Select value={statusFilter} onValueChange={setStatusFilter}>
|
|
||||||
<SelectTrigger className="w-56">
|
|
||||||
<SelectValue placeholder="All statuses" />
|
|
||||||
</SelectTrigger>
|
|
||||||
<SelectContent>
|
|
||||||
<SelectItem value="all">All statuses</SelectItem>
|
|
||||||
{Object.keys(EXPORT_STATUS_STYLES).map((s) => (
|
|
||||||
<SelectItem key={s} value={s}>
|
|
||||||
{statusLabel(s)}
|
|
||||||
</SelectItem>
|
|
||||||
))}
|
|
||||||
</SelectContent>
|
|
||||||
</Select>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Table */}
|
|
||||||
<div className="rounded-lg border border-zinc-800 overflow-x-auto">
|
|
||||||
<table className="w-full text-sm">
|
|
||||||
<thead>
|
|
||||||
<tr className="border-b border-zinc-800 bg-zinc-900/60 text-left text-xs text-zinc-400">
|
|
||||||
<th className="px-4 py-2.5 font-medium">Shot</th>
|
|
||||||
<th className="px-4 py-2.5 font-medium">Version</th>
|
|
||||||
<th className="px-4 py-2.5 font-medium">Status</th>
|
|
||||||
<th className="px-4 py-2.5 font-medium w-48">Progress</th>
|
|
||||||
<th className="px-4 py-2.5 font-medium">Machine</th>
|
|
||||||
<th className="px-4 py-2.5 font-medium">Attempt</th>
|
|
||||||
<th className="px-4 py-2.5 font-medium">Queued</th>
|
|
||||||
<th className="px-4 py-2.5 font-medium text-right">Actions</th>
|
|
||||||
</tr>
|
|
||||||
</thead>
|
|
||||||
<tbody>
|
|
||||||
{isLoading ? (
|
|
||||||
<tr>
|
|
||||||
<td colSpan={8} className="px-4 py-10 text-center text-zinc-500">
|
|
||||||
Loading…
|
|
||||||
</td>
|
|
||||||
</tr>
|
|
||||||
) : exports.length === 0 ? (
|
|
||||||
<tr>
|
|
||||||
<td colSpan={8} className="px-4 py-10 text-center text-zinc-500">
|
|
||||||
No exports yet — queue one from the After Effects panel
|
|
||||||
</td>
|
|
||||||
</tr>
|
|
||||||
) : (
|
) : (
|
||||||
exports.map((e) => (
|
<span className="ml-2 text-xs text-zinc-500">{blenderJobs.length}</span>
|
||||||
<tr key={e.id} className="border-b border-zinc-800/60 hover:bg-zinc-900/40">
|
|
||||||
<td className="px-4 py-2.5">
|
|
||||||
<Link href={`/pipeline/exports/${e.id}`} className="text-white hover:text-amber-400 font-medium">
|
|
||||||
{e.shotCode}
|
|
||||||
</Link>
|
|
||||||
<div className="text-xs text-zinc-500">
|
|
||||||
{e.projectCode}
|
|
||||||
{e.episode ? ` · ep ${e.episode}` : ""}
|
|
||||||
</div>
|
|
||||||
</td>
|
|
||||||
<td className="px-4 py-2.5 text-zinc-300">{e.versionString}</td>
|
|
||||||
<td className="px-4 py-2.5">
|
|
||||||
<span
|
|
||||||
className={cn(
|
|
||||||
"inline-block rounded-full border px-2 py-0.5 text-xs whitespace-nowrap",
|
|
||||||
EXPORT_STATUS_STYLES[e.status] ?? "bg-zinc-500/15 text-zinc-300 border-zinc-500/30"
|
|
||||||
)}
|
|
||||||
title={e.job?.errorMessage ?? undefined}
|
|
||||||
>
|
|
||||||
{statusLabel(e.status)}
|
|
||||||
</span>
|
|
||||||
</td>
|
|
||||||
<td className="px-4 py-2.5">
|
|
||||||
{e.status === "RENDERING" && e.job ? (
|
|
||||||
<div className="space-y-1">
|
|
||||||
<Progress value={e.job.progress * 100} className="h-1.5" />
|
|
||||||
<div className="text-xs text-zinc-500">
|
|
||||||
{e.job.currentFrame != null && e.job.totalFrames != null
|
|
||||||
? `frame ${e.job.currentFrame}/${e.job.totalFrames} · `
|
|
||||||
: ""}
|
|
||||||
ETA {formatEta(e.job.etaSeconds)}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
) : (
|
|
||||||
<span className="text-zinc-600 text-xs">—</span>
|
|
||||||
)}
|
|
||||||
</td>
|
|
||||||
<td className="px-4 py-2.5 text-zinc-400">{e.job?.machineName ?? "—"}</td>
|
|
||||||
<td className="px-4 py-2.5 text-zinc-400">
|
|
||||||
{e.job ? `${e.job.attempt}` : "—"}
|
|
||||||
</td>
|
|
||||||
<td className="px-4 py-2.5 text-zinc-500 text-xs whitespace-nowrap">
|
|
||||||
{new Date(e.createdAt).toLocaleString()}
|
|
||||||
</td>
|
|
||||||
<td className="px-4 py-2.5">
|
|
||||||
<div className="flex items-center justify-end gap-1">
|
|
||||||
{FAILED_STATUSES.includes(e.status) && (
|
|
||||||
<Button variant="ghost" size="icon-sm" title="Retry" onClick={() => action(e.id, "retry")}>
|
|
||||||
<RotateCcw className="h-4 w-4 text-amber-400" />
|
|
||||||
</Button>
|
|
||||||
)}
|
|
||||||
{ACTIVE_STATUSES.includes(e.status) && (
|
|
||||||
<Button variant="ghost" size="icon-sm" title="Cancel" onClick={() => action(e.id, "cancel")}>
|
|
||||||
<XCircle className="h-4 w-4 text-red-400" />
|
|
||||||
</Button>
|
|
||||||
)}
|
|
||||||
{isAdmin && ["QUEUED", "RENDERING"].includes(e.status) && (
|
|
||||||
<Button
|
|
||||||
variant="ghost"
|
|
||||||
size="icon-sm"
|
|
||||||
title="Mark done manually (rendered outside the pipeline)"
|
|
||||||
onClick={() => action(e.id, "mark-done")}
|
|
||||||
>
|
|
||||||
<CheckCircle2 className="h-4 w-4 text-green-400" />
|
|
||||||
</Button>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
</td>
|
|
||||||
</tr>
|
|
||||||
))
|
|
||||||
)}
|
)}
|
||||||
</tbody>
|
</TabsTrigger>
|
||||||
</table>
|
</TabsList>
|
||||||
</div>
|
|
||||||
|
|
||||||
<BlenderQueue projectId={projectId} />
|
<TabsContent value="exports" className="space-y-4 mt-0">
|
||||||
|
{/* Summary cards — each one with a status filters the table to what it counts */}
|
||||||
|
<div className="grid grid-cols-2 sm:grid-cols-5 gap-3">
|
||||||
|
{cards.map((c) => {
|
||||||
|
const selected = c.status !== undefined && statusFilter === c.status;
|
||||||
|
const body = (
|
||||||
|
<>
|
||||||
|
<div className={cn("text-2xl font-semibold text-white", c.className)}>{c.value}</div>
|
||||||
|
<div className="text-xs text-zinc-400 mt-0.5">{c.label}</div>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
return c.status ? (
|
||||||
|
<button
|
||||||
|
key={c.label}
|
||||||
|
type="button"
|
||||||
|
onClick={() => changeStatus(selected ? "all" : c.status!)}
|
||||||
|
className={cn(
|
||||||
|
"rounded-lg border bg-zinc-900 px-4 py-3 text-left transition-colors hover:border-zinc-600",
|
||||||
|
selected ? "border-zinc-500" : "border-zinc-800"
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
{body}
|
||||||
|
</button>
|
||||||
|
) : (
|
||||||
|
<div key={c.label} className="rounded-lg border border-zinc-800 bg-zinc-900 px-4 py-3">
|
||||||
|
{body}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex items-center gap-2 flex-wrap">
|
||||||
|
<div className="relative w-full sm:w-72">
|
||||||
|
<Search className="pointer-events-none absolute left-2.5 top-1/2 h-4 w-4 -translate-y-1/2 text-zinc-500" />
|
||||||
|
<Input
|
||||||
|
value={searchInput}
|
||||||
|
onChange={(e) => setSearchInput(e.target.value)}
|
||||||
|
onKeyDown={(e) => e.key === "Escape" && setSearchInput("")}
|
||||||
|
placeholder="Search shots, e.g. UNG_114"
|
||||||
|
aria-label="Search exports by shot code"
|
||||||
|
className="pl-8 pr-8"
|
||||||
|
/>
|
||||||
|
{searchInput && (
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => setSearchInput("")}
|
||||||
|
className="absolute right-2 top-1/2 -translate-y-1/2 text-zinc-500 hover:text-zinc-300"
|
||||||
|
aria-label="Clear search"
|
||||||
|
>
|
||||||
|
<X className="h-4 w-4" />
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<Select value={statusFilter} onValueChange={changeStatus}>
|
||||||
|
<SelectTrigger className="w-56">
|
||||||
|
<SelectValue placeholder="All statuses" />
|
||||||
|
</SelectTrigger>
|
||||||
|
<SelectContent>
|
||||||
|
<SelectItem value="all">All statuses</SelectItem>
|
||||||
|
{Object.keys(EXPORT_STATUS_STYLES).map((s) => (
|
||||||
|
<SelectItem key={s} value={s}>
|
||||||
|
{statusLabel(s)}
|
||||||
|
</SelectItem>
|
||||||
|
))}
|
||||||
|
</SelectContent>
|
||||||
|
</Select>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="rounded-lg border border-zinc-800 overflow-x-auto">
|
||||||
|
<table className="w-full text-sm">
|
||||||
|
<thead>
|
||||||
|
<tr className="border-b border-zinc-800 bg-zinc-900/60 text-left text-xs text-zinc-400">
|
||||||
|
<th className="px-4 py-2.5 font-medium">Shot</th>
|
||||||
|
<th className="px-4 py-2.5 font-medium">Version</th>
|
||||||
|
<th className="px-4 py-2.5 font-medium">Status</th>
|
||||||
|
<th className="px-4 py-2.5 font-medium w-48">Progress</th>
|
||||||
|
<th className="px-4 py-2.5 font-medium">Machine</th>
|
||||||
|
<th className="px-4 py-2.5 font-medium">Attempt</th>
|
||||||
|
<th className="px-4 py-2.5 font-medium">Queued</th>
|
||||||
|
<th className="px-4 py-2.5 font-medium text-right">Actions</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
{isLoading ? (
|
||||||
|
<tr>
|
||||||
|
<td colSpan={8} className="px-4 py-10 text-center text-zinc-500">
|
||||||
|
Loading…
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
) : exports.length === 0 ? (
|
||||||
|
<tr>
|
||||||
|
<td colSpan={8} className="px-4 py-10 text-center text-zinc-500">
|
||||||
|
{search
|
||||||
|
? `No exports match “${search}”`
|
||||||
|
: statusFilter === "all"
|
||||||
|
? "No exports yet — queue one from the After Effects panel"
|
||||||
|
: `No exports are ${statusLabel(statusFilter).toLowerCase()}`}
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
) : (
|
||||||
|
exports.map((e) => (
|
||||||
|
<tr key={e.id} className="border-b border-zinc-800/60 hover:bg-zinc-900/40">
|
||||||
|
<td className="px-4 py-2.5">
|
||||||
|
<Link href={`/pipeline/exports/${e.id}`} className="text-white hover:text-amber-400 font-medium">
|
||||||
|
{e.shotCode}
|
||||||
|
</Link>
|
||||||
|
<div className="text-xs text-zinc-500">
|
||||||
|
{e.projectCode}
|
||||||
|
{e.episode ? ` · ep ${e.episode}` : ""}
|
||||||
|
</div>
|
||||||
|
</td>
|
||||||
|
<td className="px-4 py-2.5 text-zinc-300">{e.versionString}</td>
|
||||||
|
<td className="px-4 py-2.5">
|
||||||
|
<span
|
||||||
|
className={cn(
|
||||||
|
"inline-block rounded-full border px-2 py-0.5 text-xs whitespace-nowrap",
|
||||||
|
EXPORT_STATUS_STYLES[e.status] ?? "bg-zinc-500/15 text-zinc-300 border-zinc-500/30"
|
||||||
|
)}
|
||||||
|
title={e.job?.errorMessage ?? undefined}
|
||||||
|
>
|
||||||
|
{statusLabel(e.status)}
|
||||||
|
</span>
|
||||||
|
</td>
|
||||||
|
<td className="px-4 py-2.5">
|
||||||
|
{e.status === "RENDERING" && e.job ? (
|
||||||
|
<div className="space-y-1">
|
||||||
|
<Progress value={e.job.progress * 100} className="h-1.5" />
|
||||||
|
<div className="text-xs text-zinc-500">
|
||||||
|
{e.job.currentFrame != null && e.job.totalFrames != null
|
||||||
|
? `frame ${e.job.currentFrame}/${e.job.totalFrames} · `
|
||||||
|
: ""}
|
||||||
|
ETA {formatEta(e.job.etaSeconds)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<span className="text-zinc-600 text-xs">—</span>
|
||||||
|
)}
|
||||||
|
</td>
|
||||||
|
<td className="px-4 py-2.5 text-zinc-400">{e.job?.machineName ?? "—"}</td>
|
||||||
|
<td className="px-4 py-2.5 text-zinc-400">{e.job ? `${e.job.attempt}` : "—"}</td>
|
||||||
|
<td className="px-4 py-2.5 text-zinc-500 text-xs whitespace-nowrap">
|
||||||
|
{new Date(e.createdAt).toLocaleString()}
|
||||||
|
</td>
|
||||||
|
<td className="px-4 py-2.5">
|
||||||
|
<div className="flex items-center justify-end gap-1">
|
||||||
|
{FAILED_STATUSES.includes(e.status) && (
|
||||||
|
<Button variant="ghost" size="icon-sm" title="Retry" onClick={() => action(e.id, "retry")}>
|
||||||
|
<RotateCcw className="h-4 w-4 text-amber-400" />
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
{ACTIVE_STATUSES.includes(e.status) && (
|
||||||
|
<Button variant="ghost" size="icon-sm" title="Cancel" onClick={() => action(e.id, "cancel")}>
|
||||||
|
<XCircle className="h-4 w-4 text-red-400" />
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
{isAdmin && ["QUEUED", "RENDERING"].includes(e.status) && (
|
||||||
|
<Button
|
||||||
|
variant="ghost"
|
||||||
|
size="icon-sm"
|
||||||
|
title="Mark done manually (rendered outside the pipeline)"
|
||||||
|
onClick={() => action(e.id, "mark-done")}
|
||||||
|
>
|
||||||
|
<CheckCircle2 className="h-4 w-4 text-green-400" />
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
))
|
||||||
|
)}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{pagination && pagination.pages > 1 && (
|
||||||
|
<div className="flex items-center justify-between text-sm text-zinc-400">
|
||||||
|
<span>
|
||||||
|
{firstRow}–{lastRow} of {pagination.total}
|
||||||
|
</span>
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<Button variant="outline" size="sm" disabled={page <= 1} onClick={() => setPage((p) => p - 1)}>
|
||||||
|
<ChevronLeft className="h-4 w-4" />
|
||||||
|
</Button>
|
||||||
|
<span className="text-xs">
|
||||||
|
Page {pagination.page} of {pagination.pages}
|
||||||
|
</span>
|
||||||
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
size="sm"
|
||||||
|
disabled={page >= pagination.pages}
|
||||||
|
onClick={() => setPage((p) => p + 1)}
|
||||||
|
>
|
||||||
|
<ChevronRight className="h-4 w-4" />
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</TabsContent>
|
||||||
|
|
||||||
|
<TabsContent value="blender" className="mt-0">
|
||||||
|
<BlenderQueue jobs={blenderJobs} loaded={blenderData !== undefined} />
|
||||||
|
</TabsContent>
|
||||||
|
</Tabs>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -318,24 +467,13 @@ const BLENDER_STATUS_STYLES: Record<string, string> = {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Standalone Blender renders. They have no Export behind them, so they cannot
|
* Standalone Blender renders. They have no Export behind them, so they cannot
|
||||||
* appear in the table above — but they share the queue, and a render nobody can
|
* appear in the exports table — but they share the queue, and a render nobody
|
||||||
* see is a render nobody can retry.
|
* can see is a render nobody can retry.
|
||||||
*/
|
*/
|
||||||
function BlenderQueue({ projectId }: { projectId: string }) {
|
function BlenderQueue({ jobs, loaded }: { jobs: BlenderJobRow[]; loaded: boolean }) {
|
||||||
const { toast } = useToast();
|
const { toast } = useToast();
|
||||||
const queryClient = useQueryClient();
|
const queryClient = useQueryClient();
|
||||||
|
|
||||||
const { data } = useQuery({
|
|
||||||
queryKey: ["blender-jobs", projectId],
|
|
||||||
queryFn: async () => {
|
|
||||||
const qs = projectId && projectId !== "all" ? `?projectId=${encodeURIComponent(projectId)}` : "";
|
|
||||||
const res = await fetch(`/api/render/blender${qs}`);
|
|
||||||
if (!res.ok) throw new Error("Failed to load Blender jobs");
|
|
||||||
return res.json() as Promise<{ jobs: BlenderJobRow[] }>;
|
|
||||||
},
|
|
||||||
refetchInterval: 5000,
|
|
||||||
});
|
|
||||||
|
|
||||||
async function jobAction(id: string, verb: "cancel" | "retry") {
|
async function jobAction(id: string, verb: "cancel" | "retry") {
|
||||||
const res = await fetch(`/api/render/blender/${id}?action=${verb}`, { method: "POST" });
|
const res = await fetch(`/api/render/blender/${id}?action=${verb}`, { method: "POST" });
|
||||||
if (!res.ok) {
|
if (!res.ok) {
|
||||||
@@ -345,14 +483,16 @@ function BlenderQueue({ projectId }: { projectId: string }) {
|
|||||||
queryClient.invalidateQueries({ queryKey: ["blender-jobs"] });
|
queryClient.invalidateQueries({ queryKey: ["blender-jobs"] });
|
||||||
}
|
}
|
||||||
|
|
||||||
const jobs = data?.jobs ?? [];
|
if (jobs.length === 0) {
|
||||||
if (jobs.length === 0) return null;
|
return (
|
||||||
|
<div className="rounded-lg border border-zinc-800 px-4 py-10 text-center text-sm text-zinc-500">
|
||||||
|
{loaded ? "No Blender renders yet — submit one from the Blender panel" : "Loading…"}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="rounded-lg border border-zinc-800 bg-zinc-900/40">
|
<div className="rounded-lg border border-zinc-800 bg-zinc-900/40">
|
||||||
<div className="px-4 py-2.5 border-b border-zinc-800 text-sm font-medium text-white">
|
|
||||||
Blender renders
|
|
||||||
</div>
|
|
||||||
<div className="divide-y divide-zinc-800/60">
|
<div className="divide-y divide-zinc-800/60">
|
||||||
{jobs.map((j) => (
|
{jobs.map((j) => (
|
||||||
<div key={j.id} className="px-4 py-3 text-sm">
|
<div key={j.id} className="px-4 py-3 text-sm">
|
||||||
|
|||||||
@@ -3,11 +3,14 @@
|
|||||||
import { useState } from "react";
|
import { useState } from "react";
|
||||||
import Link from "next/link";
|
import Link from "next/link";
|
||||||
import { useQuery, useQueryClient } from "@tanstack/react-query";
|
import { useQuery, useQueryClient } from "@tanstack/react-query";
|
||||||
import { ArrowLeft, Package, CheckCircle2, XCircle, RefreshCw } from "lucide-react";
|
import { ArrowLeft, Package, CheckCircle2, XCircle, RefreshCw, Upload } from "lucide-react";
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
import { useToast } from "@/components/ui/use-toast";
|
import { useToast } from "@/components/ui/use-toast";
|
||||||
import { cn } from "@/lib/utils";
|
import { cn } from "@/lib/utils";
|
||||||
|
import { handoffStage } from "@/lib/render-pipeline/delivery-handoff";
|
||||||
import { DELIVERY_STATUS_STYLES, statusLabel } from "../status-colors";
|
import { DELIVERY_STATUS_STYLES, statusLabel } from "../status-colors";
|
||||||
|
import { RecordShareDialog, RecordUploadDialog } from "./HandoffDialogs";
|
||||||
|
import { RequestsPanel } from "./RequestsPanel";
|
||||||
|
|
||||||
interface ReadyExport {
|
interface ReadyExport {
|
||||||
exportId: string;
|
exportId: string;
|
||||||
@@ -29,19 +32,31 @@ interface PackageRow {
|
|||||||
id: string;
|
id: string;
|
||||||
packageNumber: number;
|
packageNumber: number;
|
||||||
name: string;
|
name: string;
|
||||||
|
kind: "EXR_DELIVERY" | "MOV_REVIEW";
|
||||||
episode: string;
|
episode: string;
|
||||||
status: string;
|
status: string;
|
||||||
rootPath: string | null;
|
rootPath: string | null;
|
||||||
errorMessage: string | null;
|
errorMessage: string | null;
|
||||||
projectName: string;
|
projectName: string;
|
||||||
|
projectCode: string;
|
||||||
createdAt: string;
|
createdAt: string;
|
||||||
builtAt: string | null;
|
builtAt: string | null;
|
||||||
|
uploadUrl: string | null;
|
||||||
|
uploadedAt: string | null;
|
||||||
|
uploadedByName: string | null;
|
||||||
|
sharedWith: string | null;
|
||||||
|
sharedNote: string | null;
|
||||||
deliveredAt: string | null;
|
deliveredAt: string | null;
|
||||||
|
deliveredByName: string | null;
|
||||||
itemCount: number;
|
itemCount: number;
|
||||||
verifiedCount: number;
|
verifiedCount: number;
|
||||||
|
exrFileCount: number;
|
||||||
|
movCount: number;
|
||||||
|
totalBytes: number;
|
||||||
items: {
|
items: {
|
||||||
id: string;
|
id: string;
|
||||||
shotCode: string;
|
shotCode: string;
|
||||||
|
clientCode: string | null;
|
||||||
versionString: string;
|
versionString: string;
|
||||||
status: string;
|
status: string;
|
||||||
fileCount: number | null;
|
fileCount: number | null;
|
||||||
@@ -68,6 +83,10 @@ export function DeliveriesClient({ canBuild }: { canBuild: boolean }) {
|
|||||||
const [projectId, setProjectId] = useState<string>("");
|
const [projectId, setProjectId] = useState<string>("");
|
||||||
const [episode, setEpisode] = useState<string>("");
|
const [episode, setEpisode] = useState<string>("");
|
||||||
const [building, setBuilding] = useState(false);
|
const [building, setBuilding] = useState(false);
|
||||||
|
// Tracked as exclusions so every ready shot — including one that passes QC
|
||||||
|
// while the page is open — starts selected.
|
||||||
|
const [deselected, setDeselected] = useState<Set<string>>(() => new Set());
|
||||||
|
const [handoff, setHandoff] = useState<{ step: "upload" | "share"; packageId: string } | null>(null);
|
||||||
|
|
||||||
const { data: projects } = useQuery({
|
const { data: projects } = useQuery({
|
||||||
queryKey: ["pipeline-projects"],
|
queryKey: ["pipeline-projects"],
|
||||||
@@ -100,14 +119,36 @@ export function DeliveriesClient({ canBuild }: { canBuild: boolean }) {
|
|||||||
refetchInterval: 5000,
|
refetchInterval: 5000,
|
||||||
});
|
});
|
||||||
|
|
||||||
async function build(ep: string) {
|
function toggleExport(exportId: string, selected: boolean) {
|
||||||
if (!projectId) return;
|
setDeselected((prev) => {
|
||||||
|
const next = new Set(prev);
|
||||||
|
if (selected) next.delete(exportId);
|
||||||
|
else next.add(exportId);
|
||||||
|
return next;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function setEpisodeSelected(exportIds: string[], selected: boolean) {
|
||||||
|
setDeselected((prev) => {
|
||||||
|
const next = new Set(prev);
|
||||||
|
for (const id of exportIds) {
|
||||||
|
if (selected) next.delete(id);
|
||||||
|
else next.add(id);
|
||||||
|
}
|
||||||
|
return next;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async function build(ep: string, exportIds: string[]) {
|
||||||
|
if (!projectId || exportIds.length === 0) return;
|
||||||
setBuilding(true);
|
setBuilding(true);
|
||||||
try {
|
try {
|
||||||
|
// Always send the explicit list: the package holds exactly the shots
|
||||||
|
// ticked on screen, never one that turned ready since the page loaded.
|
||||||
const res = await fetch("/api/deliveries", {
|
const res = await fetch("/api/deliveries", {
|
||||||
method: "POST",
|
method: "POST",
|
||||||
headers: { "Content-Type": "application/json" },
|
headers: { "Content-Type": "application/json" },
|
||||||
body: JSON.stringify({ projectId, episode: ep || null }),
|
body: JSON.stringify({ projectId, episode: ep || null, exportIds }),
|
||||||
});
|
});
|
||||||
const body = await res.json().catch(() => ({}));
|
const body = await res.json().catch(() => ({}));
|
||||||
if (!res.ok) {
|
if (!res.ok) {
|
||||||
@@ -125,21 +166,28 @@ export function DeliveriesClient({ canBuild }: { canBuild: boolean }) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async function packageAction(id: string, verb: "delivered" | "cancel") {
|
function refreshPackages() {
|
||||||
const res = await fetch(`/api/deliveries/${id}/${verb}`, { method: "POST" });
|
|
||||||
const body = await res.json().catch(() => ({}));
|
|
||||||
if (!res.ok) {
|
|
||||||
toast({ title: `${verb} failed`, description: body.error ?? res.statusText, variant: "destructive" });
|
|
||||||
}
|
|
||||||
queryClient.invalidateQueries({ queryKey: ["delivery-packages"] });
|
queryClient.invalidateQueries({ queryKey: ["delivery-packages"] });
|
||||||
queryClient.invalidateQueries({ queryKey: ["delivery-ready"] });
|
queryClient.invalidateQueries({ queryKey: ["delivery-ready"] });
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async function cancelPackage(id: string) {
|
||||||
|
const res = await fetch(`/api/deliveries/${id}/cancel`, { method: "POST" });
|
||||||
|
const body = await res.json().catch(() => ({}));
|
||||||
|
if (!res.ok) {
|
||||||
|
toast({ title: "Cancel failed", description: body.error ?? res.statusText, variant: "destructive" });
|
||||||
|
}
|
||||||
|
refreshPackages();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Looked up from the live list so the dialog never acts on a stale row.
|
||||||
|
const handoffPackage = handoff ? packages?.packages.find((p) => p.id === handoff.packageId) : undefined;
|
||||||
|
|
||||||
const episodes = ready?.episodes ?? [];
|
const episodes = ready?.episodes ?? [];
|
||||||
const shown = episode ? episodes.filter((e) => e.episode === episode) : episodes;
|
const shown = episode ? episodes.filter((e) => e.episode === episode) : episodes;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="p-6 space-y-6 max-w-6xl">
|
<div className="p-4 md:p-6 space-y-6 max-w-6xl">
|
||||||
<div className="flex items-center gap-3">
|
<div className="flex items-center gap-3">
|
||||||
<Link href="/pipeline">
|
<Link href="/pipeline">
|
||||||
<Button variant="ghost" size="icon-sm">
|
<Button variant="ghost" size="icon-sm">
|
||||||
@@ -156,6 +204,7 @@ export function DeliveriesClient({ canBuild }: { canBuild: boolean }) {
|
|||||||
onChange={(e) => {
|
onChange={(e) => {
|
||||||
setProjectId(e.target.value);
|
setProjectId(e.target.value);
|
||||||
setEpisode("");
|
setEpisode("");
|
||||||
|
setDeselected(new Set());
|
||||||
}}
|
}}
|
||||||
className="rounded-md border border-zinc-800 bg-zinc-900 px-3 py-1.5 text-sm text-zinc-200"
|
className="rounded-md border border-zinc-800 bg-zinc-900 px-3 py-1.5 text-sm text-zinc-200"
|
||||||
>
|
>
|
||||||
@@ -182,6 +231,8 @@ export function DeliveriesClient({ canBuild }: { canBuild: boolean }) {
|
|||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<RequestsPanel projectId={projectId} canBuild={canBuild} />
|
||||||
|
|
||||||
{/* Ready to build */}
|
{/* Ready to build */}
|
||||||
{projectId && (
|
{projectId && (
|
||||||
<div className="rounded-lg border border-zinc-800 bg-zinc-900/40">
|
<div className="rounded-lg border border-zinc-800 bg-zinc-900/40">
|
||||||
@@ -194,30 +245,69 @@ export function DeliveriesClient({ canBuild }: { canBuild: boolean }) {
|
|||||||
Nothing has passed QC yet. Exports appear here once QC passes them.
|
Nothing has passed QC yet. Exports appear here once QC passes them.
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
{shown.map((ep) => (
|
{shown.map((ep) => {
|
||||||
|
const allIds = ep.exports.map((x) => x.exportId);
|
||||||
|
const selectedIds = allIds.filter((id) => !deselected.has(id));
|
||||||
|
const allSelected = selectedIds.length === allIds.length;
|
||||||
|
const selectedExports = ep.exports.filter((x) => !deselected.has(x.exportId));
|
||||||
|
const missingChecksum = selectedExports.filter((x) => !x.hasChecksum).length;
|
||||||
|
return (
|
||||||
<div key={ep.episode} className="border-b border-zinc-800/60 last:border-0">
|
<div key={ep.episode} className="border-b border-zinc-800/60 last:border-0">
|
||||||
<div className="flex items-center justify-between gap-4 px-4 py-3 flex-wrap">
|
<div className="flex items-center justify-between gap-4 px-4 py-3 flex-wrap">
|
||||||
<div>
|
<div>
|
||||||
<span className="text-white text-sm font-medium">
|
<span className="text-white text-sm font-medium">
|
||||||
{ep.episode ? `Episode ${ep.episode}` : "No episode"}
|
{ep.episode ? `Episode ${ep.episode}` : "No episode"}
|
||||||
</span>
|
</span>
|
||||||
<span className="ml-3 text-sm text-zinc-400">Ready: {ep.count} shots</span>
|
<span className="ml-3 text-sm text-zinc-400">
|
||||||
{ep.exports.some((x) => !x.hasChecksum) && (
|
{canBuild ? `Selected: ${selectedIds.length} of ${ep.count} shots` : `Ready: ${ep.count} shots`}
|
||||||
|
</span>
|
||||||
|
{canBuild && selectedIds.length > 0 && (
|
||||||
|
<span className="ml-3 text-xs text-zinc-500">
|
||||||
|
{formatBytes(selectedExports.reduce((sum, x) => sum + (x.totalBytes ?? 0), 0))}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
{missingChecksum > 0 && (
|
||||||
<span className="ml-3 text-xs text-amber-400">
|
<span className="ml-3 text-xs text-amber-400">
|
||||||
{ep.exports.filter((x) => !x.hasChecksum).length} without a validation checksum
|
{missingChecksum} without a validation checksum
|
||||||
</span>
|
</span>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
{canBuild && (
|
{canBuild && (
|
||||||
<Button size="sm" onClick={() => build(ep.episode)} disabled={building}>
|
<span className="flex items-center gap-2">
|
||||||
<Package className="h-4 w-4 mr-2" />
|
<Button
|
||||||
Build delivery
|
size="sm"
|
||||||
</Button>
|
variant="outline"
|
||||||
|
onClick={() => setEpisodeSelected(allIds, !allSelected)}
|
||||||
|
>
|
||||||
|
{allSelected ? "Deselect all" : "Select all"}
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
size="sm"
|
||||||
|
onClick={() => build(ep.episode, selectedIds)}
|
||||||
|
disabled={building || selectedIds.length === 0}
|
||||||
|
>
|
||||||
|
<Package className="h-4 w-4 mr-2" />
|
||||||
|
Build delivery ({selectedIds.length})
|
||||||
|
</Button>
|
||||||
|
</span>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
<div className="px-4 pb-3 grid sm:grid-cols-2 lg:grid-cols-3 gap-x-6 gap-y-1">
|
<div className="px-4 pb-3 grid sm:grid-cols-2 lg:grid-cols-3 gap-x-6 gap-y-1">
|
||||||
{ep.exports.map((x) => (
|
{ep.exports.map((x) => {
|
||||||
<div key={x.exportId} className="flex items-center gap-2 text-xs">
|
const selected = !deselected.has(x.exportId);
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
key={x.exportId}
|
||||||
|
className={cn("flex items-center gap-2 text-xs", canBuild && !selected && "opacity-50")}
|
||||||
|
>
|
||||||
|
{canBuild && (
|
||||||
|
<input
|
||||||
|
type="checkbox"
|
||||||
|
checked={selected}
|
||||||
|
onChange={(e) => toggleExport(x.exportId, e.target.checked)}
|
||||||
|
aria-label={`Include ${x.shotCode} in the package`}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
<Link href={`/pipeline/exports/${x.exportId}`} className="text-zinc-300 hover:text-white">
|
<Link href={`/pipeline/exports/${x.exportId}`} className="text-zinc-300 hover:text-white">
|
||||||
{x.shotCode}
|
{x.shotCode}
|
||||||
</Link>
|
</Link>
|
||||||
@@ -226,10 +316,12 @@ export function DeliveriesClient({ canBuild }: { canBuild: boolean }) {
|
|||||||
<span className="text-zinc-600">{formatBytes(x.totalBytes)}</span>
|
<span className="text-zinc-600">{formatBytes(x.totalBytes)}</span>
|
||||||
{!x.deliveryMovPath && <span className="text-amber-500/80">no MOV</span>}
|
{!x.deliveryMovPath && <span className="text-amber-500/80">no MOV</span>}
|
||||||
</div>
|
</div>
|
||||||
))}
|
);
|
||||||
|
})}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
))}
|
);
|
||||||
|
})}
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
@@ -237,18 +329,31 @@ export function DeliveriesClient({ canBuild }: { canBuild: boolean }) {
|
|||||||
<div className="rounded-lg border border-zinc-800 bg-zinc-900/40">
|
<div className="rounded-lg border border-zinc-800 bg-zinc-900/40">
|
||||||
<div className="px-4 py-2.5 border-b border-zinc-800 text-sm font-medium text-white">Packages</div>
|
<div className="px-4 py-2.5 border-b border-zinc-800 text-sm font-medium text-white">Packages</div>
|
||||||
<div className="divide-y divide-zinc-800/60">
|
<div className="divide-y divide-zinc-800/60">
|
||||||
{(packages?.packages ?? []).map((p) => (
|
{(packages?.packages ?? []).map((p) => {
|
||||||
|
const stage = handoffStage(p);
|
||||||
|
return (
|
||||||
<details key={p.id} className="group">
|
<details key={p.id} className="group">
|
||||||
<summary className="flex items-center gap-3 px-4 py-3 cursor-pointer hover:bg-zinc-900/60 flex-wrap">
|
<summary className="flex items-center gap-3 px-4 py-3 cursor-pointer hover:bg-zinc-900/60 flex-wrap">
|
||||||
<span className="text-sm text-white font-medium">#{p.packageNumber}</span>
|
<span className="text-sm text-white font-medium">#{p.packageNumber}</span>
|
||||||
<span className="text-sm text-zinc-300">{p.name}</span>
|
<span className="text-sm text-zinc-300">{p.name}</span>
|
||||||
|
{p.kind === "MOV_REVIEW" && (
|
||||||
|
<span className="rounded-full border border-violet-500/30 bg-violet-500/10 px-2 py-0.5 text-xs text-violet-300">
|
||||||
|
MOV review
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
<span
|
<span
|
||||||
className={cn(
|
className={cn(
|
||||||
"rounded-full border px-2 py-0.5 text-xs",
|
"rounded-full border px-2 py-0.5 text-xs",
|
||||||
DELIVERY_STATUS_STYLES[p.status] ?? ""
|
// Built is not delivered: a package still owed to the
|
||||||
|
// client must not read as a green "READY".
|
||||||
|
stage ? "bg-amber-500/15 text-amber-400 border-amber-500/30" : (DELIVERY_STATUS_STYLES[p.status] ?? "")
|
||||||
)}
|
)}
|
||||||
>
|
>
|
||||||
{statusLabel(p.status)}
|
{stage === "AWAITING_UPLOAD"
|
||||||
|
? "BUILT — NOT UPLOADED"
|
||||||
|
: stage === "AWAITING_SHARE"
|
||||||
|
? "UPLOADED — LINK NOT SHARED"
|
||||||
|
: statusLabel(p.status)}
|
||||||
</span>
|
</span>
|
||||||
<span className="text-xs text-zinc-500">
|
<span className="text-xs text-zinc-500">
|
||||||
{p.episode ? `episode ${p.episode} · ` : ""}
|
{p.episode ? `episode ${p.episode} · ` : ""}
|
||||||
@@ -257,17 +362,30 @@ export function DeliveriesClient({ canBuild }: { canBuild: boolean }) {
|
|||||||
<span className="text-xs text-zinc-600">{new Date(p.createdAt).toLocaleDateString()}</span>
|
<span className="text-xs text-zinc-600">{new Date(p.createdAt).toLocaleDateString()}</span>
|
||||||
{p.status === "BUILDING" && <RefreshCw className="h-3.5 w-3.5 text-blue-400 animate-spin" />}
|
{p.status === "BUILDING" && <RefreshCw className="h-3.5 w-3.5 text-blue-400 animate-spin" />}
|
||||||
<span className="ml-auto flex items-center gap-2">
|
<span className="ml-auto flex items-center gap-2">
|
||||||
{canBuild && p.status === "READY" && (
|
{canBuild && stage === "AWAITING_UPLOAD" && (
|
||||||
<Button
|
<Button
|
||||||
size="sm"
|
size="sm"
|
||||||
variant="outline"
|
variant="outline"
|
||||||
onClick={(e) => {
|
onClick={(e) => {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
packageAction(p.id, "delivered");
|
setHandoff({ step: "upload", packageId: p.id });
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Upload className="h-4 w-4 mr-2 text-amber-400" />
|
||||||
|
Record upload
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
{canBuild && stage === "AWAITING_SHARE" && (
|
||||||
|
<Button
|
||||||
|
size="sm"
|
||||||
|
variant="outline"
|
||||||
|
onClick={(e) => {
|
||||||
|
e.preventDefault();
|
||||||
|
setHandoff({ step: "share", packageId: p.id });
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<CheckCircle2 className="h-4 w-4 mr-2 text-emerald-400" />
|
<CheckCircle2 className="h-4 w-4 mr-2 text-emerald-400" />
|
||||||
Mark delivered
|
Share link
|
||||||
</Button>
|
</Button>
|
||||||
)}
|
)}
|
||||||
{canBuild && ["QUEUED", "FAILED", "DRAFT"].includes(p.status) && (
|
{canBuild && ["QUEUED", "FAILED", "DRAFT"].includes(p.status) && (
|
||||||
@@ -276,7 +394,7 @@ export function DeliveriesClient({ canBuild }: { canBuild: boolean }) {
|
|||||||
variant="outline"
|
variant="outline"
|
||||||
onClick={(e) => {
|
onClick={(e) => {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
packageAction(p.id, "cancel");
|
cancelPackage(p.id);
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<XCircle className="h-4 w-4 mr-2 text-red-400" />
|
<XCircle className="h-4 w-4 mr-2 text-red-400" />
|
||||||
@@ -288,9 +406,31 @@ export function DeliveriesClient({ canBuild }: { canBuild: boolean }) {
|
|||||||
<div className="px-4 pb-4 space-y-2">
|
<div className="px-4 pb-4 space-y-2">
|
||||||
{p.rootPath && <div className="text-xs text-zinc-500 break-all">{p.rootPath}</div>}
|
{p.rootPath && <div className="text-xs text-zinc-500 break-all">{p.rootPath}</div>}
|
||||||
{p.errorMessage && <div className="text-xs text-red-400">{p.errorMessage}</div>}
|
{p.errorMessage && <div className="text-xs text-red-400">{p.errorMessage}</div>}
|
||||||
|
{p.uploadedAt && p.uploadUrl && (
|
||||||
|
<div className="text-xs text-zinc-400 break-all">
|
||||||
|
Uploaded {new Date(p.uploadedAt).toLocaleString()}
|
||||||
|
{p.uploadedByName ? ` by ${p.uploadedByName}` : ""} —{" "}
|
||||||
|
<a href={p.uploadUrl} target="_blank" rel="noreferrer" className="text-sky-400 hover:underline">
|
||||||
|
{p.uploadUrl}
|
||||||
|
</a>
|
||||||
|
{canBuild && stage === "AWAITING_SHARE" && (
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="ml-2 text-zinc-500 hover:text-white underline"
|
||||||
|
onClick={() => setHandoff({ step: "upload", packageId: p.id })}
|
||||||
|
>
|
||||||
|
change
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
{p.deliveredAt && (
|
{p.deliveredAt && (
|
||||||
<div className="text-xs text-emerald-400">
|
<div className="text-xs text-emerald-400">
|
||||||
Delivered {new Date(p.deliveredAt).toLocaleString()}
|
{p.sharedWith
|
||||||
|
? `Link shared with ${p.sharedWith} ${new Date(p.deliveredAt).toLocaleString()}`
|
||||||
|
: `Delivered ${new Date(p.deliveredAt).toLocaleString()} — before uploads and shares were recorded`}
|
||||||
|
{p.deliveredByName ? ` by ${p.deliveredByName}` : ""}
|
||||||
|
{p.sharedNote ? ` — ${p.sharedNote}` : ""}
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
<div className="grid sm:grid-cols-2 lg:grid-cols-3 gap-x-6 gap-y-1">
|
<div className="grid sm:grid-cols-2 lg:grid-cols-3 gap-x-6 gap-y-1">
|
||||||
@@ -309,7 +449,9 @@ export function DeliveriesClient({ canBuild }: { canBuild: boolean }) {
|
|||||||
</span>
|
</span>
|
||||||
<span className="text-zinc-300">{item.shotCode}</span>
|
<span className="text-zinc-300">{item.shotCode}</span>
|
||||||
<span className="text-zinc-500">{item.versionString}</span>
|
<span className="text-zinc-500">{item.versionString}</span>
|
||||||
{item.fileCount != null && <span className="text-zinc-600">{item.fileCount}f</span>}
|
{p.kind === "EXR_DELIVERY" && item.fileCount != null && (
|
||||||
|
<span className="text-zinc-600">{item.fileCount}f</span>
|
||||||
|
)}
|
||||||
{item.linkMode && <span className="text-zinc-600">{item.linkMode}</span>}
|
{item.linkMode && <span className="text-zinc-600">{item.linkMode}</span>}
|
||||||
{item.errorMessage && <span className="text-red-400">{item.errorMessage}</span>}
|
{item.errorMessage && <span className="text-red-400">{item.errorMessage}</span>}
|
||||||
</div>
|
</div>
|
||||||
@@ -317,12 +459,24 @@ export function DeliveriesClient({ canBuild }: { canBuild: boolean }) {
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</details>
|
</details>
|
||||||
))}
|
);
|
||||||
|
})}
|
||||||
{(packages?.packages ?? []).length === 0 && (
|
{(packages?.packages ?? []).length === 0 && (
|
||||||
<div className="p-4 text-sm text-zinc-500">No packages built yet</div>
|
<div className="p-4 text-sm text-zinc-500">No packages built yet</div>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
{handoff?.step === "upload" && handoffPackage && (
|
||||||
|
<RecordUploadDialog pkg={handoffPackage} onClose={() => setHandoff(null)} onSaved={refreshPackages} />
|
||||||
|
)}
|
||||||
|
{handoff?.step === "share" && handoffPackage?.uploadUrl && (
|
||||||
|
<RecordShareDialog
|
||||||
|
pkg={{ ...handoffPackage, uploadUrl: handoffPackage.uploadUrl }}
|
||||||
|
onClose={() => setHandoff(null)}
|
||||||
|
onSaved={refreshPackages}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,218 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useState } from "react";
|
||||||
|
import { Copy } from "lucide-react";
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";
|
||||||
|
import { Input } from "@/components/ui/input";
|
||||||
|
import { Label } from "@/components/ui/label";
|
||||||
|
import { Textarea } from "@/components/ui/textarea";
|
||||||
|
import { useToast } from "@/components/ui/use-toast";
|
||||||
|
import { buildShareMessage } from "@/lib/render-pipeline/delivery-handoff";
|
||||||
|
|
||||||
|
export interface HandoffPackage {
|
||||||
|
id: string;
|
||||||
|
packageNumber: number;
|
||||||
|
name: string;
|
||||||
|
projectCode: string;
|
||||||
|
episode: string;
|
||||||
|
rootPath: string | null;
|
||||||
|
uploadUrl: string | null;
|
||||||
|
itemCount: number;
|
||||||
|
exrFileCount: number;
|
||||||
|
movCount: number;
|
||||||
|
totalBytes: number;
|
||||||
|
items: { shotCode: string; clientCode: string | null; versionString: string }[];
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatSize(bytes: number): string {
|
||||||
|
if (!bytes) return "size unknown";
|
||||||
|
const gb = bytes / 1_073_741_824;
|
||||||
|
return gb >= 1 ? `${gb.toFixed(1)} GB` : `${(bytes / 1_048_576).toFixed(0)} MB`;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function post(path: string, body: unknown): Promise<string | null> {
|
||||||
|
const res = await fetch(path, {
|
||||||
|
method: "POST",
|
||||||
|
headers: { "Content-Type": "application/json" },
|
||||||
|
body: JSON.stringify(body),
|
||||||
|
});
|
||||||
|
if (res.ok) return null;
|
||||||
|
const data = await res.json().catch(() => ({}));
|
||||||
|
return data.error ?? res.statusText;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Step one: where the folder now lives on the client's side. */
|
||||||
|
export function RecordUploadDialog({
|
||||||
|
pkg,
|
||||||
|
onClose,
|
||||||
|
onSaved,
|
||||||
|
}: {
|
||||||
|
pkg: HandoffPackage;
|
||||||
|
onClose: () => void;
|
||||||
|
onSaved: () => void;
|
||||||
|
}) {
|
||||||
|
const { toast } = useToast();
|
||||||
|
const [uploadUrl, setUploadUrl] = useState(pkg.uploadUrl ?? "");
|
||||||
|
const [confirmed, setConfirmed] = useState(false);
|
||||||
|
const [saving, setSaving] = useState(false);
|
||||||
|
|
||||||
|
async function save() {
|
||||||
|
setSaving(true);
|
||||||
|
const error = await post(`/api/deliveries/${pkg.id}/uploaded`, { uploadUrl, contentsConfirmed: confirmed });
|
||||||
|
setSaving(false);
|
||||||
|
if (error) {
|
||||||
|
toast({ title: "Upload not recorded", description: error, variant: "destructive" });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
onSaved();
|
||||||
|
onClose();
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Dialog open onOpenChange={(open) => !open && onClose()}>
|
||||||
|
<DialogContent>
|
||||||
|
<DialogHeader>
|
||||||
|
<DialogTitle>
|
||||||
|
Record upload — #{pkg.packageNumber} {pkg.name}
|
||||||
|
</DialogTitle>
|
||||||
|
<DialogDescription>
|
||||||
|
Paste the link to the folder on the client's portal. The package stays on the dashboard as
|
||||||
|
awaiting delivery until the link has also been shared.
|
||||||
|
</DialogDescription>
|
||||||
|
</DialogHeader>
|
||||||
|
|
||||||
|
<div className="space-y-4">
|
||||||
|
<div className="rounded-md border border-zinc-800 bg-zinc-900/60 p-3 text-xs text-zinc-400 space-y-1">
|
||||||
|
<div className="text-zinc-200">
|
||||||
|
The upload should contain {pkg.itemCount} shot{pkg.itemCount === 1 ? "" : "s"} · {pkg.exrFileCount} EXR
|
||||||
|
frames · {pkg.movCount} MOV{pkg.movCount === 1 ? "" : "s"} · {formatSize(pkg.totalBytes)}
|
||||||
|
</div>
|
||||||
|
{pkg.rootPath && <div className="break-all">Source: {pkg.rootPath}</div>}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="space-y-1.5">
|
||||||
|
<Label htmlFor="upload-url">Upload link</Label>
|
||||||
|
<Input
|
||||||
|
id="upload-url"
|
||||||
|
type="url"
|
||||||
|
placeholder="https://…"
|
||||||
|
value={uploadUrl}
|
||||||
|
onChange={(e) => setUploadUrl(e.target.value)}
|
||||||
|
autoFocus
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<label className="flex items-start gap-2 text-sm text-zinc-300">
|
||||||
|
<input
|
||||||
|
type="checkbox"
|
||||||
|
className="mt-1"
|
||||||
|
checked={confirmed}
|
||||||
|
onChange={(e) => setConfirmed(e.target.checked)}
|
||||||
|
/>
|
||||||
|
<span>I opened this link and the upload has finished and matches the counts above.</span>
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<DialogFooter>
|
||||||
|
<Button variant="outline" onClick={onClose}>
|
||||||
|
Cancel
|
||||||
|
</Button>
|
||||||
|
<Button onClick={save} disabled={saving || !uploadUrl.trim() || !confirmed}>
|
||||||
|
Record upload
|
||||||
|
</Button>
|
||||||
|
</DialogFooter>
|
||||||
|
</DialogContent>
|
||||||
|
</Dialog>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Step two: the link went to a person. This is what makes it delivered. */
|
||||||
|
export function RecordShareDialog({
|
||||||
|
pkg,
|
||||||
|
onClose,
|
||||||
|
onSaved,
|
||||||
|
}: {
|
||||||
|
pkg: HandoffPackage & { uploadUrl: string };
|
||||||
|
onClose: () => void;
|
||||||
|
onSaved: () => void;
|
||||||
|
}) {
|
||||||
|
const { toast } = useToast();
|
||||||
|
const [sharedWith, setSharedWith] = useState("");
|
||||||
|
const [note, setNote] = useState("");
|
||||||
|
const [saving, setSaving] = useState(false);
|
||||||
|
const message = buildShareMessage(pkg);
|
||||||
|
|
||||||
|
async function copy() {
|
||||||
|
try {
|
||||||
|
await navigator.clipboard.writeText(message);
|
||||||
|
toast({ title: "Message copied" });
|
||||||
|
} catch {
|
||||||
|
toast({ title: "Could not copy", description: "Select the text and copy it by hand.", variant: "destructive" });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function save() {
|
||||||
|
setSaving(true);
|
||||||
|
const error = await post(`/api/deliveries/${pkg.id}/delivered`, { sharedWith, note: note || null });
|
||||||
|
setSaving(false);
|
||||||
|
if (error) {
|
||||||
|
toast({ title: "Not marked delivered", description: error, variant: "destructive" });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
onSaved();
|
||||||
|
onClose();
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Dialog open onOpenChange={(open) => !open && onClose()}>
|
||||||
|
<DialogContent>
|
||||||
|
<DialogHeader>
|
||||||
|
<DialogTitle>
|
||||||
|
Share link — #{pkg.packageNumber} {pkg.name}
|
||||||
|
</DialogTitle>
|
||||||
|
<DialogDescription>
|
||||||
|
Send this message to the client, then record who it went to. That marks the package delivered.
|
||||||
|
</DialogDescription>
|
||||||
|
</DialogHeader>
|
||||||
|
|
||||||
|
<div className="space-y-4">
|
||||||
|
<div className="space-y-1.5">
|
||||||
|
<div className="flex items-center justify-between">
|
||||||
|
<Label htmlFor="share-message">Message</Label>
|
||||||
|
<Button size="sm" variant="outline" onClick={copy}>
|
||||||
|
<Copy className="h-3.5 w-3.5 mr-2" />
|
||||||
|
Copy message
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
<Textarea id="share-message" readOnly value={message} rows={8} className="font-mono text-xs" />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="space-y-1.5">
|
||||||
|
<Label htmlFor="shared-with">Sent to</Label>
|
||||||
|
<Input
|
||||||
|
id="shared-with"
|
||||||
|
placeholder="Name, and where — e.g. Sam, production WhatsApp group"
|
||||||
|
value={sharedWith}
|
||||||
|
onChange={(e) => setSharedWith(e.target.value)}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="space-y-1.5">
|
||||||
|
<Label htmlFor="share-note">Note (optional)</Label>
|
||||||
|
<Input id="share-note" value={note} onChange={(e) => setNote(e.target.value)} />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<DialogFooter>
|
||||||
|
<Button variant="outline" onClick={onClose}>
|
||||||
|
Cancel
|
||||||
|
</Button>
|
||||||
|
<Button onClick={save} disabled={saving || !sharedWith.trim()}>
|
||||||
|
Link sent — mark delivered
|
||||||
|
</Button>
|
||||||
|
</DialogFooter>
|
||||||
|
</DialogContent>
|
||||||
|
</Dialog>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,273 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useState } from "react";
|
||||||
|
import { useQuery, useQueryClient } from "@tanstack/react-query";
|
||||||
|
import { Package, Plus, XCircle } from "lucide-react";
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";
|
||||||
|
import { Input } from "@/components/ui/input";
|
||||||
|
import { useToast } from "@/components/ui/use-toast";
|
||||||
|
import { cn } from "@/lib/utils";
|
||||||
|
import { LogRequestDialog } from "@/components/delivery/LogRequestDialog";
|
||||||
|
import {
|
||||||
|
DELIVERABLE_LABEL,
|
||||||
|
LINE_STAGE_LABEL,
|
||||||
|
type Deliverable,
|
||||||
|
type RequestLineStage,
|
||||||
|
} from "@/lib/render-pipeline/delivery-request-state";
|
||||||
|
|
||||||
|
interface RequestRow {
|
||||||
|
id: string;
|
||||||
|
requestNumber: number;
|
||||||
|
projectId: string;
|
||||||
|
projectCode: string;
|
||||||
|
episode: string;
|
||||||
|
deliverable: string;
|
||||||
|
requestedBy: string;
|
||||||
|
note: string | null;
|
||||||
|
dueDate: string | null;
|
||||||
|
createdAt: string;
|
||||||
|
cancelReason: string | null;
|
||||||
|
state: "OPEN" | "CLOSED" | "CANCELLED";
|
||||||
|
lineCount: number;
|
||||||
|
deliveredCount: number;
|
||||||
|
severity: "normal" | "warning" | "critical";
|
||||||
|
lines: {
|
||||||
|
id: string;
|
||||||
|
shotCode: string;
|
||||||
|
clientCode: string | null;
|
||||||
|
stage: RequestLineStage;
|
||||||
|
readyExportId: string | null;
|
||||||
|
}[];
|
||||||
|
}
|
||||||
|
|
||||||
|
const SEVERITY_STYLES: Record<RequestRow["severity"], string> = {
|
||||||
|
normal: "bg-zinc-500/15 text-zinc-300 border-zinc-500/30",
|
||||||
|
warning: "bg-amber-500/15 text-amber-400 border-amber-500/30",
|
||||||
|
critical: "bg-red-500/15 text-red-400 border-red-500/30",
|
||||||
|
};
|
||||||
|
|
||||||
|
const STAGE_STYLES: Record<RequestLineStage, string> = {
|
||||||
|
DELIVERED: "text-emerald-400",
|
||||||
|
UPLOADED: "text-amber-400",
|
||||||
|
BUILT: "text-amber-400",
|
||||||
|
BUILDING: "text-blue-400",
|
||||||
|
READY: "text-green-400",
|
||||||
|
IN_QC: "text-zinc-400",
|
||||||
|
NOT_READY: "text-zinc-500",
|
||||||
|
};
|
||||||
|
|
||||||
|
function requestTitle(r: RequestRow): string {
|
||||||
|
const what = DELIVERABLE_LABEL[r.deliverable as Deliverable] ?? r.deliverable;
|
||||||
|
return r.episode ? `${what} for ${r.episode}` : `${what} · ${r.lineCount} shot${r.lineCount === 1 ? "" : "s"}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* What clients have asked for. An open request lists every shot with where it
|
||||||
|
* stands, so "did 116 go out?" is answered by the page rather than by memory.
|
||||||
|
*/
|
||||||
|
export function RequestsPanel({ projectId, canBuild }: { projectId: string; canBuild: boolean }) {
|
||||||
|
const { toast } = useToast();
|
||||||
|
const queryClient = useQueryClient();
|
||||||
|
const [logging, setLogging] = useState(false);
|
||||||
|
const [cancelling, setCancelling] = useState<RequestRow | null>(null);
|
||||||
|
const [reason, setReason] = useState("");
|
||||||
|
const [busy, setBusy] = useState(false);
|
||||||
|
|
||||||
|
const { data } = useQuery({
|
||||||
|
queryKey: ["delivery-requests", projectId],
|
||||||
|
queryFn: async () => {
|
||||||
|
const res = await fetch(`/api/delivery-requests${projectId ? `?projectId=${encodeURIComponent(projectId)}` : ""}`);
|
||||||
|
if (!res.ok) throw new Error("Failed to load delivery requests");
|
||||||
|
return res.json() as Promise<{ requests: RequestRow[] }>;
|
||||||
|
},
|
||||||
|
// Lines move as packages build and get shared on this same page.
|
||||||
|
refetchInterval: 5000,
|
||||||
|
});
|
||||||
|
|
||||||
|
const refresh = () => {
|
||||||
|
queryClient.invalidateQueries({ queryKey: ["delivery-requests"] });
|
||||||
|
queryClient.invalidateQueries({ queryKey: ["delivery-packages"] });
|
||||||
|
queryClient.invalidateQueries({ queryKey: ["delivery-ready"] });
|
||||||
|
};
|
||||||
|
|
||||||
|
async function build(request: RequestRow) {
|
||||||
|
const exportIds = request.lines.flatMap((l) => (l.readyExportId ? [l.readyExportId] : []));
|
||||||
|
if (!exportIds.length) return;
|
||||||
|
setBusy(true);
|
||||||
|
const res = await fetch("/api/deliveries", {
|
||||||
|
method: "POST",
|
||||||
|
headers: { "Content-Type": "application/json" },
|
||||||
|
body: JSON.stringify({ projectId: request.projectId, episode: request.episode || null, exportIds }),
|
||||||
|
});
|
||||||
|
const body = await res.json().catch(() => ({}));
|
||||||
|
setBusy(false);
|
||||||
|
if (!res.ok) {
|
||||||
|
toast({ title: "Build failed", description: body.error ?? res.statusText, variant: "destructive" });
|
||||||
|
} else {
|
||||||
|
toast({
|
||||||
|
title: `Package #${body.package.packageNumber} queued`,
|
||||||
|
description: `${body.package.itemCount} shots for request #${request.requestNumber}`,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
refresh();
|
||||||
|
}
|
||||||
|
|
||||||
|
async function cancel() {
|
||||||
|
if (!cancelling) return;
|
||||||
|
setBusy(true);
|
||||||
|
const res = await fetch(`/api/delivery-requests/${cancelling.id}/cancel`, {
|
||||||
|
method: "POST",
|
||||||
|
headers: { "Content-Type": "application/json" },
|
||||||
|
body: JSON.stringify({ reason }),
|
||||||
|
});
|
||||||
|
const body = await res.json().catch(() => ({}));
|
||||||
|
setBusy(false);
|
||||||
|
if (!res.ok) {
|
||||||
|
toast({ title: "Not cancelled", description: body.error ?? res.statusText, variant: "destructive" });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setCancelling(null);
|
||||||
|
refresh();
|
||||||
|
}
|
||||||
|
|
||||||
|
const requests = data?.requests ?? [];
|
||||||
|
const open = requests.filter((r) => r.state === "OPEN");
|
||||||
|
const past = requests.filter((r) => r.state !== "OPEN");
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="rounded-lg border border-zinc-800 bg-zinc-900/40">
|
||||||
|
<div className="flex items-center justify-between gap-3 px-4 py-2.5 border-b border-zinc-800">
|
||||||
|
<span className="text-sm font-medium text-white">Delivery requests</span>
|
||||||
|
{canBuild && (
|
||||||
|
<Button size="sm" variant="outline" onClick={() => setLogging(true)}>
|
||||||
|
<Plus className="h-3.5 w-3.5 mr-1.5" />
|
||||||
|
Log request
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{open.length === 0 && <div className="p-4 text-sm text-zinc-500">No open requests.</div>}
|
||||||
|
|
||||||
|
<div className="divide-y divide-zinc-800/60">
|
||||||
|
{open.map((r) => {
|
||||||
|
const readyCount = r.lines.filter((l) => l.readyExportId).length;
|
||||||
|
return (
|
||||||
|
<details key={r.id} open className="group">
|
||||||
|
<summary className="flex items-center gap-3 px-4 py-3 cursor-pointer hover:bg-zinc-900/60 flex-wrap">
|
||||||
|
<span className="text-sm text-white font-medium">Request #{r.requestNumber}</span>
|
||||||
|
<span className="text-sm text-zinc-300">{requestTitle(r)}</span>
|
||||||
|
<span className={cn("rounded-full border px-2 py-0.5 text-xs", SEVERITY_STYLES[r.severity])}>
|
||||||
|
{r.deliveredCount} of {r.lineCount} delivered
|
||||||
|
</span>
|
||||||
|
<span className="text-xs text-zinc-500">
|
||||||
|
{r.projectCode} · asked by {r.requestedBy} · {new Date(r.createdAt).toLocaleDateString()}
|
||||||
|
{r.dueDate ? ` · due ${new Date(r.dueDate).toLocaleDateString()}` : ""}
|
||||||
|
</span>
|
||||||
|
<span className="ml-auto flex items-center gap-2">
|
||||||
|
{canBuild && readyCount > 0 && (
|
||||||
|
<Button
|
||||||
|
size="sm"
|
||||||
|
disabled={busy}
|
||||||
|
onClick={(e) => {
|
||||||
|
e.preventDefault();
|
||||||
|
build(r);
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Package className="h-4 w-4 mr-2" />
|
||||||
|
Build {readyCount} ready
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
{canBuild && (
|
||||||
|
<Button
|
||||||
|
size="sm"
|
||||||
|
variant="outline"
|
||||||
|
onClick={(e) => {
|
||||||
|
e.preventDefault();
|
||||||
|
setReason("");
|
||||||
|
setCancelling(r);
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<XCircle className="h-4 w-4 mr-2 text-red-400" />
|
||||||
|
Cancel request
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
</span>
|
||||||
|
</summary>
|
||||||
|
<div className="px-4 pb-4 space-y-2">
|
||||||
|
{r.note && <div className="text-xs text-zinc-400">{r.note}</div>}
|
||||||
|
<div className="grid sm:grid-cols-2 lg:grid-cols-3 gap-x-6 gap-y-1">
|
||||||
|
{r.lines.map((line) => (
|
||||||
|
<div key={line.id} className="flex items-center gap-2 text-xs">
|
||||||
|
<span className="text-zinc-300">{line.shotCode}</span>
|
||||||
|
{line.clientCode && <span className="text-zinc-600">{line.clientCode}</span>}
|
||||||
|
<span className={STAGE_STYLES[line.stage]}>{LINE_STAGE_LABEL[line.stage]}</span>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</details>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{past.length > 0 && (
|
||||||
|
<details className="border-t border-zinc-800">
|
||||||
|
<summary className="px-4 py-2.5 cursor-pointer text-xs text-zinc-500 hover:text-zinc-300">
|
||||||
|
Closed and cancelled ({past.length})
|
||||||
|
</summary>
|
||||||
|
<div className="px-4 pb-3 space-y-1">
|
||||||
|
{past.map((r) => (
|
||||||
|
<div key={r.id} className="text-xs text-zinc-500">
|
||||||
|
<span className="text-zinc-300">Request #{r.requestNumber}</span> {requestTitle(r)} · {r.projectCode} ·
|
||||||
|
asked by {r.requestedBy} ·{" "}
|
||||||
|
{r.state === "CANCELLED" ? (
|
||||||
|
<span className="text-zinc-400">cancelled — {r.cancelReason}</span>
|
||||||
|
) : (
|
||||||
|
<span className="text-emerald-400">all {r.lineCount} delivered</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</details>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<LogRequestDialog
|
||||||
|
open={logging}
|
||||||
|
onClose={() => setLogging(false)}
|
||||||
|
onLogged={refresh}
|
||||||
|
defaultProjectId={projectId || undefined}
|
||||||
|
/>
|
||||||
|
|
||||||
|
{cancelling && (
|
||||||
|
<Dialog open onOpenChange={(o) => !o && !busy && setCancelling(null)}>
|
||||||
|
<DialogContent>
|
||||||
|
<DialogHeader>
|
||||||
|
<DialogTitle>Cancel request #{cancelling.requestNumber}</DialogTitle>
|
||||||
|
<DialogDescription>
|
||||||
|
{cancelling.lineCount - cancelling.deliveredCount} of {cancelling.lineCount} shots have not been
|
||||||
|
delivered. Cancelling removes the request from Awaiting delivery; it stays in the history with the
|
||||||
|
reason.
|
||||||
|
</DialogDescription>
|
||||||
|
</DialogHeader>
|
||||||
|
<Input
|
||||||
|
aria-label="Reason"
|
||||||
|
placeholder="Why — e.g. client no longer needs 116"
|
||||||
|
value={reason}
|
||||||
|
onChange={(e) => setReason(e.target.value)}
|
||||||
|
autoFocus
|
||||||
|
/>
|
||||||
|
<DialogFooter>
|
||||||
|
<Button variant="outline" onClick={() => setCancelling(null)} disabled={busy}>
|
||||||
|
Keep request
|
||||||
|
</Button>
|
||||||
|
<Button variant="destructive" onClick={cancel} disabled={busy || !reason.trim()}>
|
||||||
|
Cancel request
|
||||||
|
</Button>
|
||||||
|
</DialogFooter>
|
||||||
|
</DialogContent>
|
||||||
|
</Dialog>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -155,10 +155,10 @@ export function ExportDetailClient({ exportId }: { exportId: string }) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (isLoading) return <div className="p-6 text-zinc-500">Loading…</div>;
|
if (isLoading) return <div className="p-4 md:p-6 text-zinc-500">Loading…</div>;
|
||||||
if (error || !data) {
|
if (error || !data) {
|
||||||
return (
|
return (
|
||||||
<div className="p-6 text-red-400">
|
<div className="p-4 md:p-6 text-red-400">
|
||||||
{(error as Error)?.message ?? "Export not found"}
|
{(error as Error)?.message ?? "Export not found"}
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
@@ -180,7 +180,7 @@ export function ExportDetailClient({ exportId }: { exportId: string }) {
|
|||||||
];
|
];
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="p-6 space-y-6 max-w-5xl">
|
<div className="p-4 md:p-6 space-y-6 max-w-5xl">
|
||||||
<div className="flex items-center justify-between gap-4 flex-wrap">
|
<div className="flex items-center justify-between gap-4 flex-wrap">
|
||||||
<div className="flex items-center gap-3">
|
<div className="flex items-center gap-3">
|
||||||
<Link href="/pipeline">
|
<Link href="/pipeline">
|
||||||
|
|||||||
@@ -76,7 +76,7 @@ export function MachinesClient() {
|
|||||||
const machines = data?.machines ?? [];
|
const machines = data?.machines ?? [];
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="p-6 space-y-6">
|
<div className="p-4 md:p-6 space-y-6">
|
||||||
<div className="flex items-center gap-3">
|
<div className="flex items-center gap-3">
|
||||||
<Link href="/pipeline">
|
<Link href="/pipeline">
|
||||||
<Button variant="ghost" size="icon-sm">
|
<Button variant="ghost" size="icon-sm">
|
||||||
|
|||||||
@@ -1,20 +1,32 @@
|
|||||||
import { auth } from "@/auth";
|
import { auth } from "@/auth";
|
||||||
import { redirect } from "next/navigation";
|
import { redirect } from "next/navigation";
|
||||||
|
import { ExportStatus } from "@prisma/client";
|
||||||
import { db } from "@/lib/db";
|
import { db } from "@/lib/db";
|
||||||
import { PipelineQueueClient } from "./PipelineQueueClient";
|
import { PipelineQueueClient } from "./PipelineQueueClient";
|
||||||
|
|
||||||
export const dynamic = "force-dynamic";
|
export const dynamic = "force-dynamic";
|
||||||
|
|
||||||
export default async function PipelinePage() {
|
export default async function PipelinePage({
|
||||||
|
searchParams,
|
||||||
|
}: {
|
||||||
|
searchParams: Promise<{ status?: string }>;
|
||||||
|
}) {
|
||||||
const session = await auth();
|
const session = await auth();
|
||||||
if (!session?.user) redirect("/login");
|
if (!session?.user) redirect("/login");
|
||||||
if (session.user.role === "CLIENT") redirect("/dashboard");
|
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({
|
const projects = await db.project.findMany({
|
||||||
where: { status: { in: ["ACTIVE", "ON_HOLD"] } },
|
where: { status: { in: ["ACTIVE", "ON_HOLD"] } },
|
||||||
select: { id: true, name: true, code: true },
|
select: { id: true, name: true, code: true },
|
||||||
orderBy: { name: "asc" },
|
orderBy: { name: "asc" },
|
||||||
});
|
});
|
||||||
|
|
||||||
return <PipelineQueueClient projects={projects} />;
|
return <PipelineQueueClient projects={projects} initialStatus={initialStatus} />;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,9 +1,10 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import { useState, useEffect, useRef, useCallback } from "react";
|
import { useState, useEffect, useRef, useCallback, useMemo, startTransition } from "react";
|
||||||
import Image from "next/image";
|
import Image from "next/image";
|
||||||
import Link from "next/link";
|
import Link from "next/link";
|
||||||
import { ReviewPlayer, type ReviewPlayerRef } from "@/components/player/ReviewPlayer";
|
import { ReviewPlayer, type ReviewPlayerRef } from "@/components/player/ReviewPlayer";
|
||||||
|
import { SequencePlayer, type SequenceClip } from "@/components/player/SequencePlayer";
|
||||||
import { useReviewStore } from "@/hooks/use-review-player";
|
import { useReviewStore } from "@/hooks/use-review-player";
|
||||||
import {
|
import {
|
||||||
Select,
|
Select,
|
||||||
@@ -26,6 +27,8 @@ import {
|
|||||||
ExternalLink,
|
ExternalLink,
|
||||||
ShieldCheck,
|
ShieldCheck,
|
||||||
Send,
|
Send,
|
||||||
|
ListVideo,
|
||||||
|
X,
|
||||||
} from "lucide-react";
|
} from "lucide-react";
|
||||||
|
|
||||||
interface Project {
|
interface Project {
|
||||||
@@ -42,6 +45,12 @@ interface PlaylistVersion {
|
|||||||
thumbnailUrl: string | null;
|
thumbnailUrl: string | null;
|
||||||
posterUrl: string | null;
|
posterUrl: string | null;
|
||||||
fps: number;
|
fps: number;
|
||||||
|
duration?: number | null;
|
||||||
|
frameCount?: number | null;
|
||||||
|
hqFileUrl?: string | null;
|
||||||
|
handleHead?: number | null;
|
||||||
|
handleTail?: number | null;
|
||||||
|
pictureStartFrame?: number | null;
|
||||||
approvalStatus: string;
|
approvalStatus: string;
|
||||||
taskTitle: string;
|
taskTitle: string;
|
||||||
}
|
}
|
||||||
@@ -86,6 +95,10 @@ export function PlaylistClient({ projects, userRole }: PlaylistClientProps) {
|
|||||||
const [activeShot, setActiveShot] = useState<PlaylistShot | null>(null);
|
const [activeShot, setActiveShot] = useState<PlaylistShot | null>(null);
|
||||||
const [isLoading, setIsLoading] = useState(false);
|
const [isLoading, setIsLoading] = useState(false);
|
||||||
const [isActioning, setIsActioning] = useState(false);
|
const [isActioning, setIsActioning] = useState(false);
|
||||||
|
/** Shots checked for the seamless playlist, by shot id. */
|
||||||
|
const [selected, setSelected] = useState<Set<string>>(new Set());
|
||||||
|
const [sequenceMode, setSequenceMode] = useState(false);
|
||||||
|
const lastChecked = useRef<string | null>(null);
|
||||||
|
|
||||||
const canApprove = ["ADMIN", "PRODUCER", "SUPERVISOR"].includes(userRole);
|
const canApprove = ["ADMIN", "PRODUCER", "SUPERVISOR"].includes(userRole);
|
||||||
|
|
||||||
@@ -112,6 +125,9 @@ export function PlaylistClient({ projects, userRole }: PlaylistClientProps) {
|
|||||||
if (cancelled) return;
|
if (cancelled) return;
|
||||||
const list: PlaylistShot[] = data.shots ?? [];
|
const list: PlaylistShot[] = data.shots ?? [];
|
||||||
setShots(list);
|
setShots(list);
|
||||||
|
setSelected(loadSelection(projectId, list));
|
||||||
|
lastChecked.current = null;
|
||||||
|
setSequenceMode(false);
|
||||||
// Auto-select the first shot, or keep the current one if it still exists
|
// Auto-select the first shot, or keep the current one if it still exists
|
||||||
setActiveShot((prev) => {
|
setActiveShot((prev) => {
|
||||||
const stillExists = prev && list.some((s) => s.id === prev.id);
|
const stillExists = prev && list.some((s) => s.id === prev.id);
|
||||||
@@ -134,9 +150,78 @@ export function PlaylistClient({ projects, userRole }: PlaylistClientProps) {
|
|||||||
|
|
||||||
const handleSelectShot = useCallback((shot: PlaylistShot) => {
|
const handleSelectShot = useCallback((shot: PlaylistShot) => {
|
||||||
reset();
|
reset();
|
||||||
|
setSequenceMode(false);
|
||||||
setActiveShot(shot);
|
setActiveShot(shot);
|
||||||
}, [reset]);
|
}, [reset]);
|
||||||
|
|
||||||
|
const updateSelection = useCallback(
|
||||||
|
(next: Set<string>) => {
|
||||||
|
setSelected(next);
|
||||||
|
if (projectId) saveSelection(projectId, next);
|
||||||
|
if (next.size === 0) setSequenceMode(false);
|
||||||
|
},
|
||||||
|
[projectId]
|
||||||
|
);
|
||||||
|
|
||||||
|
/** Toggle one shot; shift-click sets every shot between it and the last one checked. */
|
||||||
|
const toggleChecked = (shot: PlaylistShot, shift: boolean) => {
|
||||||
|
const next = new Set(selected);
|
||||||
|
const on = !selected.has(shot.id);
|
||||||
|
const from = lastChecked.current ? shots.findIndex((s) => s.id === lastChecked.current) : -1;
|
||||||
|
const to = shots.findIndex((s) => s.id === shot.id);
|
||||||
|
const range = shift && from >= 0 ? shots.slice(Math.min(from, to), Math.max(from, to) + 1) : [shot];
|
||||||
|
for (const s of range) {
|
||||||
|
if (on) next.add(s.id);
|
||||||
|
else next.delete(s.id);
|
||||||
|
}
|
||||||
|
lastChecked.current = shot.id;
|
||||||
|
updateSelection(next);
|
||||||
|
};
|
||||||
|
|
||||||
|
const setGroupChecked = (group: PlaylistShot[], on: boolean) => {
|
||||||
|
const next = new Set(selected);
|
||||||
|
for (const s of group) {
|
||||||
|
if (on) next.add(s.id);
|
||||||
|
else next.delete(s.id);
|
||||||
|
}
|
||||||
|
updateSelection(next);
|
||||||
|
};
|
||||||
|
|
||||||
|
// The playlist, in edit order. Keyed on the versions it plays so a refresh
|
||||||
|
// (e.g. after approving a shot) doesn't restart playback.
|
||||||
|
const clipKey = shots
|
||||||
|
.filter((s) => selected.has(s.id))
|
||||||
|
.map((s) => s.latestVersion.id)
|
||||||
|
.join(",");
|
||||||
|
const clips = useMemo<SequenceClip[]>(
|
||||||
|
() =>
|
||||||
|
shots
|
||||||
|
.filter((s) => selected.has(s.id))
|
||||||
|
.map((s) => ({
|
||||||
|
id: s.latestVersion.id,
|
||||||
|
label: s.shotCode,
|
||||||
|
sublabel: `v${String(s.latestVersion.versionNumber).padStart(3, "0")}`,
|
||||||
|
url: s.latestVersion.fileUrl,
|
||||||
|
hqUrl: s.latestVersion.hqFileUrl,
|
||||||
|
fps: s.latestVersion.fps,
|
||||||
|
duration: s.latestVersion.duration,
|
||||||
|
handles: s.latestVersion,
|
||||||
|
})),
|
||||||
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||||
|
[clipKey]
|
||||||
|
);
|
||||||
|
|
||||||
|
const handleClipChange = useCallback(
|
||||||
|
(clip: SequenceClip) => {
|
||||||
|
// A transition, so re-rendering the page (shot list and all) yields to
|
||||||
|
// the video: rendered in one go, it dropped the frame after every cut.
|
||||||
|
startTransition(() => {
|
||||||
|
setActiveShot(shots.find((s) => s.latestVersion.id === clip.id) ?? null);
|
||||||
|
});
|
||||||
|
},
|
||||||
|
[shots]
|
||||||
|
);
|
||||||
|
|
||||||
const refreshShots = useCallback(() => {
|
const refreshShots = useCallback(() => {
|
||||||
if (!projectId) return;
|
if (!projectId) return;
|
||||||
fetch(`/api/playlist?projectId=${projectId}`)
|
fetch(`/api/playlist?projectId=${projectId}`)
|
||||||
@@ -215,6 +300,33 @@ export function PlaylistClient({ projects, userRole }: PlaylistClientProps) {
|
|||||||
</Select>
|
</Select>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
{selected.size > 0 && (
|
||||||
|
sequenceMode ? (
|
||||||
|
<Button
|
||||||
|
size="sm"
|
||||||
|
variant="outline"
|
||||||
|
onClick={() => setSequenceMode(false)}
|
||||||
|
className="h-7 text-xs gap-1"
|
||||||
|
>
|
||||||
|
<X className="h-3 w-3" />
|
||||||
|
Exit playlist
|
||||||
|
</Button>
|
||||||
|
) : (
|
||||||
|
<Button
|
||||||
|
size="sm"
|
||||||
|
onClick={() => {
|
||||||
|
reset();
|
||||||
|
setSequenceMode(true);
|
||||||
|
}}
|
||||||
|
className="h-7 text-xs gap-1"
|
||||||
|
title="Play the checked shots back to back: cut only, no slate or handles"
|
||||||
|
>
|
||||||
|
<ListVideo className="h-3.5 w-3.5" />
|
||||||
|
Play selection ({selected.size})
|
||||||
|
</Button>
|
||||||
|
)
|
||||||
|
)}
|
||||||
|
|
||||||
{activeShot && (
|
{activeShot && (
|
||||||
<div className="flex items-center gap-2 ml-auto">
|
<div className="flex items-center gap-2 ml-auto">
|
||||||
<span className="font-mono text-sm text-white">{activeShot.shotCode}</span>
|
<span className="font-mono text-sm text-white">{activeShot.shotCode}</span>
|
||||||
@@ -267,7 +379,9 @@ export function PlaylistClient({ projects, userRole }: PlaylistClientProps) {
|
|||||||
<div className="flex flex-1 min-h-0 overflow-hidden">
|
<div className="flex flex-1 min-h-0 overflow-hidden">
|
||||||
{/* Player */}
|
{/* Player */}
|
||||||
<div className="flex-1 min-w-0 bg-black flex flex-col">
|
<div className="flex-1 min-w-0 bg-black flex flex-col">
|
||||||
{activeShot ? (
|
{sequenceMode && clips.length > 0 ? (
|
||||||
|
<SequencePlayer clips={clips} onClipChange={handleClipChange} />
|
||||||
|
) : activeShot ? (
|
||||||
<ReviewPlayer
|
<ReviewPlayer
|
||||||
key={activeShot.latestVersion.id}
|
key={activeShot.latestVersion.id}
|
||||||
ref={playerRef}
|
ref={playerRef}
|
||||||
@@ -276,6 +390,8 @@ export function PlaylistClient({ projects, userRole }: PlaylistClientProps) {
|
|||||||
fps={activeShot.latestVersion.fps}
|
fps={activeShot.latestVersion.fps}
|
||||||
comments={[]}
|
comments={[]}
|
||||||
annotations={[]}
|
annotations={[]}
|
||||||
|
handles={activeShot.latestVersion}
|
||||||
|
hqVideoUrl={activeShot.latestVersion.hqFileUrl}
|
||||||
/>
|
/>
|
||||||
) : (
|
) : (
|
||||||
<div className="flex-1 flex flex-col items-center justify-center gap-3 text-zinc-600">
|
<div className="flex-1 flex flex-col items-center justify-center gap-3 text-zinc-600">
|
||||||
@@ -297,7 +413,26 @@ export function PlaylistClient({ projects, userRole }: PlaylistClientProps) {
|
|||||||
<div className="px-3 py-2.5 border-b border-border shrink-0 flex items-center justify-between">
|
<div className="px-3 py-2.5 border-b border-border shrink-0 flex items-center justify-between">
|
||||||
<span className="text-xs font-medium text-zinc-400 uppercase tracking-wider">Shots</span>
|
<span className="text-xs font-medium text-zinc-400 uppercase tracking-wider">Shots</span>
|
||||||
{shots.length > 0 && (
|
{shots.length > 0 && (
|
||||||
<span className="text-xs text-zinc-600">{shots.length}</span>
|
<div className="flex items-center gap-2 text-xs">
|
||||||
|
{selected.size > 0 ? (
|
||||||
|
<button
|
||||||
|
onClick={() => updateSelection(new Set())}
|
||||||
|
className="text-zinc-500 hover:text-zinc-200"
|
||||||
|
>
|
||||||
|
Clear
|
||||||
|
</button>
|
||||||
|
) : (
|
||||||
|
<button
|
||||||
|
onClick={() => setGroupChecked(shots, true)}
|
||||||
|
className="text-zinc-500 hover:text-zinc-200"
|
||||||
|
>
|
||||||
|
Select all
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
<span className="text-zinc-600">
|
||||||
|
{selected.size > 0 ? `${selected.size}/${shots.length}` : shots.length}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@@ -320,16 +455,25 @@ export function PlaylistClient({ projects, userRole }: PlaylistClientProps) {
|
|||||||
<div>
|
<div>
|
||||||
{episodeGroups.map(([episode, episodeShots]) => (
|
{episodeGroups.map(([episode, episodeShots]) => (
|
||||||
<div key={episode}>
|
<div key={episode}>
|
||||||
<div className="px-3 py-1.5 bg-zinc-900/80 sticky top-0 z-10 border-b border-zinc-800">
|
<label className="px-3 py-1.5 bg-zinc-900/80 sticky top-0 z-10 border-b border-zinc-800 flex items-center gap-2 cursor-pointer">
|
||||||
|
<input
|
||||||
|
type="checkbox"
|
||||||
|
className="h-3 w-3 accent-blue-500 cursor-pointer"
|
||||||
|
checked={episodeShots.every((s) => selected.has(s.id))}
|
||||||
|
onChange={(e) => setGroupChecked(episodeShots, e.target.checked)}
|
||||||
|
title="Select this episode"
|
||||||
|
/>
|
||||||
<span className="text-[10px] font-semibold text-zinc-500 uppercase tracking-wider">
|
<span className="text-[10px] font-semibold text-zinc-500 uppercase tracking-wider">
|
||||||
Ep {episode}
|
Ep {episode}
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</label>
|
||||||
{episodeShots.map((shot) => (
|
{episodeShots.map((shot) => (
|
||||||
<ShotThumbnail
|
<ShotThumbnail
|
||||||
key={shot.id}
|
key={shot.id}
|
||||||
shot={shot}
|
shot={shot}
|
||||||
isActive={activeShot?.id === shot.id}
|
isActive={activeShot?.id === shot.id}
|
||||||
|
isChecked={selected.has(shot.id)}
|
||||||
|
onToggle={(shift) => toggleChecked(shot, shift)}
|
||||||
onClick={() => handleSelectShot(shot)}
|
onClick={() => handleSelectShot(shot)}
|
||||||
/>
|
/>
|
||||||
))}
|
))}
|
||||||
@@ -343,6 +487,8 @@ export function PlaylistClient({ projects, userRole }: PlaylistClientProps) {
|
|||||||
key={shot.id}
|
key={shot.id}
|
||||||
shot={shot}
|
shot={shot}
|
||||||
isActive={activeShot?.id === shot.id}
|
isActive={activeShot?.id === shot.id}
|
||||||
|
isChecked={selected.has(shot.id)}
|
||||||
|
onToggle={(shift) => toggleChecked(shot, shift)}
|
||||||
onClick={() => handleSelectShot(shot)}
|
onClick={() => handleSelectShot(shot)}
|
||||||
/>
|
/>
|
||||||
))}
|
))}
|
||||||
@@ -358,25 +504,45 @@ export function PlaylistClient({ projects, userRole }: PlaylistClientProps) {
|
|||||||
function ShotThumbnail({
|
function ShotThumbnail({
|
||||||
shot,
|
shot,
|
||||||
isActive,
|
isActive,
|
||||||
|
isChecked,
|
||||||
|
onToggle,
|
||||||
onClick,
|
onClick,
|
||||||
}: {
|
}: {
|
||||||
shot: PlaylistShot;
|
shot: PlaylistShot;
|
||||||
isActive: boolean;
|
isActive: boolean;
|
||||||
|
isChecked: boolean;
|
||||||
|
onToggle: (shift: boolean) => void;
|
||||||
onClick: () => void;
|
onClick: () => void;
|
||||||
}) {
|
}) {
|
||||||
const thumb = shot.latestVersion.thumbnailUrl ?? shot.latestVersion.posterUrl ?? shot.thumbnailUrl;
|
const thumb = shot.latestVersion.thumbnailUrl ?? shot.latestVersion.posterUrl ?? shot.thumbnailUrl;
|
||||||
const ApprovalIcon = APPROVAL_ICONS[shot.latestVersion.approvalStatus] ?? Clock;
|
const ApprovalIcon = APPROVAL_ICONS[shot.latestVersion.approvalStatus] ?? Clock;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<button
|
<div
|
||||||
|
role="button"
|
||||||
|
tabIndex={0}
|
||||||
onClick={onClick}
|
onClick={onClick}
|
||||||
|
onKeyDown={(e) => {
|
||||||
|
if (e.key === "Enter") onClick();
|
||||||
|
}}
|
||||||
className={cn(
|
className={cn(
|
||||||
"w-full flex items-start gap-2.5 px-3 py-2.5 text-left transition-colors border-b border-zinc-800/60 group",
|
"w-full flex items-start gap-2.5 px-3 py-2.5 text-left transition-colors border-b border-zinc-800/60 group cursor-pointer",
|
||||||
isActive
|
isActive
|
||||||
? "bg-blue-500/10 border-l-2 border-l-blue-500"
|
? "bg-blue-500/10 border-l-2 border-l-blue-500"
|
||||||
: "hover:bg-zinc-800/40 border-l-2 border-l-transparent"
|
: "hover:bg-zinc-800/40 border-l-2 border-l-transparent"
|
||||||
)}
|
)}
|
||||||
>
|
>
|
||||||
|
<input
|
||||||
|
type="checkbox"
|
||||||
|
checked={isChecked}
|
||||||
|
onChange={() => {}}
|
||||||
|
onClick={(e) => {
|
||||||
|
e.stopPropagation();
|
||||||
|
onToggle(e.shiftKey);
|
||||||
|
}}
|
||||||
|
className="mt-3 h-3.5 w-3.5 shrink-0 accent-blue-500 cursor-pointer"
|
||||||
|
title="Add to playlist (shift-click for a range)"
|
||||||
|
/>
|
||||||
{/* Thumbnail */}
|
{/* Thumbnail */}
|
||||||
<div className="w-20 aspect-[2.39/1] rounded overflow-hidden bg-zinc-800 shrink-0 flex items-center justify-center">
|
<div className="w-20 aspect-[2.39/1] rounded overflow-hidden bg-zinc-800 shrink-0 flex items-center justify-center">
|
||||||
{thumb ? (
|
{thumb ? (
|
||||||
@@ -408,6 +574,28 @@ function ShotThumbnail({
|
|||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</button>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const selectionKey = (projectId: string) => `playlist:selection:${projectId}`;
|
||||||
|
|
||||||
|
/** The checked shots remembered for this project, minus any no longer listed. */
|
||||||
|
function loadSelection(projectId: string, shots: PlaylistShot[]): Set<string> {
|
||||||
|
try {
|
||||||
|
const ids: unknown = JSON.parse(localStorage.getItem(selectionKey(projectId)) ?? "[]");
|
||||||
|
if (!Array.isArray(ids)) return new Set();
|
||||||
|
const listed = new Set(shots.map((s) => s.id));
|
||||||
|
return new Set(ids.filter((id): id is string => typeof id === "string" && listed.has(id)));
|
||||||
|
} catch {
|
||||||
|
return new Set();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function saveSelection(projectId: string, selected: Set<string>) {
|
||||||
|
try {
|
||||||
|
localStorage.setItem(selectionKey(projectId), JSON.stringify([...selected]));
|
||||||
|
} catch {
|
||||||
|
// Storage unavailable: the selection just isn't remembered.
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -13,6 +13,7 @@ import { TaskCard } from "@/components/tasks/TaskCard";
|
|||||||
import { NewTaskDialog } from "@/components/tasks/NewTaskDialog";
|
import { NewTaskDialog } from "@/components/tasks/NewTaskDialog";
|
||||||
import { KanbanBoard } from "@/components/tasks/KanbanBoard";
|
import { KanbanBoard } from "@/components/tasks/KanbanBoard";
|
||||||
import { cn } from "@/lib/utils";
|
import { cn } from "@/lib/utils";
|
||||||
|
import { sortShotsForList } from "@/lib/shot-order";
|
||||||
import { Film, Package, ListTodo, LayoutDashboard, Plus, Settings, FileUp, ChevronDown, ChevronRight, Calendar, Pencil, Check, X } from "lucide-react";
|
import { Film, Package, ListTodo, LayoutDashboard, Plus, Settings, FileUp, ChevronDown, ChevronRight, Calendar, Pencil, Check, X } from "lucide-react";
|
||||||
import type { ShotWithDetails } from "@/types";
|
import type { ShotWithDetails } from "@/types";
|
||||||
import { ProjectSettingsTab } from "@/components/projects/ProjectSettingsTab";
|
import { ProjectSettingsTab } from "@/components/projects/ProjectSettingsTab";
|
||||||
@@ -64,6 +65,7 @@ interface ProjectTabsClientProps {
|
|||||||
overlayComp?: string | null;
|
overlayComp?: string | null;
|
||||||
previewComp?: string | null;
|
previewComp?: string | null;
|
||||||
lutComp?: string | null;
|
lutComp?: string | null;
|
||||||
|
autoShotThumbnail?: boolean | null;
|
||||||
} | null;
|
} | null;
|
||||||
};
|
};
|
||||||
clients: Client[];
|
clients: Client[];
|
||||||
@@ -146,13 +148,7 @@ export function ProjectTabsClient({
|
|||||||
// For episodic projects: group and sort shots by episode → scene → shotNumber
|
// For episodic projects: group and sort shots by episode → scene → shotNumber
|
||||||
const episodeGroups: [string, ShotWithDetails[]][] = projectType === "EPISODIC"
|
const episodeGroups: [string, ShotWithDetails[]][] = projectType === "EPISODIC"
|
||||||
? (() => {
|
? (() => {
|
||||||
const sorted = [...shots].sort((a, b) => {
|
const sorted = sortShotsForList(shots, projectType);
|
||||||
const ea = a.episode ?? "";
|
|
||||||
const eb = b.episode ?? "";
|
|
||||||
if (ea !== eb) return ea.localeCompare(eb, undefined, { numeric: true });
|
|
||||||
if (a.scene !== b.scene) return a.scene.localeCompare(b.scene, undefined, { numeric: true });
|
|
||||||
return a.shotNumber - b.shotNumber;
|
|
||||||
});
|
|
||||||
const map = new Map<string, ShotWithDetails[]>();
|
const map = new Map<string, ShotWithDetails[]>();
|
||||||
for (const shot of sorted) {
|
for (const shot of sorted) {
|
||||||
const key = shot.episode ?? "(No Episode)";
|
const key = shot.episode ?? "(No Episode)";
|
||||||
@@ -166,13 +162,7 @@ export function ProjectTabsClient({
|
|||||||
// For standard projects: group by custom shot group when any exist
|
// For standard projects: group by custom shot group when any exist
|
||||||
const standardGroups: [string, ShotWithDetails[]][] = projectType === "STANDARD" && shots.some((s) => s.shotGroup)
|
const standardGroups: [string, ShotWithDetails[]][] = projectType === "STANDARD" && shots.some((s) => s.shotGroup)
|
||||||
? (() => {
|
? (() => {
|
||||||
const sorted = [...shots].sort((a, b) => {
|
const sorted = sortShotsForList(shots, projectType);
|
||||||
const ga = a.shotGroup?.name ?? "\uFFFF";
|
|
||||||
const gb = b.shotGroup?.name ?? "\uFFFF";
|
|
||||||
if (ga !== gb) return ga.localeCompare(gb, undefined, { numeric: true });
|
|
||||||
if (a.scene !== b.scene) return a.scene.localeCompare(b.scene, undefined, { numeric: true });
|
|
||||||
return a.shotNumber - b.shotNumber;
|
|
||||||
});
|
|
||||||
const map = new Map<string, ShotWithDetails[]>();
|
const map = new Map<string, ShotWithDetails[]>();
|
||||||
for (const shot of sorted) {
|
for (const shot of sorted) {
|
||||||
const key = shot.shotGroup?.name ?? "(Ungrouped)";
|
const key = shot.shotGroup?.name ?? "(Ungrouped)";
|
||||||
|
|||||||
@@ -41,7 +41,7 @@ export default async function KanbanPage({
|
|||||||
where: { projectId: id },
|
where: { projectId: id },
|
||||||
orderBy: [{ status: "asc" }, { sortOrder: "asc" }],
|
orderBy: [{ status: "asc" }, { sortOrder: "asc" }],
|
||||||
include: {
|
include: {
|
||||||
shot: { select: { id: true, shotCode: true, thumbnailUrl: true } },
|
shot: { select: { id: true, shotCode: true, thumbnailUrl: true, generatedThumbnailUrl: true } },
|
||||||
asset: { select: { id: true, assetCode: true, name: true } },
|
asset: { select: { id: true, assetCode: true, name: true } },
|
||||||
assignedArtist: {
|
assignedArtist: {
|
||||||
select: { id: true, name: true, email: true, image: true },
|
select: { id: true, name: true, email: true, image: true },
|
||||||
@@ -69,7 +69,7 @@ export default async function KanbanPage({
|
|||||||
]);
|
]);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="p-6 space-y-6 max-w-[1800px] mx-auto">
|
<div className="p-4 md:p-6 space-y-6 max-w-[1800px] mx-auto">
|
||||||
{/* Breadcrumb */}
|
{/* Breadcrumb */}
|
||||||
<div className="flex items-center gap-2 text-sm text-muted-foreground">
|
<div className="flex items-center gap-2 text-sm text-muted-foreground">
|
||||||
<Link href="/projects" className="hover:text-foreground transition-colors">
|
<Link href="/projects" className="hover:text-foreground transition-colors">
|
||||||
|
|||||||
@@ -60,7 +60,7 @@ async function getProject(id: string) {
|
|||||||
tasks: {
|
tasks: {
|
||||||
orderBy: [{ status: "asc" }, { sortOrder: "asc" }],
|
orderBy: [{ status: "asc" }, { sortOrder: "asc" }],
|
||||||
include: {
|
include: {
|
||||||
shot: { select: { id: true, shotCode: true, thumbnailUrl: true } },
|
shot: { select: { id: true, shotCode: true, thumbnailUrl: true, generatedThumbnailUrl: true } },
|
||||||
asset: { select: { id: true, assetCode: true, name: true } },
|
asset: { select: { id: true, assetCode: true, name: true } },
|
||||||
assignedArtist: { select: { id: true, name: true, email: true, image: true } },
|
assignedArtist: { select: { id: true, name: true, email: true, image: true } },
|
||||||
_count: { select: { versions: true } },
|
_count: { select: { versions: true } },
|
||||||
@@ -123,7 +123,7 @@ export default async function ProjectPage({ params }: { params: Promise<{ id: st
|
|||||||
const doneTasks = project.tasks.filter((t) => t.status === "DONE").length;
|
const doneTasks = project.tasks.filter((t) => t.status === "DONE").length;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="p-8 space-y-6 max-w-[1600px] mx-auto">
|
<div className="p-4 md:p-8 space-y-6 max-w-[1600px] mx-auto">
|
||||||
{/* Breadcrumb */}
|
{/* Breadcrumb */}
|
||||||
<div className="flex items-center gap-2 text-sm text-zinc-500">
|
<div className="flex items-center gap-2 text-sm text-zinc-500">
|
||||||
<Link href="/projects" className="hover:text-white transition-colors">
|
<Link href="/projects" className="hover:text-white transition-colors">
|
||||||
@@ -207,6 +207,7 @@ export default async function ProjectPage({ params }: { params: Promise<{ id: st
|
|||||||
overlayComp?: string | null;
|
overlayComp?: string | null;
|
||||||
previewComp?: string | null;
|
previewComp?: string | null;
|
||||||
lutComp?: string | null;
|
lutComp?: string | null;
|
||||||
|
autoShotThumbnail?: boolean | null;
|
||||||
} | null,
|
} | null,
|
||||||
}}
|
}}
|
||||||
clients={clients}
|
clients={clients}
|
||||||
|
|||||||
@@ -31,6 +31,8 @@ import {
|
|||||||
Pencil,
|
Pencil,
|
||||||
Check,
|
Check,
|
||||||
LayoutList,
|
LayoutList,
|
||||||
|
ChevronLeft,
|
||||||
|
ChevronRight,
|
||||||
} from "lucide-react";
|
} from "lucide-react";
|
||||||
import { Input } from "@/components/ui/input";
|
import { Input } from "@/components/ui/input";
|
||||||
import type { ShotWithDetails } from "@/types";
|
import type { ShotWithDetails } from "@/types";
|
||||||
@@ -76,6 +78,41 @@ const PRIORITY_CONFIG: Record<string, { label: string; dot: string }> = {
|
|||||||
};
|
};
|
||||||
|
|
||||||
import { useToast } from "@/components/ui/use-toast";
|
import { useToast } from "@/components/ui/use-toast";
|
||||||
|
import { shotThumbnail } from "@/lib/shot-thumbnail";
|
||||||
|
|
||||||
|
type ShotNavTarget = { id: string; shotCode: string } | null;
|
||||||
|
type ShotNav = { prev: ShotNavTarget; next: ShotNavTarget; position: number; total: number };
|
||||||
|
|
||||||
|
function ShotNavLink({
|
||||||
|
projectId,
|
||||||
|
target,
|
||||||
|
direction,
|
||||||
|
}: {
|
||||||
|
projectId: string;
|
||||||
|
target: ShotNavTarget;
|
||||||
|
direction: "prev" | "next";
|
||||||
|
}) {
|
||||||
|
const Icon = direction === "prev" ? ChevronLeft : ChevronRight;
|
||||||
|
const label = direction === "prev" ? "Previous shot" : "Next shot";
|
||||||
|
if (!target) {
|
||||||
|
return (
|
||||||
|
<Button variant="outline" size="sm" disabled className="h-7 gap-1 px-2 font-mono text-xs">
|
||||||
|
{direction === "prev" && <Icon className="h-3.5 w-3.5" />}
|
||||||
|
<span className="hidden sm:inline">{direction === "prev" ? "Prev" : "Next"}</span>
|
||||||
|
{direction === "next" && <Icon className="h-3.5 w-3.5" />}
|
||||||
|
</Button>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return (
|
||||||
|
<Button variant="outline" size="sm" asChild className="h-7 gap-1 px-2 font-mono text-xs">
|
||||||
|
<Link href={`/projects/${projectId}/shots/${target.id}`} title={`${label}: ${target.shotCode}`}>
|
||||||
|
{direction === "prev" && <Icon className="h-3.5 w-3.5" />}
|
||||||
|
<span className="hidden sm:inline max-w-[10rem] truncate">{target.shotCode}</span>
|
||||||
|
{direction === "next" && <Icon className="h-3.5 w-3.5" />}
|
||||||
|
</Link>
|
||||||
|
</Button>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
export default function ShotDetailPage() {
|
export default function ShotDetailPage() {
|
||||||
const params = useParams<{ id: string; shotId: string }>();
|
const params = useParams<{ id: string; shotId: string }>();
|
||||||
@@ -83,6 +120,7 @@ export default function ShotDetailPage() {
|
|||||||
const { toast } = useToast();
|
const { toast } = useToast();
|
||||||
const [shot, setShot] = useState<ShotWithDetails | null>(null);
|
const [shot, setShot] = useState<ShotWithDetails | null>(null);
|
||||||
const [projectName, setProjectName] = useState<string>("");
|
const [projectName, setProjectName] = useState<string>("");
|
||||||
|
const [shotNav, setShotNav] = useState<ShotNav | null>(null);
|
||||||
const [loading, setLoading] = useState(true);
|
const [loading, setLoading] = useState(true);
|
||||||
const [canApprove, setCanApprove] = useState(false);
|
const [canApprove, setCanApprove] = useState(false);
|
||||||
const [canInternallyApprove, setCanInternallyApprove] = useState(false);
|
const [canInternallyApprove, setCanInternallyApprove] = useState(false);
|
||||||
@@ -107,6 +145,7 @@ export default function ShotDetailPage() {
|
|||||||
const data = await res.json();
|
const data = await res.json();
|
||||||
setShot(data.shot);
|
setShot(data.shot);
|
||||||
setProjectName(data.projectName ?? "");
|
setProjectName(data.projectName ?? "");
|
||||||
|
setShotNav(data.shotNav ?? null);
|
||||||
setCanApprove(data.canApprove ?? false);
|
setCanApprove(data.canApprove ?? false);
|
||||||
setCanInternallyApprove(data.canInternallyApprove ?? false);
|
setCanInternallyApprove(data.canInternallyApprove ?? false);
|
||||||
setTasks(data.tasks ?? []);
|
setTasks(data.tasks ?? []);
|
||||||
@@ -229,7 +268,7 @@ export default function ShotDetailPage() {
|
|||||||
const { Icon: StatusIcon } = statusCfg;
|
const { Icon: StatusIcon } = statusCfg;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="p-6 space-y-6 max-w-[1400px] mx-auto">
|
<div className="p-4 md:p-6 space-y-6 max-w-[1400px] mx-auto">
|
||||||
{/* Breadcrumb */}
|
{/* Breadcrumb */}
|
||||||
<div className="flex items-center gap-2 text-sm text-muted-foreground">
|
<div className="flex items-center gap-2 text-sm text-muted-foreground">
|
||||||
<Link href="/projects" className="hover:text-foreground transition-colors">
|
<Link href="/projects" className="hover:text-foreground transition-colors">
|
||||||
@@ -241,31 +280,44 @@ export default function ShotDetailPage() {
|
|||||||
</Link>
|
</Link>
|
||||||
<span>/</span>
|
<span>/</span>
|
||||||
<span className="text-foreground font-mono">{shot.shotCode}</span>
|
<span className="text-foreground font-mono">{shot.shotCode}</span>
|
||||||
|
|
||||||
|
{/* Prev / next shot, in the project page's list order */}
|
||||||
|
{shotNav && shotNav.total > 1 && (
|
||||||
|
<div className="ml-auto flex items-center gap-1">
|
||||||
|
<ShotNavLink projectId={params.id} target={shotNav.prev} direction="prev" />
|
||||||
|
<span className="px-1 text-xs tabular-nums">
|
||||||
|
{shotNav.position} / {shotNav.total}
|
||||||
|
</span>
|
||||||
|
<ShotNavLink projectId={params.id} target={shotNav.next} direction="next" />
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Header */}
|
{/* Header */}
|
||||||
<div className="flex items-start gap-6">
|
{/* Phones: back button, then a full-width thumbnail, then the details
|
||||||
|
below it. From md: one row, as on desktop. */}
|
||||||
|
<div className="flex flex-wrap md:flex-nowrap items-start gap-4 md:gap-6">
|
||||||
{/* Thumbnail – cinema scope 2.39:1 */}
|
{/* Thumbnail – cinema scope 2.39:1 */}
|
||||||
<Button variant="ghost" size="icon" asChild className="-ml-2 h-8 w-8">
|
<Button variant="ghost" size="icon" asChild className="-ml-2 h-8 w-8">
|
||||||
<Link href={`/projects/${params.id}`}>
|
<Link href={`/projects/${params.id}`}>
|
||||||
<ArrowLeft className="h-4 w-4" />
|
<ArrowLeft className="h-4 w-4" />
|
||||||
</Link>
|
</Link>
|
||||||
</Button>
|
</Button>
|
||||||
{shot.thumbnailUrl && (
|
{shotThumbnail(shot) && (
|
||||||
<div className="relative flex-shrink-0 w-72 aspect-[2.39] rounded-lg overflow-hidden border border-border">
|
<div className="relative flex-shrink-0 w-full md:w-72 aspect-[2.39] rounded-lg overflow-hidden border border-border">
|
||||||
|
|
||||||
<Image
|
<Image
|
||||||
src={shot.thumbnailUrl}
|
src={shotThumbnail(shot)!}
|
||||||
alt={shot.shotCode}
|
alt={shot.shotCode}
|
||||||
fill
|
fill
|
||||||
className="object-cover"
|
className="object-cover"
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
<div className="space-y-2">
|
<div className="space-y-2 min-w-0 w-full md:w-auto md:min-w-min">
|
||||||
<div className="flex items-center gap-3">
|
<div className="flex flex-wrap items-center gap-3">
|
||||||
|
|
||||||
<h1 className="text-2xl font-bold font-mono">{shot.shotCode}</h1>
|
<h1 className="text-2xl font-bold font-mono break-all md:break-normal">{shot.shotCode}</h1>
|
||||||
|
|
||||||
{/* Shot version badge — click to edit for managers */}
|
{/* Shot version badge — click to edit for managers */}
|
||||||
{canManage ? (
|
{canManage ? (
|
||||||
@@ -423,7 +475,7 @@ export default function ShotDetailPage() {
|
|||||||
)}
|
)}
|
||||||
|
|
||||||
{canManage && (
|
{canManage && (
|
||||||
<div className="ml-auto shrink-0 flex items-center gap-2">
|
<div className="ml-auto shrink-0 flex flex-wrap md:flex-nowrap items-center gap-2 w-full md:w-auto">
|
||||||
{/* Internal approval action */}
|
{/* Internal approval action */}
|
||||||
{canInternallyApprove && shot.shotApprovalStatus === "PENDING" && (
|
{canInternallyApprove && shot.shotApprovalStatus === "PENDING" && (
|
||||||
<Button
|
<Button
|
||||||
@@ -509,7 +561,8 @@ export default function ShotDetailPage() {
|
|||||||
|
|
||||||
{/* Tabs */}
|
{/* Tabs */}
|
||||||
<div>
|
<div>
|
||||||
<div className="flex border-b border-border mb-5">
|
{/* Phones: five tabs are wider than the screen, so the bar scrolls sideways. */}
|
||||||
|
<div className="flex border-b border-border mb-5 overflow-x-auto overflow-y-hidden md:overflow-visible [&>button]:shrink-0 [&>button]:whitespace-nowrap">
|
||||||
<button
|
<button
|
||||||
onClick={() => setActiveTab("tasks")}
|
onClick={() => setActiveTab("tasks")}
|
||||||
className={cn(
|
className={cn(
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import { useState, useEffect } from "react";
|
import { useState, useEffect, useRef } from "react";
|
||||||
import { useQuery } from "@tanstack/react-query";
|
import { useQuery } from "@tanstack/react-query";
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
import { Input } from "@/components/ui/input";
|
import { Input } from "@/components/ui/input";
|
||||||
@@ -8,6 +8,7 @@ import { ProjectCard } from "@/components/projects/ProjectCard";
|
|||||||
import { NewProjectDialog } from "@/components/projects/NewProjectDialog";
|
import { NewProjectDialog } from "@/components/projects/NewProjectDialog";
|
||||||
import { Plus, Search, Loader2 } from "lucide-react";
|
import { Plus, Search, Loader2 } from "lucide-react";
|
||||||
import { HIDE_ARCHIVED_KEY } from "@/components/settings/HideArchivedToggle";
|
import { HIDE_ARCHIVED_KEY } from "@/components/settings/HideArchivedToggle";
|
||||||
|
import { useScrollMemory } from "@/hooks/use-scroll-memory";
|
||||||
|
|
||||||
export default function ProjectsPage() {
|
export default function ProjectsPage() {
|
||||||
const [search, setSearch] = useState("");
|
const [search, setSearch] = useState("");
|
||||||
@@ -43,22 +44,11 @@ export default function ProjectsPage() {
|
|||||||
|
|
||||||
const visibleProjects = hideArchived ? projects.filter((p: any) => p.status !== "ARCHIVED") : projects;
|
const visibleProjects = hideArchived ? projects.filter((p: any) => p.status !== "ARCHIVED") : projects;
|
||||||
|
|
||||||
const SCROLL_KEY = 'projects-scroll';
|
const pageRef = useRef<HTMLDivElement>(null);
|
||||||
|
useScrollMemory("projects", pageRef, !isLoading);
|
||||||
useEffect(() => {
|
|
||||||
if (!isLoading) {
|
|
||||||
const saved = sessionStorage.getItem(SCROLL_KEY);
|
|
||||||
if (saved) {
|
|
||||||
sessionStorage.removeItem(SCROLL_KEY);
|
|
||||||
requestAnimationFrame(() => window.scrollTo(0, parseInt(saved, 10)));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}, [isLoading]);
|
|
||||||
|
|
||||||
const saveScroll = () => sessionStorage.setItem(SCROLL_KEY, String(window.scrollY));
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="p-8 space-y-6 max-w-[1600px] mx-auto">
|
<div ref={pageRef} className="p-4 md:p-8 space-y-6 max-w-[1600px] mx-auto">
|
||||||
<div className="flex items-center justify-between gap-4 mb-8">
|
<div className="flex items-center justify-between gap-4 mb-8">
|
||||||
<div>
|
<div>
|
||||||
<h1 className="text-3xl font-bold text-white">Projects</h1>
|
<h1 className="text-3xl font-bold text-white">Projects</h1>
|
||||||
@@ -104,9 +94,11 @@ export default function ProjectsPage() {
|
|||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
) : (
|
) : (
|
||||||
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4">
|
// auto-rows-fr keeps every row the same height, so a project with a
|
||||||
|
// long description does not make its whole row taller than the rest.
|
||||||
|
<div className="grid auto-rows-fr grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4">
|
||||||
{visibleProjects.map((project: any) => (
|
{visibleProjects.map((project: any) => (
|
||||||
<div key={project.id} onClick={saveScroll}>
|
<div key={project.id} className="h-full">
|
||||||
<ProjectCard project={project} />
|
<ProjectCard project={project} />
|
||||||
</div>
|
</div>
|
||||||
))}
|
))}
|
||||||
|
|||||||
@@ -53,7 +53,12 @@ export interface ScheduleTask {
|
|||||||
email: string;
|
email: string;
|
||||||
image: string | null;
|
image: string | null;
|
||||||
} | null;
|
} | null;
|
||||||
shot: { id: string; shotCode: string; thumbnailUrl: string | null } | null;
|
shot: {
|
||||||
|
id: string;
|
||||||
|
shotCode: string;
|
||||||
|
thumbnailUrl: string | null;
|
||||||
|
generatedThumbnailUrl: string | null;
|
||||||
|
} | null;
|
||||||
asset: { id: string; assetCode: string; name: string } | null;
|
asset: { id: string; assetCode: string; name: string } | null;
|
||||||
project: { id: string; name: string; code: string };
|
project: { id: string; name: string; code: string };
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -31,7 +31,7 @@ export default async function SchedulePage({
|
|||||||
...(artist ? { assignedArtistId: artist } : {}),
|
...(artist ? { assignedArtistId: artist } : {}),
|
||||||
},
|
},
|
||||||
include: {
|
include: {
|
||||||
shot: { select: { id: true, shotCode: true, thumbnailUrl: true } },
|
shot: { select: { id: true, shotCode: true, thumbnailUrl: true, generatedThumbnailUrl: true } },
|
||||||
asset: { select: { id: true, assetCode: true, name: true } },
|
asset: { select: { id: true, assetCode: true, name: true } },
|
||||||
project: { select: { id: true, name: true, code: true } },
|
project: { select: { id: true, name: true, code: true } },
|
||||||
assignedArtist: {
|
assignedArtist: {
|
||||||
@@ -49,7 +49,7 @@ export default async function SchedulePage({
|
|||||||
...(artist ? { assignedArtistId: artist } : {}),
|
...(artist ? { assignedArtistId: artist } : {}),
|
||||||
},
|
},
|
||||||
include: {
|
include: {
|
||||||
shot: { select: { id: true, shotCode: true, thumbnailUrl: true } },
|
shot: { select: { id: true, shotCode: true, thumbnailUrl: true, generatedThumbnailUrl: true } },
|
||||||
asset: { select: { id: true, assetCode: true, name: true } },
|
asset: { select: { id: true, assetCode: true, name: true } },
|
||||||
project: { select: { id: true, name: true, code: true } },
|
project: { select: { id: true, name: true, code: true } },
|
||||||
assignedArtist: {
|
assignedArtist: {
|
||||||
|
|||||||
@@ -186,7 +186,7 @@ export default function MigrationPage() {
|
|||||||
|
|
||||||
if (fetchError) {
|
if (fetchError) {
|
||||||
return (
|
return (
|
||||||
<div className="p-6 max-w-2xl">
|
<div className="p-4 md:p-6 max-w-2xl">
|
||||||
<div className="flex items-center gap-2 text-sm text-red-400 rounded-md border border-red-500/20 bg-red-500/10 px-3 py-2">
|
<div className="flex items-center gap-2 text-sm text-red-400 rounded-md border border-red-500/20 bg-red-500/10 px-3 py-2">
|
||||||
<AlertCircle className="h-4 w-4 shrink-0" />
|
<AlertCircle className="h-4 w-4 shrink-0" />
|
||||||
{fetchError}
|
{fetchError}
|
||||||
@@ -200,7 +200,7 @@ export default function MigrationPage() {
|
|||||||
|
|
||||||
if (!hetznerConfigured) {
|
if (!hetznerConfigured) {
|
||||||
return (
|
return (
|
||||||
<div className="p-6 max-w-2xl">
|
<div className="p-4 md:p-6 max-w-2xl">
|
||||||
<div className="flex items-center gap-2 text-sm text-amber-400 rounded-md border border-amber-500/20 bg-amber-500/10 px-3 py-2">
|
<div className="flex items-center gap-2 text-sm text-amber-400 rounded-md border border-amber-500/20 bg-amber-500/10 px-3 py-2">
|
||||||
<AlertCircle className="h-4 w-4 shrink-0" />
|
<AlertCircle className="h-4 w-4 shrink-0" />
|
||||||
Hetzner object storage is not configured. Set{" "}
|
Hetzner object storage is not configured. Set{" "}
|
||||||
@@ -217,7 +217,7 @@ export default function MigrationPage() {
|
|||||||
const allFilteredSelected = filtered.length > 0 && filtered.every((f) => selected.has(f.key));
|
const allFilteredSelected = filtered.length > 0 && filtered.every((f) => selected.has(f.key));
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="p-6 space-y-4 max-w-5xl">
|
<div className="p-4 md:p-6 space-y-4 max-w-5xl">
|
||||||
{/* Header */}
|
{/* Header */}
|
||||||
<div className="flex items-start justify-between gap-4">
|
<div className="flex items-start justify-between gap-4">
|
||||||
<div>
|
<div>
|
||||||
|
|||||||
@@ -19,7 +19,7 @@ export default async function SettingsPage() {
|
|||||||
const hetznerConfig = isAdmin ? await getHetznerConfig() : null;
|
const hetznerConfig = isAdmin ? await getHetznerConfig() : null;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="p-6 space-y-6 max-w-2xl mx-auto">
|
<div className="p-4 md:p-6 space-y-6 max-w-2xl mx-auto">
|
||||||
<h1 className="text-2xl font-bold">Account Settings</h1>
|
<h1 className="text-2xl font-bold">Account Settings</h1>
|
||||||
|
|
||||||
<Card>
|
<Card>
|
||||||
|
|||||||
@@ -72,7 +72,7 @@ export default function StorageTestPage() {
|
|||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="p-6 max-w-3xl space-y-6">
|
<div className="p-4 md:p-6 max-w-3xl space-y-6">
|
||||||
<div>
|
<div>
|
||||||
<h1 className="text-xl font-semibold">Object Storage Playback Test</h1>
|
<h1 className="text-xl font-semibold">Object Storage Playback Test</h1>
|
||||||
<p className="text-sm text-muted-foreground mt-1">
|
<p className="text-sm text-muted-foreground mt-1">
|
||||||
|
|||||||
@@ -0,0 +1,146 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useState, useTransition } from "react";
|
||||||
|
import Link from "next/link";
|
||||||
|
import * as Popover from "@radix-ui/react-popover";
|
||||||
|
import { formatDistanceToNow } from "date-fns";
|
||||||
|
import { AlertCircle, Check, Loader2, MessageSquareReply } from "lucide-react";
|
||||||
|
import { listUnreadShotComments, markShotCommentsRead } from "@/actions/comment-reads";
|
||||||
|
import type { UnreadCommentItem } from "@/lib/comment-reads";
|
||||||
|
import { useToast } from "@/components/ui/use-toast";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The "!" beside a shot code while it has comments this user has not marked
|
||||||
|
* read. Opening it lists them; they stay flagged until "Mark read" is clicked —
|
||||||
|
* opening the list or the shot is not enough.
|
||||||
|
*/
|
||||||
|
export function NewCommentsMarker({
|
||||||
|
shotId,
|
||||||
|
shotCode,
|
||||||
|
count,
|
||||||
|
latestAt,
|
||||||
|
onRead,
|
||||||
|
}: {
|
||||||
|
shotId: string;
|
||||||
|
shotCode: string;
|
||||||
|
count: number;
|
||||||
|
latestAt: string;
|
||||||
|
onRead: (shotId: string) => void;
|
||||||
|
}) {
|
||||||
|
const { toast } = useToast();
|
||||||
|
const [open, setOpen] = useState(false);
|
||||||
|
const [items, setItems] = useState<UnreadCommentItem[] | null>(null);
|
||||||
|
const [loadError, setLoadError] = useState(false);
|
||||||
|
const [marking, startMarking] = useTransition();
|
||||||
|
|
||||||
|
const load = async () => {
|
||||||
|
setLoadError(false);
|
||||||
|
try {
|
||||||
|
setItems(await listUnreadShotComments(shotId));
|
||||||
|
} catch {
|
||||||
|
setLoadError(true);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const markRead = () =>
|
||||||
|
startMarking(async () => {
|
||||||
|
// Read up to what was listed; with the list not loaded, up to what the
|
||||||
|
// board showed. Anything newer stays flagged.
|
||||||
|
const upTo = items?.[0]?.createdAt ?? latestAt;
|
||||||
|
try {
|
||||||
|
await markShotCommentsRead(shotId, upTo);
|
||||||
|
setOpen(false);
|
||||||
|
onRead(shotId);
|
||||||
|
} catch {
|
||||||
|
toast({ title: "Could not mark comments read", variant: "destructive" });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Popover.Root
|
||||||
|
open={open}
|
||||||
|
onOpenChange={(next) => {
|
||||||
|
setOpen(next);
|
||||||
|
if (next) load();
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Popover.Trigger asChild>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
title={`${count} new comment${count !== 1 ? "s" : ""} on ${shotCode}`}
|
||||||
|
aria-label={`${count} new comment${count !== 1 ? "s" : ""} on ${shotCode}`}
|
||||||
|
className="flex items-center justify-center h-4 min-w-4 rounded-full bg-orange-500 px-1 text-[10px] font-bold leading-none text-white hover:bg-orange-400 shrink-0"
|
||||||
|
>
|
||||||
|
!{count > 1 && <span className="ml-0.5 font-medium">{count}</span>}
|
||||||
|
</button>
|
||||||
|
</Popover.Trigger>
|
||||||
|
<Popover.Portal>
|
||||||
|
<Popover.Content
|
||||||
|
align="start"
|
||||||
|
sideOffset={6}
|
||||||
|
className="z-50 w-96 rounded-lg border border-zinc-700 bg-zinc-900 shadow-xl"
|
||||||
|
>
|
||||||
|
<div className="flex items-center justify-between border-b border-zinc-800 px-3 py-2">
|
||||||
|
<span className="text-xs font-medium text-zinc-300">
|
||||||
|
New on <span className="font-mono text-white">{shotCode}</span>
|
||||||
|
</span>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={markRead}
|
||||||
|
disabled={marking}
|
||||||
|
className="flex items-center gap-1 rounded border border-zinc-700 px-2 py-1 text-xs text-zinc-200 hover:bg-zinc-800 disabled:opacity-50"
|
||||||
|
>
|
||||||
|
{marking ? <Loader2 className="h-3 w-3 animate-spin" /> : <Check className="h-3 w-3" />}
|
||||||
|
Mark read
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
<div className="max-h-80 overflow-y-auto">
|
||||||
|
{loadError ? (
|
||||||
|
<p className="flex items-center gap-1.5 px-3 py-4 text-xs text-red-400">
|
||||||
|
<AlertCircle className="h-3.5 w-3.5" />
|
||||||
|
Could not load the comments.
|
||||||
|
</p>
|
||||||
|
) : items === null ? (
|
||||||
|
<p className="flex items-center gap-1.5 px-3 py-4 text-xs text-zinc-500">
|
||||||
|
<Loader2 className="h-3.5 w-3.5 animate-spin" />
|
||||||
|
Loading…
|
||||||
|
</p>
|
||||||
|
) : items.length === 0 ? (
|
||||||
|
<p className="px-3 py-4 text-xs text-zinc-500">
|
||||||
|
Nothing new — the comments may have been deleted.
|
||||||
|
</p>
|
||||||
|
) : (
|
||||||
|
<ul className="divide-y divide-zinc-800">
|
||||||
|
{items.map((item) => (
|
||||||
|
<li key={`${item.kind}-${item.id}`}>
|
||||||
|
<Link
|
||||||
|
href={`/review/${item.versionId}`}
|
||||||
|
className="block px-3 py-2 hover:bg-zinc-800/60"
|
||||||
|
>
|
||||||
|
<div className="flex items-center gap-1.5 text-[11px] text-zinc-500">
|
||||||
|
{item.kind === "reply" && <MessageSquareReply className="h-3 w-3" />}
|
||||||
|
<span className="text-zinc-300">{item.authorName}</span>
|
||||||
|
{item.source === "WHATSAPP" && (
|
||||||
|
<span className="rounded bg-green-500/15 px-1 text-green-400">client</span>
|
||||||
|
)}
|
||||||
|
<span className="font-mono">
|
||||||
|
v{String(item.versionNumber).padStart(3, "0")} · f{item.frameNumber}
|
||||||
|
</span>
|
||||||
|
<span className="ml-auto">
|
||||||
|
{formatDistanceToNow(new Date(item.createdAt), { addSuffix: true })}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<p className="mt-0.5 line-clamp-3 whitespace-pre-line text-xs text-zinc-200">
|
||||||
|
{item.text}
|
||||||
|
</p>
|
||||||
|
</Link>
|
||||||
|
</li>
|
||||||
|
))}
|
||||||
|
</ul>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</Popover.Content>
|
||||||
|
</Popover.Portal>
|
||||||
|
</Popover.Root>
|
||||||
|
);
|
||||||
|
}
|
||||||
File diff suppressed because it is too large
Load Diff
@@ -2,6 +2,8 @@ import { db } from "@/lib/db";
|
|||||||
import { auth } from "@/auth";
|
import { auth } from "@/auth";
|
||||||
import { redirect } from "next/navigation";
|
import { redirect } from "next/navigation";
|
||||||
import { ShotStatusClient } from "./ShotStatusClient";
|
import { ShotStatusClient } from "./ShotStatusClient";
|
||||||
|
import { summariseShotDelivery } from "@/lib/render-pipeline/shot-delivery-summary";
|
||||||
|
import { getUnreadCommentSummaries, type UnreadCommentSummary } from "@/lib/comment-reads";
|
||||||
|
|
||||||
async function getProjects() {
|
async function getProjects() {
|
||||||
return db.project.findMany({
|
return db.project.findMany({
|
||||||
@@ -19,14 +21,20 @@ 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" },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const shotCodeCollator = new Intl.Collator(undefined, { numeric: true, sensitivity: "base" });
|
||||||
|
|
||||||
async function getShotsForProject(projectId: string) {
|
async function getShotsForProject(projectId: string) {
|
||||||
return db.shot.findMany({
|
const shots = await db.shot.findMany({
|
||||||
where: { projectId },
|
where: { projectId },
|
||||||
orderBy: [
|
|
||||||
{ episode: { sort: "asc", nulls: "last" } },
|
|
||||||
{ scene: "asc" },
|
|
||||||
{ shotNumber: "asc" },
|
|
||||||
],
|
|
||||||
select: {
|
select: {
|
||||||
id: true,
|
id: true,
|
||||||
shotCode: true,
|
shotCode: true,
|
||||||
@@ -37,13 +45,72 @@ async function getShotsForProject(projectId: string) {
|
|||||||
priority: true,
|
priority: true,
|
||||||
dueDate: true,
|
dueDate: true,
|
||||||
thumbnailUrl: true,
|
thumbnailUrl: true,
|
||||||
|
generatedThumbnailUrl: true,
|
||||||
notes: true,
|
notes: true,
|
||||||
description: true,
|
description: true,
|
||||||
isKeyShot: true,
|
isKeyShot: true,
|
||||||
|
isScaled: true,
|
||||||
|
manualDeliveredAt: true,
|
||||||
|
manualDeliveryNote: true,
|
||||||
|
manualDeliverySharedWith: true,
|
||||||
|
// The shot-level version the panel burns into overlays and queueExport
|
||||||
|
// renders under — not the count of review Versions uploaded.
|
||||||
|
shotVersion: true,
|
||||||
artist: { select: { id: true, name: true, image: true, email: true } },
|
artist: { select: { id: true, name: true, image: true, email: true } },
|
||||||
shotGroup: { select: { id: true, name: true } },
|
shotGroup: { select: { id: true, name: true } },
|
||||||
|
// Every export, for the packages each went into; the newest live one
|
||||||
|
// is what is on its way.
|
||||||
|
exports: {
|
||||||
|
orderBy: [{ versionNumber: "desc" }, { createdAt: "desc" }],
|
||||||
|
select: {
|
||||||
|
versionString: true,
|
||||||
|
status: true,
|
||||||
|
deliveryItems: {
|
||||||
|
select: {
|
||||||
|
versionString: true,
|
||||||
|
package: {
|
||||||
|
select: {
|
||||||
|
kind: true,
|
||||||
|
status: true,
|
||||||
|
packageNumber: true,
|
||||||
|
createdAt: true,
|
||||||
|
builtAt: true,
|
||||||
|
uploadedAt: true,
|
||||||
|
deliveredAt: true,
|
||||||
|
sharedWith: true,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// Sorted by shot code rather than scene + shotNumber: imports and the
|
||||||
|
// external API assign shotNumber as "max + 10" (or 0), which needn't match
|
||||||
|
// the number in the code, so new shots could sink to the bottom.
|
||||||
|
shots.sort(
|
||||||
|
(a, b) =>
|
||||||
|
(a.episode === null ? 1 : 0) - (b.episode === null ? 1 : 0) ||
|
||||||
|
shotCodeCollator.compare(a.episode ?? "", b.episode ?? "") ||
|
||||||
|
shotCodeCollator.compare(a.shotCode, b.shotCode)
|
||||||
|
);
|
||||||
|
|
||||||
|
return shots.map(({ exports, ...shot }) => ({
|
||||||
|
...shot,
|
||||||
|
delivery: summariseShotDelivery({
|
||||||
|
packages: exports.flatMap((e) =>
|
||||||
|
e.deliveryItems.map((item) => ({ ...item.package, versionString: item.versionString }))
|
||||||
|
),
|
||||||
|
manual: {
|
||||||
|
deliveredAt: shot.manualDeliveredAt,
|
||||||
|
sharedWith: shot.manualDeliverySharedWith,
|
||||||
|
note: shot.manualDeliveryNote,
|
||||||
|
},
|
||||||
|
latestExport: exports.find((e) => e.status !== "CANCELLED" && e.status !== "ARCHIVED") ?? null,
|
||||||
|
}),
|
||||||
|
}));
|
||||||
}
|
}
|
||||||
|
|
||||||
export default async function ShotStatusPage({
|
export default async function ShotStatusPage({
|
||||||
@@ -57,11 +124,14 @@ export default async function ShotStatusPage({
|
|||||||
const { projectId } = await searchParams;
|
const { projectId } = await searchParams;
|
||||||
const canManage = ["ADMIN", "PRODUCER", "SUPERVISOR"].includes(session.user.role);
|
const canManage = ["ADMIN", "PRODUCER", "SUPERVISOR"].includes(session.user.role);
|
||||||
|
|
||||||
const [projects, shots, episodeDueDates] = await Promise.all([
|
const [projects, shotRows, episodeDueDates, artists, unread] = await Promise.all([
|
||||||
getProjects(),
|
getProjects(),
|
||||||
projectId ? getShotsForProject(projectId) : Promise.resolve([]),
|
projectId ? getShotsForProject(projectId) : Promise.resolve([]),
|
||||||
projectId ? getEpisodeDueDatesForProject(projectId) : Promise.resolve([]),
|
projectId ? getEpisodeDueDatesForProject(projectId) : Promise.resolve([]),
|
||||||
|
canManage ? getAssignableArtists() : Promise.resolve([]),
|
||||||
|
projectId ? getUnreadCommentSummaries(session.user.id, projectId) : Promise.resolve({} as Record<string, UnreadCommentSummary>),
|
||||||
]);
|
]);
|
||||||
|
const shots = shotRows.map((shot) => ({ ...shot, unreadComments: unread[shot.id] ?? null }));
|
||||||
|
|
||||||
const selectedProject = projects.find((p) => p.id === projectId) ?? null;
|
const selectedProject = projects.find((p) => p.id === projectId) ?? null;
|
||||||
|
|
||||||
@@ -72,6 +142,7 @@ export default async function ShotStatusPage({
|
|||||||
selectedProject={selectedProject}
|
selectedProject={selectedProject}
|
||||||
shots={shots as any}
|
shots={shots as any}
|
||||||
episodeDueDates={episodeDueDates}
|
episodeDueDates={episodeDueDates}
|
||||||
|
artists={artists}
|
||||||
canManage={canManage}
|
canManage={canManage}
|
||||||
/>
|
/>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -110,7 +110,7 @@ export function TasksPageClient({
|
|||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="p-6 max-w-5xl mx-auto space-y-6">
|
<div className="p-4 md:p-6 max-w-5xl mx-auto space-y-6">
|
||||||
{/* Header */}
|
{/* Header */}
|
||||||
<div className="flex items-center justify-between">
|
<div className="flex items-center justify-between">
|
||||||
<div>
|
<div>
|
||||||
|
|||||||
@@ -32,7 +32,7 @@ export default async function UsersPage() {
|
|||||||
}));
|
}));
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="p-6 max-w-5xl mx-auto space-y-6">
|
<div className="p-4 md:p-6 max-w-5xl mx-auto space-y-6">
|
||||||
<div className="flex items-center gap-3">
|
<div className="flex items-center gap-3">
|
||||||
<div className="w-10 h-10 rounded-lg bg-amber-500/10 border border-amber-500/20 flex items-center justify-center shrink-0">
|
<div className="w-10 h-10 rounded-lg bg-amber-500/10 border border-amber-500/20 flex items-center justify-center shrink-0">
|
||||||
<Users className="h-5 w-5 text-amber-400" />
|
<Users className="h-5 w-5 text-amber-400" />
|
||||||
|
|||||||
@@ -0,0 +1,124 @@
|
|||||||
|
import { NextRequest, NextResponse } from "next/server";
|
||||||
|
import { auth } from "@/auth";
|
||||||
|
import { db } from "@/lib/db";
|
||||||
|
import { PLATE_EXTS, parsePlateFilename } from "@/lib/batch-upload-parser";
|
||||||
|
|
||||||
|
export type PlatePreviewItemStatus =
|
||||||
|
| "match" // shot found → a new footage plate will be added
|
||||||
|
| "duplicate" // the shot already has a plate with this exact filename
|
||||||
|
| "no-match" // no shot in this project matches the filename
|
||||||
|
| "unsupported"; // extension is not an accepted video format
|
||||||
|
|
||||||
|
export interface PlatePreviewItem {
|
||||||
|
fileName: string;
|
||||||
|
shotCode: string | null;
|
||||||
|
shotId: string | null;
|
||||||
|
/** Label the new plate will be created with */
|
||||||
|
label: string;
|
||||||
|
status: PlatePreviewItemStatus;
|
||||||
|
/** Number of plates the matched shot already has */
|
||||||
|
existingPlateCount: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* POST /api/batch-upload/plates
|
||||||
|
* Body: { projectId: string; fileNames: string[] }
|
||||||
|
*
|
||||||
|
* Previews which shot each footage plate file will be attached to, derived
|
||||||
|
* from the filename. e.g. "DH2_VFX_058_120_REF.mov" → shot "DH2_VFX_058_120"
|
||||||
|
* with the label "REF". Nothing is uploaded.
|
||||||
|
*/
|
||||||
|
export async function POST(req: NextRequest) {
|
||||||
|
const session = await auth();
|
||||||
|
if (!session?.user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
|
||||||
|
|
||||||
|
let body: unknown;
|
||||||
|
try {
|
||||||
|
body = await req.json();
|
||||||
|
} catch {
|
||||||
|
return NextResponse.json({ error: "Invalid JSON" }, { status: 400 });
|
||||||
|
}
|
||||||
|
|
||||||
|
const { projectId, fileNames } = body as { projectId?: unknown; fileNames?: unknown };
|
||||||
|
|
||||||
|
if (!projectId || typeof projectId !== "string" || !Array.isArray(fileNames)) {
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: "projectId and fileNames[] are required" },
|
||||||
|
{ status: 400 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const shots = await db.shot.findMany({
|
||||||
|
where: { projectId },
|
||||||
|
select: {
|
||||||
|
id: true,
|
||||||
|
shotCode: true,
|
||||||
|
footagePlates: { select: { fileName: true } },
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const shotCodes = shots.map((s) => s.shotCode);
|
||||||
|
const shotByCode = new Map(shots.map((s) => [s.shotCode, s]));
|
||||||
|
|
||||||
|
// Several files in one batch can land on the same shot, so keep a running
|
||||||
|
// count per shot to number the "Plate N" fallback labels correctly.
|
||||||
|
const allocated = new Map<string, number>();
|
||||||
|
|
||||||
|
const items: PlatePreviewItem[] = fileNames.map((fileName: string) => {
|
||||||
|
const parsed = parsePlateFilename(fileName, shotCodes);
|
||||||
|
|
||||||
|
if (!PLATE_EXTS.has(parsed.ext)) {
|
||||||
|
return {
|
||||||
|
fileName,
|
||||||
|
shotCode: null,
|
||||||
|
shotId: null,
|
||||||
|
label: "",
|
||||||
|
status: "unsupported" as const,
|
||||||
|
existingPlateCount: 0,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const shot = parsed.shotCode ? shotByCode.get(parsed.shotCode) ?? null : null;
|
||||||
|
if (!shot) {
|
||||||
|
return {
|
||||||
|
fileName,
|
||||||
|
shotCode: null,
|
||||||
|
shotId: null,
|
||||||
|
label: "",
|
||||||
|
status: "no-match" as const,
|
||||||
|
existingPlateCount: 0,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const existingPlateCount = shot.footagePlates.length;
|
||||||
|
|
||||||
|
// Re-running a batch shouldn't silently pile up identical plates.
|
||||||
|
const isDuplicate = shot.footagePlates.some(
|
||||||
|
(p) => p.fileName.toLowerCase() === fileName.toLowerCase()
|
||||||
|
);
|
||||||
|
if (isDuplicate) {
|
||||||
|
return {
|
||||||
|
fileName,
|
||||||
|
shotCode: shot.shotCode,
|
||||||
|
shotId: shot.id,
|
||||||
|
label: parsed.label,
|
||||||
|
status: "duplicate" as const,
|
||||||
|
existingPlateCount,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const takenSoFar = allocated.get(shot.id) ?? 0;
|
||||||
|
allocated.set(shot.id, takenSoFar + 1);
|
||||||
|
|
||||||
|
return {
|
||||||
|
fileName,
|
||||||
|
shotCode: shot.shotCode,
|
||||||
|
shotId: shot.id,
|
||||||
|
label: parsed.label || `Plate ${existingPlateCount + takenSoFar + 1}`,
|
||||||
|
status: "match" as const,
|
||||||
|
existingPlateCount,
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
return NextResponse.json({ items });
|
||||||
|
}
|
||||||
@@ -0,0 +1,96 @@
|
|||||||
|
import { NextRequest, NextResponse } from "next/server";
|
||||||
|
import { auth } from "@/auth";
|
||||||
|
import { db } from "@/lib/db";
|
||||||
|
import { revalidatePath } from "next/cache";
|
||||||
|
|
||||||
|
export const maxDuration = 30;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* POST /api/batch-upload/plates/upload
|
||||||
|
* Body: { projectId, shotId, key, fileName, fileSize?, label? }
|
||||||
|
*
|
||||||
|
* Commits a footage plate whose bytes were already uploaded straight to
|
||||||
|
* Hetzner via POST /api/upload/presign, so large .mov plates never pass
|
||||||
|
* through this server or the reverse proxy.
|
||||||
|
*/
|
||||||
|
export async function POST(req: NextRequest) {
|
||||||
|
const session = await auth();
|
||||||
|
if (!session?.user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
|
||||||
|
if (!["ADMIN", "PRODUCER", "SUPERVISOR"].includes(session.user.role)) {
|
||||||
|
return NextResponse.json({ error: "Forbidden" }, { status: 403 });
|
||||||
|
}
|
||||||
|
|
||||||
|
let body: unknown;
|
||||||
|
try {
|
||||||
|
body = await req.json();
|
||||||
|
} catch {
|
||||||
|
return NextResponse.json({ error: "Invalid JSON" }, { status: 400 });
|
||||||
|
}
|
||||||
|
|
||||||
|
const { projectId, shotId, key, fileName, fileSize, label } = body as {
|
||||||
|
projectId?: unknown;
|
||||||
|
shotId?: unknown;
|
||||||
|
key?: unknown;
|
||||||
|
fileName?: unknown;
|
||||||
|
fileSize?: unknown;
|
||||||
|
label?: unknown;
|
||||||
|
};
|
||||||
|
|
||||||
|
if (
|
||||||
|
typeof projectId !== "string" ||
|
||||||
|
typeof shotId !== "string" ||
|
||||||
|
typeof key !== "string" ||
|
||||||
|
typeof fileName !== "string" ||
|
||||||
|
!projectId ||
|
||||||
|
!shotId ||
|
||||||
|
!key ||
|
||||||
|
!fileName
|
||||||
|
) {
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: "projectId, shotId, key and fileName are required" },
|
||||||
|
{ status: 400 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// The key must be one this app handed out via /api/upload/presign.
|
||||||
|
if (!key.startsWith("videos/")) {
|
||||||
|
return NextResponse.json({ error: "Invalid storage key" }, { status: 400 });
|
||||||
|
}
|
||||||
|
|
||||||
|
const shot = await db.shot.findFirst({
|
||||||
|
where: { id: shotId, projectId },
|
||||||
|
select: { id: true },
|
||||||
|
});
|
||||||
|
if (!shot) return NextResponse.json({ error: "Shot not found" }, { status: 404 });
|
||||||
|
|
||||||
|
const last = await db.footagePlate.findFirst({
|
||||||
|
where: { shotId },
|
||||||
|
orderBy: { sortOrder: "desc" },
|
||||||
|
select: { sortOrder: true },
|
||||||
|
});
|
||||||
|
|
||||||
|
const size = typeof fileSize === "number" && Number.isFinite(fileSize) && fileSize > 0
|
||||||
|
? BigInt(Math.round(fileSize))
|
||||||
|
: null;
|
||||||
|
|
||||||
|
const plate = await db.footagePlate.create({
|
||||||
|
data: {
|
||||||
|
shotId,
|
||||||
|
fileUrl: `/api/files/${key}`,
|
||||||
|
fileKey: key,
|
||||||
|
fileName,
|
||||||
|
fileSize: size,
|
||||||
|
label: typeof label === "string" ? label.trim().slice(0, 100) : "",
|
||||||
|
sortOrder: (last?.sortOrder ?? -1) + 1,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
revalidatePath(`/projects/${projectId}`);
|
||||||
|
revalidatePath(`/projects/${projectId}/shots/${shotId}`);
|
||||||
|
|
||||||
|
return NextResponse.json({
|
||||||
|
success: true,
|
||||||
|
plateId: plate.id,
|
||||||
|
label: plate.label,
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -2,7 +2,7 @@ import { NextRequest, NextResponse } from "next/server";
|
|||||||
import { auth } from "@/auth";
|
import { auth } from "@/auth";
|
||||||
import { db } from "@/lib/db";
|
import { db } from "@/lib/db";
|
||||||
import { uploadToHetzner, deleteFromHetzner } from "@/lib/storage";
|
import { uploadToHetzner, deleteFromHetzner } from "@/lib/storage";
|
||||||
import { recalcShotStatus } from "@/lib/shot-status";
|
import { recalcShotStatus, clearStaleShotApproval } from "@/lib/shot-status";
|
||||||
|
|
||||||
export const maxDuration = 300; // 5 min — large .mov high-res files
|
export const maxDuration = 300; // 5 min — large .mov high-res files
|
||||||
|
|
||||||
@@ -194,8 +194,14 @@ export async function POST(
|
|||||||
data: { status: "INTERNAL_REVIEW" },
|
data: { status: "INTERNAL_REVIEW" },
|
||||||
});
|
});
|
||||||
|
|
||||||
// Recalculate the parent shot's status
|
// Recalculate the parent shot's status, clearing any stale sign-off first so
|
||||||
await recalcShotStatus(shotId).catch(() => {});
|
// the new version does not land under a shot still reading COMPLETE.
|
||||||
|
await db
|
||||||
|
.$transaction(async (tx) => {
|
||||||
|
await clearStaleShotApproval(tx, shotId);
|
||||||
|
await recalcShotStatus(shotId, tx);
|
||||||
|
})
|
||||||
|
.catch(() => {});
|
||||||
|
|
||||||
return NextResponse.json({
|
return NextResponse.json({
|
||||||
success: true,
|
success: true,
|
||||||
|
|||||||
@@ -1,21 +1,8 @@
|
|||||||
import { NextRequest, NextResponse } from "next/server";
|
import { NextRequest, NextResponse } from "next/server";
|
||||||
import { db } from "@/lib/db";
|
import { db } from "@/lib/db";
|
||||||
import { ApprovalStatus } from "@prisma/client";
|
import { ApprovalStatus } from "@prisma/client";
|
||||||
import { recalcShotStatus } from "@/lib/shot-status";
|
import { recalcShotStatus, markShotForRevisions } from "@/lib/shot-status";
|
||||||
import { validateReviewToken } from "@/lib/review-auth";
|
import { validateReviewToken, getOrCreateReviewUser } from "@/lib/review-auth";
|
||||||
|
|
||||||
async function getOrCreateClientUser(email: string, label?: string | null) {
|
|
||||||
const existing = await db.user.findUnique({ where: { email } });
|
|
||||||
if (existing) return existing;
|
|
||||||
return db.user.create({
|
|
||||||
data: {
|
|
||||||
email,
|
|
||||||
name: label ?? email.split("@")[0],
|
|
||||||
role: "CLIENT",
|
|
||||||
isActive: true,
|
|
||||||
},
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function POST(
|
export async function POST(
|
||||||
req: NextRequest,
|
req: NextRequest,
|
||||||
@@ -48,9 +35,12 @@ export async function POST(
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (action === "APPROVE") {
|
if (action === "APPROVE") {
|
||||||
await db.shot.update({
|
await db.$transaction(async (tx) => {
|
||||||
where: { id: shotId },
|
await tx.shot.update({
|
||||||
data: { shotApprovalStatus: "CLIENT_APPROVED", status: "COMPLETE" },
|
where: { id: shotId },
|
||||||
|
data: { shotApprovalStatus: "CLIENT_APPROVED" },
|
||||||
|
});
|
||||||
|
await recalcShotStatus(shotId, tx);
|
||||||
});
|
});
|
||||||
} else if (action === "NEEDS_CHANGES") {
|
} else if (action === "NEEDS_CHANGES") {
|
||||||
// Increment shotVersion: v001 → v002, v009 → v010, etc.
|
// Increment shotVersion: v001 → v002, v009 → v010, etc.
|
||||||
@@ -59,17 +49,41 @@ export async function POST(
|
|||||||
const nextNum = verMatch ? parseInt(verMatch[1], 10) + 1 : 2;
|
const nextNum = verMatch ? parseInt(verMatch[1], 10) + 1 : 2;
|
||||||
const nextVersion = "v" + String(nextNum).padStart(3, "0");
|
const nextVersion = "v" + String(nextNum).padStart(3, "0");
|
||||||
|
|
||||||
|
const user = await getOrCreateReviewUser(session, token);
|
||||||
|
|
||||||
await db.$transaction(async (tx) => {
|
await db.$transaction(async (tx) => {
|
||||||
await tx.shot.update({
|
await tx.shot.update({
|
||||||
where: { id: shotId },
|
where: { id: shotId },
|
||||||
data: { shotApprovalStatus: "PENDING", sharedWithClient: false, shotVersion: nextVersion },
|
data: { shotVersion: nextVersion },
|
||||||
});
|
});
|
||||||
// Mark all non-DONE tasks as CHANGES
|
|
||||||
await tx.task.updateMany({
|
// Clears the approval, unshares, marks the tasks needing rework and
|
||||||
where: { shotId, status: { not: "DONE" } },
|
// recalculates — including the case where every task was already DONE,
|
||||||
data: { status: "CHANGES" },
|
// which used to match nothing and leave the request with no effect.
|
||||||
|
await markShotForRevisions(tx, shotId);
|
||||||
|
|
||||||
|
// The shot-level verdict has to land on the versions too: the dashboard
|
||||||
|
// counters, the version badges and the client portal's own filters all
|
||||||
|
// read Version.approvalStatus, so a shot-level change request was
|
||||||
|
// invisible everywhere those look.
|
||||||
|
const shown = await tx.version.findMany({
|
||||||
|
where: { task: { shotId }, isClientVisible: true, isLatest: true },
|
||||||
|
select: { id: true },
|
||||||
});
|
});
|
||||||
await recalcShotStatus(shotId, tx);
|
for (const v of shown) {
|
||||||
|
await tx.approval.create({
|
||||||
|
data: {
|
||||||
|
versionId: v.id,
|
||||||
|
userId: user.id,
|
||||||
|
status: "NEEDS_CHANGES",
|
||||||
|
notes: notes ?? "Changes requested on the shot",
|
||||||
|
},
|
||||||
|
});
|
||||||
|
await tx.version.update({
|
||||||
|
where: { id: v.id },
|
||||||
|
data: { approvalStatus: "NEEDS_CHANGES" },
|
||||||
|
});
|
||||||
|
}
|
||||||
});
|
});
|
||||||
} else {
|
} else {
|
||||||
return NextResponse.json({ error: "Invalid action" }, { status: 400 });
|
return NextResponse.json({ error: "Invalid action" }, { status: 400 });
|
||||||
@@ -99,8 +113,7 @@ export async function POST(
|
|||||||
return NextResponse.json({ error: "Version not found" }, { status: 404 });
|
return NextResponse.json({ error: "Version not found" }, { status: 404 });
|
||||||
}
|
}
|
||||||
|
|
||||||
const email = session.email ?? `client+${token.slice(0, 8)}@review.external`;
|
const user = await getOrCreateReviewUser(session, token);
|
||||||
const user = await getOrCreateClientUser(email, session.label);
|
|
||||||
|
|
||||||
// Record approval
|
// Record approval
|
||||||
await db.approval.create({
|
await db.approval.create({
|
||||||
@@ -126,9 +139,12 @@ export async function POST(
|
|||||||
select: { sharedWithClient: true, shotApprovalStatus: true },
|
select: { sharedWithClient: true, shotApprovalStatus: true },
|
||||||
});
|
});
|
||||||
if (shot?.sharedWithClient && shot.shotApprovalStatus !== "CLIENT_APPROVED") {
|
if (shot?.sharedWithClient && shot.shotApprovalStatus !== "CLIENT_APPROVED") {
|
||||||
|
// status is left to the recalc below — writing COMPLETE here was
|
||||||
|
// overwritten by it anyway, and disagreed with it whenever another
|
||||||
|
// task on the shot was still on CHANGES.
|
||||||
await db.shot.update({
|
await db.shot.update({
|
||||||
where: { id: version.task.shot.id },
|
where: { id: version.task.shot.id },
|
||||||
data: { shotApprovalStatus: "CLIENT_APPROVED", status: "COMPLETE" },
|
data: { shotApprovalStatus: "CLIENT_APPROVED" },
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,127 @@
|
|||||||
|
import { NextRequest, NextResponse } from "next/server";
|
||||||
|
import { db } from "@/lib/db";
|
||||||
|
import { validateReviewToken, findReviewUser, ownsComment } from "@/lib/review-auth";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Edit and delete for notes left through a client review link.
|
||||||
|
*
|
||||||
|
* A reviewer may only touch their own notes: the studio's comments and those of
|
||||||
|
* any other review session are read-only here, whatever the link holder sends.
|
||||||
|
* Ownership is the review session's guest User (lib/review-auth.ts) — the link
|
||||||
|
* is the credential, so everyone holding it shares that identity.
|
||||||
|
*/
|
||||||
|
|
||||||
|
/** Matches the internal addComment/editComment limits (actions/comments.ts). */
|
||||||
|
const MAX_LENGTH = 5000;
|
||||||
|
|
||||||
|
/** The annotation companion comments written by the drawing tools. */
|
||||||
|
const ANNOTATION_PREFIX = "✏️ Annotation at frame";
|
||||||
|
|
||||||
|
type Ctx = { params: Promise<{ token: string; commentId: string }> };
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Resolves the request to a comment the caller is allowed to change, or the
|
||||||
|
* response explaining why not.
|
||||||
|
*
|
||||||
|
* "Not yours" is deliberately answered with 404 rather than 403: a link holder
|
||||||
|
* has no business learning which comment ids exist outside their own notes.
|
||||||
|
*/
|
||||||
|
async function authorizeCommentEdit(req: NextRequest, ctx: Ctx) {
|
||||||
|
const { token, commentId } = await ctx.params;
|
||||||
|
|
||||||
|
const result = await validateReviewToken(token, req);
|
||||||
|
if (result.type === "requiresPassword") {
|
||||||
|
return { error: NextResponse.json({ requiresPassword: true }, { status: 401 }) };
|
||||||
|
}
|
||||||
|
if (result.type === "invalid") {
|
||||||
|
return {
|
||||||
|
error: NextResponse.json({ error: "Invalid or expired review link" }, { status: 403 }),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
const session = result.session;
|
||||||
|
|
||||||
|
const notFound = NextResponse.json({ error: "Comment not found" }, { status: 404 });
|
||||||
|
|
||||||
|
const comment = await db.comment.findUnique({
|
||||||
|
where: { id: commentId },
|
||||||
|
select: {
|
||||||
|
id: true,
|
||||||
|
authorId: true,
|
||||||
|
versionId: true,
|
||||||
|
frameNumber: true,
|
||||||
|
text: true,
|
||||||
|
version: {
|
||||||
|
select: {
|
||||||
|
shot: { select: { projectId: true } },
|
||||||
|
task: { select: { projectId: true } },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
if (!comment) return { error: notFound };
|
||||||
|
|
||||||
|
// Same project scoping the rest of the portal applies.
|
||||||
|
const projectId = comment.version.shot?.projectId ?? comment.version.task?.projectId;
|
||||||
|
if (projectId !== session.projectId) return { error: notFound };
|
||||||
|
|
||||||
|
const user = await findReviewUser(session, token);
|
||||||
|
if (!ownsComment(comment, user?.id)) return { error: notFound };
|
||||||
|
|
||||||
|
return { comment };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** PATCH — change the text of one's own note. */
|
||||||
|
export async function PATCH(req: NextRequest, ctx: Ctx) {
|
||||||
|
const authorized = await authorizeCommentEdit(req, ctx);
|
||||||
|
if (authorized.error) return authorized.error;
|
||||||
|
const { comment } = authorized;
|
||||||
|
|
||||||
|
const body = await req.json().catch(() => null);
|
||||||
|
const text = typeof body?.text === "string" ? body.text.trim() : "";
|
||||||
|
if (!text) {
|
||||||
|
return NextResponse.json({ error: "Note text is required" }, { status: 400 });
|
||||||
|
}
|
||||||
|
if (text.length > MAX_LENGTH) {
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: `Note must be ${MAX_LENGTH} characters or fewer` },
|
||||||
|
{ status: 400 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Only the text is editable. The frame a note is pinned to is what the studio
|
||||||
|
// works from, so moving it would silently repoint feedback someone may have
|
||||||
|
// already actioned; a note about a different frame is a new note.
|
||||||
|
const updated = await db.comment.update({
|
||||||
|
where: { id: comment.id },
|
||||||
|
data: { text },
|
||||||
|
include: {
|
||||||
|
author: { select: { id: true, name: true, image: true, email: true } },
|
||||||
|
replies: {
|
||||||
|
orderBy: { createdAt: "asc" },
|
||||||
|
include: { author: { select: { id: true, name: true, image: true, email: true } } },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
return NextResponse.json({ comment: { ...updated, canEdit: true } });
|
||||||
|
}
|
||||||
|
|
||||||
|
/** DELETE — remove one's own note. */
|
||||||
|
export async function DELETE(req: NextRequest, ctx: Ctx) {
|
||||||
|
const authorized = await authorizeCommentEdit(req, ctx);
|
||||||
|
if (authorized.error) return authorized.error;
|
||||||
|
const { comment } = authorized;
|
||||||
|
|
||||||
|
await db.comment.delete({ where: { id: comment.id } });
|
||||||
|
|
||||||
|
// A drawing leaves a companion comment; deleting the note without the strokes
|
||||||
|
// would leave marks on the frame that nothing explains. Mirrors deleteComment
|
||||||
|
// in actions/comments.ts.
|
||||||
|
if (comment.text.startsWith(ANNOTATION_PREFIX)) {
|
||||||
|
await db.annotation.deleteMany({
|
||||||
|
where: { versionId: comment.versionId, frameNumber: comment.frameNumber },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
return NextResponse.json({ success: true });
|
||||||
|
}
|
||||||
@@ -1,21 +1,8 @@
|
|||||||
import { NextRequest, NextResponse } from "next/server";
|
import { NextRequest, NextResponse } from "next/server";
|
||||||
import { db } from "@/lib/db";
|
import { db } from "@/lib/db";
|
||||||
import { slackNotifyNewFeedback } from "@/lib/slack";
|
import { slackNotifyNewFeedback } from "@/lib/slack";
|
||||||
import { validateReviewToken } from "@/lib/review-auth";
|
import { notifyCommentsAdded } from "@/lib/notifications";
|
||||||
|
import { validateReviewToken, getOrCreateReviewUser } from "@/lib/review-auth";
|
||||||
/** Find or create a guest user for the client reviewer based on the session email */
|
|
||||||
async function getOrCreateClientUser(email: string, label?: string | null) {
|
|
||||||
const existing = await db.user.findUnique({ where: { email } });
|
|
||||||
if (existing) return existing;
|
|
||||||
return db.user.create({
|
|
||||||
data: {
|
|
||||||
email,
|
|
||||||
name: label ?? email.split("@")[0],
|
|
||||||
role: "CLIENT",
|
|
||||||
isActive: true,
|
|
||||||
},
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function POST(
|
export async function POST(
|
||||||
req: NextRequest,
|
req: NextRequest,
|
||||||
@@ -42,8 +29,8 @@ export async function POST(
|
|||||||
const version = await db.version.findUnique({
|
const version = await db.version.findUnique({
|
||||||
where: { id: versionId },
|
where: { id: versionId },
|
||||||
include: {
|
include: {
|
||||||
shot: { select: { projectId: true, shotCode: true, project: { select: { slackWebhook: true } } } },
|
shot: { select: { projectId: true, shotCode: true, artistId: true, project: { select: { slackWebhook: true } } } },
|
||||||
task: { select: { projectId: true, title: true, project: { select: { slackWebhook: true } }, shot: { select: { shotCode: true } } } },
|
task: { select: { projectId: true, title: true, assignedArtistId: true, project: { select: { slackWebhook: true } }, shot: { select: { shotCode: true } } } },
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
const projectId = version?.shot?.projectId ?? version?.task?.projectId;
|
const projectId = version?.shot?.projectId ?? version?.task?.projectId;
|
||||||
@@ -52,8 +39,7 @@ export async function POST(
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Resolve commenter identity
|
// Resolve commenter identity
|
||||||
const email = session.email ?? `client+${token.slice(0, 8)}@review.external`;
|
const user = await getOrCreateReviewUser(session, token);
|
||||||
const user = await getOrCreateClientUser(email, session.label);
|
|
||||||
|
|
||||||
const comment = await db.comment.create({
|
const comment = await db.comment.create({
|
||||||
data: {
|
data: {
|
||||||
@@ -85,5 +71,18 @@ export async function POST(
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
return NextResponse.json({ comment }, { status: 201 });
|
await notifyCommentsAdded({
|
||||||
|
notes: [{
|
||||||
|
versionId,
|
||||||
|
shotCode,
|
||||||
|
frameNumber,
|
||||||
|
artistIds: [version.shot?.artistId, version.task?.assignedArtistId],
|
||||||
|
}],
|
||||||
|
authorId: user.id,
|
||||||
|
authorName: user.name ?? user.email,
|
||||||
|
origin: "client",
|
||||||
|
}).catch((err) => console.error("[client comment] notify failed", err));
|
||||||
|
|
||||||
|
// canEdit mirrors the GET shape — a note you just wrote is always your own.
|
||||||
|
return NextResponse.json({ comment: { ...comment, canEdit: true } }, { status: 201 });
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,8 @@
|
|||||||
import { NextRequest, NextResponse } from "next/server";
|
import { NextRequest, NextResponse } from "next/server";
|
||||||
import { db } from "@/lib/db";
|
import { db } from "@/lib/db";
|
||||||
import { validateReviewToken } from "@/lib/review-auth";
|
import { validateReviewToken } from "@/lib/review-auth";
|
||||||
|
import { shotThumbnail } from "@/lib/shot-thumbnail";
|
||||||
|
import { clientShotCode, clientTaskTitle } from "@/lib/shot-code";
|
||||||
|
|
||||||
/** GET /api/client/[token]/project — returns project + shots with tasks that have client-visible versions */
|
/** GET /api/client/[token]/project — returns project + shots with tasks that have client-visible versions */
|
||||||
export async function GET(
|
export async function GET(
|
||||||
@@ -43,12 +45,15 @@ export async function GET(
|
|||||||
select: {
|
select: {
|
||||||
id: true,
|
id: true,
|
||||||
shotCode: true,
|
shotCode: true,
|
||||||
|
clientCode: true,
|
||||||
episode: true,
|
episode: true,
|
||||||
sequence: true,
|
sequence: true,
|
||||||
|
scene: true,
|
||||||
description: true,
|
description: true,
|
||||||
status: true,
|
status: true,
|
||||||
shotApprovalStatus: true,
|
shotApprovalStatus: true,
|
||||||
thumbnailUrl: true,
|
thumbnailUrl: true,
|
||||||
|
generatedThumbnailUrl: true,
|
||||||
tasks: {
|
tasks: {
|
||||||
where: {
|
where: {
|
||||||
versions: { some: { isClientVisible: true } },
|
versions: { some: { isClientVisible: true } },
|
||||||
@@ -113,7 +118,26 @@ export async function GET(
|
|||||||
|
|
||||||
return NextResponse.json({
|
return NextResponse.json({
|
||||||
project,
|
project,
|
||||||
shots,
|
// Shots the client sees resolve the same way as internally: the reference
|
||||||
|
// still first, a render-derived one only where the show supplied none.
|
||||||
|
// Everything the client reads is in their own naming: the alias replaces
|
||||||
|
// our shot code, and the same swap runs over task titles, which carry the
|
||||||
|
// code by convention ("UNG_106_010_020_cmp_TT_v004"). The internal code is
|
||||||
|
// not sent at all — there is nothing here for it to be useful for, and
|
||||||
|
// leaking it invites the client to quote it back at us.
|
||||||
|
// The scene is our numbering too, and an alias does not have to share it
|
||||||
|
// (SNV's "SNV_101_0463_CP_VFX" is our scene 001), so an aliased shot goes
|
||||||
|
// out without one rather than with a number the client never used.
|
||||||
|
shots: shots.map(({ generatedThumbnailUrl, clientCode, scene, ...shot }) => ({
|
||||||
|
...shot,
|
||||||
|
shotCode: clientShotCode({ ...shot, clientCode }),
|
||||||
|
scene: clientShotCode({ ...shot, clientCode }) === shot.shotCode ? scene || null : null,
|
||||||
|
thumbnailUrl: shotThumbnail({ ...shot, generatedThumbnailUrl }),
|
||||||
|
tasks: shot.tasks.map((task) => ({
|
||||||
|
...task,
|
||||||
|
title: clientTaskTitle(task.title, { ...shot, clientCode }),
|
||||||
|
})),
|
||||||
|
})),
|
||||||
assetTasks,
|
assetTasks,
|
||||||
sessionLabel: session.label,
|
sessionLabel: session.label,
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -0,0 +1,57 @@
|
|||||||
|
import { NextRequest, NextResponse } from "next/server";
|
||||||
|
import { db } from "@/lib/db";
|
||||||
|
import { validateReviewToken } from "@/lib/review-auth";
|
||||||
|
import { generateHetznerDownloadUrl } from "@/lib/storage";
|
||||||
|
import { clientHighResFilename } from "@/lib/shot-code";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* GET /api/client/[token]/versions/[versionId]/highres/download
|
||||||
|
* The version's ProRes, for a client reviewer: same visibility rule as the
|
||||||
|
* version itself (GET ../route.ts), and named with the client's shot code.
|
||||||
|
*/
|
||||||
|
export async function GET(
|
||||||
|
req: NextRequest,
|
||||||
|
{ params }: { params: Promise<{ token: string; versionId: string }> }
|
||||||
|
) {
|
||||||
|
const { token, versionId } = await params;
|
||||||
|
|
||||||
|
const result = await validateReviewToken(token, req);
|
||||||
|
if (result.type !== "ok") {
|
||||||
|
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
|
||||||
|
}
|
||||||
|
|
||||||
|
const version = await db.version.findUnique({
|
||||||
|
where: { id: versionId },
|
||||||
|
select: {
|
||||||
|
highResKey: true,
|
||||||
|
highResFilename: true,
|
||||||
|
isClientVisible: true,
|
||||||
|
shot: { select: { projectId: true, shotCode: true, clientCode: true } },
|
||||||
|
task: {
|
||||||
|
select: {
|
||||||
|
projectId: true,
|
||||||
|
shot: { select: { shotCode: true, clientCode: true } },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const projectId = version?.shot?.projectId ?? version?.task?.projectId;
|
||||||
|
if (!version || projectId !== result.session.projectId) {
|
||||||
|
return NextResponse.json({ error: "Not found" }, { status: 404 });
|
||||||
|
}
|
||||||
|
// Task-only versions need explicit sharing, as in the version route
|
||||||
|
if (!version.shot && !version.isClientVisible) {
|
||||||
|
return NextResponse.json({ error: "Not found" }, { status: 404 });
|
||||||
|
}
|
||||||
|
if (!version.highResKey) {
|
||||||
|
return NextResponse.json({ error: "No high-res file available" }, { status: 404 });
|
||||||
|
}
|
||||||
|
|
||||||
|
const shot = version.shot ?? version.task?.shot ?? null;
|
||||||
|
const url = await generateHetznerDownloadUrl(
|
||||||
|
version.highResKey,
|
||||||
|
clientHighResFilename(version.highResFilename ?? "high-res.mov", shot)
|
||||||
|
);
|
||||||
|
return NextResponse.json({ url });
|
||||||
|
}
|
||||||
@@ -1,6 +1,7 @@
|
|||||||
import { NextRequest, NextResponse } from "next/server";
|
import { NextRequest, NextResponse } from "next/server";
|
||||||
import { db } from "@/lib/db";
|
import { db } from "@/lib/db";
|
||||||
import { validateReviewToken } from "@/lib/review-auth";
|
import { validateReviewToken, findReviewUser, ownsComment } from "@/lib/review-auth";
|
||||||
|
import { clientHighResFilename, clientShotCode, clientTaskTitle } from "@/lib/shot-code";
|
||||||
|
|
||||||
/** GET /api/client/[token]/versions/[versionId] — returns version + comments for client portal */
|
/** GET /api/client/[token]/versions/[versionId] — returns version + comments for client portal */
|
||||||
export async function GET(
|
export async function GET(
|
||||||
@@ -40,7 +41,7 @@ export async function GET(
|
|||||||
task: {
|
task: {
|
||||||
include: {
|
include: {
|
||||||
project: { select: { id: true, name: true, code: true } },
|
project: { select: { id: true, name: true, code: true } },
|
||||||
shot: { select: { id: true, shotCode: true, highResKey: true, highResFilename: true } },
|
shot: { select: { id: true, shotCode: true, clientCode: true, highResKey: true, highResFilename: true } },
|
||||||
asset: { select: { assetCode: true, name: true } },
|
asset: { select: { assetCode: true, name: true } },
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
@@ -64,7 +65,7 @@ export async function GET(
|
|||||||
return NextResponse.json({ error: "Version not found" }, { status: 404 });
|
return NextResponse.json({ error: "Version not found" }, { status: 404 });
|
||||||
}
|
}
|
||||||
|
|
||||||
const comments = await db.comment.findMany({
|
const commentRows = await db.comment.findMany({
|
||||||
where: { versionId },
|
where: { versionId },
|
||||||
orderBy: { frameNumber: "asc" },
|
orderBy: { frameNumber: "asc" },
|
||||||
include: {
|
include: {
|
||||||
@@ -78,31 +79,59 @@ export async function GET(
|
|||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// Which notes this reviewer may edit or delete. Read-only: opening a review
|
||||||
|
// link should not create the guest User, so a session that has never posted
|
||||||
|
// simply owns nothing. The edit/delete route re-checks this — the flag drives
|
||||||
|
// the UI, it does not grant anything.
|
||||||
|
const reviewUser = await findReviewUser(session, token);
|
||||||
|
const comments = commentRows.map((c) => ({
|
||||||
|
...c,
|
||||||
|
canEdit: ownsComment(c, reviewUser?.id),
|
||||||
|
}));
|
||||||
|
|
||||||
// Resolve the shot that has the high-res file (comes from version.shot OR version.task.shot)
|
// Resolve the shot that has the high-res file (comes from version.shot OR version.task.shot)
|
||||||
const highResShot = version.shot ?? (version.task as any)?.shot ?? null;
|
const highResShot = version.shot ?? (version.task as any)?.shot ?? null;
|
||||||
|
|
||||||
|
// The shot the title and breadcrumb are drawn from — either relation.
|
||||||
|
const namingShot = version.shot ?? ((version.task as any)?.shot ?? null);
|
||||||
|
|
||||||
|
// High Res: this version's own ProRes (uploaded by the render worker) wins;
|
||||||
|
// the shot's manually uploaded file is the fallback for older versions.
|
||||||
|
const versionHighRes = !!version.highResKey;
|
||||||
const serializedVersion = {
|
const serializedVersion = {
|
||||||
...version,
|
...version,
|
||||||
fileSize: version.fileSize?.toString() ?? null,
|
fileSize: version.fileSize?.toString() ?? null,
|
||||||
|
highResKey: undefined, // never expose a storage key
|
||||||
|
highResSize: version.highResSize?.toString() ?? null,
|
||||||
// Top-level high-res fields so the client works for both shot and task versions
|
// Top-level high-res fields so the client works for both shot and task versions
|
||||||
hasHighRes: !!(highResShot?.highResKey),
|
hasHighRes: versionHighRes || !!(highResShot?.highResKey),
|
||||||
highResShotId: highResShot?.highResKey ? (highResShot.id ?? null) : null,
|
highResSource: versionHighRes ? "version" : highResShot?.highResKey ? "shot" : null,
|
||||||
highResFilename: highResShot?.highResFilename ?? null,
|
highResShotId: !versionHighRes && highResShot?.highResKey ? (highResShot.id ?? null) : null,
|
||||||
|
highResFilename: versionHighRes
|
||||||
|
? clientHighResFilename(version.highResFilename ?? "high-res.mov", namingShot)
|
||||||
|
: highResShot?.highResFilename ?? null,
|
||||||
// Expose only whether a high-res file exists on the shot relation, never the storage key
|
// Expose only whether a high-res file exists on the shot relation, never the storage key
|
||||||
shot: version.shot
|
shot: version.shot
|
||||||
? {
|
? {
|
||||||
...version.shot,
|
...version.shot,
|
||||||
|
shotCode: clientShotCode(version.shot),
|
||||||
|
clientCode: undefined,
|
||||||
hasHighRes: !!version.shot.highResKey,
|
hasHighRes: !!version.shot.highResKey,
|
||||||
highResFilename: version.shot.highResFilename ?? null,
|
highResFilename: version.shot.highResFilename ?? null,
|
||||||
highResKey: undefined,
|
highResKey: undefined,
|
||||||
}
|
}
|
||||||
: null,
|
: null,
|
||||||
|
// Task titles carry the shot code by convention, so the player header gets
|
||||||
|
// the same swap as the shot list (lib/shot-code.ts).
|
||||||
task: version.task
|
task: version.task
|
||||||
? {
|
? {
|
||||||
...version.task,
|
...version.task,
|
||||||
|
title: namingShot ? clientTaskTitle(version.task.title, namingShot) : version.task.title,
|
||||||
shot: (version.task as any)?.shot
|
shot: (version.task as any)?.shot
|
||||||
? {
|
? {
|
||||||
...((version.task as any).shot),
|
...((version.task as any).shot),
|
||||||
|
shotCode: clientShotCode((version.task as any).shot),
|
||||||
|
clientCode: undefined,
|
||||||
highResKey: undefined, // strip storage key
|
highResKey: undefined, // strip storage key
|
||||||
}
|
}
|
||||||
: null,
|
: null,
|
||||||
|
|||||||
@@ -2,20 +2,30 @@ import { NextRequest, NextResponse } from "next/server";
|
|||||||
import { toErrorResponse } from "@/lib/render-pipeline/errors";
|
import { toErrorResponse } from "@/lib/render-pipeline/errors";
|
||||||
import { requirePipelineAdmin } from "@/lib/render-pipeline/session-auth";
|
import { requirePipelineAdmin } from "@/lib/render-pipeline/session-auth";
|
||||||
import { markDelivered } from "@/lib/render-pipeline/deliveries";
|
import { markDelivered } from "@/lib/render-pipeline/deliveries";
|
||||||
|
import { recordShareSchema } from "@/lib/render-pipeline/delivery-handoff";
|
||||||
|
|
||||||
// ── POST /api/deliveries/{id}/delivered (E19) ────────────────────────────────
|
// ── POST /api/deliveries/{id}/delivered (E19) ────────────────────────────────
|
||||||
//
|
//
|
||||||
// The folder has been uploaded to the client. Moves every packaged export to
|
// The upload link has been sent to the client. Takes who it was sent to, and
|
||||||
// DELIVERED — the end of the pipeline.
|
// moves every packaged export to DELIVERED — the end of the pipeline.
|
||||||
|
|
||||||
export async function POST(
|
export async function POST(
|
||||||
_req: NextRequest,
|
req: NextRequest,
|
||||||
{ params }: { params: Promise<{ packageId: string }> }
|
{ params }: { params: Promise<{ packageId: string }> }
|
||||||
) {
|
) {
|
||||||
try {
|
try {
|
||||||
const user = await requirePipelineAdmin();
|
const user = await requirePipelineAdmin();
|
||||||
const { packageId } = await params;
|
const { packageId } = await params;
|
||||||
const result = await markDelivered(packageId, user.id);
|
|
||||||
|
const parsed = recordShareSchema.safeParse(await req.json().catch(() => null));
|
||||||
|
if (!parsed.success) {
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: parsed.error.issues[0]?.message ?? "Invalid request", details: parsed.error.issues },
|
||||||
|
{ status: 422 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const result = await markDelivered(packageId, parsed.data, user.id);
|
||||||
return NextResponse.json(result);
|
return NextResponse.json(result);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
const { body, status } = toErrorResponse(err);
|
const { body, status } = toErrorResponse(err);
|
||||||
|
|||||||
@@ -0,0 +1,34 @@
|
|||||||
|
import { NextRequest, NextResponse } from "next/server";
|
||||||
|
import { toErrorResponse } from "@/lib/render-pipeline/errors";
|
||||||
|
import { requirePipelineAdmin } from "@/lib/render-pipeline/session-auth";
|
||||||
|
import { markUploaded } from "@/lib/render-pipeline/deliveries";
|
||||||
|
import { recordUploadSchema } from "@/lib/render-pipeline/delivery-handoff";
|
||||||
|
|
||||||
|
// ── POST /api/deliveries/{id}/uploaded ───────────────────────────────────────
|
||||||
|
//
|
||||||
|
// The folder is on the client's portal. Records where, so the package shows as
|
||||||
|
// waiting to be shared rather than waiting to be uploaded.
|
||||||
|
|
||||||
|
export async function POST(
|
||||||
|
req: NextRequest,
|
||||||
|
{ params }: { params: Promise<{ packageId: string }> }
|
||||||
|
) {
|
||||||
|
try {
|
||||||
|
const user = await requirePipelineAdmin();
|
||||||
|
const { packageId } = await params;
|
||||||
|
|
||||||
|
const parsed = recordUploadSchema.safeParse(await req.json().catch(() => null));
|
||||||
|
if (!parsed.success) {
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: parsed.error.issues[0]?.message ?? "Invalid request", details: parsed.error.issues },
|
||||||
|
{ status: 422 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const result = await markUploaded(packageId, parsed.data, user.id);
|
||||||
|
return NextResponse.json(result);
|
||||||
|
} catch (err) {
|
||||||
|
const { body, status } = toErrorResponse(err);
|
||||||
|
return NextResponse.json(body, { status });
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
import { NextRequest, NextResponse } from "next/server";
|
import { NextRequest, NextResponse } from "next/server";
|
||||||
import { DeliveryStatus } from "@prisma/client";
|
import { DeliveryKind, DeliveryStatus } from "@prisma/client";
|
||||||
import { toErrorResponse } from "@/lib/render-pipeline/errors";
|
import { toErrorResponse } from "@/lib/render-pipeline/errors";
|
||||||
import { requirePipelineUser, requirePipelineAdmin } from "@/lib/render-pipeline/session-auth";
|
import { requirePipelineUser, requirePipelineAdmin } from "@/lib/render-pipeline/session-auth";
|
||||||
import {
|
import {
|
||||||
@@ -15,10 +15,12 @@ export async function GET(req: NextRequest) {
|
|||||||
await requirePipelineUser();
|
await requirePipelineUser();
|
||||||
const { searchParams } = new URL(req.url);
|
const { searchParams } = new URL(req.url);
|
||||||
const status = searchParams.get("status");
|
const status = searchParams.get("status");
|
||||||
|
const kind = searchParams.get("kind");
|
||||||
const result = await listDeliveryPackages({
|
const result = await listDeliveryPackages({
|
||||||
projectId: searchParams.get("projectId") ?? undefined,
|
projectId: searchParams.get("projectId") ?? undefined,
|
||||||
episode: searchParams.get("episode") ?? undefined,
|
episode: searchParams.get("episode") ?? undefined,
|
||||||
status: status ? (status as DeliveryStatus) : undefined,
|
status: status ? (status as DeliveryStatus) : undefined,
|
||||||
|
kind: kind ? (kind as DeliveryKind) : undefined,
|
||||||
});
|
});
|
||||||
return NextResponse.json(result);
|
return NextResponse.json(result);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
|
|||||||
@@ -0,0 +1,34 @@
|
|||||||
|
import { NextRequest, NextResponse } from "next/server";
|
||||||
|
import { toErrorResponse } from "@/lib/render-pipeline/errors";
|
||||||
|
import { requirePipelineAdmin } from "@/lib/render-pipeline/session-auth";
|
||||||
|
import { cancelDeliveryRequest } from "@/lib/render-pipeline/delivery-requests";
|
||||||
|
import { cancelRequestSchema } from "@/lib/render-pipeline/delivery-request-state";
|
||||||
|
|
||||||
|
// ── POST /api/delivery-requests/{id}/cancel ──────────────────────────────────
|
||||||
|
//
|
||||||
|
// The only way a request leaves the awaiting list without being delivered, and
|
||||||
|
// it has to say why.
|
||||||
|
|
||||||
|
export async function POST(
|
||||||
|
req: NextRequest,
|
||||||
|
{ params }: { params: Promise<{ requestId: string }> }
|
||||||
|
) {
|
||||||
|
try {
|
||||||
|
const user = await requirePipelineAdmin();
|
||||||
|
const { requestId } = await params;
|
||||||
|
|
||||||
|
const parsed = cancelRequestSchema.safeParse(await req.json().catch(() => null));
|
||||||
|
if (!parsed.success) {
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: parsed.error.issues[0]?.message ?? "Invalid request", details: parsed.error.issues },
|
||||||
|
{ status: 422 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const result = await cancelDeliveryRequest(requestId, parsed.data.reason, user.id);
|
||||||
|
return NextResponse.json(result);
|
||||||
|
} catch (err) {
|
||||||
|
const { body, status } = toErrorResponse(err);
|
||||||
|
return NextResponse.json(body, { status });
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
import { NextRequest, NextResponse } from "next/server";
|
||||||
|
import { toErrorResponse } from "@/lib/render-pipeline/errors";
|
||||||
|
import { requirePipelineUser } from "@/lib/render-pipeline/session-auth";
|
||||||
|
import { getRequestOptions } from "@/lib/render-pipeline/delivery-requests";
|
||||||
|
|
||||||
|
// ── GET /api/delivery-requests/options?projectId= ────────────────────────────
|
||||||
|
//
|
||||||
|
// The episodes a request can be logged against.
|
||||||
|
|
||||||
|
export async function GET(req: NextRequest) {
|
||||||
|
try {
|
||||||
|
await requirePipelineUser();
|
||||||
|
const projectId = new URL(req.url).searchParams.get("projectId");
|
||||||
|
if (!projectId) {
|
||||||
|
return NextResponse.json({ error: "projectId is required" }, { status: 400 });
|
||||||
|
}
|
||||||
|
return NextResponse.json(await getRequestOptions(projectId));
|
||||||
|
} catch (err) {
|
||||||
|
const { body, status } = toErrorResponse(err);
|
||||||
|
return NextResponse.json(body, { status });
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
import { NextRequest, NextResponse } from "next/server";
|
||||||
|
import { toErrorResponse } from "@/lib/render-pipeline/errors";
|
||||||
|
import { requirePipelineAdmin, requirePipelineUser } from "@/lib/render-pipeline/session-auth";
|
||||||
|
import { createDeliveryRequest, listDeliveryRequests } from "@/lib/render-pipeline/delivery-requests";
|
||||||
|
import { createRequestSchema } from "@/lib/render-pipeline/delivery-request-state";
|
||||||
|
|
||||||
|
// ── GET /api/delivery-requests · POST /api/delivery-requests ─────────────────
|
||||||
|
//
|
||||||
|
// What clients have asked for, and how much of each ask has gone out.
|
||||||
|
|
||||||
|
export async function GET(req: NextRequest) {
|
||||||
|
try {
|
||||||
|
await requirePipelineUser();
|
||||||
|
const { searchParams } = new URL(req.url);
|
||||||
|
const requests = await listDeliveryRequests({
|
||||||
|
projectId: searchParams.get("projectId") ?? undefined,
|
||||||
|
openOnly: searchParams.get("open") === "1",
|
||||||
|
});
|
||||||
|
return NextResponse.json({ requests });
|
||||||
|
} catch (err) {
|
||||||
|
const { body, status } = toErrorResponse(err);
|
||||||
|
return NextResponse.json(body, { status });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function POST(req: NextRequest) {
|
||||||
|
try {
|
||||||
|
const user = await requirePipelineAdmin();
|
||||||
|
|
||||||
|
const parsed = createRequestSchema.safeParse(await req.json().catch(() => null));
|
||||||
|
if (!parsed.success) {
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: parsed.error.issues[0]?.message ?? "Invalid request", details: parsed.error.issues },
|
||||||
|
{ status: 422 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const result = await createDeliveryRequest(parsed.data, user.id);
|
||||||
|
return NextResponse.json(result, { status: 201 });
|
||||||
|
} catch (err) {
|
||||||
|
const { body, status } = toErrorResponse(err);
|
||||||
|
return NextResponse.json(body, { status });
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,5 +1,6 @@
|
|||||||
import { NextRequest, NextResponse } from "next/server";
|
import { NextRequest, NextResponse } from "next/server";
|
||||||
import { db } from "@/lib/db";
|
import { db } from "@/lib/db";
|
||||||
|
import { shotThumbnail } from "@/lib/shot-thumbnail";
|
||||||
|
|
||||||
// ── Auth ─────────────────────────────────────────────────────────────────────
|
// ── Auth ─────────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
@@ -91,6 +92,7 @@ export async function GET(
|
|||||||
seqTimecodeStart: true,
|
seqTimecodeStart: true,
|
||||||
seqTimecodeEnd: true,
|
seqTimecodeEnd: true,
|
||||||
thumbnailUrl: true,
|
thumbnailUrl: true,
|
||||||
|
generatedThumbnailUrl: true,
|
||||||
artist: {
|
artist: {
|
||||||
select: { id: true, name: true, email: true },
|
select: { id: true, name: true, email: true },
|
||||||
},
|
},
|
||||||
@@ -111,6 +113,9 @@ export async function GET(
|
|||||||
return NextResponse.json({
|
return NextResponse.json({
|
||||||
project,
|
project,
|
||||||
pagination: { page, limit, total, pages: Math.ceil(total / limit) },
|
pagination: { page, limit, total, pages: Math.ceil(total / limit) },
|
||||||
shots,
|
shots: shots.map(({ generatedThumbnailUrl, ...shot }) => ({
|
||||||
|
...shot,
|
||||||
|
thumbnailUrl: shotThumbnail({ ...shot, generatedThumbnailUrl }),
|
||||||
|
})),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,62 @@
|
|||||||
|
import { NextRequest, NextResponse } from "next/server";
|
||||||
|
import { isExtAuthorized } from "@/lib/render-pipeline/ext-auth";
|
||||||
|
import { toErrorResponse, PipelineError } from "@/lib/render-pipeline/errors";
|
||||||
|
import { isArtifactKey } from "@/lib/render-pipeline/artifact-kinds";
|
||||||
|
import { db } from "@/lib/db";
|
||||||
|
import { abortHetznerMultipartUpload, completeHetznerMultipartUpload } from "@/lib/storage";
|
||||||
|
|
||||||
|
// ── POST /api/ext/render/jobs/{jobId}/artifact-complete (E20b) ───────────────
|
||||||
|
//
|
||||||
|
// Closes a multipart upload started by artifact-presign: stitches the parts
|
||||||
|
// (by part number + ETag) into the final object, or with `abort: true` throws
|
||||||
|
// the stored parts away after the worker gave up.
|
||||||
|
|
||||||
|
export async function POST(
|
||||||
|
req: NextRequest,
|
||||||
|
{ params }: { params: Promise<{ jobId: string }> }
|
||||||
|
) {
|
||||||
|
if (!isExtAuthorized(req)) {
|
||||||
|
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
|
||||||
|
}
|
||||||
|
const { jobId } = await params;
|
||||||
|
let body: {
|
||||||
|
machineId?: string;
|
||||||
|
key?: string;
|
||||||
|
uploadId?: string;
|
||||||
|
parts?: { partNumber?: number; etag?: string }[];
|
||||||
|
abort?: boolean;
|
||||||
|
};
|
||||||
|
try {
|
||||||
|
body = await req.json();
|
||||||
|
} catch {
|
||||||
|
return NextResponse.json({ error: "Invalid JSON" }, { status: 400 });
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
if (!body.machineId) throw new PipelineError(400, "machineId is required");
|
||||||
|
if (!body.key || !isArtifactKey(body.key)) throw new PipelineError(422, "key is not a worker artifact key");
|
||||||
|
if (!body.uploadId) throw new PipelineError(400, "uploadId is required");
|
||||||
|
|
||||||
|
const job = await db.renderJob.findUnique({ where: { id: jobId }, select: { machineId: true } });
|
||||||
|
if (!job) throw new PipelineError(404, "Render job not found");
|
||||||
|
if (job.machineId !== body.machineId) {
|
||||||
|
throw new PipelineError(409, "Job is not held by this machine (lease reassigned?)");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (body.abort) {
|
||||||
|
await abortHetznerMultipartUpload(body.key, body.uploadId);
|
||||||
|
return NextResponse.json({ ok: true, aborted: true });
|
||||||
|
}
|
||||||
|
|
||||||
|
const parts = (body.parts ?? []).filter(
|
||||||
|
(p): p is { partNumber: number; etag: string } =>
|
||||||
|
typeof p.partNumber === "number" && typeof p.etag === "string" && p.etag.length > 0
|
||||||
|
);
|
||||||
|
if (parts.length === 0) throw new PipelineError(422, "parts are required");
|
||||||
|
|
||||||
|
await completeHetznerMultipartUpload(body.key, body.uploadId, parts);
|
||||||
|
return NextResponse.json({ ok: true, key: body.key, url: `/api/files/${body.key}` });
|
||||||
|
} catch (err) {
|
||||||
|
const { body: errBody, status } = toErrorResponse(err);
|
||||||
|
return NextResponse.json(errBody, { status });
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -3,20 +3,29 @@ import { randomUUID } from "crypto";
|
|||||||
import { isExtAuthorized } from "@/lib/render-pipeline/ext-auth";
|
import { isExtAuthorized } from "@/lib/render-pipeline/ext-auth";
|
||||||
import { toErrorResponse, PipelineError } from "@/lib/render-pipeline/errors";
|
import { toErrorResponse, PipelineError } from "@/lib/render-pipeline/errors";
|
||||||
import { db } from "@/lib/db";
|
import { db } from "@/lib/db";
|
||||||
import { generateHetznerPresignedUploadUrl, sanitizeFileName } from "@/lib/storage";
|
import { ARTIFACT_KIND_FOLDERS } from "@/lib/render-pipeline/artifact-kinds";
|
||||||
|
import {
|
||||||
|
createHetznerMultipartUpload,
|
||||||
|
generateHetznerPresignedUploadUrl,
|
||||||
|
sanitizeFileName,
|
||||||
|
} from "@/lib/storage";
|
||||||
|
|
||||||
// ── POST /api/ext/render/jobs/{jobId}/artifact-presign (E20) ─────────────────
|
// ── POST /api/ext/render/jobs/{jobId}/artifact-presign (E20) ─────────────────
|
||||||
//
|
//
|
||||||
// Presigned upload URL for worker artifacts. Kinds map to the existing object
|
// Presigned upload URL for worker artifacts. Kinds map to the existing object
|
||||||
// storage folder layout: preview → videos/, thumbnail → image/,
|
// storage folder layout: preview → videos/, thumbnail → image/,
|
||||||
// metadata/log → renders/.
|
// metadata/log → renders/, highres (the delivery MOV) → highres/ beside the
|
||||||
|
// manually uploaded High Res files.
|
||||||
|
//
|
||||||
|
// `multipart: true` + `size` (worker ≥ 1.7.2) returns an S3 multipart upload
|
||||||
|
// instead — an uploadId and one presigned URL per part — which the worker
|
||||||
|
// fills in parallel and closes with artifact-complete (E20b). A single PUT
|
||||||
|
// from the studio is capped near 0.1 MB/s; parallel parts scale with the
|
||||||
|
// number of connections. Older workers never ask and get the single PUT.
|
||||||
|
|
||||||
const KIND_FOLDERS: Record<string, string> = {
|
const KIND_FOLDERS = ARTIFACT_KIND_FOLDERS;
|
||||||
preview: "videos",
|
const MIN_PART = 8 * 1024 * 1024;
|
||||||
thumbnail: "image",
|
const MAX_PARTS = 10000; // S3 limit
|
||||||
metadata: "renders",
|
|
||||||
log: "renders",
|
|
||||||
};
|
|
||||||
|
|
||||||
export async function POST(
|
export async function POST(
|
||||||
req: NextRequest,
|
req: NextRequest,
|
||||||
@@ -26,7 +35,14 @@ export async function POST(
|
|||||||
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
|
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
|
||||||
}
|
}
|
||||||
const { jobId } = await params;
|
const { jobId } = await params;
|
||||||
let body: { machineId?: string; kind?: string; fileName?: string; contentType?: string };
|
let body: {
|
||||||
|
machineId?: string;
|
||||||
|
kind?: string;
|
||||||
|
fileName?: string;
|
||||||
|
contentType?: string;
|
||||||
|
multipart?: boolean;
|
||||||
|
size?: number;
|
||||||
|
};
|
||||||
try {
|
try {
|
||||||
body = await req.json();
|
body = await req.json();
|
||||||
} catch {
|
} catch {
|
||||||
@@ -48,6 +64,14 @@ export async function POST(
|
|||||||
}
|
}
|
||||||
|
|
||||||
const key = `${folder}/${randomUUID()}-${sanitizeFileName(body.fileName)}`;
|
const key = `${folder}/${randomUUID()}-${sanitizeFileName(body.fileName)}`;
|
||||||
|
|
||||||
|
if (body.multipart && typeof body.size === "number" && body.size > MIN_PART) {
|
||||||
|
const partSize = Math.max(MIN_PART, Math.ceil(body.size / MAX_PARTS));
|
||||||
|
const partCount = Math.ceil(body.size / partSize);
|
||||||
|
const { uploadId, partUrls } = await createHetznerMultipartUpload(key, body.contentType, partCount);
|
||||||
|
return NextResponse.json({ key, url: `/api/files/${key}`, uploadId, partSize, partUrls });
|
||||||
|
}
|
||||||
|
|
||||||
const presignedUrl = await generateHetznerPresignedUploadUrl(key, body.contentType);
|
const presignedUrl = await generateHetznerPresignedUploadUrl(key, body.contentType);
|
||||||
return NextResponse.json({ presignedUrl, key, url: `/api/files/${key}` });
|
return NextResponse.json({ presignedUrl, key, url: `/api/files/${key}` });
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
|
|||||||
@@ -0,0 +1,38 @@
|
|||||||
|
import { NextRequest, NextResponse } from "next/server";
|
||||||
|
import { isExtAuthorized } from "@/lib/render-pipeline/ext-auth";
|
||||||
|
import { toErrorResponse } from "@/lib/render-pipeline/errors";
|
||||||
|
import { attachHighRes, type AttachHighResInput } from "@/lib/render-pipeline/preview";
|
||||||
|
|
||||||
|
// ── POST /api/ext/render/jobs/{jobId}/attach-highres (E13b) ──────────────────
|
||||||
|
//
|
||||||
|
// The preview's ProRes MOV, uploaded in the background after finalize (worker
|
||||||
|
// ≥ 1.7.1). Attaches it to the version as its High Res download, or records on
|
||||||
|
// the export timeline that the upload failed.
|
||||||
|
|
||||||
|
export async function POST(
|
||||||
|
req: NextRequest,
|
||||||
|
{ params }: { params: Promise<{ jobId: string }> }
|
||||||
|
) {
|
||||||
|
if (!isExtAuthorized(req)) {
|
||||||
|
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
|
||||||
|
}
|
||||||
|
const { jobId } = await params;
|
||||||
|
|
||||||
|
let body: AttachHighResInput & { machineId?: string };
|
||||||
|
try {
|
||||||
|
body = await req.json();
|
||||||
|
} catch {
|
||||||
|
return NextResponse.json({ error: "Invalid JSON" }, { status: 400 });
|
||||||
|
}
|
||||||
|
if (!body.machineId) {
|
||||||
|
return NextResponse.json({ error: "machineId is required" }, { status: 400 });
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const result = await attachHighRes(jobId, body.machineId, body);
|
||||||
|
return NextResponse.json(result);
|
||||||
|
} catch (err) {
|
||||||
|
const { body: errBody, status } = toErrorResponse(err);
|
||||||
|
return NextResponse.json(errBody, { status });
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,5 +1,6 @@
|
|||||||
import { NextRequest, NextResponse } from "next/server";
|
import { NextRequest, NextResponse } from "next/server";
|
||||||
import { db } from "@/lib/db";
|
import { db } from "@/lib/db";
|
||||||
|
import { shotThumbnail } from "@/lib/shot-thumbnail";
|
||||||
|
|
||||||
// ── Auth ─────────────────────────────────────────────────────────────────────
|
// ── Auth ─────────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
@@ -67,6 +68,7 @@ export async function GET(req: NextRequest) {
|
|||||||
seqTimecodeEnd: true,
|
seqTimecodeEnd: true,
|
||||||
shotVersion: true,
|
shotVersion: true,
|
||||||
thumbnailUrl: true,
|
thumbnailUrl: true,
|
||||||
|
generatedThumbnailUrl: true,
|
||||||
createdAt: true,
|
createdAt: true,
|
||||||
updatedAt: true,
|
updatedAt: true,
|
||||||
project: {
|
project: {
|
||||||
@@ -104,5 +106,8 @@ export async function GET(req: NextRequest) {
|
|||||||
return NextResponse.json({ error: "Shot not found" }, { status: 404 });
|
return NextResponse.json({ error: "Shot not found" }, { status: 404 });
|
||||||
}
|
}
|
||||||
|
|
||||||
return NextResponse.json({ shot });
|
const { generatedThumbnailUrl, ...rest } = shot;
|
||||||
|
return NextResponse.json({
|
||||||
|
shot: { ...rest, thumbnailUrl: shotThumbnail(shot) },
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
import { NextRequest, NextResponse } from "next/server";
|
import { NextRequest, NextResponse } from "next/server";
|
||||||
import { auth } from "@/auth";
|
import { auth } from "@/auth";
|
||||||
import { db } from "@/lib/db";
|
import { db } from "@/lib/db";
|
||||||
|
import { shotThumbnail } from "@/lib/shot-thumbnail";
|
||||||
|
|
||||||
export async function GET(req: NextRequest) {
|
export async function GET(req: NextRequest) {
|
||||||
const session = await auth();
|
const session = await auth();
|
||||||
@@ -33,6 +34,7 @@ export async function GET(req: NextRequest) {
|
|||||||
shotApprovalStatus: true,
|
shotApprovalStatus: true,
|
||||||
sharedWithClient: true,
|
sharedWithClient: true,
|
||||||
thumbnailUrl: true,
|
thumbnailUrl: true,
|
||||||
|
generatedThumbnailUrl: true,
|
||||||
tasks: {
|
tasks: {
|
||||||
select: {
|
select: {
|
||||||
id: true,
|
id: true,
|
||||||
@@ -48,6 +50,12 @@ export async function GET(req: NextRequest) {
|
|||||||
thumbnailUrl: true,
|
thumbnailUrl: true,
|
||||||
posterUrl: true,
|
posterUrl: true,
|
||||||
fps: true,
|
fps: true,
|
||||||
|
duration: true,
|
||||||
|
frameCount: true,
|
||||||
|
hqFileUrl: true,
|
||||||
|
handleHead: true,
|
||||||
|
handleTail: true,
|
||||||
|
pictureStartFrame: true,
|
||||||
approvalStatus: true,
|
approvalStatus: true,
|
||||||
mimeType: true,
|
mimeType: true,
|
||||||
createdAt: true,
|
createdAt: true,
|
||||||
@@ -75,7 +83,7 @@ export async function GET(req: NextRequest) {
|
|||||||
status: shot.status,
|
status: shot.status,
|
||||||
shotApprovalStatus: shot.shotApprovalStatus,
|
shotApprovalStatus: shot.shotApprovalStatus,
|
||||||
sharedWithClient: shot.sharedWithClient,
|
sharedWithClient: shot.sharedWithClient,
|
||||||
thumbnailUrl: shot.thumbnailUrl,
|
thumbnailUrl: shotThumbnail(shot),
|
||||||
latestVersion: {
|
latestVersion: {
|
||||||
id: latest.id,
|
id: latest.id,
|
||||||
versionNumber: latest.versionNumber,
|
versionNumber: latest.versionNumber,
|
||||||
@@ -83,6 +91,12 @@ export async function GET(req: NextRequest) {
|
|||||||
thumbnailUrl: latest.thumbnailUrl,
|
thumbnailUrl: latest.thumbnailUrl,
|
||||||
posterUrl: latest.posterUrl,
|
posterUrl: latest.posterUrl,
|
||||||
fps: latest.fps,
|
fps: latest.fps,
|
||||||
|
duration: latest.duration,
|
||||||
|
frameCount: latest.frameCount,
|
||||||
|
hqFileUrl: latest.hqFileUrl,
|
||||||
|
handleHead: latest.handleHead,
|
||||||
|
handleTail: latest.handleTail,
|
||||||
|
pictureStartFrame: latest.pictureStartFrame,
|
||||||
approvalStatus: latest.approvalStatus,
|
approvalStatus: latest.approvalStatus,
|
||||||
taskTitle: latest.taskTitle,
|
taskTitle: latest.taskTitle,
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
import { NextResponse } from "next/server";
|
import { NextResponse } from "next/server";
|
||||||
import { auth } from "@/auth";
|
import { auth } from "@/auth";
|
||||||
import { db } from "@/lib/db";
|
import { db } from "@/lib/db";
|
||||||
|
import { getProjectPosters } from "@/lib/project-poster";
|
||||||
|
|
||||||
export async function GET(req: Request) {
|
export async function GET(req: Request) {
|
||||||
const session = await auth();
|
const session = await auth();
|
||||||
@@ -53,9 +54,13 @@ export async function GET(req: Request) {
|
|||||||
statsMap.set(row.projectId, existing);
|
statsMap.set(row.projectId, existing);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// One still per project for the card art, chosen from the shots themselves.
|
||||||
|
const posters = await getProjectPosters(projects.map((p) => p.id));
|
||||||
|
|
||||||
const projectsWithStats = projects.map((p) => ({
|
const projectsWithStats = projects.map((p) => ({
|
||||||
...p,
|
...p,
|
||||||
shotStats: statsMap.get(p.id) ?? { total: 0, approved: 0, inProgress: 0 },
|
shotStats: statsMap.get(p.id) ?? { total: 0, approved: 0, inProgress: 0 },
|
||||||
|
poster: posters.get(p.id) ?? null,
|
||||||
}));
|
}));
|
||||||
|
|
||||||
return NextResponse.json({ projects: projectsWithStats });
|
return NextResponse.json({ projects: projectsWithStats });
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ import { listExports } from "@/lib/render-pipeline/exports";
|
|||||||
// ── GET /api/render/queue (E21) ──────────────────────────────────────────────
|
// ── GET /api/render/queue (E21) ──────────────────────────────────────────────
|
||||||
//
|
//
|
||||||
// Exports list for the Render Queue page. Optional filters: projectId,
|
// Exports list for the Render Queue page. Optional filters: projectId,
|
||||||
// episode, status; standard pagination. Defaults to all statuses so the queue
|
// episode, status, q (shot/client code search); standard pagination. Defaults to all statuses so the queue
|
||||||
// page can show history too — the UI filters live states client-side.
|
// page can show history too — the UI filters live states client-side.
|
||||||
|
|
||||||
export async function GET(req: NextRequest) {
|
export async function GET(req: NextRequest) {
|
||||||
@@ -19,6 +19,7 @@ export async function GET(req: NextRequest) {
|
|||||||
projectId: searchParams.get("projectId") ?? undefined,
|
projectId: searchParams.get("projectId") ?? undefined,
|
||||||
episode: searchParams.get("episode") ?? undefined,
|
episode: searchParams.get("episode") ?? undefined,
|
||||||
shotId: searchParams.get("shotId") ?? undefined,
|
shotId: searchParams.get("shotId") ?? undefined,
|
||||||
|
search: searchParams.get("q")?.slice(0, 100) || undefined,
|
||||||
status:
|
status:
|
||||||
status && (Object.values(ExportStatus) as string[]).includes(status)
|
status && (Object.values(ExportStatus) as string[]).includes(status)
|
||||||
? (status as ExportStatus)
|
? (status as ExportStatus)
|
||||||
|
|||||||
@@ -73,6 +73,40 @@ export async function POST(req: NextRequest) {
|
|||||||
return NextResponse.json({ session: reviewSession, portalUrl }, { status: 201 });
|
return NextResponse.json({ session: reviewSession, portalUrl }, { status: 201 });
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Reactivate a review link: push its expiry `expiresInDays` from now and turn
|
||||||
|
* it back on. The token is unchanged, so a URL the client already has works
|
||||||
|
* again rather than a new one having to be sent.
|
||||||
|
*/
|
||||||
|
export async function PATCH(req: NextRequest) {
|
||||||
|
const session = await auth();
|
||||||
|
if (!session?.user) {
|
||||||
|
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
|
||||||
|
}
|
||||||
|
if (!["ADMIN", "PRODUCER", "SUPERVISOR"].includes(session.user.role as string)) {
|
||||||
|
return NextResponse.json({ error: "Forbidden" }, { status: 403 });
|
||||||
|
}
|
||||||
|
|
||||||
|
const id = req.nextUrl.searchParams.get("id");
|
||||||
|
if (!id) return NextResponse.json({ error: "id required" }, { status: 400 });
|
||||||
|
|
||||||
|
const body = await req.json().catch(() => ({}));
|
||||||
|
const expiresInDays = Number(body.expiresInDays ?? 30);
|
||||||
|
if (!Number.isInteger(expiresInDays) || expiresInDays < 1 || expiresInDays > 365) {
|
||||||
|
return NextResponse.json({ error: "expiresInDays must be 1–365" }, { status: 400 });
|
||||||
|
}
|
||||||
|
|
||||||
|
const existing = await db.reviewSession.findUnique({ where: { id }, select: { id: true } });
|
||||||
|
if (!existing) return NextResponse.json({ error: "Review link not found" }, { status: 404 });
|
||||||
|
|
||||||
|
const reviewSession = await db.reviewSession.update({
|
||||||
|
where: { id },
|
||||||
|
data: { expiresAt: addDays(new Date(), expiresInDays), isActive: true },
|
||||||
|
});
|
||||||
|
|
||||||
|
return NextResponse.json({ session: reviewSession });
|
||||||
|
}
|
||||||
|
|
||||||
export async function DELETE(req: NextRequest) {
|
export async function DELETE(req: NextRequest) {
|
||||||
const session = await auth();
|
const session = await auth();
|
||||||
if (!session?.user) {
|
if (!session?.user) {
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
import { NextRequest, NextResponse } from "next/server";
|
import { NextRequest, NextResponse } from "next/server";
|
||||||
import { auth } from "@/auth";
|
import { auth } from "@/auth";
|
||||||
import { db } from "@/lib/db";
|
import { db } from "@/lib/db";
|
||||||
|
import { shotThumbnail } from "@/lib/shot-thumbnail";
|
||||||
|
|
||||||
function requireRole(role: string) {
|
function requireRole(role: string) {
|
||||||
return ["ADMIN", "PRODUCER", "SUPERVISOR"].includes(role);
|
return ["ADMIN", "PRODUCER", "SUPERVISOR"].includes(role);
|
||||||
@@ -27,6 +28,7 @@ export async function GET(
|
|||||||
scene: true,
|
scene: true,
|
||||||
episode: true,
|
episode: true,
|
||||||
thumbnailUrl: true,
|
thumbnailUrl: true,
|
||||||
|
generatedThumbnailUrl: true,
|
||||||
references: {
|
references: {
|
||||||
orderBy: { sortOrder: "asc" },
|
orderBy: { sortOrder: "asc" },
|
||||||
select: {
|
select: {
|
||||||
@@ -41,5 +43,9 @@ export async function GET(
|
|||||||
});
|
});
|
||||||
|
|
||||||
if (!shot) return NextResponse.json({ error: "Not found" }, { status: 404 });
|
if (!shot) return NextResponse.json({ error: "Not found" }, { status: 404 });
|
||||||
return NextResponse.json({ shot });
|
|
||||||
|
const { generatedThumbnailUrl, ...rest } = shot;
|
||||||
|
return NextResponse.json({
|
||||||
|
shot: { ...rest, thumbnailUrl: shotThumbnail(shot) },
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
import { NextRequest, NextResponse } from "next/server";
|
import { NextRequest, NextResponse } from "next/server";
|
||||||
import { auth } from "@/auth";
|
import { auth } from "@/auth";
|
||||||
import { db } from "@/lib/db";
|
import { db } from "@/lib/db";
|
||||||
|
import { sortShotsForList } from "@/lib/shot-order";
|
||||||
|
|
||||||
export async function GET(
|
export async function GET(
|
||||||
req: NextRequest,
|
req: NextRequest,
|
||||||
@@ -38,9 +39,35 @@ export async function GET(
|
|||||||
|
|
||||||
const project = await db.project.findUnique({
|
const project = await db.project.findUnique({
|
||||||
where: { id: shot.projectId },
|
where: { id: shot.projectId },
|
||||||
select: { name: true },
|
select: {
|
||||||
|
name: true,
|
||||||
|
projectType: true,
|
||||||
|
shots: {
|
||||||
|
orderBy: { createdAt: "asc" },
|
||||||
|
select: {
|
||||||
|
id: true,
|
||||||
|
shotCode: true,
|
||||||
|
episode: true,
|
||||||
|
scene: true,
|
||||||
|
shotNumber: true,
|
||||||
|
shotGroup: { select: { name: true } },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// Neighbours in the project page's shot list order, for prev/next navigation
|
||||||
|
const orderedShots = project ? sortShotsForList(project.shots, project.projectType) : [];
|
||||||
|
const shotIndex = orderedShots.findIndex((s) => s.id === shotId);
|
||||||
|
const neighbour = (i: number) =>
|
||||||
|
shotIndex >= 0 && orderedShots[i] ? { id: orderedShots[i].id, shotCode: orderedShots[i].shotCode } : null;
|
||||||
|
const shotNav = {
|
||||||
|
prev: neighbour(shotIndex - 1),
|
||||||
|
next: neighbour(shotIndex + 1),
|
||||||
|
position: shotIndex + 1,
|
||||||
|
total: orderedShots.length,
|
||||||
|
};
|
||||||
|
|
||||||
const [tasks, artists] = await Promise.all([
|
const [tasks, artists] = await Promise.all([
|
||||||
db.task.findMany({
|
db.task.findMany({
|
||||||
where: { shotId },
|
where: { shotId },
|
||||||
@@ -82,7 +109,7 @@ export async function GET(
|
|||||||
session.user.role as string
|
session.user.role as string
|
||||||
);
|
);
|
||||||
|
|
||||||
// Serialize BigInt fields (fileSize) so JSON.stringify doesn't throw
|
// Serialize BigInt fields (fileSize, highResSize) so JSON.stringify doesn't throw
|
||||||
const shotSerialized = {
|
const shotSerialized = {
|
||||||
...shot,
|
...shot,
|
||||||
footagePlates: shot.footagePlates.map((p) => ({
|
footagePlates: shot.footagePlates.map((p) => ({
|
||||||
@@ -92,12 +119,14 @@ export async function GET(
|
|||||||
versions: shot.versions.map((v) => ({
|
versions: shot.versions.map((v) => ({
|
||||||
...v,
|
...v,
|
||||||
fileSize: v.fileSize != null ? v.fileSize.toString() : null,
|
fileSize: v.fileSize != null ? v.fileSize.toString() : null,
|
||||||
|
highResSize: v.highResSize != null ? v.highResSize.toString() : null,
|
||||||
})),
|
})),
|
||||||
};
|
};
|
||||||
|
|
||||||
return NextResponse.json({
|
return NextResponse.json({
|
||||||
shot: shotSerialized,
|
shot: shotSerialized,
|
||||||
projectName: project?.name ?? "",
|
projectName: project?.name ?? "",
|
||||||
|
shotNav,
|
||||||
canApprove,
|
canApprove,
|
||||||
canInternallyApprove: ["ADMIN", "PRODUCER", "SUPERVISOR"].includes(session.user.role as string),
|
canInternallyApprove: ["ADMIN", "PRODUCER", "SUPERVISOR"].includes(session.user.role as string),
|
||||||
tasks,
|
tasks,
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
import { NextRequest, NextResponse } from "next/server";
|
import { NextRequest, NextResponse } from "next/server";
|
||||||
import { auth } from "@/auth";
|
import { auth } from "@/auth";
|
||||||
import { db } from "@/lib/db";
|
import { db } from "@/lib/db";
|
||||||
|
import { shotThumbnail } from "@/lib/shot-thumbnail";
|
||||||
|
|
||||||
// ─── Helpers ──────────────────────────────────────────────────────────────────
|
// ─── Helpers ──────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
@@ -409,13 +410,18 @@ export async function GET(req: NextRequest) {
|
|||||||
where: { projectId },
|
where: { projectId },
|
||||||
select: {
|
select: {
|
||||||
id: true, shotCode: true, scene: true, episode: true, shotNumber: true,
|
id: true, shotCode: true, scene: true, episode: true, shotNumber: true,
|
||||||
description: true, notes: true, status: true, thumbnailUrl: true,
|
description: true, notes: true, status: true,
|
||||||
|
thumbnailUrl: true, generatedThumbnailUrl: true,
|
||||||
frameStart: true, frameEnd: true, fps: true, isKeyShot: true, shotVersion: true,
|
frameStart: true, frameEnd: true, fps: true, isKeyShot: true, shotVersion: true,
|
||||||
shotGroup: { select: { id: true, name: true } },
|
shotGroup: { select: { id: true, name: true } },
|
||||||
},
|
},
|
||||||
orderBy: [{ episode: "asc" }, { scene: "asc" }, { shotNumber: "asc" }],
|
orderBy: [{ episode: "asc" }, { scene: "asc" }, { shotNumber: "asc" }],
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// Collapse the two columns before anything reads them, so the "only shots
|
||||||
|
// with thumbnails" filter and the page renderer agree on what counts as one.
|
||||||
|
shots = shots.map((s) => ({ ...s, thumbnailUrl: shotThumbnail(s) }));
|
||||||
|
|
||||||
if (onlyThumbs) shots = shots.filter((s) => !!s.thumbnailUrl);
|
if (onlyThumbs) shots = shots.filter((s) => !!s.thumbnailUrl);
|
||||||
if (epFilter.length) shots = shots.filter((s) => epFilter.includes(s.episode ?? ""));
|
if (epFilter.length) shots = shots.filter((s) => epFilter.includes(s.episode ?? ""));
|
||||||
if (grpFilter.length) shots = shots.filter((s) => grpFilter.includes(s.shotGroup?.id ?? ""));
|
if (grpFilter.length) shots = shots.filter((s) => grpFilter.includes(s.shotGroup?.id ?? ""));
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
import { NextRequest, NextResponse } from "next/server";
|
import { NextRequest, NextResponse } from "next/server";
|
||||||
import { auth } from "@/auth";
|
import { auth } from "@/auth";
|
||||||
import { db } from "@/lib/db";
|
import { db } from "@/lib/db";
|
||||||
|
import { shotThumbnail } from "@/lib/shot-thumbnail";
|
||||||
|
|
||||||
// GET /api/storyboard/shots?projectId=xxx
|
// GET /api/storyboard/shots?projectId=xxx
|
||||||
export async function GET(req: NextRequest) {
|
export async function GET(req: NextRequest) {
|
||||||
@@ -26,6 +27,7 @@ export async function GET(req: NextRequest) {
|
|||||||
notes: true,
|
notes: true,
|
||||||
status: true,
|
status: true,
|
||||||
thumbnailUrl: true,
|
thumbnailUrl: true,
|
||||||
|
generatedThumbnailUrl: true,
|
||||||
frameStart: true,
|
frameStart: true,
|
||||||
frameEnd: true,
|
frameEnd: true,
|
||||||
fps: true,
|
fps: true,
|
||||||
@@ -40,5 +42,12 @@ export async function GET(req: NextRequest) {
|
|||||||
],
|
],
|
||||||
});
|
});
|
||||||
|
|
||||||
return NextResponse.json({ shots });
|
// The reference still wins; a render-derived one fills the gap where a show
|
||||||
|
// shipped no stills at all (lib/shot-thumbnail.ts).
|
||||||
|
return NextResponse.json({
|
||||||
|
shots: shots.map(({ generatedThumbnailUrl, ...shot }) => ({
|
||||||
|
...shot,
|
||||||
|
thumbnailUrl: shotThumbnail({ ...shot, generatedThumbnailUrl }),
|
||||||
|
})),
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,34 @@
|
|||||||
|
import { NextRequest, NextResponse } from "next/server";
|
||||||
|
import { auth } from "@/auth";
|
||||||
|
import { db } from "@/lib/db";
|
||||||
|
import { generateHetznerDownloadUrl } from "@/lib/storage";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* GET /api/versions/[versionId]/highres/download — short-lived presigned URL
|
||||||
|
* for this version's ProRes (the delivery MOV the render worker uploaded).
|
||||||
|
*/
|
||||||
|
export async function GET(
|
||||||
|
req: NextRequest,
|
||||||
|
{ params }: { params: Promise<{ versionId: string }> }
|
||||||
|
) {
|
||||||
|
const session = await auth();
|
||||||
|
if (!session?.user) {
|
||||||
|
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
|
||||||
|
}
|
||||||
|
|
||||||
|
const { versionId } = await params;
|
||||||
|
const version = await db.version.findUnique({
|
||||||
|
where: { id: versionId },
|
||||||
|
select: { highResKey: true, highResFilename: true },
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!version?.highResKey) {
|
||||||
|
return NextResponse.json({ error: "No high-res file available" }, { status: 404 });
|
||||||
|
}
|
||||||
|
|
||||||
|
const url = await generateHetznerDownloadUrl(
|
||||||
|
version.highResKey,
|
||||||
|
version.highResFilename ?? "high-res.mov"
|
||||||
|
);
|
||||||
|
return NextResponse.json({ url });
|
||||||
|
}
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user