Compare commits

..
Author SHA1 Message Date
spark 5794660694 Stop an expired event pin from filing later shots into its folder.
When the pin is gone from the agenda and its ingest window has closed, arrivals follow the capture time instead of the old event.
2026-11-26 22:39:55 +00:00
23 changed files with 86 additions and 871 deletions

No files matched your search

+2 -7
View File
@@ -392,13 +392,8 @@ export async function registerDeliveryRoutes(
where: { id: itemId, organizationId: orgId, status: "FAILED" },
data: { status: "QUEUED", attempts: 0, nextAttemptAt: new Date(), lastError: null },
});
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);
if (!result.count) throw notFound("failed_item_not_found");
return toItemSummary(await db.deliveryItem.findUniqueOrThrow({ where: { id: itemId } }));
});
/** ZeroZero: the event's game on the photo desk (chosen, or found by teams and time). */
-36
View File
@@ -111,40 +111,4 @@ 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",
},
]);
});
});
-10
View File
@@ -8,8 +8,6 @@ import {
nationalNamesMatch,
nationalSideFromTexts,
nationalTeamExternalId,
youthEuroRound,
youthNationalTeam,
} from "./national.js";
describe("national call-up", () => {
@@ -78,12 +76,4 @@ 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");
});
});
-64
View File
@@ -171,19 +171,6 @@ 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"). */
@@ -244,21 +231,6 @@ 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;
}
@@ -276,15 +248,6 @@ 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",
@@ -298,33 +261,6 @@ 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;
+2 -5
View File
@@ -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; round: string | null; group: string | null }[]> {
): Promise<{ matchId: string; startsAt: Date; homeNation: string | null; awayNation: string | null; venue: string | null; city: 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; round: string | null; group: string | null }[] = [];
const out: { matchId: string; startsAt: Date; homeNation: string | null; awayNation: string | null; venue: string | null; city: string | null }[] = [];
for (const row of rows) {
const m = obj(row);
const matchId = str(m.matchID);
@@ -1557,7 +1557,6 @@ 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,
@@ -1565,8 +1564,6 @@ 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;
-81
View File
@@ -17,7 +17,6 @@ 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,
@@ -25,8 +24,6 @@ import {
SUI_EURO_CUP_2026,
nationToSnamTeam,
nationalNamesMatch,
youthEuroRound,
youthNationalTeam,
type NationalCallUp,
} from "./national.js";
import { tallyOf, tallySquadPhotos } from "./squadPhotos.js";
@@ -618,7 +615,6 @@ 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);
@@ -810,83 +806,6 @@ export class SportsService {
}
}
/**
* 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) {
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.
-26
View File
@@ -851,32 +851,6 @@ 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());
-82
View File
@@ -733,28 +733,6 @@ 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,
@@ -773,45 +751,6 @@ 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,
@@ -909,27 +848,6 @@ 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",
});
});
});
+1 -27
View File
@@ -119,23 +119,7 @@ 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;
@@ -220,24 +204,14 @@ 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>}
{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`}
className="ml-auto h-7 bg-accent px-3 text-[12px] font-semibold text-white hover:bg-accent-strong"
onClick={() => void open(manual.installer!)}
>
{t.update.download}
-21
View File
@@ -92,27 +92,6 @@ 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} />);
+2 -4
View File
@@ -713,7 +713,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), 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.",
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.",
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",
@@ -912,9 +912,7 @@ 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: "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.`,
manual: "Esta instalação não se atualiza sozinha: descarrega o instalador e abre-o (só desta vez).",
download: "Descarregar instalador",
later: "Mais tarde",
uiReady: "Nova versão da interface descarregada. Fica ativa ao recarregar (ou no próximo arranque).",
-136
View File
@@ -1,136 +0,0 @@
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>;
}
+12 -3
View File
@@ -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, lisbonInstant, localPhoto, localPhotos } from "../offline/local.js";
import { eventForArrival, exifDateTime, exifLens, lisbonDay, 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,6 +89,12 @@ 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;
@@ -177,7 +183,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);
const eventId = eventForArrival(to?.id ?? null, events, capturedAt, pinWindow(to));
const filed = events.find((e) => e.id === eventId);
if (!localPhotos.bySha(info.sha256)) {
let url = "";
@@ -239,9 +245,12 @@ 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 (no capture time, or this computer has not seen the event).
// The pin is not in the cached list and its window still covers this shot.
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(() => {
+16 -5
View File
@@ -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, lisbonInstant } from "../offline/local.js";
import { eventForArrival, exifDateTime, lisbonDay, 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 } from "./LocalFtp.js";
import { type FtpTarget, type IncomingFile, type Invoke, eventLabel, pinWindow } 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,16 +103,27 @@ 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);
const eventId = eventForArrival(to?.id ?? null, events, capturedAt, pinWindow(to));
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: filed ? eventLabel(filed) : (to?.title ?? ""),
date: filed ? filed.startsAt.slice(0, 10) : (to?.date ?? ""),
event: sentEvent,
date: sentDate,
})
.then(() => {
retryPhotoFile(original.sha256);
-70
View File
@@ -1,70 +0,0 @@
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
@@ -1,266 +0,0 @@
/**
* 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;
}
+29 -3
View File
@@ -102,6 +102,16 @@ 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})/);
@@ -137,19 +147,35 @@ 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): string | null {
export function eventForArrival(
pinnedId: string | null,
events: RoutedEvent[],
at: string | null,
pinWindow?: { ingestFrom: string; ingestUntil: string } | null,
): string | null {
if (!at) return pinnedId;
if (!pinnedId) return routeLocally(events, at);
const pinned = events.find((e) => e.id === pinnedId);
if (!pinned) {
// Agenda cache miss: keep the open pin so USB/FTP does not dump live shots into Sem evento.
return pinnedId;
if (windowCovers(pinWindow, at)) return pinnedId;
return routeLocally(events, at);
}
if (pinned.archivedAt) return routeLocally(events, at);
const t = Date.parse(at);
+20 -1
View File
@@ -150,8 +150,27 @@ 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 (do not dump into Sem evento); archived pins fall through to the clock.
// Cache miss for the pin id: keep it while its window is unknown or still open.
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");
});
+1 -1
View File
@@ -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, () => load())}>
<button className="pr-quiet" onClick={() => void api.retryDelivery(orgId, i.id).then(load)}>
{t.retry}
</button>
)}
-2
View File
@@ -29,7 +29,6 @@ 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";
@@ -967,7 +966,6 @@ 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,7 +180,6 @@ 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,16 +48,6 @@ 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> {
+1 -10
View File
@@ -330,10 +330,7 @@ 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. 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. Youth camps (sub-17, sub-19, sub-20, men or women) come from
matches; photo/number come from the sheet. 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
@@ -404,12 +401,6 @@ 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