fix(ingest): route by capture time, not leftover open-event pin (BIT-165) (#165)
Pin only wins inside its ingest window; overlapping windows pick closest startsAt; no capture keeps the named folder.
This commit was merged in pull request #165.
This commit is contained in:
commit
f20dea883e
12 files changed
+183
-55
No files matched your search
@@ -109,8 +109,8 @@ export class IngestService {
|
||||
return { status: "skipped", reason: "unknown_login" };
|
||||
}
|
||||
|
||||
// "Receber FTP aqui": the login sends everything to the event chosen in the library, whatever the camera's
|
||||
// clock says, until the time set; then (or with that event put away) by the time again.
|
||||
// "Receber FTP aqui": pin is a preferred event for captures that still sit in its ingest window (and session).
|
||||
// Outside that window the clock routes — a leftover pin on the afternoon training must not take the morning studio.
|
||||
const target =
|
||||
account.targetEventId && (!account.targetUntil || account.targetUntil > new Date())
|
||||
? await db.event.findFirst({ where: { id: account.targetEventId, organizationId: account.organizationId, archivedAt: null }, select: { id: true } })
|
||||
@@ -173,16 +173,19 @@ export class IngestService {
|
||||
const camera = await readCameraInfo(file).catch(() => ({}) as Awaited<ReturnType<typeof readCameraInfo>>);
|
||||
const embedded = await readEmbeddedIptc(file);
|
||||
const capturedAt = camera.capturedAt ? new Date(camera.capturedAt.getTime() + (origin.clockOffsetSec ?? 0) * 1000) : undefined;
|
||||
const at = capturedAt ?? new Date();
|
||||
// Archive imports name their own event. A file with no camera time, or a time outside that event's window,
|
||||
// must not fall through onto whatever is live today.
|
||||
// Archive imports name their own event. No camera time: keep the folder/pin the photographer named — do not
|
||||
// invent "now" (that would also force today's open event). With a capture time, the pin only wins inside its
|
||||
// ingest window; otherwise the clock (closest start when windows overlap) decides.
|
||||
const requestedEventId = origin.inbox
|
||||
? null
|
||||
: origin.held && origin.eventId
|
||||
? origin.eventId
|
||||
: origin.source === "CLOUD"
|
||||
? await this.namedEvent(orgId, origin.eventId)
|
||||
: (await this.requestedEvent(orgId, origin.userId, origin.eventId, at)) ?? (await this.routeToEvent(orgId, origin.userId, at));
|
||||
: !capturedAt
|
||||
? await this.namedEvent(orgId, origin.eventId)
|
||||
: (await this.requestedEvent(orgId, origin.userId, origin.eventId, capturedAt)) ??
|
||||
(await this.routeToEvent(orgId, origin.userId, capturedAt));
|
||||
const storageKey = storage.originalKey(orgId, sha256, ext === ".jpeg" ? ".jpg" : ext);
|
||||
const size = (await stat(file)).size;
|
||||
await storage.adopt(file, storageKey);
|
||||
@@ -407,8 +410,9 @@ export class IngestService {
|
||||
|
||||
/**
|
||||
* The event this photo belongs to: one the photographer is assigned to (or an event with no assignments,
|
||||
* open to everyone) whose ingest window contains the capture time, without a >1 h shooting gap. The
|
||||
* latest-starting one that still fits wins.
|
||||
* open to everyone) whose ingest window contains the capture time, without a >1 h shooting gap. When two
|
||||
* windows overlap (studio at 14:00 and training at 16:30), the start closest to the capture wins — not the
|
||||
* latest event on the calendar.
|
||||
*/
|
||||
async routeToEvent(organizationId: string, userId: string, at: Date): Promise<string | null> {
|
||||
const events = await this.deps.db.event.findMany({
|
||||
@@ -419,10 +423,10 @@ export class IngestService {
|
||||
ingestUntil: { gte: at },
|
||||
OR: [{ assignments: { some: { userId } } }, { assignments: { none: {} } }],
|
||||
},
|
||||
orderBy: { startsAt: "desc" },
|
||||
take: 20,
|
||||
select: { id: true },
|
||||
select: { id: true, startsAt: true },
|
||||
});
|
||||
events.sort((a, b) => Math.abs(a.startsAt.getTime() - at.getTime()) - Math.abs(b.startsAt.getTime() - at.getTime()));
|
||||
for (const event of events) {
|
||||
if (await this.sameSession(event.id, userId, at)) return event.id;
|
||||
}
|
||||
|
||||
@@ -25,11 +25,13 @@ export async function joinedEvent(db: Db, eventId: string, ids: string[]): Promi
|
||||
/**
|
||||
* Photos waiting in "Sem evento" taken during this event's ingest window (by the photographers it is assigned to,
|
||||
* or anyone when it has none): photos sent before the event was created, or before its times were corrected.
|
||||
* When another open event's window also covers the capture and starts closer to it, leave the photo in the inbox
|
||||
* (or for that other event) — otherwise creating a 16:30 training steals a 14:00 studio card from the overlap.
|
||||
*/
|
||||
export async function claimInbox(db: Db, eventId: string): Promise<string[]> {
|
||||
const event = await db.event.findUnique({
|
||||
where: { id: eventId },
|
||||
select: { organizationId: true, archivedAt: true, ingestFrom: true, ingestUntil: true, assignments: { select: { userId: true } } },
|
||||
select: { organizationId: true, archivedAt: true, ingestFrom: true, ingestUntil: true, startsAt: true, assignments: { select: { userId: true } } },
|
||||
});
|
||||
if (!event || event.archivedAt) return [];
|
||||
const photos = await db.photo.findMany({
|
||||
@@ -39,14 +41,35 @@ export async function claimInbox(db: Db, eventId: string): Promise<string[]> {
|
||||
capturedAt: { gte: event.ingestFrom, lte: event.ingestUntil },
|
||||
...(event.assignments.length && { uploaderId: { in: event.assignments.map((a) => a.userId) } }),
|
||||
},
|
||||
select: { id: true },
|
||||
select: { id: true, capturedAt: true },
|
||||
take: 20_000,
|
||||
});
|
||||
const ids = photos.map((p) => p.id);
|
||||
if (!photos.length) return [];
|
||||
const rivals = await db.event.findMany({
|
||||
where: {
|
||||
organizationId: event.organizationId,
|
||||
archivedAt: null,
|
||||
id: { not: eventId },
|
||||
ingestFrom: { lte: event.ingestUntil },
|
||||
ingestUntil: { gte: event.ingestFrom },
|
||||
},
|
||||
select: { id: true, startsAt: true, ingestFrom: true, ingestUntil: true },
|
||||
});
|
||||
const ids = photos
|
||||
.filter((p) => {
|
||||
if (!p.capturedAt) return true;
|
||||
const t = p.capturedAt.getTime();
|
||||
const better = rivals.some((r) => {
|
||||
if (t < r.ingestFrom.getTime() || t > r.ingestUntil.getTime()) return false;
|
||||
return Math.abs(r.startsAt.getTime() - t) < Math.abs(event.startsAt.getTime() - t);
|
||||
});
|
||||
return !better;
|
||||
})
|
||||
.map((p) => p.id);
|
||||
if (!ids.length) return [];
|
||||
// Only the ones still in the inbox (another event may have claimed some meanwhile).
|
||||
await db.photo.updateMany({ where: { id: { in: ids }, eventId: null }, data: { eventId } });
|
||||
const claimed = (await db.photo.findMany({ where: { id: { in: ids }, eventId }, select: { id: true } })).map((p) => p.id);
|
||||
await joinedEvent(db, eventId, claimed);
|
||||
return claimed;
|
||||
}
|
||||
}
|
||||
@@ -160,10 +160,10 @@ describe("library", () => {
|
||||
expect(forged.statusCode).toBe(404);
|
||||
});
|
||||
|
||||
it("sends a login's photos to the event chosen by hand, whatever the camera's clock, until switched off", async () => {
|
||||
it("FTP pin keeps shots inside its window; shots from another event's time still follow the clock", async () => {
|
||||
const { orgId, admin, foto, other, event } = await setup();
|
||||
const until = new Date(Date.now() + 3600_000).toISOString();
|
||||
const press = (await ctx.app.inject({ method: "POST", url: `/v1/orgs/${orgId}/events`, headers: bearer(admin), payload: { home: "Conferência de imprensa", startsAt: new Date().toISOString(), photographerIds: [] } })).json() as { id: string };
|
||||
const press = (await ctx.app.inject({ method: "POST", url: `/v1/orgs/${orgId}/events`, headers: bearer(admin), payload: { home: "Conferência de imprensa", startsAt: "2026-10-14T10:00:00Z", photographerIds: [] } })).json() as { id: string };
|
||||
await ctx.app.inject({ method: "POST", url: `/v1/orgs/${orgId}/ftp-accounts`, headers: bearer(admin), payload: { userId: other.id, login: "outro.r1" } });
|
||||
// The photographer sees only their own login; the editor sees all.
|
||||
let res = await ctx.app.inject({ method: "GET", url: `/v1/events/${event.id}/ftp-target`, headers: bearer(foto) });
|
||||
@@ -178,8 +178,10 @@ describe("library", () => {
|
||||
res = await ctx.app.inject({ method: "PUT", url: `/v1/events/${press.id}/ftp-target`, headers: bearer(admin), payload: { accountIds: [mine[0]!.id], until } });
|
||||
expect(res.json()).toMatchObject({ ftpTargets: [{ login: "foto.r1", until }] });
|
||||
expect(((await ctx.app.inject({ method: "GET", url: `/v1/events/${event.id}/ftp-target`, headers: bearer(foto) })).json() as { accounts: { elsewhere: { id: string } | null }[] }).accounts[0]!.elsewhere).toMatchObject({ id: press.id });
|
||||
// Taken during the game, but sent while the login points at the press conference: it goes there.
|
||||
expect(await service.ingestFile(await drop("foto.r1", "a.jpg", await jpeg({ color: "#123456" })))).toMatchObject({ status: "ingested", eventId: press.id });
|
||||
// Taken during the press (pin window): press gets it.
|
||||
expect(await service.ingestFile(await drop("foto.r1", "a.jpg", await jpeg({ color: "#123456", taken: "2026:10:14 10:15:00" })))).toMatchObject({ status: "ingested", eventId: press.id });
|
||||
// Taken during the game, pin still on press: clock wins — pin must not swallow another session.
|
||||
expect(await service.ingestFile(await drop("foto.r1", "game.jpg", await jpeg({ color: "#abcdef" })))).toMatchObject({ status: "ingested", eventId: event.id });
|
||||
|
||||
// Switched off: by the time again.
|
||||
await ctx.app.inject({ method: "PUT", url: `/v1/events/${press.id}/ftp-target`, headers: bearer(admin), payload: { accountIds: [] } });
|
||||
@@ -189,6 +191,41 @@ describe("library", () => {
|
||||
expect(await service.ingestFile(await drop("foto.r1", "c.jpg", await jpeg({ color: "#665544" })))).toMatchObject({ status: "ingested", eventId: event.id });
|
||||
});
|
||||
|
||||
it("when two ingest windows overlap, files the photo in the event whose start is closest to the capture", async () => {
|
||||
const { orgId, admin, photographer } = await setup();
|
||||
const miguel = (
|
||||
await ctx.app.inject({
|
||||
method: "POST",
|
||||
url: `/v1/orgs/${orgId}/events`,
|
||||
headers: bearer(admin),
|
||||
payload: { home: "Miguel em estúdio", startsAt: "2026-11-03T14:00:00Z", photographerIds: [photographer.id] },
|
||||
})
|
||||
).json() as { id: string };
|
||||
const sub21 = (
|
||||
await ctx.app.inject({
|
||||
method: "POST",
|
||||
url: `/v1/orgs/${orgId}/events`,
|
||||
headers: bearer(admin),
|
||||
payload: { home: "Treino Sub-21", startsAt: "2026-11-03T16:30:00Z", photographerIds: [photographer.id] },
|
||||
})
|
||||
).json() as { id: string };
|
||||
// Widen windows so they overlap (default is −2h/+4h: Miguel until 18:00, Sub-21 from 14:30).
|
||||
await ctx.db.event.update({ where: { id: miguel.id }, data: { ingestFrom: new Date("2026-11-03T12:00:00Z"), ingestUntil: new Date("2026-11-03T18:00:00Z") } });
|
||||
await ctx.db.event.update({ where: { id: sub21.id }, data: { ingestFrom: new Date("2026-11-03T14:30:00Z"), ingestUntil: new Date("2026-11-03T20:30:00Z") } });
|
||||
|
||||
const send = async (name: string, taken: string, pin?: string) => {
|
||||
const file = path.join(dir, name);
|
||||
await writeFile(file, await jpeg({ color: "#778899", taken }));
|
||||
return service.ingest(file, { organizationId: orgId, userId: photographer.id, source: "DESKTOP", originalName: name, eventId: pin });
|
||||
};
|
||||
// 14:20: only Miguel — Sub-21 pin must not take it.
|
||||
expect(await send("studio.jpg", "2026:11:03 14:20:00", sub21.id)).toMatchObject({ status: "ingested", eventId: miguel.id });
|
||||
// 15:00 overlap, no pin: closest start is Miguel.
|
||||
expect(await send("overlap.jpg", "2026:11:03 15:00:00")).toMatchObject({ status: "ingested", eventId: miguel.id });
|
||||
// 16:40: Sub-21.
|
||||
expect(await send("treino.jpg", "2026:11:03 16:40:00")).toMatchObject({ status: "ingested", eventId: sub21.id });
|
||||
});
|
||||
|
||||
it("a pin left on a game already put away does not take photos shot for the next event", async () => {
|
||||
const { orgId, admin, photographer, event } = await setup();
|
||||
await ctx.db.event.update({ where: { id: event.id }, data: { archivedAt: new Date("2026-10-19T10:40:00Z") } });
|
||||
|
||||
@@ -81,13 +81,14 @@ describe("local FTP feed", () => {
|
||||
// Each shows as soon as it arrives. The one the server has leaves; the failed one stays so it can be edited.
|
||||
await waitFor(() => expect(localPhotos.list().map((p) => p.name)).toEqual(["B.JPG"]));
|
||||
// Working locally (the default): previews go up, each with the fingerprint of its original.
|
||||
// Stub previews have no EXIF DateTimeOriginal → no event invented from the open pin alone.
|
||||
expect(added).toEqual([
|
||||
{ name: "A.JPG", eventId: "ev1", size: "preview of /x/FTP/A.JPG".length, sha: "sha-/x/FTP/A.JPG" },
|
||||
{ name: "B.JPG", eventId: "ev1", size: "preview of /x/FTP/B.JPG".length, sha: "sha-/x/FTP/B.JPG" },
|
||||
{ name: "A.JPG", eventId: undefined, size: "preview of /x/FTP/A.JPG".length, sha: "sha-/x/FTP/A.JPG" },
|
||||
{ name: "B.JPG", eventId: undefined, size: "preview of /x/FTP/B.JPG".length, sha: "sha-/x/FTP/B.JPG" },
|
||||
]);
|
||||
await waitFor(() => expect(result.current.counts).toEqual({ received: 2, sent: 1, failed: 1 }));
|
||||
// Only the one the server has moves to the event's work folder; the failed one stays in ingest.
|
||||
expect(shell.sent).toEqual([{ path: "/x/FTP/A.JPG", event: "ABC x Benfica", date: "2026-10-12" }]);
|
||||
// Only the one the server has moves out; without a known event (no EXIF) the work-folder name stays empty.
|
||||
expect(shell.sent).toEqual([{ path: "/x/FTP/A.JPG", event: "", date: "" }]);
|
||||
for (const photo of localPhotos.list()) localPhotos.remove(photo.id);
|
||||
});
|
||||
|
||||
|
||||
@@ -63,7 +63,9 @@ describe("usb tether", () => {
|
||||
}
|
||||
};
|
||||
renderHook(() => useUsbCamera(add, true, { id: "ev1", title: "Portugal x Suíça", date: "2026-11-04" }, invoke));
|
||||
await waitFor(() => expect(added).toEqual([{ name: "IMG_0001.JPG", eventId: "ev1" }]));
|
||||
// Preview has no EXIF DateTimeOriginal: without a capture time the open pin must not invent an event
|
||||
// (that mis-filed morning studio cards into the afternoon training).
|
||||
await waitFor(() => expect(added).toEqual([{ name: "IMG_0001.JPG", eventId: undefined }]));
|
||||
await waitFor(() => expect(sent).toEqual([{ path: "/ingest/.usb/IMG_0001.JPG", event: "Portugal x Suíça", date: "2026-11-04" }]));
|
||||
});
|
||||
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import type { EventSummary } from "@photoreport/sdk";
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
import { t } from "../i18n.js";
|
||||
import { cache } from "../offline/cache.js";
|
||||
import { eventForArrival, exifDateTime, lisbonInstant } from "../offline/local.js";
|
||||
import { asArrayBuffer, prefs } from "../platform.js";
|
||||
import { type FtpTarget, type IncomingFile, type Invoke, eventLabel } from "./LocalFtp.js";
|
||||
import type { PreviewOf, UploadStatus } from "./uploads.js";
|
||||
@@ -54,7 +56,7 @@ function savedTetherOn(): boolean {
|
||||
return prefs.get("usb.tether") === "1";
|
||||
}
|
||||
|
||||
export function useUsbCamera(add: Add, enabled: boolean, target: FtpTarget | null, invoke: Invoke = tauriInvoke) {
|
||||
export function useUsbCamera(add: Add, enabled: boolean, target: FtpTarget | null, invoke: Invoke = tauriInvoke, orgId = "") {
|
||||
const [status, setStatus] = useState<UsbStatus | null>(null);
|
||||
const [outdated, setOutdated] = useState(false);
|
||||
const [counts, setCounts] = useState({ received: 0, sent: 0, failed: 0 });
|
||||
@@ -68,6 +70,8 @@ export function useUsbCamera(add: Add, enabled: boolean, target: FtpTarget | nul
|
||||
const tetherRestored = useRef(false);
|
||||
const targetRef = useRef(target);
|
||||
targetRef.current = target;
|
||||
const orgIdRef = useRef(orgId);
|
||||
orgIdRef.current = orgId;
|
||||
const autoIngestRef = useRef(autoIngest);
|
||||
autoIngestRef.current = autoIngest;
|
||||
|
||||
@@ -94,11 +98,21 @@ export function useUsbCamera(add: Add, enabled: boolean, target: FtpTarget | nul
|
||||
invoke<PreviewOf>("ftp_info", { path: f.path }),
|
||||
]);
|
||||
const file = new File([bytes], f.name, { type: "image/jpeg", lastModified: f.modifiedMs });
|
||||
add([file], to?.id, (_file, result) => {
|
||||
const cached = orgIdRef.current ? await cache.events(orgIdRef.current) : null;
|
||||
const events = cached?.events ?? [];
|
||||
const capturedAt = lisbonInstant(exifDateTime(bytes));
|
||||
const pinnedId = to && (!cached || events.some((e) => e.id === to.id && !e.archivedAt)) ? to.id : null;
|
||||
const eventId = eventForArrival(pinnedId, events, capturedAt);
|
||||
const filed = events.find((e) => e.id === eventId);
|
||||
add([file], eventId ?? undefined, (_file, result) => {
|
||||
inFlight.current--;
|
||||
if (result === "done" || result === "duplicate") {
|
||||
setCounts((c) => ({ ...c, sent: c.sent + 1 }));
|
||||
invoke("ftp_sent", { path: f.path, event: to?.title ?? "", date: to?.date ?? "" }).catch(() => {});
|
||||
invoke("ftp_sent", {
|
||||
path: f.path,
|
||||
event: filed ? eventLabel(filed) : (to?.title ?? ""),
|
||||
date: filed ? filed.startsAt.slice(0, 10) : (to?.date ?? ""),
|
||||
}).catch(() => {});
|
||||
} else {
|
||||
setCounts((c) => ({ ...c, failed: c.failed + 1 }));
|
||||
}
|
||||
|
||||
@@ -37,7 +37,7 @@ function IngestState({ api, orgId, children }: { api: ReturnType<typeof useAuth>
|
||||
const desktop = isDesktop();
|
||||
const uploads = useUploadQueue(api, orgId);
|
||||
const localFtp = useLocalFtp(uploads.add, desktop && !!orgId, undefined, orgId);
|
||||
const usb = useUsbCamera(uploads.add, desktop && !!orgId, localFtp.target);
|
||||
const usb = useUsbCamera(uploads.add, desktop && !!orgId, localFtp.target, undefined, orgId);
|
||||
const originals = useMemo(() => (desktop && orgId ? new OriginalSender(api) : null), [api, desktop, orgId]);
|
||||
useOfflineSync(api, orgId);
|
||||
return (
|
||||
|
||||
@@ -13,7 +13,7 @@ describe("showLocalJpeg", () => {
|
||||
eventId: "ev1",
|
||||
origin: { sha256: "abc123", size: 4, width: 100, height: 80 },
|
||||
});
|
||||
expect(sha).toBe("abc123");
|
||||
expect(sha?.sha256).toBe("abc123");
|
||||
expect(localPhotos.bySha("abc123")?.eventId).toBe("ev1");
|
||||
expect(localPhotos.bySha("abc123")?.originalName).toBe("IMG_1.JPG");
|
||||
for (const p of localPhotos.list()) localPhotos.remove(p.id);
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import type { PhotoSummary } from "@photoreport/contracts";
|
||||
import { exifDateTime, lisbonInstant, localPhoto, localPhotos } from "../offline/local.js";
|
||||
import type { EventSummary } from "@photoreport/sdk";
|
||||
import { eventForArrival, exifDateTime, lisbonInstant, localPhoto, localPhotos } from "../offline/local.js";
|
||||
import { localId, offlineQueue } from "../offline/queue.js";
|
||||
import type { DesktopOrigin } from "./uploads.js";
|
||||
|
||||
@@ -33,39 +34,46 @@ async function imageSize(blob: Blob): Promise<{ width: number; height: number }>
|
||||
|
||||
/**
|
||||
* Puts a JPEG into the library at once from bytes already on this computer. Upload can finish later;
|
||||
* `photo.added` (same sha) replaces this row. Returns the sha when the preview is on screen.
|
||||
* `photo.added` (same sha) replaces this row. Returns the sha (and the event chosen from EXIF) when on screen.
|
||||
*/
|
||||
export async function showLocalJpeg(args: {
|
||||
file: File;
|
||||
eventId?: string | undefined;
|
||||
origin?: DesktopOrigin | undefined;
|
||||
orgId?: string | undefined;
|
||||
}): Promise<string | null> {
|
||||
const { file, eventId, origin, orgId } = args;
|
||||
events?: Pick<EventSummary, "id" | "startsAt" | "ingestFrom" | "ingestUntil" | "archivedAt">[] | undefined;
|
||||
}): Promise<{ sha256: string; eventId: string | null } | null> {
|
||||
const { file, origin, orgId, events } = args;
|
||||
try {
|
||||
let sha256: string;
|
||||
let width: number;
|
||||
let height: number;
|
||||
let previewBytes: ArrayBuffer | null = null;
|
||||
// Always read EXIF from the JPEG bytes when we can — desktop previews keep DateTimeOriginal, and that
|
||||
// clock (not the open event pin) decides which folder the photo appears in.
|
||||
const previewBytes = await file.arrayBuffer();
|
||||
if (origin && origin !== "original") {
|
||||
sha256 = origin.sha256;
|
||||
width = origin.width;
|
||||
height = origin.height;
|
||||
} else {
|
||||
previewBytes = await file.arrayBuffer();
|
||||
sha256 = await sha256Hex(previewBytes);
|
||||
const size = await imageSize(new Blob([previewBytes], { type: "image/jpeg" }));
|
||||
width = size.width;
|
||||
height = size.height;
|
||||
}
|
||||
if (localPhotos.bySha(sha256)) return sha256;
|
||||
if (localPhotos.bySha(sha256)) return { sha256, eventId: localPhotos.bySha(sha256)?.eventId ?? null };
|
||||
let url = "";
|
||||
try {
|
||||
url = URL.createObjectURL(file);
|
||||
url = URL.createObjectURL(new Blob([previewBytes], { type: "image/jpeg" }));
|
||||
} catch {
|
||||
/* tests / no blob URLs */
|
||||
try {
|
||||
url = URL.createObjectURL(file);
|
||||
} catch {
|
||||
/* tests / no blob URLs */
|
||||
}
|
||||
}
|
||||
const capturedAt = previewBytes ? lisbonInstant(exifDateTime(previewBytes)) : null;
|
||||
const capturedAt = lisbonInstant(exifDateTime(previewBytes));
|
||||
const eventId = events ? eventForArrival(args.eventId ?? null, events, capturedAt) : (args.eventId ?? null);
|
||||
localPhotos.put(
|
||||
localPhoto({
|
||||
sha256,
|
||||
@@ -73,7 +81,7 @@ export async function showLocalJpeg(args: {
|
||||
width,
|
||||
height,
|
||||
capturedAt,
|
||||
eventId: eventId ?? null,
|
||||
eventId,
|
||||
url,
|
||||
}),
|
||||
);
|
||||
@@ -84,7 +92,7 @@ export async function showLocalJpeg(args: {
|
||||
}
|
||||
}
|
||||
}
|
||||
return sha256;
|
||||
return { sha256, eventId };
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import type { PhotoSummary } from "@photoreport/contracts";
|
||||
import { ApiError, type ApiClient } from "@photoreport/sdk";
|
||||
import { cache } from "../offline/cache.js";
|
||||
import { isNetworkError, offlineQueue } from "../offline/queue.js";
|
||||
import { useCallback, useRef, useState } from "react";
|
||||
import { prefs } from "../platform.js";
|
||||
@@ -259,14 +260,22 @@ export function useUploadQueue(api: ApiClient, orgId: string) {
|
||||
}
|
||||
added.push(item);
|
||||
// Preview in the grid before the bytes leave this computer (USB, drop, FTP share this path).
|
||||
// Event from EXIF + window (not the open folder alone), so a morning studio card does not land on the afternoon training.
|
||||
void (async () => {
|
||||
const sha256 = await showLocalJpeg({ file, eventId, origin: original, orgId });
|
||||
const cached = orgId ? await cache.events(orgId) : null;
|
||||
const shown = await showLocalJpeg({
|
||||
file,
|
||||
eventId,
|
||||
origin: original,
|
||||
orgId,
|
||||
events: cached?.events,
|
||||
});
|
||||
queue.current.push({
|
||||
item,
|
||||
file,
|
||||
eventId,
|
||||
eventId: shown?.eventId ?? eventId,
|
||||
...(original && { original }),
|
||||
sha256,
|
||||
sha256: shown?.sha256 ?? null,
|
||||
...(onSettled && { onSettled: (status: UploadStatus, photo?: PhotoSummary) => onSettled(file, status, photo) }),
|
||||
});
|
||||
pump();
|
||||
|
||||
@@ -75,29 +75,44 @@ export function lisbonInstant(exif: string | null): string | null {
|
||||
|
||||
type RoutedEvent = Pick<EventSummary, "id" | "ingestFrom" | "ingestUntil" | "archivedAt" | "startsAt">;
|
||||
|
||||
/**
|
||||
* Among open events whose ingest window covers `at`, the one whose start is closest to the capture.
|
||||
* "Latest start wins" wrongly pulled a 14:00 studio session into a 16:30 training when windows overlapped.
|
||||
*/
|
||||
export function bestEventForCapture(events: RoutedEvent[], at: string): RoutedEvent | null {
|
||||
const t = Date.parse(at);
|
||||
if (!Number.isFinite(t)) return null;
|
||||
const open = events.filter((e) => !e.archivedAt && Date.parse(e.ingestFrom) <= t && t <= Date.parse(e.ingestUntil));
|
||||
if (!open.length) return null;
|
||||
open.sort((a, b) => Math.abs(Date.parse(a.startsAt) - t) - Math.abs(Date.parse(b.startsAt) - t));
|
||||
return open[0] ?? null;
|
||||
}
|
||||
|
||||
/** The event a photo taken at `at` belongs to, as the server would route it (offline guess; the server decides). */
|
||||
export function routeLocally(events: RoutedEvent[], at: string | null): string | null {
|
||||
if (!at) return null;
|
||||
const t = Date.parse(at);
|
||||
const open = events.filter((e) => !e.archivedAt && Date.parse(e.ingestFrom) <= t && t <= Date.parse(e.ingestUntil));
|
||||
open.sort((a, b) => Date.parse(b.startsAt) - Date.parse(a.startsAt));
|
||||
return open[0]?.id ?? null;
|
||||
return bestEventForCapture(events, at)?.id ?? null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Where a local-FTP photo goes. The event the photographer pinned receives it only while the capture falls in that
|
||||
* event's window. Outside it (the pin left over from yesterday's match), the photo goes to the event of the time
|
||||
* it was taken. A pin whose window isn't in the list, or a photo with no capture time, keeps the pin.
|
||||
* Where a photo arrives on this computer. The pin (FTP target / open event) wins only while the capture sits
|
||||
* inside that event's window — leftover pins from the morning studio must not swallow the afternoon training
|
||||
* (or the other way around). No capture time → inbox; never invent "now" to keep the pin.
|
||||
*/
|
||||
export function eventForArrival(pinnedId: string | null, events: RoutedEvent[], at: string | null): string | null {
|
||||
if (!at) return null;
|
||||
if (!pinnedId) return routeLocally(events, at);
|
||||
const pinned = events.find((e) => e.id === pinnedId);
|
||||
if (!pinned || !at) return pinnedId;
|
||||
const pinned = events.find((e) => e.id === pinnedId && !e.archivedAt);
|
||||
if (!pinned) {
|
||||
// Agenda not loaded yet: keep the open pin so live FTP still lands somewhere; a stale id with a warm
|
||||
// cache falls through to the clock instead.
|
||||
if (!events.length) return pinnedId;
|
||||
return routeLocally(events, at);
|
||||
}
|
||||
const t = Date.parse(at);
|
||||
if (Date.parse(pinned.ingestFrom) <= t && t <= Date.parse(pinned.ingestUntil)) return pinnedId;
|
||||
return routeLocally(events, at);
|
||||
}
|
||||
|
||||
export function localPhoto(p: { sha256: string; name: string; width: number; height: number; capturedAt: string | null; eventId: string | null; url: string }): PhotoSummary {
|
||||
return {
|
||||
id: localId(p.sha256),
|
||||
|
||||
@@ -123,8 +123,23 @@ describe("photos arriving on this computer", () => {
|
||||
// Yesterday's pin only holds photos taken inside it. The next morning goes to that morning's event.
|
||||
expect(eventForArrival("braga", events, at)).toBe("braga");
|
||||
expect(eventForArrival("braga", events, "2026-10-10T15:30:00Z")).toBe("other");
|
||||
expect(eventForArrival("braga", events, null)).toBe("braga");
|
||||
expect(eventForArrival("missing", events, "2026-10-10T15:30:00Z")).toBe("missing");
|
||||
// No capture time: inbox — do not keep a leftover pin (that put morning studio shots into the afternoon training).
|
||||
expect(eventForArrival("braga", events, null)).toBeNull();
|
||||
expect(eventForArrival("missing", events, "2026-10-10T15:30:00Z")).toBe("other");
|
||||
});
|
||||
|
||||
it("when two ingest windows overlap, files the photo in the event whose start is closest to the capture", () => {
|
||||
const events = [
|
||||
{ id: "miguel", startsAt: "2026-11-03T14:00:00Z", ingestFrom: "2026-11-03T12:00:00Z", ingestUntil: "2026-11-03T18:00:00Z", archivedAt: null },
|
||||
{ id: "sub21", startsAt: "2026-11-03T16:30:00Z", ingestFrom: "2026-11-03T14:30:00Z", ingestUntil: "2026-11-03T20:30:00Z", archivedAt: null },
|
||||
];
|
||||
// Studio at 14:20: only Miguel's window.
|
||||
expect(eventForArrival("sub21", events, "2026-11-03T14:20:00Z")).toBe("miguel");
|
||||
// Overlap at 15:00 with Sub-21 pinned: pin wins while capture is inside its window.
|
||||
expect(eventForArrival("sub21", events, "2026-11-03T15:00:00Z")).toBe("sub21");
|
||||
// Overlap without a pin: closest start (Miguel at 14:00 beats Sub-21 at 16:30 for a 15:00 capture).
|
||||
expect(eventForArrival(null, events, "2026-11-03T15:00:00Z")).toBe("miguel");
|
||||
expect(eventForArrival(null, events, "2026-11-03T16:40:00Z")).toBe("sub21");
|
||||
});
|
||||
|
||||
it("show in the library at once and give way to the server's copy, keeping what was done to them", () => {
|
||||
|
||||
Reference in new issue
Block a user