Compare commits
10
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c8949c690d | ||
|
|
690b35389d | ||
|
|
cb2b887a48 | ||
|
|
413983a057 | ||
|
|
30b30ef122 | ||
|
|
2fad6e96c3 | ||
|
|
ae6e467103 | ||
|
|
360dc5efb8 | ||
|
|
92cecc7214 | ||
|
|
a9b7007d5d |
No files matched your search
@@ -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<string, number>();
|
||||
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
|
||||
|
||||
@@ -22,8 +22,96 @@ export function exportTargets(settings: Pick<AutopilotSettings, "deliverTargetId
|
||||
return out;
|
||||
}
|
||||
|
||||
export interface BurstExportSlot {
|
||||
targetId: string;
|
||||
alsoTargetIds: string[];
|
||||
/** Null: this destination stays in every burst. */
|
||||
count: number | null;
|
||||
originals: boolean;
|
||||
/** Photos already queued or delivered to `targetId` in this event. */
|
||||
sent: number;
|
||||
}
|
||||
|
||||
export interface BurstAssignment {
|
||||
targetId: string;
|
||||
alsoTargetIds: string[];
|
||||
originals: boolean;
|
||||
/** Index into the burst's ranked frames. 0 is the best available. */
|
||||
rank: number;
|
||||
}
|
||||
|
||||
/** The configured exports, or one slot per legacy destination when that list is empty. */
|
||||
export function exportSlots(
|
||||
settings: Pick<AutopilotSettings, "deliverExports" | "deliverTargetIds" | "deliverTargetId" | "restTargetId">,
|
||||
): Omit<BurstExportSlot, "sent">[] {
|
||||
const configured = settings.deliverExports ?? [];
|
||||
if (configured.length) {
|
||||
const seen = new Set<string>();
|
||||
const slots: Omit<BurstExportSlot, "sent">[] = [];
|
||||
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;
|
||||
|
||||
@@ -4,13 +4,19 @@ import type { Db } from "../db.js";
|
||||
/** The destination photographers pick to send an under-19 national game to the FPA cloud. */
|
||||
export const CLOUD_M19_TARGET = "Cloud M19";
|
||||
|
||||
/** The same kind of destination for the women's under-17 side. */
|
||||
export const CLOUD_W17_TARGET = "Cloud W17";
|
||||
|
||||
/**
|
||||
* One Nextcloud destination per organisation that already delivers club games to cloud.photoreport.pt.
|
||||
* Same account and file name as that destination; the folder is Seleções Nacionais/M19.
|
||||
* Same account and file name as that destination; the folder is under Seleções Nacionais.
|
||||
* It does not send on arrival: the photographer chooses it for this game.
|
||||
* Returns how many destinations were created.
|
||||
*/
|
||||
export async function ensureCloudM19Target(db: Db): Promise<number> {
|
||||
async function ensureNationalCloudTarget(
|
||||
db: Db,
|
||||
target: { name: string; folder: string; fileName: string },
|
||||
): Promise<number> {
|
||||
const sources = await db.deliveryTarget.findMany({
|
||||
where: {
|
||||
kind: "NEXTCLOUD",
|
||||
@@ -31,21 +37,21 @@ export async function ensureCloudM19Target(db: Db): Promise<number> {
|
||||
if (seen.has(source.organizationId)) continue;
|
||||
seen.add(source.organizationId);
|
||||
const exists = await db.deliveryTarget.findUnique({
|
||||
where: { organizationId_name: { organizationId: source.organizationId, name: CLOUD_M19_TARGET } },
|
||||
where: { organizationId_name: { organizationId: source.organizationId, name: target.name } },
|
||||
select: { id: true },
|
||||
});
|
||||
if (exists) continue;
|
||||
await db.deliveryTarget.create({
|
||||
data: {
|
||||
organizationId: source.organizationId,
|
||||
name: CLOUD_M19_TARGET,
|
||||
name: target.name,
|
||||
kind: source.kind,
|
||||
baseUrl: source.baseUrl,
|
||||
username: source.username,
|
||||
secretEnc: source.secretEnc,
|
||||
hostFingerprint: source.hostFingerprint,
|
||||
folderTemplate: DESTINATION_EXAMPLES.fpaM19.folder,
|
||||
fileNameTemplate: source.fileNameTemplate || DESTINATION_EXAMPLES.fpaM19.fileName,
|
||||
folderTemplate: target.folder,
|
||||
fileNameTemplate: source.fileNameTemplate || target.fileName,
|
||||
longEdge: source.longEdge,
|
||||
jpegQuality: source.jpegQuality,
|
||||
sharpen: source.sharpen,
|
||||
@@ -64,3 +70,19 @@ export async function ensureCloudM19Target(db: Db): Promise<number> {
|
||||
}
|
||||
return created;
|
||||
}
|
||||
|
||||
export function ensureCloudM19Target(db: Db): Promise<number> {
|
||||
return ensureNationalCloudTarget(db, {
|
||||
name: CLOUD_M19_TARGET,
|
||||
folder: DESTINATION_EXAMPLES.fpaM19.folder,
|
||||
fileName: DESTINATION_EXAMPLES.fpaM19.fileName,
|
||||
});
|
||||
}
|
||||
|
||||
export function ensureCloudW17Target(db: Db): Promise<number> {
|
||||
return ensureNationalCloudTarget(db, {
|
||||
name: CLOUD_W17_TARGET,
|
||||
folder: DESTINATION_EXAMPLES.fpaW17.folder,
|
||||
fileName: DESTINATION_EXAMPLES.fpaW17.fileName,
|
||||
});
|
||||
}
|
||||
@@ -392,8 +392,13 @@ export async function registerDeliveryRoutes(
|
||||
where: { id: itemId, organizationId: orgId, status: "FAILED" },
|
||||
data: { status: "QUEUED", attempts: 0, nextAttemptAt: new Date(), lastError: null },
|
||||
});
|
||||
if (!result.count) throw notFound("failed_item_not_found");
|
||||
return toItemSummary(await db.deliveryItem.findUniqueOrThrow({ where: { id: itemId } }));
|
||||
if (result.count) return toItemSummary(await db.deliveryItem.findUniqueOrThrow({ where: { id: itemId } }));
|
||||
// Race: the item was no longer FAILED between the render and the retry (autopilot/queue worker
|
||||
// requeued, retried, or retracted it). The retry is idempotent — return the current state instead
|
||||
// of a 404, so the desktop does not unhandledrejection into the error loop (BIT-33418).
|
||||
const current = await db.deliveryItem.findUnique({ where: { id: itemId } });
|
||||
if (!current) throw notFound("item_not_found");
|
||||
return toItemSummary(current);
|
||||
});
|
||||
|
||||
/** ZeroZero: the event's game on the photo desk (chosen, or found by teams and time). */
|
||||
|
||||
@@ -17,6 +17,7 @@ describe("selectionKey", () => {
|
||||
expect(selectionKey(["Seleção Nacional sub-19 Masculina"])).toBe("m19");
|
||||
expect(selectionKey(["Portugal", "Espanha", "sub-19"])).toBe("m19");
|
||||
expect(selectionKey(["Seleção Nacional sub-19 feminina"])).toBe("w19");
|
||||
expect(selectionKey(["/FPA/Fotos/2026_2027/Seleções Nacionais/W17/20261127 - POR x ITA"])).toBe("w17");
|
||||
});
|
||||
|
||||
it("names no team for a club game, a gala, or a gathering", () => {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { ensureCloudM19Target } from "./delivery/fpa-m19.js";
|
||||
import { ensureCloudM19Target, ensureCloudW17Target } from "./delivery/fpa-m19.js";
|
||||
import { preferIpv4 } from "./lib/prefer-ipv4.js";
|
||||
import { buildApp, reporterFor } from "./app.js";
|
||||
import { loadConfig } from "./config.js";
|
||||
@@ -21,6 +21,7 @@ process.on("SIGTERM", () => void shutdown("SIGTERM"));
|
||||
process.on("SIGINT", () => void shutdown("SIGINT"));
|
||||
|
||||
ensureCloudM19Target(db).catch((err) => app.log.warn({ err }, "delivery: Cloud M19 profile not created"));
|
||||
ensureCloudW17Target(db).catch((err) => app.log.warn({ err }, "delivery: Cloud W17 profile not created"));
|
||||
|
||||
try {
|
||||
await app.listen({ port: config.PORT, host: "0.0.0.0" });
|
||||
|
||||
@@ -111,4 +111,40 @@ describe("EHF matches", () => {
|
||||
expect(seen.some((u) => u.includes("/men/2026-27/matches/"))).toBe(true);
|
||||
expect(seen.filter((u) => u.includes("GetMatches")).length).toBe(3);
|
||||
});
|
||||
|
||||
it("reads a national standing list with the hall, the group and the kick-off", async () => {
|
||||
const fetch: Fetch = async () => ({
|
||||
ok: true,
|
||||
status: 200,
|
||||
json: async () => ({
|
||||
matches: [
|
||||
{
|
||||
matchID: "202712010502014",
|
||||
venue: {
|
||||
date: { utc: "2026-11-27T19:00:00Z" },
|
||||
place: { hallName: "Pavilhão da Associação Atlética de Águas Santas", cityName: "Àguas Santas" },
|
||||
},
|
||||
homeTeam: { team: { nationAbbreviation: "POR" } },
|
||||
guestTeam: { team: { nationAbbreviation: "ITA" } },
|
||||
comp: { round: { name: "Qualification Tournaments" }, group: { name: "C" } },
|
||||
},
|
||||
],
|
||||
}),
|
||||
text: async () => "",
|
||||
arrayBuffer: async () => new ArrayBuffer(0),
|
||||
});
|
||||
const rows = await new EhfProvider(fetch, 0).euroCupMenMatches("comp", "139009");
|
||||
expect(rows).toEqual([
|
||||
{
|
||||
matchId: "202712010502014",
|
||||
startsAt: new Date("2026-11-27T19:00:00Z"),
|
||||
homeNation: "POR",
|
||||
awayNation: "ITA",
|
||||
venue: "Pavilhão da Associação Atlética de Águas Santas",
|
||||
city: "Àguas Santas",
|
||||
round: "Qualification Tournaments",
|
||||
group: "C",
|
||||
},
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -8,6 +8,8 @@ import {
|
||||
nationalNamesMatch,
|
||||
nationalSideFromTexts,
|
||||
nationalTeamExternalId,
|
||||
youthEuroRound,
|
||||
youthNationalTeam,
|
||||
} from "./national.js";
|
||||
|
||||
describe("national call-up", () => {
|
||||
@@ -76,4 +78,12 @@ describe("nationalTeamExternalId", () => {
|
||||
expect(nationalTeamExternalId("Roménia", "w18")).toBe("ROU-W18");
|
||||
expect(nationalCountryLabel("Switzerland")).toBe("Suíça");
|
||||
});
|
||||
|
||||
it("maps the W17 qualification nations onto youth sides", () => {
|
||||
expect(youthNationalTeam("POR", "w17")).toEqual({ externalId: "W17", name: "Portugal", abbreviation: "POR" });
|
||||
expect(youthNationalTeam("ITA", "w17")).toEqual({ externalId: "ITA-W17", name: "Itália", abbreviation: "ITA" });
|
||||
expect(youthNationalTeam("SLO", "w17")?.externalId).toBe("SLO-W17");
|
||||
expect(youthNationalTeam("FAR", "w17")?.name).toBe("Ilhas Faroé");
|
||||
expect(youthEuroRound("Qualification Tournaments", "C")).toBe("Qualificação C");
|
||||
});
|
||||
});
|
||||
@@ -171,6 +171,19 @@ export const EHF_EURO_CUP_MEN = {
|
||||
sheetWindowMs: 3 * 86400_000,
|
||||
} as const;
|
||||
|
||||
/**
|
||||
* Women's under-17 EHF EURO 2027 qualification (Águas Santas, 27–29 Nov 2026, and the same page
|
||||
* for the rest of that tournament). Same standing list and match sheet as the men's Euro Cup.
|
||||
*/
|
||||
export const EHF_W17_EURO = {
|
||||
competitionId: "DrPEklHxLKeDu_IajXOQvA",
|
||||
contentId: "139009",
|
||||
externalId: "W17-EURO",
|
||||
name: "W17 EHF EURO",
|
||||
gender: "F" as const,
|
||||
side: "w17",
|
||||
} as const;
|
||||
|
||||
const fold = (s: string) => s.normalize("NFD").replace(/[\u0300-\u036f]/g, "").toLowerCase().replace(/\s+/g, " ").trim();
|
||||
|
||||
/** Same athlete across FPA call-up spelling and EHF sheet ("Iturriza" / "Iturizza", "Miguel Oliveira" / "Miguel Moreira de Oliveira"). */
|
||||
@@ -231,6 +244,21 @@ export function nationalCountryLabel(raw: string): string | null {
|
||||
if (/^(fra|fr|franca|france)$/.test(n)) return "França";
|
||||
if (/^(ger|deu|alemanha|germany)$/.test(n)) return "Alemanha";
|
||||
if (/^(swe|suecia|sweden)$/.test(n)) return "Suécia";
|
||||
if (/^(ita|italy|italia)$/.test(n)) return "Itália";
|
||||
if (/^(slo|svn|slovenia|eslovenia)$/.test(n)) return "Eslovénia";
|
||||
if (/^(ukr|ukraine|ucrania)$/.test(n)) return "Ucrânia";
|
||||
if (/^(isl|iceland|islandia)$/.test(n)) return "Islândia";
|
||||
if (/^(far|fro|faroe|faroe islands|ilhas faroe)$/.test(n)) return "Ilhas Faroé";
|
||||
if (/^(tur|turkey|turkiye|turquia)$/.test(n)) return "Turquia";
|
||||
if (/^(isr|israel)$/.test(n)) return "Israel";
|
||||
if (/^(mkd|north macedonia|macedonia do norte)$/.test(n)) return "Macedónia do Norte";
|
||||
if (/^(ltu|lithuania|lituania)$/.test(n)) return "Lituânia";
|
||||
if (/^(kos|kosovo)$/.test(n)) return "Kosovo";
|
||||
if (/^(gre|greece|grecia)$/.test(n)) return "Grécia";
|
||||
if (/^(aut|austria)$/.test(n)) return "Áustria";
|
||||
if (/^(pol|poland|polonia)$/.test(n)) return "Polónia";
|
||||
if (/^(fin|finland|finlandia)$/.test(n)) return "Finlândia";
|
||||
if (/^(lux|luxembourg|luxemburgo)$/.test(n)) return "Luxemburgo";
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -248,6 +276,15 @@ const YOUTH_CODE: Record<string, string> = {
|
||||
hungria: "HUN",
|
||||
noruega: "NOR",
|
||||
italia: "ITA",
|
||||
ucrania: "UKR",
|
||||
"ilhas faroe": "FAR",
|
||||
turquia: "TUR",
|
||||
israel: "ISR",
|
||||
"macedonia do norte": "MKD",
|
||||
lituania: "LTU",
|
||||
kosovo: "KOS",
|
||||
grecia: "GRE",
|
||||
luxemburgo: "LUX",
|
||||
polonia: "POL",
|
||||
chequia: "CZE",
|
||||
montenegro: "MNE",
|
||||
@@ -261,6 +298,33 @@ const YOUTH_CODE: Record<string, string> = {
|
||||
"paises baixos": "NED",
|
||||
};
|
||||
|
||||
/**
|
||||
* A youth national side from an EHF nation code or an English/Portuguese country name.
|
||||
* Portugal's under-17 women are "W17"; Italy is "ITA-W17".
|
||||
*/
|
||||
export function youthNationalTeam(
|
||||
nation: string | null | undefined,
|
||||
side: string,
|
||||
): { externalId: string; name: string; abbreviation: string } | null {
|
||||
if (!nation) return null;
|
||||
const name = nationalCountryLabel(nation);
|
||||
if (!name) return null;
|
||||
const externalId = nationalTeamExternalId(name, side);
|
||||
if (!externalId) return null;
|
||||
const abbreviation = YOUTH_CODE[fold(name)];
|
||||
if (!abbreviation) return null;
|
||||
return { externalId, name, abbreviation };
|
||||
}
|
||||
|
||||
/** "Qualification Tournaments" + group "C" is what the picker shows as "Qualificação C". */
|
||||
export function youthEuroRound(round: string | null, group: string | null): string | null {
|
||||
let name = round;
|
||||
if (name === "Qualification Tournaments") name = "Qualificação";
|
||||
if (name && group) return `${name} ${group}`;
|
||||
if (name) return name;
|
||||
return group;
|
||||
}
|
||||
|
||||
/** Which national sports team externalId fits this country + side key. */
|
||||
export function nationalTeamExternalId(country: string, side: string): string | null {
|
||||
const label = nationalCountryLabel(country) ?? country;
|
||||
|
||||
@@ -1538,7 +1538,7 @@ export class EhfProvider {
|
||||
async euroCupMenMatches(
|
||||
competitionId: string,
|
||||
contentId: string,
|
||||
): Promise<{ matchId: string; startsAt: Date; homeNation: string | null; awayNation: string | null; venue: string | null; city: string | null }[]> {
|
||||
): Promise<{ matchId: string; startsAt: Date; homeNation: string | null; awayNation: string | null; venue: string | null; city: string | null; round: string | null; group: string | null }[]> {
|
||||
const data = await get(
|
||||
this.fetcher,
|
||||
`https://www.eurohandball.com/umbraco/api/competitionapi/GetStandingMatches?contentId=${encodeURIComponent(contentId)}&competitionId=${encodeURIComponent(competitionId)}`,
|
||||
@@ -1546,7 +1546,7 @@ export class EhfProvider {
|
||||
"json",
|
||||
);
|
||||
const rows = Array.isArray(obj(data).matches) ? (obj(data).matches as unknown[]) : [];
|
||||
const out: { matchId: string; startsAt: Date; homeNation: string | null; awayNation: string | null; venue: string | null; city: string | null }[] = [];
|
||||
const out: { matchId: string; startsAt: Date; homeNation: string | null; awayNation: string | null; venue: string | null; city: string | null; round: string | null; group: string | null }[] = [];
|
||||
for (const row of rows) {
|
||||
const m = obj(row);
|
||||
const matchId = str(m.matchID);
|
||||
@@ -1557,6 +1557,7 @@ export class EhfProvider {
|
||||
if (Number.isNaN(at.getTime())) continue;
|
||||
const hall = str(place.hallName);
|
||||
const city = str(place.cityName);
|
||||
const comp = obj(m.comp);
|
||||
out.push({
|
||||
matchId,
|
||||
startsAt: at,
|
||||
@@ -1564,6 +1565,8 @@ export class EhfProvider {
|
||||
awayNation: str(obj(obj(m.guestTeam).team).nationAbbreviation) ?? str(obj(obj(m.guestTeam).team).countryAbbreviation),
|
||||
venue: hall,
|
||||
city,
|
||||
round: str(obj(comp.round).name),
|
||||
group: str(obj(comp.group).name),
|
||||
});
|
||||
}
|
||||
return out;
|
||||
|
||||
@@ -17,6 +17,7 @@ import { type ClubCandidate, type JogaClient, chooseClub, jogaCompetitionId, jog
|
||||
import { sameListedPerson } from "./people.js";
|
||||
import {
|
||||
EHF_EURO_CUP_MEN,
|
||||
EHF_W17_EURO,
|
||||
ESP_M19_2026,
|
||||
M19_POR_2026,
|
||||
NATIONAL_SIDES,
|
||||
@@ -24,6 +25,8 @@ import {
|
||||
SUI_EURO_CUP_2026,
|
||||
nationToSnamTeam,
|
||||
nationalNamesMatch,
|
||||
youthEuroRound,
|
||||
youthNationalTeam,
|
||||
type NationalCallUp,
|
||||
} from "./national.js";
|
||||
import { tallyOf, tallySquadPhotos } from "./squadPhotos.js";
|
||||
@@ -615,6 +618,7 @@ export class SportsService {
|
||||
const espHave = await this.deps.db.sportsPlayer.count({ where: { teamId: espM19Id, season, goneAt: null } });
|
||||
if (espHave === 0) result.players += await this.saveNationalCallUp(espM19Id, season, ESP_M19_2026);
|
||||
await this.applyEuroCupSheets(now, season, result);
|
||||
await this.applyYouthEuros(now, season, result);
|
||||
// People + reference faces: only when an event syncs these teams (`syncEventSquads`), not on every FPA refresh.
|
||||
await this.fillNationalPhotos(snamId, season);
|
||||
await this.fillNationalPhotos(suiId, season);
|
||||
@@ -687,6 +691,20 @@ export class SportsService {
|
||||
this.deps.log.info({ side: camp.side, players: camp.players.length, source: camp.sourceUrl }, "sports: youth call-up");
|
||||
}
|
||||
for (const game of camp.games) {
|
||||
if (camp.side === EHF_W17_EURO.side) {
|
||||
const homeTeamId = await this.upsertTeam("FPA", {
|
||||
externalId: game.homeExternalId,
|
||||
name: game.homeCountry,
|
||||
abbreviation: youthAbbrev(game.homeExternalId, camp.side),
|
||||
});
|
||||
const awayTeamId = await this.upsertTeam("FPA", {
|
||||
externalId: game.awayExternalId,
|
||||
name: game.awayCountry,
|
||||
abbreviation: youthAbbrev(game.awayExternalId, camp.side),
|
||||
});
|
||||
const listed = await this.hasOfficialYouthFixture(homeTeamId, awayTeamId, game.startsAt, EHF_W17_EURO.externalId);
|
||||
if (listed) continue;
|
||||
}
|
||||
const comp = await this.youthCompetition(season, camp.side);
|
||||
result.fixtures += await this.saveFixture(comp, "FPA", {
|
||||
externalId: game.externalId,
|
||||
@@ -806,6 +824,149 @@ export class SportsService {
|
||||
}
|
||||
}
|
||||
|
||||
/** The FPA camp and the EHF page can disagree by an hour and still be the same match. */
|
||||
private sameKickoff(startsAt: Date) {
|
||||
const slackMs = 2 * 60 * 60 * 1000;
|
||||
return {
|
||||
gte: new Date(startsAt.getTime() - slackMs),
|
||||
lte: new Date(startsAt.getTime() + slackMs),
|
||||
};
|
||||
}
|
||||
|
||||
/** The official under-17 EURO already has this kick-off, so the camp must not add it again as a friendly. */
|
||||
private async hasOfficialYouthFixture(homeTeamId: string, awayTeamId: string, startsAt: Date, competitionExternalId: string): Promise<boolean> {
|
||||
const row = await this.deps.db.sportsFixture.findFirst({
|
||||
where: {
|
||||
homeTeamId,
|
||||
awayTeamId,
|
||||
startsAt: this.sameKickoff(startsAt),
|
||||
competition: { externalId: competitionExternalId },
|
||||
},
|
||||
select: { id: true },
|
||||
});
|
||||
return row !== null;
|
||||
}
|
||||
|
||||
/**
|
||||
* The FPA post lists the same under-17 game as a friendly ("Sub-17 feminina"). One match, one row.
|
||||
* An event already opened on the friendly keeps that row when it can become the official one.
|
||||
*/
|
||||
private async foldYouthFriendly(
|
||||
officialCompetitionId: string,
|
||||
officialExternalId: string,
|
||||
homeTeamId: string,
|
||||
awayTeamId: string,
|
||||
startsAt: Date,
|
||||
): Promise<void> {
|
||||
const friendly = await this.deps.db.sportsFixture.findFirst({
|
||||
where: {
|
||||
homeTeamId,
|
||||
awayTeamId,
|
||||
startsAt: this.sameKickoff(startsAt),
|
||||
competition: { provider: "FPA", externalId: { endsWith: "-AMIG" } },
|
||||
},
|
||||
select: { id: true },
|
||||
});
|
||||
if (!friendly) return;
|
||||
const official = await this.deps.db.sportsFixture.findUnique({
|
||||
where: { competitionId_externalId: { competitionId: officialCompetitionId, externalId: officialExternalId } },
|
||||
select: { id: true },
|
||||
});
|
||||
if (!official) {
|
||||
await this.deps.db.sportsFixture.update({
|
||||
where: { id: friendly.id },
|
||||
data: { competitionId: officialCompetitionId, externalId: officialExternalId },
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (official.id === friendly.id) return;
|
||||
await this.deps.db.event.updateMany({
|
||||
where: { fixtureId: friendly.id },
|
||||
data: { fixtureId: official.id },
|
||||
});
|
||||
await this.deps.db.sportsFixture.delete({ where: { id: friendly.id } });
|
||||
}
|
||||
|
||||
/**
|
||||
* Women's under-17 EHF EURO qualification on eurohandball.com. The whole tournament is stored so the
|
||||
* picker can open Portugal–Italy (and the rest of the weekend) before the nominated sheet is published.
|
||||
* The sheet, when it is out, writes shirt numbers and headshots onto W17 / ITA-W17 / …
|
||||
*/
|
||||
private async applyYouthEuros(now: Date, season: string, result: RefreshResult): Promise<void> {
|
||||
const { db, log } = this.deps;
|
||||
let matches: Awaited<ReturnType<EhfProvider["euroCupMenMatches"]>>;
|
||||
try {
|
||||
matches = await this.ehf.euroCupMenMatches(EHF_W17_EURO.competitionId, EHF_W17_EURO.contentId);
|
||||
} catch (err) {
|
||||
result.errors.push(`ehf w17: ${(err as Error).message}`);
|
||||
return;
|
||||
}
|
||||
const listed = matches.flatMap((m) => {
|
||||
const home = youthNationalTeam(m.homeNation, EHF_W17_EURO.side);
|
||||
const away = youthNationalTeam(m.awayNation, EHF_W17_EURO.side);
|
||||
if (!home || !away) return [];
|
||||
return [{ match: m, home, away }];
|
||||
});
|
||||
if (!listed.length) return;
|
||||
const comp = await db.sportsCompetition.upsert({
|
||||
where: { provider_externalId: { provider: "FPA", externalId: EHF_W17_EURO.externalId } },
|
||||
create: {
|
||||
provider: "FPA",
|
||||
externalId: EHF_W17_EURO.externalId,
|
||||
sport: "andebol",
|
||||
name: EHF_W17_EURO.name,
|
||||
gender: EHF_W17_EURO.gender,
|
||||
season,
|
||||
},
|
||||
update: { name: EHF_W17_EURO.name, gender: EHF_W17_EURO.gender, season },
|
||||
});
|
||||
for (const row of listed) {
|
||||
const homeTeamId = await this.upsertTeam("FPA", row.home);
|
||||
const awayTeamId = await this.upsertTeam("FPA", row.away);
|
||||
await this.foldYouthFriendly(comp.id, row.match.matchId, homeTeamId, awayTeamId, row.match.startsAt);
|
||||
result.fixtures += await this.saveFixture(comp, "FPA", {
|
||||
externalId: row.match.matchId,
|
||||
competition: EHF_W17_EURO.externalId,
|
||||
season,
|
||||
home: row.home,
|
||||
away: row.away,
|
||||
startsAt: row.match.startsAt,
|
||||
timeKnown: true,
|
||||
round: youthEuroRound(row.match.round, row.match.group),
|
||||
venue: row.match.venue,
|
||||
city: row.match.city,
|
||||
});
|
||||
}
|
||||
const due = listed.filter((row) => Math.abs(row.match.startsAt.getTime() - now.getTime()) <= EHF_EURO_CUP_MEN.sheetWindowMs);
|
||||
for (const row of due) {
|
||||
if (this.deps.ehfDelayMs) await new Promise((r) => setTimeout(r, this.deps.ehfDelayMs));
|
||||
let sheet: Awaited<ReturnType<EhfProvider["nationalSheet"]>>;
|
||||
try {
|
||||
sheet = await this.ehf.nationalSheet(row.match.matchId);
|
||||
} catch (err) {
|
||||
result.errors.push(`ehf w17 sheet ${row.match.matchId}: ${(err as Error).message}`);
|
||||
continue;
|
||||
}
|
||||
if (!sheet) continue;
|
||||
const sides = [
|
||||
{ nation: sheet.homeNation, players: sheet.home },
|
||||
{ nation: sheet.awayNation, players: sheet.away },
|
||||
];
|
||||
for (const side of sides) {
|
||||
const team = youthNationalTeam(side.nation, EHF_W17_EURO.side);
|
||||
if (!team) continue;
|
||||
const teamId = await this.upsertTeam("FPA", team);
|
||||
const field = side.players.filter((p) => p.position !== "Equipa técnica");
|
||||
result.players += await this.mergeNationalSheet(teamId, season, field, []);
|
||||
await this.fillNationalPhotos(teamId, season);
|
||||
}
|
||||
log.info(
|
||||
{ matchId: row.match.matchId, home: sheet.homeNation, away: sheet.awayNation, players: sheet.home.length + sheet.away.length },
|
||||
"sports: w17 sheet",
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Write EHF sheet players onto a national team. For Portugal, keep the CIPA from the FPA call-up when the
|
||||
* name matches; still take the shirt number and headshot from the sheet.
|
||||
|
||||
@@ -16,7 +16,7 @@ import { RenderPool, RenderProcess } from "./develop/engine.js";
|
||||
import { DevelopService, RenderWorker } from "./develop/service.js";
|
||||
import { FaceProcess, GrowingFacePool } from "./faces/process.js";
|
||||
import { AutopilotService, AutopilotWorker } from "./autopilot/service.js";
|
||||
import { ensureCloudM19Target } from "./delivery/fpa-m19.js";
|
||||
import { ensureCloudM19Target, ensureCloudW17Target } from "./delivery/fpa-m19.js";
|
||||
import { jogaClientFromConfig } from "./sports/joga.js";
|
||||
import { SportsService, SportsWorker } from "./sports/service.js";
|
||||
import { ArchiveService, ArchiveWorker, localDirs } from "./archive/service.js";
|
||||
@@ -177,6 +177,7 @@ const sports = config.SPORTS_SYNC === "on"
|
||||
: undefined;
|
||||
|
||||
ensureCloudM19Target(db).catch((err) => log.warn({ err }, "delivery: Cloud M19 profile not created"));
|
||||
ensureCloudW17Target(db).catch((err) => log.warn({ err }, "delivery: Cloud W17 profile not created"));
|
||||
scanner.start();
|
||||
if (secrets) archive.start();
|
||||
autopilot.start();
|
||||
|
||||
@@ -851,6 +851,32 @@ describe("delivery", () => {
|
||||
expect(broadcaster.sent.filter((s) => s.message.type === "delivery.updated").map((s) => (s.message as { item: { status: string } }).item.status)).toEqual(["QUEUED", "QUEUED", "FAILED", "DONE"]);
|
||||
});
|
||||
|
||||
it("retry is idempotent when the item leaves FAILED between render and click (BIT-33418)", async () => {
|
||||
const { orgId, token, target } = await setup();
|
||||
const id = await photo("race.jpg", "2026:09:23 21:10:00");
|
||||
await delivery.enqueue({ organizationId: orgId, targetId: target.id, photoIds: [id], again: false, requestedById: (await ctx.db.user.findFirstOrThrow()).id });
|
||||
const [claimed] = await delivery.claim(5);
|
||||
nc.status = 401;
|
||||
expect(await delivery.process(claimed!)).toMatchObject({ status: "FAILED", attempts: 1 });
|
||||
nc.status = undefined;
|
||||
|
||||
// Between the desktop rendering the FAILED row and the user clicking "Repetir", the queue worker
|
||||
// requeued the item (autopilot, queueEdited, queueOrphanRetracts, …) so it is no longer FAILED.
|
||||
const itemId = (await ctx.db.deliveryItem.findFirstOrThrow({ where: { photoId: id, targetId: target.id } })).id;
|
||||
await ctx.db.deliveryItem.update({ where: { id: itemId }, data: { status: "QUEUED", attempts: 0, nextAttemptAt: new Date(), lastError: null } });
|
||||
|
||||
// The retry must not 404 — it returns the current state, so the desktop's promise resolves and no
|
||||
// unhandledrejection reaches the error hub.
|
||||
const retry = await ctx.app.inject({ method: "POST", url: `/v1/orgs/${orgId}/deliveries/${itemId}/retry`, headers: bearer(token) });
|
||||
expect(retry.statusCode).toBe(200);
|
||||
expect(retry.json()).toMatchObject({ id: itemId, status: "QUEUED", attempts: 0 });
|
||||
|
||||
// A truly missing item still 404s.
|
||||
const ghost = await ctx.app.inject({ method: "POST", url: `/v1/orgs/${orgId}/deliveries/00000000-0000-4000-8000-000000000000/retry`, headers: bearer(token) });
|
||||
expect(ghost.statusCode).toBe(404);
|
||||
expect(ghost.json()).toMatchObject({ error: "item_not_found" });
|
||||
});
|
||||
|
||||
it("writes long venues whole in IIM and XMP, flagged as UTF-8", async () => {
|
||||
const src = path.join(dir, "src.jpg");
|
||||
await writeFile(src, await sharp({ create: { width: 300, height: 200, channels: 3, background: "#123456" } }).jpeg().toBuffer());
|
||||
|
||||
@@ -733,6 +733,28 @@ describe("sports data service", () => {
|
||||
log: quiet,
|
||||
fetch: (async (url, init) => {
|
||||
const u = String(url);
|
||||
if (u.includes("GetStandingMatches") && u.includes("contentId=139009"))
|
||||
return {
|
||||
ok: true,
|
||||
status: 200,
|
||||
json: async () => ({
|
||||
matches: [
|
||||
{
|
||||
matchID: "202712010502014",
|
||||
venue: {
|
||||
date: { utc: kick.toISOString() },
|
||||
place: { hallName: "Pavilhão da Associação Atlética de Águas Santas", cityName: "Àguas Santas" },
|
||||
},
|
||||
homeTeam: { team: { nationAbbreviation: "POR" } },
|
||||
guestTeam: { team: { nationAbbreviation: "ITA" } },
|
||||
comp: { round: { name: "Qualification Tournaments" }, group: { name: "C" } },
|
||||
},
|
||||
],
|
||||
rounds: [],
|
||||
}),
|
||||
text: async () => "",
|
||||
arrayBuffer: async () => new ArrayBuffer(0),
|
||||
};
|
||||
if (u.includes("GetStandingMatches"))
|
||||
return {
|
||||
ok: true,
|
||||
@@ -751,6 +773,45 @@ describe("sports data service", () => {
|
||||
text: async () => "",
|
||||
arrayBuffer: async () => new ArrayBuffer(0),
|
||||
};
|
||||
if (u.includes("GetMatchDetails") && u.includes("202712010502014"))
|
||||
return {
|
||||
ok: true,
|
||||
status: 200,
|
||||
json: async () => ({
|
||||
matchDetails: {
|
||||
details: {
|
||||
homeTeam: {
|
||||
team: { nationAbbreviation: "POR" },
|
||||
players: [
|
||||
{
|
||||
id: "ehf-w17-costa",
|
||||
shirtNumber: "7",
|
||||
playingPosition: "Centre Back",
|
||||
person: { firstName: "Maria", lastName: "Costa", nationAbbreviation: "POR" },
|
||||
newPhoto: { w512: "https://res.ehf.eu/photo/w17-costa.jpg" },
|
||||
},
|
||||
],
|
||||
officials: [],
|
||||
},
|
||||
guestTeam: {
|
||||
team: { nationAbbreviation: "ITA" },
|
||||
players: [
|
||||
{
|
||||
id: "ehf-w17-rossi",
|
||||
shirtNumber: "9",
|
||||
playingPosition: "Left Wing",
|
||||
person: { firstName: "Giulia", lastName: "Rossi", nationAbbreviation: "ITA" },
|
||||
newPhoto: { w512: "https://res.ehf.eu/photo/w17-rossi.jpg" },
|
||||
},
|
||||
],
|
||||
officials: [],
|
||||
},
|
||||
},
|
||||
},
|
||||
}),
|
||||
text: async () => "",
|
||||
arrayBuffer: async () => new ArrayBuffer(0),
|
||||
};
|
||||
if (u.includes("GetMatchDetails") && u.includes("202811130101002"))
|
||||
return {
|
||||
ok: true,
|
||||
@@ -848,6 +909,85 @@ describe("sports data service", () => {
|
||||
expect(friendly?.startsAt.toISOString()).toBe("2026-11-05T20:00:00.000Z");
|
||||
expect(friendly?.venue).toBe("Pavilhão Municipal Fernando Lima");
|
||||
expect(friendly?.city).toBe("Caminha");
|
||||
const w17 = await ctx.db.sportsFixture.findFirst({
|
||||
where: { externalId: "202712010502014" },
|
||||
include: { homeTeam: true, awayTeam: true, competition: true },
|
||||
});
|
||||
expect(w17?.competition.name).toBe("W17 EHF EURO");
|
||||
expect(w17?.competition.gender).toBe("F");
|
||||
expect(w17?.round).toBe("Qualificação C");
|
||||
expect(w17?.venue).toBe("Pavilhão da Associação Atlética de Águas Santas");
|
||||
expect(w17?.city).toBe("Àguas Santas");
|
||||
expect(w17?.homeTeam.externalId).toBe("W17");
|
||||
expect(w17?.homeTeam.name).toBe("Portugal");
|
||||
expect(w17?.awayTeam.externalId).toBe("ITA-W17");
|
||||
expect(w17?.awayTeam.name).toBe("Itália");
|
||||
expect(await ctx.db.sportsPlayer.findFirstOrThrow({ where: { teamId: w17!.homeTeam.id, name: "Maria Costa" } })).toMatchObject({
|
||||
number: "7",
|
||||
photoUrl: "https://res.ehf.eu/photo/w17-costa.jpg",
|
||||
});
|
||||
expect(await ctx.db.sportsPlayer.findFirstOrThrow({ where: { teamId: w17!.awayTeam.id, name: "Giulia Rossi" } })).toMatchObject({
|
||||
number: "9",
|
||||
externalId: "ehf-w17-rossi",
|
||||
});
|
||||
|
||||
const { org } = await seedUser(ctx.db, "[email protected]", { org: "w17dup", role: "OWNER" });
|
||||
const friendlyComp = await ctx.db.sportsCompetition.create({
|
||||
data: { provider: "FPA", externalId: "W17-AMIG", sport: "andebol", name: "Sub-17 feminina", gender: "F", season: w17!.season },
|
||||
});
|
||||
const duplicate = await ctx.db.sportsFixture.create({
|
||||
data: {
|
||||
competitionId: friendlyComp.id,
|
||||
externalId: "w17-por-ita-20261127",
|
||||
season: w17!.season,
|
||||
homeTeamId: w17!.homeTeam.id,
|
||||
awayTeamId: w17!.awayTeam.id,
|
||||
startsAt: w17!.startsAt,
|
||||
timeKnown: true,
|
||||
round: "Particular",
|
||||
},
|
||||
});
|
||||
const opened = await ctx.db.event.create({
|
||||
data: {
|
||||
organizationId: org!.id,
|
||||
home: "Portugal",
|
||||
away: "Itália",
|
||||
startsAt: w17!.startsAt,
|
||||
ingestFrom: w17!.startsAt,
|
||||
ingestUntil: w17!.startsAt,
|
||||
iptcTemplate: {},
|
||||
fixtureId: duplicate.id,
|
||||
},
|
||||
});
|
||||
await sports.syncNationalCallUps(kick);
|
||||
const paired = await ctx.db.sportsFixture.findMany({
|
||||
where: { homeTeamId: w17!.homeTeam.id, awayTeamId: w17!.awayTeam.id, startsAt: w17!.startsAt },
|
||||
});
|
||||
expect(paired.map((row) => row.externalId)).toEqual(["202712010502014"]);
|
||||
expect((await ctx.db.event.findUniqueOrThrow({ where: { id: opened.id } })).fixtureId).toBe(w17!.id);
|
||||
|
||||
await ctx.db.sportsFixture.delete({ where: { id: w17!.id } });
|
||||
const campOnly = await ctx.db.sportsFixture.create({
|
||||
data: {
|
||||
competitionId: friendlyComp.id,
|
||||
externalId: "w17-por-ita-20261127",
|
||||
season: w17!.season,
|
||||
homeTeamId: w17!.homeTeam.id,
|
||||
awayTeamId: w17!.awayTeam.id,
|
||||
startsAt: w17!.startsAt,
|
||||
timeKnown: true,
|
||||
round: "Particular",
|
||||
},
|
||||
});
|
||||
await ctx.db.event.update({ where: { id: opened.id }, data: { fixtureId: campOnly.id } });
|
||||
await sports.syncNationalCallUps(kick);
|
||||
const adopted = await ctx.db.sportsFixture.findMany({
|
||||
where: { homeTeamId: w17!.homeTeam.id, awayTeamId: w17!.awayTeam.id, startsAt: w17!.startsAt },
|
||||
include: { competition: true },
|
||||
});
|
||||
expect(adopted).toHaveLength(1);
|
||||
expect(adopted[0]).toMatchObject({ id: campOnly.id, externalId: "202712010502014", competition: { name: "W17 EHF EURO" } });
|
||||
expect((await ctx.db.event.findUniqueOrThrow({ where: { id: opened.id } })).fixtureId).toBe(campOnly.id);
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -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> = {}): 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] });
|
||||
|
||||
@@ -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",
|
||||
@@ -713,7 +721,7 @@ export const t = {
|
||||
startsAt: "Início",
|
||||
photographers: "Fotógrafos",
|
||||
pickMatch: "Escolher o jogo",
|
||||
pickMatchHelp: "Jogos da Liga Portugal, FPF, FPA, EHF Euro Cup (seleções) e UEFA (Champions, Liga Europa, Conference, Champions feminina e de futsal) dos próximos dias (ao pesquisar, também os dos últimos 10 dias). Preenche o evento e junta os plantéis às pessoas. As fotos de 2 h antes até 4 h depois do apito vão para este evento.",
|
||||
pickMatchHelp: "Jogos da Liga Portugal, FPF, FPA, EHF Euro Cup (seleções), W17 EHF EURO (qualificação de sub-17 feminina) e UEFA (Champions, Liga Europa, Conference, Champions feminina e de futsal) dos próximos dias (ao pesquisar, também os dos últimos 10 dias). Preenche o evento e junta os plantéis às pessoas. As fotos de 2 h antes até 4 h depois do apito vão para este evento.",
|
||||
squadFromMatch: "Usar o plantel de um jogo",
|
||||
squadFromMatchHelp: "Treino ou sessão: fica com os jogadores desse jogo, sem ser o jogo (legenda e hora são as tuas).",
|
||||
searchMatch: "Equipa, competição ou pavilhão",
|
||||
|
||||
@@ -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<string>();
|
||||
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 (
|
||||
<div className="space-y-2">
|
||||
<p className="text-faint">{L.exportHelp}</p>
|
||||
{rows.map((row, index) => {
|
||||
const also = row.alsoTargetIds[0] ?? "";
|
||||
return (
|
||||
<div key={`${row.targetId}-${index}`} className="space-y-1 border border-line p-1.5">
|
||||
<label className="flex items-center justify-between gap-2">
|
||||
<span>{index + 1}</span>
|
||||
<span className="flex items-center gap-1">
|
||||
<select
|
||||
className="h-6 max-w-[160px] border border-black bg-cell px-1"
|
||||
disabled={!props.canEdit}
|
||||
value={row.targetId}
|
||||
onChange={(e) => {
|
||||
const value = e.target.value;
|
||||
if (!value) return;
|
||||
const alsoIds = row.alsoTargetIds.filter((id) => id !== value);
|
||||
update(index, { ...row, targetId: value, alsoTargetIds: alsoIds });
|
||||
}}
|
||||
>
|
||||
{props.targets.map((target) => {
|
||||
if (used.has(target.id) && target.id !== row.targetId && target.id !== also) return null;
|
||||
return (
|
||||
<option key={target.id} value={target.id}>
|
||||
{target.name}
|
||||
</option>
|
||||
);
|
||||
})}
|
||||
</select>
|
||||
<button type="button" className="text-faint hover:text-ink" disabled={!props.canEdit} onClick={() => remove(index)}>
|
||||
{L.exportRemove}
|
||||
</button>
|
||||
</span>
|
||||
</label>
|
||||
<label className="flex items-center justify-between gap-2">
|
||||
<span className="text-faint">{L.exportAlso}</span>
|
||||
<select
|
||||
className="h-6 max-w-[160px] border border-black bg-cell px-1"
|
||||
disabled={!props.canEdit}
|
||||
value={also}
|
||||
onChange={(e) => {
|
||||
const value = e.target.value;
|
||||
if (!value) update(index, { ...row, alsoTargetIds: [] });
|
||||
else update(index, { ...row, alsoTargetIds: [value] });
|
||||
}}
|
||||
>
|
||||
<option value="">{L.noDelivery}</option>
|
||||
{props.targets.map((target) => {
|
||||
if (target.id === row.targetId) return null;
|
||||
if (used.has(target.id) && target.id !== also) return null;
|
||||
return (
|
||||
<option key={target.id} value={target.id}>
|
||||
{target.name}
|
||||
</option>
|
||||
);
|
||||
})}
|
||||
</select>
|
||||
</label>
|
||||
<label className="flex items-center justify-between gap-2">
|
||||
<span className="text-faint">{L.exportCount}</span>
|
||||
<input
|
||||
type="number"
|
||||
min={1}
|
||||
max={2000}
|
||||
disabled={!props.canEdit}
|
||||
value={row.count ?? ""}
|
||||
placeholder="—"
|
||||
onChange={(e) => {
|
||||
const raw = e.target.value.trim();
|
||||
let count: number | null = null;
|
||||
if (raw) count = Math.max(1, Math.min(2000, Number(raw) || 1));
|
||||
update(index, { ...row, count });
|
||||
}}
|
||||
className="h-6 w-20 border border-black bg-[#161617] px-1 text-ink"
|
||||
/>
|
||||
</label>
|
||||
<label className="flex items-center gap-2">
|
||||
<input
|
||||
type="checkbox"
|
||||
disabled={!props.canEdit}
|
||||
checked={row.originals}
|
||||
onChange={(e) => update(index, { ...row, originals: e.target.checked })}
|
||||
/>
|
||||
<span>{L.exportOriginals}</span>
|
||||
</label>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
<button type="button" className="pr-quiet" disabled={!props.canEdit || used.size >= props.targets.length} onClick={add}>
|
||||
{L.exportAdd}
|
||||
</button>
|
||||
<p className="text-faint">{L.exportPlayers}</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 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}
|
||||
</button>
|
||||
{open && (
|
||||
<div className="absolute right-0 top-7 z-30 w-[360px] space-y-3 border border-black bg-panel p-3 text-[12px] shadow-xl" role="dialog" aria-label={L.button}>
|
||||
<div className="absolute right-0 top-7 z-30 w-[420px] space-y-3 border border-black bg-panel p-3 text-[12px] shadow-xl" role="dialog" aria-label={L.button}>
|
||||
<label className="flex items-center justify-between gap-2">
|
||||
<span className="font-semibold uppercase tracking-wide text-ink">{L.button}</span>
|
||||
<input type="checkbox" disabled={!props.canEdit} checked={s.enabled} onChange={(e) => void save({ ...s, enabled: e.target.checked })} aria-label={L.enable} />
|
||||
@@ -110,17 +260,22 @@ export function AutopilotButton(props: {
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
<label className="flex items-center justify-between gap-2">
|
||||
<span>{L.deliver}</span>
|
||||
<select className="h-6 max-w-[180px] border border-black bg-cell px-1" disabled={!s.enabled || !props.canEdit} value={s.deliverTargetId ?? ""} onChange={(e) => void save({ ...s, deliverTargetId: e.target.value || null })}>
|
||||
<option value="">{L.noDelivery}</option>
|
||||
{props.targets.map((x) => (
|
||||
<option key={x.id} value={x.id}>
|
||||
{x.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
{s.selection === "bursts" && (
|
||||
<BurstExports settings={s} targets={props.targets} canEdit={props.canEdit && s.enabled} onChange={(next) => void save(next)} />
|
||||
)}
|
||||
{s.selection !== "bursts" && (
|
||||
<label className="flex items-center justify-between gap-2">
|
||||
<span>{L.deliver}</span>
|
||||
<select className="h-6 max-w-[180px] border border-black bg-cell px-1" disabled={!s.enabled || !props.canEdit} value={s.deliverTargetId ?? ""} onChange={(e) => void save({ ...s, deliverTargetId: e.target.value || null })}>
|
||||
<option value="">{L.noDelivery}</option>
|
||||
{props.targets.map((x) => (
|
||||
<option key={x.id} value={x.id}>
|
||||
{x.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
)}
|
||||
<label className="flex items-center justify-between gap-2">
|
||||
<span>{L.selection}</span>
|
||||
<select className="h-6 max-w-[180px] border border-black bg-cell px-1" disabled={!s.enabled || !props.canEdit} value={s.selection} onChange={(e) => void save({ ...s, selection: e.target.value as AutopilotSettings["selection"] })}>
|
||||
|
||||
@@ -3,7 +3,7 @@ import type { EventSummary } from "@photoreport/sdk";
|
||||
import { useAuth } from "../auth.js";
|
||||
import { planLocalAutopilot } from "../offline/autopilot.js";
|
||||
import { cache } from "../offline/cache.js";
|
||||
import { eventForArrival, exifDateTime, exifLens, lisbonDay, lisbonInstant, localPhoto, localPhotos } from "../offline/local.js";
|
||||
import { eventForArrival, exifDateTime, exifLens, lisbonInstant, localPhoto, localPhotos } from "../offline/local.js";
|
||||
import { localId, offlineQueue } from "../offline/queue.js";
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
import { t } from "../i18n.js";
|
||||
@@ -89,12 +89,6 @@ type Add = (
|
||||
|
||||
export const eventLabel = (e: Pick<EventSummary, "title" | "home" | "away">) => e.title || [e.home, e.away].filter(Boolean).join(" x ");
|
||||
|
||||
/** The pin's own ingest window, when the agenda no longer lists that event. */
|
||||
export function pinWindow(to: FtpTarget | null): { ingestFrom: string; ingestUntil: string } | null {
|
||||
if (!to?.ingestFrom || !to.ingestUntil) return null;
|
||||
return { ingestFrom: to.ingestFrom, ingestUntil: to.ingestUntil };
|
||||
}
|
||||
|
||||
function savedTarget(): FtpTarget | null {
|
||||
try {
|
||||
const v = JSON.parse(prefs.get("ftp.target") ?? "null") as FtpTarget | null;
|
||||
@@ -183,7 +177,7 @@ export function useLocalFtp(add: Add, enabled: boolean, invoke: Invoke = tauriIn
|
||||
const events = cached?.events ?? [];
|
||||
const capturedAt = lisbonInstant(exifDateTime(preview));
|
||||
// Open FTP target always; eventForArrival drops an archived leftover and keeps shots inside the window.
|
||||
const eventId = eventForArrival(to?.id ?? null, events, capturedAt, pinWindow(to));
|
||||
const eventId = eventForArrival(to?.id ?? null, events, capturedAt);
|
||||
const filed = events.find((e) => e.id === eventId);
|
||||
if (!localPhotos.bySha(info.sha256)) {
|
||||
let url = "";
|
||||
@@ -245,12 +239,9 @@ export function useLocalFtp(add: Add, enabled: boolean, invoke: Invoke = tauriIn
|
||||
sentEvent = eventLabel(filed);
|
||||
sentDate = filed.startsAt.slice(0, 10);
|
||||
} else if (to && eventId === to.id) {
|
||||
// The pin is not in the cached list and its window still covers this shot.
|
||||
// The pin is not in the cached list (no capture time, or this computer has not seen the event).
|
||||
sentEvent = to.title;
|
||||
sentDate = to.date;
|
||||
} else if (capturedAt) {
|
||||
// No event for this time: file under the shoot day (Desktop/2026/20261126), not the expired pin.
|
||||
sentDate = lisbonDay(capturedAt);
|
||||
}
|
||||
invoke("ftp_sent", { path: f.path, event: sentEvent, date: sentDate })
|
||||
.then(() => {
|
||||
|
||||
@@ -139,6 +139,13 @@ const PRESETS = {
|
||||
longEdge: 4000,
|
||||
...DESTINATION_EXAMPLES.fpaM19,
|
||||
},
|
||||
fpaW17: {
|
||||
label: "Cloud W17",
|
||||
kind: "NEXTCLOUD",
|
||||
baseUrl: "https://cloud.photoreport.pt",
|
||||
longEdge: 4000,
|
||||
...DESTINATION_EXAMPLES.fpaW17,
|
||||
},
|
||||
liga: {
|
||||
label: "Estrutura Liga",
|
||||
kind: "NEXTCLOUD",
|
||||
|
||||
@@ -2,10 +2,10 @@ 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, lisbonDay, lisbonInstant } from "../offline/local.js";
|
||||
import { eventForArrival, exifDateTime, lisbonInstant } from "../offline/local.js";
|
||||
import { retryPhotoFile } from "../desktop/lightroomSidecar.js";
|
||||
import { asArrayBuffer, prefs } from "../platform.js";
|
||||
import { type FtpTarget, type IncomingFile, type Invoke, eventLabel, pinWindow } from "./LocalFtp.js";
|
||||
import { type FtpTarget, type IncomingFile, type Invoke, eventLabel } from "./LocalFtp.js";
|
||||
import type { PreviewOf, UploadStatus } from "./uploads.js";
|
||||
|
||||
/** What the desktop shell reports for a PTP body on the USB cable (`camera.rs`). */
|
||||
@@ -103,27 +103,16 @@ export function useUsbCamera(add: Add, enabled: boolean, target: FtpTarget | nul
|
||||
const events = cached?.events ?? [];
|
||||
const capturedAt = lisbonInstant(exifDateTime(bytes));
|
||||
// Always the open USB target — never drop a live pull into Sem evento because the agenda cache is stale.
|
||||
const eventId = eventForArrival(to?.id ?? null, events, capturedAt, pinWindow(to));
|
||||
const eventId = eventForArrival(to?.id ?? null, events, capturedAt);
|
||||
const filed = events.find((e) => e.id === eventId);
|
||||
let sentEvent = "";
|
||||
let sentDate = "";
|
||||
if (filed) {
|
||||
sentEvent = eventLabel(filed);
|
||||
sentDate = filed.startsAt.slice(0, 10);
|
||||
} else if (to && eventId === to.id) {
|
||||
sentEvent = to.title;
|
||||
sentDate = to.date;
|
||||
} else if (capturedAt) {
|
||||
sentDate = lisbonDay(capturedAt);
|
||||
}
|
||||
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: sentEvent,
|
||||
date: sentDate,
|
||||
event: filed ? eventLabel(filed) : (to?.title ?? ""),
|
||||
date: filed ? filed.startsAt.slice(0, 10) : (to?.date ?? ""),
|
||||
})
|
||||
.then(() => {
|
||||
retryPhotoFile(original.sha256);
|
||||
|
||||
@@ -14,6 +14,17 @@ import { kv } from "./kv.js";
|
||||
import { localPhotos } from "./local.js";
|
||||
import { localId, offlineQueue } from "./queue.js";
|
||||
|
||||
/** One pick per export group, otherwise the event's own number. Matches the server. */
|
||||
function picksFor(settings: AutopilotSettings): number {
|
||||
if (settings.deliverExports.length > 0) {
|
||||
return Math.min(10, settings.deliverExports.length);
|
||||
}
|
||||
if (settings.deliverTargetIds.length > 0) {
|
||||
return Math.min(5, settings.deliverTargetIds.length);
|
||||
}
|
||||
return settings.picksPerBurst;
|
||||
}
|
||||
|
||||
/** Same settle window as the server: a burst is decided once no new frame has arrived for this long. */
|
||||
const BURST_SETTLE_MS = 15_000;
|
||||
const PENDING_KEY = (orgId: string, eventId: string) => `autopilot:pending:${orgId}:${eventId}`;
|
||||
@@ -98,7 +109,7 @@ export async function planLocalAutopilot(args: {
|
||||
const pending = await loadPending(args.orgId, args.event.id);
|
||||
const next = [...pending.filter((f) => f.sha256 !== frame.sha256), frame];
|
||||
await savePending(args.orgId, args.event.id, next);
|
||||
scheduleSettle(args.orgId, args.event.id, settings.picksPerBurst, settings.burstGapSec * 1000);
|
||||
scheduleSettle(args.orgId, args.event.id, picksFor(settings), settings.burstGapSec * 1000);
|
||||
}
|
||||
|
||||
const timers = new Map<string, ReturnType<typeof setTimeout>>();
|
||||
|
||||
@@ -102,16 +102,6 @@ function readTiff(v: DataView, start: number, end: number): { date: string | nul
|
||||
};
|
||||
}
|
||||
|
||||
/** Lisbon calendar day of an ISO instant, "YYYY-MM-DD" (the work-folder date). */
|
||||
export function lisbonDay(iso: string): string {
|
||||
return new Intl.DateTimeFormat("en-CA", {
|
||||
timeZone: "Europe/Lisbon",
|
||||
year: "numeric",
|
||||
month: "2-digit",
|
||||
day: "2-digit",
|
||||
}).format(new Date(iso));
|
||||
}
|
||||
|
||||
/** "2026:10:09 20:26:47" (Lisbon wall time, as the API reads it) to an ISO instant. */
|
||||
export function lisbonInstant(exif: string | null): string | null {
|
||||
const m = exif?.match(/^(\d{4}):(\d{2}):(\d{2}) (\d{2}):(\d{2}):(\d{2})/);
|
||||
@@ -147,35 +137,19 @@ export function routeLocally(events: RoutedEvent[], at: string | null): string |
|
||||
return bestEventForCapture(events, at)?.id ?? null;
|
||||
}
|
||||
|
||||
function windowCovers(window: { ingestFrom: string; ingestUntil: string } | null | undefined, at: string): boolean {
|
||||
if (!window) return true;
|
||||
const t = Date.parse(at);
|
||||
const from = Date.parse(window.ingestFrom);
|
||||
const until = Date.parse(window.ingestUntil);
|
||||
if (!Number.isFinite(t) || !Number.isFinite(from) || !Number.isFinite(until)) return true;
|
||||
return from <= t && t <= until;
|
||||
}
|
||||
|
||||
/**
|
||||
* Where a photo arrives on this computer. With a capture time, the pin (FTP target / open event) wins only
|
||||
* inside that event's window — leftover pins from the morning studio must not swallow the afternoon training.
|
||||
* Without a capture time, keep the pin (same as the server): USB auto-pull already filtered by the window via
|
||||
* the card clock, and inventing "now" is what we must not do.
|
||||
* A pin missing from the agenda is kept only while its own window still covers the shot. An expired pin
|
||||
* (the event dropped off the list) must not keep filing the next day into that folder.
|
||||
*/
|
||||
export function eventForArrival(
|
||||
pinnedId: string | null,
|
||||
events: RoutedEvent[],
|
||||
at: string | null,
|
||||
pinWindow?: { ingestFrom: string; ingestUntil: string } | null,
|
||||
): string | null {
|
||||
export function eventForArrival(pinnedId: string | null, events: RoutedEvent[], at: string | null): string | null {
|
||||
if (!at) return pinnedId;
|
||||
if (!pinnedId) return routeLocally(events, at);
|
||||
const pinned = events.find((e) => e.id === pinnedId);
|
||||
if (!pinned) {
|
||||
if (windowCovers(pinWindow, at)) return pinnedId;
|
||||
return routeLocally(events, at);
|
||||
// Agenda cache miss: keep the open pin so USB/FTP does not dump live shots into Sem evento.
|
||||
return pinnedId;
|
||||
}
|
||||
if (pinned.archivedAt) return routeLocally(events, at);
|
||||
const t = Date.parse(at);
|
||||
|
||||
@@ -150,27 +150,8 @@ describe("photos arriving on this computer", () => {
|
||||
// No capture time: keep the pin (USB already filtered by the card clock; server keeps the named folder too).
|
||||
expect(eventForArrival("braga", events, null)).toBe("braga");
|
||||
expect(eventForArrival(null, events, null)).toBeNull();
|
||||
// Cache miss for the pin id: keep it while its window is unknown or still open.
|
||||
// Cache miss for the pin id: keep it (do not dump into Sem evento); archived pins fall through to the clock.
|
||||
expect(eventForArrival("missing", events, "2026-10-10T15:30:00Z")).toBe("missing");
|
||||
expect(
|
||||
eventForArrival("missing", events, "2026-10-09T19:26:47.000Z", {
|
||||
ingestFrom: "2026-10-09T17:15:00Z",
|
||||
ingestUntil: "2026-10-09T23:15:00Z",
|
||||
}),
|
||||
).toBe("missing");
|
||||
// The pin left the agenda and its window has closed: file by the clock, not into that old folder.
|
||||
expect(
|
||||
eventForArrival("studio", events, "2026-11-26T20:20:00Z", {
|
||||
ingestFrom: "2026-11-24T11:08:00.000Z",
|
||||
ingestUntil: "2026-11-24T17:08:00.000Z",
|
||||
}),
|
||||
).toBeNull();
|
||||
expect(
|
||||
eventForArrival("studio", events, "2026-10-10T15:30:00Z", {
|
||||
ingestFrom: "2026-10-09T17:15:00Z",
|
||||
ingestUntil: "2026-10-09T23:15:00Z",
|
||||
}),
|
||||
).toBe("other");
|
||||
expect(eventForArrival("braga", [{ ...events[0]!, archivedAt: "2026-10-10T00:00:00Z" }, events[1]!], "2026-10-10T15:30:00Z")).toBe("other");
|
||||
});
|
||||
|
||||
|
||||
@@ -136,7 +136,7 @@ export function DeliveryPage() {
|
||||
</td>
|
||||
<td className="border-b border-line px-3 py-1.5 text-right">
|
||||
{i.status === "FAILED" && (
|
||||
<button className="pr-quiet" onClick={() => void api.retryDelivery(orgId, i.id).then(load)}>
|
||||
<button className="pr-quiet" onClick={() => void api.retryDelivery(orgId, i.id).then(load, () => load())}>
|
||||
{t.retry}
|
||||
</button>
|
||||
)}
|
||||
|
||||
@@ -330,14 +330,20 @@ every 6 hours (`SPORTS_SYNC=off` turns it off). It is shared by every organisati
|
||||
sides (`M19`, `ESP-M19`), and merges the Men's EHF EURO Cup match sheets from `www.eurohandball.com`
|
||||
(`GetStandingMatches` / `GetMatchDetails` — same shape as club sheets, with shirt numbers and `res.ehf.eu`
|
||||
headshots for the nominated 16). Portuguese CIPAs from the FPA call-up stay as `externalId` when the name
|
||||
matches; photo/number come from the sheet. Youth camps (sub-17, sub-19, sub-20, men or women) come from
|
||||
matches; photo/number come from the sheet. The same pass reads the Women's U17 EHF EURO qualification
|
||||
(`W17-EURO`, content `139009`: Portugal–Italy `202712010502014`, 27 Nov 2026 19:00 in Águas Santas, and the
|
||||
rest of that tournament). Portugal is team `W17`; every other country is `<code>-W17` (Italy is `ITA-W17`). The nominated sheet
|
||||
fills numbers and headshots once the EHF publishes it. The FPA camp lists that same match as a friendly
|
||||
(`Sub-17 feminina`): it is folded into `W17-EURO`, and an event already opened on it stays on the one fixture.
|
||||
Youth camps (sub-17, sub-19, sub-20, men or women) come from
|
||||
recent posts on `portal.fpa.pt`: the call-up PDF (CIPA, no shirt number from the list order) and the
|
||||
"Jogos Particulares" calendar. A sheet with a real squad replaces that age group; a post the site does not
|
||||
return leaves the plantel we already have. The November 2026 M19 list and the Spain name list are only the
|
||||
seed when that team is still empty. Those friendlies are fixtures (`m19-por-esp-20261105`,
|
||||
`m19-esp-por-20261107`) so picking the game links that plantel, not the senior one. A folder or title that
|
||||
says sub-19 / M19 (not "Encontro Nacional") is that age group. Cloud delivery for these games is the
|
||||
destination "Cloud M19" (`/FPA/Fotos/{season}/Seleções Nacionais/M19/…`), created from the organisation's
|
||||
destination "Cloud M19" (`/FPA/Fotos/{season}/Seleções Nacionais/M19/…`) and "Cloud W17"
|
||||
(`…/Seleções Nacionais/W17/…`), each created from the organisation's
|
||||
existing FPA Nextcloud account and never sent on arrival. FPA licence or an older EHF club photo fills
|
||||
gaps. People and reference faces are created when the event syncs those teams (`POST …/squads/sync`), not on
|
||||
every sports refresh. Example match: Portugal–Switzerland `202811130101002`.
|
||||
|
||||
@@ -61,6 +61,22 @@ export const AutopilotSettings = z.object({
|
||||
* legacy pair below. Empty: use `deliverTargetId` / `restTargetId` when set.
|
||||
*/
|
||||
deliverTargetIds: z.array(z.string().uuid()).max(10).default([]),
|
||||
/**
|
||||
* One frame of each burst per row. `alsoTargetIds` receive that same frame (Cofina Direto and Arquivo) and
|
||||
* are not a separate pick. `count` is how many photos that destination takes over the match (null: no cap).
|
||||
* `originals`: the camera file, without the develop render. Empty: `deliverTargetIds`, one destination each.
|
||||
*/
|
||||
deliverExports: z
|
||||
.array(
|
||||
z.object({
|
||||
targetId: z.string().uuid(),
|
||||
alsoTargetIds: z.array(z.string().uuid()).max(4).default([]),
|
||||
count: z.number().int().min(1).max(2000).nullable().default(null),
|
||||
originals: z.boolean().default(false),
|
||||
}),
|
||||
)
|
||||
.max(10)
|
||||
.default([]),
|
||||
/** Legacy first export (null: don't). Kept for older clients; folded into `deliverTargetIds` when that is empty. */
|
||||
deliverTargetId: z.string().uuid().nullable().default(null),
|
||||
/**
|
||||
|
||||
@@ -238,6 +238,21 @@ describe("delivery paths", () => {
|
||||
expect(renderFileName(DESTINATION_EXAMPLES.fpaM19.fileName, { ...m19, n: 3 }, "R1_0003.JPG")).toBe("PS_POR x ESP_3.jpg");
|
||||
});
|
||||
|
||||
it("matches the women's under-17 cloud folder", () => {
|
||||
const w17 = buildVars({
|
||||
home: "Portugal",
|
||||
away: "Itália",
|
||||
homeShort: "POR",
|
||||
awayShort: "ITA",
|
||||
competition: "W17 EHF EURO",
|
||||
startsAt: new Date("2026-11-27T19:00:00Z"),
|
||||
});
|
||||
expect(renderFolder(DESTINATION_EXAMPLES.fpaW17.folder, w17)).toBe(
|
||||
"/FPA/Fotos/2026_2027/Seleções Nacionais/W17/20261127 - POR x ITA/",
|
||||
);
|
||||
expect(renderFileName(DESTINATION_EXAMPLES.fpaW17.fileName, { ...w17, n: 1 }, "R1_0001.JPG")).toBe("PS_POR x ITA_1.jpg");
|
||||
});
|
||||
|
||||
it("matches the Liga folder and keeps the camera name", () => {
|
||||
const liga = buildVars({ home: "Casa Pia", away: "Sporting", round: 1, matchNumber: 1, startsAt: new Date("2025-08-09T18:00:00Z") });
|
||||
expect(renderFolder(DESTINATION_EXAMPLES.liga.folder, liga)).toBe("/LPBetclic 25-26/Jornada 1/1. Casa Pia x Sporting/");
|
||||
|
||||
@@ -82,6 +82,11 @@ export const DESTINATION_EXAMPLES = {
|
||||
folder: "/FPA/Fotos/{season}/Seleções Nacionais/M19/{dateCompact} - {homeShort} x {awayShort}/",
|
||||
fileName: "PS_{homeShort} x {awayShort}_{n}.jpg",
|
||||
},
|
||||
/** Women's under-17. Same account as the club cloud; its own folder under Seleções Nacionais. */
|
||||
fpaW17: {
|
||||
folder: "/FPA/Fotos/{season}/Seleções Nacionais/W17/{dateCompact} - {homeShort} x {awayShort}/",
|
||||
fileName: "PS_{homeShort} x {awayShort}_{n}.jpg",
|
||||
},
|
||||
liga: {
|
||||
folder: "/LPBetclic {seasonShort}/Jornada {round}/{matchNumber}. {home} x {away}/",
|
||||
fileName: "{originalName}",
|
||||
|
||||
Reference in new issue
Block a user