diff --git a/apps/api/src/autopilot/service.ts b/apps/api/src/autopilot/service.ts index 6386edb..ee531f8 100644 --- a/apps/api/src/autopilot/service.ts +++ b/apps/api/src/autopilot/service.ts @@ -29,7 +29,7 @@ import { import { curate, matchMinutes } from "./curate.js"; import { type LearntStyle, learntStyle } from "./learning.js"; import { detailForCrop, lookValues } from "./look.js"; -import { exportTargets, galleryReceivers, MELHORES_GAP_MS, picksNeeded, type GalleryExport } from "./targets.js"; +import { assignBurstExports, exportSlots, exportTargets, galleryReceivers, MELHORES_GAP_MS, picksNeeded, type BurstExportSlot, type GalleryExport } from "./targets.js"; const STALE_RUNNING_MS = 10 * 60_000; /** A burst is decided once no new frame of it has arrived for this long. */ @@ -282,7 +282,18 @@ export class AutopilotService { const score = rec?.score == null ? null : rec.score * (look.get(p.id) ?? 1); return { ...p, rec, camera: p.cameraSerial ?? p.cameraModel ?? p.uploaderId ?? "?", score }; }); - for (const burst of groupBursts(frames, settings.burstGapSec * 1000)) { + const orderedBursts = groupBursts(frames, settings.burstGapSec * 1000); + const sentByTarget = new Map(); + if (settings.deliverExports.length > 0) { + const sentRows = await db.deliveryItem.groupBy({ + by: ["targetId"], + where: { eventId, status: { in: ["QUEUED", "RUNNING", "WAITING", "DONE"] } }, + _count: true, + }); + for (const row of sentRows) sentByTarget.set(row.targetId, row._count); + } + for (let burstIndex = 0; burstIndex < orderedBursts.length; burstIndex++) { + const burst = orderedBursts[burstIndex]!; if (burst.every((f) => f.rec?.decided)) continue; // Still arriving: wait until the burst has settled. if (Math.max(...burst.map((f) => f.createdAt.getTime())) > now.getTime() - BURST_SETTLE_MS) continue; @@ -301,7 +312,8 @@ export class AutopilotService { // between frames) is still that sequence. A frame that looks different may add another, up to four. let take = asked; if (!reportage) { - take = Math.min(asked, Math.max(0, settings.picksPerBurst)); + const cap = settings.deliverExports.length > 0 ? settings.deliverExports.length : settings.picksPerBurst; + take = Math.min(asked, Math.max(0, cap)); } const start = Math.min(...burst.map((f) => (f.capturedAt ?? f.createdAt).getTime())); const sameCamera = frames @@ -323,13 +335,16 @@ export class AutopilotService { }); if (already.length > 0) { const next = bestOf(pool, 1)[0]; - const room = next - ? sequenceSendRoom(settings.picksPerBurst, already.map((frame) => frame.look), { - subject: next.rec?.subject ?? null, - people: next.rec?.people ?? null, - reason: next.rec?.reason ?? null, - }) - : 0; + let sequenceCap = settings.picksPerBurst; + if (settings.deliverExports.length > 0) sequenceCap = settings.deliverExports.length; + let room = 0; + if (next) { + room = sequenceSendRoom(sequenceCap, already.map((frame) => frame.look), { + subject: next.rec?.subject ?? null, + people: next.rec?.people ?? null, + reason: next.rec?.reason ?? null, + }); + } take = Math.min(take, room); } const chosen = bestOf(pool, take) @@ -408,11 +423,37 @@ export class AutopilotService { await db.photo.update({ where: { id: f.id }, data: { autopilot: { ...(f.rec ?? {}), decided: true, picked: pickedIds.has(f.id) } as object } }); } // "Only the best" delivers per window of the match instead (below), not every burst's picks. - // N exports → rank i of this burst to export i (same file never to two). - const targets = exportTargets(settings); - if (settings.selection === "bursts" && targets.length && best.length && this.deps.deliveries && event.createdById) { + // One different frame per destination still under its total. A copy (Direto → Arquivo) shares the frame. + const slots: BurstExportSlot[] = exportSlots(settings).map((slot) => ({ + ...slot, + sent: sentByTarget.get(slot.targetId) ?? 0, + })); + if (settings.selection === "bursts" && settings.deliverExports.length > 0 && slots.length && best.length && this.deps.deliveries && event.createdById) { const when = new Map(photos.map((p) => [p.id, p.capturedAt])); const sendable = best.filter((f) => f.rec?.hold !== "ball" && takenHere([f.id], when, event).length); + const plan = assignBurstExports(slots, burstIndex, sendable.length); + for (const assignment of plan) { + const frame = sendable[assignment.rank]; + if (!frame) continue; + const targets = [assignment.targetId, ...assignment.alsoTargetIds]; + for (const targetId of targets) { + await this.deps.deliveries + .enqueue({ + organizationId: event.organizationId, + targetId, + photoIds: [frame.id], + again: false, + originals: assignment.originals, + requestedById: event.createdById, + }) + .catch((err: unknown) => log.warn({ err, targetId }, "autopilot: delivery not queued")); + } + sentByTarget.set(assignment.targetId, (sentByTarget.get(assignment.targetId) ?? 0) + 1); + } + } else if (settings.selection === "bursts" && slots.length && best.length && this.deps.deliveries && event.createdById) { + const when = new Map(photos.map((p) => [p.id, p.capturedAt])); + const sendable = best.filter((f) => f.rec?.hold !== "ball" && takenHere([f.id], when, event).length); + const targets = exportTargets(settings); for (let i = 0; i < targets.length && i < sendable.length; i++) { const id = sendable[i]!.id; await this.deps.deliveries diff --git a/apps/api/src/autopilot/targets.ts b/apps/api/src/autopilot/targets.ts index 1026e6c..24abdc9 100644 --- a/apps/api/src/autopilot/targets.ts +++ b/apps/api/src/autopilot/targets.ts @@ -22,8 +22,96 @@ export function exportTargets(settings: Pick, +): Omit[] { + const configured = settings.deliverExports ?? []; + if (configured.length) { + const seen = new Set(); + const slots: Omit[] = []; + for (const row of configured) { + if (!row.targetId || seen.has(row.targetId)) continue; + seen.add(row.targetId); + const also: string[] = []; + for (const id of row.alsoTargetIds) { + if (!id || id === row.targetId || seen.has(id)) continue; + seen.add(id); + also.push(id); + } + slots.push({ + targetId: row.targetId, + alsoTargetIds: also, + count: row.count, + originals: row.originals, + }); + } + return slots; + } + return exportTargets(settings).map((targetId) => ({ + targetId, + alsoTargetIds: [], + count: null, + originals: false, + })); +} + +/** + * One different frame per destination that is still under its total. A short burst starts at the next + * destination, so the frames that do exist rotate and every total can still be met. A destination that + * already has its `count` is skipped. `alsoTargetIds` ride with that frame and do not take another one. + */ +export function assignBurstExports(slots: readonly BurstExportSlot[], burstIndex: number, frameCount: number): BurstAssignment[] { + if (frameCount <= 0 || slots.length === 0) return []; + const open: { slot: BurstExportSlot; order: number }[] = []; + for (let order = 0; order < slots.length; order++) { + const slot = slots[order]!; + if (slot.count !== null && slot.sent >= slot.count) continue; + open.push({ slot, order }); + } + if (open.length === 0) return []; + const start = burstIndex % slots.length; + open.sort((left, right) => { + const leftTurn = (left.order - start + slots.length) % slots.length; + const rightTurn = (right.order - start + slots.length) % slots.length; + return leftTurn - rightTurn; + }); + const take = Math.min(open.length, frameCount); + const assigned: BurstAssignment[] = []; + for (let rank = 0; rank < take; rank++) { + const slot = open[rank]!.slot; + assigned.push({ + targetId: slot.targetId, + alsoTargetIds: slot.alsoTargetIds, + originals: slot.originals, + rank, + }); + } + return assigned; +} + /** How many frames of a burst to keep: one per configured export, else `picksPerBurst`. */ export function picksNeeded(settings: AutopilotSettings): number { + const configured = settings.deliverExports?.length ?? 0; + if (configured > 0) return Math.min(10, configured); const n = exportTargets(settings).length; if (n > 0) return Math.min(5, Math.max(1, n)); return settings.picksPerBurst; diff --git a/apps/api/test/targets.test.ts b/apps/api/test/targets.test.ts index e9bd290..0382626 100644 --- a/apps/api/test/targets.test.ts +++ b/apps/api/test/targets.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it } from "vitest"; import { AutopilotSettings } from "@photoreport/contracts"; -import { exportTargets, galleryReceivers, picksNeeded } from "../src/autopilot/targets.js"; +import { assignBurstExports, exportSlots, exportTargets, galleryReceivers, picksNeeded, type BurstExportSlot } from "../src/autopilot/targets.js"; const a = "11111111-1111-4111-8111-111111111111"; const b = "22222222-2222-4222-8222-222222222222"; @@ -17,6 +17,62 @@ describe("exportTargets", () => { }); }); +function slot(targetId: string, extra: Partial = {}): BurstExportSlot { + return { + targetId, + alsoTargetIds: [], + count: null, + originals: false, + sent: 0, + ...extra, + }; +} + +describe("exportSlots", () => { + it("keeps a copy on the same frame and out of the pick list", () => { + const settings = AutopilotSettings.parse({ + enabled: true, + deliverExports: [ + { targetId: a, alsoTargetIds: [b], count: 50, originals: false }, + { targetId: c, alsoTargetIds: [], count: null, originals: true }, + ], + }); + expect(exportSlots(settings)).toEqual([ + { targetId: a, alsoTargetIds: [b], count: 50, originals: false }, + { targetId: c, alsoTargetIds: [], count: null, originals: true }, + ]); + }); +}); + +describe("assignBurstExports", () => { + const three = [slot(a), slot(b), slot(c)]; + + it("gives one different frame to each destination when the burst has enough", () => { + expect(assignBurstExports(three, 0, 3).map((row) => row.targetId)).toEqual([a, b, c]); + }); + + it("rotates the only frame so a short burst does not always feed the first destination", () => { + expect(assignBurstExports(three, 0, 1).map((row) => row.targetId)).toEqual([a]); + expect(assignBurstExports(three, 1, 1).map((row) => row.targetId)).toEqual([b]); + expect(assignBurstExports(three, 2, 1).map((row) => row.targetId)).toEqual([c]); + expect(assignBurstExports(three, 3, 1).map((row) => row.targetId)).toEqual([a]); + }); + + it("stops a destination that already has its total and keeps filling the others", () => { + const slots = [slot(a, { count: 20, sent: 20 }), slot(b, { count: 80, sent: 20 }), slot(c)]; + expect(assignBurstExports(slots, 0, 2).map((row) => row.targetId)).toEqual([b, c]); + }); + + it("sends the same frame's copy alongside, without taking a second frame", () => { + const slots = [slot(a, { alsoTargetIds: [b] }), slot(c)]; + const plan = assignBurstExports(slots, 0, 2); + expect(plan).toEqual([ + { targetId: a, alsoTargetIds: [b], originals: false, rank: 0 }, + { targetId: c, alsoTargetIds: [], originals: false, rank: 1 }, + ]); + }); +}); + describe("picksNeeded", () => { it("matches the number of exports when set", () => { const s = AutopilotSettings.parse({ enabled: true, deliverTargetIds: [a, b, c] }); diff --git a/apps/app/src/i18n.ts b/apps/app/src/i18n.ts index 5822a1b..235b129 100644 --- a/apps/app/src/i18n.ts +++ b/apps/app/src/i18n.ts @@ -578,6 +578,14 @@ export const t = { noPicks: "Não escolher", minLongEdge: "Resolução mínima do recorte", deliver: "Enviar as escolhidas para", + exportAdd: "Acrescentar envio", + exportRemove: "Tirar", + exportAlso: "A mesma foto também para", + exportCount: "Total neste jogo", + exportOriginals: "Originais, sem edição", + exportHelp: + "Há tantos escolhidos por sequência quantos os envios: uma foto diferente para cada um. Se a sequência não chegar para todos, a que houver vai rodando, para no fim cada destino chegar ao total que pediste. Vazio nesse total: uma por sequência, até ao fim. «Também para» manda a mesma foto aos dois (Cofina Direto e Cofina Arquivo) e não conta como outra escolha. Originais sai o ficheiro da câmara, sem o recorte nem o tom.", + exportPlayers: "Um destino com «Esperar pelas caras» sai com os jogadores no ficheiro. Se os nomes chegarem depois, o ficheiro volta a ser enviado.", noDelivery: "Não enviar", selection: "O que enviar", selectionBursts: "As escolhidas de cada sequência", diff --git a/apps/app/src/library/Autopilot.tsx b/apps/app/src/library/Autopilot.tsx index c051e3b..cb693eb 100644 --- a/apps/app/src/library/Autopilot.tsx +++ b/apps/app/src/library/Autopilot.tsx @@ -4,6 +4,153 @@ import { useEffect, useState } from "react"; import { t } from "../i18n.js"; import { ZerozeroGamePicker } from "./ZerozeroGame.js"; +type ExportRow = AutopilotSettings["deliverExports"][number]; + +/** As many burst exports as the photographer lists. One frame each; a copy shares that frame. */ +function BurstExports(props: { + settings: AutopilotSettings; + targets: DeliveryTarget[]; + canEdit: boolean; + onChange: (next: AutopilotSettings) => void; +}) { + const L = t.autopilot; + const rows = props.settings.deliverExports; + const used = new Set(); + for (const row of rows) { + used.add(row.targetId); + for (const id of row.alsoTargetIds) used.add(id); + } + + const commit = (nextRows: ExportRow[]) => { + const primaries: string[] = []; + for (const row of nextRows) primaries.push(row.targetId); + props.onChange({ + ...props.settings, + deliverExports: nextRows, + deliverTargetIds: primaries, + deliverTargetId: primaries[0] ?? null, + }); + }; + + const update = (index: number, row: ExportRow) => { + const next = rows.map((item) => ({ ...item, alsoTargetIds: [...item.alsoTargetIds] })); + next[index] = row; + commit(next); + }; + + const add = () => { + let free = ""; + for (const target of props.targets) { + if (!used.has(target.id)) { + free = target.id; + break; + } + } + if (!free) return; + commit([...rows, { targetId: free, alsoTargetIds: [], count: null, originals: false }]); + }; + + const remove = (index: number) => { + commit(rows.filter((_, i) => i !== index)); + }; + + return ( +
+

{L.exportHelp}

+ {rows.map((row, index) => { + const also = row.alsoTargetIds[0] ?? ""; + return ( +
+ + + + +
+ ); + })} + +

{L.exportPlayers}

+
+ ); +} + /** * Autopilot for the open event (docs/photo-editing-rules.md): photos arriving by FTP or the desktop app's ingest * are edited (tone, level, crop) and the best frames of each burst picked, and optionally delivered. @@ -30,9 +177,12 @@ export function AutopilotButton(props: { }, [props.autopilotAsk, props.event.id, props.onAsked]); const save = async (next: AutopilotSettings) => { - // Keep deliverTargetIds in sync with the two legacy slots (N exports = ordered list). - const ids = [next.deliverTargetId, next.restTargetId].filter((x): x is string => !!x); - const synced = { ...next, deliverTargetIds: ids.length ? ids : next.deliverTargetIds ?? [] }; + // Burst groups already name every destination. The two legacy slots must not wipe that list. + let synced = next; + if (next.selection !== "bursts" || next.deliverExports.length === 0) { + const ids = [next.deliverTargetId, next.restTargetId].filter((x): x is string => !!x); + if (ids.length > 0) synced = { ...next, deliverTargetIds: ids }; + } setS(synced); setState("saving"); try { @@ -59,7 +209,7 @@ export function AutopilotButton(props: { {L.button} {open && ( -
+
- + {s.selection === "bursts" && ( + void save(next)} /> + )} + {s.selection !== "bursts" && ( + + )}