From 42912453e28c40dc7c6a2b46fa829252d6b06d46 Mon Sep 17 00:00:00 2001 From: spark Date: Tue, 3 Nov 2026 17:00:09 +0000 Subject: [PATCH 1/2] fix(ingest): route by capture time, not leftover open-event pin (BIT-165) Morning studio cards (14h) were landing on the afternoon Sub-21 training when windows overlapped or the pin ignored EXIF. Pin only wins inside its ingest window; overlapping windows pick the closest startsAt; no capture time stays in the inbox. --- apps/api/src/ingest/service.ts | 23 ++++++------ apps/api/src/library/adopt.ts | 31 +++++++++++++--- apps/api/test/library.test.ts | 45 +++++++++++++++++++++--- apps/app/src/library/LocalFtp.test.tsx | 9 ++--- apps/app/src/library/UsbCamera.test.tsx | 4 ++- apps/app/src/library/UsbCamera.tsx | 20 +++++++++-- apps/app/src/library/ingest.tsx | 2 +- apps/app/src/library/localIngest.test.ts | 2 +- apps/app/src/library/localIngest.ts | 32 ++++++++++------- apps/app/src/library/uploads.ts | 15 ++++++-- apps/app/src/offline/local.ts | 35 ++++++++++++------ apps/app/src/offline/offline.test.ts | 19 ++++++++-- 12 files changed, 182 insertions(+), 55 deletions(-) diff --git a/apps/api/src/ingest/service.ts b/apps/api/src/ingest/service.ts index 6977fa2..06845a7 100644 --- a/apps/api/src/ingest/service.ts +++ b/apps/api/src/ingest/service.ts @@ -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,18 @@ export class IngestService { const camera = await readCameraInfo(file).catch(() => ({}) as Awaited>); 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: do not invent "now" (that would force today's open + // event and pull a morning studio card into the afternoon training). Held merges keep their named event. 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 + ? null + : (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 +409,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 { const events = await this.deps.db.event.findMany({ @@ -419,10 +422,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; } diff --git a/apps/api/src/library/adopt.ts b/apps/api/src/library/adopt.ts index a882237..087b54d 100644 --- a/apps/api/src/library/adopt.ts +++ b/apps/api/src/library/adopt.ts @@ -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 { 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 { 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; -} +} \ No newline at end of file diff --git a/apps/api/test/library.test.ts b/apps/api/test/library.test.ts index edd5bfe..96eea60 100644 --- a/apps/api/test/library.test.ts +++ b/apps/api/test/library.test.ts @@ -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") } }); diff --git a/apps/app/src/library/LocalFtp.test.tsx b/apps/app/src/library/LocalFtp.test.tsx index 9e980e5..9b724cd 100644 --- a/apps/app/src/library/LocalFtp.test.tsx +++ b/apps/app/src/library/LocalFtp.test.tsx @@ -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); }); diff --git a/apps/app/src/library/UsbCamera.test.tsx b/apps/app/src/library/UsbCamera.test.tsx index 104f095..f8fa9ff 100644 --- a/apps/app/src/library/UsbCamera.test.tsx +++ b/apps/app/src/library/UsbCamera.test.tsx @@ -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" }])); }); diff --git a/apps/app/src/library/UsbCamera.tsx b/apps/app/src/library/UsbCamera.tsx index 5d1a30f..817c52b 100644 --- a/apps/app/src/library/UsbCamera.tsx +++ b/apps/app/src/library/UsbCamera.tsx @@ -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(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("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 })); } diff --git a/apps/app/src/library/ingest.tsx b/apps/app/src/library/ingest.tsx index d145a0a..7f74f54 100644 --- a/apps/app/src/library/ingest.tsx +++ b/apps/app/src/library/ingest.tsx @@ -37,7 +37,7 @@ function IngestState({ api, orgId, children }: { api: ReturnType 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 ( diff --git a/apps/app/src/library/localIngest.test.ts b/apps/app/src/library/localIngest.test.ts index bbd5e16..f03f775 100644 --- a/apps/app/src/library/localIngest.test.ts +++ b/apps/app/src/library/localIngest.test.ts @@ -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); diff --git a/apps/app/src/library/localIngest.ts b/apps/app/src/library/localIngest.ts index e8879f4..05ea6da 100644 --- a/apps/app/src/library/localIngest.ts +++ b/apps/app/src/library/localIngest.ts @@ -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 { - const { file, eventId, origin, orgId } = args; + events?: Pick[] | 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; } diff --git a/apps/app/src/library/uploads.ts b/apps/app/src/library/uploads.ts index ebbf6be..989919f 100644 --- a/apps/app/src/library/uploads.ts +++ b/apps/app/src/library/uploads.ts @@ -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(); diff --git a/apps/app/src/offline/local.ts b/apps/app/src/offline/local.ts index ccc8df1..d0f9292 100644 --- a/apps/app/src/offline/local.ts +++ b/apps/app/src/offline/local.ts @@ -75,29 +75,44 @@ export function lisbonInstant(exif: string | null): string | null { type RoutedEvent = Pick; +/** + * 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), diff --git a/apps/app/src/offline/offline.test.ts b/apps/app/src/offline/offline.test.ts index 811542b..9d7a0f0 100644 --- a/apps/app/src/offline/offline.test.ts +++ b/apps/app/src/offline/offline.test.ts @@ -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", () => { -- 2.47.3 From a9ae5ce6ad87ff9476f81693761863b33630b8a0 Mon Sep 17 00:00:00 2001 From: spark Date: Tue, 3 Nov 2026 17:10:55 +0000 Subject: [PATCH 2/2] fix(ingest): keep named event when the JPEG has no capture time (BIT-165) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Hand/desktop uploads into an open folder (and zero-width test fixtures) have no DateTimeOriginal; dropping them into Sem evento broke autopilot. The Miguel→Sub-21 bug is the case with EXIF outside the pin window. --- apps/api/src/ingest/service.ts | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/apps/api/src/ingest/service.ts b/apps/api/src/ingest/service.ts index 06845a7..6b4d590 100644 --- a/apps/api/src/ingest/service.ts +++ b/apps/api/src/ingest/service.ts @@ -173,8 +173,9 @@ export class IngestService { const camera = await readCameraInfo(file).catch(() => ({}) as Awaited>); const embedded = await readEmbeddedIptc(file); const capturedAt = camera.capturedAt ? new Date(camera.capturedAt.getTime() + (origin.clockOffsetSec ?? 0) * 1000) : undefined; - // Archive imports name their own event. No camera time: do not invent "now" (that would force today's open - // event and pull a morning studio card into the afternoon training). Held merges keep their named event. + // 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 @@ -182,7 +183,7 @@ export class IngestService { : origin.source === "CLOUD" ? await this.namedEvent(orgId, origin.eventId) : !capturedAt - ? null + ? 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); -- 2.47.3