Compare commits

..
Author SHA1 Message Date
spark 3513864773 Show the EHF host checklist on those matches, and point a stale window at the Applications copy.
The installer replaces /Applications/PhotoReport.app. A window launched from a build folder stays on its old version and keeps asking for an update.
2026-11-27 15:01:48 +00:00
25 changed files with 582 additions and 610 deletions

No files matched your search

+13 -54
View File
@@ -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 { assignBurstExports, exportSlots, exportTargets, galleryReceivers, MELHORES_GAP_MS, picksNeeded, type BurstExportSlot, type GalleryExport } from "./targets.js";
import { exportTargets, galleryReceivers, MELHORES_GAP_MS, picksNeeded, 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,18 +282,7 @@ 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 };
});
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]!;
for (const burst of groupBursts(frames, settings.burstGapSec * 1000)) {
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;
@@ -312,8 +301,7 @@ 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) {
const cap = settings.deliverExports.length > 0 ? settings.deliverExports.length : settings.picksPerBurst;
take = Math.min(asked, Math.max(0, cap));
take = Math.min(asked, Math.max(0, settings.picksPerBurst));
}
const start = Math.min(...burst.map((f) => (f.capturedAt ?? f.createdAt).getTime()));
const sameCamera = frames
@@ -335,16 +323,13 @@ export class AutopilotService {
});
if (already.length > 0) {
const next = bestOf(pool, 1)[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,
});
}
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;
take = Math.min(take, room);
}
const chosen = bestOf(pool, take)
@@ -423,37 +408,11 @@ 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.
// 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) {
// 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) {
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
-88
View File
@@ -22,96 +22,8 @@ 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;
+6 -28
View File
@@ -4,19 +4,13 @@ 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 under Seleções Nacionais.
* Same account and file name as that destination; the folder is Seleções Nacionais/M19.
* It does not send on arrival: the photographer chooses it for this game.
* Returns how many destinations were created.
*/
async function ensureNationalCloudTarget(
db: Db,
target: { name: string; folder: string; fileName: string },
): Promise<number> {
export async function ensureCloudM19Target(db: Db): Promise<number> {
const sources = await db.deliveryTarget.findMany({
where: {
kind: "NEXTCLOUD",
@@ -37,21 +31,21 @@ async function ensureNationalCloudTarget(
if (seen.has(source.organizationId)) continue;
seen.add(source.organizationId);
const exists = await db.deliveryTarget.findUnique({
where: { organizationId_name: { organizationId: source.organizationId, name: target.name } },
where: { organizationId_name: { organizationId: source.organizationId, name: CLOUD_M19_TARGET } },
select: { id: true },
});
if (exists) continue;
await db.deliveryTarget.create({
data: {
organizationId: source.organizationId,
name: target.name,
name: CLOUD_M19_TARGET,
kind: source.kind,
baseUrl: source.baseUrl,
username: source.username,
secretEnc: source.secretEnc,
hostFingerprint: source.hostFingerprint,
folderTemplate: target.folder,
fileNameTemplate: source.fileNameTemplate || target.fileName,
folderTemplate: DESTINATION_EXAMPLES.fpaM19.folder,
fileNameTemplate: source.fileNameTemplate || DESTINATION_EXAMPLES.fpaM19.fileName,
longEdge: source.longEdge,
jpegQuality: source.jpegQuality,
sharpen: source.sharpen,
@@ -70,19 +64,3 @@ async function ensureNationalCloudTarget(
}
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,
});
}
-1
View File
@@ -17,7 +17,6 @@ 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 -2
View File
@@ -1,4 +1,4 @@
import { ensureCloudM19Target, ensureCloudW17Target } from "./delivery/fpa-m19.js";
import { ensureCloudM19Target } from "./delivery/fpa-m19.js";
import { preferIpv4 } from "./lib/prefer-ipv4.js";
import { buildApp, reporterFor } from "./app.js";
import { loadConfig } from "./config.js";
@@ -21,7 +21,6 @@ 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" });
-80
View File
@@ -691,20 +691,6 @@ 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,
@@ -824,69 +810,6 @@ 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.
@@ -921,9 +844,6 @@ export class SportsService {
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,
+1 -2
View File
@@ -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, ensureCloudW17Target } from "./delivery/fpa-m19.js";
import { ensureCloudM19Target } 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,7 +177,6 @@ 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();
-58
View File
@@ -930,64 +930,6 @@ describe("sports data service", () => {
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 -57
View File
@@ -1,6 +1,6 @@
import { describe, expect, it } from "vitest";
import { AutopilotSettings } from "@photoreport/contracts";
import { assignBurstExports, exportSlots, exportTargets, galleryReceivers, picksNeeded, type BurstExportSlot } from "../src/autopilot/targets.js";
import { exportTargets, galleryReceivers, picksNeeded } from "../src/autopilot/targets.js";
const a = "11111111-1111-4111-8111-111111111111";
const b = "22222222-2222-4222-8222-222222222222";
@@ -17,62 +17,6 @@ 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] });
+27 -1
View File
@@ -119,7 +119,23 @@ export function UpdateNotice({
const [state, setState] = useState<"idle" | "installing" | "failed">("idle");
const [error, setError] = useState<string | null>(null);
const [dismissed, setDismissed] = useState(false);
const [bundlePath, setBundlePath] = useState<string | null>(null);
const started = useRef(false);
const onMac = /Mac OS X|Macintosh/.test(typeof navigator === "undefined" ? "" : navigator.userAgent);
useEffect(() => {
if (!enabled) return;
let alive = true;
invoke<string>("app_executable_path").then(
(path) => {
if (alive && path) setBundlePath(path);
},
() => {},
);
return () => {
alive = false;
};
}, [enabled, invoke]);
useEffect(() => {
if (!enabled) return;
@@ -204,14 +220,24 @@ export function UpdateNotice({
);
}
if (!manual) return null;
const elsewhere = bundlePath !== null && !bundlePath.includes("/Applications/PhotoReport.app/");
return (
<div role="status" className="flex flex-wrap items-center gap-3 border-b border-black bg-[#1d2a3a] px-4 py-1.5 text-[12px] text-ink">
<span>{t.update.available(manual.version, manual.currentVersion)}</span>
<span className="text-muted">{t.update.manual}</span>
{elsewhere && bundlePath && <span className="text-muted">{t.update.runningElsewhere(bundlePath)}</span>}
{manual.reason && <span className="truncate text-faint">({manual.reason})</span>}
{manual.installer && (
{onMac && (
<button
className="ml-auto h-7 bg-accent px-3 text-[12px] font-semibold text-white hover:bg-accent-strong"
onClick={() => void open("file:///Applications/PhotoReport.app")}
>
{t.update.openInstalled}
</button>
)}
{manual.installer && (
<button
className={`${onMac ? "" : "ml-auto "}h-7 border border-line px-3 text-[12px] text-ink hover:bg-raised`}
onClick={() => void open(manual.installer!)}
>
{t.update.download}
+21
View File
@@ -92,6 +92,27 @@ describe("update notice", () => {
expect(screen.queryByText("Descarregar instalador")).toBeNull();
});
it("on a Mac, opens the Applications copy instead of the window that is already running", async () => {
const previous = navigator.userAgent;
Object.defineProperty(navigator, "userAgent", { configurable: true, value: "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7)" });
try {
const invoke = vi.fn(async (cmd: string) => {
if (cmd === "app_executable_path") {
return "/Users/me/photoreport-m19-deploy/PhotoReport.app/Contents/MacOS/photoreport";
}
return null;
}) as unknown as Invoke;
const open = vi.fn(async () => {});
const server = vi.fn(async () => ({ version: "0.3.33", currentVersion: "0.3.27", installer: "https://api.example/PhotoReport.dmg" }));
render(<UpdateNotice invoke={invoke} enabled server={server} open={open} />);
expect(await screen.findByText(/cópia em \/Users\/me\/photoreport-m19-deploy/)).toBeTruthy();
fireEvent.click(screen.getByText("Abrir a das Aplicações"));
expect(open).toHaveBeenCalledWith("file:///Applications/PhotoReport.app");
} finally {
Object.defineProperty(navigator, "userAgent", { configurable: true, value: previous });
}
});
it("stays quiet when there is nothing new, and outside the desktop app", async () => {
const invoke = vi.fn(async () => null) as unknown as Invoke;
const { container } = render(<UpdateNotice invoke={invoke} enabled server={async () => null} />);
+3 -9
View File
@@ -578,14 +578,6 @@ 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",
@@ -920,7 +912,9 @@ export const t = {
install: "Instalar e reiniciar",
installing: "A instalar a nova versão. A app reinicia sozinha.",
failed: "Não foi possível instalar. Tenta mais tarde.",
manual: "Esta instalação não se atualiza sozinha: descarrega o instalador e abre-o (só desta vez).",
manual: "O instalador não substitui esta janela. No Mac, arrasta o PhotoReport para Aplicações (substitui), fecha esta janela e abre a das Aplicações.",
openInstalled: "Abrir a das Aplicações",
runningElsewhere: (path: string) => `Esta janela é a cópia em ${path}. A versão nova fica na pasta Aplicações.`,
download: "Descarregar instalador",
later: "Mais tarde",
uiReady: "Nova versão da interface descarregada. Fica ativa ao recarregar (ou no próximo arranque).",
+15 -170
View File
@@ -4,153 +4,6 @@ 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.
@@ -177,12 +30,9 @@ export function AutopilotButton(props: {
}, [props.autopilotAsk, props.event.id, props.onAsked]);
const save = async (next: AutopilotSettings) => {
// 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 };
}
// 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 ?? [] };
setS(synced);
setState("saving");
try {
@@ -209,7 +59,7 @@ export function AutopilotButton(props: {
{L.button}
</button>
{open && (
<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}>
<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}>
<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} />
@@ -260,22 +110,17 @@ export function AutopilotButton(props: {
))}
</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.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"] })}>
+136
View File
@@ -0,0 +1,136 @@
import type { ApiClient, EventSquads, EventSummary } from "@photoreport/sdk";
import type { PhotoSummary } from "@photoreport/contracts";
import { useEffect, useState } from "react";
import { prefs } from "../platform.js";
import { assessEhfChecklist, checklistGap, isEhfEvent, shotTitle, type ShotId, type ShotMark, type ShotResult } from "./ehfShots.js";
const keyOf = (eventId: string) => `ehf-checklist:${eventId}`;
function readMarks(eventId: string): Partial<Record<ShotId, ShotMark>> {
const raw = prefs.get(keyOf(eventId));
if (!raw) return {};
try {
const parsed = JSON.parse(raw) as Partial<Record<ShotId, ShotMark>>;
if (!parsed || typeof parsed !== "object") return {};
return parsed;
} catch {
return {};
}
}
function playersOf(squads: EventSquads | null) {
if (!squads) return [];
const players = [];
for (const side of squads.sides) {
for (const player of side.players) {
let photoCount = player.photoIds?.length ?? 0;
if (photoCount === 0 && player.photos) {
photoCount = player.photos.confirmed + player.photos.likely;
}
players.push({
position: player.position,
side: side.side,
photoCount,
});
}
}
return players;
}
/**
* For an EHF match (club competitions and the under-17 EURO): what the host-photographer list
* still needs. Measured items come from the photos; the rest wait for a tick.
*/
export function EhfChecklistButton({ api, event, photos }: { api: ApiClient; event: EventSummary; photos: PhotoSummary[] }) {
const [open, setOpen] = useState(false);
const [marks, setMarks] = useState<Partial<Record<ShotId, ShotMark>>>(() => readMarks(event.id));
const [squads, setSquads] = useState<EventSquads | null>(null);
const show = isEhfEvent(event);
useEffect(() => {
setMarks(readMarks(event.id));
setSquads(null);
}, [event.id]);
useEffect(() => {
if (!show || !(event.homeTeamId || event.awayTeamId)) return;
let alive = true;
api.eventSquads(event.id).then(
(next) => {
if (alive) setSquads(next);
},
() => {
if (alive) setSquads(null);
},
);
return () => {
alive = false;
};
}, [api, show, event.id, event.homeTeamId, event.awayTeamId, photos.length]);
if (!show) return null;
const shots = assessEhfChecklist({
photos: photos.map((photo) => ({
name: photo.name || photo.originalName,
status: photo.status,
width: photo.width,
height: photo.height,
capturedAt: photo.capturedAt,
})),
players: playersOf(squads),
startsAt: event.startsAt,
now: Date.now(),
marks,
});
const gap = checklistGap(shots);
const cycle = (shot: ShotResult) => {
const current = marks[shot.id];
let next: ShotMark | undefined;
if (!current) next = "have";
else if (current === "have") next = "skip";
else next = undefined;
const updated = { ...marks };
if (next) updated[shot.id] = next;
else delete updated[shot.id];
setMarks(updated);
prefs.set(keyOf(event.id), JSON.stringify(updated));
};
return (
<div className="relative">
<button onClick={() => setOpen((value) => !value)} aria-expanded={open} className={`pr-quiet ${open || gap > 0 ? "is-on" : ""}`}>
{gap > 0 ? `Checklist EHF · ${gap}` : "Checklist EHF"}
</button>
{open && (
<div className="absolute left-0 top-7 z-20 w-[min(420px,calc(100vw-24px))] border border-line bg-panel p-3 text-[12px] shadow-2xl">
<p className="mb-2 text-muted">
Lista da EHF para o fotógrafo da casa. O que dá para medir está visto nas fotos; o resto marcas tu. Um clique: já tenho. Outro: não se aplica. O terceiro volta ao automático.
</p>
<ul className="flex flex-col gap-1">
{shots.map((shot) => (
<li key={shot.id}>
<button onClick={() => cycle(shot)} className="flex w-full items-baseline gap-2 text-left hover:bg-raised">
<Mark state={shot.state} skipped={marks[shot.id] === "skip"} />
<span className="min-w-0">
<span className="block text-ink">{shotTitle(shot.id)}</span>
<span className="block text-[11px] text-faint">{shot.detail}</span>
</span>
</button>
</li>
))}
</ul>
<p className="mt-2 text-[11px] text-faint">O envio grava JPEG a 300 dpi. O mínimo da EHF é 8 megapixéis.</p>
</div>
)}
</div>
);
}
function Mark({ state, skipped }: { state: ShotResult["state"]; skipped: boolean }) {
if (skipped) return <span className="font-mono text-faint">—</span>;
if (state === "have") return <span className="font-mono text-ok">✓</span>;
if (state === "missing") return <span className="font-mono text-danger">✗</span>;
return <span className="font-mono text-star">?</span>;
}
-7
View File
@@ -139,13 +139,6 @@ 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",
+70
View File
@@ -0,0 +1,70 @@
import { describe, expect, it } from "vitest";
import { assessEhfChecklist, checklistGap, isEhfEvent } from "./ehfShots.js";
const start = "2026-11-27T19:00:00.000Z";
const during = "2026-11-27T19:20:00.000Z";
const before = "2026-11-27T18:40:00.000Z";
const after = "2026-11-27T20:30:00.000Z";
function jpeg(name: string, capturedAt: string, pixels = 20_000_000) {
const side = Math.round(Math.sqrt(pixels));
return { name, status: "READY", width: side, height: side, capturedAt };
}
describe("isEhfEvent", () => {
it("recognises the EHF competitions and leaves a domestic league alone", () => {
expect(isEhfEvent({ competition: "W17 EHF EURO", competitionCode: "W17-EURO" })).toBe(true);
expect(isEhfEvent({ competition: "EHF Champions League", competitionCode: "cl-men" })).toBe(true);
expect(isEhfEvent({ title: "Portugal x Itália", round: "Qualificação C", competition: "Europeu sub-17" })).toBe(true);
expect(isEhfEvent({ competition: "Campeonato Betclic", competitionCode: "PO01" })).toBe(false);
expect(isEhfEvent({ title: "Portugal x Espanha" })).toBe(false);
});
});
describe("assessEhfChecklist", () => {
it("counts JPEGs, megapixels, the warm-up and both teams", () => {
const photos = [
jpeg("a.jpg", before),
jpeg("b.jpg", during),
jpeg("c.CR3", during),
];
const shots = assessEhfChecklist({
photos,
players: [
{ position: "Guarda-redes", side: "home", photoCount: 1 },
{ position: "Central", side: "home", photoCount: 2 },
{ position: "Central", side: "away", photoCount: 1 },
{ position: "Treinador", side: "home", photoCount: 0 },
],
startsAt: start,
now: Date.parse(during),
});
const byId = Object.fromEntries(shots.map((shot) => [shot.id, shot]));
expect(byId.count?.state).toBe("missing");
expect(byId.count?.detail).toContain("3 de 20");
expect(byId.count?.detail).toContain("grava JPEG");
expect(byId.megapixels?.state).toBe("have");
expect(byId.warmup?.state).toBe("have");
expect(byId.action?.state).toBe("have");
expect(byId.goalkeeper?.state).toBe("have");
expect(byId.coach?.state).toBe("missing");
expect(byId.lineup?.state).toBe("confirm");
expect(byId.cheer?.state).toBe("confirm");
});
it("treats a marked scene as done and a skip as not applicable", () => {
const shots = assessEhfChecklist({
photos: [jpeg("a.jpg", after, 2_000_000)],
players: [],
startsAt: start,
now: Date.parse(after),
marks: { fans: "have", referee: "skip" },
});
const byId = Object.fromEntries(shots.map((shot) => [shot.id, shot]));
expect(byId.fans?.state).toBe("have");
expect(byId.referee?.detail).toBe("não se aplica a este jogo");
expect(byId.megapixels?.state).toBe("missing");
expect(byId.cheer?.state).toBe("confirm");
expect(checklistGap(shots)).toBeGreaterThan(0);
});
});
+266
View File
@@ -0,0 +1,266 @@
/**
* The EHF host-photographer list (W17 qualification regulations, §29.16–29.17) and what this
* event's photos already cover. Scenes we cannot see (fans, the full court, a timeout) stay
* "confirm" until the photographer marks them. Quality we can measure (count, JPEG, megapixels).
*/
export const EHF_MIN_PHOTOS = 20;
export const EHF_MIN_PIXELS = 8_000_000;
/** A handball match, with the break, from the throw-off. */
const MATCH_MS = 80 * 60_000;
const WARMUP_MS = 3 * 60 * 60_000;
export type ShotId =
| "count"
| "megapixels"
| "warmup"
| "action"
| "goalkeeper"
| "coach"
| "cheer"
| "lineup"
| "court"
| "timeout"
| "ceremony"
| "referee"
| "fans";
export type ShotState = "have" | "missing" | "confirm";
export type ShotMark = "have" | "skip";
export interface ChecklistPhoto {
name: string;
status: string;
width: number | null;
height: number | null;
capturedAt: string | null;
}
export interface ChecklistPlayer {
position: string | null;
side: "home" | "away";
photoCount: number;
}
export interface ShotResult {
id: ShotId;
state: ShotState;
detail: string;
}
const TITLES: Record<ShotId, string> = {
count: "Pelo menos 20 fotografias",
megapixels: "Cada foto com 8 megapixéis ou mais",
warmup: "Antes do jogo (balneário, aquecimento)",
action: "Jogo, com as duas equipas e os patrocinadores visíveis",
goalkeeper: "Guarda-redes em ação",
coach: "Treinadores em ação",
cheer: "Festa da equipa que ganhou",
lineup: "Alinhamento das equipas",
court: "Plano do pavilhão com o campo todo",
timeout: "Desconto de tempo",
ceremony: "Cerimónia, abertura ou entrega de prémios",
referee: "Árbitros em ação",
fans: "Público, de perto",
};
export function shotTitle(id: ShotId): string {
return TITLES[id];
}
/** An EHF competition, including the under-17 EURO. A domestic league is not. */
export function isEhfEvent(event: {
competition?: string | null;
competitionCode?: string | null;
title?: string | null;
round?: string | null;
}): boolean {
const code = (event.competitionCode ?? "").toUpperCase();
if (code === "W17-EURO" || code === "EURO-CUP-M") return true;
if (code.startsWith("CL-") || code.startsWith("EL-") || code.startsWith("EC-")) return true;
const text = [event.competition, event.title, event.round, event.competitionCode].filter(Boolean).join("\n");
const folded = text.normalize("NFD").replace(/[\u0300-\u036f]/g, "").toLowerCase();
if (/\behf\b/.test(folded) || /\bw17\b/.test(folded)) return true;
if (/\bsub-?17\b/.test(folded) && /euro|qualif/.test(folded)) return true;
if (/\bu-?17\b/.test(folded) && /euro|qualif/.test(folded)) return true;
return false;
}
function isJpeg(name: string): boolean {
return /\.jpe?g$/i.test(name);
}
function when(value: string | null): number | null {
if (!value) return null;
const at = Date.parse(value);
if (Number.isNaN(at)) return null;
return at;
}
function isKeeper(position: string | null): boolean {
if (!position) return false;
const folded = position.normalize("NFD").replace(/[\u0300-\u036f]/g, "").toLowerCase();
return /guarda/.test(folded);
}
function isCoach(position: string | null): boolean {
if (!position) return false;
const folded = position.normalize("NFD").replace(/[\u0300-\u036f]/g, "").toLowerCase();
return /treinador|seleccionador|selecionador|equipa tecnica/.test(folded);
}
function applyMark(shot: ShotResult, mark: ShotMark | undefined): ShotResult {
if (mark === "have") return { ...shot, state: "have", detail: shot.detail || "marcado por ti" };
if (mark === "skip") return { ...shot, state: "have", detail: "não se aplica a este jogo" };
return shot;
}
export function assessEhfChecklist(input: {
photos: ChecklistPhoto[];
players: ChecklistPlayer[];
startsAt: string;
now: number;
marks?: Partial<Record<ShotId, ShotMark>>;
}): ShotResult[] {
const marks = input.marks ?? {};
const start = Date.parse(input.startsAt);
const usable = input.photos.filter((photo) => photo.status !== "FAILED");
const others = usable.filter((photo) => !isJpeg(photo.name));
const early = usable.filter((photo) => {
const at = when(photo.capturedAt);
if (at === null || Number.isNaN(start)) return false;
return at < start && at >= start - WARMUP_MS;
});
const during = usable.filter((photo) => {
const at = when(photo.capturedAt);
if (at === null || Number.isNaN(start)) return false;
return at >= start && at <= start + MATCH_MS;
});
const after = usable.filter((photo) => {
const at = when(photo.capturedAt);
if (at === null || Number.isNaN(start)) return false;
return at > start + MATCH_MS;
});
const sized = usable.filter((photo) => photo.width && photo.height);
const small = sized.filter((photo) => {
const width = photo.width ?? 0;
const height = photo.height ?? 0;
return width * height < EHF_MIN_PIXELS;
});
const pictured = (side: "home" | "away") =>
input.players.some((player) => player.side === side && player.photoCount > 0 && !isCoach(player.position));
const home = pictured("home");
const away = pictured("away");
const keepers = input.players.filter((player) => isKeeper(player.position));
const coaches = input.players.filter((player) => isCoach(player.position));
const squadKnown = input.players.length > 0;
let countDetail = `${usable.length} de ${EHF_MIN_PHOTOS}`;
if (usable.length >= EHF_MIN_PHOTOS) {
countDetail = `${usable.length} fotos`;
}
if (others.length > 0) {
countDetail = `${countDetail}; o envio grava JPEG (a EHF pede JPG)`;
}
let countState: ShotResult["state"] = "missing";
if (usable.length >= EHF_MIN_PHOTOS) {
countState = "have";
}
const count: ShotResult = {
id: "count",
state: countState,
detail: countDetail,
};
let pixels: ShotResult;
if (sized.length === 0) {
pixels = { id: "megapixels", state: "confirm", detail: "ainda sem medida nas fotos" };
} else if (small.length > 0) {
pixels = { id: "megapixels", state: "missing", detail: `${small.length} abaixo de 8 megapixéis` };
} else {
pixels = { id: "megapixels", state: "have", detail: "as que têm medida passam dos 8 megapixéis" };
}
let warmup: ShotResult;
if (early.length > 0) {
warmup = { id: "warmup", state: "have", detail: `${early.length} antes do apito` };
} else if (!Number.isNaN(start) && input.now < start) {
warmup = { id: "warmup", state: "confirm", detail: "o jogo ainda não começou" };
} else {
warmup = { id: "warmup", state: "missing", detail: "nenhuma foto antes do apito" };
}
let action: ShotResult = {
id: "action",
state: "confirm",
detail: "sem plantel, não dá para ver as duas equipas",
};
if (!squadKnown && during.length > 0) {
action = {
id: "action",
state: "confirm",
detail: `${during.length} durante o jogo; sem plantel não sei se estão as duas equipas`,
};
}
if (squadKnown && home && away) {
action = { id: "action", state: "have", detail: "há fotos das duas equipas" };
}
if (squadKnown && (!home || !away)) {
action = { id: "action", state: "missing", detail: "falta uma das equipas nas fotos com nome" };
}
let goalkeeper: ShotResult;
if (!squadKnown) {
goalkeeper = { id: "goalkeeper", state: "confirm", detail: "sem plantel, não sei quem é o guarda-redes" };
} else if (keepers.length === 0) {
goalkeeper = { id: "goalkeeper", state: "confirm", detail: "o plantel não traz guarda-redes" };
} else if (keepers.some((player) => player.photoCount > 0)) {
goalkeeper = { id: "goalkeeper", state: "have", detail: "há fotos de um guarda-redes" };
} else {
goalkeeper = { id: "goalkeeper", state: "missing", detail: "nenhuma foto do guarda-redes" };
}
let coach: ShotResult;
if (!squadKnown) {
coach = { id: "coach", state: "confirm", detail: "sem plantel, não sei quem é o treinador" };
} else if (coaches.length === 0) {
coach = { id: "coach", state: "confirm", detail: "o plantel não traz a equipa técnica" };
} else if (coaches.some((player) => player.photoCount > 0)) {
coach = { id: "coach", state: "have", detail: "há fotos da equipa técnica" };
} else {
coach = { id: "coach", state: "missing", detail: "nenhuma foto do treinador" };
}
let cheer: ShotResult;
if (after.length > 0) {
cheer = { id: "cheer", state: "confirm", detail: `${after.length} depois do jogo; confirma se é a festa` };
} else if (!Number.isNaN(start) && input.now < start + MATCH_MS) {
cheer = { id: "cheer", state: "confirm", detail: "ainda é cedo para a festa" };
} else {
cheer = { id: "cheer", state: "missing", detail: "nenhuma foto depois do jogo" };
}
const confirmOnly = (id: ShotId, detail: string): ShotResult => ({ id, state: "confirm", detail });
const shots: ShotResult[] = [
count,
pixels,
warmup,
action,
goalkeeper,
coach,
cheer,
confirmOnly("lineup", "não consigo ver o alinhamento; marca quando o tiveres"),
confirmOnly("court", "não consigo ver se o campo está todo no enquadramento"),
confirmOnly("timeout", "não consigo ver um desconto de tempo"),
confirmOnly("ceremony", "não consigo ver a cerimónia"),
confirmOnly("referee", "não consigo distinguir os árbitros"),
confirmOnly("fans", "não consigo ver o público"),
];
return shots.map((shot) => applyMark(shot, marks[shot.id]));
}
export function checklistGap(shots: ShotResult[]): number {
return shots.filter((shot) => shot.state !== "have").length;
}
+1 -12
View File
@@ -14,17 +14,6 @@ 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}`;
@@ -109,7 +98,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, picksFor(settings), settings.burstGapSec * 1000);
scheduleSettle(args.orgId, args.event.id, settings.picksPerBurst, settings.burstGapSec * 1000);
}
const timers = new Map<string, ReturnType<typeof setTimeout>>();
+2
View File
@@ -29,6 +29,7 @@ import { CardIngestButton, CardOverallStatus } from "../library/CardIngest.js";
import { MergeButton } from "../library/MergeButton.js";
import { AutopilotButton } from "../library/Autopilot.js";
import { SquadsButton } from "../library/Squads.js";
import { EhfChecklistButton } from "../library/EhfChecklist.js";
import { type PlayerPick, photoIdsOf, samePicks } from "../library/squadFilter.js";
import { PhotoContextMenu, type PhotoMenuAction } from "../library/PhotoContextMenu.js";
import { RemoveFromEventDialog } from "../library/RemoveFromEvent.js";
@@ -966,6 +967,7 @@ export function LibraryPage() {
{canCull && openEvent && (
<SquadsButton api={api} event={openEvent} canEdit={canCreate} facesTick={facesTick} selectedIds={selectedPlayerIds} onPlayers={onPlayers} onSaved={(e) => setEvents((list) => list.map((x) => (x.id === e.id ? e : x)))} />
)}
{canCull && openEvent && <EhfChecklistButton api={api} event={openEvent} photos={state.photos} />}
{canCull && openEvent && (
<AutopilotButton
api={api}
+1
View File
@@ -180,6 +180,7 @@ pub fn run() {
faces::faces_read,
updater::update_check,
updater::update_install,
updater::app_executable_path,
ui::ui_status,
ui::ui_check,
deliver::delivery_machine,
+10
View File
@@ -48,6 +48,16 @@ fn updater(app: &tauri::AppHandle) -> Result<tauri_plugin_updater::Updater, Stri
.map_err(|e| e.to_string())
}
/// Where this window was launched from. The installer replaces the copy in Applications;
/// a copy opened from a build folder keeps its old version.
#[tauri::command]
pub fn app_executable_path() -> String {
match std::env::current_exe() {
Ok(path) => path.display().to_string(),
Err(_) => String::new(),
}
}
/// A newer shell, if there is one (None also when this build cannot update itself).
#[tauri::command]
pub async fn update_check(app: tauri::AppHandle) -> Result<Option<UpdateInfo>, String> {
+8 -5
View File
@@ -333,17 +333,14 @@ every 6 hours (`SPORTS_SYNC=off` turns it off). It is shared by every organisati
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
fills numbers and headshots once the EHF publishes it. 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/…`) and "Cloud W17"
(`…/Seleções Nacionais/W17/…`), each created from the organisation's
destination "Cloud M19" (`/FPA/Fotos/{season}/Seleções Nacionais/M19/…`), 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`.
@@ -407,6 +404,12 @@ A match does not stop when the venue's internet does. The desktop app keeps work
photo to its server id.
- **Uploads wait instead of failing**: the queue pauses on a network error and resumes when the connection is back.
- The autopilot runs on the server when the photo arrives, and never over a person's edit (made offline first).
- **The installer replaces `/Applications/PhotoReport.app`.** A window opened from a build folder keeps that
old version and keeps offering an update. The banner says so and can open the Applications copy.
`app_executable_path` reports which copy is running.
- **EHF host checklist** (`library/ehfShots.ts`, on an EHF or W17 event): the photo count, megapixels, the
warm-up and named squad photos come from the library. Scenes the app cannot see stay unmarked until the
photographer ticks them. Those ticks stay on this computer.
## Library realtime
-16
View File
@@ -61,22 +61,6 @@ 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),
/**
-15
View File
@@ -238,21 +238,6 @@ 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/");
-5
View File
@@ -82,11 +82,6 @@ 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}",