Compare commits
21 Commits
5e29c3b88d
...
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 |
+1
-1
@@ -23,7 +23,7 @@ Dockerfile*
|
|||||||
.github
|
.github
|
||||||
migrations
|
migrations
|
||||||
README.md
|
README.md
|
||||||
uploads
|
uploads*
|
||||||
.git
|
.git
|
||||||
*.tar
|
*.tar
|
||||||
*.sql
|
*.sql
|
||||||
+66
-9
@@ -20,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.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -69,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 |
|
||||||
|
|
||||||
@@ -166,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.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -233,8 +286,12 @@ 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? }`.
|
||||||
|
|||||||
+1
-1
@@ -1194,7 +1194,7 @@ Renders run past the cut at each end (8 + 8 by house convention). Handles ship w
|
|||||||
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):
|
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.
|
- **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.
|
- **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.
|
A lease keep-alive runs during the encode and uploads (they can outlast the 300 s lease). The export timeline records what was attached.
|
||||||
|
|
||||||
|
|||||||
@@ -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.
|
||||||
|
|
||||||
|
|||||||
@@ -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();
|
||||||
|
}
|
||||||
@@ -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);
|
||||||
|
|
||||||
|
|||||||
@@ -304,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;
|
||||||
@@ -418,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,
|
||||||
@@ -433,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)
|
||||||
@@ -443,28 +454,26 @@ public sealed class JobExecutor
|
|||||||
|
|
||||||
// High quality MP4 + the MOV as the version's High Res download
|
// High quality MP4 + the MOV as the version's High Res download
|
||||||
// (§9.6). Both optional: a failure here costs the extras, never the
|
// (§9.6). Both optional: a failure here costs the extras, never the
|
||||||
// preview, which is already safely uploaded.
|
// 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;
|
string? hqKey = null;
|
||||||
string? highResKey = null;
|
var highResPending = false;
|
||||||
long? highResSize = null;
|
|
||||||
if (manifest.HighQuality)
|
if (manifest.HighQuality)
|
||||||
{
|
{
|
||||||
await using var keepAlive = new LeaseKeepAlive(_api, job.Id, machineId, TimeSpan.FromSeconds(60), shutdown);
|
status.Line("Encoding High quality MP4");
|
||||||
|
|
||||||
var hqPath = await _preview.TryMakeHighQualityAsync(job.Id, result.MovPath!, result.Mp4Path!, shutdown);
|
var hqPath = await _preview.TryMakeHighQualityAsync(job.Id, result.MovPath!, result.Mp4Path!, shutdown);
|
||||||
if (hqPath is not null)
|
if (hqPath is not null)
|
||||||
{
|
{
|
||||||
hqKey = await _api.UploadArtifactAsync(job.Id, machineId, "preview", hqPath, "video/mp4", shutdown);
|
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);
|
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");
|
||||||
}
|
}
|
||||||
|
|
||||||
if (result.MovPath is not null && File.Exists(result.MovPath))
|
highResPending = result.MovPath is not null && File.Exists(result.MovPath);
|
||||||
{
|
if (highResPending)
|
||||||
highResSize = new FileInfo(result.MovPath).Length;
|
status.Line("ProRes MOV queued for background upload — completing the job now");
|
||||||
highResKey = await _api.UploadArtifactAsync(
|
|
||||||
job.Id, machineId, "highres", result.MovPath, "video/quicktime", shutdown);
|
|
||||||
if (highResKey is null) _log.LogWarning("ProRes upload failed for job {JobId}", job.Id);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
_spooler.Enqueue("finalize", job.Id, new Dictionary<string, object?>
|
_spooler.Enqueue("finalize", job.Id, new Dictionary<string, object?>
|
||||||
@@ -476,9 +485,7 @@ public sealed class JobExecutor
|
|||||||
["previewMovKey"] = previewKey,
|
["previewMovKey"] = previewKey,
|
||||||
["thumbnailKey"] = thumbKey,
|
["thumbnailKey"] = thumbKey,
|
||||||
["hqPreviewKey"] = hqKey,
|
["hqPreviewKey"] = hqKey,
|
||||||
["highResKey"] = highResKey,
|
["highResPending"] = highResPending,
|
||||||
["highResFileName"] = highResKey is null ? null : Path.GetFileName(result.MovPath),
|
|
||||||
["highResSize"] = highResKey is null ? null : highResSize,
|
|
||||||
},
|
},
|
||||||
["renderStats"] = new Dictionary<string, object?>
|
["renderStats"] = new Dictionary<string, object?>
|
||||||
{
|
{
|
||||||
@@ -497,6 +504,10 @@ public sealed class JobExecutor
|
|||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// 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);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,18 +1,35 @@
|
|||||||
|
using System.Diagnostics;
|
||||||
|
using System.Text;
|
||||||
|
|
||||||
namespace VFXReviewWorker;
|
namespace VFXReviewWorker;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Renews a job's lease with progress reports while the worker does something
|
/// 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
|
/// long that reports nothing on its own — the High quality encode and the
|
||||||
/// ProRes upload can each outlast a 300 s lease, and an expired lease lets the
|
/// uploads can each outlast a 300 s lease, and an expired lease lets the
|
||||||
/// reaper hand the job to another machine mid-upload.
|
/// 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>
|
/// </summary>
|
||||||
internal sealed class LeaseKeepAlive : IAsyncDisposable
|
internal sealed class LeaseKeepAlive : IAsyncDisposable
|
||||||
{
|
{
|
||||||
|
private readonly ApiClient _api;
|
||||||
|
private readonly string _jobId;
|
||||||
|
private readonly string _machineId;
|
||||||
private readonly CancellationTokenSource _cts;
|
private readonly CancellationTokenSource _cts;
|
||||||
|
private readonly SemaphoreSlim _wake = new(0);
|
||||||
private readonly Task _loop;
|
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)
|
public LeaseKeepAlive(ApiClient api, string jobId, string machineId, TimeSpan interval, CancellationToken shutdown)
|
||||||
{
|
{
|
||||||
|
_api = api;
|
||||||
|
_jobId = jobId;
|
||||||
|
_machineId = machineId;
|
||||||
_cts = CancellationTokenSource.CreateLinkedTokenSource(shutdown);
|
_cts = CancellationTokenSource.CreateLinkedTokenSource(shutdown);
|
||||||
var token = _cts.Token;
|
var token = _cts.Token;
|
||||||
_loop = Task.Run(async () =>
|
_loop = Task.Run(async () =>
|
||||||
@@ -21,10 +38,10 @@ internal sealed class LeaseKeepAlive : IAsyncDisposable
|
|||||||
{
|
{
|
||||||
while (!token.IsCancellationRequested)
|
while (!token.IsCancellationRequested)
|
||||||
{
|
{
|
||||||
await Task.Delay(interval, token);
|
|
||||||
// Best-effort by contract (ApiClient.ProgressAsync never throws
|
// Best-effort by contract (ApiClient.ProgressAsync never throws
|
||||||
// on transport errors); progress stays at 1.0 — the render is done.
|
// on transport errors); progress stays at 1.0 — the render is done.
|
||||||
await api.ProgressAsync(jobId, machineId, 1.0, null, null, null, null, token);
|
await _api.ProgressAsync(_jobId, _machineId, 1.0, null, null, null, Render(), token);
|
||||||
|
await _wake.WaitAsync(interval, token);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
catch (OperationCanceledException)
|
catch (OperationCanceledException)
|
||||||
@@ -34,10 +51,53 @@ internal sealed class LeaseKeepAlive : IAsyncDisposable
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <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()
|
public async ValueTask DisposeAsync()
|
||||||
{
|
{
|
||||||
_cts.Cancel();
|
_cts.Cancel();
|
||||||
try { await _loop; } catch { /* already reported */ }
|
try { await _loop; } catch { /* already reported */ }
|
||||||
_cts.Dispose();
|
_cts.Dispose();
|
||||||
|
_wake.Dispose();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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.7.0</Version>
|
<Version>1.7.2</Version>
|
||||||
</PropertyGroup>
|
</PropertyGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
|
|||||||
@@ -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);
|
||||||
|
|
||||||
|
|||||||
@@ -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.7.0";
|
var PANEL_VERSION = "2.7.1";
|
||||||
|
|
||||||
(function VFXReviewConnector(thisObj) {
|
(function VFXReviewConnector(thisObj) {
|
||||||
var uiState = {
|
var uiState = {
|
||||||
@@ -4710,7 +4710,6 @@ var PANEL_VERSION = "2.7.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;
|
||||||
@@ -4868,6 +4867,7 @@ var PANEL_VERSION = "2.7.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";
|
||||||
@@ -4974,12 +4974,6 @@ var PANEL_VERSION = "2.7.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"];
|
||||||
|
|||||||
@@ -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
|
||||||
|
|||||||
@@ -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 };
|
||||||
|
}
|
||||||
+12
-10
@@ -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,
|
||||||
|
shotCode,
|
||||||
|
frameNumber: parsed.frameNumber,
|
||||||
|
artistIds: [version?.shot?.artistId, version?.task?.assignedArtistId],
|
||||||
|
}],
|
||||||
|
authorId: session.user.id,
|
||||||
authorName: user?.name ?? session.user.email ?? "Someone",
|
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,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 };
|
||||||
|
}
|
||||||
+35
-3
@@ -6,6 +6,7 @@ import { revalidatePath } from "next/cache";
|
|||||||
import { z } from "zod";
|
import { z } from "zod";
|
||||||
import { ShotStatus, ShotPriority, ShotApprovalStatus, Prisma } from "@prisma/client";
|
import { ShotStatus, ShotPriority, ShotApprovalStatus, Prisma } from "@prisma/client";
|
||||||
import { recalcShotStatus, markShotForRevisions } 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"),
|
||||||
@@ -718,6 +719,8 @@ export async function bulkSetManualDelivery(
|
|||||||
shotIds: string[],
|
shotIds: string[],
|
||||||
deliveredOn: string | null,
|
deliveredOn: string | null,
|
||||||
note?: string,
|
note?: string,
|
||||||
|
/** Where it was uploaded and who was sent the link. */
|
||||||
|
evidence?: { uploadUrl?: string; sharedWith?: string },
|
||||||
) {
|
) {
|
||||||
const session = await auth();
|
const session = await auth();
|
||||||
if (!session?.user) throw new Error("Unauthorized");
|
if (!session?.user) throw new Error("Unauthorized");
|
||||||
@@ -726,7 +729,7 @@ export async function bulkSetManualDelivery(
|
|||||||
}
|
}
|
||||||
|
|
||||||
const ids = z.array(z.string().cuid()).parse(shotIds);
|
const ids = z.array(z.string().cuid()).parse(shotIds);
|
||||||
if (!ids.length) return { success: true, updated: 0 };
|
if (!ids.length) return { success: true as const, updated: 0 };
|
||||||
|
|
||||||
let deliveredAt: Date | null = null;
|
let deliveredAt: Date | null = null;
|
||||||
if (deliveredOn) {
|
if (deliveredOn) {
|
||||||
@@ -745,6 +748,27 @@ export async function bulkSetManualDelivery(
|
|||||||
if (shots.length !== ids.length) throw new Error("Some shots not found");
|
if (shots.length !== ids.length) throw new Error("Some shots not found");
|
||||||
|
|
||||||
const trimmedNote = note?.trim() || null;
|
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({
|
await db.shot.updateMany({
|
||||||
where: { id: { in: ids } },
|
where: { id: { in: ids } },
|
||||||
data: deliveredAt
|
data: deliveredAt
|
||||||
@@ -752,8 +776,16 @@ export async function bulkSetManualDelivery(
|
|||||||
manualDeliveredAt: deliveredAt,
|
manualDeliveredAt: deliveredAt,
|
||||||
manualDeliveredById: session.user.id,
|
manualDeliveredById: session.user.id,
|
||||||
manualDeliveryNote: trimmedNote,
|
manualDeliveryNote: trimmedNote,
|
||||||
|
manualDeliveryUrl: uploadUrl,
|
||||||
|
manualDeliverySharedWith: sharedWith,
|
||||||
}
|
}
|
||||||
: { manualDeliveredAt: null, manualDeliveredById: null, manualDeliveryNote: null },
|
: {
|
||||||
|
manualDeliveredAt: null,
|
||||||
|
manualDeliveredById: null,
|
||||||
|
manualDeliveryNote: null,
|
||||||
|
manualDeliveryUrl: null,
|
||||||
|
manualDeliverySharedWith: null,
|
||||||
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
for (const pid of [...new Set(shots.map((s) => s.projectId))]) {
|
for (const pid of [...new Set(shots.map((s) => s.projectId))]) {
|
||||||
@@ -762,7 +794,7 @@ export async function bulkSetManualDelivery(
|
|||||||
revalidatePath(`/shot-status`);
|
revalidatePath(`/shot-status`);
|
||||||
revalidatePath(`/dashboard`);
|
revalidatePath(`/dashboard`);
|
||||||
|
|
||||||
return { success: true, updated: shots.length };
|
return { success: true as const, updated: shots.length };
|
||||||
}
|
}
|
||||||
|
|
||||||
// ── Bulk Delete Shots ─────────────────────────────────────────────────────────
|
// ── Bulk Delete Shots ─────────────────────────────────────────────────────────
|
||||||
|
|||||||
@@ -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} />;
|
||||||
|
}
|
||||||
@@ -5,12 +5,15 @@ import { BlockedQueue } from "@/components/dashboard/BlockedQueue";
|
|||||||
import { FarmStrip } from "@/components/dashboard/FarmStrip";
|
import { FarmStrip } from "@/components/dashboard/FarmStrip";
|
||||||
import { DeliveryCountdown } from "@/components/dashboard/DeliveryCountdown";
|
import { DeliveryCountdown } from "@/components/dashboard/DeliveryCountdown";
|
||||||
import { QcQueue } from "@/components/dashboard/QcQueue";
|
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 { RecentDeliveries } from "@/components/dashboard/RecentDeliveries";
|
||||||
import { WhoseCourt } from "@/components/dashboard/WhoseCourt";
|
import { WhoseCourt } from "@/components/dashboard/WhoseCourt";
|
||||||
import { ShotQueue } from "@/components/dashboard/ShotQueue";
|
import { ShotQueue } from "@/components/dashboard/ShotQueue";
|
||||||
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 {
|
import {
|
||||||
|
getAwaitingDelivery,
|
||||||
getBlockedExports,
|
getBlockedExports,
|
||||||
getDeliveryCountdown,
|
getDeliveryCountdown,
|
||||||
getFarmStatus,
|
getFarmStatus,
|
||||||
@@ -20,6 +23,7 @@ import {
|
|||||||
getRecentDeliveries,
|
getRecentDeliveries,
|
||||||
getWhoseCourt,
|
getWhoseCourt,
|
||||||
} from "@/lib/dashboard/ops";
|
} 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" };
|
||||||
@@ -37,7 +41,7 @@ async function getDashboardData(userId: string, role: string) {
|
|||||||
const isClient = role === "CLIENT";
|
const isClient = role === "CLIENT";
|
||||||
|
|
||||||
// Producers see the floor; an artist sees the failures that are theirs.
|
// Producers see the floor; an artist sees the failures that are theirs.
|
||||||
const [counts, blocked, farm, episodes, qcQueue, qcStaleHours, deliveries, court] =
|
const [counts, blocked, farm, episodes, qcQueue, qcStaleHours, deliveries, awaitingDelivery, openRequests, court] =
|
||||||
await Promise.all([
|
await Promise.all([
|
||||||
getOpsCounts(isArtist ? userId : undefined),
|
getOpsCounts(isArtist ? userId : undefined),
|
||||||
getBlockedExports(isArtist ? { artistId: userId } : {}),
|
getBlockedExports(isArtist ? { artistId: userId } : {}),
|
||||||
@@ -46,6 +50,8 @@ async function getDashboardData(userId: string, role: string) {
|
|||||||
isArtist || isClient ? [] : getQcQueue(),
|
isArtist || isClient ? [] : getQcQueue(),
|
||||||
getQcStaleHours(),
|
getQcStaleHours(),
|
||||||
isArtist || isClient ? [] : getRecentDeliveries(),
|
isArtist || isClient ? [] : getRecentDeliveries(),
|
||||||
|
isArtist || isClient ? [] : getAwaitingDelivery(),
|
||||||
|
isArtist || isClient ? [] : listDeliveryRequests({ openOnly: true }),
|
||||||
isArtist || isClient ? null : getWhoseCourt(),
|
isArtist || isClient ? null : getWhoseCourt(),
|
||||||
]);
|
]);
|
||||||
|
|
||||||
@@ -128,6 +134,8 @@ async function getDashboardData(userId: string, role: string) {
|
|||||||
qcQueue,
|
qcQueue,
|
||||||
qcStaleHours,
|
qcStaleHours,
|
||||||
deliveries,
|
deliveries,
|
||||||
|
awaitingDelivery,
|
||||||
|
openRequests,
|
||||||
court,
|
court,
|
||||||
shots,
|
shots,
|
||||||
myTasks,
|
myTasks,
|
||||||
@@ -152,6 +160,8 @@ export default async function DashboardPage() {
|
|||||||
qcQueue,
|
qcQueue,
|
||||||
qcStaleHours,
|
qcStaleHours,
|
||||||
deliveries,
|
deliveries,
|
||||||
|
awaitingDelivery,
|
||||||
|
openRequests,
|
||||||
court,
|
court,
|
||||||
shots,
|
shots,
|
||||||
myTasks,
|
myTasks,
|
||||||
@@ -171,6 +181,26 @@ export default async function DashboardPage() {
|
|||||||
|
|
||||||
{!isClient && <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 && (
|
{!isClient && (
|
||||||
<div className="space-y-3">
|
<div className="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">
|
||||||
|
|||||||
@@ -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;
|
||||||
@@ -35,14 +38,25 @@ interface PackageRow {
|
|||||||
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;
|
||||||
@@ -69,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"],
|
||||||
@@ -101,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) {
|
||||||
@@ -126,16 +166,23 @@ 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;
|
||||||
|
|
||||||
@@ -157,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"
|
||||||
>
|
>
|
||||||
@@ -183,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">
|
||||||
@@ -195,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"
|
||||||
|
variant="outline"
|
||||||
|
onClick={() => setEpisodeSelected(allIds, !allSelected)}
|
||||||
|
>
|
||||||
|
{allSelected ? "Deselect all" : "Select all"}
|
||||||
</Button>
|
</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>
|
||||||
@@ -227,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>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
@@ -238,7 +329,9 @@ 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>
|
||||||
@@ -251,10 +344,16 @@ export function DeliveriesClient({ canBuild }: { canBuild: boolean }) {
|
|||||||
<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} · ` : ""}
|
||||||
@@ -263,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" && p.kind === "EXR_DELIVERY" && (
|
{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) && (
|
||||||
@@ -282,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" />
|
||||||
@@ -294,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">
|
||||||
@@ -325,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>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -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,7 @@ interface PlaylistVersion {
|
|||||||
thumbnailUrl: string | null;
|
thumbnailUrl: string | null;
|
||||||
posterUrl: string | null;
|
posterUrl: string | null;
|
||||||
fps: number;
|
fps: number;
|
||||||
|
duration?: number | null;
|
||||||
frameCount?: number | null;
|
frameCount?: number | null;
|
||||||
hqFileUrl?: string | null;
|
hqFileUrl?: string | null;
|
||||||
handleHead?: number | null;
|
handleHead?: number | null;
|
||||||
@@ -91,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);
|
||||||
|
|
||||||
@@ -117,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);
|
||||||
@@ -139,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}`)
|
||||||
@@ -220,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>
|
||||||
@@ -272,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}
|
||||||
@@ -304,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>
|
||||||
|
|
||||||
@@ -327,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)}
|
||||||
/>
|
/>
|
||||||
))}
|
))}
|
||||||
@@ -350,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)}
|
||||||
/>
|
/>
|
||||||
))}
|
))}
|
||||||
@@ -365,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 ? (
|
||||||
@@ -415,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";
|
||||||
@@ -147,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)";
|
||||||
@@ -167,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)";
|
||||||
|
|||||||
@@ -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";
|
||||||
@@ -78,12 +80,47 @@ 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";
|
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 }>();
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
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);
|
||||||
@@ -108,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 ?? []);
|
||||||
@@ -242,6 +280,17 @@ 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 */}
|
||||||
|
|||||||
@@ -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>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -35,6 +35,9 @@ import { cn, getInitials } from "@/lib/utils";
|
|||||||
import { updateShotNotes, bulkUpdateDueDates, bulkAssignArtist, bulkDeleteShots, bulkSetManualDelivery, toggleKeyShot, toggleScaledShot } from "@/actions/shots";
|
import { updateShotNotes, bulkUpdateDueDates, bulkAssignArtist, bulkDeleteShots, bulkSetManualDelivery, toggleKeyShot, toggleScaledShot } from "@/actions/shots";
|
||||||
import { previewMovReview, buildMovReview } from "@/actions/deliveries";
|
import { previewMovReview, buildMovReview } from "@/actions/deliveries";
|
||||||
import { useToast } from "@/components/ui/use-toast";
|
import { useToast } from "@/components/ui/use-toast";
|
||||||
|
import { LogRequestDialog } from "@/components/delivery/LogRequestDialog";
|
||||||
|
import { markProjectCommentsRead } from "@/actions/comment-reads";
|
||||||
|
import { NewCommentsMarker } from "./NewCommentsMarker";
|
||||||
import {
|
import {
|
||||||
Film,
|
Film,
|
||||||
Clock,
|
Clock,
|
||||||
@@ -55,9 +58,11 @@ import {
|
|||||||
Scaling,
|
Scaling,
|
||||||
UserPlus,
|
UserPlus,
|
||||||
PackageCheck,
|
PackageCheck,
|
||||||
|
ClipboardList,
|
||||||
} from "lucide-react";
|
} from "lucide-react";
|
||||||
import { format } from "date-fns";
|
import { format } from "date-fns";
|
||||||
import { shotThumbnail } from "@/lib/shot-thumbnail";
|
import { shotThumbnail } from "@/lib/shot-thumbnail";
|
||||||
|
import type { ShotDeliverySummary } from "@/lib/render-pipeline/shot-delivery-summary";
|
||||||
|
|
||||||
type ShotRow = {
|
type ShotRow = {
|
||||||
id: string;
|
id: string;
|
||||||
@@ -77,6 +82,9 @@ type ShotRow = {
|
|||||||
manualDeliveredAt: Date | string | null;
|
manualDeliveredAt: Date | string | null;
|
||||||
manualDeliveryNote: string | null;
|
manualDeliveryNote: string | null;
|
||||||
shotVersion: string | null;
|
shotVersion: string | null;
|
||||||
|
delivery: ShotDeliverySummary;
|
||||||
|
/** Comments from others this user has not marked read; null = none. */
|
||||||
|
unreadComments: { count: number; latestAt: string } | null;
|
||||||
artist: { id: string; name: string | null; image: string | null; email: string } | null;
|
artist: { id: string; name: string | null; image: string | null; email: string } | null;
|
||||||
shotGroup: { id: string; name: string } | null;
|
shotGroup: { id: string; name: string } | null;
|
||||||
};
|
};
|
||||||
@@ -373,11 +381,17 @@ function ManualDeliveryDialog({
|
|||||||
}: {
|
}: {
|
||||||
open: boolean;
|
open: boolean;
|
||||||
onClose: () => void;
|
onClose: () => void;
|
||||||
onApply: (deliveredOn: string | null, note: string) => Promise<void>;
|
onApply: (
|
||||||
|
deliveredOn: string | null,
|
||||||
|
note: string,
|
||||||
|
evidence: { uploadUrl: string; sharedWith: string },
|
||||||
|
) => Promise<void>;
|
||||||
count: number;
|
count: number;
|
||||||
}) {
|
}) {
|
||||||
const [date, setDate] = useState("");
|
const [date, setDate] = useState("");
|
||||||
const [note, setNote] = useState("");
|
const [note, setNote] = useState("");
|
||||||
|
const [uploadUrl, setUploadUrl] = useState("");
|
||||||
|
const [sharedWith, setSharedWith] = useState("");
|
||||||
const [clearing, setClearing] = useState(false);
|
const [clearing, setClearing] = useState(false);
|
||||||
const [isPending, startTransition] = useTransition();
|
const [isPending, startTransition] = useTransition();
|
||||||
|
|
||||||
@@ -385,6 +399,8 @@ function ManualDeliveryDialog({
|
|||||||
if (open) {
|
if (open) {
|
||||||
setDate("");
|
setDate("");
|
||||||
setNote("");
|
setNote("");
|
||||||
|
setUploadUrl("");
|
||||||
|
setSharedWith("");
|
||||||
setClearing(false);
|
setClearing(false);
|
||||||
}
|
}
|
||||||
}, [open]);
|
}, [open]);
|
||||||
@@ -392,7 +408,7 @@ function ManualDeliveryDialog({
|
|||||||
const handleApply = () => {
|
const handleApply = () => {
|
||||||
if (!clearing && !date) return;
|
if (!clearing && !date) return;
|
||||||
startTransition(async () => {
|
startTransition(async () => {
|
||||||
await onApply(clearing ? null : date, note);
|
await onApply(clearing ? null : date, note, { uploadUrl, sharedWith });
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -444,6 +460,30 @@ function ManualDeliveryDialog({
|
|||||||
className="w-full rounded-md border border-zinc-700 bg-zinc-900 px-3 py-2 text-sm text-zinc-100 [color-scheme:dark] focus:border-zinc-500 focus:outline-none focus:ring-1 focus:ring-zinc-500"
|
className="w-full rounded-md border border-zinc-700 bg-zinc-900 px-3 py-2 text-sm text-zinc-100 [color-scheme:dark] focus:border-zinc-500 focus:outline-none focus:ring-1 focus:ring-zinc-500"
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
<div className="space-y-1.5">
|
||||||
|
<label className="text-xs font-medium text-zinc-400">Upload link</label>
|
||||||
|
<input
|
||||||
|
type="url"
|
||||||
|
value={uploadUrl}
|
||||||
|
onChange={(e) => setUploadUrl(e.target.value)}
|
||||||
|
placeholder="https://…"
|
||||||
|
className="w-full rounded-md border border-zinc-700 bg-zinc-900 px-3 py-2 text-sm text-zinc-100 placeholder:text-zinc-600 focus:border-zinc-500 focus:outline-none focus:ring-1 focus:ring-zinc-500"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div className="space-y-1.5">
|
||||||
|
<label className="text-xs font-medium text-zinc-400">Link sent to</label>
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
value={sharedWith}
|
||||||
|
onChange={(e) => setSharedWith(e.target.value)}
|
||||||
|
placeholder="Name, and where it was sent"
|
||||||
|
className="w-full rounded-md border border-zinc-700 bg-zinc-900 px-3 py-2 text-sm text-zinc-100 placeholder:text-zinc-600 focus:border-zinc-500 focus:outline-none focus:ring-1 focus:ring-zinc-500"
|
||||||
|
/>
|
||||||
|
<p className="text-xs text-zinc-500">
|
||||||
|
Both are needed for shots on an open delivery request; a backfill of old deliveries can leave
|
||||||
|
them blank.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
<div className="space-y-1.5">
|
<div className="space-y-1.5">
|
||||||
<label className="text-xs font-medium text-zinc-400">Note (optional)</label>
|
<label className="text-xs font-medium text-zinc-400">Note (optional)</label>
|
||||||
<Textarea
|
<Textarea
|
||||||
@@ -819,6 +859,73 @@ function ScaledShotToggle({ shot }: { shot: ShotRow }) {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const PENDING_TONE = {
|
||||||
|
progress: "text-blue-300",
|
||||||
|
waiting: "text-amber-300",
|
||||||
|
failed: "text-red-400",
|
||||||
|
} as const;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* What last reached the client for this shot, with evidence — not what was
|
||||||
|
* rendered or built — plus whatever newer is still on its way.
|
||||||
|
*/
|
||||||
|
function DeliveryCell({ delivery, shotVersion }: { delivery: ShotDeliverySummary; shotVersion: string | null }) {
|
||||||
|
const { sent, review, pending } = delivery;
|
||||||
|
if (!sent && !review && !pending) {
|
||||||
|
return <span className="text-xs text-zinc-600 italic">Never sent</span>;
|
||||||
|
}
|
||||||
|
// The panel's version moving past what was delivered means a newer version
|
||||||
|
// exists that the client has not had, even before it has been exported.
|
||||||
|
const behind = sent?.version && shotVersion && sent.version !== shotVersion && !pending;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="space-y-0.5 text-xs leading-tight">
|
||||||
|
{sent ? (
|
||||||
|
<div
|
||||||
|
className="flex items-center gap-1 whitespace-nowrap text-emerald-300"
|
||||||
|
// Who it went to stays in the tooltip: an email address swamps the column.
|
||||||
|
title={[sent.label, sent.to && `sent to ${sent.to}`, sent.note].filter(Boolean).join(" · ")}
|
||||||
|
>
|
||||||
|
<PackageCheck className="h-3 w-3 shrink-0" />
|
||||||
|
{sent.version && <span className="font-mono">{sent.version}</span>}
|
||||||
|
<span className="text-zinc-300">{format(new Date(sent.at), "d MMM")}</span>
|
||||||
|
{sent.via === "MANUAL" && <span className="text-zinc-500">· manual</span>}
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<div className="text-zinc-600 italic">Not delivered</div>
|
||||||
|
)}
|
||||||
|
{pending && (
|
||||||
|
<div className={cn("truncate", PENDING_TONE[pending.tone])} title={pending.label}>
|
||||||
|
{pending.version && <span className="font-mono">{pending.version}</span>} {pending.label}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{behind && <div className="text-zinc-500">current is <span className="font-mono">{shotVersion}</span></div>}
|
||||||
|
{review && (
|
||||||
|
<div className="truncate text-zinc-500" title={review.label}>
|
||||||
|
Review MOV <span className="font-mono">{review.version}</span> {format(new Date(review.at), "d MMM")}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** On a section header: how many of its shots have new comments, so a
|
||||||
|
* collapsed episode, scene or group still shows there is something to read. */
|
||||||
|
function SectionUnreadBadge({ shots }: { shots: ShotRow[] }) {
|
||||||
|
const flagged = shots.filter((s) => s.unreadComments).length;
|
||||||
|
if (!flagged) return null;
|
||||||
|
const label = `${flagged} shot${flagged !== 1 ? "s" : ""} with new comments`;
|
||||||
|
return (
|
||||||
|
<span
|
||||||
|
title={label}
|
||||||
|
aria-label={label}
|
||||||
|
className="flex items-center gap-0.5 rounded-full bg-orange-500 px-1.5 h-4 text-[10px] font-bold leading-none text-white shrink-0"
|
||||||
|
>
|
||||||
|
!<span className="font-medium">{flagged}</span>
|
||||||
|
</span>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
function ShotTable({
|
function ShotTable({
|
||||||
shots,
|
shots,
|
||||||
canManage,
|
canManage,
|
||||||
@@ -826,6 +933,7 @@ function ShotTable({
|
|||||||
selectedIds,
|
selectedIds,
|
||||||
onToggle,
|
onToggle,
|
||||||
onToggleAll,
|
onToggleAll,
|
||||||
|
onCommentsRead,
|
||||||
}: {
|
}: {
|
||||||
shots: ShotRow[];
|
shots: ShotRow[];
|
||||||
canManage: boolean;
|
canManage: boolean;
|
||||||
@@ -833,6 +941,7 @@ function ShotTable({
|
|||||||
selectedIds: Set<string>;
|
selectedIds: Set<string>;
|
||||||
onToggle: (id: string) => void;
|
onToggle: (id: string) => void;
|
||||||
onToggleAll: (ids: string[], checked: boolean) => void;
|
onToggleAll: (ids: string[], checked: boolean) => void;
|
||||||
|
onCommentsRead: (shotId: string) => void;
|
||||||
}) {
|
}) {
|
||||||
const allChecked = shots.length > 0 && shots.every((s) => selectedIds.has(s.id));
|
const allChecked = shots.length > 0 && shots.every((s) => selectedIds.has(s.id));
|
||||||
const someChecked = shots.some((s) => selectedIds.has(s.id));
|
const someChecked = shots.some((s) => selectedIds.has(s.id));
|
||||||
@@ -855,6 +964,7 @@ function ShotTable({
|
|||||||
<th className="text-left py-2 px-3 text-xs font-medium text-zinc-500 w-32">Status</th>
|
<th className="text-left py-2 px-3 text-xs font-medium text-zinc-500 w-32">Status</th>
|
||||||
<th className="text-left py-2 px-3 text-xs font-medium text-zinc-500 w-40">Artist</th>
|
<th className="text-left py-2 px-3 text-xs font-medium text-zinc-500 w-40">Artist</th>
|
||||||
<th className="text-left py-2 px-3 text-xs font-medium text-zinc-500 w-32">Due Date</th>
|
<th className="text-left py-2 px-3 text-xs font-medium text-zinc-500 w-32">Due Date</th>
|
||||||
|
<th className="text-left py-2 px-3 text-xs font-medium text-zinc-500 w-36">Last sent</th>
|
||||||
<th className="text-left py-2 px-3 text-xs font-medium text-zinc-500">Notes</th>
|
<th className="text-left py-2 px-3 text-xs font-medium text-zinc-500">Notes</th>
|
||||||
<th className="py-2 px-3 text-xs font-medium text-zinc-500 w-20 text-center">
|
<th className="py-2 px-3 text-xs font-medium text-zinc-500 w-20 text-center">
|
||||||
<span className="flex items-center gap-1 justify-center">
|
<span className="flex items-center gap-1 justify-center">
|
||||||
@@ -927,6 +1037,15 @@ function ShotTable({
|
|||||||
>
|
>
|
||||||
{shot.shotCode}
|
{shot.shotCode}
|
||||||
</Link>
|
</Link>
|
||||||
|
{shot.unreadComments && (
|
||||||
|
<NewCommentsMarker
|
||||||
|
shotId={shot.id}
|
||||||
|
shotCode={shot.shotCode}
|
||||||
|
count={shot.unreadComments.count}
|
||||||
|
latestAt={shot.unreadComments.latestAt}
|
||||||
|
onRead={onCommentsRead}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
{shot.shotVersion && (
|
{shot.shotVersion && (
|
||||||
<span className="font-mono text-xs text-zinc-400 shrink-0">{shot.shotVersion}</span>
|
<span className="font-mono text-xs text-zinc-400 shrink-0">{shot.shotVersion}</span>
|
||||||
)}
|
)}
|
||||||
@@ -936,15 +1055,6 @@ function ShotTable({
|
|||||||
Scaled
|
Scaled
|
||||||
</span>
|
</span>
|
||||||
)}
|
)}
|
||||||
{shot.manualDeliveredAt && (
|
|
||||||
<span
|
|
||||||
title={shot.manualDeliveryNote ?? "Delivered outside the render pipeline"}
|
|
||||||
className="flex items-center gap-1 rounded-full border border-emerald-500/30 bg-emerald-500/10 px-1.5 py-0.5 text-[10px] font-medium text-emerald-300 shrink-0"
|
|
||||||
>
|
|
||||||
<PackageCheck className="h-2.5 w-2.5" />
|
|
||||||
Delivered {format(new Date(shot.manualDeliveredAt), "d MMM")}
|
|
||||||
</span>
|
|
||||||
)}
|
|
||||||
</div>
|
</div>
|
||||||
{shot.description && (
|
{shot.description && (
|
||||||
<p className="text-xs text-zinc-500 mt-0.5 truncate max-w-[200px]">
|
<p className="text-xs text-zinc-500 mt-0.5 truncate max-w-[200px]">
|
||||||
@@ -997,6 +1107,11 @@ function ShotTable({
|
|||||||
)}
|
)}
|
||||||
</td>
|
</td>
|
||||||
|
|
||||||
|
{/* Last delivery, and anything newer on its way */}
|
||||||
|
<td className="py-2 px-3">
|
||||||
|
<DeliveryCell delivery={shot.delivery} shotVersion={shot.shotVersion} />
|
||||||
|
</td>
|
||||||
|
|
||||||
{/* Notes */}
|
{/* Notes */}
|
||||||
<td className="py-2 px-3 min-w-[220px]">
|
<td className="py-2 px-3 min-w-[220px]">
|
||||||
<NotesCell shot={shot} canManage={canManage} />
|
<NotesCell shot={shot} canManage={canManage} />
|
||||||
@@ -1023,7 +1138,7 @@ export function ShotStatusClient({
|
|||||||
projects,
|
projects,
|
||||||
selectedProjectId,
|
selectedProjectId,
|
||||||
selectedProject,
|
selectedProject,
|
||||||
shots,
|
shots: initialShots,
|
||||||
episodeDueDates,
|
episodeDueDates,
|
||||||
artists,
|
artists,
|
||||||
canManage,
|
canManage,
|
||||||
@@ -1031,6 +1146,18 @@ export function ShotStatusClient({
|
|||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
const { toast } = useToast();
|
const { toast } = useToast();
|
||||||
|
|
||||||
|
// Shots marked read here drop their "!" at once, ahead of the refresh; the
|
||||||
|
// refreshed props are authoritative, so the local set is cleared when they land.
|
||||||
|
const [readShotIds, setReadShotIds] = useState<Set<string>>(new Set());
|
||||||
|
useEffect(() => setReadShotIds(new Set()), [initialShots]);
|
||||||
|
const shots = readShotIds.size
|
||||||
|
? initialShots.map((s) => (readShotIds.has(s.id) ? { ...s, unreadComments: null } : s))
|
||||||
|
: initialShots;
|
||||||
|
const markShotReadLocally = (shotId: string) =>
|
||||||
|
setReadShotIds((prev) => new Set(prev).add(shotId));
|
||||||
|
const [unreadOnly, setUnreadOnly] = useState(false);
|
||||||
|
const [markingAllRead, startMarkingAllRead] = useTransition();
|
||||||
|
|
||||||
// Restore last selected project if no project is currently selected
|
// Restore last selected project if no project is currently selected
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!selectedProjectId) {
|
if (!selectedProjectId) {
|
||||||
@@ -1047,6 +1174,8 @@ export function ShotStatusClient({
|
|||||||
const [expandedGroups, setExpandedGroups] = useState<Set<string>>(new Set());
|
const [expandedGroups, setExpandedGroups] = useState<Set<string>>(new Set());
|
||||||
const [groupMode, setGroupMode] = useState<"flat" | "scene" | "group">("flat");
|
const [groupMode, setGroupMode] = useState<"flat" | "scene" | "group">("flat");
|
||||||
const [selectedIds, setSelectedIds] = useState<Set<string>>(new Set());
|
const [selectedIds, setSelectedIds] = useState<Set<string>>(new Set());
|
||||||
|
// Statuses picked from the summary badges; empty shows every shot.
|
||||||
|
const [statusFilter, setStatusFilter] = useState<Set<string>>(new Set());
|
||||||
|
|
||||||
// Which sections were open is restored before the scroll position: until
|
// Which sections were open is restored before the scroll position: until
|
||||||
// they are, the page is shorter and the saved offset would not fit.
|
// they are, the page is shorter and the saved offset would not fit.
|
||||||
@@ -1058,6 +1187,8 @@ export function ShotStatusClient({
|
|||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!selectedProjectId) return;
|
if (!selectedProjectId) return;
|
||||||
setExpandRestored(false);
|
setExpandRestored(false);
|
||||||
|
setStatusFilter(new Set());
|
||||||
|
setUnreadOnly(false);
|
||||||
const mode = (readStored(`shotStatus:${selectedProjectId}:groupMode`) ?? "flat") as "flat" | "scene" | "group";
|
const mode = (readStored(`shotStatus:${selectedProjectId}:groupMode`) ?? "flat") as "flat" | "scene" | "group";
|
||||||
setGroupMode(mode);
|
setGroupMode(mode);
|
||||||
setExpandedEpisodes(new Set(readStoredList(`shotStatus:${selectedProjectId}:episodeExpand`) ?? []));
|
setExpandedEpisodes(new Set(readStoredList(`shotStatus:${selectedProjectId}:episodeExpand`) ?? []));
|
||||||
@@ -1086,6 +1217,7 @@ export function ShotStatusClient({
|
|||||||
const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
|
const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
|
||||||
const [movReviewDialogOpen, setMovReviewDialogOpen] = useState(false);
|
const [movReviewDialogOpen, setMovReviewDialogOpen] = useState(false);
|
||||||
const [manualDeliveryDialogOpen, setManualDeliveryDialogOpen] = useState(false);
|
const [manualDeliveryDialogOpen, setManualDeliveryDialogOpen] = useState(false);
|
||||||
|
const [requestDialogOpen, setRequestDialogOpen] = useState(false);
|
||||||
|
|
||||||
const toggleEpisode = (ep: string) =>
|
const toggleEpisode = (ep: string) =>
|
||||||
setExpandedEpisodes((prev) => {
|
setExpandedEpisodes((prev) => {
|
||||||
@@ -1151,6 +1283,52 @@ export function ShotStatusClient({
|
|||||||
|
|
||||||
const clearSelection = () => setSelectedIds(new Set());
|
const clearSelection = () => setSelectedIds(new Set());
|
||||||
|
|
||||||
|
const toggleStatusFilter = (status: string) => {
|
||||||
|
const next = new Set(statusFilter);
|
||||||
|
next.has(status) ? next.delete(status) : next.add(status);
|
||||||
|
setStatusFilter(next);
|
||||||
|
// Bulk actions must never reach shots the filter has hidden.
|
||||||
|
if (next.size > 0) {
|
||||||
|
setSelectedIds((prev) => {
|
||||||
|
const kept = new Set<string>();
|
||||||
|
for (const s of shots)
|
||||||
|
if (prev.has(s.id) && next.has(s.status) && (!unreadOnly || s.unreadComments)) kept.add(s.id);
|
||||||
|
return kept;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const visibleShots = shots.filter(
|
||||||
|
(s) => (statusFilter.size === 0 || statusFilter.has(s.status)) && (!unreadOnly || s.unreadComments)
|
||||||
|
);
|
||||||
|
const unreadShotCount = shots.filter((s) => s.unreadComments).length;
|
||||||
|
const isFiltered = statusFilter.size > 0 || unreadOnly;
|
||||||
|
|
||||||
|
const toggleUnreadOnly = () => {
|
||||||
|
const next = !unreadOnly;
|
||||||
|
setUnreadOnly(next);
|
||||||
|
// Bulk actions must never reach shots the filter has hidden.
|
||||||
|
if (next) {
|
||||||
|
setSelectedIds((prev) => {
|
||||||
|
const kept = new Set<string>();
|
||||||
|
for (const s of shots) if (prev.has(s.id) && s.unreadComments) kept.add(s.id);
|
||||||
|
return kept;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleMarkAllRead = () =>
|
||||||
|
startMarkingAllRead(async () => {
|
||||||
|
if (!selectedProjectId) return;
|
||||||
|
try {
|
||||||
|
await markProjectCommentsRead(selectedProjectId);
|
||||||
|
setReadShotIds(new Set(shots.filter((s) => s.unreadComments).map((s) => s.id)));
|
||||||
|
setUnreadOnly(false);
|
||||||
|
} catch {
|
||||||
|
toast({ title: "Could not mark comments read", variant: "destructive" });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
const handleBulkDueDate = async (date: string, includeTasks: boolean) => {
|
const handleBulkDueDate = async (date: string, includeTasks: boolean) => {
|
||||||
try {
|
try {
|
||||||
const result = await bulkUpdateDueDates([...selectedIds], date, includeTasks);
|
const result = await bulkUpdateDueDates([...selectedIds], date, includeTasks);
|
||||||
@@ -1185,9 +1363,18 @@ export function ShotStatusClient({
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleManualDelivery = async (deliveredOn: string | null, note: string) => {
|
const handleManualDelivery = async (
|
||||||
|
deliveredOn: string | null,
|
||||||
|
note: string,
|
||||||
|
evidence: { uploadUrl: string; sharedWith: string },
|
||||||
|
) => {
|
||||||
try {
|
try {
|
||||||
const result = await bulkSetManualDelivery([...selectedIds], deliveredOn, note);
|
const result = await bulkSetManualDelivery([...selectedIds], deliveredOn, note, evidence);
|
||||||
|
if (!result.success) {
|
||||||
|
// The dialog stays open so the missing link and recipient can be added.
|
||||||
|
toast({ title: "Not marked delivered", description: result.error, variant: "destructive" });
|
||||||
|
return;
|
||||||
|
}
|
||||||
const n =`${result.updated} shot${result.updated !== 1 ? "s" : ""}`;
|
const n =`${result.updated} shot${result.updated !== 1 ? "s" : ""}`;
|
||||||
toast({ title: deliveredOn ? `${n} marked delivered` : `Manual delivery cleared on ${n}` });
|
toast({ title: deliveredOn ? `${n} marked delivered` : `Manual delivery cleared on ${n}` });
|
||||||
setManualDeliveryDialogOpen(false);
|
setManualDeliveryDialogOpen(false);
|
||||||
@@ -1227,7 +1414,7 @@ export function ShotStatusClient({
|
|||||||
const episodeGroups: [string, ShotRow[]][] = isEpisodic
|
const episodeGroups: [string, ShotRow[]][] = isEpisodic
|
||||||
? (() => {
|
? (() => {
|
||||||
const map = new Map<string, ShotRow[]>();
|
const map = new Map<string, ShotRow[]>();
|
||||||
for (const shot of shots) {
|
for (const shot of visibleShots) {
|
||||||
const key = shot.episode ?? "(No Episode)";
|
const key = shot.episode ?? "(No Episode)";
|
||||||
if (!map.has(key)) map.set(key, []);
|
if (!map.has(key)) map.set(key, []);
|
||||||
map.get(key)!.push(shot);
|
map.get(key)!.push(shot);
|
||||||
@@ -1239,7 +1426,7 @@ export function ShotStatusClient({
|
|||||||
const sceneGroups: [string, ShotRow[]][] = !isEpisodic && groupMode === "scene"
|
const sceneGroups: [string, ShotRow[]][] = !isEpisodic && groupMode === "scene"
|
||||||
? (() => {
|
? (() => {
|
||||||
const map = new Map<string, ShotRow[]>();
|
const map = new Map<string, ShotRow[]>();
|
||||||
for (const shot of shots) {
|
for (const shot of visibleShots) {
|
||||||
const key = shot.scene || "(No Scene)";
|
const key = shot.scene || "(No Scene)";
|
||||||
if (!map.has(key)) map.set(key, []);
|
if (!map.has(key)) map.set(key, []);
|
||||||
map.get(key)!.push(shot);
|
map.get(key)!.push(shot);
|
||||||
@@ -1251,7 +1438,7 @@ export function ShotStatusClient({
|
|||||||
const shotGroupGroups: [string, string, ShotRow[]][] = !isEpisodic && groupMode === "group"
|
const shotGroupGroups: [string, string, ShotRow[]][] = !isEpisodic && groupMode === "group"
|
||||||
? (() => {
|
? (() => {
|
||||||
const map = new Map<string, [string, ShotRow[]]>();
|
const map = new Map<string, [string, ShotRow[]]>();
|
||||||
for (const shot of shots) {
|
for (const shot of visibleShots) {
|
||||||
const id = shot.shotGroup?.id ?? "";
|
const id = shot.shotGroup?.id ?? "";
|
||||||
const name = shot.shotGroup?.name ?? "(No Group)";
|
const name = shot.shotGroup?.name ?? "(No Group)";
|
||||||
if (!map.has(id)) map.set(id, [name, []]);
|
if (!map.has(id)) map.set(id, [name, []]);
|
||||||
@@ -1344,16 +1531,78 @@ export function ShotStatusClient({
|
|||||||
<div className="flex flex-wrap items-center gap-2">
|
<div className="flex flex-wrap items-center gap-2">
|
||||||
{selectionCount === 0 ? (
|
{selectionCount === 0 ? (
|
||||||
<>
|
<>
|
||||||
<span className="text-xs text-zinc-500 self-center">{shots.length} shots total</span>
|
<span className="text-xs text-zinc-500 self-center">
|
||||||
|
{isFiltered ? `${visibleShots.length} of ${shots.length} shots` : `${shots.length} shots total`}
|
||||||
|
</span>
|
||||||
{Object.entries(STATUS_CONFIG).map(([key, cfg]) => {
|
{Object.entries(STATUS_CONFIG).map(([key, cfg]) => {
|
||||||
const count = statusCounts[key] ?? 0;
|
const count = statusCounts[key] ?? 0;
|
||||||
if (!count) return null;
|
if (!count) return null;
|
||||||
|
const active = statusFilter.has(key);
|
||||||
return (
|
return (
|
||||||
<Badge key={key} className={cn("gap-1 text-xs", cfg.color)}>
|
<button
|
||||||
|
key={key}
|
||||||
|
type="button"
|
||||||
|
onClick={() => toggleStatusFilter(key)}
|
||||||
|
aria-pressed={active}
|
||||||
|
title={active ? `Stop filtering by ${cfg.label}` : `Show only ${cfg.label}`}
|
||||||
|
className="rounded-full"
|
||||||
|
>
|
||||||
|
<Badge
|
||||||
|
className={cn(
|
||||||
|
"gap-1 text-xs cursor-pointer",
|
||||||
|
cfg.color,
|
||||||
|
statusFilter.size > 0 && !active && "opacity-40 hover:opacity-70",
|
||||||
|
active && "ring-1 ring-current"
|
||||||
|
)}
|
||||||
|
>
|
||||||
{count} {cfg.label}
|
{count} {cfg.label}
|
||||||
</Badge>
|
</Badge>
|
||||||
|
</button>
|
||||||
);
|
);
|
||||||
})}
|
})}
|
||||||
|
{unreadShotCount > 0 && (
|
||||||
|
<span className="flex items-center gap-1">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={toggleUnreadOnly}
|
||||||
|
aria-pressed={unreadOnly}
|
||||||
|
title={unreadOnly ? "Show all shots" : "Show only shots with new comments"}
|
||||||
|
className="rounded-full"
|
||||||
|
>
|
||||||
|
<Badge
|
||||||
|
className={cn(
|
||||||
|
"gap-1 text-xs cursor-pointer bg-orange-500/15 text-orange-300 border-orange-500/30",
|
||||||
|
unreadOnly && "ring-1 ring-current"
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
<span className="font-bold">!</span>
|
||||||
|
{unreadShotCount} with new comments
|
||||||
|
</Badge>
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={handleMarkAllRead}
|
||||||
|
disabled={markingAllRead}
|
||||||
|
className="flex items-center gap-1 text-xs text-zinc-500 hover:text-zinc-300 transition-colors disabled:opacity-50"
|
||||||
|
>
|
||||||
|
{markingAllRead ? <Loader2 className="h-3 w-3 animate-spin" /> : <CheckCircle2 className="h-3 w-3" />}
|
||||||
|
Mark all read
|
||||||
|
</button>
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
{isFiltered && (
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => {
|
||||||
|
setStatusFilter(new Set());
|
||||||
|
setUnreadOnly(false);
|
||||||
|
}}
|
||||||
|
className="flex items-center gap-1 text-xs text-zinc-500 hover:text-zinc-300 transition-colors"
|
||||||
|
>
|
||||||
|
<X className="h-3 w-3" />
|
||||||
|
Clear filter
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
</>
|
</>
|
||||||
) : (
|
) : (
|
||||||
<div className="flex items-center gap-3 rounded-lg border border-blue-500/30 bg-blue-500/10 px-4 py-2">
|
<div className="flex items-center gap-3 rounded-lg border border-blue-500/30 bg-blue-500/10 px-4 py-2">
|
||||||
@@ -1384,6 +1633,10 @@ export function ShotStatusClient({
|
|||||||
<Clapperboard className="h-3.5 w-3.5 mr-2" />
|
<Clapperboard className="h-3.5 w-3.5 mr-2" />
|
||||||
Build MOV Review Package
|
Build MOV Review Package
|
||||||
</DropdownMenuItem>
|
</DropdownMenuItem>
|
||||||
|
<DropdownMenuItem onClick={() => setRequestDialogOpen(true)}>
|
||||||
|
<ClipboardList className="h-3.5 w-3.5 mr-2" />
|
||||||
|
Log Delivery Request
|
||||||
|
</DropdownMenuItem>
|
||||||
<DropdownMenuItem onClick={() => setManualDeliveryDialogOpen(true)}>
|
<DropdownMenuItem onClick={() => setManualDeliveryDialogOpen(true)}>
|
||||||
<PackageCheck className="h-3.5 w-3.5 mr-2" />
|
<PackageCheck className="h-3.5 w-3.5 mr-2" />
|
||||||
Delivered Outside Pipeline
|
Delivered Outside Pipeline
|
||||||
@@ -1444,6 +1697,7 @@ export function ShotStatusClient({
|
|||||||
<span className="text-xs text-zinc-500 font-normal">
|
<span className="text-xs text-zinc-500 font-normal">
|
||||||
{episodeShots.length} shot{episodeShots.length !== 1 ? "s" : ""}
|
{episodeShots.length} shot{episodeShots.length !== 1 ? "s" : ""}
|
||||||
</span>
|
</span>
|
||||||
|
<SectionUnreadBadge shots={episodeShots} />
|
||||||
{epDueDate && (
|
{epDueDate && (
|
||||||
<span className={cn(
|
<span className={cn(
|
||||||
"flex items-center gap-1 text-xs",
|
"flex items-center gap-1 text-xs",
|
||||||
@@ -1463,6 +1717,7 @@ export function ShotStatusClient({
|
|||||||
projectId={selectedProjectId!}
|
projectId={selectedProjectId!}
|
||||||
selectedIds={selectedIds}
|
selectedIds={selectedIds}
|
||||||
onToggle={toggleShot}
|
onToggle={toggleShot}
|
||||||
|
onCommentsRead={markShotReadLocally}
|
||||||
onToggleAll={toggleMany}
|
onToggleAll={toggleMany}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
@@ -1502,6 +1757,7 @@ export function ShotStatusClient({
|
|||||||
<span className="text-xs text-zinc-500 font-normal">
|
<span className="text-xs text-zinc-500 font-normal">
|
||||||
{sceneShots.length} shot{sceneShots.length !== 1 ? "s" : ""}
|
{sceneShots.length} shot{sceneShots.length !== 1 ? "s" : ""}
|
||||||
</span>
|
</span>
|
||||||
|
<SectionUnreadBadge shots={sceneShots} />
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
{!collapsed && (
|
{!collapsed && (
|
||||||
@@ -1512,6 +1768,7 @@ export function ShotStatusClient({
|
|||||||
projectId={selectedProjectId!}
|
projectId={selectedProjectId!}
|
||||||
selectedIds={selectedIds}
|
selectedIds={selectedIds}
|
||||||
onToggle={toggleShot}
|
onToggle={toggleShot}
|
||||||
|
onCommentsRead={markShotReadLocally}
|
||||||
onToggleAll={toggleMany}
|
onToggleAll={toggleMany}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
@@ -1551,6 +1808,7 @@ export function ShotStatusClient({
|
|||||||
<span className="text-xs text-zinc-500 font-normal">
|
<span className="text-xs text-zinc-500 font-normal">
|
||||||
{groupShots.length} shot{groupShots.length !== 1 ? "s" : ""}
|
{groupShots.length} shot{groupShots.length !== 1 ? "s" : ""}
|
||||||
</span>
|
</span>
|
||||||
|
<SectionUnreadBadge shots={groupShots} />
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
{!collapsed && (
|
{!collapsed && (
|
||||||
@@ -1561,6 +1819,7 @@ export function ShotStatusClient({
|
|||||||
projectId={selectedProjectId!}
|
projectId={selectedProjectId!}
|
||||||
selectedIds={selectedIds}
|
selectedIds={selectedIds}
|
||||||
onToggle={toggleShot}
|
onToggle={toggleShot}
|
||||||
|
onCommentsRead={markShotReadLocally}
|
||||||
onToggleAll={toggleMany}
|
onToggleAll={toggleMany}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
@@ -1572,11 +1831,12 @@ export function ShotStatusClient({
|
|||||||
) : (
|
) : (
|
||||||
<div className="overflow-x-auto">
|
<div className="overflow-x-auto">
|
||||||
<ShotTable
|
<ShotTable
|
||||||
shots={shots}
|
shots={visibleShots}
|
||||||
canManage={canManage}
|
canManage={canManage}
|
||||||
projectId={selectedProjectId!}
|
projectId={selectedProjectId!}
|
||||||
selectedIds={selectedIds}
|
selectedIds={selectedIds}
|
||||||
onToggle={toggleShot}
|
onToggle={toggleShot}
|
||||||
|
onCommentsRead={markShotReadLocally}
|
||||||
onToggleAll={toggleMany}
|
onToggleAll={toggleMany}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
@@ -1610,6 +1870,16 @@ export function ShotStatusClient({
|
|||||||
count={selectionCount}
|
count={selectionCount}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
|
{/* A client asked for the selected shots */}
|
||||||
|
{selectedProjectId && (
|
||||||
|
<LogRequestDialog
|
||||||
|
open={requestDialogOpen}
|
||||||
|
onClose={() => setRequestDialogOpen(false)}
|
||||||
|
onLogged={clearSelection}
|
||||||
|
preset={{ projectId: selectedProjectId, shotIds: [...selectedIds] }}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
|
||||||
{/* Bulk delete dialog */}
|
{/* Bulk delete dialog */}
|
||||||
<BulkDeleteDialog
|
<BulkDeleteDialog
|
||||||
open={deleteDialogOpen}
|
open={deleteDialogOpen}
|
||||||
|
|||||||
@@ -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({
|
||||||
@@ -28,14 +30,11 @@ async function getAssignableArtists() {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
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,
|
||||||
@@ -53,13 +52,65 @@ async function getShotsForProject(projectId: string) {
|
|||||||
isScaled: true,
|
isScaled: true,
|
||||||
manualDeliveredAt: true,
|
manualDeliveredAt: true,
|
||||||
manualDeliveryNote: true,
|
manualDeliveryNote: true,
|
||||||
|
manualDeliverySharedWith: true,
|
||||||
// The shot-level version the panel burns into overlays and queueExport
|
// The shot-level version the panel burns into overlays and queueExport
|
||||||
// renders under — not the count of review Versions uploaded.
|
// renders under — not the count of review Versions uploaded.
|
||||||
shotVersion: true,
|
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({
|
||||||
@@ -73,12 +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, artists] = 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([]),
|
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;
|
||||||
|
|
||||||
|
|||||||
@@ -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 { slackNotifyNewFeedback } from "@/lib/slack";
|
import { slackNotifyNewFeedback } from "@/lib/slack";
|
||||||
|
import { notifyCommentsAdded } from "@/lib/notifications";
|
||||||
import { validateReviewToken, getOrCreateReviewUser } from "@/lib/review-auth";
|
import { validateReviewToken, getOrCreateReviewUser } from "@/lib/review-auth";
|
||||||
|
|
||||||
export async function POST(
|
export async function POST(
|
||||||
@@ -28,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;
|
||||||
@@ -70,6 +71,18 @@ export async function POST(
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
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.
|
// canEdit mirrors the GET shape — a note you just wrote is always your own.
|
||||||
return NextResponse.json({ comment: { ...comment, canEdit: true } }, { status: 201 });
|
return NextResponse.json({ comment: { ...comment, canEdit: true } }, { status: 201 });
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -48,6 +48,7 @@ export async function GET(
|
|||||||
clientCode: 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,
|
||||||
@@ -124,9 +125,13 @@ export async function GET(
|
|||||||
// code by convention ("UNG_106_010_020_cmp_TT_v004"). The internal code is
|
// 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
|
// 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.
|
// leaking it invites the client to quote it back at us.
|
||||||
shots: shots.map(({ generatedThumbnailUrl, clientCode, ...shot }) => ({
|
// 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,
|
...shot,
|
||||||
shotCode: clientShotCode({ ...shot, clientCode }),
|
shotCode: clientShotCode({ ...shot, clientCode }),
|
||||||
|
scene: clientShotCode({ ...shot, clientCode }) === shot.shotCode ? scene || null : null,
|
||||||
thumbnailUrl: shotThumbnail({ ...shot, generatedThumbnailUrl }),
|
thumbnailUrl: shotThumbnail({ ...shot, generatedThumbnailUrl }),
|
||||||
tasks: shot.tasks.map((task) => ({
|
tasks: shot.tasks.map((task) => ({
|
||||||
...task,
|
...task,
|
||||||
|
|||||||
@@ -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 });
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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 });
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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,7 +3,12 @@ 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) ─────────────────
|
||||||
//
|
//
|
||||||
@@ -11,14 +16,16 @@ import { generateHetznerPresignedUploadUrl, sanitizeFileName } from "@/lib/stora
|
|||||||
// storage folder layout: preview → videos/, thumbnail → image/,
|
// storage folder layout: preview → videos/, thumbnail → image/,
|
||||||
// metadata/log → renders/, highres (the delivery MOV) → highres/ beside the
|
// metadata/log → renders/, highres (the delivery MOV) → highres/ beside the
|
||||||
// manually uploaded High Res files.
|
// 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",
|
|
||||||
highres: "highres",
|
|
||||||
};
|
|
||||||
|
|
||||||
export async function POST(
|
export async function POST(
|
||||||
req: NextRequest,
|
req: NextRequest,
|
||||||
@@ -28,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 {
|
||||||
@@ -50,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 });
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -50,6 +50,7 @@ export async function GET(req: NextRequest) {
|
|||||||
thumbnailUrl: true,
|
thumbnailUrl: true,
|
||||||
posterUrl: true,
|
posterUrl: true,
|
||||||
fps: true,
|
fps: true,
|
||||||
|
duration: true,
|
||||||
frameCount: true,
|
frameCount: true,
|
||||||
hqFileUrl: true,
|
hqFileUrl: true,
|
||||||
handleHead: true,
|
handleHead: true,
|
||||||
@@ -90,6 +91,7 @@ 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,
|
frameCount: latest.frameCount,
|
||||||
hqFileUrl: latest.hqFileUrl,
|
hqFileUrl: latest.hqFileUrl,
|
||||||
handleHead: latest.handleHead,
|
handleHead: latest.handleHead,
|
||||||
|
|||||||
@@ -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 { 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 },
|
||||||
@@ -99,6 +126,7 @@ export async function GET(
|
|||||||
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,
|
||||||
|
|||||||
+218
-131
@@ -19,6 +19,7 @@ import {
|
|||||||
Check,
|
Check,
|
||||||
Search,
|
Search,
|
||||||
X,
|
X,
|
||||||
|
Layers,
|
||||||
} from 'lucide-react';
|
} from 'lucide-react';
|
||||||
import { cn } from '@/lib/utils';
|
import { cn } from '@/lib/utils';
|
||||||
import { Montserrat } from 'next/font/google';
|
import { Montserrat } from 'next/font/google';
|
||||||
@@ -52,6 +53,7 @@ interface ClientShot {
|
|||||||
shotCode: string;
|
shotCode: string;
|
||||||
episode: string | null;
|
episode: string | null;
|
||||||
sequence: string | null;
|
sequence: string | null;
|
||||||
|
scene: string | null;
|
||||||
description: string | null;
|
description: string | null;
|
||||||
status: string;
|
status: string;
|
||||||
thumbnailUrl: string | null;
|
thumbnailUrl: string | null;
|
||||||
@@ -136,6 +138,26 @@ function getLatestVersion(task: ClientTask): ClientVersion | undefined {
|
|||||||
return task.versions[0];
|
return task.versions[0];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const NO_SCENE = '__none__';
|
||||||
|
|
||||||
|
/** Shots split into scenes in scene order, with unscened shots last. */
|
||||||
|
function groupShotsByScene<T extends ClientShot>(shots: T[]): [string, T[]][] {
|
||||||
|
const map = new Map<string, T[]>();
|
||||||
|
for (const shot of shots) {
|
||||||
|
const key = shot.scene || NO_SCENE;
|
||||||
|
if (!map.has(key)) map.set(key, []);
|
||||||
|
map.get(key)!.push(shot);
|
||||||
|
}
|
||||||
|
return Array.from(map.entries()).sort(([a], [b]) => {
|
||||||
|
if (a === NO_SCENE) return 1;
|
||||||
|
if (b === NO_SCENE) return -1;
|
||||||
|
return a.localeCompare(b, undefined, { numeric: true });
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Collapse key for a scene, kept in the same set as the episodes. */
|
||||||
|
const sceneKey = (episode: string, scene: string) => `${episode}::${scene}`;
|
||||||
|
|
||||||
export default function ClientPortalPage({
|
export default function ClientPortalPage({
|
||||||
params,
|
params,
|
||||||
}: {
|
}: {
|
||||||
@@ -152,6 +174,7 @@ export default function ClientPortalPage({
|
|||||||
const [collapsedEpisodes, setCollapsedEpisodes] = useState<Set<string>>(new Set());
|
const [collapsedEpisodes, setCollapsedEpisodes] = useState<Set<string>>(new Set());
|
||||||
const [statusFilter, setStatusFilter] = useState<string | null>(null);
|
const [statusFilter, setStatusFilter] = useState<string | null>(null);
|
||||||
const [sortMode, setSortMode] = useState<'episode' | 'recent'>('episode');
|
const [sortMode, setSortMode] = useState<'episode' | 'recent'>('episode');
|
||||||
|
const [groupByScene, setGroupByScene] = useState(false);
|
||||||
const [searchQuery, setSearchQuery] = useState<string>('');
|
const [searchQuery, setSearchQuery] = useState<string>('');
|
||||||
const [episodeFilter, setEpisodeFilter] = useState<string | null>(null);
|
const [episodeFilter, setEpisodeFilter] = useState<string | null>(null);
|
||||||
// Filters and collapsed episodes set the page height, so the scroll
|
// Filters and collapsed episodes set the page height, so the scroll
|
||||||
@@ -194,9 +217,10 @@ export default function ClientPortalPage({
|
|||||||
if (savedState) {
|
if (savedState) {
|
||||||
sessionStorage.removeItem(STATE_KEY);
|
sessionStorage.removeItem(STATE_KEY);
|
||||||
try {
|
try {
|
||||||
const { statusFilter: sf, sortMode: sm, searchQuery: sq, episodeFilter: ef, collapsedEpisodes: ce } = JSON.parse(savedState);
|
const { statusFilter: sf, sortMode: sm, groupByScene: gs, searchQuery: sq, episodeFilter: ef, collapsedEpisodes: ce } = JSON.parse(savedState);
|
||||||
if (sf !== undefined) setStatusFilter(sf);
|
if (sf !== undefined) setStatusFilter(sf);
|
||||||
if (sm !== undefined) setSortMode(sm);
|
if (sm !== undefined) setSortMode(sm);
|
||||||
|
if (gs !== undefined) setGroupByScene(gs);
|
||||||
if (sq !== undefined) setSearchQuery(sq ?? '');
|
if (sq !== undefined) setSearchQuery(sq ?? '');
|
||||||
if (ef !== undefined) setEpisodeFilter(ef);
|
if (ef !== undefined) setEpisodeFilter(ef);
|
||||||
if (ce !== undefined) setCollapsedEpisodes(new Set(ce));
|
if (ce !== undefined) setCollapsedEpisodes(new Set(ce));
|
||||||
@@ -205,9 +229,10 @@ export default function ClientPortalPage({
|
|||||||
try {
|
try {
|
||||||
const prefs = localStorage.getItem(PREFS_KEY_PREFIX + token);
|
const prefs = localStorage.getItem(PREFS_KEY_PREFIX + token);
|
||||||
if (prefs) {
|
if (prefs) {
|
||||||
const { statusFilter: sf, sortMode: sm, searchQuery: sq, episodeFilter: ef, collapsedEpisodes: ce } = JSON.parse(prefs);
|
const { statusFilter: sf, sortMode: sm, groupByScene: gs, searchQuery: sq, episodeFilter: ef, collapsedEpisodes: ce } = JSON.parse(prefs);
|
||||||
if (sf !== undefined) setStatusFilter(sf);
|
if (sf !== undefined) setStatusFilter(sf);
|
||||||
if (sm !== undefined) setSortMode(sm);
|
if (sm !== undefined) setSortMode(sm);
|
||||||
|
if (gs !== undefined) setGroupByScene(gs);
|
||||||
if (sq !== undefined) setSearchQuery(sq ?? '');
|
if (sq !== undefined) setSearchQuery(sq ?? '');
|
||||||
if (ef !== undefined) setEpisodeFilter(ef);
|
if (ef !== undefined) setEpisodeFilter(ef);
|
||||||
if (ce !== undefined) setCollapsedEpisodes(new Set(ce));
|
if (ce !== undefined) setCollapsedEpisodes(new Set(ce));
|
||||||
@@ -226,13 +251,14 @@ export default function ClientPortalPage({
|
|||||||
JSON.stringify({
|
JSON.stringify({
|
||||||
statusFilter,
|
statusFilter,
|
||||||
sortMode,
|
sortMode,
|
||||||
|
groupByScene,
|
||||||
searchQuery,
|
searchQuery,
|
||||||
episodeFilter,
|
episodeFilter,
|
||||||
collapsedEpisodes: Array.from(collapsedEpisodes),
|
collapsedEpisodes: Array.from(collapsedEpisodes),
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
} catch { /* ignore */ }
|
} catch { /* ignore */ }
|
||||||
}, [token, statusFilter, sortMode, searchQuery, episodeFilter, collapsedEpisodes, loading]);
|
}, [token, statusFilter, sortMode, groupByScene, searchQuery, episodeFilter, collapsedEpisodes, loading]);
|
||||||
|
|
||||||
const loadProject = (t: string) => {
|
const loadProject = (t: string) => {
|
||||||
setLoading(true);
|
setLoading(true);
|
||||||
@@ -309,6 +335,8 @@ export default function ClientPortalPage({
|
|||||||
|
|
||||||
// Group shots by episode; null episode → "Shots"
|
// Group shots by episode; null episode → "Shots"
|
||||||
const isEpisodic = shots.some((s) => s.episode != null);
|
const isEpisodic = shots.some((s) => s.episode != null);
|
||||||
|
const hasScenes = shots.some((s) => s.scene);
|
||||||
|
const showScenes = groupByScene && hasScenes;
|
||||||
const shotsByEpisode = shots.reduce<Record<string, ClientShot[]>>(
|
const shotsByEpisode = shots.reduce<Record<string, ClientShot[]>>(
|
||||||
(acc, shot) => {
|
(acc, shot) => {
|
||||||
const key = shot.episode ?? 'Shots';
|
const key = shot.episode ?? 'Shots';
|
||||||
@@ -409,10 +437,11 @@ export default function ClientPortalPage({
|
|||||||
Object.entries(shotsByEpisode)
|
Object.entries(shotsByEpisode)
|
||||||
.filter(([episode]) => episodeFilter === null || episodeFilter === episode)
|
.filter(([episode]) => episodeFilter === null || episodeFilter === episode)
|
||||||
.forEach(([, epShots]) => {
|
.forEach(([, epShots]) => {
|
||||||
epShots
|
const visible = epShots
|
||||||
.map((shot) => ({ ...shot, tasks: shot.tasks.filter(taskMatchesFilter) }))
|
.map((shot) => ({ ...shot, tasks: shot.tasks.filter(taskMatchesFilter) }))
|
||||||
.filter((shot) => shot.tasks.length > 0)
|
.filter((shot) => shot.tasks.length > 0)
|
||||||
.filter(shotMatchesSearch)
|
.filter(shotMatchesSearch);
|
||||||
|
(showScenes ? groupShotsByScene(visible).flatMap(([, sc]) => sc) : visible)
|
||||||
.forEach((shot) => {
|
.forEach((shot) => {
|
||||||
shot.tasks.forEach((task) => {
|
shot.tasks.forEach((task) => {
|
||||||
const ver = getLatestVersion(task);
|
const ver = getLatestVersion(task);
|
||||||
@@ -434,6 +463,7 @@ export default function ClientPortalPage({
|
|||||||
JSON.stringify({
|
JSON.stringify({
|
||||||
statusFilter,
|
statusFilter,
|
||||||
sortMode,
|
sortMode,
|
||||||
|
groupByScene,
|
||||||
searchQuery,
|
searchQuery,
|
||||||
episodeFilter,
|
episodeFilter,
|
||||||
collapsedEpisodes: Array.from(collapsedEpisodes),
|
collapsedEpisodes: Array.from(collapsedEpisodes),
|
||||||
@@ -441,6 +471,147 @@ export default function ClientPortalPage({
|
|||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// Approved / needs changes / awaiting counts for an episode or scene header.
|
||||||
|
const statusPills = (tasks: ClientTask[]) => {
|
||||||
|
const nApproved = tasks.filter(
|
||||||
|
(t) => getLatestVersion(t)?.approvalStatus === 'APPROVED',
|
||||||
|
).length;
|
||||||
|
const nChanges = tasks.filter((t) =>
|
||||||
|
['REJECTED', 'NEEDS_CHANGES'].includes(
|
||||||
|
getLatestVersion(t)?.approvalStatus ?? '',
|
||||||
|
),
|
||||||
|
).length;
|
||||||
|
const nPending = tasks.length - nApproved - nChanges;
|
||||||
|
return (
|
||||||
|
<div className="flex items-center gap-2 shrink-0">
|
||||||
|
{nApproved > 0 && (
|
||||||
|
<span className="inline-flex items-center gap-1 px-2 py-0.5 rounded-full bg-emerald-900/40 border border-emerald-800/40 text-emerald-400 text-xs">
|
||||||
|
<CheckCircle2 className="h-3 w-3" />
|
||||||
|
{nApproved}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
{nChanges > 0 && (
|
||||||
|
<span className="inline-flex items-center gap-1 px-2 py-0.5 rounded-full bg-red-900/30 border border-red-800/30 text-red-400 text-xs">
|
||||||
|
<AlertCircle className="h-3 w-3" />
|
||||||
|
{nChanges}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
{nPending > 0 && (
|
||||||
|
<span className="inline-flex items-center gap-1 px-2 py-0.5 rounded-full bg-amber-900/20 border border-amber-800/20 text-amber-400 text-xs">
|
||||||
|
<Clock className="h-3 w-3" />
|
||||||
|
{nPending}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
const renderShot = (shot: ClientShot) => (
|
||||||
|
<div key={shot.id} className="px-5 py-4 space-y-2">
|
||||||
|
<div className="flex items-center gap-3">
|
||||||
|
{shot.thumbnailUrl && (
|
||||||
|
<div className="relative flex-shrink-0 w-32 aspect-[2.39] rounded overflow-hidden border border-zinc-800">
|
||||||
|
<Image
|
||||||
|
src={shot.thumbnailUrl}
|
||||||
|
alt={shot.shotCode}
|
||||||
|
fill
|
||||||
|
className="object-cover"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
<div className="flex items-center gap-1.5 group/shotcode">
|
||||||
|
<p className="font-mono text-sm font-semibold text-zinc-300">
|
||||||
|
{shot.shotCode}
|
||||||
|
{shot.description && (
|
||||||
|
<span className="font-sans font-normal text-zinc-500 ml-2">
|
||||||
|
{shot.description}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</p>
|
||||||
|
<button
|
||||||
|
onClick={() => copyToClipboard(shot.shotCode, `shot-${shot.id}`)}
|
||||||
|
className="shrink-0 p-0.5 rounded opacity-0 group-hover/shotcode:opacity-100 text-zinc-600 hover:text-zinc-300 transition-all"
|
||||||
|
title="Copy shot code"
|
||||||
|
>
|
||||||
|
{copiedId === `shot-${shot.id}` ? (
|
||||||
|
<Check className="h-3 w-3 text-emerald-400" />
|
||||||
|
) : (
|
||||||
|
<Copy className="h-3 w-3" />
|
||||||
|
)}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="space-y-1.5 pl-3 border-l border-zinc-800">
|
||||||
|
{shot.tasks.map((task) => {
|
||||||
|
const ver = getLatestVersion(task);
|
||||||
|
const approvalKey =
|
||||||
|
ver?.approvalStatus ?? 'PENDING_REVIEW';
|
||||||
|
const approval =
|
||||||
|
APPROVAL_STYLES[approvalKey] ??
|
||||||
|
APPROVAL_STYLES.PENDING_REVIEW;
|
||||||
|
const ApprovalIcon = approval.Icon;
|
||||||
|
return (
|
||||||
|
<Link
|
||||||
|
key={task.id}
|
||||||
|
href={ver ? `/client/${token}/review/${ver.id}` : '#'}
|
||||||
|
onClick={handleReviewClick}
|
||||||
|
className={cn(
|
||||||
|
'flex flex-wrap sm:flex-nowrap items-center gap-x-4 gap-y-2 p-3 sm:p-4 rounded-xl border transition-all group',
|
||||||
|
'bg-zinc-900 border-zinc-800 hover:border-zinc-600 hover:bg-zinc-800/70',
|
||||||
|
!ver && 'pointer-events-none opacity-40',
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
<div className="min-w-0 w-full sm:w-auto sm:flex-1">
|
||||||
|
<div className="flex items-center gap-1.5">
|
||||||
|
<p className="text-sm font-medium text-white min-w-0 break-words">
|
||||||
|
{task.title}
|
||||||
|
</p>
|
||||||
|
<button
|
||||||
|
onClick={(e) => { e.preventDefault(); e.stopPropagation(); copyToClipboard(task.title, `task-${task.id}`); }}
|
||||||
|
className="hidden sm:block shrink-0 p-0.5 rounded opacity-0 group-hover:opacity-100 text-zinc-600 hover:text-zinc-300 transition-all"
|
||||||
|
title="Copy task name"
|
||||||
|
>
|
||||||
|
{copiedId === `task-${task.id}` ? (
|
||||||
|
<Check className="h-3 w-3 text-emerald-400" />
|
||||||
|
) : (
|
||||||
|
<Copy className="h-3 w-3" />
|
||||||
|
)}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
<p className="text-xs text-zinc-500">
|
||||||
|
{TASK_TYPE_LABELS[task.type] ?? task.type}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
{ver ? (
|
||||||
|
<div className="flex items-center gap-3 shrink-0">
|
||||||
|
{ver.createdAt && (
|
||||||
|
<span className="text-xs text-zinc-600 hidden sm:block">
|
||||||
|
{formatDate(ver.createdAt)}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
<span
|
||||||
|
className={cn(
|
||||||
|
'inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full border text-xs font-medium',
|
||||||
|
approval.className,
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
<ApprovalIcon className="h-3 w-3" />
|
||||||
|
{approval.label}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<span className="text-xs text-zinc-600 shrink-0">
|
||||||
|
No versions yet
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
<ChevronRight className="h-4 w-4 text-zinc-600 group-hover:text-zinc-400 shrink-0 transition-colors ml-auto sm:ml-0" />
|
||||||
|
</Link>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div ref={pageRef} className="min-h-screen bg-zinc-950 text-white">
|
<div ref={pageRef} className="min-h-screen bg-zinc-950 text-white">
|
||||||
<header className="border-b border-zinc-800 bg-zinc-900">
|
<header className="border-b border-zinc-800 bg-zinc-900">
|
||||||
@@ -618,6 +789,20 @@ export default function ClientPortalPage({
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="flex items-center gap-2">
|
<div className="flex items-center gap-2">
|
||||||
|
{hasScenes && sortMode === 'episode' && (
|
||||||
|
<button
|
||||||
|
onClick={() => setGroupByScene((prev) => !prev)}
|
||||||
|
className={cn(
|
||||||
|
'inline-flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs font-medium border transition-all',
|
||||||
|
groupByScene
|
||||||
|
? 'bg-amber-500/10 border-amber-500/30 text-amber-400'
|
||||||
|
: 'bg-zinc-800 border-zinc-700 text-zinc-400 hover:text-zinc-300',
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
<Layers className="h-3 w-3" />
|
||||||
|
{groupByScene ? 'Grouped by Scene' : 'Group by Scene'}
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
<button
|
<button
|
||||||
onClick={() =>
|
onClick={() =>
|
||||||
setSortMode((prev) => (prev === 'episode' ? 'recent' : 'episode'))
|
setSortMode((prev) => (prev === 'episode' ? 'recent' : 'episode'))
|
||||||
@@ -778,15 +963,6 @@ export default function ClientPortalPage({
|
|||||||
|
|
||||||
const isCollapsed = collapsedEpisodes.has(episode);
|
const isCollapsed = collapsedEpisodes.has(episode);
|
||||||
const epTasks = filteredEpShots.flatMap((s) => s.tasks);
|
const epTasks = filteredEpShots.flatMap((s) => s.tasks);
|
||||||
const epApproved = epTasks.filter(
|
|
||||||
(t) => getLatestVersion(t)?.approvalStatus === 'APPROVED',
|
|
||||||
).length;
|
|
||||||
const epChanges = epTasks.filter((t) =>
|
|
||||||
['REJECTED', 'NEEDS_CHANGES'].includes(
|
|
||||||
getLatestVersion(t)?.approvalStatus ?? '',
|
|
||||||
),
|
|
||||||
).length;
|
|
||||||
const epPending = epTasks.length - epApproved - epChanges;
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div key={episode} className="rounded-xl border border-zinc-800 overflow-hidden">
|
<div key={episode} className="rounded-xl border border-zinc-800 overflow-hidden">
|
||||||
@@ -810,137 +986,48 @@ export default function ClientPortalPage({
|
|||||||
{filteredEpShots.length === 1 ? 'shot' : 'shots'}
|
{filteredEpShots.length === 1 ? 'shot' : 'shots'}
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
{/* Per-episode progress pills */}
|
{statusPills(epTasks)}
|
||||||
<div className="flex items-center gap-2 shrink-0">
|
|
||||||
{epApproved > 0 && (
|
|
||||||
<span className="inline-flex items-center gap-1 px-2 py-0.5 rounded-full bg-emerald-900/40 border border-emerald-800/40 text-emerald-400 text-xs">
|
|
||||||
<CheckCircle2 className="h-3 w-3" />
|
|
||||||
{epApproved}
|
|
||||||
</span>
|
|
||||||
)}
|
|
||||||
{epChanges > 0 && (
|
|
||||||
<span className="inline-flex items-center gap-1 px-2 py-0.5 rounded-full bg-red-900/30 border border-red-800/30 text-red-400 text-xs">
|
|
||||||
<AlertCircle className="h-3 w-3" />
|
|
||||||
{epChanges}
|
|
||||||
</span>
|
|
||||||
)}
|
|
||||||
{epPending > 0 && (
|
|
||||||
<span className="inline-flex items-center gap-1 px-2 py-0.5 rounded-full bg-amber-900/20 border border-amber-800/20 text-amber-400 text-xs">
|
|
||||||
<Clock className="h-3 w-3" />
|
|
||||||
{epPending}
|
|
||||||
</span>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
</button>
|
</button>
|
||||||
|
|
||||||
{/* Collapsible shot list */}
|
{/* Collapsible shot list */}
|
||||||
{!isCollapsed && (
|
{!isCollapsed && (
|
||||||
<div className="divide-y divide-zinc-800/60 bg-zinc-950/40">
|
<div className="divide-y divide-zinc-800/60 bg-zinc-950/40">
|
||||||
{filteredEpShots.map((shot) => (
|
{showScenes
|
||||||
<div key={shot.id} className="px-5 py-4 space-y-2">
|
? groupShotsByScene(filteredEpShots).map(([scene, sceneShots]) => {
|
||||||
<div className="flex items-center gap-3">
|
const key = sceneKey(episode, scene);
|
||||||
{shot.thumbnailUrl && (
|
const sceneCollapsed = collapsedEpisodes.has(key);
|
||||||
<div className="relative flex-shrink-0 w-32 aspect-[2.39] rounded overflow-hidden border border-zinc-800">
|
|
||||||
<Image
|
|
||||||
src={shot.thumbnailUrl}
|
|
||||||
alt={shot.shotCode}
|
|
||||||
fill
|
|
||||||
className="object-cover"
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
<div className="flex items-center gap-1.5 group/shotcode">
|
|
||||||
<p className="font-mono text-sm font-semibold text-zinc-300">
|
|
||||||
{shot.shotCode}
|
|
||||||
{shot.description && (
|
|
||||||
<span className="font-sans font-normal text-zinc-500 ml-2">
|
|
||||||
{shot.description}
|
|
||||||
</span>
|
|
||||||
)}
|
|
||||||
</p>
|
|
||||||
<button
|
|
||||||
onClick={() => copyToClipboard(shot.shotCode, `shot-${shot.id}`)}
|
|
||||||
className="shrink-0 p-0.5 rounded opacity-0 group-hover/shotcode:opacity-100 text-zinc-600 hover:text-zinc-300 transition-all"
|
|
||||||
title="Copy shot code"
|
|
||||||
>
|
|
||||||
{copiedId === `shot-${shot.id}` ? (
|
|
||||||
<Check className="h-3 w-3 text-emerald-400" />
|
|
||||||
) : (
|
|
||||||
<Copy className="h-3 w-3" />
|
|
||||||
)}
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<div className="space-y-1.5 pl-3 border-l border-zinc-800">
|
|
||||||
{shot.tasks.map((task) => {
|
|
||||||
const ver = getLatestVersion(task);
|
|
||||||
const approvalKey =
|
|
||||||
ver?.approvalStatus ?? 'PENDING_REVIEW';
|
|
||||||
const approval =
|
|
||||||
APPROVAL_STYLES[approvalKey] ??
|
|
||||||
APPROVAL_STYLES.PENDING_REVIEW;
|
|
||||||
const ApprovalIcon = approval.Icon;
|
|
||||||
return (
|
return (
|
||||||
<Link
|
<div key={key}>
|
||||||
key={task.id}
|
|
||||||
href={ver ? `/client/${token}/review/${ver.id}` : '#'}
|
|
||||||
onClick={handleReviewClick}
|
|
||||||
className={cn(
|
|
||||||
'flex flex-wrap sm:flex-nowrap items-center gap-x-4 gap-y-2 p-3 sm:p-4 rounded-xl border transition-all group',
|
|
||||||
'bg-zinc-900 border-zinc-800 hover:border-zinc-600 hover:bg-zinc-800/70',
|
|
||||||
!ver && 'pointer-events-none opacity-40',
|
|
||||||
)}
|
|
||||||
>
|
|
||||||
<div className="min-w-0 w-full sm:w-auto sm:flex-1">
|
|
||||||
<div className="flex items-center gap-1.5">
|
|
||||||
<p className="text-sm font-medium text-white min-w-0 break-words">
|
|
||||||
{task.title}
|
|
||||||
</p>
|
|
||||||
<button
|
<button
|
||||||
onClick={(e) => { e.preventDefault(); e.stopPropagation(); copyToClipboard(task.title, `task-${task.id}`); }}
|
className="w-full flex items-center gap-3 px-5 py-2.5 bg-zinc-900/60 hover:bg-zinc-800/60 transition-colors text-left"
|
||||||
className="hidden sm:block shrink-0 p-0.5 rounded opacity-0 group-hover:opacity-100 text-zinc-600 hover:text-zinc-300 transition-all"
|
onClick={() => toggleEpisode(key)}
|
||||||
title="Copy task name"
|
|
||||||
>
|
>
|
||||||
{copiedId === `task-${task.id}` ? (
|
<ChevronDown
|
||||||
<Check className="h-3 w-3 text-emerald-400" />
|
|
||||||
) : (
|
|
||||||
<Copy className="h-3 w-3" />
|
|
||||||
)}
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
<p className="text-xs text-zinc-500">
|
|
||||||
{TASK_TYPE_LABELS[task.type] ?? task.type}
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
{ver ? (
|
|
||||||
<div className="flex items-center gap-3 shrink-0">
|
|
||||||
{ver.createdAt && (
|
|
||||||
<span className="text-xs text-zinc-600 hidden sm:block">
|
|
||||||
{formatDate(ver.createdAt)}
|
|
||||||
</span>
|
|
||||||
)}
|
|
||||||
<span
|
|
||||||
className={cn(
|
className={cn(
|
||||||
'inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full border text-xs font-medium',
|
'h-3.5 w-3.5 text-zinc-500 shrink-0 transition-transform duration-200',
|
||||||
approval.className,
|
sceneCollapsed && '-rotate-90',
|
||||||
)}
|
)}
|
||||||
>
|
/>
|
||||||
<ApprovalIcon className="h-3 w-3" />
|
<div className="flex-1 min-w-0">
|
||||||
{approval.label}
|
<span className="text-xs font-medium uppercase tracking-wider text-zinc-400">
|
||||||
|
{scene === NO_SCENE ? 'No scene' : `Scene ${scene}`}
|
||||||
|
</span>
|
||||||
|
<span className="ml-3 text-xs text-zinc-600">
|
||||||
|
{sceneShots.length}{' '}
|
||||||
|
{sceneShots.length === 1 ? 'shot' : 'shots'}
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
) : (
|
{statusPills(sceneShots.flatMap((s) => s.tasks))}
|
||||||
<span className="text-xs text-zinc-600 shrink-0">
|
</button>
|
||||||
No versions yet
|
{!sceneCollapsed && (
|
||||||
</span>
|
<div className="divide-y divide-zinc-800/60 border-t border-zinc-800/60">
|
||||||
|
{sceneShots.map(renderShot)}
|
||||||
|
</div>
|
||||||
)}
|
)}
|
||||||
<ChevronRight className="h-4 w-4 text-zinc-600 group-hover:text-zinc-400 shrink-0 transition-colors ml-auto sm:ml-0" />
|
</div>
|
||||||
</Link>
|
|
||||||
);
|
);
|
||||||
})}
|
})
|
||||||
</div>
|
: filteredEpShots.map(renderShot)}
|
||||||
</div>
|
|
||||||
))}
|
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -46,6 +46,8 @@ interface Comment {
|
|||||||
timestamp: number;
|
timestamp: number;
|
||||||
text: string;
|
text: string;
|
||||||
isResolved: boolean;
|
isResolved: boolean;
|
||||||
|
/** "WHATSAPP" = client feedback sent by message and logged by the studio */
|
||||||
|
source?: string | null;
|
||||||
createdAt: string;
|
createdAt: string;
|
||||||
/** This reviewer wrote it, so they can change or remove it. Set by the API. */
|
/** This reviewer wrote it, so they can change or remove it. Set by the API. */
|
||||||
canEdit?: boolean;
|
canEdit?: boolean;
|
||||||
@@ -660,7 +662,9 @@ export default function ClientReviewPage({
|
|||||||
</AvatarFallback>
|
</AvatarFallback>
|
||||||
</Avatar>
|
</Avatar>
|
||||||
<span className="text-xs text-zinc-300 font-medium">
|
<span className="text-xs text-zinc-300 font-medium">
|
||||||
{comment.author.name ?? comment.author.email.split("@")[0]}
|
{comment.source === "WHATSAPP"
|
||||||
|
? "Client feedback"
|
||||||
|
: comment.author.name ?? comment.author.email.split("@")[0]}
|
||||||
</span>
|
</span>
|
||||||
<span className="ml-auto font-mono text-xs text-amber-400/80">
|
<span className="ml-auto font-mono text-xs text-amber-400/80">
|
||||||
{frameToTimecode(comment.frameNumber, version.fps)}
|
{frameToTimecode(comment.frameNumber, version.fps)}
|
||||||
|
|||||||
@@ -2,8 +2,15 @@
|
|||||||
|
|
||||||
import { useState } from "react";
|
import { useState } from "react";
|
||||||
import { useRouter } from "next/navigation";
|
import { useRouter } from "next/navigation";
|
||||||
import { ExternalLink, Copy, Check, Trash2, Clock, Film } from "lucide-react";
|
import { ExternalLink, Copy, Check, Trash2, Clock, Film, RotateCcw, Loader2 } from "lucide-react";
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
|
import {
|
||||||
|
DropdownMenu,
|
||||||
|
DropdownMenuContent,
|
||||||
|
DropdownMenuItem,
|
||||||
|
DropdownMenuLabel,
|
||||||
|
DropdownMenuTrigger,
|
||||||
|
} from "@/components/ui/dropdown-menu";
|
||||||
import { useToast } from "@/components/ui/use-toast";
|
import { useToast } from "@/components/ui/use-toast";
|
||||||
import { cn, formatRelativeDate } from "@/lib/utils";
|
import { cn, formatRelativeDate } from "@/lib/utils";
|
||||||
|
|
||||||
@@ -28,9 +35,36 @@ const APP_URL = process.env.NEXT_PUBLIC_APP_URL ?? "";
|
|||||||
export function ReviewSessionList({ sessions }: ReviewSessionListProps) {
|
export function ReviewSessionList({ sessions }: ReviewSessionListProps) {
|
||||||
const [copiedId, setCopiedId] = useState<string | null>(null);
|
const [copiedId, setCopiedId] = useState<string | null>(null);
|
||||||
const [deletingId, setDeletingId] = useState<string | null>(null);
|
const [deletingId, setDeletingId] = useState<string | null>(null);
|
||||||
|
const [reactivatingId, setReactivatingId] = useState<string | null>(null);
|
||||||
const { toast } = useToast();
|
const { toast } = useToast();
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
|
|
||||||
|
// Same token, new expiry — the URL the client already has starts working again.
|
||||||
|
const handleReactivate = async (id: string, days: number) => {
|
||||||
|
setReactivatingId(id);
|
||||||
|
try {
|
||||||
|
const res = await fetch(`/api/review-sessions?id=${id}`, {
|
||||||
|
method: "PATCH",
|
||||||
|
headers: { "Content-Type": "application/json" },
|
||||||
|
body: JSON.stringify({ expiresInDays: days }),
|
||||||
|
});
|
||||||
|
if (!res.ok) {
|
||||||
|
const body = await res.json().catch(() => ({}));
|
||||||
|
throw new Error(body.error);
|
||||||
|
}
|
||||||
|
toast({ title: "Review link reactivated", description: `Valid for ${days} more days — same URL.` });
|
||||||
|
router.refresh();
|
||||||
|
} catch (e) {
|
||||||
|
toast({
|
||||||
|
title: "Failed to reactivate link",
|
||||||
|
description: e instanceof Error && e.message ? e.message : undefined,
|
||||||
|
variant: "destructive",
|
||||||
|
});
|
||||||
|
} finally {
|
||||||
|
setReactivatingId(null);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
const handleCopy = async (token: string, id: string) => {
|
const handleCopy = async (token: string, id: string) => {
|
||||||
const url = `${APP_URL}/client/${token}`;
|
const url = `${APP_URL}/client/${token}`;
|
||||||
await navigator.clipboard.writeText(url);
|
await navigator.clipboard.writeText(url);
|
||||||
@@ -122,6 +156,33 @@ export function ReviewSessionList({ sessions }: ReviewSessionListProps) {
|
|||||||
<span className="text-xs text-zinc-500 mr-2">
|
<span className="text-xs text-zinc-500 mr-2">
|
||||||
{session.accessCount} view{session.accessCount !== 1 ? "s" : ""}
|
{session.accessCount} view{session.accessCount !== 1 ? "s" : ""}
|
||||||
</span>
|
</span>
|
||||||
|
{expired && (
|
||||||
|
<DropdownMenu>
|
||||||
|
<DropdownMenuTrigger asChild>
|
||||||
|
<Button
|
||||||
|
size="sm"
|
||||||
|
variant="outline"
|
||||||
|
className="h-7 px-2.5 gap-1.5 text-emerald-400 hover:bg-emerald-500/10 border-emerald-500/30"
|
||||||
|
disabled={reactivatingId === session.id}
|
||||||
|
>
|
||||||
|
{reactivatingId === session.id ? (
|
||||||
|
<Loader2 className="h-3.5 w-3.5 animate-spin" />
|
||||||
|
) : (
|
||||||
|
<RotateCcw className="h-3.5 w-3.5" />
|
||||||
|
)}
|
||||||
|
Reactivate
|
||||||
|
</Button>
|
||||||
|
</DropdownMenuTrigger>
|
||||||
|
<DropdownMenuContent align="end">
|
||||||
|
<DropdownMenuLabel className="text-xs text-zinc-500">Valid for</DropdownMenuLabel>
|
||||||
|
{[7, 14, 30, 60, 90].map((d) => (
|
||||||
|
<DropdownMenuItem key={d} onClick={() => handleReactivate(session.id, d)}>
|
||||||
|
{d} days
|
||||||
|
</DropdownMenuItem>
|
||||||
|
))}
|
||||||
|
</DropdownMenuContent>
|
||||||
|
</DropdownMenu>
|
||||||
|
)}
|
||||||
<Button
|
<Button
|
||||||
size="sm"
|
size="sm"
|
||||||
variant="outline"
|
variant="outline"
|
||||||
|
|||||||
@@ -342,8 +342,18 @@ function CommentThread({
|
|||||||
<div className="flex-1 min-w-0">
|
<div className="flex-1 min-w-0">
|
||||||
<div className="flex items-center gap-2 flex-wrap">
|
<div className="flex items-center gap-2 flex-wrap">
|
||||||
<span className="text-xs font-medium">
|
<span className="text-xs font-medium">
|
||||||
{comment.author?.name ?? comment.author?.email ?? "Deleted User"}
|
{comment.source === "WHATSAPP"
|
||||||
|
? "Client feedback"
|
||||||
|
: comment.author?.name ?? comment.author?.email ?? "Deleted User"}
|
||||||
</span>
|
</span>
|
||||||
|
{comment.source === "WHATSAPP" && (
|
||||||
|
<span
|
||||||
|
className="rounded border border-indigo-500/20 bg-indigo-500/10 px-1 py-px text-[10px] text-indigo-400"
|
||||||
|
title={`Pasted from WhatsApp by ${comment.author?.name ?? comment.author?.email ?? "someone"}`}
|
||||||
|
>
|
||||||
|
via {comment.author?.name?.split(" ")[0] ?? "WhatsApp"}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
<button
|
<button
|
||||||
className="font-mono text-xs text-primary/80 hover:text-primary hover:underline"
|
className="font-mono text-xs text-primary/80 hover:text-primary hover:underline"
|
||||||
onClick={() => onJumpToFrame(comment.frameNumber)}
|
onClick={() => onJumpToFrame(comment.frameNumber)}
|
||||||
|
|||||||
@@ -0,0 +1,88 @@
|
|||||||
|
import Link from "next/link";
|
||||||
|
import { format, formatDistanceToNowStrict } from "date-fns";
|
||||||
|
import { cn } from "@/lib/utils";
|
||||||
|
import type { AwaitingDelivery as AwaitingDeliveryRow } from "@/lib/dashboard/ops";
|
||||||
|
import type { DeliveryRequestView } from "@/lib/render-pipeline/delivery-requests";
|
||||||
|
import { DELIVERABLE_LABEL, type Deliverable } from "@/lib/render-pipeline/delivery-request-state";
|
||||||
|
|
||||||
|
const STAGE_LABEL: Record<AwaitingDeliveryRow["stage"], string> = {
|
||||||
|
AWAITING_UPLOAD: "Not uploaded",
|
||||||
|
AWAITING_SHARE: "Uploaded — link not shared",
|
||||||
|
};
|
||||||
|
|
||||||
|
const SEVERITY_STYLES: Record<AwaitingDeliveryRow["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 ROW_CLASS =
|
||||||
|
"flex items-center gap-3 border-b border-zinc-800/60 px-4 py-2.5 last:border-b-0 hover:bg-zinc-900/40";
|
||||||
|
const PILL_CLASS = "shrink-0 rounded-full border px-2 py-0.5 text-xs whitespace-nowrap";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Everything a client is owed: what they asked for that has not fully gone
|
||||||
|
* out, and built packages they do not have yet. A row only leaves this list
|
||||||
|
* when the upload location and who the link went to are on record (or a
|
||||||
|
* request is cancelled with a reason) — never because time passed or someone
|
||||||
|
* remembers doing it.
|
||||||
|
*/
|
||||||
|
export function AwaitingDelivery({
|
||||||
|
requests,
|
||||||
|
packages,
|
||||||
|
}: {
|
||||||
|
requests: DeliveryRequestView[];
|
||||||
|
packages: AwaitingDeliveryRow[];
|
||||||
|
}) {
|
||||||
|
if (requests.length === 0 && packages.length === 0) {
|
||||||
|
return (
|
||||||
|
<div className="rounded-lg border border-zinc-800 bg-card px-4 py-4 text-sm text-zinc-500">
|
||||||
|
Nothing is owed to a client.
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="rounded-lg border border-amber-500/30 bg-card overflow-hidden">
|
||||||
|
{requests.map((r) => (
|
||||||
|
<Link key={r.id} href="/pipeline/deliveries" className={ROW_CLASS}>
|
||||||
|
<div className="min-w-0 flex-1">
|
||||||
|
<div className="truncate text-[13px] text-white">
|
||||||
|
<span className="font-medium">Request #{r.requestNumber}</span>{" "}
|
||||||
|
<span className="text-zinc-300">
|
||||||
|
{DELIVERABLE_LABEL[r.deliverable as Deliverable] ?? r.deliverable}
|
||||||
|
{r.episode ? ` for ${r.episode}` : ""}
|
||||||
|
</span>{" "}
|
||||||
|
<span className="text-zinc-500">{r.projectCode}</span>
|
||||||
|
</div>
|
||||||
|
<div className="truncate text-xs text-zinc-500">
|
||||||
|
asked by {r.requestedBy} {formatDistanceToNowStrict(r.createdAt)} ago
|
||||||
|
{r.dueDate ? ` · due ${format(r.dueDate, "d MMM")}` : ""}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<span className={cn(PILL_CLASS, SEVERITY_STYLES[r.severity])}>
|
||||||
|
{r.deliveredCount} of {r.lineCount} delivered
|
||||||
|
</span>
|
||||||
|
</Link>
|
||||||
|
))}
|
||||||
|
{packages.map((p) => (
|
||||||
|
<Link key={p.id} href="/pipeline/deliveries" className={ROW_CLASS}>
|
||||||
|
<div className="min-w-0 flex-1">
|
||||||
|
<div className="truncate text-[13px] text-white">
|
||||||
|
<span className="font-mono font-medium">#{p.packageNumber}</span>{" "}
|
||||||
|
<span className="text-zinc-300">{p.name}</span>{" "}
|
||||||
|
<span className="text-zinc-500">
|
||||||
|
{p.projectCode}
|
||||||
|
{p.episode ? ` · ${p.episode}` : ""}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<div className="truncate text-xs text-zinc-500">
|
||||||
|
{p.itemCount} shot{p.itemCount === 1 ? "" : "s"} · built {formatDistanceToNowStrict(p.builtAt)} ago
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<span className={cn(PILL_CLASS, SEVERITY_STYLES[p.severity])}>{STAGE_LABEL[p.stage]}</span>
|
||||||
|
</Link>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useState } from "react";
|
||||||
|
import { useRouter } from "next/navigation";
|
||||||
|
import { Plus } from "lucide-react";
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
import { LogRequestDialog } from "@/components/delivery/LogRequestDialog";
|
||||||
|
|
||||||
|
/** The dashboard's way in to logging what a client just asked for. */
|
||||||
|
export function LogRequestButton() {
|
||||||
|
const router = useRouter();
|
||||||
|
const [open, setOpen] = useState(false);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<Button size="sm" variant="outline" onClick={() => setOpen(true)}>
|
||||||
|
<Plus className="h-3.5 w-3.5 mr-1.5" />
|
||||||
|
Log request
|
||||||
|
</Button>
|
||||||
|
<LogRequestDialog open={open} onClose={() => setOpen(false)} onLogged={() => router.refresh()} />
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,262 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useEffect, useState } from "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 { DELIVERABLES, DELIVERABLE_LABEL, parseShotCodes, type Deliverable } from "@/lib/render-pipeline/delivery-request-state";
|
||||||
|
|
||||||
|
const SELECT_CLASS = "w-full rounded-md border border-zinc-800 bg-zinc-900 px-3 py-2 text-sm text-zinc-200";
|
||||||
|
|
||||||
|
interface ProjectOption {
|
||||||
|
id: string;
|
||||||
|
name: string;
|
||||||
|
code: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Log what a client asked for. The ask arrives over chat, so this has to be
|
||||||
|
* quicker than deciding to do it later: a project, the shots, who asked.
|
||||||
|
*
|
||||||
|
* With `preset` the shots are already chosen (the shot-status selection);
|
||||||
|
* otherwise they come from an episode or a pasted list of codes.
|
||||||
|
*/
|
||||||
|
export function LogRequestDialog({
|
||||||
|
open,
|
||||||
|
onClose,
|
||||||
|
onLogged,
|
||||||
|
preset,
|
||||||
|
defaultProjectId,
|
||||||
|
}: {
|
||||||
|
open: boolean;
|
||||||
|
onClose: () => void;
|
||||||
|
onLogged: () => void;
|
||||||
|
preset?: { projectId: string; shotIds: string[] };
|
||||||
|
defaultProjectId?: string;
|
||||||
|
}) {
|
||||||
|
const { toast } = useToast();
|
||||||
|
const [projects, setProjects] = useState<ProjectOption[]>([]);
|
||||||
|
const [projectId, setProjectId] = useState("");
|
||||||
|
const [episodes, setEpisodes] = useState<{ episode: string; shotCount: number }[]>([]);
|
||||||
|
const [mode, setMode] = useState<"episode" | "codes">("episode");
|
||||||
|
const [episode, setEpisode] = useState("");
|
||||||
|
const [codes, setCodes] = useState("");
|
||||||
|
const [deliverable, setDeliverable] = useState<Deliverable>("EXR");
|
||||||
|
const [requestedBy, setRequestedBy] = useState("");
|
||||||
|
const [dueDate, setDueDate] = useState("");
|
||||||
|
const [note, setNote] = useState("");
|
||||||
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
const [saving, setSaving] = useState(false);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!open) return;
|
||||||
|
setProjectId(preset?.projectId ?? defaultProjectId ?? "");
|
||||||
|
setMode("episode");
|
||||||
|
setEpisode("");
|
||||||
|
setCodes("");
|
||||||
|
setDeliverable("EXR");
|
||||||
|
setRequestedBy("");
|
||||||
|
setDueDate("");
|
||||||
|
setNote("");
|
||||||
|
setError(null);
|
||||||
|
if (preset) return;
|
||||||
|
fetch("/api/projects")
|
||||||
|
.then((res) => (res.ok ? res.json() : { projects: [] }))
|
||||||
|
.then((body) => setProjects((body.projects ?? body) as ProjectOption[]))
|
||||||
|
.catch(() => setProjects([]));
|
||||||
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||||
|
}, [open]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
setEpisodes([]);
|
||||||
|
setEpisode("");
|
||||||
|
if (!open || preset || !projectId) return;
|
||||||
|
let stale = false;
|
||||||
|
fetch(`/api/delivery-requests/options?projectId=${encodeURIComponent(projectId)}`)
|
||||||
|
.then((res) => (res.ok ? res.json() : { episodes: [] }))
|
||||||
|
.then((body) => {
|
||||||
|
if (!stale) setEpisodes(body.episodes ?? []);
|
||||||
|
})
|
||||||
|
.catch(() => {});
|
||||||
|
return () => {
|
||||||
|
stale = true;
|
||||||
|
};
|
||||||
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||||
|
}, [open, projectId]);
|
||||||
|
|
||||||
|
const codeCount = parseShotCodes(codes).length;
|
||||||
|
const hasShots = preset ? preset.shotIds.length > 0 : mode === "episode" ? Boolean(episode) : codeCount > 0;
|
||||||
|
const canSave = Boolean(projectId) && hasShots && requestedBy.trim().length > 0 && !saving;
|
||||||
|
|
||||||
|
async function save() {
|
||||||
|
setSaving(true);
|
||||||
|
setError(null);
|
||||||
|
const res = await fetch("/api/delivery-requests", {
|
||||||
|
method: "POST",
|
||||||
|
headers: { "Content-Type": "application/json" },
|
||||||
|
body: JSON.stringify({
|
||||||
|
projectId,
|
||||||
|
...(preset ? { shotIds: preset.shotIds } : mode === "episode" ? { episode } : { shotCodes: codes }),
|
||||||
|
deliverable,
|
||||||
|
requestedBy,
|
||||||
|
dueDate: dueDate || null,
|
||||||
|
note: note || null,
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
const body = await res.json().catch(() => ({}));
|
||||||
|
setSaving(false);
|
||||||
|
if (!res.ok) {
|
||||||
|
// Shown in place rather than as a toast: an unmatched code has to be
|
||||||
|
// fixed in the text right above it.
|
||||||
|
setError(body.error ?? res.statusText);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
toast({
|
||||||
|
title: `Request #${body.request.requestNumber} logged`,
|
||||||
|
description: `${body.request.lineCount} shot${body.request.lineCount === 1 ? "" : "s"} awaiting delivery`,
|
||||||
|
});
|
||||||
|
onLogged();
|
||||||
|
onClose();
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Dialog open={open} onOpenChange={(o) => !o && !saving && onClose()}>
|
||||||
|
<DialogContent>
|
||||||
|
<DialogHeader>
|
||||||
|
<DialogTitle>Log delivery request</DialogTitle>
|
||||||
|
<DialogDescription>
|
||||||
|
What the client asked for. It stays under Awaiting delivery until every shot has been uploaded and the
|
||||||
|
link shared.
|
||||||
|
</DialogDescription>
|
||||||
|
</DialogHeader>
|
||||||
|
|
||||||
|
<div className="space-y-4">
|
||||||
|
{preset ? (
|
||||||
|
<p className="text-sm text-zinc-300">
|
||||||
|
{preset.shotIds.length} selected shot{preset.shotIds.length === 1 ? "" : "s"}
|
||||||
|
</p>
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
<div className="space-y-1.5">
|
||||||
|
<Label htmlFor="request-project">Project</Label>
|
||||||
|
<select
|
||||||
|
id="request-project"
|
||||||
|
value={projectId}
|
||||||
|
onChange={(e) => setProjectId(e.target.value)}
|
||||||
|
className={SELECT_CLASS}
|
||||||
|
>
|
||||||
|
<option value="">Select a project…</option>
|
||||||
|
{projects.map((p) => (
|
||||||
|
<option key={p.id} value={p.id}>
|
||||||
|
{p.name} ({p.code})
|
||||||
|
</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="space-y-2">
|
||||||
|
<div className="flex items-center gap-4 text-sm text-zinc-200">
|
||||||
|
<label className="flex items-center gap-2 cursor-pointer">
|
||||||
|
<input type="radio" checked={mode === "episode"} onChange={() => setMode("episode")} />
|
||||||
|
Whole episode
|
||||||
|
</label>
|
||||||
|
<label className="flex items-center gap-2 cursor-pointer">
|
||||||
|
<input type="radio" checked={mode === "codes"} onChange={() => setMode("codes")} />
|
||||||
|
Paste shot codes
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
{mode === "episode" ? (
|
||||||
|
<select
|
||||||
|
aria-label="Episode"
|
||||||
|
value={episode}
|
||||||
|
onChange={(e) => setEpisode(e.target.value)}
|
||||||
|
disabled={!projectId}
|
||||||
|
className={SELECT_CLASS}
|
||||||
|
>
|
||||||
|
<option value="">{projectId ? "Select an episode…" : "Pick a project first"}</option>
|
||||||
|
{episodes.map((e) => (
|
||||||
|
<option key={e.episode} value={e.episode}>
|
||||||
|
{e.episode} — {e.shotCount} shots
|
||||||
|
</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
) : (
|
||||||
|
<div className="space-y-1">
|
||||||
|
<Textarea
|
||||||
|
aria-label="Shot codes"
|
||||||
|
value={codes}
|
||||||
|
onChange={(e) => setCodes(e.target.value)}
|
||||||
|
rows={4}
|
||||||
|
placeholder="Paste from the client's message — our codes or theirs, any separator"
|
||||||
|
className="font-mono text-xs"
|
||||||
|
/>
|
||||||
|
<p className="text-xs text-zinc-500">
|
||||||
|
{codeCount} code{codeCount === 1 ? "" : "s"} found
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<div className="grid grid-cols-2 gap-3">
|
||||||
|
<div className="space-y-1.5">
|
||||||
|
<Label htmlFor="request-deliverable">Wanted</Label>
|
||||||
|
<select
|
||||||
|
id="request-deliverable"
|
||||||
|
value={deliverable}
|
||||||
|
onChange={(e) => setDeliverable(e.target.value as Deliverable)}
|
||||||
|
className={SELECT_CLASS}
|
||||||
|
>
|
||||||
|
{DELIVERABLES.map((d) => (
|
||||||
|
<option key={d} value={d}>
|
||||||
|
{DELIVERABLE_LABEL[d]}
|
||||||
|
</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
<div className="space-y-1.5">
|
||||||
|
<Label htmlFor="request-due">Due (optional)</Label>
|
||||||
|
<Input
|
||||||
|
id="request-due"
|
||||||
|
type="date"
|
||||||
|
value={dueDate}
|
||||||
|
onChange={(e) => setDueDate(e.target.value)}
|
||||||
|
className="[color-scheme:dark]"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="space-y-1.5">
|
||||||
|
<Label htmlFor="request-by">Asked by</Label>
|
||||||
|
<Input
|
||||||
|
id="request-by"
|
||||||
|
placeholder="Who at the client asked"
|
||||||
|
value={requestedBy}
|
||||||
|
onChange={(e) => setRequestedBy(e.target.value)}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="space-y-1.5">
|
||||||
|
<Label htmlFor="request-note">Note (optional)</Label>
|
||||||
|
<Input id="request-note" value={note} onChange={(e) => setNote(e.target.value)} />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{error && <p className="text-sm text-red-400 break-words">{error}</p>}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<DialogFooter>
|
||||||
|
<Button variant="outline" onClick={onClose} disabled={saving}>
|
||||||
|
Cancel
|
||||||
|
</Button>
|
||||||
|
<Button onClick={save} disabled={!canSave}>
|
||||||
|
Log request
|
||||||
|
</Button>
|
||||||
|
</DialogFooter>
|
||||||
|
</DialogContent>
|
||||||
|
</Dialog>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -15,6 +15,7 @@ import {
|
|||||||
ChevronLeft,
|
ChevronLeft,
|
||||||
ChevronRight,
|
ChevronRight,
|
||||||
ListTodo,
|
ListTodo,
|
||||||
|
NotebookPen,
|
||||||
CalendarRange,
|
CalendarRange,
|
||||||
BarChart2,
|
BarChart2,
|
||||||
ListVideo,
|
ListVideo,
|
||||||
@@ -32,6 +33,7 @@ import { useMobileNav } from '@/components/layout/MobileNav';
|
|||||||
const navItems = [
|
const navItems = [
|
||||||
{ href: '/dashboard', label: 'Dashboard', icon: LayoutDashboard },
|
{ href: '/dashboard', label: 'Dashboard', icon: LayoutDashboard },
|
||||||
{ href: '/projects', label: 'Projects', icon: FolderOpen },
|
{ href: '/projects', label: 'Projects', icon: FolderOpen },
|
||||||
|
{ href: '/board', label: 'Board', icon: NotebookPen, hideForClient: true },
|
||||||
{ href: '/shot-status', label: 'Shot Status', icon: BarChart2, hideForClient: true },
|
{ href: '/shot-status', label: 'Shot Status', icon: BarChart2, hideForClient: true },
|
||||||
{ href: '/playlist', label: 'Playlist', icon: ListVideo, hideForClient: true },
|
{ href: '/playlist', label: 'Playlist', icon: ListVideo, hideForClient: true },
|
||||||
{ href: '/tasks', label: 'My Tasks', icon: ListTodo, hideForClient: true },
|
{ href: '/tasks', label: 'My Tasks', icon: ListTodo, hideForClient: true },
|
||||||
|
|||||||
@@ -0,0 +1,842 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Seamless playlist playback: plays the cut of each clip back to back — no
|
||||||
|
* slate, no handles — without the gap of loading one video after another.
|
||||||
|
*
|
||||||
|
* Two <video> elements are stacked. While one plays, the other has the next
|
||||||
|
* clip loaded and parked on its cut in-point; on the cut out-point they swap.
|
||||||
|
* The out-point is caught with requestVideoFrameCallback (per presented
|
||||||
|
* frame) where the browser has it, else every animation frame.
|
||||||
|
*
|
||||||
|
* The media is never changed: the cut comes from the version's handle and
|
||||||
|
* slate metadata (lib/handles.ts), as in the review player.
|
||||||
|
*/
|
||||||
|
|
||||||
|
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||||
|
import { cn } from "@/lib/utils";
|
||||||
|
import { cutSpan, type FrameSpan, type VersionHandles } from "@/lib/handles";
|
||||||
|
import { durationToFrameCount, frameToTime, frameToTimecode, timeToFrame } from "@/lib/frame-utils";
|
||||||
|
import {
|
||||||
|
ChevronFirst,
|
||||||
|
ChevronLast,
|
||||||
|
Loader2,
|
||||||
|
Pause,
|
||||||
|
Play,
|
||||||
|
Repeat,
|
||||||
|
Volume2,
|
||||||
|
VolumeX,
|
||||||
|
} from "lucide-react";
|
||||||
|
|
||||||
|
export interface SequenceClip {
|
||||||
|
/** Version id. */
|
||||||
|
id: string;
|
||||||
|
label: string;
|
||||||
|
sublabel?: string;
|
||||||
|
url: string;
|
||||||
|
hqUrl?: string | null;
|
||||||
|
fps: number;
|
||||||
|
/** Media duration in seconds, if known — sizes the timeline before loading. */
|
||||||
|
duration?: number | null;
|
||||||
|
handles: VersionHandles;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface SequencePlayerProps {
|
||||||
|
clips: SequenceClip[];
|
||||||
|
/** Called with the clip now on screen. */
|
||||||
|
onClipChange?: (clip: SequenceClip, index: number) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
type Slot = 0 | 1;
|
||||||
|
|
||||||
|
interface Loaded {
|
||||||
|
index: number;
|
||||||
|
url: string;
|
||||||
|
/** Media frame it is parked on, once seeked. */
|
||||||
|
parkedAt?: number;
|
||||||
|
/** Its cut in-point, once the media length is known. */
|
||||||
|
cutIn?: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Seek a quarter frame in so float error can't land on the previous frame. */
|
||||||
|
const SEEK_BIAS = 0.25;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The next clip waits this many frames before its cut in (handle or slate —
|
||||||
|
* hidden anyway) so it's already running, past the stutter of a video
|
||||||
|
* starting up, when it comes on screen. Clips with less lead-in (a 1-frame
|
||||||
|
* slate, no handles) pre-roll what they have.
|
||||||
|
*/
|
||||||
|
const PREROLL_FRAMES = 4;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* How long before its pre-roll frames the next clip must start. Chrome counts
|
||||||
|
* the parked frame as shown the moment play() is called, so ~0; calibrated at
|
||||||
|
* every cut for browsers that differ.
|
||||||
|
*/
|
||||||
|
const INITIAL_START_LATENCY_MS = 0;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Hold off loading the clip after next until the cut has settled: loading
|
||||||
|
* one video while another starts playing made the incoming clip drop a frame.
|
||||||
|
*/
|
||||||
|
const PRELOAD_DELAY_MS = 300;
|
||||||
|
|
||||||
|
function estimatedSpan(clip: SequenceClip): FrameSpan {
|
||||||
|
const total =
|
||||||
|
clip.duration && clip.duration > 0
|
||||||
|
? durationToFrameCount(clip.duration, clip.fps)
|
||||||
|
: (clip.handles.frameCount ?? 0) + 1;
|
||||||
|
return cutSpan(clip.handles, total) ?? { start: 0, end: Math.max(1, total) };
|
||||||
|
}
|
||||||
|
|
||||||
|
export function SequencePlayer({ clips, onClipChange }: SequencePlayerProps) {
|
||||||
|
const videoRefs = [useRef<HTMLVideoElement>(null), useRef<HTMLVideoElement>(null)];
|
||||||
|
const loaded = useRef<[Loaded | null, Loaded | null]>([null, null]);
|
||||||
|
/** Real spans, filled in as each clip's metadata arrives. */
|
||||||
|
const spans = useRef(new Map<string, FrameSpan>());
|
||||||
|
|
||||||
|
const [active, setActive] = useState<Slot>(0);
|
||||||
|
const activeRef = useRef<Slot>(0);
|
||||||
|
const [index, setIndex] = useState(0);
|
||||||
|
const indexRef = useRef(0);
|
||||||
|
const [frame, setFrame] = useState(0); // frame within the active media
|
||||||
|
const [playing, setPlaying] = useState(false);
|
||||||
|
const playingRef = useRef(false);
|
||||||
|
const [buffering, setBuffering] = useState(false);
|
||||||
|
const [loop, setLoop] = useState(true);
|
||||||
|
const loopRef = useRef(true);
|
||||||
|
loopRef.current = loop;
|
||||||
|
const [muted, setMuted] = useState(true);
|
||||||
|
const [hq, setHq] = useState(false);
|
||||||
|
const [spanVersion, bumpSpans] = useState(0);
|
||||||
|
/** The latest load into each slot; an older load's listeners stand down. */
|
||||||
|
const slotToken = useRef<[object | null, object | null]>([null, null]);
|
||||||
|
/** The clip on screen, by id, to stay on when the clip list changes. */
|
||||||
|
const shownId = useRef<string | null>(null);
|
||||||
|
/** Bumped on every goTo so a superseded load stops acting. */
|
||||||
|
const generation = useRef(0);
|
||||||
|
/** The slot a goTo is loading into, until its clip is on screen. */
|
||||||
|
const jumpingInto = useRef<Slot | null>(null);
|
||||||
|
/** How much earlier than its pre-roll frames the next clip must start. */
|
||||||
|
const startLatency = useRef(INITIAL_START_LATENCY_MS);
|
||||||
|
|
||||||
|
const srcFor = useCallback(
|
||||||
|
(clip: SequenceClip) => (hq && clip.hqUrl ? clip.hqUrl : clip.url),
|
||||||
|
[hq]
|
||||||
|
);
|
||||||
|
const srcForRef = useRef(srcFor);
|
||||||
|
srcForRef.current = srcFor;
|
||||||
|
|
||||||
|
const spanOf = useCallback(
|
||||||
|
(i: number) => spans.current.get(clips[i].id) ?? estimatedSpan(clips[i]),
|
||||||
|
[clips]
|
||||||
|
);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Load clip `i` into a slot and park it on `frameInMedia` (default: its cut
|
||||||
|
* in, less `preroll` frames). Resolves false if superseded or the media failed.
|
||||||
|
*/
|
||||||
|
const prepare = useCallback(
|
||||||
|
(slot: Slot, i: number, frameInMedia?: number, preroll = 0): Promise<boolean> => {
|
||||||
|
const video = videoRefs[slot].current;
|
||||||
|
const clip = clips[i];
|
||||||
|
if (!video || !clip) return Promise.resolve(false);
|
||||||
|
const url = srcForRef.current(clip);
|
||||||
|
const gen = generation.current;
|
||||||
|
const token = {};
|
||||||
|
slotToken.current[slot] = token;
|
||||||
|
|
||||||
|
return new Promise<boolean>((resolve) => {
|
||||||
|
const superseded = () => {
|
||||||
|
if (slotToken.current[slot] === token) return false;
|
||||||
|
cleanup();
|
||||||
|
resolve(false);
|
||||||
|
return true;
|
||||||
|
};
|
||||||
|
const cleanup = () => {
|
||||||
|
video.removeEventListener("loadedmetadata", onMeta);
|
||||||
|
video.removeEventListener("seeked", onSeeked);
|
||||||
|
video.removeEventListener("error", onError);
|
||||||
|
};
|
||||||
|
const onError = () => {
|
||||||
|
if (superseded()) return;
|
||||||
|
cleanup();
|
||||||
|
resolve(false);
|
||||||
|
};
|
||||||
|
const onSeeked = () => {
|
||||||
|
if (superseded()) return;
|
||||||
|
cleanup();
|
||||||
|
resolve(gen === generation.current);
|
||||||
|
};
|
||||||
|
const seek = () => {
|
||||||
|
const total = durationToFrameCount(video.duration, clip.fps);
|
||||||
|
const span = cutSpan(clip.handles, total);
|
||||||
|
if (span) spans.current.set(clip.id, span);
|
||||||
|
const cutIn = span?.start ?? 0;
|
||||||
|
const target = frameInMedia ?? Math.max(0, cutIn - preroll);
|
||||||
|
const entry = loaded.current[slot];
|
||||||
|
if (entry) {
|
||||||
|
entry.cutIn = cutIn;
|
||||||
|
entry.parkedAt = target;
|
||||||
|
}
|
||||||
|
video.addEventListener("seeked", onSeeked);
|
||||||
|
video.currentTime = frameToTime(target + SEEK_BIAS, clip.fps);
|
||||||
|
};
|
||||||
|
const onMeta = () => {
|
||||||
|
if (superseded()) return;
|
||||||
|
video.removeEventListener("loadedmetadata", onMeta);
|
||||||
|
bumpSpans((n) => n + 1);
|
||||||
|
seek();
|
||||||
|
};
|
||||||
|
|
||||||
|
video.addEventListener("error", onError);
|
||||||
|
const current = loaded.current[slot];
|
||||||
|
if (current && current.url === url && video.readyState >= 1) {
|
||||||
|
loaded.current[slot] = { index: i, url };
|
||||||
|
seek();
|
||||||
|
} else {
|
||||||
|
loaded.current[slot] = { index: i, url };
|
||||||
|
video.addEventListener("loadedmetadata", onMeta);
|
||||||
|
video.src = url;
|
||||||
|
video.load();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
},
|
||||||
|
// videoRefs are stable refs
|
||||||
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||||
|
[clips]
|
||||||
|
);
|
||||||
|
|
||||||
|
const nextIndex = useCallback(
|
||||||
|
(i: number) => (i + 1 < clips.length ? i + 1 : loopRef.current ? 0 : null),
|
||||||
|
[clips.length]
|
||||||
|
);
|
||||||
|
|
||||||
|
const preloadNext = useCallback(
|
||||||
|
(fromIndex: number) => {
|
||||||
|
const n = nextIndex(fromIndex);
|
||||||
|
if (n == null) return;
|
||||||
|
const standby = (1 - activeRef.current) as Slot;
|
||||||
|
// A jump is loading its clip there; it preloads the next one itself
|
||||||
|
// once it's on screen. Loading over it would leave the screen black.
|
||||||
|
if (jumpingInto.current === standby) return;
|
||||||
|
void prepare(standby, n, undefined, PREROLL_FRAMES);
|
||||||
|
},
|
||||||
|
[nextIndex, prepare]
|
||||||
|
);
|
||||||
|
|
||||||
|
const show = useCallback(
|
||||||
|
(slot: Slot, i: number) => {
|
||||||
|
activeRef.current = slot;
|
||||||
|
indexRef.current = i;
|
||||||
|
setActive(slot);
|
||||||
|
setIndex(i);
|
||||||
|
// Straight on the DOM, not via a re-render: a render later, the outgoing
|
||||||
|
// clip would already have painted a frame past its cut.
|
||||||
|
const other = videoRefs[1 - slot].current;
|
||||||
|
if (other) {
|
||||||
|
other.pause();
|
||||||
|
other.muted = true;
|
||||||
|
other.style.opacity = "0";
|
||||||
|
}
|
||||||
|
const video = videoRefs[slot].current;
|
||||||
|
if (video) {
|
||||||
|
video.style.opacity = "1";
|
||||||
|
video.muted = muted;
|
||||||
|
setFrame(timeToFrame(video.currentTime, clips[i].fps));
|
||||||
|
}
|
||||||
|
shownId.current = clips[i].id;
|
||||||
|
onClipChange?.(clips[i], i);
|
||||||
|
},
|
||||||
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||||
|
[clips, muted, onClipChange]
|
||||||
|
);
|
||||||
|
|
||||||
|
/** Jump to clip `i` (at a media frame, default its cut in). */
|
||||||
|
const goTo = useCallback(
|
||||||
|
async (i: number, frameInMedia?: number, autoplay = playingRef.current) => {
|
||||||
|
if (!clips[i]) return;
|
||||||
|
generation.current += 1;
|
||||||
|
const gen = generation.current;
|
||||||
|
// Always via the hidden slot: the picture on screen stays put while the
|
||||||
|
// clip loads (loading into the visible slot flashed its slate), and when
|
||||||
|
// it already holds this clip — usually the next one — it's just a seek.
|
||||||
|
// A seek within the clip on screen stays where it is.
|
||||||
|
const onScreen = loaded.current[activeRef.current];
|
||||||
|
const slot =
|
||||||
|
onScreen?.index === i && onScreen.url === srcForRef.current(clips[i])
|
||||||
|
? activeRef.current
|
||||||
|
: ((1 - activeRef.current) as Slot);
|
||||||
|
videoRefs[0].current?.pause();
|
||||||
|
videoRefs[1].current?.pause();
|
||||||
|
setBuffering(true);
|
||||||
|
jumpingInto.current = slot;
|
||||||
|
const ok = await prepare(slot, i, frameInMedia);
|
||||||
|
if (gen !== generation.current) return;
|
||||||
|
jumpingInto.current = null;
|
||||||
|
setBuffering(false);
|
||||||
|
if (!ok) return;
|
||||||
|
show(slot, i);
|
||||||
|
if (autoplay) {
|
||||||
|
playingRef.current = true;
|
||||||
|
setPlaying(true);
|
||||||
|
videoRefs[slot].current?.play().catch(() => {});
|
||||||
|
}
|
||||||
|
preloadNext(i);
|
||||||
|
},
|
||||||
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||||
|
[clips, prepare, show, preloadNext]
|
||||||
|
);
|
||||||
|
|
||||||
|
/** Put the (already playing) standby clip on screen. */
|
||||||
|
const cutTo = useCallback(
|
||||||
|
(slot: Slot, i: number) => {
|
||||||
|
videoRefs[1 - slot].current?.pause();
|
||||||
|
show(slot, i);
|
||||||
|
setTimeout(() => {
|
||||||
|
if (indexRef.current === i && activeRef.current === slot) preloadNext(i);
|
||||||
|
}, PRELOAD_DELAY_MS);
|
||||||
|
},
|
||||||
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||||
|
[show, preloadNext]
|
||||||
|
);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Cut to the next clip now — the fallback when it wasn't pre-rolled (no
|
||||||
|
* requestVideoFrameCallback, or it wasn't loaded in time).
|
||||||
|
*/
|
||||||
|
const advance = useCallback(async () => {
|
||||||
|
const i = indexRef.current;
|
||||||
|
const n = nextIndex(i);
|
||||||
|
const slot = activeRef.current;
|
||||||
|
const current = videoRefs[slot].current;
|
||||||
|
if (n == null) {
|
||||||
|
// End of the playlist: hold the last frame of the cut.
|
||||||
|
current?.pause();
|
||||||
|
if (current) current.currentTime = frameToTime(spanOf(i).end - 1 + SEEK_BIAS, clips[i].fps);
|
||||||
|
playingRef.current = false;
|
||||||
|
setPlaying(false);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const standby = (1 - slot) as Slot;
|
||||||
|
const ready = loaded.current[standby];
|
||||||
|
const standbyVideo = videoRefs[standby].current;
|
||||||
|
if (ready?.index === n && ready.cutIn != null && standbyVideo && standbyVideo.readyState >= 2) {
|
||||||
|
// Parked short of its cut for a pre-roll: bring it up to the cut in.
|
||||||
|
if (ready.parkedAt !== ready.cutIn || standbyVideo.seeking) {
|
||||||
|
const ok = await prepare(standby, n);
|
||||||
|
if (!ok || !playingRef.current || indexRef.current !== i) return;
|
||||||
|
}
|
||||||
|
standbyVideo.play().catch(() => {});
|
||||||
|
cutTo(standby, n);
|
||||||
|
} else {
|
||||||
|
// Next clip not ready (slow network): load it, then carry on.
|
||||||
|
void goTo(n, undefined, true);
|
||||||
|
}
|
||||||
|
}, [nextIndex, spanOf, clips, prepare, cutTo, goTo]);
|
||||||
|
|
||||||
|
// Playing: watch the active clip for its out-point, pre-roll the next one
|
||||||
|
// so it arrives on its cut in-point as the out-point passes, and keep the
|
||||||
|
// frame readout live.
|
||||||
|
//
|
||||||
|
// A frame is reported as it goes to the screen, so waiting to see the first
|
||||||
|
// handle frame would mean it had already been shown. Instead the active
|
||||||
|
// clip pauses on the last frame of its cut (holding it, never decoding the
|
||||||
|
// handle), and the cut happens when the next clip reports its cut in-point.
|
||||||
|
useEffect(() => {
|
||||||
|
if (!playing) return;
|
||||||
|
const video = videoRefs[active].current;
|
||||||
|
const clip = clips[index];
|
||||||
|
if (!video || !clip) return;
|
||||||
|
const end = spanOf(index).end;
|
||||||
|
const n = nextIndex(index);
|
||||||
|
const standbySlot = (1 - active) as Slot;
|
||||||
|
const standbyVideo = videoRefs[standbySlot].current;
|
||||||
|
const hasRvfc = "requestVideoFrameCallback" in HTMLVideoElement.prototype;
|
||||||
|
|
||||||
|
const armedGeneration = generation.current;
|
||||||
|
let disposed = false;
|
||||||
|
let held = false; // active clip paused on its last cut frame
|
||||||
|
let prerolling = false;
|
||||||
|
let didCut = false;
|
||||||
|
let handle = 0;
|
||||||
|
let standbyHandle = 0;
|
||||||
|
let cutTimer: ReturnType<typeof setTimeout> | undefined;
|
||||||
|
let prerollTimer: ReturnType<typeof setTimeout> | undefined;
|
||||||
|
|
||||||
|
const standbyReady = () => {
|
||||||
|
const l = loaded.current[standbySlot];
|
||||||
|
return n != null &&
|
||||||
|
hasRvfc &&
|
||||||
|
standbyVideo &&
|
||||||
|
l?.index === n &&
|
||||||
|
l.cutIn != null &&
|
||||||
|
l.parkedAt != null &&
|
||||||
|
l.parkedAt <= l.cutIn &&
|
||||||
|
standbyVideo.readyState >= 2 &&
|
||||||
|
!standbyVideo.seeking
|
||||||
|
? { l: l as Required<Loaded>, sv: standbyVideo }
|
||||||
|
: null;
|
||||||
|
};
|
||||||
|
|
||||||
|
/** `cutAt`: when the next clip's cut in-point should reach the screen. */
|
||||||
|
const startPreroll = (r: NonNullable<ReturnType<typeof standbyReady>>, cutAt: number) => {
|
||||||
|
if (disposed || prerolling || standbyReady() == null) return;
|
||||||
|
prerolling = true;
|
||||||
|
const onStandbyFrame = (_now: number, meta: VideoFrameCallbackMetadata) => {
|
||||||
|
if (disposed) return;
|
||||||
|
if (timeToFrame(meta.mediaTime, clips[r.l.index].fps) >= r.l.cutIn) {
|
||||||
|
// Calibrate: arrived early → start later next time, and vice versa.
|
||||||
|
const error = meta.expectedDisplayTime - cutAt;
|
||||||
|
if (Math.abs(error) < 250) {
|
||||||
|
startLatency.current = Math.min(
|
||||||
|
300,
|
||||||
|
Math.max(-100, startLatency.current + error / 2)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
didCut = true;
|
||||||
|
cutTo(standbySlot, r.l.index);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
standbyHandle = r.sv.requestVideoFrameCallback(onStandbyFrame);
|
||||||
|
};
|
||||||
|
standbyHandle = r.sv.requestVideoFrameCallback(onStandbyFrame);
|
||||||
|
r.sv.play().catch(() => {});
|
||||||
|
};
|
||||||
|
|
||||||
|
const check = (mediaTime: number, shownAt: number) => {
|
||||||
|
const f = timeToFrame(mediaTime, clip.fps);
|
||||||
|
setFrame(f);
|
||||||
|
const frameMs = 1000 / clip.fps / (video.playbackRate || 1);
|
||||||
|
const now = performance.now();
|
||||||
|
// When the out-point would reach the screen.
|
||||||
|
const cutAt = shownAt + (end - f) * frameMs;
|
||||||
|
|
||||||
|
// Start the next clip `lead` before the cut — on a timer, as frame
|
||||||
|
// callbacks only come once a frame.
|
||||||
|
if (!prerolling && prerollTimer === undefined) {
|
||||||
|
const r = standbyReady();
|
||||||
|
if (r) {
|
||||||
|
const lead =
|
||||||
|
startLatency.current + (r.l.cutIn - r.l.parkedAt) * (1000 / clips[r.l.index].fps);
|
||||||
|
const startIn = cutAt - now - lead;
|
||||||
|
if (startIn < frameMs * 2) {
|
||||||
|
prerollTimer = setTimeout(() => startPreroll(r, cutAt), Math.max(0, startIn));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (f >= end - 1) {
|
||||||
|
held = true;
|
||||||
|
video.pause();
|
||||||
|
// Not pre-rolled: cut on time by hand. Pre-rolled: the next clip cuts
|
||||||
|
// itself in; this only catches it never arriving.
|
||||||
|
const wait =
|
||||||
|
Math.max(0, cutAt - now) + (prerolling || prerollTimer !== undefined ? 500 : 0);
|
||||||
|
cutTimer = setTimeout(() => {
|
||||||
|
if (!disposed && !didCut && playingRef.current) void advance();
|
||||||
|
}, wait);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
};
|
||||||
|
|
||||||
|
if (hasRvfc) {
|
||||||
|
const onFrame = (_now: number, meta: VideoFrameCallbackMetadata) => {
|
||||||
|
if (disposed || check(meta.mediaTime, meta.expectedDisplayTime)) return;
|
||||||
|
handle = video.requestVideoFrameCallback(onFrame);
|
||||||
|
};
|
||||||
|
handle = video.requestVideoFrameCallback(onFrame);
|
||||||
|
} else {
|
||||||
|
const tick = () => {
|
||||||
|
if (disposed || check(video.currentTime, performance.now())) return;
|
||||||
|
handle = requestAnimationFrame(tick);
|
||||||
|
};
|
||||||
|
handle = requestAnimationFrame(tick);
|
||||||
|
}
|
||||||
|
// Media that ends before the computed out-point (duration rounding).
|
||||||
|
const onEnded = () => {
|
||||||
|
if (!held && !prerolling) {
|
||||||
|
held = true;
|
||||||
|
void advance();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
video.addEventListener("ended", onEnded);
|
||||||
|
|
||||||
|
return () => {
|
||||||
|
disposed = true;
|
||||||
|
clearTimeout(cutTimer);
|
||||||
|
clearTimeout(prerollTimer);
|
||||||
|
video.removeEventListener("ended", onEnded);
|
||||||
|
if (hasRvfc) {
|
||||||
|
video.cancelVideoFrameCallback(handle);
|
||||||
|
standbyVideo?.cancelVideoFrameCallback(standbyHandle);
|
||||||
|
} else {
|
||||||
|
cancelAnimationFrame(handle);
|
||||||
|
}
|
||||||
|
// Stopped mid pre-roll (paused): park the next clip again — unless a
|
||||||
|
// jump has taken over, and the standby may now be the clip on screen.
|
||||||
|
if (
|
||||||
|
prerolling &&
|
||||||
|
!didCut &&
|
||||||
|
standbyVideo &&
|
||||||
|
n != null &&
|
||||||
|
generation.current === armedGeneration &&
|
||||||
|
activeRef.current !== standbySlot
|
||||||
|
) {
|
||||||
|
standbyVideo.pause();
|
||||||
|
void prepare(standbySlot, n, undefined, PREROLL_FRAMES);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
// spans are read live; re-arm when the active clip changes
|
||||||
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||||
|
}, [playing, active, index, clips, advance, cutTo]);
|
||||||
|
|
||||||
|
// A new clip list: stay on the clip on screen if it's still in the list
|
||||||
|
// (a shot checked or unchecked mid-review), else start from the first.
|
||||||
|
useEffect(() => {
|
||||||
|
if (!clips.length) return;
|
||||||
|
const video = videoRefs[activeRef.current].current;
|
||||||
|
const keep = shownId.current ? clips.findIndex((c) => c.id === shownId.current) : -1;
|
||||||
|
loaded.current = [null, null];
|
||||||
|
if (keep >= 0 && video) {
|
||||||
|
void goTo(keep, timeToFrame(video.currentTime, clips[keep].fps));
|
||||||
|
} else {
|
||||||
|
playingRef.current = false;
|
||||||
|
setPlaying(false);
|
||||||
|
void goTo(0, undefined, false);
|
||||||
|
}
|
||||||
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||||
|
}, [clips]);
|
||||||
|
|
||||||
|
// Quality switch: reload the current clip at the same frame.
|
||||||
|
const lastHq = useRef(hq);
|
||||||
|
useEffect(() => {
|
||||||
|
if (lastHq.current === hq) return;
|
||||||
|
lastHq.current = hq;
|
||||||
|
const video = videoRefs[activeRef.current].current;
|
||||||
|
const clip = clips[indexRef.current];
|
||||||
|
if (!video || !clip) return;
|
||||||
|
const at = timeToFrame(video.currentTime, clip.fps);
|
||||||
|
loaded.current = [null, null];
|
||||||
|
void goTo(indexRef.current, at);
|
||||||
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||||
|
}, [hq]);
|
||||||
|
|
||||||
|
// Loop toggled: what comes after the last clip changed, so reload the
|
||||||
|
// standby. Not on mount — the first goTo is loading then.
|
||||||
|
const lastLoop = useRef(loop);
|
||||||
|
useEffect(() => {
|
||||||
|
if (lastLoop.current === loop) return;
|
||||||
|
lastLoop.current = loop;
|
||||||
|
if (clips.length) preloadNext(indexRef.current);
|
||||||
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||||
|
}, [loop]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const video = videoRefs[activeRef.current].current;
|
||||||
|
if (video) video.muted = muted;
|
||||||
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||||
|
}, [muted]);
|
||||||
|
|
||||||
|
// ── Transport ──────────────────────────────────────────────────────────────
|
||||||
|
const play = useCallback(() => {
|
||||||
|
const i = indexRef.current;
|
||||||
|
const video = videoRefs[activeRef.current].current;
|
||||||
|
const clip = clips[i];
|
||||||
|
if (!video || !clip) return;
|
||||||
|
const span = spanOf(i);
|
||||||
|
const f = timeToFrame(video.currentTime, clip.fps);
|
||||||
|
// Parked on the last frame of the cut (paused at the cut, or at the end
|
||||||
|
// of the playlist): carry on from the next clip, or start over.
|
||||||
|
if (f >= span.end - 1) {
|
||||||
|
if (nextIndex(i) == null) {
|
||||||
|
void goTo(0, undefined, true);
|
||||||
|
} else {
|
||||||
|
playingRef.current = true;
|
||||||
|
setPlaying(true);
|
||||||
|
void advance();
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (f < span.start || f >= span.end) {
|
||||||
|
video.currentTime = frameToTime(span.start + SEEK_BIAS, clip.fps);
|
||||||
|
}
|
||||||
|
playingRef.current = true;
|
||||||
|
setPlaying(true);
|
||||||
|
video.play().catch(() => {});
|
||||||
|
}, [clips, spanOf, nextIndex, goTo, advance]);
|
||||||
|
|
||||||
|
const pause = useCallback(() => {
|
||||||
|
playingRef.current = false;
|
||||||
|
setPlaying(false);
|
||||||
|
videoRefs[activeRef.current].current?.pause();
|
||||||
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const toggle = useCallback(() => (playingRef.current ? pause() : play()), [play, pause]);
|
||||||
|
|
||||||
|
/** Step within the cut; stepping past either end moves to the next/previous clip. */
|
||||||
|
const step = useCallback(
|
||||||
|
(delta: number) => {
|
||||||
|
pause();
|
||||||
|
const i = indexRef.current;
|
||||||
|
const video = videoRefs[activeRef.current].current;
|
||||||
|
const clip = clips[i];
|
||||||
|
if (!video || !clip) return;
|
||||||
|
const span = spanOf(i);
|
||||||
|
const f = timeToFrame(video.currentTime, clip.fps) + delta;
|
||||||
|
if (f >= span.end) {
|
||||||
|
if (i + 1 < clips.length) void goTo(i + 1, undefined, false);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (f < span.start) {
|
||||||
|
if (i > 0) void goTo(i - 1, spanOf(i - 1).end - 1, false);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
video.currentTime = frameToTime(f + SEEK_BIAS, clip.fps);
|
||||||
|
setFrame(f);
|
||||||
|
},
|
||||||
|
[clips, spanOf, goTo, pause]
|
||||||
|
);
|
||||||
|
|
||||||
|
const prevClip = useCallback(() => {
|
||||||
|
const i = indexRef.current;
|
||||||
|
const video = videoRefs[activeRef.current].current;
|
||||||
|
const clip = clips[i];
|
||||||
|
// Like a transport: first press returns to the head of this clip.
|
||||||
|
if (video && clip && timeToFrame(video.currentTime, clip.fps) > spanOf(i).start + 2) {
|
||||||
|
void goTo(i);
|
||||||
|
} else {
|
||||||
|
void goTo(Math.max(0, i - 1));
|
||||||
|
}
|
||||||
|
}, [clips, spanOf, goTo]);
|
||||||
|
|
||||||
|
const nextClip = useCallback(() => {
|
||||||
|
const n = nextIndex(indexRef.current);
|
||||||
|
if (n != null) void goTo(n);
|
||||||
|
}, [nextIndex, goTo]);
|
||||||
|
|
||||||
|
// Keyboard
|
||||||
|
useEffect(() => {
|
||||||
|
const onKey = (e: KeyboardEvent) => {
|
||||||
|
const t = e.target as HTMLElement | null;
|
||||||
|
if (t && (t.tagName === "INPUT" || t.tagName === "TEXTAREA" || t.isContentEditable)) return;
|
||||||
|
switch (e.key) {
|
||||||
|
case " ":
|
||||||
|
case "k":
|
||||||
|
case "K":
|
||||||
|
e.preventDefault();
|
||||||
|
toggle();
|
||||||
|
break;
|
||||||
|
case "ArrowRight":
|
||||||
|
e.preventDefault();
|
||||||
|
step(1);
|
||||||
|
break;
|
||||||
|
case "ArrowLeft":
|
||||||
|
e.preventDefault();
|
||||||
|
step(-1);
|
||||||
|
break;
|
||||||
|
case "ArrowDown":
|
||||||
|
e.preventDefault();
|
||||||
|
nextClip();
|
||||||
|
break;
|
||||||
|
case "ArrowUp":
|
||||||
|
e.preventDefault();
|
||||||
|
prevClip();
|
||||||
|
break;
|
||||||
|
case "Home":
|
||||||
|
e.preventDefault();
|
||||||
|
void goTo(0);
|
||||||
|
break;
|
||||||
|
case "m":
|
||||||
|
case "M":
|
||||||
|
setMuted((m) => !m);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
window.addEventListener("keydown", onKey);
|
||||||
|
return () => window.removeEventListener("keydown", onKey);
|
||||||
|
}, [toggle, step, nextClip, prevClip, goTo]);
|
||||||
|
|
||||||
|
// ── Timeline ───────────────────────────────────────────────────────────────
|
||||||
|
const segments = useMemo(() => {
|
||||||
|
let offset = 0;
|
||||||
|
return clips.map((clip, i) => {
|
||||||
|
const span = spanOf(i);
|
||||||
|
const length = span.end - span.start;
|
||||||
|
const seg = { clip, span, offset, length };
|
||||||
|
offset += length;
|
||||||
|
return seg;
|
||||||
|
});
|
||||||
|
// spans refine as clips load (bumpSpans)
|
||||||
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||||
|
}, [clips, spanOf, spanVersion]);
|
||||||
|
const totalLength = segments.reduce((sum, s) => sum + s.length, 0) || 1;
|
||||||
|
const current = segments[index];
|
||||||
|
const posInClip = current ? Math.min(Math.max(frame - current.span.start, 0), current.length - 1) : 0;
|
||||||
|
const position = current ? current.offset + posInClip : 0;
|
||||||
|
const fps = clips[index]?.fps ?? 24;
|
||||||
|
|
||||||
|
const seekTimeline = (e: React.MouseEvent<HTMLDivElement>) => {
|
||||||
|
const rect = e.currentTarget.getBoundingClientRect();
|
||||||
|
const target = ((e.clientX - rect.left) / rect.width) * totalLength;
|
||||||
|
const seg =
|
||||||
|
segments.find((s) => target < s.offset + s.length) ?? segments[segments.length - 1];
|
||||||
|
if (!seg) return;
|
||||||
|
const i = segments.indexOf(seg);
|
||||||
|
const f = seg.span.start + Math.min(seg.length - 1, Math.floor(target - seg.offset));
|
||||||
|
if (i === indexRef.current) {
|
||||||
|
const video = videoRefs[activeRef.current].current;
|
||||||
|
if (video) {
|
||||||
|
video.currentTime = frameToTime(f + SEEK_BIAS, seg.clip.fps);
|
||||||
|
setFrame(f);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
void goTo(i, f);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const anyHq = clips.some((c) => c.hqUrl);
|
||||||
|
|
||||||
|
if (!clips.length) return null;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="flex flex-col flex-1 min-h-0 bg-black">
|
||||||
|
{/* Stage */}
|
||||||
|
<div className="relative flex-1 min-h-0" onClick={toggle}>
|
||||||
|
{[0, 1].map((slot) => (
|
||||||
|
<video
|
||||||
|
key={slot}
|
||||||
|
ref={videoRefs[slot]}
|
||||||
|
playsInline
|
||||||
|
muted
|
||||||
|
preload="auto"
|
||||||
|
// Initial stacking only; show() swaps opacity on the DOM from then on.
|
||||||
|
style={{ opacity: slot === 0 ? 1 : 0 }}
|
||||||
|
className="absolute inset-0 w-full h-full object-contain"
|
||||||
|
/>
|
||||||
|
))}
|
||||||
|
{current && (
|
||||||
|
<div className="absolute top-3 left-3 pointer-events-none flex items-center gap-2 rounded bg-black/60 px-2 py-1">
|
||||||
|
<span className="font-mono text-xs font-semibold text-white">{current.clip.label}</span>
|
||||||
|
{current.clip.sublabel && (
|
||||||
|
<span className="text-[10px] text-zinc-400">{current.clip.sublabel}</span>
|
||||||
|
)}
|
||||||
|
<span className="text-[10px] text-zinc-500">
|
||||||
|
{index + 1}/{clips.length}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{buffering && (
|
||||||
|
<div className="absolute inset-0 flex items-center justify-center pointer-events-none">
|
||||||
|
<Loader2 className="h-6 w-6 animate-spin text-zinc-400" />
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Timeline: one segment per clip, sized by its cut length */}
|
||||||
|
<div className="px-3 pt-2 shrink-0">
|
||||||
|
<div
|
||||||
|
className="relative h-7 flex rounded overflow-hidden cursor-pointer bg-zinc-900 select-none"
|
||||||
|
onClick={seekTimeline}
|
||||||
|
>
|
||||||
|
{segments.map((s, i) => (
|
||||||
|
<div
|
||||||
|
key={s.clip.id}
|
||||||
|
style={{ width: `${(s.length / totalLength) * 100}%` }}
|
||||||
|
className={cn(
|
||||||
|
"h-full border-r border-black/70 px-1 flex items-center overflow-hidden",
|
||||||
|
i === index ? "bg-blue-500/30" : i % 2 ? "bg-zinc-800" : "bg-zinc-800/60"
|
||||||
|
)}
|
||||||
|
title={`${s.clip.label} · ${s.length} fr`}
|
||||||
|
>
|
||||||
|
<span className="text-[10px] font-mono text-zinc-300 truncate">{s.clip.label}</span>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
<div
|
||||||
|
className="absolute top-0 bottom-0 w-px bg-white pointer-events-none"
|
||||||
|
style={{ left: `${(position / totalLength) * 100}%` }}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Transport */}
|
||||||
|
<div className="flex items-center gap-1 px-3 py-2 shrink-0 text-zinc-300">
|
||||||
|
<TransportButton onClick={prevClip} title="Previous shot (↑)">
|
||||||
|
<ChevronFirst className="h-4 w-4" />
|
||||||
|
</TransportButton>
|
||||||
|
<TransportButton onClick={toggle} title="Play / pause (Space)">
|
||||||
|
{playing ? <Pause className="h-4 w-4" /> : <Play className="h-4 w-4" />}
|
||||||
|
</TransportButton>
|
||||||
|
<TransportButton onClick={nextClip} title="Next shot (↓)">
|
||||||
|
<ChevronLast className="h-4 w-4" />
|
||||||
|
</TransportButton>
|
||||||
|
|
||||||
|
<span className="ml-2 font-mono text-xs tabular-nums text-zinc-400">
|
||||||
|
{frameToTimecode(position, fps)}
|
||||||
|
<span className="text-zinc-600"> / {frameToTimecode(totalLength, fps)}</span>
|
||||||
|
</span>
|
||||||
|
<span className="ml-3 font-mono text-[10px] text-zinc-600 tabular-nums">
|
||||||
|
shot fr {posInClip + 1}/{current?.length ?? 0}
|
||||||
|
</span>
|
||||||
|
|
||||||
|
<div className="ml-auto flex items-center gap-1">
|
||||||
|
{anyHq && (
|
||||||
|
<button
|
||||||
|
onClick={() => setHq((v) => !v)}
|
||||||
|
onMouseDown={(e) => e.preventDefault()}
|
||||||
|
className={cn(
|
||||||
|
"px-2 h-7 rounded text-[10px] font-semibold uppercase tracking-wider border",
|
||||||
|
hq
|
||||||
|
? "border-blue-500/40 text-blue-300 bg-blue-500/10"
|
||||||
|
: "border-zinc-700 text-zinc-500 hover:text-zinc-300"
|
||||||
|
)}
|
||||||
|
title="High quality where available"
|
||||||
|
>
|
||||||
|
HQ
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
<TransportButton
|
||||||
|
onClick={() => setLoop((v) => !v)}
|
||||||
|
title="Loop playlist"
|
||||||
|
active={loop}
|
||||||
|
>
|
||||||
|
<Repeat className="h-4 w-4" />
|
||||||
|
</TransportButton>
|
||||||
|
<TransportButton onClick={() => setMuted((m) => !m)} title="Mute (M)">
|
||||||
|
{muted ? <VolumeX className="h-4 w-4" /> : <Volume2 className="h-4 w-4" />}
|
||||||
|
</TransportButton>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function TransportButton({
|
||||||
|
onClick,
|
||||||
|
title,
|
||||||
|
active,
|
||||||
|
children,
|
||||||
|
}: {
|
||||||
|
onClick: () => void;
|
||||||
|
title: string;
|
||||||
|
active?: boolean;
|
||||||
|
children: React.ReactNode;
|
||||||
|
}) {
|
||||||
|
return (
|
||||||
|
<button
|
||||||
|
onClick={onClick}
|
||||||
|
// Keep focus off the button so Space stays play/pause.
|
||||||
|
onMouseDown={(e) => e.preventDefault()}
|
||||||
|
title={title}
|
||||||
|
className={cn(
|
||||||
|
"h-8 w-8 flex items-center justify-center rounded hover:bg-zinc-800 transition-colors",
|
||||||
|
active ? "text-blue-400" : "text-zinc-300"
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
{children}
|
||||||
|
</button>
|
||||||
|
);
|
||||||
|
}
|
||||||
+2
-1
@@ -11,7 +11,8 @@ services:
|
|||||||
- .env
|
- .env
|
||||||
|
|
||||||
volumes:
|
volumes:
|
||||||
- ./uploads:/app/uploads
|
# Uploads live on the Hetzner volume, not the root disk (uid 1001 must own it)
|
||||||
|
- /mnt/HC_Volume_105945736/vfxreview-uploads:/app/uploads
|
||||||
|
|
||||||
depends_on:
|
depends_on:
|
||||||
postgres:
|
postgres:
|
||||||
|
|||||||
@@ -0,0 +1,107 @@
|
|||||||
|
import { describe, it, expect } from "vitest";
|
||||||
|
import { parseBoardLine, parseBoardText, suggestShot } from "./board-parse";
|
||||||
|
|
||||||
|
const shots = [
|
||||||
|
{ id: "s1", shotCode: "DH2_VFX_027_090" },
|
||||||
|
{ id: "s2", shotCode: "DH2_VFX_005_010" },
|
||||||
|
{ id: "s3", shotCode: "DH2_VFX_004_100" },
|
||||||
|
{ id: "s4", shotCode: "UNG_117_023_010", clientCode: "EP17_VFX_003" },
|
||||||
|
];
|
||||||
|
const users = [
|
||||||
|
{ id: "u1", name: "Chris Pinto", email: "chris@example.com" },
|
||||||
|
{ id: "u2", name: "Michelle Pinto", email: "michelle@example.com" },
|
||||||
|
];
|
||||||
|
const ctx = { shots, users };
|
||||||
|
|
||||||
|
describe("parseBoardLine", () => {
|
||||||
|
it("links the shot and assigns from (NAME)", () => {
|
||||||
|
expect(parseBoardLine("DH2_VFX_027_090 finalise (CHRIS)", ctx)).toEqual({
|
||||||
|
text: "finalise",
|
||||||
|
code: "DH2_VFX_027_090",
|
||||||
|
shotId: "s1",
|
||||||
|
assigneeId: "u1",
|
||||||
|
waitingOn: null,
|
||||||
|
group: "",
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it("matches codes case-insensitively and by client alias", () => {
|
||||||
|
expect(parseBoardLine("dh2_vfx_027_090 x", ctx).shotId).toBe("s1");
|
||||||
|
const alias = parseBoardLine("EP17_VFX_003 warp fix", ctx);
|
||||||
|
expect(alias.shotId).toBe("s4");
|
||||||
|
expect(alias.code).toBe("UNG_117_023_010");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("keeps an unknown code as typed for flagging", () => {
|
||||||
|
const r = parseBoardLine("DH2_004_100 not on our tracker?", ctx);
|
||||||
|
expect(r.code).toBe("DH2_004_100");
|
||||||
|
expect(r.shotId).toBeNull();
|
||||||
|
expect(r.text).toBe("not on our tracker?");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("assigns from @name and keeps the rest of a parenthesised group", () => {
|
||||||
|
expect(parseBoardLine("DH2_VFX_005_010 gfx @michelle", ctx).assigneeId).toBe("u2");
|
||||||
|
const r = parseBoardLine("(MICHELLE ROTO) Maagie shot", ctx);
|
||||||
|
expect(r.assigneeId).toBe("u2");
|
||||||
|
expect(r.text).toBe("ROTO Maagie shot");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("leaves parentheses that are not a user alone", () => {
|
||||||
|
const r = parseBoardLine("DH2_VFX_005_010 track (90% done)", ctx);
|
||||||
|
expect(r.assigneeId).toBeNull();
|
||||||
|
expect(r.text).toBe("track (90% done)");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("splits off what the line is waiting on", () => {
|
||||||
|
const r = parseBoardLine(
|
||||||
|
"DH2_VFX_005_010 gfx required for update (MICHELLE) wait: client GFX ADH_GFX_005_020",
|
||||||
|
ctx,
|
||||||
|
);
|
||||||
|
expect(r.shotId).toBe("s2");
|
||||||
|
expect(r.waitingOn).toBe("client GFX ADH_GFX_005_020");
|
||||||
|
expect(r.text).toBe("gfx required for update");
|
||||||
|
expect(parseBoardLine("x waiting on: grade", ctx).waitingOn).toBe("grade");
|
||||||
|
// no colon → prose
|
||||||
|
expect(parseBoardLine("awaiting gfx", ctx).waitingOn).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("takes a note with no shot code", () => {
|
||||||
|
const r = parseBoardLine("- Deposit received", ctx);
|
||||||
|
expect(r).toMatchObject({ text: "Deposit received", code: null, shotId: null });
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("parseBoardText", () => {
|
||||||
|
it("groups lines under headings and skips blanks", () => {
|
||||||
|
const items = parseBoardText(
|
||||||
|
"DH2_VFX_027_090 finalise (CHRIS)\n\nWATER DROPS:\nDH2_VFX_005_010 still do (CHRIS)\nDH2_VFX_004_100\n",
|
||||||
|
ctx,
|
||||||
|
);
|
||||||
|
expect(items.map((i) => [i.code, i.group, i.text])).toEqual([
|
||||||
|
["DH2_VFX_027_090", "", "finalise"],
|
||||||
|
["DH2_VFX_005_010", "WATER DROPS", "still do"],
|
||||||
|
["DH2_VFX_004_100", "WATER DROPS", ""],
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("treats an all-caps line without a code as a heading", () => {
|
||||||
|
const items = parseBoardText("FLAGS\nDH2_004_100 not on our tracker?", ctx);
|
||||||
|
expect(items).toHaveLength(1);
|
||||||
|
expect(items[0].group).toBe("FLAGS");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("never treats a single typed line as a heading", () => {
|
||||||
|
expect(parseBoardText("CALL CLIENT", ctx)).toHaveLength(1);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("suggestShot", () => {
|
||||||
|
it("suggests the shot with the same prefix and numbers", () => {
|
||||||
|
expect(suggestShot("DH2_004_100", shots)?.id).toBe("s3");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("does not guess between several candidates", () => {
|
||||||
|
const dup = [...shots, { id: "s5", shotCode: "DH2_GFX_004_100" }];
|
||||||
|
expect(suggestShot("DH2_004_100", dup)).toBeNull();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,171 @@
|
|||||||
|
/**
|
||||||
|
* Turns lines typed (or pasted) onto the daily board into board items.
|
||||||
|
*
|
||||||
|
* The board replaces a shared doc, so the input is whatever someone would
|
||||||
|
* have typed there:
|
||||||
|
*
|
||||||
|
* WATER DROPS:
|
||||||
|
* DH2_VFX_027_210 still do (CHRIS)
|
||||||
|
* DH2_VFX_005_010 gfx required for update @michelle wait: client GFX ADH_GFX_005_020
|
||||||
|
*
|
||||||
|
* - The first shot-code-shaped token is the line's shot. It is matched against
|
||||||
|
* the project's shot codes and client aliases; a code that matches nothing
|
||||||
|
* is kept as typed so the board can flag it.
|
||||||
|
* - `(NAME)` or `@name` assigns the line when NAME is a user's first or full
|
||||||
|
* name. A parenthesised group can carry more than the name — "(MICHELLE
|
||||||
|
* ROTO)" assigns Michelle and keeps "ROTO" in the text.
|
||||||
|
* - `wait: …` (also `waiting on:`, `blocked by:`) marks what the line is
|
||||||
|
* blocked on. The colon is required so prose like "awaiting gfx" stays text.
|
||||||
|
* - A line with no shot code that ends in ":" or is all capitals is a heading;
|
||||||
|
* the lines after it are grouped under it.
|
||||||
|
*/
|
||||||
|
|
||||||
|
export interface BoardShot {
|
||||||
|
id: string;
|
||||||
|
shotCode: string;
|
||||||
|
clientCode?: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface BoardUser {
|
||||||
|
id: string;
|
||||||
|
name: string | null;
|
||||||
|
email: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ParsedBoardLine {
|
||||||
|
text: string;
|
||||||
|
/** The shot code as typed (canonical shotCode when it matched); null = no code on the line */
|
||||||
|
code: string | null;
|
||||||
|
shotId: string | null;
|
||||||
|
assigneeId: string | null;
|
||||||
|
waitingOn: string | null;
|
||||||
|
group: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Three or more underscore-separated segments, starting with a letter:
|
||||||
|
// DH2_VFX_027_090, UNG_117_023_010, ADH_GFX_005_020.
|
||||||
|
export const CODE_RE = /\b[A-Za-z][A-Za-z0-9]*(?:_[A-Za-z0-9]+){2,}\b/;
|
||||||
|
const WAIT_RE = /\b(?:wait(?:ing)?(?:\s+(?:on|for))?|blocked(?:\s+(?:on|by))?)\s*:\s*(.*)$/i;
|
||||||
|
const BULLET_RE = /^(?:[-*•–]|\d+[.)])\s+/;
|
||||||
|
|
||||||
|
export function findShot(code: string, shots: BoardShot[]): BoardShot | null {
|
||||||
|
const c = code.toUpperCase();
|
||||||
|
return (
|
||||||
|
shots.find((s) => s.shotCode.toUpperCase() === c) ??
|
||||||
|
shots.find((s) => s.clientCode?.trim().toUpperCase() === c) ??
|
||||||
|
null
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A likely intended shot for a code that matched nothing — same leading
|
||||||
|
* segment and same numeric segments, so "DH2_004_100" suggests
|
||||||
|
* "DH2_VFX_004_100". Only a unique candidate is suggested.
|
||||||
|
*/
|
||||||
|
export function suggestShot(code: string, shots: BoardShot[]): BoardShot | null {
|
||||||
|
const sig = (c: string) => {
|
||||||
|
const parts = c.toUpperCase().split("_");
|
||||||
|
return `${parts[0]}|${parts.filter((p) => /^\d+$/.test(p)).join("_")}`;
|
||||||
|
};
|
||||||
|
const want = sig(code);
|
||||||
|
if (want.endsWith("|")) return null; // no numeric segments to go on
|
||||||
|
const hits = shots.filter((s) => sig(s.shotCode) === want);
|
||||||
|
return hits.length === 1 ? hits[0] : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
function userNames(u: BoardUser): string[] {
|
||||||
|
const names = [u.email.split("@")[0]];
|
||||||
|
if (u.name) {
|
||||||
|
names.push(u.name);
|
||||||
|
names.push(u.name.split(/\s+/)[0]);
|
||||||
|
}
|
||||||
|
return names.map((n) => n.toLowerCase());
|
||||||
|
}
|
||||||
|
|
||||||
|
function findUser(word: string, users: BoardUser[]): BoardUser | null {
|
||||||
|
const w = word.toLowerCase();
|
||||||
|
const hits = users.filter((u) => userNames(u).includes(w));
|
||||||
|
return hits.length === 1 ? hits[0] : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
function isHeading(line: string): boolean {
|
||||||
|
if (CODE_RE.test(line)) return false;
|
||||||
|
if (line.endsWith(":")) return true;
|
||||||
|
const letters = line.replace(/[^A-Za-z]/g, "");
|
||||||
|
return letters.length >= 3 && letters === letters.toUpperCase();
|
||||||
|
}
|
||||||
|
|
||||||
|
export function parseBoardLine(
|
||||||
|
raw: string,
|
||||||
|
ctx: { shots: BoardShot[]; users: BoardUser[] },
|
||||||
|
group = "",
|
||||||
|
): ParsedBoardLine {
|
||||||
|
let line = raw.trim().replace(BULLET_RE, "");
|
||||||
|
|
||||||
|
let waitingOn: string | null = null;
|
||||||
|
const wait = WAIT_RE.exec(line);
|
||||||
|
if (wait) {
|
||||||
|
waitingOn = wait[1].trim() || null;
|
||||||
|
line = line.slice(0, wait.index);
|
||||||
|
}
|
||||||
|
|
||||||
|
let code: string | null = null;
|
||||||
|
let shotId: string | null = null;
|
||||||
|
const codeMatch = CODE_RE.exec(line);
|
||||||
|
if (codeMatch) {
|
||||||
|
const shot = findShot(codeMatch[0], ctx.shots);
|
||||||
|
code = shot?.shotCode ?? codeMatch[0].toUpperCase();
|
||||||
|
shotId = shot?.id ?? null;
|
||||||
|
line = line.slice(0, codeMatch.index) + line.slice(codeMatch.index + codeMatch[0].length);
|
||||||
|
}
|
||||||
|
|
||||||
|
let assigneeId: string | null = null;
|
||||||
|
// (NAME …) — first word a user's name; the rest of the group stays as text
|
||||||
|
line = line.replace(/\(([^)]*)\)/g, (whole, inner: string) => {
|
||||||
|
if (assigneeId) return whole;
|
||||||
|
const words = inner.trim().split(/\s+/);
|
||||||
|
// Full name first ("Chris Pinto"), then first word
|
||||||
|
const full = findUser(words.slice(0, 2).join(" "), ctx.users);
|
||||||
|
const user = full ?? findUser(words[0] ?? "", ctx.users);
|
||||||
|
if (!user) return whole;
|
||||||
|
assigneeId = user.id;
|
||||||
|
const rest = words.slice(full ? 2 : 1).join(" ");
|
||||||
|
return rest ? ` ${rest} ` : " ";
|
||||||
|
});
|
||||||
|
line = line.replace(/@([A-Za-z][\w.-]*)/g, (whole, name: string) => {
|
||||||
|
if (assigneeId) return whole;
|
||||||
|
const user = findUser(name, ctx.users);
|
||||||
|
if (!user) return whole;
|
||||||
|
assigneeId = user.id;
|
||||||
|
return " ";
|
||||||
|
});
|
||||||
|
|
||||||
|
const text = line
|
||||||
|
.replace(/\s+/g, " ")
|
||||||
|
.replace(/^[\s:\-–,.]+|[\s:\-–,]+$/g, "")
|
||||||
|
.trim();
|
||||||
|
|
||||||
|
return { text, code, shotId, assigneeId, waitingOn, group };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Every non-blank line of `input` as a board item, headings applied as groups. */
|
||||||
|
export function parseBoardText(
|
||||||
|
input: string,
|
||||||
|
ctx: { shots: BoardShot[]; users: BoardUser[]; group?: string },
|
||||||
|
): ParsedBoardLine[] {
|
||||||
|
const out: ParsedBoardLine[] = [];
|
||||||
|
let group = ctx.group ?? "";
|
||||||
|
const lines = input.split(/\r?\n/).map((l) => l.trim()).filter(Boolean);
|
||||||
|
for (const raw of lines) {
|
||||||
|
const line = raw.replace(BULLET_RE, "");
|
||||||
|
// A single line is always an item — someone typing "Deposit received"
|
||||||
|
// into the quick-add box means a note, not a heading.
|
||||||
|
if (lines.length > 1 && isHeading(line)) {
|
||||||
|
group = line.replace(/:$/, "").trim();
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const parsed = parseBoardLine(line, ctx, group);
|
||||||
|
if (parsed.text || parsed.code || parsed.waitingOn) out.push(parsed);
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
@@ -0,0 +1,146 @@
|
|||||||
|
import { db } from "@/lib/db";
|
||||||
|
import { Prisma } from "@prisma/client";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* New-comment tracking for the shot-status board. A comment or reply is new to
|
||||||
|
* a user when someone else wrote it on one of the shot's versions (directly or
|
||||||
|
* through a task on the shot) after the user's ShotCommentRead marker. With no
|
||||||
|
* marker the baseline is when the account was created, so a new user does not
|
||||||
|
* inherit the whole back catalogue.
|
||||||
|
*
|
||||||
|
* Comments with no author (the author's account was deleted) count as someone
|
||||||
|
* else's. Pasted WhatsApp notes are authored by whoever pasted them, so they
|
||||||
|
* are new to everyone but that person.
|
||||||
|
*/
|
||||||
|
|
||||||
|
export type UnreadCommentSummary = {
|
||||||
|
count: number;
|
||||||
|
/** createdAt of the newest unread item — what "mark read" reads up to. */
|
||||||
|
latestAt: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
export async function getUnreadCommentSummaries(
|
||||||
|
userId: string,
|
||||||
|
projectId: string
|
||||||
|
): Promise<Record<string, UnreadCommentSummary>> {
|
||||||
|
const rows = await db.$queryRaw<{ shotId: string; count: number; latestAt: Date }[]>(Prisma.sql`
|
||||||
|
WITH me AS (
|
||||||
|
SELECT "createdAt" FROM "users" WHERE "id" = ${userId}
|
||||||
|
),
|
||||||
|
items AS (
|
||||||
|
SELECT COALESCE(v."shotId", t."shotId") AS "shotId", c."createdAt", c."authorId"
|
||||||
|
FROM "comments" c
|
||||||
|
JOIN "versions" v ON v."id" = c."versionId"
|
||||||
|
LEFT JOIN "tasks" t ON t."id" = v."taskId"
|
||||||
|
UNION ALL
|
||||||
|
SELECT COALESCE(v."shotId", t."shotId") AS "shotId", r."createdAt", r."authorId"
|
||||||
|
FROM "comment_replies" r
|
||||||
|
JOIN "comments" c ON c."id" = r."commentId"
|
||||||
|
JOIN "versions" v ON v."id" = c."versionId"
|
||||||
|
LEFT JOIN "tasks" t ON t."id" = v."taskId"
|
||||||
|
)
|
||||||
|
SELECT i."shotId", COUNT(*)::int AS "count", MAX(i."createdAt") AS "latestAt"
|
||||||
|
FROM items i
|
||||||
|
JOIN "shots" s ON s."id" = i."shotId"
|
||||||
|
LEFT JOIN "shot_comment_reads" scr ON scr."shotId" = s."id" AND scr."userId" = ${userId}
|
||||||
|
WHERE s."projectId" = ${projectId}
|
||||||
|
AND i."authorId" IS DISTINCT FROM ${userId}
|
||||||
|
AND i."createdAt" > COALESCE(scr."readAt", (SELECT "createdAt" FROM me))
|
||||||
|
GROUP BY i."shotId"
|
||||||
|
`);
|
||||||
|
|
||||||
|
return Object.fromEntries(
|
||||||
|
rows.map((r) => [r.shotId, { count: r.count, latestAt: r.latestAt.toISOString() }])
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export type UnreadCommentItem = {
|
||||||
|
id: string;
|
||||||
|
kind: "comment" | "reply";
|
||||||
|
text: string;
|
||||||
|
authorName: string;
|
||||||
|
source: string | null;
|
||||||
|
versionId: string;
|
||||||
|
versionNumber: number;
|
||||||
|
frameNumber: number;
|
||||||
|
createdAt: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
/** The unread comments and replies on one shot, newest first. */
|
||||||
|
export async function getUnreadCommentsForShot(
|
||||||
|
userId: string,
|
||||||
|
shotId: string
|
||||||
|
): Promise<UnreadCommentItem[]> {
|
||||||
|
const [user, marker] = await Promise.all([
|
||||||
|
db.user.findUnique({ where: { id: userId }, select: { createdAt: true } }),
|
||||||
|
db.shotCommentRead.findUnique({ where: { userId_shotId: { userId, shotId } } }),
|
||||||
|
]);
|
||||||
|
const since = marker?.readAt ?? user?.createdAt ?? new Date(0);
|
||||||
|
|
||||||
|
const onShot: Prisma.VersionWhereInput = { OR: [{ shotId }, { task: { shotId } }] };
|
||||||
|
// `not: userId` alone would also drop authorless rows (SQL NULL), which count.
|
||||||
|
const byOthers = { OR: [{ authorId: null }, { authorId: { not: userId } }] };
|
||||||
|
const author = { select: { name: true, email: true } };
|
||||||
|
const version = { select: { id: true, versionNumber: true } };
|
||||||
|
|
||||||
|
const [comments, replies] = await Promise.all([
|
||||||
|
db.comment.findMany({
|
||||||
|
where: { version: onShot, createdAt: { gt: since }, ...byOthers },
|
||||||
|
select: { id: true, text: true, source: true, frameNumber: true, createdAt: true, author, version },
|
||||||
|
}),
|
||||||
|
db.commentReply.findMany({
|
||||||
|
where: { comment: { version: onShot }, createdAt: { gt: since }, ...byOthers },
|
||||||
|
select: {
|
||||||
|
id: true,
|
||||||
|
text: true,
|
||||||
|
createdAt: true,
|
||||||
|
author,
|
||||||
|
comment: { select: { frameNumber: true, version } },
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
]);
|
||||||
|
|
||||||
|
const items: UnreadCommentItem[] = [
|
||||||
|
...comments.map((c) => ({
|
||||||
|
id: c.id,
|
||||||
|
kind: "comment" as const,
|
||||||
|
text: c.text,
|
||||||
|
authorName: c.author?.name ?? c.author?.email ?? "Unknown",
|
||||||
|
source: c.source,
|
||||||
|
versionId: c.version.id,
|
||||||
|
versionNumber: c.version.versionNumber,
|
||||||
|
frameNumber: c.frameNumber,
|
||||||
|
createdAt: c.createdAt.toISOString(),
|
||||||
|
})),
|
||||||
|
...replies.map((r) => ({
|
||||||
|
id: r.id,
|
||||||
|
kind: "reply" as const,
|
||||||
|
text: r.text,
|
||||||
|
authorName: r.author?.name ?? r.author?.email ?? "Unknown",
|
||||||
|
source: null,
|
||||||
|
versionId: r.comment.version.id,
|
||||||
|
versionNumber: r.comment.version.versionNumber,
|
||||||
|
frameNumber: r.comment.frameNumber,
|
||||||
|
createdAt: r.createdAt.toISOString(),
|
||||||
|
})),
|
||||||
|
];
|
||||||
|
return items.sort((a, b) => b.createdAt.localeCompare(a.createdAt));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Move a user's marker forward to `upTo` — the newest item they were shown,
|
||||||
|
* not "now", so a comment that lands while the list is open stays unread.
|
||||||
|
* Never moves a marker backwards.
|
||||||
|
*/
|
||||||
|
export async function markShotCommentsRead(userId: string, shotId: string, upTo: Date) {
|
||||||
|
const readAt = upTo > new Date() ? new Date() : upTo;
|
||||||
|
const existing = await db.shotCommentRead.findUnique({
|
||||||
|
where: { userId_shotId: { userId, shotId } },
|
||||||
|
});
|
||||||
|
if (existing && existing.readAt >= readAt) return;
|
||||||
|
await db.shotCommentRead.upsert({
|
||||||
|
where: { userId_shotId: { userId, shotId } },
|
||||||
|
create: { userId, shotId, readAt },
|
||||||
|
update: { readAt },
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -1,6 +1,7 @@
|
|||||||
import { db } from "@/lib/db";
|
import { db } from "@/lib/db";
|
||||||
import { getConfigNumber } from "@/lib/render-pipeline/config";
|
import { getConfigNumber } from "@/lib/render-pipeline/config";
|
||||||
import { listMachines } from "@/lib/render-pipeline/machines";
|
import { listMachines } from "@/lib/render-pipeline/machines";
|
||||||
|
import { handoffStage, type HandoffStage } from "@/lib/render-pipeline/delivery-handoff";
|
||||||
import type { ExportStatus, Prisma } from "@prisma/client";
|
import type { ExportStatus, Prisma } from "@prisma/client";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -596,6 +597,72 @@ export async function getRecentDeliveries(limit = 5): Promise<DeliverySummary[]>
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface AwaitingDelivery {
|
||||||
|
id: string;
|
||||||
|
packageNumber: number;
|
||||||
|
name: string;
|
||||||
|
projectCode: string;
|
||||||
|
episode: string;
|
||||||
|
itemCount: number;
|
||||||
|
stage: HandoffStage;
|
||||||
|
/** When the folder was ready to go — the clock the client is waiting on. */
|
||||||
|
builtAt: Date;
|
||||||
|
severity: "normal" | "warning" | "critical";
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Built packages the client does not have yet.
|
||||||
|
*
|
||||||
|
* A READY package is the easiest thing in the pipeline to believe is done: the
|
||||||
|
* folder exists and every file verified, but nothing has left the building.
|
||||||
|
* It stays listed until the upload location and the person it was shared with
|
||||||
|
* are both on record, and gets louder the longer that takes.
|
||||||
|
*/
|
||||||
|
export async function getAwaitingDelivery(): Promise<AwaitingDelivery[]> {
|
||||||
|
const rows = await db.deliveryPackage.findMany({
|
||||||
|
where: {
|
||||||
|
kind: "EXR_DELIVERY",
|
||||||
|
status: "READY",
|
||||||
|
project: { status: { in: ["ACTIVE", "ON_HOLD"] } },
|
||||||
|
},
|
||||||
|
orderBy: { builtAt: "asc" },
|
||||||
|
select: {
|
||||||
|
id: true,
|
||||||
|
packageNumber: true,
|
||||||
|
name: true,
|
||||||
|
kind: true,
|
||||||
|
status: true,
|
||||||
|
episode: true,
|
||||||
|
createdAt: true,
|
||||||
|
builtAt: true,
|
||||||
|
uploadedAt: true,
|
||||||
|
project: { select: { code: true } },
|
||||||
|
_count: { select: { items: true } },
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const day = 24 * 3600_000;
|
||||||
|
return rows.flatMap((row) => {
|
||||||
|
const stage = handoffStage(row);
|
||||||
|
if (!stage) return [];
|
||||||
|
const builtAt = row.builtAt ?? row.createdAt;
|
||||||
|
const age = Date.now() - builtAt.getTime();
|
||||||
|
return [
|
||||||
|
{
|
||||||
|
id: row.id,
|
||||||
|
packageNumber: row.packageNumber,
|
||||||
|
name: row.name,
|
||||||
|
projectCode: row.project.code,
|
||||||
|
episode: row.episode,
|
||||||
|
itemCount: row._count.items,
|
||||||
|
stage,
|
||||||
|
builtAt,
|
||||||
|
severity: age >= 2 * day ? "critical" : age >= day ? "warning" : "normal",
|
||||||
|
},
|
||||||
|
];
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
export interface CourtSide {
|
export interface CourtSide {
|
||||||
count: number;
|
count: number;
|
||||||
items: { id: string; shotCode: string; label: string; href: string }[];
|
items: { id: string; shotCode: string; label: string; href: string }[];
|
||||||
|
|||||||
@@ -0,0 +1,116 @@
|
|||||||
|
import { describe, it, expect } from "vitest";
|
||||||
|
import { parseDue, parseFeedback, slateFrames, toPlayerFrame } from "./feedback-parse";
|
||||||
|
|
||||||
|
describe("parseFeedback", () => {
|
||||||
|
it("splits rounds and notes from the doc's own format", () => {
|
||||||
|
const { rounds, ignored } = parseFeedback(`FEEDBACK 117 DUE Oct 7, 2026 12:00 PM
|
||||||
|
UNG_117_023_010 The screen comp starts warping, slightly expanding and contracting in the second half of the shot.
|
||||||
|
UNG_117_024_010 48fps @ 200% Done Dineo seems slightly too small
|
||||||
|
|
||||||
|
FEEDBACK 113 DUE Oct 7, 2026 12:00 PM
|
||||||
|
UNG_113_008_040 The screen is partially peeking under the mask on OZ
|
||||||
|
UNG_113_018_050 At frame 1018, the mask is still slipping`);
|
||||||
|
expect(ignored).toEqual([]);
|
||||||
|
expect(rounds.map((r) => [r.title, r.dueText, r.notes.length])).toEqual([
|
||||||
|
["FEEDBACK 117", "Oct 7, 2026 12:00 PM", 2],
|
||||||
|
["FEEDBACK 113", "Oct 7, 2026 12:00 PM", 2],
|
||||||
|
]);
|
||||||
|
expect(rounds[1].notes[1]).toEqual({
|
||||||
|
codes: ["UNG_113_018_050"],
|
||||||
|
text: "At frame 1018, the mask is still slipping",
|
||||||
|
frame: 1018,
|
||||||
|
});
|
||||||
|
expect(rounds[0].notes[1].frame).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("joins wrapped lines onto the note above, even ones mentioning changes or due", () => {
|
||||||
|
const { rounds } = parseFeedback(`UNG_108_004_030 Comp needs work.
|
||||||
|
Visible matte edge on left of "Top Story" banner.
|
||||||
|
lighting changes, due to the grade`);
|
||||||
|
expect(rounds).toHaveLength(1);
|
||||||
|
expect(rounds[0].title).toBe("");
|
||||||
|
expect(rounds[0].notes[0].text).toBe(
|
||||||
|
'Comp needs work. Visible matte edge on left of "Top Story" banner. lighting changes, due to the grade',
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("strips WhatsApp prefixes and formatting, and keeps preamble aside", () => {
|
||||||
|
const { rounds, ignored } = parseFeedback(`[07/10/2026, 09:12] Stephen Abbott: Hi team, notes below
|
||||||
|
[07/10/2026, 09:13] Stephen Abbott: *UNG_113_031_010* As the camera pans the screen comp seems to shrink`);
|
||||||
|
expect(rounds[0].title).toBe("");
|
||||||
|
expect(rounds[0].notes[0].codes).toEqual(["UNG_113_031_010"]);
|
||||||
|
expect(rounds[0].notes[0].text).toBe("As the camera pans the screen comp seems to shrink");
|
||||||
|
expect(ignored).toEqual(["Hi team, notes below"]);
|
||||||
|
|
||||||
|
const plain = parseFeedback("Morning!\nUNG_113_031_010 shrink");
|
||||||
|
expect(plain.ignored).toEqual(["Morning!"]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("gives one note per shot when several codes lead the line", () => {
|
||||||
|
const { rounds } = parseFeedback("UNG_113_032_034 / UNG_113_032_036, UNG_113_032_038 same matte fix");
|
||||||
|
expect(rounds[0].notes.map((n) => [n.codes[0], n.text])).toEqual([
|
||||||
|
["UNG_113_032_034", "same matte fix"],
|
||||||
|
["UNG_113_032_036", "same matte fix"],
|
||||||
|
["UNG_113_032_038", "same matte fix"],
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("accepts codes without the show prefix and upper-cases them", () => {
|
||||||
|
const { rounds } = parseFeedback("- 113_018_040: hard blue edge, fr 1004");
|
||||||
|
expect(rounds[0].notes[0]).toMatchObject({ codes: ["113_018_040"], text: "hard blue edge, fr 1004", frame: 1004 });
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("parseDue", () => {
|
||||||
|
const now = new Date(2026, 9, 7, 8, 0);
|
||||||
|
|
||||||
|
it("reads a full date and time", () => {
|
||||||
|
const d = parseDue("Oct 7, 2026 12:00 PM", now)!;
|
||||||
|
expect([d.getFullYear(), d.getMonth(), d.getDate(), d.getHours()]).toEqual([2026, 9, 7, 12]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("fills in the year", () => {
|
||||||
|
const d = parseDue("7 Oct 16:00", now)!;
|
||||||
|
expect([d.getFullYear(), d.getMonth(), d.getDate(), d.getHours()]).toEqual([2026, 9, 7, 16]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("returns null for what it cannot read", () => {
|
||||||
|
expect(parseDue("end of day", now)).toBeNull();
|
||||||
|
expect(parseDue(null, now)).toBeNull();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("slateFrames", () => {
|
||||||
|
it("uses the recorded slate, else 1 for pipeline previews, else 0", () => {
|
||||||
|
expect(slateFrames({ pictureStartFrame: 2, frameCount: 120 })).toBe(2);
|
||||||
|
expect(slateFrames({ pictureStartFrame: 0, frameCount: 120 })).toBe(0);
|
||||||
|
expect(slateFrames({ pictureStartFrame: null, frameCount: 120 })).toBe(1);
|
||||||
|
expect(slateFrames({ pictureStartFrame: null, frameCount: null })).toBe(0);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("toPlayerFrame", () => {
|
||||||
|
it("maps a comp frame through the shot start and slate", () => {
|
||||||
|
expect(toPlayerFrame(1018, { shotFrameStart: 1001, pictureStart: 1, frameCount: 120 })).toEqual({
|
||||||
|
frame: 18,
|
||||||
|
fromComp: true,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it("assumes the house 1001 start when the shot has none", () => {
|
||||||
|
expect(toPlayerFrame(1018, { shotFrameStart: null, pictureStart: 1, frameCount: 120 }).frame).toBe(18);
|
||||||
|
expect(toPlayerFrame(1018, { shotFrameStart: 0, pictureStart: 0, frameCount: null }).frame).toBe(17);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("takes a small number as the player's own frame", () => {
|
||||||
|
expect(toPlayerFrame(40, { shotFrameStart: 1001, pictureStart: 1, frameCount: 120 })).toEqual({
|
||||||
|
frame: 40,
|
||||||
|
fromComp: false,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it("keeps the frame inside the picture", () => {
|
||||||
|
expect(toPlayerFrame(1500, { shotFrameStart: 1001, pictureStart: 1, frameCount: 100 }).frame).toBe(100);
|
||||||
|
expect(toPlayerFrame(500, { shotFrameStart: null, pictureStart: 0, frameCount: 100 }).frame).toBe(99);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,180 @@
|
|||||||
|
/**
|
||||||
|
* Client feedback pasted from WhatsApp (or an email, or the old doc) split
|
||||||
|
* into rounds and per-shot notes.
|
||||||
|
*
|
||||||
|
* [07/10/2026, 09:12] Stephen: FEEDBACK 113 DUE Oct 7, 2026 12:00 PM
|
||||||
|
* UNG_113_018_040 there is a hard blue edge on her finger,
|
||||||
|
* along her thumb, which is not in the OCF
|
||||||
|
* UNG_113_018_050 At frame 1018, the mask is still slipping
|
||||||
|
*
|
||||||
|
* - A line that starts with a shot code starts a note. Several codes before
|
||||||
|
* the text ("UNG_113_032_034 / UNG_113_032_036 same fix") give one note per
|
||||||
|
* shot. Lines without a code continue the note above them — WhatsApp
|
||||||
|
* messages wrap.
|
||||||
|
* - A line with no code that names feedback/notes/a round, mentions a due
|
||||||
|
* date, or ends in ":" starts a new round. "DUE …" is split off as the
|
||||||
|
* round's due text; turning it into a date is left to the browser
|
||||||
|
* (parseDue) so "12:00 PM" means the studio's noon, not the server's.
|
||||||
|
* - WhatsApp's copy prefix ("[07/10, 09:12] Name: ") and bold, italic
|
||||||
|
* and strike markers are stripped.
|
||||||
|
*
|
||||||
|
* Codes are kept as typed; matching them to shots is the server's job.
|
||||||
|
*/
|
||||||
|
|
||||||
|
export interface FeedbackNote {
|
||||||
|
codes: string[];
|
||||||
|
text: string;
|
||||||
|
/** Frame number as the client quoted it ("at frame 1018"); null = none given */
|
||||||
|
frame: number | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface FeedbackRoundDraft {
|
||||||
|
title: string;
|
||||||
|
dueText: string | null;
|
||||||
|
notes: FeedbackNote[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ParsedFeedback {
|
||||||
|
rounds: FeedbackRoundDraft[];
|
||||||
|
/** Lines before any note that were not a round header ("Hi team") */
|
||||||
|
ignored: string[];
|
||||||
|
}
|
||||||
|
|
||||||
|
// "[07/10/2026, 09:12]" / "[9:12 AM, 10/7/2026]" then "Sender Name: "
|
||||||
|
const WHATSAPP_PREFIX = /^\[[^\]]*\d[^\]]*\]\s*(?:[^:]{1,60}:\s)?/;
|
||||||
|
const BULLET = /^(?:[-*•–]|\d+[.)])\s+/;
|
||||||
|
// One code: underscore-joined segments. Clients sometimes drop the show
|
||||||
|
// prefix ("113_018_050"), so two segments are enough here.
|
||||||
|
const CODE = "[A-Za-z0-9]+(?:_[A-Za-z0-9]+)+";
|
||||||
|
const LEADING_CODES = new RegExp(`^(${CODE})((?:\\s*(?:,|/|&|\\+|and)?\\s*${CODE})*)`, "i");
|
||||||
|
const HEADER_START = /^(feedback|notes|round|comments)\b/i;
|
||||||
|
const DUE = /\bdue\b[:\s]*(.*)$/i;
|
||||||
|
const DUE_WITH_DATE = /\bdue\b[:\s]+\S*\d/i;
|
||||||
|
const FRAME = /\b(?:frames?|fr\.?|frm)\s*#?\s*(\d{1,6})\b/i;
|
||||||
|
|
||||||
|
function clean(line: string): string {
|
||||||
|
return line
|
||||||
|
.replace(WHATSAPP_PREFIX, "")
|
||||||
|
.replace(/[*~]/g, "") // *bold*, ~strike~
|
||||||
|
// _italic_ only around whole words: shot codes are full of underscores
|
||||||
|
.replace(/(^|\s)_([^_\s][^_]*?)_(?=[\s.,!?]|$)/g, "$1$2")
|
||||||
|
.replace(BULLET, "")
|
||||||
|
.trim();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Strict on purpose: a wrapped note line ("lighting changes, due to the
|
||||||
|
// grade") must continue the note, not start a round.
|
||||||
|
function isHeader(line: string): boolean {
|
||||||
|
if (HEADER_START.test(line)) return true;
|
||||||
|
return line.length <= 60 && (line.endsWith(":") || DUE_WITH_DATE.test(line));
|
||||||
|
}
|
||||||
|
|
||||||
|
export function parseFeedback(input: string): ParsedFeedback {
|
||||||
|
const rounds: FeedbackRoundDraft[] = [];
|
||||||
|
const ignored: string[] = [];
|
||||||
|
let round: FeedbackRoundDraft | null = null;
|
||||||
|
let note: FeedbackNote[] | null = null; // the note (one per code) being continued
|
||||||
|
|
||||||
|
const startRound = (title: string, dueText: string | null) => {
|
||||||
|
round = { title, dueText, notes: [] };
|
||||||
|
rounds.push(round);
|
||||||
|
note = null;
|
||||||
|
};
|
||||||
|
|
||||||
|
for (const raw of input.split(/\r?\n/)) {
|
||||||
|
const line = clean(raw);
|
||||||
|
if (!line) continue;
|
||||||
|
|
||||||
|
const lead = LEADING_CODES.exec(line);
|
||||||
|
if (lead) {
|
||||||
|
const codes = (lead[0].match(new RegExp(CODE, "g")) ?? []).map((c) => c.toUpperCase());
|
||||||
|
const text = line.slice(lead[0].length).replace(/^[\s:\-–,.]+/, "").trim();
|
||||||
|
if (!round) startRound("", null);
|
||||||
|
note = codes.map((code) => ({ codes: [code], text, frame: null }));
|
||||||
|
round!.notes.push(...note);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (isHeader(line)) {
|
||||||
|
const due = DUE.exec(line);
|
||||||
|
const title = (due ? line.slice(0, due.index) : line).replace(/[\s:\-–]+$/, "").trim();
|
||||||
|
startRound(title, due?.[1].trim() || null);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (note) {
|
||||||
|
for (const n of note as FeedbackNote[]) n.text = n.text ? `${n.text} ${line}` : line;
|
||||||
|
} else {
|
||||||
|
ignored.push(line);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
for (const r of rounds as FeedbackRoundDraft[]) {
|
||||||
|
for (const n of r.notes) {
|
||||||
|
const f = FRAME.exec(n.text);
|
||||||
|
n.frame = f ? Number(f[1]) : null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return { rounds: rounds.filter((r) => r.notes.length > 0), ignored };
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The round's due time from the text the client wrote ("Oct 7, 2026 12:00 PM",
|
||||||
|
* "7 Oct 12:00", "Friday" is not attempted). Run in the browser so the time is
|
||||||
|
* read in the studio's zone. A date without a year takes `now`'s year.
|
||||||
|
*/
|
||||||
|
export function parseDue(dueText: string | null, now = new Date()): Date | null {
|
||||||
|
if (!dueText) return null;
|
||||||
|
const text = dueText.replace(/\b(at|@)\b/gi, " ").replace(/\s+/g, " ").trim();
|
||||||
|
// V8's Date parser accepts almost anything ("end of day 2026"); insist on
|
||||||
|
// a month name or a numeric date before handing it over.
|
||||||
|
if (!/\b(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)[a-z]*\b|\d{1,2}[/.-]\d{1,2}/i.test(text)) return null;
|
||||||
|
const direct = new Date(text);
|
||||||
|
if (!isNaN(direct.getTime()) && /\d{4}/.test(text)) return direct;
|
||||||
|
const withYear = new Date(`${text} ${now.getFullYear()}`);
|
||||||
|
if (!isNaN(withYear.getTime())) return withYear;
|
||||||
|
// "7 Oct 12:00" → move the year before the time so Date can read it
|
||||||
|
const m = /^(.*?)(\d{1,2}:\d{2}\s*(?:am|pm)?)$/i.exec(text);
|
||||||
|
if (m) {
|
||||||
|
const d = new Date(`${m[1].trim()} ${now.getFullYear()} ${m[2]}`);
|
||||||
|
if (!isNaN(d.getTime())) return d;
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** First comp frame by house convention, for shots with no frameStart recorded */
|
||||||
|
export const HOUSE_FRAME_START = 1001;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Slate frames before the picture in a version's review media. Recorded on
|
||||||
|
* newer versions; otherwise pipeline previews (the ones that record an EXR
|
||||||
|
* frameCount) open with a 1-frame slate and other uploads with none.
|
||||||
|
* Version.duration is not stored, so the length-based inference in
|
||||||
|
* lib/handles.ts is not available here.
|
||||||
|
*/
|
||||||
|
export function slateFrames(v: { pictureStartFrame: number | null; frameCount: number | null }): number {
|
||||||
|
if (v.pictureStartFrame != null && v.pictureStartFrame >= 0) return v.pictureStartFrame;
|
||||||
|
return v.frameCount != null ? 1 : 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The player frame (0-based, in the review media) for a frame the client
|
||||||
|
* quoted. Clients read the burned-in comp frame (1001-based), so a quote at
|
||||||
|
* or past the shot's first frame is mapped through it and the slate; a
|
||||||
|
* smaller number is taken as the player's own counter.
|
||||||
|
*/
|
||||||
|
export function toPlayerFrame(
|
||||||
|
quoted: number,
|
||||||
|
opts: { shotFrameStart: number | null; pictureStart: number; frameCount: number | null },
|
||||||
|
): { frame: number; fromComp: boolean } {
|
||||||
|
const { pictureStart, frameCount } = opts;
|
||||||
|
const compStart = opts.shotFrameStart && opts.shotFrameStart > 0 ? opts.shotFrameStart : HOUSE_FRAME_START;
|
||||||
|
const last = frameCount && frameCount > 0 ? pictureStart + frameCount - 1 : null;
|
||||||
|
const clamp = (f: number, min: number) => Math.max(min, last != null ? Math.min(last, f) : f);
|
||||||
|
|
||||||
|
if (quoted >= compStart) {
|
||||||
|
return { frame: clamp(quoted - compStart + pictureStart, pictureStart), fromComp: true };
|
||||||
|
}
|
||||||
|
return { frame: clamp(quoted, 0), fromComp: false };
|
||||||
|
}
|
||||||
+33
-1
@@ -1,5 +1,5 @@
|
|||||||
import { describe, expect, it } from "vitest";
|
import { describe, expect, it } from "vitest";
|
||||||
import { computeEditRange, frameRegion, isHandleFrame } from "./handles";
|
import { computeEditRange, cutSpan, frameRegion, isHandleFrame } from "./handles";
|
||||||
|
|
||||||
describe("computeEditRange", () => {
|
describe("computeEditRange", () => {
|
||||||
it("is null when no handles are marked", () => {
|
it("is null when no handles are marked", () => {
|
||||||
@@ -92,3 +92,35 @@ describe("frameRegion", () => {
|
|||||||
expect(isHandleFrame(range, 1)).toBe(true);
|
expect(isHandleFrame(range, 1)).toBe(true);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
describe("cutSpan", () => {
|
||||||
|
it("plays the cut when handles are marked, skipping slate and handles", () => {
|
||||||
|
// 1 slate + 8 head + 84 cut + 8 tail = 101 MP4 frames
|
||||||
|
expect(cutSpan({ handleHead: 8, handleTail: 8, frameCount: 100 }, 101)).toEqual({
|
||||||
|
start: 9,
|
||||||
|
end: 93,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it("plays the whole picture minus the slate when no handles are marked", () => {
|
||||||
|
expect(cutSpan({ frameCount: 100 }, 101)).toEqual({ start: 1, end: 101 });
|
||||||
|
expect(cutSpan({ pictureStartFrame: 2 }, 50)).toEqual({ start: 2, end: 50 });
|
||||||
|
});
|
||||||
|
|
||||||
|
it("plays the whole media when nothing is known about it", () => {
|
||||||
|
expect(cutSpan(null, 48)).toEqual({ start: 0, end: 48 });
|
||||||
|
expect(cutSpan({}, 48)).toEqual({ start: 0, end: 48 });
|
||||||
|
});
|
||||||
|
|
||||||
|
it("is null until the media length is known", () => {
|
||||||
|
expect(cutSpan({ handleHead: 8, handleTail: 8 }, 0)).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("never returns an empty span", () => {
|
||||||
|
// Handles longer than the picture
|
||||||
|
expect(cutSpan({ handleHead: 30, handleTail: 30, frameCount: 40 }, 40)).toEqual({
|
||||||
|
start: 0,
|
||||||
|
end: 40,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|||||||
+41
-3
@@ -61,6 +61,21 @@ export function computeEditRange(
|
|||||||
const tail = Math.max(0, Math.floor(handles.handleTail ?? 0));
|
const tail = Math.max(0, Math.floor(handles.handleTail ?? 0));
|
||||||
if (head === 0 && tail === 0) return null;
|
if (head === 0 && tail === 0) return null;
|
||||||
|
|
||||||
|
const { pictureStart, pictureEnd } = pictureBounds(handles, totalFrames);
|
||||||
|
const cutIn = Math.min(pictureStart + head, pictureEnd);
|
||||||
|
const tailStart = Math.max(cutIn, pictureEnd - tail);
|
||||||
|
|
||||||
|
return { pictureStart, cutIn, tailStart, pictureEnd };
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Where the picture sits in the media: after any slate, up to the end of the
|
||||||
|
* rendered frames. See computeEditRange for how the slate is found.
|
||||||
|
*/
|
||||||
|
function pictureBounds(
|
||||||
|
handles: VersionHandles,
|
||||||
|
totalFrames: number
|
||||||
|
): { pictureStart: number; pictureEnd: number } {
|
||||||
const frameCount =
|
const frameCount =
|
||||||
handles.frameCount != null && handles.frameCount > 0 ? Math.floor(handles.frameCount) : null;
|
handles.frameCount != null && handles.frameCount > 0 ? Math.floor(handles.frameCount) : null;
|
||||||
|
|
||||||
@@ -80,10 +95,33 @@ export function computeEditRange(
|
|||||||
const pictureEnd =
|
const pictureEnd =
|
||||||
frameCount != null ? Math.min(totalFrames, pictureStart + frameCount) : totalFrames;
|
frameCount != null ? Math.min(totalFrames, pictureStart + frameCount) : totalFrames;
|
||||||
|
|
||||||
const cutIn = Math.min(pictureStart + head, pictureEnd);
|
return { pictureStart, pictureEnd };
|
||||||
const tailStart = Math.max(cutIn, pictureEnd - tail);
|
}
|
||||||
|
|
||||||
return { pictureStart, cutIn, tailStart, pictureEnd };
|
/** A half-open frame range [start, end) of the review media. */
|
||||||
|
export interface FrameSpan {
|
||||||
|
start: number;
|
||||||
|
end: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The frames a seamless playlist plays for this version: the cut when handles
|
||||||
|
* are marked, otherwise the whole picture — never the slate. Falls back to
|
||||||
|
* the whole media rather than an empty span, so a clip never plays nothing.
|
||||||
|
*/
|
||||||
|
export function cutSpan(
|
||||||
|
handles: VersionHandles | null | undefined,
|
||||||
|
totalFrames: number
|
||||||
|
): FrameSpan | null {
|
||||||
|
if (!(totalFrames > 0)) return null;
|
||||||
|
const edit = computeEditRange(handles, totalFrames);
|
||||||
|
const span = edit
|
||||||
|
? { start: edit.cutIn, end: edit.tailStart }
|
||||||
|
: (() => {
|
||||||
|
const { pictureStart, pictureEnd } = pictureBounds(handles ?? {}, totalFrames);
|
||||||
|
return { start: pictureStart, end: pictureEnd };
|
||||||
|
})();
|
||||||
|
return span.end > span.start ? span : { start: 0, end: totalFrames };
|
||||||
}
|
}
|
||||||
|
|
||||||
export type FrameRegion = "slate" | "head" | "edit" | "tail";
|
export type FrameRegion = "slate" | "head" | "edit" | "tail";
|
||||||
|
|||||||
@@ -0,0 +1,75 @@
|
|||||||
|
import { describe, expect, it, vi } from "vitest";
|
||||||
|
|
||||||
|
vi.mock("@/lib/db", () => ({ db: {} }));
|
||||||
|
|
||||||
|
import { buildCommentNotifications } from "./notifications";
|
||||||
|
|
||||||
|
const note = (versionId: string, shotCode: string, frameNumber: number, artistIds: (string | null)[] = []) => ({
|
||||||
|
versionId,
|
||||||
|
shotCode,
|
||||||
|
frameNumber,
|
||||||
|
artistIds,
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("buildCommentNotifications", () => {
|
||||||
|
it("tells every staff member and the artist, never the author", () => {
|
||||||
|
const out = buildCommentNotifications({
|
||||||
|
notes: [note("v1", "DH2_010", 1012, ["artist"])],
|
||||||
|
authorId: "sup",
|
||||||
|
authorName: "Sam",
|
||||||
|
staffIds: ["sup", "prod", "admin"],
|
||||||
|
});
|
||||||
|
expect(out.map((p) => p.userId).sort()).toEqual(["admin", "artist", "prod"]);
|
||||||
|
expect(out[0]).toMatchObject({
|
||||||
|
type: "FEEDBACK_ADDED",
|
||||||
|
title: "New feedback",
|
||||||
|
message: "Sam commented on DH2_010 at frame 1012",
|
||||||
|
data: { versionId: "v1", shotCode: "DH2_010", frameNumber: 1012 },
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it("does not notify an artist twice when they are also staff or on both shot and task", () => {
|
||||||
|
const out = buildCommentNotifications({
|
||||||
|
notes: [note("v1", "A", 1, ["prod", "prod", null])],
|
||||||
|
authorId: "x",
|
||||||
|
authorName: "X",
|
||||||
|
staffIds: ["prod"],
|
||||||
|
});
|
||||||
|
expect(out.map((p) => p.userId)).toEqual(["prod"]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("labels client comments", () => {
|
||||||
|
const [p] = buildCommentNotifications({
|
||||||
|
notes: [note("v1", "A", 5)],
|
||||||
|
authorId: "client",
|
||||||
|
authorName: "Netflix",
|
||||||
|
origin: "client",
|
||||||
|
staffIds: ["prod"],
|
||||||
|
});
|
||||||
|
expect(p.title).toBe("New client feedback");
|
||||||
|
expect(p.message).toBe("Client Netflix commented on A at frame 5");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("groups a pasted round into one notification per version", () => {
|
||||||
|
const out = buildCommentNotifications({
|
||||||
|
notes: [note("v1", "A", 1, ["art1"]), note("v1", "A", 9), note("v2", "B", 3, ["art2"])],
|
||||||
|
authorId: "prod",
|
||||||
|
authorName: "Pat",
|
||||||
|
origin: "whatsapp",
|
||||||
|
staffIds: ["prod", "sup"],
|
||||||
|
});
|
||||||
|
const msgs = out.map((p) => `${p.userId}: ${p.message}`).sort();
|
||||||
|
expect(msgs).toEqual([
|
||||||
|
"art1: Client feedback (logged by Pat) left 2 notes on A",
|
||||||
|
"art2: Client feedback (logged by Pat) commented on B at frame 3",
|
||||||
|
"sup: Client feedback (logged by Pat) commented on B at frame 3",
|
||||||
|
"sup: Client feedback (logged by Pat) left 2 notes on A",
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("sends nothing for no notes", () => {
|
||||||
|
expect(
|
||||||
|
buildCommentNotifications({ notes: [], authorId: "a", authorName: "A", staffIds: ["b"] })
|
||||||
|
).toEqual([]);
|
||||||
|
});
|
||||||
|
});
|
||||||
+94
-23
@@ -78,29 +78,6 @@ export async function notifyNewVersionUploaded(params: {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Notify the shot's artist about new feedback.
|
|
||||||
*/
|
|
||||||
export async function notifyFeedbackAdded(params: {
|
|
||||||
artistId: string;
|
|
||||||
shotCode: string;
|
|
||||||
frameNumber: number;
|
|
||||||
versionId: string;
|
|
||||||
authorName: string;
|
|
||||||
}) {
|
|
||||||
await createNotification({
|
|
||||||
userId: params.artistId,
|
|
||||||
type: NotificationType.FEEDBACK_ADDED,
|
|
||||||
title: "New feedback on your shot",
|
|
||||||
message: `${params.authorName} commented on ${params.shotCode} at frame ${params.frameNumber}`,
|
|
||||||
data: {
|
|
||||||
versionId: params.versionId,
|
|
||||||
shotCode: params.shotCode,
|
|
||||||
frameNumber: params.frameNumber,
|
|
||||||
},
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Notify relevant users of an approval status change.
|
* Notify relevant users of an approval status change.
|
||||||
*/
|
*/
|
||||||
@@ -250,3 +227,97 @@ export async function notifyCommentReply(params: {
|
|||||||
},
|
},
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** One new comment, as the recipients of its notification need it. */
|
||||||
|
export interface NewCommentNote {
|
||||||
|
versionId: string;
|
||||||
|
shotCode: string;
|
||||||
|
frameNumber: number;
|
||||||
|
/** The shot's artist and, for a task version, the task's artist. */
|
||||||
|
artistIds: (string | null | undefined)[];
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Who hears about new comments, and what they read. Pure so it can be tested:
|
||||||
|
* every active staff member plus each note's artist, never the author.
|
||||||
|
* Notes are grouped per version so a pasted round of client feedback is one
|
||||||
|
* notification per shot rather than one per line.
|
||||||
|
*/
|
||||||
|
export function buildCommentNotifications(params: {
|
||||||
|
notes: NewCommentNote[];
|
||||||
|
authorId: string;
|
||||||
|
authorName: string;
|
||||||
|
/** "client" = typed on a client review link; "whatsapp" = pasted by staff. */
|
||||||
|
origin?: "client" | "whatsapp";
|
||||||
|
staffIds: string[];
|
||||||
|
}): CreateNotificationPayload[] {
|
||||||
|
const byVersion = new Map<string, NewCommentNote[]>();
|
||||||
|
for (const n of params.notes) {
|
||||||
|
byVersion.set(n.versionId, [...(byVersion.get(n.versionId) ?? []), n]);
|
||||||
|
}
|
||||||
|
|
||||||
|
const who =
|
||||||
|
params.origin === "client"
|
||||||
|
? `Client ${params.authorName}`
|
||||||
|
: params.origin === "whatsapp"
|
||||||
|
? `Client feedback (logged by ${params.authorName})`
|
||||||
|
: params.authorName;
|
||||||
|
const title = params.origin ? "New client feedback" : "New feedback";
|
||||||
|
|
||||||
|
const payloads: CreateNotificationPayload[] = [];
|
||||||
|
for (const [versionId, notes] of byVersion) {
|
||||||
|
const { shotCode, frameNumber } = notes[0];
|
||||||
|
const message =
|
||||||
|
notes.length === 1
|
||||||
|
? `${who} commented on ${shotCode} at frame ${frameNumber}`
|
||||||
|
: `${who} left ${notes.length} notes on ${shotCode}`;
|
||||||
|
const recipients = new Set([
|
||||||
|
...params.staffIds,
|
||||||
|
...notes.flatMap((n) => n.artistIds).filter((id): id is string => !!id),
|
||||||
|
]);
|
||||||
|
recipients.delete(params.authorId);
|
||||||
|
for (const userId of recipients) {
|
||||||
|
payloads.push({
|
||||||
|
userId,
|
||||||
|
type: NotificationType.FEEDBACK_ADDED,
|
||||||
|
title,
|
||||||
|
message,
|
||||||
|
data: { versionId, shotCode, frameNumber },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return payloads;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Notify staff and the shot's artist about new comments. Artists who are not
|
||||||
|
* staff are only told when they are still active.
|
||||||
|
*/
|
||||||
|
export async function notifyCommentsAdded(params: {
|
||||||
|
notes: NewCommentNote[];
|
||||||
|
authorId: string;
|
||||||
|
authorName: string;
|
||||||
|
origin?: "client" | "whatsapp";
|
||||||
|
}) {
|
||||||
|
if (params.notes.length === 0) return;
|
||||||
|
const artistIds = [
|
||||||
|
...new Set(params.notes.flatMap((n) => n.artistIds).filter((id): id is string => !!id)),
|
||||||
|
];
|
||||||
|
const [staff, activeArtists] = await Promise.all([
|
||||||
|
db.user.findMany({
|
||||||
|
where: { role: { in: ["ADMIN", "PRODUCER", "SUPERVISOR"] }, isActive: true },
|
||||||
|
select: { id: true },
|
||||||
|
}),
|
||||||
|
db.user.findMany({
|
||||||
|
where: { id: { in: artistIds }, isActive: true, role: { not: "CLIENT" } },
|
||||||
|
select: { id: true },
|
||||||
|
}),
|
||||||
|
]);
|
||||||
|
const active = new Set(activeArtists.map((u) => u.id));
|
||||||
|
const payloads = buildCommentNotifications({
|
||||||
|
...params,
|
||||||
|
notes: params.notes.map((n) => ({ ...n, artistIds: n.artistIds.filter((id) => id && active.has(id)) })),
|
||||||
|
staffIds: staff.map((u) => u.id),
|
||||||
|
});
|
||||||
|
if (payloads.length) await createNotifications(payloads);
|
||||||
|
}
|
||||||
|
|||||||
@@ -0,0 +1,18 @@
|
|||||||
|
/**
|
||||||
|
* Worker artifact kinds (E20) and the object-storage folder each lands in:
|
||||||
|
* preview → videos/, thumbnail → image/, metadata/log → renders/, highres (the
|
||||||
|
* delivery MOV) → highres/ beside the manually uploaded High Res files.
|
||||||
|
*/
|
||||||
|
export const ARTIFACT_KIND_FOLDERS: Record<string, string> = {
|
||||||
|
preview: "videos",
|
||||||
|
thumbnail: "image",
|
||||||
|
metadata: "renders",
|
||||||
|
log: "renders",
|
||||||
|
highres: "highres",
|
||||||
|
};
|
||||||
|
|
||||||
|
/** True for keys artifact-presign could have issued — guards E20b. */
|
||||||
|
export function isArtifactKey(key: string): boolean {
|
||||||
|
const folder = key.split("/")[0];
|
||||||
|
return key.includes("/") && !key.includes("..") && Object.values(ARTIFACT_KIND_FOLDERS).includes(folder);
|
||||||
|
}
|
||||||
@@ -5,6 +5,7 @@ import { PipelineError } from "./errors";
|
|||||||
import { applyTransition } from "./transitions";
|
import { applyTransition } from "./transitions";
|
||||||
import { getConfigNumber, getConfigValue } from "./config";
|
import { getConfigNumber, getConfigValue } from "./config";
|
||||||
import { clientShotCode } from "@/lib/shot-code";
|
import { clientShotCode } from "@/lib/shot-code";
|
||||||
|
import type { RecordShareInput, RecordUploadInput } from "./delivery-handoff";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Delivery builder (RenderPipeline2 §11). The web app decides *what* goes in a
|
* Delivery builder (RenderPipeline2 §11). The web app decides *what* goes in a
|
||||||
@@ -640,11 +641,33 @@ export async function listDeliveryPackages(filter: {
|
|||||||
},
|
},
|
||||||
orderBy: { createdAt: "desc" },
|
orderBy: { createdAt: "desc" },
|
||||||
include: {
|
include: {
|
||||||
items: { select: { id: true, shotCode: true, versionString: true, status: true, fileCount: true, linkMode: true, errorMessage: true } },
|
items: {
|
||||||
|
select: {
|
||||||
|
id: true,
|
||||||
|
shotCode: true,
|
||||||
|
clientCode: true,
|
||||||
|
versionString: true,
|
||||||
|
status: true,
|
||||||
|
fileCount: true,
|
||||||
|
totalBytes: true,
|
||||||
|
movPath: true,
|
||||||
|
linkMode: true,
|
||||||
|
errorMessage: true,
|
||||||
|
},
|
||||||
|
},
|
||||||
project: { select: { id: true, name: true, code: true } },
|
project: { select: { id: true, name: true, code: true } },
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// Who recorded each handoff step — the ids are plain columns, not relations.
|
||||||
|
const userIds = [
|
||||||
|
...new Set(packages.flatMap((p) => [p.uploadedById, p.deliveredById]).filter((id): id is string => !!id)),
|
||||||
|
];
|
||||||
|
const users = userIds.length
|
||||||
|
? await db.user.findMany({ where: { id: { in: userIds } }, select: { id: true, name: true, email: true } })
|
||||||
|
: [];
|
||||||
|
const userName = new Map(users.map((u) => [u.id, u.name ?? u.email]));
|
||||||
|
|
||||||
return {
|
return {
|
||||||
packages: packages.map((p) => ({
|
packages: packages.map((p) => ({
|
||||||
id: p.id,
|
id: p.id,
|
||||||
@@ -659,30 +682,71 @@ export async function listDeliveryPackages(filter: {
|
|||||||
projectCode: p.project.code,
|
projectCode: p.project.code,
|
||||||
createdAt: p.createdAt,
|
createdAt: p.createdAt,
|
||||||
builtAt: p.builtAt,
|
builtAt: p.builtAt,
|
||||||
|
uploadUrl: p.uploadUrl,
|
||||||
|
uploadedAt: p.uploadedAt,
|
||||||
|
uploadedByName: p.uploadedById ? (userName.get(p.uploadedById) ?? null) : null,
|
||||||
|
sharedWith: p.sharedWith,
|
||||||
|
sharedNote: p.sharedNote,
|
||||||
deliveredAt: p.deliveredAt,
|
deliveredAt: p.deliveredAt,
|
||||||
|
deliveredByName: p.deliveredById ? (userName.get(p.deliveredById) ?? null) : null,
|
||||||
itemCount: p.items.length,
|
itemCount: p.items.length,
|
||||||
verifiedCount: p.items.filter((i) => i.status === "VERIFIED").length,
|
verifiedCount: p.items.filter((i) => i.status === "VERIFIED").length,
|
||||||
items: p.items,
|
// What the upload should contain, for the person comparing it against
|
||||||
|
// the client's portal.
|
||||||
|
exrFileCount: p.items.reduce((sum, i) => sum + (i.fileCount ?? 0), 0),
|
||||||
|
movCount: p.items.filter((i) => i.movPath).length,
|
||||||
|
totalBytes: p.items.reduce((sum, i) => sum + Number(i.totalBytes ?? 0), 0),
|
||||||
|
items: p.items.map(({ totalBytes: _bytes, movPath: _mov, ...item }) => item),
|
||||||
})),
|
})),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
/** E19 — the human uploaded the folder to the client and is confirming it. */
|
function assertHandoffAllowed(pkg: { kind: DeliveryKind; status: DeliveryStatus }, verb: string) {
|
||||||
export async function markDelivered(packageId: string, userId: string) {
|
if (pkg.kind !== "EXR_DELIVERY") {
|
||||||
|
throw new PipelineError(
|
||||||
|
409,
|
||||||
|
"A MOV review package is shared for review, not delivered — it has no delivered state"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (pkg.status !== "READY") {
|
||||||
|
throw new PipelineError(409, `Package is ${pkg.status} — only a READY package can be ${verb}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Step one of the handoff: the folder is on the client's portal, and this is
|
||||||
|
* where. Repeatable while the package is READY, so a wrong link can be
|
||||||
|
* corrected before it is shared.
|
||||||
|
*/
|
||||||
|
export async function markUploaded(packageId: string, input: RecordUploadInput, userId: string) {
|
||||||
|
return db.$transaction(async (tx) => {
|
||||||
|
const pkg = await tx.deliveryPackage.findUnique({ where: { id: packageId } });
|
||||||
|
if (!pkg) throw new PipelineError(404, "Delivery package not found");
|
||||||
|
assertHandoffAllowed(pkg, "recorded as uploaded");
|
||||||
|
|
||||||
|
const updated = await tx.deliveryPackage.update({
|
||||||
|
where: { id: pkg.id },
|
||||||
|
data: { uploadUrl: input.uploadUrl, uploadedAt: new Date(), uploadedById: userId },
|
||||||
|
});
|
||||||
|
return { package: { id: updated.id, status: updated.status, uploadUrl: updated.uploadUrl } };
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* E19 — step two: the link was sent to a named person, which is what makes the
|
||||||
|
* package DELIVERED. Refused until the upload location is on record, so
|
||||||
|
* "delivered" always has somewhere to point.
|
||||||
|
*/
|
||||||
|
export async function markDelivered(packageId: string, input: RecordShareInput, userId: string) {
|
||||||
return db.$transaction(async (tx) => {
|
return db.$transaction(async (tx) => {
|
||||||
const pkg = await tx.deliveryPackage.findUnique({ where: { id: packageId }, include: { items: true } });
|
const pkg = await tx.deliveryPackage.findUnique({ where: { id: packageId }, include: { items: true } });
|
||||||
if (!pkg) throw new PipelineError(404, "Delivery package not found");
|
if (!pkg) throw new PipelineError(404, "Delivery package not found");
|
||||||
if (pkg.status === "DELIVERED") {
|
if (pkg.status === "DELIVERED") {
|
||||||
return { package: { id: pkg.id, status: pkg.status }, alreadyApplied: true };
|
return { package: { id: pkg.id, status: pkg.status }, alreadyApplied: true };
|
||||||
}
|
}
|
||||||
if (pkg.status !== "READY") {
|
assertHandoffAllowed(pkg, "marked delivered");
|
||||||
throw new PipelineError(409, `Package is ${pkg.status} — only a READY package can be marked delivered`);
|
if (!pkg.uploadedAt || !pkg.uploadUrl) {
|
||||||
}
|
throw new PipelineError(409, "Record where the package was uploaded before marking it delivered");
|
||||||
if (pkg.kind !== "EXR_DELIVERY") {
|
|
||||||
throw new PipelineError(
|
|
||||||
409,
|
|
||||||
"A MOV review package is shared for review, not delivered — it has no delivered state"
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
for (const item of pkg.items) {
|
for (const item of pkg.items) {
|
||||||
@@ -698,7 +762,13 @@ export async function markDelivered(packageId: string, userId: string) {
|
|||||||
|
|
||||||
const updated = await tx.deliveryPackage.update({
|
const updated = await tx.deliveryPackage.update({
|
||||||
where: { id: pkg.id },
|
where: { id: pkg.id },
|
||||||
data: { status: "DELIVERED", deliveredAt: new Date(), deliveredById: userId },
|
data: {
|
||||||
|
status: "DELIVERED",
|
||||||
|
sharedWith: input.sharedWith,
|
||||||
|
sharedNote: input.note || null,
|
||||||
|
deliveredAt: new Date(),
|
||||||
|
deliveredById: userId,
|
||||||
|
},
|
||||||
});
|
});
|
||||||
return { package: { id: updated.id, status: updated.status }, alreadyApplied: false };
|
return { package: { id: updated.id, status: updated.status }, alreadyApplied: false };
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -0,0 +1,72 @@
|
|||||||
|
import { describe, expect, it } from "vitest";
|
||||||
|
import { buildShareMessage, handoffStage, recordShareSchema, recordUploadSchema } from "./delivery-handoff";
|
||||||
|
|
||||||
|
describe("handoffStage", () => {
|
||||||
|
const ready = { kind: "EXR_DELIVERY", status: "READY", uploadedAt: null };
|
||||||
|
|
||||||
|
it("waits on the upload first, then on the share", () => {
|
||||||
|
expect(handoffStage(ready)).toBe("AWAITING_UPLOAD");
|
||||||
|
expect(handoffStage({ ...ready, uploadedAt: new Date() })).toBe("AWAITING_SHARE");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("waits on nothing before the build or after delivery", () => {
|
||||||
|
expect(handoffStage({ ...ready, status: "BUILDING" })).toBeNull();
|
||||||
|
expect(handoffStage({ ...ready, status: "FAILED" })).toBeNull();
|
||||||
|
expect(handoffStage({ ...ready, status: "DELIVERED", uploadedAt: new Date() })).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("never asks for a review package to be delivered", () => {
|
||||||
|
expect(handoffStage({ ...ready, kind: "MOV_REVIEW" })).toBeNull();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("recordUploadSchema", () => {
|
||||||
|
const url = "https://contenthub.example.com/folders/abc";
|
||||||
|
|
||||||
|
it("accepts a link with the contents confirmed", () => {
|
||||||
|
expect(recordUploadSchema.safeParse({ uploadUrl: url, contentsConfirmed: true }).success).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("refuses an unconfirmed upload", () => {
|
||||||
|
expect(recordUploadSchema.safeParse({ uploadUrl: url, contentsConfirmed: false }).success).toBe(false);
|
||||||
|
expect(recordUploadSchema.safeParse({ uploadUrl: url }).success).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("refuses anything that is not a web link", () => {
|
||||||
|
for (const uploadUrl of ["", "uploaded", "//SAN/DELIVERY/ACME/101", "javascript:alert(1)"]) {
|
||||||
|
expect(recordUploadSchema.safeParse({ uploadUrl, contentsConfirmed: true }).success).toBe(false);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("recordShareSchema", () => {
|
||||||
|
it("needs a recipient", () => {
|
||||||
|
expect(recordShareSchema.safeParse({ sharedWith: " " }).success).toBe(false);
|
||||||
|
expect(recordShareSchema.safeParse({ sharedWith: "Sam (post super)" }).success).toBe(true);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("buildShareMessage", () => {
|
||||||
|
it("lists the packaged versions under the client's own shot codes", () => {
|
||||||
|
const message = buildShareMessage({
|
||||||
|
projectCode: "UNG",
|
||||||
|
episode: "116",
|
||||||
|
name: "20260930_Delivery",
|
||||||
|
uploadUrl: "https://contenthub.example.com/folders/abc",
|
||||||
|
items: [
|
||||||
|
{ shotCode: "UNG_116_020", clientCode: null, versionString: "v002" },
|
||||||
|
{ shotCode: "UNG_116_010", clientCode: "116_A_0010", versionString: "v004" },
|
||||||
|
],
|
||||||
|
});
|
||||||
|
expect(message).toBe(
|
||||||
|
[
|
||||||
|
"Delivery: UNG · episode 116 · 20260930_Delivery",
|
||||||
|
"2 shots",
|
||||||
|
"https://contenthub.example.com/folders/abc",
|
||||||
|
"",
|
||||||
|
"116_A_0010 v004",
|
||||||
|
"UNG_116_020 v002",
|
||||||
|
].join("\n")
|
||||||
|
);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,73 @@
|
|||||||
|
import { z } from "zod";
|
||||||
|
import { clientShotCode } from "@/lib/shot-code";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The handoff after a package is built: upload it, then share the link.
|
||||||
|
*
|
||||||
|
* Kept free of database imports so the deliveries page can use the same stage
|
||||||
|
* logic and share message the server does.
|
||||||
|
*/
|
||||||
|
|
||||||
|
export type HandoffStage = "AWAITING_UPLOAD" | "AWAITING_SHARE";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* What a built EXR package is still waiting on, or null when it is waiting on
|
||||||
|
* nothing — not built yet, already delivered, or a review (which has no
|
||||||
|
* delivered state at all).
|
||||||
|
*/
|
||||||
|
export function handoffStage(pkg: {
|
||||||
|
kind: string;
|
||||||
|
status: string;
|
||||||
|
uploadedAt: Date | string | null;
|
||||||
|
}): HandoffStage | null {
|
||||||
|
if (pkg.kind !== "EXR_DELIVERY" || pkg.status !== "READY") return null;
|
||||||
|
return pkg.uploadedAt ? "AWAITING_SHARE" : "AWAITING_UPLOAD";
|
||||||
|
}
|
||||||
|
|
||||||
|
export const recordUploadSchema = z.object({
|
||||||
|
uploadUrl: z
|
||||||
|
.string()
|
||||||
|
.trim()
|
||||||
|
.max(2000)
|
||||||
|
.url("Paste the full link to the upload folder")
|
||||||
|
.refine((value) => /^https?:\/\//i.test(value), "The upload link must start with http:// or https://"),
|
||||||
|
/** The person looked at the upload and its contents match the package. */
|
||||||
|
contentsConfirmed: z.literal(true, {
|
||||||
|
errorMap: () => ({ message: "Confirm the uploaded files match the package" }),
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
|
||||||
|
export type RecordUploadInput = z.infer<typeof recordUploadSchema>;
|
||||||
|
|
||||||
|
export const recordShareSchema = z.object({
|
||||||
|
sharedWith: z.string().trim().min(1, "Say who the link was sent to").max(200),
|
||||||
|
note: z.string().trim().max(1000).optional().nullable(),
|
||||||
|
});
|
||||||
|
|
||||||
|
export type RecordShareInput = z.infer<typeof recordShareSchema>;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The message sent to the client with the link. Generated rather than typed so
|
||||||
|
* the shots and versions the client is told about are the ones in the package.
|
||||||
|
*/
|
||||||
|
export function buildShareMessage(pkg: {
|
||||||
|
projectCode: string;
|
||||||
|
episode: string;
|
||||||
|
name: string;
|
||||||
|
uploadUrl: string;
|
||||||
|
items: { shotCode: string; clientCode?: string | null; versionString: string }[];
|
||||||
|
}): string {
|
||||||
|
const shots = pkg.items
|
||||||
|
.map((item) => `${clientShotCode(item)} ${item.versionString}`)
|
||||||
|
.sort((a, b) => a.localeCompare(b));
|
||||||
|
const heading = [pkg.projectCode, pkg.episode ? `episode ${pkg.episode}` : "", pkg.name]
|
||||||
|
.filter(Boolean)
|
||||||
|
.join(" · ");
|
||||||
|
return [
|
||||||
|
`Delivery: ${heading}`,
|
||||||
|
`${shots.length} shot${shots.length === 1 ? "" : "s"}`,
|
||||||
|
pkg.uploadUrl,
|
||||||
|
"",
|
||||||
|
...shots,
|
||||||
|
].join("\n");
|
||||||
|
}
|
||||||
@@ -0,0 +1,113 @@
|
|||||||
|
import { describe, expect, it } from "vitest";
|
||||||
|
import {
|
||||||
|
createRequestSchema,
|
||||||
|
matchShotCodes,
|
||||||
|
parseShotCodes,
|
||||||
|
resolveLineStage,
|
||||||
|
waitingSeverity,
|
||||||
|
} from "./delivery-request-state";
|
||||||
|
|
||||||
|
describe("parseShotCodes", () => {
|
||||||
|
it("takes codes out of a pasted message whatever separates them", () => {
|
||||||
|
expect(parseShotCodes("UNG_116_010, UNG_116_020\nUNG_116_030; 116-A-0040")).toEqual([
|
||||||
|
"UNG_116_010",
|
||||||
|
"UNG_116_020",
|
||||||
|
"UNG_116_030",
|
||||||
|
"116-A-0040",
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("drops repeats regardless of case", () => {
|
||||||
|
expect(parseShotCodes("ung_116_010 UNG_116_010")).toEqual(["ung_116_010"]);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("matchShotCodes", () => {
|
||||||
|
const shots = [
|
||||||
|
{ id: "a", shotCode: "UNG_116_010", clientCode: "116_A_0010" },
|
||||||
|
{ id: "b", shotCode: "UNG_116_020", clientCode: null },
|
||||||
|
];
|
||||||
|
|
||||||
|
it("matches our code or the client's, in any case", () => {
|
||||||
|
const { matched, unmatched } = matchShotCodes(["116_a_0010", "ung_116_020"], shots);
|
||||||
|
expect(matched.map((s) => s.id)).toEqual(["a", "b"]);
|
||||||
|
expect(unmatched).toEqual([]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("reports what it could not match instead of dropping it", () => {
|
||||||
|
expect(matchShotCodes(["UNG_116_010", "UNG_116_999"], shots).unmatched).toEqual(["UNG_116_999"]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("counts a shot once when both of its codes are given", () => {
|
||||||
|
expect(matchShotCodes(["UNG_116_010", "116_A_0010"], shots).matched).toHaveLength(1);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("resolveLineStage", () => {
|
||||||
|
const logged = new Date("2026-09-30T14:00:00Z");
|
||||||
|
const before = new Date("2026-09-20T10:00:00Z");
|
||||||
|
const after = new Date("2026-10-01T10:00:00Z");
|
||||||
|
const base = {
|
||||||
|
requestCreatedAt: logged,
|
||||||
|
packages: [],
|
||||||
|
manual: { deliveredAt: null, url: null, sharedWith: null },
|
||||||
|
exportStatuses: [],
|
||||||
|
};
|
||||||
|
|
||||||
|
it("walks a shot from not ready through to delivered", () => {
|
||||||
|
expect(resolveLineStage(base)).toBe("NOT_READY");
|
||||||
|
expect(resolveLineStage({ ...base, exportStatuses: ["READY_FOR_QC"] })).toBe("IN_QC");
|
||||||
|
expect(resolveLineStage({ ...base, exportStatuses: ["READY_FOR_QC", "READY_FOR_DELIVERY"] })).toBe("READY");
|
||||||
|
const pkg = { status: "BUILDING", uploadedAt: null, deliveredAt: null };
|
||||||
|
expect(resolveLineStage({ ...base, packages: [pkg] })).toBe("BUILDING");
|
||||||
|
expect(resolveLineStage({ ...base, packages: [{ ...pkg, status: "READY" }] })).toBe("BUILT");
|
||||||
|
expect(resolveLineStage({ ...base, packages: [{ ...pkg, status: "READY", uploadedAt: after }] })).toBe("UPLOADED");
|
||||||
|
expect(
|
||||||
|
resolveLineStage({ ...base, packages: [{ status: "DELIVERED", uploadedAt: after, deliveredAt: after }] })
|
||||||
|
).toBe("DELIVERED");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("does not let a delivery from before the request close it", () => {
|
||||||
|
expect(
|
||||||
|
resolveLineStage({ ...base, packages: [{ status: "DELIVERED", uploadedAt: before, deliveredAt: before }] })
|
||||||
|
).toBe("NOT_READY");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("closes on a manual delivery only with a link and a recipient", () => {
|
||||||
|
const sameDay = new Date("2026-09-30T12:00:00Z");
|
||||||
|
const manual = { deliveredAt: sameDay, url: "https://x.example/f", sharedWith: "Sam" };
|
||||||
|
expect(resolveLineStage({ ...base, manual })).toBe("DELIVERED");
|
||||||
|
expect(resolveLineStage({ ...base, manual: { ...manual, url: null } })).toBe("NOT_READY");
|
||||||
|
expect(resolveLineStage({ ...base, manual: { ...manual, sharedWith: null } })).toBe("NOT_READY");
|
||||||
|
expect(resolveLineStage({ ...base, manual: { ...manual, deliveredAt: before } })).toBe("NOT_READY");
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("waitingSeverity", () => {
|
||||||
|
const now = new Date("2026-09-30T12:00:00Z").getTime();
|
||||||
|
const hoursAgo = (h: number) => new Date(now - h * 3600_000);
|
||||||
|
|
||||||
|
it("escalates with age", () => {
|
||||||
|
expect(waitingSeverity(hoursAgo(2), null, now)).toBe("normal");
|
||||||
|
expect(waitingSeverity(hoursAgo(30), null, now)).toBe("warning");
|
||||||
|
expect(waitingSeverity(hoursAgo(50), null, now)).toBe("critical");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("is critical once past the due date, however new", () => {
|
||||||
|
expect(waitingSeverity(hoursAgo(2), hoursAgo(1), now)).toBe("critical");
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("createRequestSchema", () => {
|
||||||
|
const base = { projectId: "p", deliverable: "EXR", requestedBy: "Sam" };
|
||||||
|
|
||||||
|
it("needs exactly one way of naming the shots", () => {
|
||||||
|
expect(createRequestSchema.safeParse(base).success).toBe(false);
|
||||||
|
expect(createRequestSchema.safeParse({ ...base, episode: "116" }).success).toBe(true);
|
||||||
|
expect(createRequestSchema.safeParse({ ...base, episode: "116", shotCodes: "UNG_116_010" }).success).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("needs to know who asked", () => {
|
||||||
|
expect(createRequestSchema.safeParse({ ...base, episode: "116", requestedBy: " " }).success).toBe(false);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,163 @@
|
|||||||
|
import { z } from "zod";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Delivery request rules with no database behind them, shared by the server
|
||||||
|
* and the pages that show requests.
|
||||||
|
*/
|
||||||
|
|
||||||
|
export const DELIVERABLES = ["EXR", "MOV", "EXR_AND_MOV"] as const;
|
||||||
|
export type Deliverable = (typeof DELIVERABLES)[number];
|
||||||
|
|
||||||
|
export const DELIVERABLE_LABEL: Record<Deliverable, string> = {
|
||||||
|
EXR: "EXRs",
|
||||||
|
MOV: "MOVs",
|
||||||
|
EXR_AND_MOV: "EXRs + MOVs",
|
||||||
|
};
|
||||||
|
|
||||||
|
/** Where one requested shot stands, from furthest along to not started. */
|
||||||
|
export type RequestLineStage =
|
||||||
|
| "DELIVERED"
|
||||||
|
| "UPLOADED"
|
||||||
|
| "BUILT"
|
||||||
|
| "BUILDING"
|
||||||
|
| "READY"
|
||||||
|
| "IN_QC"
|
||||||
|
| "NOT_READY";
|
||||||
|
|
||||||
|
export const LINE_STAGE_LABEL: Record<RequestLineStage, string> = {
|
||||||
|
DELIVERED: "delivered",
|
||||||
|
UPLOADED: "uploaded, link not shared",
|
||||||
|
BUILT: "built, not uploaded",
|
||||||
|
BUILDING: "package building",
|
||||||
|
READY: "ready to package",
|
||||||
|
IN_QC: "in QC",
|
||||||
|
NOT_READY: "not through QC",
|
||||||
|
};
|
||||||
|
|
||||||
|
export const createRequestSchema = z
|
||||||
|
.object({
|
||||||
|
projectId: z.string().min(1),
|
||||||
|
/** Exactly one of these three says which shots were asked for. */
|
||||||
|
episode: z.string().trim().min(1).max(50).optional().nullable(),
|
||||||
|
shotIds: z.array(z.string().min(1)).min(1).max(1000).optional().nullable(),
|
||||||
|
shotCodes: z.string().trim().min(1).max(20000).optional().nullable(),
|
||||||
|
deliverable: z.enum(DELIVERABLES),
|
||||||
|
requestedBy: z.string().trim().min(1, "Say who asked for it").max(200),
|
||||||
|
dueDate: z.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional().nullable(),
|
||||||
|
note: z.string().trim().max(2000).optional().nullable(),
|
||||||
|
})
|
||||||
|
.refine((v) => [v.episode, v.shotIds, v.shotCodes].filter(Boolean).length === 1, {
|
||||||
|
message: "Choose an episode, a shot selection or a list of shot codes",
|
||||||
|
});
|
||||||
|
|
||||||
|
export type CreateRequestInput = z.infer<typeof createRequestSchema>;
|
||||||
|
|
||||||
|
export const cancelRequestSchema = z.object({
|
||||||
|
reason: z.string().trim().min(1, "Say why the request is being cancelled").max(500),
|
||||||
|
});
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Shot codes out of a pasted message: split on anything that is not part of a
|
||||||
|
* code, so "116_010, 116_020\n116_030" and a column copied from a sheet both
|
||||||
|
* work. Order is kept and repeats dropped.
|
||||||
|
*/
|
||||||
|
export function parseShotCodes(text: string): string[] {
|
||||||
|
const seen = new Set<string>();
|
||||||
|
const codes: string[] = [];
|
||||||
|
for (const raw of text.split(/[^A-Za-z0-9_\-.]+/)) {
|
||||||
|
const code = raw.trim();
|
||||||
|
const key = code.toLowerCase();
|
||||||
|
if (!code || seen.has(key)) continue;
|
||||||
|
seen.add(key);
|
||||||
|
codes.push(code);
|
||||||
|
}
|
||||||
|
return codes;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Pasted codes against a project's shots. The client writes their own codes
|
||||||
|
* and we write ours, so either matches; anything that matches neither is
|
||||||
|
* returned rather than dropped, because a silently skipped shot is exactly the
|
||||||
|
* kind of miss a request exists to prevent.
|
||||||
|
*/
|
||||||
|
export function matchShotCodes<T extends { shotCode: string; clientCode?: string | null }>(
|
||||||
|
codes: string[],
|
||||||
|
shots: T[]
|
||||||
|
): { matched: T[]; unmatched: string[] } {
|
||||||
|
const byCode = new Map<string, T>();
|
||||||
|
for (const shot of shots) {
|
||||||
|
byCode.set(shot.shotCode.toLowerCase(), shot);
|
||||||
|
const alias = shot.clientCode?.trim().toLowerCase();
|
||||||
|
if (alias && !byCode.has(alias)) byCode.set(alias, shot);
|
||||||
|
}
|
||||||
|
const matched = new Set<T>();
|
||||||
|
const unmatched: string[] = [];
|
||||||
|
for (const code of codes) {
|
||||||
|
const shot = byCode.get(code.toLowerCase());
|
||||||
|
if (shot) matched.add(shot);
|
||||||
|
else unmatched.push(code);
|
||||||
|
}
|
||||||
|
return { matched: [...matched], unmatched };
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Where a requested shot stands. Only a delivery made after the request was
|
||||||
|
* logged closes the line — a client asking again for something already sent
|
||||||
|
* is asking for it to be sent again.
|
||||||
|
*/
|
||||||
|
export function resolveLineStage(input: {
|
||||||
|
requestCreatedAt: Date;
|
||||||
|
/** EXR delivery packages containing the shot. */
|
||||||
|
packages: { status: string; uploadedAt: Date | null; deliveredAt: Date | null }[];
|
||||||
|
manual: { deliveredAt: Date | null; url: string | null; sharedWith: string | null };
|
||||||
|
/** Statuses of the shot's exports. */
|
||||||
|
exportStatuses: string[];
|
||||||
|
}): RequestLineStage {
|
||||||
|
const { requestCreatedAt, packages, manual, exportStatuses } = input;
|
||||||
|
if (
|
||||||
|
packages.some((p) => p.status === "DELIVERED" && p.deliveredAt && p.deliveredAt >= requestCreatedAt)
|
||||||
|
) {
|
||||||
|
return "DELIVERED";
|
||||||
|
}
|
||||||
|
if (
|
||||||
|
manual.deliveredAt &&
|
||||||
|
manual.url &&
|
||||||
|
manual.sharedWith &&
|
||||||
|
manualDeliveryCounts(manual.deliveredAt, requestCreatedAt)
|
||||||
|
) {
|
||||||
|
return "DELIVERED";
|
||||||
|
}
|
||||||
|
const ready = packages.filter((p) => p.status === "READY");
|
||||||
|
if (ready.some((p) => p.uploadedAt)) return "UPLOADED";
|
||||||
|
if (ready.length) return "BUILT";
|
||||||
|
if (packages.some((p) => p.status === "QUEUED" || p.status === "BUILDING")) return "BUILDING";
|
||||||
|
if (exportStatuses.includes("READY_FOR_DELIVERY")) return "READY";
|
||||||
|
if (exportStatuses.includes("READY_FOR_QC")) return "IN_QC";
|
||||||
|
return "NOT_READY";
|
||||||
|
}
|
||||||
|
|
||||||
|
const DAY_MS = 24 * 3600_000;
|
||||||
|
|
||||||
|
/** Past its due date or two days old is critical; a day old is a warning. */
|
||||||
|
export function waitingSeverity(
|
||||||
|
since: Date,
|
||||||
|
dueDate: Date | null,
|
||||||
|
now = Date.now()
|
||||||
|
): "normal" | "warning" | "critical" {
|
||||||
|
if (dueDate && dueDate.getTime() < now) return "critical";
|
||||||
|
const age = now - since.getTime();
|
||||||
|
return age >= 2 * DAY_MS ? "critical" : age >= DAY_MS ? "warning" : "normal";
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A manual delivery is recorded as a calendar day (noon UTC), so it counts for
|
||||||
|
* a request logged any time that same day.
|
||||||
|
*/
|
||||||
|
export function manualDeliveryCounts(manualDeliveredAt: Date, requestCreatedAt: Date): boolean {
|
||||||
|
const dayStart = Date.UTC(
|
||||||
|
requestCreatedAt.getUTCFullYear(),
|
||||||
|
requestCreatedAt.getUTCMonth(),
|
||||||
|
requestCreatedAt.getUTCDate()
|
||||||
|
);
|
||||||
|
return manualDeliveredAt.getTime() >= dayStart;
|
||||||
|
}
|
||||||
@@ -0,0 +1,256 @@
|
|||||||
|
import { db } from "@/lib/db";
|
||||||
|
import { PipelineError } from "./errors";
|
||||||
|
import {
|
||||||
|
matchShotCodes,
|
||||||
|
parseShotCodes,
|
||||||
|
resolveLineStage,
|
||||||
|
waitingSeverity,
|
||||||
|
type CreateRequestInput,
|
||||||
|
type RequestLineStage,
|
||||||
|
} from "./delivery-request-state";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Delivery requests: what a client asked for, held open until it has gone out.
|
||||||
|
*
|
||||||
|
* A request stores only the ask and its shot list. Whether each shot has been
|
||||||
|
* delivered is read from the packages and manual deliveries themselves, so a
|
||||||
|
* request cannot say "done" when the delivery record does not.
|
||||||
|
*/
|
||||||
|
|
||||||
|
export async function createDeliveryRequest(input: CreateRequestInput, userId: string) {
|
||||||
|
const project = await db.project.findUnique({ where: { id: input.projectId }, select: { id: true } });
|
||||||
|
if (!project) throw new PipelineError(404, "Project not found");
|
||||||
|
|
||||||
|
const select = { id: true, shotCode: true, clientCode: true } as const;
|
||||||
|
let shots: { id: string; shotCode: string; clientCode: string | null }[];
|
||||||
|
|
||||||
|
if (input.episode) {
|
||||||
|
// Snapshot: the request is for the shots in the episode today. A shot
|
||||||
|
// added to the episode later is a new ask, not a silent change to this one.
|
||||||
|
shots = await db.shot.findMany({ where: { projectId: project.id, episode: input.episode }, select });
|
||||||
|
if (!shots.length) throw new PipelineError(422, `No shots in episode ${input.episode}`);
|
||||||
|
} else if (input.shotIds) {
|
||||||
|
const ids = [...new Set(input.shotIds)];
|
||||||
|
shots = await db.shot.findMany({ where: { projectId: project.id, id: { in: ids } }, select });
|
||||||
|
if (shots.length !== ids.length) {
|
||||||
|
throw new PipelineError(422, "Some of the selected shots are not in this project");
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
const codes = parseShotCodes(input.shotCodes ?? "");
|
||||||
|
const all = await db.shot.findMany({ where: { projectId: project.id }, select });
|
||||||
|
const { matched, unmatched } = matchShotCodes(codes, all);
|
||||||
|
if (unmatched.length) {
|
||||||
|
throw new PipelineError(
|
||||||
|
422,
|
||||||
|
`${unmatched.length} code${unmatched.length === 1 ? "" : "s"} did not match a shot: ${unmatched.slice(0, 10).join(", ")}${unmatched.length > 10 ? "…" : ""}`,
|
||||||
|
{ unmatched }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
shots = matched;
|
||||||
|
if (!shots.length) throw new PipelineError(422, "No shot codes found in the text");
|
||||||
|
}
|
||||||
|
|
||||||
|
return db.$transaction(async (tx) => {
|
||||||
|
const last = await tx.deliveryRequest.aggregate({
|
||||||
|
where: { projectId: project.id },
|
||||||
|
_max: { requestNumber: true },
|
||||||
|
});
|
||||||
|
const request = await tx.deliveryRequest.create({
|
||||||
|
data: {
|
||||||
|
projectId: project.id,
|
||||||
|
requestNumber: (last._max.requestNumber ?? 0) + 1,
|
||||||
|
episode: input.episode ?? "",
|
||||||
|
deliverable: input.deliverable,
|
||||||
|
requestedBy: input.requestedBy,
|
||||||
|
note: input.note || null,
|
||||||
|
// Noon UTC so the calendar day survives any timezone it is shown in.
|
||||||
|
dueDate: input.dueDate ? new Date(`${input.dueDate}T12:00:00.000Z`) : null,
|
||||||
|
createdById: userId,
|
||||||
|
lines: {
|
||||||
|
create: shots.map((s) => ({ shotId: s.id, shotCode: s.shotCode, clientCode: s.clientCode })),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
return { request: { id: request.id, requestNumber: request.requestNumber, lineCount: shots.length } };
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function cancelDeliveryRequest(requestId: string, reason: string, userId: string) {
|
||||||
|
const request = await db.deliveryRequest.findUnique({ where: { id: requestId } });
|
||||||
|
if (!request) throw new PipelineError(404, "Delivery request not found");
|
||||||
|
if (request.cancelledAt) return { request: { id: request.id }, alreadyApplied: true };
|
||||||
|
await db.deliveryRequest.update({
|
||||||
|
where: { id: request.id },
|
||||||
|
data: { cancelledAt: new Date(), cancelledById: userId, cancelReason: reason },
|
||||||
|
});
|
||||||
|
return { request: { id: request.id }, alreadyApplied: false };
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface DeliveryRequestLineView {
|
||||||
|
id: string;
|
||||||
|
shotId: string;
|
||||||
|
shotCode: string;
|
||||||
|
clientCode: string | null;
|
||||||
|
stage: RequestLineStage;
|
||||||
|
/** The export to package when the stage is READY. */
|
||||||
|
readyExportId: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface DeliveryRequestView {
|
||||||
|
id: string;
|
||||||
|
requestNumber: number;
|
||||||
|
projectId: string;
|
||||||
|
projectCode: string;
|
||||||
|
episode: string;
|
||||||
|
deliverable: string;
|
||||||
|
requestedBy: string;
|
||||||
|
note: string | null;
|
||||||
|
dueDate: Date | null;
|
||||||
|
createdAt: Date;
|
||||||
|
cancelledAt: Date | null;
|
||||||
|
cancelReason: string | null;
|
||||||
|
state: "OPEN" | "CLOSED" | "CANCELLED";
|
||||||
|
lineCount: number;
|
||||||
|
deliveredCount: number;
|
||||||
|
severity: "normal" | "warning" | "critical";
|
||||||
|
lines: DeliveryRequestLineView[];
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Requests with each line's stage worked out from the delivery record.
|
||||||
|
* `openOnly` is what the dashboard wants; the deliveries page takes the recent
|
||||||
|
* history too.
|
||||||
|
*/
|
||||||
|
export async function listDeliveryRequests(
|
||||||
|
filter: { projectId?: string; openOnly?: boolean } = {}
|
||||||
|
): Promise<DeliveryRequestView[]> {
|
||||||
|
const requests = await db.deliveryRequest.findMany({
|
||||||
|
where: {
|
||||||
|
...(filter.projectId ? { projectId: filter.projectId } : {}),
|
||||||
|
...(filter.openOnly ? { cancelledAt: null } : {}),
|
||||||
|
project: { status: { in: ["ACTIVE", "ON_HOLD"] } },
|
||||||
|
},
|
||||||
|
orderBy: { createdAt: "desc" },
|
||||||
|
take: 200,
|
||||||
|
include: {
|
||||||
|
project: { select: { code: true } },
|
||||||
|
lines: { orderBy: { shotCode: "asc" } },
|
||||||
|
},
|
||||||
|
});
|
||||||
|
if (!requests.length) return [];
|
||||||
|
|
||||||
|
const shotIds = [...new Set(requests.flatMap((r) => r.lines.map((l) => l.shotId)))];
|
||||||
|
const [items, shots, exports] = await Promise.all([
|
||||||
|
db.deliveryItem.findMany({
|
||||||
|
where: {
|
||||||
|
shotId: { in: shotIds },
|
||||||
|
package: { kind: "EXR_DELIVERY", status: { in: ["QUEUED", "BUILDING", "READY", "DELIVERED"] } },
|
||||||
|
},
|
||||||
|
select: { shotId: true, package: { select: { status: true, uploadedAt: true, deliveredAt: true } } },
|
||||||
|
}),
|
||||||
|
db.shot.findMany({
|
||||||
|
where: { id: { in: shotIds } },
|
||||||
|
select: { id: true, manualDeliveredAt: true, manualDeliveryUrl: true, manualDeliverySharedWith: true },
|
||||||
|
}),
|
||||||
|
db.export.findMany({
|
||||||
|
where: { shotId: { in: shotIds }, status: { in: ["READY_FOR_DELIVERY", "READY_FOR_QC"] } },
|
||||||
|
orderBy: { versionNumber: "desc" },
|
||||||
|
select: { id: true, shotId: true, status: true },
|
||||||
|
}),
|
||||||
|
]);
|
||||||
|
|
||||||
|
const packagesByShot = new Map<string, (typeof items)[number]["package"][]>();
|
||||||
|
for (const item of items) {
|
||||||
|
if (!packagesByShot.has(item.shotId)) packagesByShot.set(item.shotId, []);
|
||||||
|
packagesByShot.get(item.shotId)!.push(item.package);
|
||||||
|
}
|
||||||
|
const shotById = new Map(shots.map((s) => [s.id, s]));
|
||||||
|
const exportsByShot = new Map<string, typeof exports>();
|
||||||
|
for (const row of exports) {
|
||||||
|
if (!exportsByShot.has(row.shotId)) exportsByShot.set(row.shotId, []);
|
||||||
|
exportsByShot.get(row.shotId)!.push(row);
|
||||||
|
}
|
||||||
|
|
||||||
|
const views = requests.map((request): DeliveryRequestView => {
|
||||||
|
const lines = request.lines.map((line): DeliveryRequestLineView => {
|
||||||
|
const shot = shotById.get(line.shotId);
|
||||||
|
const shotExports = exportsByShot.get(line.shotId) ?? [];
|
||||||
|
const stage = resolveLineStage({
|
||||||
|
requestCreatedAt: request.createdAt,
|
||||||
|
packages: packagesByShot.get(line.shotId) ?? [],
|
||||||
|
manual: {
|
||||||
|
deliveredAt: shot?.manualDeliveredAt ?? null,
|
||||||
|
url: shot?.manualDeliveryUrl ?? null,
|
||||||
|
sharedWith: shot?.manualDeliverySharedWith ?? null,
|
||||||
|
},
|
||||||
|
exportStatuses: shotExports.map((e) => e.status),
|
||||||
|
});
|
||||||
|
return {
|
||||||
|
id: line.id,
|
||||||
|
shotId: line.shotId,
|
||||||
|
shotCode: line.shotCode,
|
||||||
|
clientCode: line.clientCode,
|
||||||
|
stage,
|
||||||
|
// Newest first, so this is the version a build would take.
|
||||||
|
readyExportId:
|
||||||
|
stage === "READY" ? (shotExports.find((e) => e.status === "READY_FOR_DELIVERY")?.id ?? null) : null,
|
||||||
|
};
|
||||||
|
});
|
||||||
|
const deliveredCount = lines.filter((l) => l.stage === "DELIVERED").length;
|
||||||
|
const state = request.cancelledAt ? "CANCELLED" : deliveredCount === lines.length ? "CLOSED" : "OPEN";
|
||||||
|
return {
|
||||||
|
id: request.id,
|
||||||
|
requestNumber: request.requestNumber,
|
||||||
|
projectId: request.projectId,
|
||||||
|
projectCode: request.project.code,
|
||||||
|
episode: request.episode,
|
||||||
|
deliverable: request.deliverable,
|
||||||
|
requestedBy: request.requestedBy,
|
||||||
|
note: request.note,
|
||||||
|
dueDate: request.dueDate,
|
||||||
|
createdAt: request.createdAt,
|
||||||
|
cancelledAt: request.cancelledAt,
|
||||||
|
cancelReason: request.cancelReason,
|
||||||
|
state,
|
||||||
|
lineCount: lines.length,
|
||||||
|
deliveredCount,
|
||||||
|
severity: state === "OPEN" ? waitingSeverity(request.createdAt, request.dueDate) : "normal",
|
||||||
|
lines,
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
return filter.openOnly ? views.filter((v) => v.state === "OPEN") : views;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Episodes a request can be logged against, with how many shots each holds. */
|
||||||
|
export async function getRequestOptions(projectId: string) {
|
||||||
|
const groups = await db.shot.groupBy({
|
||||||
|
by: ["episode"],
|
||||||
|
where: { projectId, episode: { not: null } },
|
||||||
|
_count: { _all: true },
|
||||||
|
});
|
||||||
|
return {
|
||||||
|
episodes: groups
|
||||||
|
.filter((g) => g.episode)
|
||||||
|
.map((g) => ({ episode: g.episode as string, shotCount: g._count._all }))
|
||||||
|
.sort((a, b) => a.episode.localeCompare(b.episode)),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* How many of these shots are still owed on a request. A manual delivery of
|
||||||
|
* such a shot has to carry the upload link and recipient, or the request it
|
||||||
|
* answers would stay open with nothing to say why.
|
||||||
|
*/
|
||||||
|
export async function countShotsOnOpenRequests(shotIds: string[]): Promise<number> {
|
||||||
|
if (!shotIds.length) return 0;
|
||||||
|
const open = await listDeliveryRequests({ openOnly: true });
|
||||||
|
const wanted = new Set(shotIds);
|
||||||
|
const owed = new Set<string>();
|
||||||
|
for (const request of open) {
|
||||||
|
for (const line of request.lines) {
|
||||||
|
if (line.stage !== "DELIVERED" && wanted.has(line.shotId)) owed.add(line.shotId);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return owed.size;
|
||||||
|
}
|
||||||
@@ -305,6 +305,8 @@ export interface FinalizeInput {
|
|||||||
highResKey?: string | null;
|
highResKey?: string | null;
|
||||||
highResFileName?: string | null;
|
highResFileName?: string | null;
|
||||||
highResSize?: number | null;
|
highResSize?: number | null;
|
||||||
|
/** Worker ≥ 1.7.1 uploads the MOV after finalize and attaches it via E13b. */
|
||||||
|
highResPending?: boolean;
|
||||||
};
|
};
|
||||||
renderStats?: { renderSeconds?: number; previewSeconds?: number };
|
renderStats?: { renderSeconds?: number; previewSeconds?: number };
|
||||||
media?: {
|
media?: {
|
||||||
@@ -626,12 +628,113 @@ async function finalizePreviewTx(jobId: string, machineId: string, body: Finaliz
|
|||||||
function highResNote(artifacts: NonNullable<FinalizeInput["artifacts"]>): string {
|
function highResNote(artifacts: NonNullable<FinalizeInput["artifacts"]>): string {
|
||||||
const hq = !!artifacts.hqPreviewKey;
|
const hq = !!artifacts.hqPreviewKey;
|
||||||
const mov = !!artifacts.highResKey;
|
const mov = !!artifacts.highResKey;
|
||||||
|
if (artifacts.highResPending) {
|
||||||
|
return hq
|
||||||
|
? " — High quality MP4 attached; ProRes uploading in the background"
|
||||||
|
: " — ProRes uploading in the background (High quality encode failed or skipped)";
|
||||||
|
}
|
||||||
if (hq && mov) return " — High quality MP4 and ProRes attached";
|
if (hq && mov) return " — High quality MP4 and ProRes attached";
|
||||||
if (hq) return " — High quality MP4 attached (ProRes upload failed or skipped)";
|
if (hq) return " — High quality MP4 attached (ProRes upload failed or skipped)";
|
||||||
if (mov) return " — ProRes attached (High quality encode failed or skipped)";
|
if (mov) return " — ProRes attached (High quality encode failed or skipped)";
|
||||||
return " — no High quality/ProRes (disabled, worker < 1.7.0, or both failed — see the worker log)";
|
return " — no High quality/ProRes (disabled, worker < 1.7.0, or both failed — see the worker log)";
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface AttachHighResInput {
|
||||||
|
highResKey?: string | null;
|
||||||
|
highResFileName?: string | null;
|
||||||
|
highResSize?: number | null;
|
||||||
|
/** Set when the worker gave up on the upload; recorded on the timeline. */
|
||||||
|
error?: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* E13b — the ProRes MOV for an already-finalized preview job (worker ≥ 1.7.1
|
||||||
|
* uploads it in the background so a slow uplink no longer holds the job
|
||||||
|
* open). Attaches it to the export's version as its High Res download.
|
||||||
|
*
|
||||||
|
* The upload can land minutes later, so it only attaches while this job is
|
||||||
|
* still the export's newest preview: a regenerated preview has newer media
|
||||||
|
* and its own MOV on the way, and the late file is deleted instead.
|
||||||
|
*/
|
||||||
|
export async function attachHighRes(jobId: string, machineId: string, body: AttachHighResInput) {
|
||||||
|
const outcome = await db.$transaction(async (tx) => {
|
||||||
|
const job = await tx.renderJob.findUnique({
|
||||||
|
where: { id: jobId },
|
||||||
|
include: { export: true },
|
||||||
|
});
|
||||||
|
if (!job) throw new PipelineError(404, "Render job not found");
|
||||||
|
if (job.machineId !== machineId) {
|
||||||
|
throw new PipelineError(409, "Job is not held by this machine (lease reassigned?)");
|
||||||
|
}
|
||||||
|
if (job.status !== "COMPLETED") {
|
||||||
|
throw new PipelineError(409, `Job is ${job.status} — ProRes can only attach to a finalized preview`);
|
||||||
|
}
|
||||||
|
const exportRow = job.export;
|
||||||
|
const key = body.highResKey ?? null;
|
||||||
|
const discard = key ? [key] : [];
|
||||||
|
|
||||||
|
const note = async (text: string) => {
|
||||||
|
if (!exportRow) return;
|
||||||
|
await tx.exportEvent.create({
|
||||||
|
data: {
|
||||||
|
exportId: exportRow.id,
|
||||||
|
fromStatus: exportRow.status,
|
||||||
|
toStatus: exportRow.status,
|
||||||
|
actorType: "WORKER",
|
||||||
|
actorId: machineId,
|
||||||
|
note: text,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
if (!exportRow?.versionId) {
|
||||||
|
return { attached: false, reason: "no version", deleteKeys: discard };
|
||||||
|
}
|
||||||
|
|
||||||
|
const newer = await tx.renderJob.findFirst({
|
||||||
|
where: { exportId: exportRow.id, type: "PREVIEW_ONLY", createdAt: { gt: job.createdAt } },
|
||||||
|
select: { id: true },
|
||||||
|
});
|
||||||
|
if (newer) {
|
||||||
|
if (key) await note("ProRes from an earlier preview arrived after a newer preview — discarded");
|
||||||
|
return { attached: false, reason: "superseded", deleteKeys: discard };
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!key) {
|
||||||
|
await note(`ProRes background upload failed — ${body.error ?? "no file"} (Standard and High quality unaffected)`);
|
||||||
|
return { attached: false, reason: "upload failed", deleteKeys: [] as string[] };
|
||||||
|
}
|
||||||
|
|
||||||
|
const version = await tx.version.findUnique({
|
||||||
|
where: { id: exportRow.versionId },
|
||||||
|
select: { id: true, highResKey: true },
|
||||||
|
});
|
||||||
|
if (!version) return { attached: false, reason: "version gone", deleteKeys: discard };
|
||||||
|
if (version.highResKey === key) return { attached: true, alreadyApplied: true, deleteKeys: [] as string[] };
|
||||||
|
|
||||||
|
await tx.version.update({
|
||||||
|
where: { id: version.id },
|
||||||
|
data: {
|
||||||
|
highResKey: key,
|
||||||
|
highResFilename: body.highResFileName ?? null,
|
||||||
|
highResSize: typeof body.highResSize === "number" ? BigInt(Math.round(body.highResSize)) : null,
|
||||||
|
highResPrunedAt: null,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
const mb = typeof body.highResSize === "number" ? ` (${Math.round(body.highResSize / 1048576)} MB)` : "";
|
||||||
|
await note(`ProRes attached${mb}`);
|
||||||
|
return {
|
||||||
|
attached: true,
|
||||||
|
deleteKeys: version.highResKey ? [version.highResKey] : ([] as string[]),
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
// Storage is only touched once the transaction has committed.
|
||||||
|
const { deleteKeys, ...result } = outcome;
|
||||||
|
await deleteStorageKeys(deleteKeys);
|
||||||
|
return { ok: true, ...result };
|
||||||
|
}
|
||||||
|
|
||||||
/** T11 — retry the preview stage only; validated EXRs are left alone. */
|
/** T11 — retry the preview stage only; validated EXRs are left alone. */
|
||||||
export async function retryPreview(exportId: string, actorId?: string) {
|
export async function retryPreview(exportId: string, actorId?: string) {
|
||||||
const maxAttempts = await getConfigNumber("render.maxAttempts");
|
const maxAttempts = await getConfigNumber("render.maxAttempts");
|
||||||
|
|||||||
@@ -0,0 +1,112 @@
|
|||||||
|
import { describe, expect, it } from "vitest";
|
||||||
|
import { summariseShotDelivery, type ShotDeliveryPackage } from "./shot-delivery-summary";
|
||||||
|
|
||||||
|
const day = (d: number) => new Date(Date.UTC(2026, 8, d, 12));
|
||||||
|
|
||||||
|
const pkg = (over: Partial<ShotDeliveryPackage>): ShotDeliveryPackage => ({
|
||||||
|
kind: "EXR_DELIVERY",
|
||||||
|
status: "DELIVERED",
|
||||||
|
packageNumber: 1,
|
||||||
|
versionString: "v001",
|
||||||
|
createdAt: day(1),
|
||||||
|
builtAt: day(1),
|
||||||
|
uploadedAt: day(1),
|
||||||
|
deliveredAt: day(1),
|
||||||
|
sharedWith: "Dana",
|
||||||
|
...over,
|
||||||
|
});
|
||||||
|
|
||||||
|
const noManual = { deliveredAt: null, sharedWith: null, note: null };
|
||||||
|
|
||||||
|
describe("summariseShotDelivery", () => {
|
||||||
|
it("reports nothing for a shot that has never been exported", () => {
|
||||||
|
expect(summariseShotDelivery({ packages: [], manual: noManual, latestExport: null })).toEqual({
|
||||||
|
sent: null,
|
||||||
|
review: null,
|
||||||
|
pending: null,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it("takes the most recently shared EXR package as sent", () => {
|
||||||
|
const s = summariseShotDelivery({
|
||||||
|
packages: [
|
||||||
|
pkg({ packageNumber: 3, versionString: "v002", deliveredAt: day(5), createdAt: day(4) }),
|
||||||
|
pkg({ packageNumber: 1, versionString: "v001", deliveredAt: day(2) }),
|
||||||
|
],
|
||||||
|
manual: noManual,
|
||||||
|
latestExport: { versionString: "v002", status: "DELIVERED" },
|
||||||
|
});
|
||||||
|
expect(s.sent).toMatchObject({ via: "PACKAGE", version: "v002", label: "Package #3", to: "Dana" });
|
||||||
|
expect(s.pending).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("prefers a later manual delivery", () => {
|
||||||
|
const s = summariseShotDelivery({
|
||||||
|
packages: [pkg({ deliveredAt: day(2) })],
|
||||||
|
manual: { deliveredAt: day(6), sharedWith: "Sam", note: "WeTransfer" },
|
||||||
|
latestExport: null,
|
||||||
|
});
|
||||||
|
expect(s.sent).toMatchObject({ via: "MANUAL", version: null, to: "Sam", note: "WeTransfer" });
|
||||||
|
});
|
||||||
|
|
||||||
|
it("does not count a built but unshared package as sent", () => {
|
||||||
|
const s = summariseShotDelivery({
|
||||||
|
packages: [pkg({ status: "READY", uploadedAt: null, deliveredAt: null, packageNumber: 7, versionString: "v003" })],
|
||||||
|
manual: noManual,
|
||||||
|
latestExport: { versionString: "v003", status: "PACKAGED" },
|
||||||
|
});
|
||||||
|
expect(s.sent).toBeNull();
|
||||||
|
expect(s.pending).toEqual({ version: "v003", label: "built in #7, not uploaded", tone: "waiting" });
|
||||||
|
});
|
||||||
|
|
||||||
|
it("flags an uploaded package whose link was never shared", () => {
|
||||||
|
const s = summariseShotDelivery({
|
||||||
|
packages: [pkg({ status: "READY", deliveredAt: null, packageNumber: 7 })],
|
||||||
|
manual: noManual,
|
||||||
|
latestExport: null,
|
||||||
|
});
|
||||||
|
expect(s.pending?.label).toBe("uploaded in #7, link not shared");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("ignores cancelled packages and open packages older than the last send", () => {
|
||||||
|
const s = summariseShotDelivery({
|
||||||
|
packages: [
|
||||||
|
pkg({ status: "CANCELLED", deliveredAt: null, createdAt: day(9) }),
|
||||||
|
pkg({ status: "FAILED", deliveredAt: null, createdAt: day(1) }),
|
||||||
|
pkg({ deliveredAt: day(3), createdAt: day(2) }),
|
||||||
|
],
|
||||||
|
manual: noManual,
|
||||||
|
latestExport: { versionString: "v001", status: "DELIVERED" },
|
||||||
|
});
|
||||||
|
expect(s.pending).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("shows a newer export that has not gone out", () => {
|
||||||
|
const s = summariseShotDelivery({
|
||||||
|
packages: [pkg({ deliveredAt: day(2) })],
|
||||||
|
manual: noManual,
|
||||||
|
latestExport: { versionString: "v002", status: "READY_FOR_QC" },
|
||||||
|
});
|
||||||
|
expect(s.pending).toEqual({ version: "v002", label: "in QC", tone: "waiting" });
|
||||||
|
});
|
||||||
|
|
||||||
|
it("reports failed exports as failed", () => {
|
||||||
|
const s = summariseShotDelivery({
|
||||||
|
packages: [],
|
||||||
|
manual: noManual,
|
||||||
|
latestExport: { versionString: "v002", status: "QC_FAILED" },
|
||||||
|
});
|
||||||
|
expect(s.pending?.tone).toBe("failed");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("keeps review MOVs apart from deliveries", () => {
|
||||||
|
const s = summariseShotDelivery({
|
||||||
|
packages: [pkg({ kind: "MOV_REVIEW", status: "READY", packageNumber: 4, versionString: "v002", builtAt: day(8), deliveredAt: null })],
|
||||||
|
manual: noManual,
|
||||||
|
latestExport: null,
|
||||||
|
});
|
||||||
|
expect(s.sent).toBeNull();
|
||||||
|
expect(s.pending).toBeNull();
|
||||||
|
expect(s.review).toMatchObject({ version: "v002", label: "Review #4" });
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,124 @@
|
|||||||
|
/**
|
||||||
|
* What has gone out for one shot, and what is on its way — the answer to
|
||||||
|
* "have we sent this?" on Shot Status. Kept free of database imports; the page
|
||||||
|
* gathers the rows and this decides what they mean.
|
||||||
|
*/
|
||||||
|
|
||||||
|
export type ShotDeliveryPackage = {
|
||||||
|
kind: string; // EXR_DELIVERY | MOV_REVIEW
|
||||||
|
status: string; // DeliveryStatus
|
||||||
|
packageNumber: number;
|
||||||
|
versionString: string;
|
||||||
|
createdAt: Date;
|
||||||
|
builtAt: Date | null;
|
||||||
|
uploadedAt: Date | null;
|
||||||
|
deliveredAt: Date | null;
|
||||||
|
sharedWith: string | null;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type PendingTone = "progress" | "waiting" | "failed";
|
||||||
|
|
||||||
|
export type ShotDeliverySummary = {
|
||||||
|
/** The last time the shot reached the client with evidence. */
|
||||||
|
sent: {
|
||||||
|
via: "PACKAGE" | "MANUAL";
|
||||||
|
version: string | null; // unknown for a manual delivery
|
||||||
|
at: Date;
|
||||||
|
to: string | null;
|
||||||
|
label: string; // "Package #15" | "Outside pipeline"
|
||||||
|
note: string | null;
|
||||||
|
} | null;
|
||||||
|
/** The last review MOV package the shot was built into. */
|
||||||
|
review: { version: string; at: Date; label: string } | null;
|
||||||
|
/** Something newer than `sent` that has not gone out yet. */
|
||||||
|
pending: { version: string | null; label: string; tone: PendingTone } | null;
|
||||||
|
};
|
||||||
|
|
||||||
|
const EXPORT_STAGE: Record<string, { label: string; tone: PendingTone }> = {
|
||||||
|
QUEUED: { label: "queued to render", tone: "progress" },
|
||||||
|
RENDERING: { label: "rendering", tone: "progress" },
|
||||||
|
RENDER_FAILED: { label: "render failed", tone: "failed" },
|
||||||
|
VALIDATING: { label: "validating", tone: "progress" },
|
||||||
|
VALIDATION_FAILED: { label: "failed validation", tone: "failed" },
|
||||||
|
GENERATING_PREVIEW: { label: "building preview", tone: "progress" },
|
||||||
|
PREVIEW_FAILED: { label: "preview failed", tone: "failed" },
|
||||||
|
READY_FOR_QC: { label: "in QC", tone: "waiting" },
|
||||||
|
QC_FAILED: { label: "failed QC", tone: "failed" },
|
||||||
|
READY_FOR_DELIVERY: { label: "ready to package", tone: "waiting" },
|
||||||
|
};
|
||||||
|
|
||||||
|
export function summariseShotDelivery(input: {
|
||||||
|
packages: ShotDeliveryPackage[];
|
||||||
|
manual: { deliveredAt: Date | null; sharedWith: string | null; note: string | null };
|
||||||
|
/** The shot's newest export, if any. */
|
||||||
|
latestExport: { versionString: string; status: string } | null;
|
||||||
|
}): ShotDeliverySummary {
|
||||||
|
const { packages, manual, latestExport } = input;
|
||||||
|
const live = packages.filter((p) => p.status !== "CANCELLED");
|
||||||
|
const exr = live.filter((p) => p.kind === "EXR_DELIVERY");
|
||||||
|
|
||||||
|
let sent: ShotDeliverySummary["sent"] = null;
|
||||||
|
for (const p of exr) {
|
||||||
|
if (p.status !== "DELIVERED" || !p.deliveredAt) continue;
|
||||||
|
if (!sent || p.deliveredAt > sent.at) {
|
||||||
|
sent = {
|
||||||
|
via: "PACKAGE",
|
||||||
|
version: p.versionString,
|
||||||
|
at: p.deliveredAt,
|
||||||
|
to: p.sharedWith,
|
||||||
|
label: `Package #${p.packageNumber}`,
|
||||||
|
note: null,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (manual.deliveredAt && (!sent || manual.deliveredAt > sent.at)) {
|
||||||
|
sent = {
|
||||||
|
via: "MANUAL",
|
||||||
|
version: null,
|
||||||
|
at: manual.deliveredAt,
|
||||||
|
to: manual.sharedWith,
|
||||||
|
label: "Outside pipeline",
|
||||||
|
note: manual.note,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
let review: ShotDeliverySummary["review"] = null;
|
||||||
|
for (const p of live) {
|
||||||
|
if (p.kind !== "MOV_REVIEW" || p.status !== "READY") continue;
|
||||||
|
const at = p.builtAt ?? p.createdAt;
|
||||||
|
if (!review || at > review.at) {
|
||||||
|
review = { version: p.versionString, at, label: `Review #${p.packageNumber}` };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return { sent, review, pending: findPending(exr, sent, latestExport) };
|
||||||
|
}
|
||||||
|
|
||||||
|
function findPending(
|
||||||
|
exr: ShotDeliveryPackage[],
|
||||||
|
sent: ShotDeliverySummary["sent"],
|
||||||
|
latestExport: { versionString: string; status: string } | null
|
||||||
|
): ShotDeliverySummary["pending"] {
|
||||||
|
// The newest EXR package started after the last send and not delivered.
|
||||||
|
const open = exr
|
||||||
|
.filter((p) => p.status !== "DELIVERED" && (!sent || p.createdAt > sent.at))
|
||||||
|
.sort((a, b) => b.createdAt.getTime() - a.createdAt.getTime())[0];
|
||||||
|
if (open) {
|
||||||
|
const pkg = `#${open.packageNumber}`;
|
||||||
|
if (open.status === "READY") {
|
||||||
|
return open.uploadedAt
|
||||||
|
? { version: open.versionString, label: `uploaded in ${pkg}, link not shared`, tone: "waiting" }
|
||||||
|
: { version: open.versionString, label: `built in ${pkg}, not uploaded`, tone: "waiting" };
|
||||||
|
}
|
||||||
|
if (open.status === "FAILED") {
|
||||||
|
return { version: open.versionString, label: `package ${pkg} failed`, tone: "failed" };
|
||||||
|
}
|
||||||
|
return { version: open.versionString, label: `package ${pkg} building`, tone: "progress" };
|
||||||
|
}
|
||||||
|
|
||||||
|
// Otherwise the newest export, if it is a version that has not gone out.
|
||||||
|
if (!latestExport) return null;
|
||||||
|
if (sent?.version === latestExport.versionString) return null;
|
||||||
|
const stage = EXPORT_STAGE[latestExport.status];
|
||||||
|
return stage ? { version: latestExport.versionString, ...stage } : null;
|
||||||
|
}
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
// The order shots appear in on the project page's Shots tab. Shared with the
|
||||||
|
// shot detail page so its previous/next navigation walks the same list.
|
||||||
|
|
||||||
|
type OrderableShot = {
|
||||||
|
episode?: string | null;
|
||||||
|
scene: string;
|
||||||
|
shotNumber: number;
|
||||||
|
shotGroup?: { name: string } | null;
|
||||||
|
};
|
||||||
|
|
||||||
|
export function sortShotsForList<T extends OrderableShot>(shots: T[], projectType: string): T[] {
|
||||||
|
// Episodic: episode → scene → shotNumber
|
||||||
|
if (projectType === "EPISODIC") {
|
||||||
|
return [...shots].sort((a, b) => {
|
||||||
|
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;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Standard with custom groups: group → scene → shotNumber, ungrouped last
|
||||||
|
if (projectType === "STANDARD" && shots.some((s) => s.shotGroup)) {
|
||||||
|
return [...shots].sort((a, b) => {
|
||||||
|
const ga = a.shotGroup?.name ?? "";
|
||||||
|
const gb = b.shotGroup?.name ?? "";
|
||||||
|
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;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Otherwise the list keeps the query's createdAt order
|
||||||
|
return shots;
|
||||||
|
}
|
||||||
@@ -17,6 +17,10 @@ import {
|
|||||||
GetObjectCommand,
|
GetObjectCommand,
|
||||||
ListObjectsV2Command,
|
ListObjectsV2Command,
|
||||||
HeadObjectCommand,
|
HeadObjectCommand,
|
||||||
|
CreateMultipartUploadCommand,
|
||||||
|
UploadPartCommand,
|
||||||
|
CompleteMultipartUploadCommand,
|
||||||
|
AbortMultipartUploadCommand,
|
||||||
} from "@aws-sdk/client-s3";
|
} from "@aws-sdk/client-s3";
|
||||||
import { getSignedUrl } from "@aws-sdk/s3-request-presigner";
|
import { getSignedUrl } from "@aws-sdk/s3-request-presigner";
|
||||||
import fs from "fs";
|
import fs from "fs";
|
||||||
@@ -323,6 +327,65 @@ export async function generateHetznerPresignedUploadUrl(
|
|||||||
return getSignedUrl(client, command, { expiresIn });
|
return getSignedUrl(client, command, { expiresIn });
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Multipart upload with presigned part URLs, for the render worker's large
|
||||||
|
* files. A single PUT from the studio to nbg1 is capped near 0.1 MB/s per
|
||||||
|
* connection (188 ms away, lossy); parts uploaded in parallel scale almost
|
||||||
|
* linearly with the number of connections.
|
||||||
|
*
|
||||||
|
* Part URLs live 6 h: parts queue behind each other, and on a slow uplink the
|
||||||
|
* last ones can start long after the upload began.
|
||||||
|
*/
|
||||||
|
export async function createHetznerMultipartUpload(
|
||||||
|
key: string,
|
||||||
|
contentType: string,
|
||||||
|
partCount: number,
|
||||||
|
expiresIn: number = 6 * 3600
|
||||||
|
): Promise<{ uploadId: string; partUrls: string[] }> {
|
||||||
|
const { client, bucket } = await buildHetznerClient();
|
||||||
|
const created = await client.send(
|
||||||
|
new CreateMultipartUploadCommand({ Bucket: bucket, Key: key, ContentType: contentType })
|
||||||
|
);
|
||||||
|
if (!created.UploadId) throw new Error("Storage did not return an UploadId");
|
||||||
|
const uploadId = created.UploadId;
|
||||||
|
const partUrls = await Promise.all(
|
||||||
|
Array.from({ length: partCount }, (_, i) =>
|
||||||
|
getSignedUrl(
|
||||||
|
client,
|
||||||
|
new UploadPartCommand({ Bucket: bucket, Key: key, UploadId: uploadId, PartNumber: i + 1 }),
|
||||||
|
{ expiresIn }
|
||||||
|
)
|
||||||
|
)
|
||||||
|
);
|
||||||
|
return { uploadId, partUrls };
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function completeHetznerMultipartUpload(
|
||||||
|
key: string,
|
||||||
|
uploadId: string,
|
||||||
|
parts: { partNumber: number; etag: string }[]
|
||||||
|
): Promise<void> {
|
||||||
|
const { client, bucket } = await buildHetznerClient();
|
||||||
|
await client.send(
|
||||||
|
new CompleteMultipartUploadCommand({
|
||||||
|
Bucket: bucket,
|
||||||
|
Key: key,
|
||||||
|
UploadId: uploadId,
|
||||||
|
MultipartUpload: {
|
||||||
|
Parts: [...parts]
|
||||||
|
.sort((a, b) => a.partNumber - b.partNumber)
|
||||||
|
.map((p) => ({ PartNumber: p.partNumber, ETag: p.etag })),
|
||||||
|
},
|
||||||
|
})
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Frees the parts already stored; otherwise they are billed until expiry. */
|
||||||
|
export async function abortHetznerMultipartUpload(key: string, uploadId: string): Promise<void> {
|
||||||
|
const { client, bucket } = await buildHetznerClient();
|
||||||
|
await client.send(new AbortMultipartUploadCommand({ Bucket: bucket, Key: key, UploadId: uploadId }));
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* In-process cache for Hetzner key existence checks.
|
* In-process cache for Hetzner key existence checks.
|
||||||
* Positive hits (key exists) are cached indefinitely for the process lifetime
|
* Positive hits (key exists) are cached indefinitely for the process lifetime
|
||||||
|
|||||||
@@ -0,0 +1,8 @@
|
|||||||
|
-- "Delivered" used to be one click with nothing behind it. Record the upload
|
||||||
|
-- location and who was sent the link, so a package only becomes DELIVERED once
|
||||||
|
-- both have actually happened. Packages delivered before this keep NULLs here.
|
||||||
|
ALTER TABLE "delivery_packages" ADD COLUMN "uploadUrl" TEXT;
|
||||||
|
ALTER TABLE "delivery_packages" ADD COLUMN "uploadedAt" TIMESTAMP(3);
|
||||||
|
ALTER TABLE "delivery_packages" ADD COLUMN "uploadedById" TEXT;
|
||||||
|
ALTER TABLE "delivery_packages" ADD COLUMN "sharedWith" TEXT;
|
||||||
|
ALTER TABLE "delivery_packages" ADD COLUMN "sharedNote" TEXT;
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
-- Delivery requests: what a client asked for, tracked until it has gone out
|
||||||
|
-- with evidence. Closure is derived from packages and manual deliveries, so
|
||||||
|
-- there is no status column to fall out of step.
|
||||||
|
CREATE TABLE "delivery_requests" (
|
||||||
|
"id" TEXT NOT NULL,
|
||||||
|
"projectId" TEXT NOT NULL,
|
||||||
|
"requestNumber" INTEGER NOT NULL,
|
||||||
|
"episode" TEXT NOT NULL DEFAULT '',
|
||||||
|
"deliverable" TEXT NOT NULL DEFAULT 'EXR',
|
||||||
|
"requestedBy" TEXT NOT NULL,
|
||||||
|
"note" TEXT,
|
||||||
|
"dueDate" TIMESTAMP(3),
|
||||||
|
"createdById" TEXT NOT NULL,
|
||||||
|
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
"cancelledAt" TIMESTAMP(3),
|
||||||
|
"cancelledById" TEXT,
|
||||||
|
"cancelReason" TEXT,
|
||||||
|
|
||||||
|
CONSTRAINT "delivery_requests_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE "delivery_request_lines" (
|
||||||
|
"id" TEXT NOT NULL,
|
||||||
|
"requestId" TEXT NOT NULL,
|
||||||
|
"shotId" TEXT NOT NULL,
|
||||||
|
"shotCode" TEXT NOT NULL,
|
||||||
|
"clientCode" TEXT,
|
||||||
|
|
||||||
|
CONSTRAINT "delivery_request_lines_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE UNIQUE INDEX "delivery_requests_projectId_requestNumber_key" ON "delivery_requests"("projectId", "requestNumber");
|
||||||
|
CREATE INDEX "delivery_requests_projectId_cancelledAt_idx" ON "delivery_requests"("projectId", "cancelledAt");
|
||||||
|
CREATE UNIQUE INDEX "delivery_request_lines_requestId_shotId_key" ON "delivery_request_lines"("requestId", "shotId");
|
||||||
|
CREATE INDEX "delivery_request_lines_shotId_idx" ON "delivery_request_lines"("shotId");
|
||||||
|
|
||||||
|
ALTER TABLE "delivery_requests" ADD CONSTRAINT "delivery_requests_projectId_fkey" FOREIGN KEY ("projectId") REFERENCES "projects"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
|
ALTER TABLE "delivery_request_lines" ADD CONSTRAINT "delivery_request_lines_requestId_fkey" FOREIGN KEY ("requestId") REFERENCES "delivery_requests"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
|
ALTER TABLE "delivery_request_lines" ADD CONSTRAINT "delivery_request_lines_shotId_fkey" FOREIGN KEY ("shotId") REFERENCES "shots"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
|
|
||||||
|
-- A manual delivery closes a request line only with the same evidence a
|
||||||
|
-- package carries: where it was uploaded and who was sent the link.
|
||||||
|
ALTER TABLE "shots" ADD COLUMN "manualDeliveryUrl" TEXT;
|
||||||
|
ALTER TABLE "shots" ADD COLUMN "manualDeliverySharedWith" TEXT;
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
-- Daily board: the day-to-day tracker that used to live in a shared doc,
|
||||||
|
-- now linked to shots. Board items are notes, not tasks, so nothing here
|
||||||
|
-- feeds shot status.
|
||||||
|
ALTER TABLE "projects" ADD COLUMN "boardStatus" TEXT;
|
||||||
|
ALTER TABLE "projects" ADD COLUMN "boardStatusAt" TIMESTAMP(3);
|
||||||
|
|
||||||
|
CREATE TABLE "board_items" (
|
||||||
|
"id" TEXT NOT NULL,
|
||||||
|
"projectId" TEXT NOT NULL,
|
||||||
|
"shotId" TEXT,
|
||||||
|
"code" TEXT,
|
||||||
|
"text" TEXT NOT NULL,
|
||||||
|
"group" TEXT NOT NULL DEFAULT '',
|
||||||
|
"assigneeId" TEXT,
|
||||||
|
"waitingOn" TEXT,
|
||||||
|
"sortOrder" INTEGER NOT NULL DEFAULT 0,
|
||||||
|
"doneAt" TIMESTAMP(3),
|
||||||
|
"doneById" TEXT,
|
||||||
|
"createdById" TEXT NOT NULL,
|
||||||
|
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||||
|
|
||||||
|
CONSTRAINT "board_items_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE "project_milestones" (
|
||||||
|
"id" TEXT NOT NULL,
|
||||||
|
"projectId" TEXT NOT NULL,
|
||||||
|
"label" TEXT NOT NULL,
|
||||||
|
"date" TIMESTAMP(3) NOT NULL,
|
||||||
|
"doneAt" TIMESTAMP(3),
|
||||||
|
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
|
||||||
|
CONSTRAINT "project_milestones_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX "board_items_projectId_doneAt_idx" ON "board_items"("projectId", "doneAt");
|
||||||
|
CREATE INDEX "board_items_shotId_idx" ON "board_items"("shotId");
|
||||||
|
CREATE INDEX "project_milestones_projectId_date_idx" ON "project_milestones"("projectId", "date");
|
||||||
|
|
||||||
|
ALTER TABLE "board_items" ADD CONSTRAINT "board_items_projectId_fkey" FOREIGN KEY ("projectId") REFERENCES "projects"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
|
ALTER TABLE "board_items" ADD CONSTRAINT "board_items_shotId_fkey" FOREIGN KEY ("shotId") REFERENCES "shots"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||||
|
ALTER TABLE "board_items" ADD CONSTRAINT "board_items_assigneeId_fkey" FOREIGN KEY ("assigneeId") REFERENCES "users"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||||
|
ALTER TABLE "project_milestones" ADD CONSTRAINT "project_milestones_projectId_fkey" FOREIGN KEY ("projectId") REFERENCES "projects"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
-- Client feedback pasted from WhatsApp: rounds group the notes on the board,
|
||||||
|
-- and each note is saved as a player comment tagged with its source.
|
||||||
|
ALTER TABLE "comments" ADD COLUMN "source" TEXT;
|
||||||
|
|
||||||
|
CREATE TABLE "feedback_rounds" (
|
||||||
|
"id" TEXT NOT NULL,
|
||||||
|
"projectId" TEXT NOT NULL,
|
||||||
|
"title" TEXT NOT NULL,
|
||||||
|
"dueAt" TIMESTAMP(3),
|
||||||
|
"createdById" TEXT NOT NULL,
|
||||||
|
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
|
||||||
|
CONSTRAINT "feedback_rounds_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
ALTER TABLE "board_items" ADD COLUMN "roundId" TEXT;
|
||||||
|
ALTER TABLE "board_items" ADD COLUMN "commentId" TEXT;
|
||||||
|
|
||||||
|
CREATE INDEX "feedback_rounds_projectId_idx" ON "feedback_rounds"("projectId");
|
||||||
|
|
||||||
|
ALTER TABLE "feedback_rounds" ADD CONSTRAINT "feedback_rounds_projectId_fkey" FOREIGN KEY ("projectId") REFERENCES "projects"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
|
ALTER TABLE "board_items" ADD CONSTRAINT "board_items_roundId_fkey" FOREIGN KEY ("roundId") REFERENCES "feedback_rounds"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
-- Per-user read marker for a shot's comments: the shot-status board flags a
|
||||||
|
-- shot with "!" while it has comments from others newer than the marker.
|
||||||
|
CREATE TABLE "shot_comment_reads" (
|
||||||
|
"id" TEXT NOT NULL,
|
||||||
|
"userId" TEXT NOT NULL,
|
||||||
|
"shotId" TEXT NOT NULL,
|
||||||
|
"readAt" TIMESTAMP(3) NOT NULL,
|
||||||
|
|
||||||
|
CONSTRAINT "shot_comment_reads_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE UNIQUE INDEX "shot_comment_reads_userId_shotId_key" ON "shot_comment_reads"("userId", "shotId");
|
||||||
|
CREATE INDEX "shot_comment_reads_shotId_idx" ON "shot_comment_reads"("shotId");
|
||||||
|
|
||||||
|
ALTER TABLE "shot_comment_reads" ADD CONSTRAINT "shot_comment_reads_userId_fkey" FOREIGN KEY ("userId") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
|
ALTER TABLE "shot_comment_reads" ADD CONSTRAINT "shot_comment_reads_shotId_fkey" FOREIGN KEY ("shotId") REFERENCES "shots"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
|
|
||||||
|
-- Everything already commented counts as read on launch, so the board starts
|
||||||
|
-- clean instead of flagging every shot that has ever had a note.
|
||||||
|
INSERT INTO "shot_comment_reads" ("id", "userId", "shotId", "readAt")
|
||||||
|
SELECT md5(u."id" || ':' || s."id"), u."id", s."id", CURRENT_TIMESTAMP
|
||||||
|
FROM "users" u
|
||||||
|
CROSS JOIN "shots" s
|
||||||
|
WHERE u."role" <> 'CLIENT'
|
||||||
|
AND EXISTS (
|
||||||
|
SELECT 1 FROM "comments" c
|
||||||
|
JOIN "versions" v ON v."id" = c."versionId"
|
||||||
|
LEFT JOIN "tasks" t ON t."id" = v."taskId"
|
||||||
|
WHERE COALESCE(v."shotId", t."shotId") = s."id"
|
||||||
|
);
|
||||||
+169
-1
@@ -262,6 +262,8 @@ model User {
|
|||||||
createdShootDays ShootDay[] @relation("ShootDayCreator")
|
createdShootDays ShootDay[] @relation("ShootDayCreator")
|
||||||
createdTakes Take[] @relation("TakeCreator")
|
createdTakes Take[] @relation("TakeCreator")
|
||||||
uploadedTakeAttachments TakeAttachment[] @relation("TakeAttachmentUploader")
|
uploadedTakeAttachments TakeAttachment[] @relation("TakeAttachmentUploader")
|
||||||
|
assignedBoardItems BoardItem[] @relation("BoardItemAssignee")
|
||||||
|
shotCommentReads ShotCommentRead[]
|
||||||
|
|
||||||
@@map("users")
|
@@map("users")
|
||||||
}
|
}
|
||||||
@@ -380,6 +382,16 @@ model Project {
|
|||||||
/// is why it lives here rather than in per-machine panel settings.
|
/// is why it lives here rather than in per-machine panel settings.
|
||||||
pipelineConfig Json?
|
pipelineConfig Json?
|
||||||
deliveryPackages DeliveryPackage[]
|
deliveryPackages DeliveryPackage[]
|
||||||
|
deliveryRequests DeliveryRequest[]
|
||||||
|
|
||||||
|
/// The one-line "where are we" on the daily board ("Official bid sent",
|
||||||
|
/// "Awaiting feedback on pick-ups"). Free text on purpose: it is what the
|
||||||
|
/// producer would have typed at the top of the project's section in the doc.
|
||||||
|
boardStatus String? @db.Text
|
||||||
|
boardStatusAt DateTime?
|
||||||
|
boardItems BoardItem[]
|
||||||
|
milestones ProjectMilestone[]
|
||||||
|
feedbackRounds FeedbackRound[]
|
||||||
|
|
||||||
@@map("projects")
|
@@map("projects")
|
||||||
}
|
}
|
||||||
@@ -463,6 +475,11 @@ model Shot {
|
|||||||
manualDeliveredAt DateTime?
|
manualDeliveredAt DateTime?
|
||||||
manualDeliveredById String?
|
manualDeliveredById String?
|
||||||
manualDeliveryNote String? @db.Text
|
manualDeliveryNote String? @db.Text
|
||||||
|
/// Where a manual delivery was uploaded and who was sent the link. Optional
|
||||||
|
/// for a backfill, but a manual delivery only closes a DeliveryRequest line
|
||||||
|
/// when both are present — the same evidence a package needs.
|
||||||
|
manualDeliveryUrl String?
|
||||||
|
manualDeliverySharedWith String?
|
||||||
// Netflix slate fields — managed via the Slate tab, used by the preview pipeline
|
// Netflix slate fields — managed via the Slate tab, used by the preview pipeline
|
||||||
slateType String?
|
slateType String?
|
||||||
slateDescription String? @db.Text
|
slateDescription String? @db.Text
|
||||||
@@ -480,6 +497,9 @@ model Shot {
|
|||||||
references ShotReference[]
|
references ShotReference[]
|
||||||
loggedTakes Take[] @relation("TakeToShot")
|
loggedTakes Take[] @relation("TakeToShot")
|
||||||
exports Export[]
|
exports Export[]
|
||||||
|
deliveryRequestLines DeliveryRequestLine[]
|
||||||
|
boardItems BoardItem[]
|
||||||
|
commentReads ShotCommentRead[]
|
||||||
|
|
||||||
@@unique([projectId, shotCode])
|
@@unique([projectId, shotCode])
|
||||||
@@map("shots")
|
@@map("shots")
|
||||||
@@ -595,6 +615,10 @@ model Comment {
|
|||||||
timestamp Float
|
timestamp Float
|
||||||
text String @db.Text
|
text String @db.Text
|
||||||
isResolved Boolean @default(false)
|
isResolved Boolean @default(false)
|
||||||
|
/// Where the note came from when it was not typed in the player. "WHATSAPP"
|
||||||
|
/// = client feedback pasted from a message; `authorId` is then whoever
|
||||||
|
/// logged it, not who said it, and the player labels it client feedback.
|
||||||
|
source String?
|
||||||
createdAt DateTime @default(now())
|
createdAt DateTime @default(now())
|
||||||
updatedAt DateTime @updatedAt
|
updatedAt DateTime @updatedAt
|
||||||
|
|
||||||
@@ -653,6 +677,24 @@ model Approval {
|
|||||||
@@map("approvals")
|
@@map("approvals")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// How far each user has read a shot's comments. A comment or reply on any of
|
||||||
|
/// the shot's versions, written by someone else after `readAt`, is new to that
|
||||||
|
/// user and flags the shot on the shot-status board until they mark it read.
|
||||||
|
/// No row = nothing read since the account was created.
|
||||||
|
model ShotCommentRead {
|
||||||
|
id String @id @default(cuid())
|
||||||
|
userId String
|
||||||
|
shotId String
|
||||||
|
readAt DateTime
|
||||||
|
|
||||||
|
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
|
||||||
|
shot Shot @relation(fields: [shotId], references: [id], onDelete: Cascade)
|
||||||
|
|
||||||
|
@@unique([userId, shotId])
|
||||||
|
@@index([shotId])
|
||||||
|
@@map("shot_comment_reads")
|
||||||
|
}
|
||||||
|
|
||||||
model Notification {
|
model Notification {
|
||||||
id String @id @default(cuid())
|
id String @id @default(cuid())
|
||||||
userId String
|
userId String
|
||||||
@@ -1155,7 +1197,16 @@ model DeliveryPackage {
|
|||||||
createdById String
|
createdById String
|
||||||
createdAt DateTime @default(now())
|
createdAt DateTime @default(now())
|
||||||
builtAt DateTime?
|
builtAt DateTime?
|
||||||
deliveredAt DateTime?
|
|
||||||
|
// Handoff evidence. Built is not delivered: the folder still has to be
|
||||||
|
// uploaded to the client's portal and the link sent to a person, and each of
|
||||||
|
// those is recorded separately so a package cannot be "delivered" on a hunch.
|
||||||
|
uploadUrl String? // where it lives on the client's side (Content Hub folder)
|
||||||
|
uploadedAt DateTime?
|
||||||
|
uploadedById String?
|
||||||
|
sharedWith String? // who was sent the link
|
||||||
|
sharedNote String?
|
||||||
|
deliveredAt DateTime? // when the link was shared — the package is DELIVERED from here
|
||||||
deliveredById String?
|
deliveredById String?
|
||||||
|
|
||||||
items DeliveryItem[]
|
items DeliveryItem[]
|
||||||
@@ -1196,6 +1247,123 @@ model DeliveryItem {
|
|||||||
@@map("delivery_items")
|
@@map("delivery_items")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Something a client asked for ("EXRs for 116"), logged by hand because the
|
||||||
|
/// ask arrives over chat. It has no status of its own: a line is closed when
|
||||||
|
/// its shot has gone out with evidence after the request was logged, and the
|
||||||
|
/// request is closed when every line is — so it cannot be ticked off by hand.
|
||||||
|
model DeliveryRequest {
|
||||||
|
id String @id @default(cuid())
|
||||||
|
projectId String
|
||||||
|
project Project @relation(fields: [projectId], references: [id], onDelete: Cascade)
|
||||||
|
requestNumber Int // sequential per project → "Request #4"
|
||||||
|
episode String @default("") // set when a whole episode was asked for
|
||||||
|
deliverable String @default("EXR") // EXR | MOV | EXR_AND_MOV — what the client asked for
|
||||||
|
requestedBy String // who at the client asked
|
||||||
|
note String? @db.Text
|
||||||
|
dueDate DateTime?
|
||||||
|
createdById String
|
||||||
|
createdAt DateTime @default(now())
|
||||||
|
cancelledAt DateTime?
|
||||||
|
cancelledById String?
|
||||||
|
cancelReason String?
|
||||||
|
|
||||||
|
lines DeliveryRequestLine[]
|
||||||
|
|
||||||
|
@@unique([projectId, requestNumber])
|
||||||
|
@@index([projectId, cancelledAt])
|
||||||
|
@@map("delivery_requests")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One requested shot. The shot list is a snapshot taken when the request was
|
||||||
|
/// logged; codes are denormalised for the same reason DeliveryItem's are.
|
||||||
|
model DeliveryRequestLine {
|
||||||
|
id String @id @default(cuid())
|
||||||
|
requestId String
|
||||||
|
request DeliveryRequest @relation(fields: [requestId], references: [id], onDelete: Cascade)
|
||||||
|
shotId String
|
||||||
|
shot Shot @relation(fields: [shotId], references: [id], onDelete: Cascade)
|
||||||
|
shotCode String
|
||||||
|
clientCode String?
|
||||||
|
|
||||||
|
@@unique([requestId, shotId])
|
||||||
|
@@index([shotId])
|
||||||
|
@@map("delivery_request_lines")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A line on the daily board — the day-to-day to-do the team used to keep in
|
||||||
|
/// a shared doc ("DH2_VFX_027_090 finalise (CHRIS)"). Deliberately not a Task:
|
||||||
|
/// tasks are the pipeline's one-per-shot work items whose state drives shot
|
||||||
|
/// status, and a note like "finalise" or "awaiting gfx" must not move a shot
|
||||||
|
/// back to IN_PROGRESS or notify anyone.
|
||||||
|
///
|
||||||
|
/// `code` is the shot code as typed. When it matches a shot, `shotId` links it
|
||||||
|
/// and the board shows the shot's live status; when it does not, the line is a
|
||||||
|
/// flag ("not on our tracker?") until the shot exists or the code is fixed.
|
||||||
|
model BoardItem {
|
||||||
|
id String @id @default(cuid())
|
||||||
|
projectId String
|
||||||
|
project Project @relation(fields: [projectId], references: [id], onDelete: Cascade)
|
||||||
|
shotId String?
|
||||||
|
shot Shot? @relation(fields: [shotId], references: [id], onDelete: SetNull)
|
||||||
|
code String?
|
||||||
|
text String @db.Text
|
||||||
|
/// Heading the line sits under on the board ("WATER DROPS"); "" = none
|
||||||
|
group String @default("")
|
||||||
|
assigneeId String?
|
||||||
|
assignee User? @relation("BoardItemAssignee", fields: [assigneeId], references: [id], onDelete: SetNull)
|
||||||
|
/// What the line is blocked on ("client GFX ADH_GFX_013_010"); null = not blocked
|
||||||
|
waitingOn String?
|
||||||
|
/// Set when the line came from pasted client feedback: the round it belongs
|
||||||
|
/// to, and the player comment it was saved as. Ticking the line off
|
||||||
|
/// resolves that comment.
|
||||||
|
roundId String?
|
||||||
|
round FeedbackRound? @relation(fields: [roundId], references: [id], onDelete: SetNull)
|
||||||
|
commentId String?
|
||||||
|
sortOrder Int @default(0)
|
||||||
|
doneAt DateTime?
|
||||||
|
doneById String?
|
||||||
|
createdById String
|
||||||
|
createdAt DateTime @default(now())
|
||||||
|
updatedAt DateTime @updatedAt
|
||||||
|
|
||||||
|
@@index([projectId, doneAt])
|
||||||
|
@@index([shotId])
|
||||||
|
@@map("board_items")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One batch of client feedback as it arrived ("FEEDBACK 113 DUE Oct 7 12:00
|
||||||
|
/// PM"). Its notes are saved as player comments and as board lines; the round
|
||||||
|
/// is what groups them on the board under one due time.
|
||||||
|
model FeedbackRound {
|
||||||
|
id String @id @default(cuid())
|
||||||
|
projectId String
|
||||||
|
project Project @relation(fields: [projectId], references: [id], onDelete: Cascade)
|
||||||
|
title String
|
||||||
|
dueAt DateTime?
|
||||||
|
createdById String
|
||||||
|
createdAt DateTime @default(now())
|
||||||
|
items BoardItem[]
|
||||||
|
|
||||||
|
@@index([projectId])
|
||||||
|
@@map("feedback_rounds")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A dated project milestone — batch deliveries, picture locks, shoot start,
|
||||||
|
/// colour & mix review. Episode due dates stay in EpisodeDueDate because the
|
||||||
|
/// shot-status board keys off them; these are the dates around the work.
|
||||||
|
model ProjectMilestone {
|
||||||
|
id String @id @default(cuid())
|
||||||
|
projectId String
|
||||||
|
project Project @relation(fields: [projectId], references: [id], onDelete: Cascade)
|
||||||
|
label String
|
||||||
|
date DateTime
|
||||||
|
doneAt DateTime?
|
||||||
|
createdAt DateTime @default(now())
|
||||||
|
|
||||||
|
@@index([projectId, date])
|
||||||
|
@@map("project_milestones")
|
||||||
|
}
|
||||||
|
|
||||||
model SketchTemplate {
|
model SketchTemplate {
|
||||||
id String @id @default(cuid())
|
id String @id @default(cuid())
|
||||||
name String
|
name String
|
||||||
|
|||||||
@@ -64,6 +64,8 @@ export interface CommentWithReplies {
|
|||||||
timestamp: number;
|
timestamp: number;
|
||||||
text: string;
|
text: string;
|
||||||
isResolved: boolean;
|
isResolved: boolean;
|
||||||
|
/** "WHATSAPP" = client feedback pasted from a message; author is who logged it */
|
||||||
|
source?: string | null;
|
||||||
createdAt: Date;
|
createdAt: Date;
|
||||||
updatedAt: Date;
|
updatedAt: Date;
|
||||||
author: {
|
author: {
|
||||||
|
|||||||
Reference in New Issue
Block a user