Compare commits

...
Author SHA1 Message Date
spark 30b30ef122 Fold the under-17 friendly into the official EHF match so Portugal–Italy is listed once.
ci / rust (pull_request) Successful in 4m9s
ci / typescript (pull_request) Successful in 9m50s
The FPA camp and the EHF page were storing the same kick-off as two fixtures. An event already opened on the friendly stays on the one row.
2026-11-27 15:14:26 +00:00
spark 2fad6e96c3 Merge pull request 'Import the women's under-17 EHF EURO qualification' (#313) from task/w17-ehf-euro into main
ci / rust (push) Successful in 4m13s
ci / typescript (push) Successful in 9m47s
2026-11-27 14:33:30 +00:00
spark ae6e467103 Import the women's under-17 EHF EURO qualification so Portugal–Italy can be picked.
ci / rust (pull_request) Successful in 4m38s
ci / typescript (pull_request) Successful in 10m0s
The standing list was only the men's Euro Cup. Tonight's game is on the W17 page and never reached the event form.
2026-11-27 13:59:55 +00:00
spark 360dc5efb8 Sign in to ZeroZero again when publish returns 403
ci / rust (push) Successful in 5m52s
ci / typescript (push) Successful in 11m29s
A stale desk session answers 403. Sign in once more before accepting the refusal.
2026-11-26 22:33:59 +00:00
spark 92cecc7214 Merge pull request 'fix(delivery): idempotent retry when item leaves FAILED between render and click (BIT-33418)' (#312) from task/BIT-33418-retry-race-condition into main
ci / rust (push) Successful in 6m28s
ci / typescript (push) Successful in 11m55s
2026-11-26 22:31:41 +00:00
spark 0a845f8bc6 Sign in to ZeroZero again when publish returns 403.
ci / rust (pull_request) Successful in 6m44s
ci / typescript (pull_request) Successful in 12m48s
A stale desk session answers Insufficient permissions instead of 401. One fresh login is tried before that refusal is accepted.
2026-11-26 22:20:55 +00:00
paula-alves a9b7007d5d fix(delivery): idempotent retry when item leaves FAILED between render and click (BIT-33418)
ci / rust (pull_request) Successful in 7m10s
ci / typescript (pull_request) Successful in 12m3s
Race condition: between the desktop rendering a FAILED delivery row and the
user clicking "Repetir", the autopilot/queue worker can requeue, retry, or
retract the item. The retry endpoint's updateMany (where status=FAILED)
matched zero rows and threw notFound("failed_item_not_found") -> 404, and
the frontend promise had no .catch -> unhandledrejection -> error loop.

API: when the item no longer matches FAILED, fetch it; if it exists return
its current state (200, idempotent), only 404 when the row is gone.
Frontend: add a rejection handler that reloads the list so a stale FAILED
row refreshes instead of becoming an unhandled rejection.

Paperclip-BIT-33418
2026-11-26 22:19:13 +00:00
spark 56c115933c Do not fail a ZeroZero delivery when the account cannot publish.
ci / rust (pull_request) Successful in 4m10s
ci / typescript (pull_request) Successful in 11m13s
A photographer login may upload and still get 403 on photo-sync. The file is already on the desk, so that refusal is not a failed delivery.
2026-11-26 22:07:12 +00:00
spark 63b021cec8 Merge pull request 'Publish ZeroZero photos onto the public game after upload' (#310) from task/zerozero-publish-game into main
ci / rust (push) Successful in 4m23s
ci / typescript (push) Successful in 10m5s
2026-11-26 20:31:40 +00:00
spark 28f08bc5bc Publish ZeroZero photos onto the public game after upload.
ci / rust (pull_request) Successful in 4m15s
ci / typescript (pull_request) Successful in 10m36s
The desk keeps a file until photo-sync runs, so a delivery was done while the game stayed empty.
2026-11-26 20:11:48 +00:00
14 changed files with 723 additions and 12 deletions

No files matched your search

+7 -2
View File
@@ -392,8 +392,13 @@ export async function registerDeliveryRoutes(
where: { id: itemId, organizationId: orgId, status: "FAILED" },
data: { status: "QUEUED", attempts: 0, nextAttemptAt: new Date(), lastError: null },
});
if (!result.count) throw notFound("failed_item_not_found");
return toItemSummary(await db.deliveryItem.findUniqueOrThrow({ where: { id: itemId } }));
if (result.count) return toItemSummary(await db.deliveryItem.findUniqueOrThrow({ where: { id: itemId } }));
// Race: the item was no longer FAILED between the render and the retry (autopilot/queue worker
// requeued, retried, or retracted it). The retry is idempotent — return the current state instead
// of a 404, so the desktop does not unhandledrejection into the error loop (BIT-33418).
const current = await db.deliveryItem.findUnique({ where: { id: itemId } });
if (!current) throw notFound("item_not_found");
return toItemSummary(current);
});
/** ZeroZero: the event's game on the photo desk (chosen, or found by teams and time). */
+1
View File
@@ -175,6 +175,7 @@ export class ZerozeroTransport implements Transport {
const account = await this.client.login();
const author = meta?.author?.trim() || account.name || "PhotoReport";
const imageId = await this.client.upload(gameId, fileName, data, author);
await this.client.publish(gameId, imageId);
return `${gameId}/${imageId}`;
});
}
+145
View File
@@ -1,6 +1,45 @@
import { describe, expect, it } from "vitest";
import { TransportError } from "./transports.js";
import { ZerozeroClient } from "./zerozero.js";
/**
* A desk that is already willing to sign the client in, and answers photo-sync however the test says.
* Login is the real OAuth dance; only the publish routes vary.
*/
function desk(publish: (pathname: string) => Response): typeof fetch {
return async (input, init) => {
const url = new URL(String(input));
const method = init?.method ?? "GET";
const cookie = new Headers(init?.headers).get("cookie") ?? "";
const has = (name: string) => cookie.split(/;\s*/).some((part) => part.startsWith(`${name}=`));
if (url.hostname === "www.zerozero.pt" && url.pathname === "/oauth.php") {
if (has("zzuser")) {
return new Response(null, {
status: 302,
headers: { location: "https://fotos.zerozero.pt/api/auth/callback?code=c&state=s" },
});
}
return new Response("login", { status: 200, headers: { "set-cookie": "PHPSESSID=s; Domain=.zerozero.pt" } });
}
if (url.hostname === "www.zerozero.pt" && url.pathname === "/ax_login.php" && method === "POST") {
return new Response(JSON.stringify({ status: true }), { headers: { "set-cookie": "zzuser=1; Domain=.zerozero.pt" } });
}
if (url.pathname === "/api/auth/login") {
return Response.json({ authURL: "https://www.zerozero.pt/oauth.php?response_type=code&state=s" });
}
if (url.pathname === "/api/auth/callback") {
return new Response(null, { status: 302, headers: { location: "https://fotos.zerozero.pt/", "set-cookie": "desk=ok; Path=/" } });
}
if (url.pathname === "/api/auth/me") {
if (!has("desk")) return Response.json({ error: "unauthorized" }, { status: 401 });
return Response.json({ role: "photographer", photographer_name: "Kapta+" });
}
if (url.pathname === "/") return new Response("desk", { status: 200 });
if (method === "POST" && url.pathname.startsWith("/api/photo-sync/")) return publish(url.pathname);
return new Response("no", { status: 404 });
};
}
describe("zerozero remove", () => {
it("never asks the desk to delete a \"synced-\" placeholder (a real image is taken back: test/delivery.test.ts)", async () => {
const calls: string[] = [];
@@ -14,3 +53,109 @@ describe("zerozero remove", () => {
expect(calls).toEqual([]);
});
});
describe("zerozero publish", () => {
it("publishes the one photo that was just uploaded", async () => {
const calls: string[] = [];
const client = new ZerozeroClient(
{ username: "kapta", password: "zz-pass" },
desk((pathname) => {
calls.push(pathname);
return Response.json({ synced: 1, failed: 0, failures: [] });
}),
);
await client.publish("12627743", "img-9");
expect(calls).toEqual(["/api/photo-sync/img-9"]);
});
it("publishes the game when the account cannot publish one photo", async () => {
const calls: string[] = [];
const client = new ZerozeroClient(
{ username: "kapta", password: "zz-pass" },
desk((pathname) => {
calls.push(pathname);
if (pathname.startsWith("/api/photo-sync/match/")) return Response.json({ synced: 1, failed: 0, failures: [] });
return Response.json({ error: "forbidden" }, { status: 403 });
}),
);
await client.publish("12627743", "img-9");
expect(calls).toEqual(["/api/photo-sync/img-9", "/api/photo-sync/img-9", "/api/photo-sync/match/12627743"]);
});
it("signs in again when publish answers insufficient permissions", async () => {
const calls: string[] = [];
let refused = false;
const client = new ZerozeroClient(
{ username: "kapta", password: "zz-pass" },
desk((pathname) => {
calls.push(pathname);
if (!refused && pathname === "/api/photo-sync/img-9") {
refused = true;
return Response.json({ error: "Insufficient permissions" }, { status: 403 });
}
return Response.json({ synced: 1, failed: 0, failures: [] });
}),
);
await client.publish("12627743", "img-9");
expect(calls).toEqual(["/api/photo-sync/img-9", "/api/photo-sync/img-9"]);
});
it("publishes the whole game when the desk has no single-photo publish", async () => {
const calls: string[] = [];
const client = new ZerozeroClient(
{ username: "kapta", password: "zz-pass" },
desk((pathname) => {
calls.push(pathname);
if (pathname === "/api/photo-sync/match/12627743") return Response.json({ synced: 1, failed: 0, failures: [] });
return new Response("missing", { status: 404 });
}),
);
await client.publish("12627743", "img-9");
expect(calls).toEqual(["/api/photo-sync/img-9", "/api/photo-sync/match/12627743"]);
});
it("publishes the game when the desk already had the file and there is no image id", async () => {
const calls: string[] = [];
const client = new ZerozeroClient(
{ username: "kapta", password: "zz-pass" },
desk((pathname) => {
calls.push(pathname);
return Response.json({ synced: 0, failed: 0, failures: [] });
}),
);
await client.publish("12627743", "synced-PS_jogo_1.jpg");
expect(calls).toEqual(["/api/photo-sync/match/12627743"]);
});
it("retries when the desk reports that this photo did not publish", async () => {
const client = new ZerozeroClient(
{ username: "kapta", password: "zz-pass" },
desk(() => Response.json({ synced: 0, failed: 1, failures: [{ id: "img-9", error: "desk busy" }] })),
);
const err = await client.publish("12627743", "img-9").then(
() => null,
(error: unknown) => error,
);
expect(err).toBeInstanceOf(TransportError);
expect((err as TransportError).message).toBe("zerozero publish: desk busy");
expect((err as TransportError).transient).toBe(true);
});
it("keeps the upload when the account is not allowed to publish", async () => {
const calls: string[] = [];
const client = new ZerozeroClient(
{ username: "kapta", password: "zz-pass" },
desk((pathname) => {
calls.push(pathname);
return Response.json({ error: "Insufficient permissions" }, { status: 403 });
}),
);
await client.publish("12627743", "img-9");
expect(calls).toEqual([
"/api/photo-sync/img-9",
"/api/photo-sync/img-9",
"/api/photo-sync/match/12627743",
"/api/photo-sync/match/12627743",
]);
});
});
+103 -2
View File
@@ -11,12 +11,16 @@ import { TransportError } from "./transports.js";
* Lisbon time).
* - Upload: tus 1.0 at `/api/upload?match_id=<id>`, metadata `match_id`, `artist` (the author shown with the photo)
* and the file name. The image's id is the upload's id; `DELETE /api/images/<id>` takes it back.
* - Publish: the upload only lands on the desk. The public game shows it after `POST /api/photo-sync/<image id>`
* (the desk's "send now"). When that route is missing, `POST /api/photo-sync/match/<id>` publishes the game.
*/
export const ZEROZERO_URL = "https://fotos.zerozero.pt";
const LOGIN_SITE = "https://www.zerozero.pt";
const CHUNK = 5 * 1024 * 1024;
const TIMEOUT_MS = 60_000;
/** Publishing pushes the file onwards to the public game, which is slower than one tus chunk. */
const PUBLISH_TIMEOUT_MS = 180_000;
export interface ZerozeroGame {
id: string;
@@ -104,7 +108,7 @@ export class ZerozeroClient {
) {}
/** One request with the jar's cookies; redirects followed by hand so every hop's cookies are kept. */
private async request(url: string, init: RequestInit = {}, hops = 10): Promise<{ res: Response; url: string }> {
private async request(url: string, init: RequestInit = {}, hops = 10, timeoutMs = TIMEOUT_MS): Promise<{ res: Response; url: string }> {
let current = url;
let options = init;
for (let i = 0; i <= hops; i++) {
@@ -114,7 +118,7 @@ export class ZerozeroClient {
if (!headers.has("user-agent")) headers.set("user-agent", "PhotoReport/2 (delivery)");
let res: Response;
try {
res = await this.fetchImpl(current, { ...options, headers, redirect: "manual", signal: AbortSignal.timeout(TIMEOUT_MS) });
res = await this.fetchImpl(current, { ...options, headers, redirect: "manual", signal: AbortSignal.timeout(timeoutMs) });
} catch (err) {
throw new TransportError(`zerozero: ${fetchFailure(err)}`, true);
}
@@ -263,6 +267,78 @@ export class ZerozeroClient {
return new URL(url).pathname.split("/").filter(Boolean).pop()!;
}
/**
* Puts an uploaded photo on the public game. The desk keeps it first (`sync_status` pending); without this call
* it never leaves the photographer's page. One photo when the desk allows it, otherwise the whole game.
* `synced-<file name>` is not an image id (the desk already had the file), so the game is published.
*/
async publish(gameId: string, imageId: string): Promise<void> {
const placeholder = imageId.startsWith("synced-");
if (!placeholder) {
const one = await this.postApi(`/photo-sync/${encodeURIComponent(imageId)}`, PUBLISH_TIMEOUT_MS);
// 404/405: this desk has no single-photo publish. 403: this account may still publish the game.
if (one.status !== 404 && one.status !== 405 && one.status !== 403) {
this.assertPublished(one, imageId);
return;
}
}
const match = await this.postApi(`/photo-sync/match/${encodeURIComponent(gameId)}`, PUBLISH_TIMEOUT_MS);
// A photographer account may upload but not publish ("Insufficient permissions"). The file is already on
// the desk; failing the delivery here only blocks the queue. The desk publishes those itself.
if (match.status === 403) return;
const ours = placeholder ? null : imageId;
this.assertPublished(match, ours);
}
private async postApi(path: string, timeoutMs: number, retry = true): Promise<{ status: number; body: unknown }> {
await this.login();
// The desk's own client posts JSON. An empty object is what "send now" sends when it has no extra fields.
const { res } = await this.request(
`${this.base}/api${path}`,
{
method: "POST",
headers: { "content-type": "application/json", accept: "application/json" },
body: "{}",
},
10,
timeoutMs,
);
// 401: logged out. 403 "Insufficient permissions": the cookie is still sent, but the session is no longer
// the photographer. One fresh sign-in. The same refusal after that is the account, not a stale login.
if (res.status === 401 && retry) {
this.account = null;
this.jar.clear();
return this.postApi(path, timeoutMs, false);
}
if (res.status === 403 && retry) {
this.account = null;
this.jar.clear();
return this.postApi(path, timeoutMs, false);
}
const text = await res.text();
let body: unknown = null;
if (text) {
try {
body = JSON.parse(text) as unknown;
} catch {
body = null;
}
}
return { status: res.status, body };
}
private assertPublished(result: { status: number; body: unknown }, imageId: string | null): void {
if (result.status >= 200 && result.status < 300) {
assertSyncBody(result.body, imageId);
return;
}
const detail = errorText(result.body);
const transient = result.status >= 500 || result.status === 429 || result.status === 404;
let message = `zerozero publish: ${result.status}`;
if (detail) message = `${message} ${detail}`;
throw new TransportError(message, transient);
}
/** Takes an uploaded image back. Already gone (or no longer this account's to remove) is not an error. */
async remove(imageId: string): Promise<void> {
// "synced-<file name>" (from `upload`, when the desk already had the file) is not a real image id: there was
@@ -275,6 +351,31 @@ export class ZerozeroClient {
}
}
function errorText(body: unknown): string | null {
if (!body || typeof body !== "object") return null;
const error = (body as { error?: unknown }).error;
if (typeof error !== "string" || !error) return null;
return error.replace(/\s+/g, " ").slice(0, 180);
}
function assertSyncBody(body: unknown, imageId: string | null): void {
if (!body || typeof body !== "object") return;
const record = body as { sync_status?: unknown; syncStatus?: unknown; failures?: unknown; error?: unknown };
const status = record.sync_status ?? record.syncStatus;
if (status === "failed") {
const message = typeof record.error === "string" && record.error ? record.error : "the desk could not publish the photo";
throw new TransportError(`zerozero publish: ${message}`, true);
}
if (!imageId || !Array.isArray(record.failures)) return;
for (const failure of record.failures) {
if (!failure || typeof failure !== "object") continue;
const row = failure as { id?: unknown; error?: unknown };
if (row.id !== imageId) continue;
const message = typeof row.error === "string" && row.error ? row.error : "the desk could not publish the photo";
throw new TransportError(`zerozero publish: ${message}`, true);
}
}
function toGame(r: Record<string, unknown> | null | undefined): ZerozeroGame | null {
if (!r) return null;
const s = (v: unknown) => (typeof v === "string" || typeof v === "number" ? String(v) : null);
+36
View File
@@ -111,4 +111,40 @@ describe("EHF matches", () => {
expect(seen.some((u) => u.includes("/men/2026-27/matches/"))).toBe(true);
expect(seen.filter((u) => u.includes("GetMatches")).length).toBe(3);
});
it("reads a national standing list with the hall, the group and the kick-off", async () => {
const fetch: Fetch = async () => ({
ok: true,
status: 200,
json: async () => ({
matches: [
{
matchID: "202712010502014",
venue: {
date: { utc: "2026-11-27T19:00:00Z" },
place: { hallName: "Pavilhão da Associação Atlética de Águas Santas", cityName: "Àguas Santas" },
},
homeTeam: { team: { nationAbbreviation: "POR" } },
guestTeam: { team: { nationAbbreviation: "ITA" } },
comp: { round: { name: "Qualification Tournaments" }, group: { name: "C" } },
},
],
}),
text: async () => "",
arrayBuffer: async () => new ArrayBuffer(0),
});
const rows = await new EhfProvider(fetch, 0).euroCupMenMatches("comp", "139009");
expect(rows).toEqual([
{
matchId: "202712010502014",
startsAt: new Date("2026-11-27T19:00:00Z"),
homeNation: "POR",
awayNation: "ITA",
venue: "Pavilhão da Associação Atlética de Águas Santas",
city: "Àguas Santas",
round: "Qualification Tournaments",
group: "C",
},
]);
});
});
+10
View File
@@ -8,6 +8,8 @@ import {
nationalNamesMatch,
nationalSideFromTexts,
nationalTeamExternalId,
youthEuroRound,
youthNationalTeam,
} from "./national.js";
describe("national call-up", () => {
@@ -76,4 +78,12 @@ describe("nationalTeamExternalId", () => {
expect(nationalTeamExternalId("Roménia", "w18")).toBe("ROU-W18");
expect(nationalCountryLabel("Switzerland")).toBe("Suíça");
});
it("maps the W17 qualification nations onto youth sides", () => {
expect(youthNationalTeam("POR", "w17")).toEqual({ externalId: "W17", name: "Portugal", abbreviation: "POR" });
expect(youthNationalTeam("ITA", "w17")).toEqual({ externalId: "ITA-W17", name: "Itália", abbreviation: "ITA" });
expect(youthNationalTeam("SLO", "w17")?.externalId).toBe("SLO-W17");
expect(youthNationalTeam("FAR", "w17")?.name).toBe("Ilhas Faroé");
expect(youthEuroRound("Qualification Tournaments", "C")).toBe("Qualificação C");
});
});
+64
View File
@@ -171,6 +171,19 @@ export const EHF_EURO_CUP_MEN = {
sheetWindowMs: 3 * 86400_000,
} as const;
/**
* Women's under-17 EHF EURO 2027 qualification (Águas Santas, 27–29 Nov 2026, and the same page
* for the rest of that tournament). Same standing list and match sheet as the men's Euro Cup.
*/
export const EHF_W17_EURO = {
competitionId: "DrPEklHxLKeDu_IajXOQvA",
contentId: "139009",
externalId: "W17-EURO",
name: "W17 EHF EURO",
gender: "F" as const,
side: "w17",
} as const;
const fold = (s: string) => s.normalize("NFD").replace(/[\u0300-\u036f]/g, "").toLowerCase().replace(/\s+/g, " ").trim();
/** Same athlete across FPA call-up spelling and EHF sheet ("Iturriza" / "Iturizza", "Miguel Oliveira" / "Miguel Moreira de Oliveira"). */
@@ -231,6 +244,21 @@ export function nationalCountryLabel(raw: string): string | null {
if (/^(fra|fr|franca|france)$/.test(n)) return "França";
if (/^(ger|deu|alemanha|germany)$/.test(n)) return "Alemanha";
if (/^(swe|suecia|sweden)$/.test(n)) return "Suécia";
if (/^(ita|italy|italia)$/.test(n)) return "Itália";
if (/^(slo|svn|slovenia|eslovenia)$/.test(n)) return "Eslovénia";
if (/^(ukr|ukraine|ucrania)$/.test(n)) return "Ucrânia";
if (/^(isl|iceland|islandia)$/.test(n)) return "Islândia";
if (/^(far|fro|faroe|faroe islands|ilhas faroe)$/.test(n)) return "Ilhas Faroé";
if (/^(tur|turkey|turkiye|turquia)$/.test(n)) return "Turquia";
if (/^(isr|israel)$/.test(n)) return "Israel";
if (/^(mkd|north macedonia|macedonia do norte)$/.test(n)) return "Macedónia do Norte";
if (/^(ltu|lithuania|lituania)$/.test(n)) return "Lituânia";
if (/^(kos|kosovo)$/.test(n)) return "Kosovo";
if (/^(gre|greece|grecia)$/.test(n)) return "Grécia";
if (/^(aut|austria)$/.test(n)) return "Áustria";
if (/^(pol|poland|polonia)$/.test(n)) return "Polónia";
if (/^(fin|finland|finlandia)$/.test(n)) return "Finlândia";
if (/^(lux|luxembourg|luxemburgo)$/.test(n)) return "Luxemburgo";
return null;
}
@@ -248,6 +276,15 @@ const YOUTH_CODE: Record<string, string> = {
hungria: "HUN",
noruega: "NOR",
italia: "ITA",
ucrania: "UKR",
"ilhas faroe": "FAR",
turquia: "TUR",
israel: "ISR",
"macedonia do norte": "MKD",
lituania: "LTU",
kosovo: "KOS",
grecia: "GRE",
luxemburgo: "LUX",
polonia: "POL",
chequia: "CZE",
montenegro: "MNE",
@@ -261,6 +298,33 @@ const YOUTH_CODE: Record<string, string> = {
"paises baixos": "NED",
};
/**
* A youth national side from an EHF nation code or an English/Portuguese country name.
* Portugal's under-17 women are "W17"; Italy is "ITA-W17".
*/
export function youthNationalTeam(
nation: string | null | undefined,
side: string,
): { externalId: string; name: string; abbreviation: string } | null {
if (!nation) return null;
const name = nationalCountryLabel(nation);
if (!name) return null;
const externalId = nationalTeamExternalId(name, side);
if (!externalId) return null;
const abbreviation = YOUTH_CODE[fold(name)];
if (!abbreviation) return null;
return { externalId, name, abbreviation };
}
/** "Qualification Tournaments" + group "C" is what the picker shows as "Qualificação C". */
export function youthEuroRound(round: string | null, group: string | null): string | null {
let name = round;
if (name === "Qualification Tournaments") name = "Qualificação";
if (name && group) return `${name} ${group}`;
if (name) return name;
return group;
}
/** Which national sports team externalId fits this country + side key. */
export function nationalTeamExternalId(country: string, side: string): string | null {
const label = nationalCountryLabel(country) ?? country;
+5 -2
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 }[]> {
): Promise<{ matchId: string; startsAt: Date; homeNation: string | null; awayNation: string | null; venue: string | null; city: string | null; round: string | null; group: string | null }[]> {
const data = await get(
this.fetcher,
`https://www.eurohandball.com/umbraco/api/competitionapi/GetStandingMatches?contentId=${encodeURIComponent(contentId)}&competitionId=${encodeURIComponent(competitionId)}`,
@@ -1546,7 +1546,7 @@ export class EhfProvider {
"json",
);
const rows = Array.isArray(obj(data).matches) ? (obj(data).matches as unknown[]) : [];
const out: { matchId: string; startsAt: Date; homeNation: string | null; awayNation: string | null; venue: string | null; city: string | null }[] = [];
const out: { matchId: string; startsAt: Date; homeNation: string | null; awayNation: string | null; venue: string | null; city: string | null; round: string | null; group: string | null }[] = [];
for (const row of rows) {
const m = obj(row);
const matchId = str(m.matchID);
@@ -1557,6 +1557,7 @@ export class EhfProvider {
if (Number.isNaN(at.getTime())) continue;
const hall = str(place.hallName);
const city = str(place.cityName);
const comp = obj(m.comp);
out.push({
matchId,
startsAt: at,
@@ -1564,6 +1565,8 @@ export class EhfProvider {
awayNation: str(obj(obj(m.guestTeam).team).nationAbbreviation) ?? str(obj(obj(m.guestTeam).team).countryAbbreviation),
venue: hall,
city,
round: str(obj(comp.round).name),
group: str(obj(comp.group).name),
});
}
return out;
+161
View File
@@ -17,6 +17,7 @@ import { type ClubCandidate, type JogaClient, chooseClub, jogaCompetitionId, jog
import { sameListedPerson } from "./people.js";
import {
EHF_EURO_CUP_MEN,
EHF_W17_EURO,
ESP_M19_2026,
M19_POR_2026,
NATIONAL_SIDES,
@@ -24,6 +25,8 @@ import {
SUI_EURO_CUP_2026,
nationToSnamTeam,
nationalNamesMatch,
youthEuroRound,
youthNationalTeam,
type NationalCallUp,
} from "./national.js";
import { tallyOf, tallySquadPhotos } from "./squadPhotos.js";
@@ -615,6 +618,7 @@ export class SportsService {
const espHave = await this.deps.db.sportsPlayer.count({ where: { teamId: espM19Id, season, goneAt: null } });
if (espHave === 0) result.players += await this.saveNationalCallUp(espM19Id, season, ESP_M19_2026);
await this.applyEuroCupSheets(now, season, result);
await this.applyYouthEuros(now, season, result);
// People + reference faces: only when an event syncs these teams (`syncEventSquads`), not on every FPA refresh.
await this.fillNationalPhotos(snamId, season);
await this.fillNationalPhotos(suiId, season);
@@ -687,6 +691,20 @@ export class SportsService {
this.deps.log.info({ side: camp.side, players: camp.players.length, source: camp.sourceUrl }, "sports: youth call-up");
}
for (const game of camp.games) {
if (camp.side === EHF_W17_EURO.side) {
const homeTeamId = await this.upsertTeam("FPA", {
externalId: game.homeExternalId,
name: game.homeCountry,
abbreviation: youthAbbrev(game.homeExternalId, camp.side),
});
const awayTeamId = await this.upsertTeam("FPA", {
externalId: game.awayExternalId,
name: game.awayCountry,
abbreviation: youthAbbrev(game.awayExternalId, camp.side),
});
const listed = await this.hasOfficialYouthFixture(homeTeamId, awayTeamId, game.startsAt, EHF_W17_EURO.externalId);
if (listed) continue;
}
const comp = await this.youthCompetition(season, camp.side);
result.fixtures += await this.saveFixture(comp, "FPA", {
externalId: game.externalId,
@@ -806,6 +824,149 @@ export class SportsService {
}
}
/** The FPA camp and the EHF page can disagree by an hour and still be the same match. */
private sameKickoff(startsAt: Date) {
const slackMs = 2 * 60 * 60 * 1000;
return {
gte: new Date(startsAt.getTime() - slackMs),
lte: new Date(startsAt.getTime() + slackMs),
};
}
/** The official under-17 EURO already has this kick-off, so the camp must not add it again as a friendly. */
private async hasOfficialYouthFixture(homeTeamId: string, awayTeamId: string, startsAt: Date, competitionExternalId: string): Promise<boolean> {
const row = await this.deps.db.sportsFixture.findFirst({
where: {
homeTeamId,
awayTeamId,
startsAt: this.sameKickoff(startsAt),
competition: { externalId: competitionExternalId },
},
select: { id: true },
});
return row !== null;
}
/**
* The FPA post lists the same under-17 game as a friendly ("Sub-17 feminina"). One match, one row.
* An event already opened on the friendly keeps that row when it can become the official one.
*/
private async foldYouthFriendly(
officialCompetitionId: string,
officialExternalId: string,
homeTeamId: string,
awayTeamId: string,
startsAt: Date,
): Promise<void> {
const friendly = await this.deps.db.sportsFixture.findFirst({
where: {
homeTeamId,
awayTeamId,
startsAt: this.sameKickoff(startsAt),
competition: { provider: "FPA", externalId: { endsWith: "-AMIG" } },
},
select: { id: true },
});
if (!friendly) return;
const official = await this.deps.db.sportsFixture.findUnique({
where: { competitionId_externalId: { competitionId: officialCompetitionId, externalId: officialExternalId } },
select: { id: true },
});
if (!official) {
await this.deps.db.sportsFixture.update({
where: { id: friendly.id },
data: { competitionId: officialCompetitionId, externalId: officialExternalId },
});
return;
}
if (official.id === friendly.id) return;
await this.deps.db.event.updateMany({
where: { fixtureId: friendly.id },
data: { fixtureId: official.id },
});
await this.deps.db.sportsFixture.delete({ where: { id: friendly.id } });
}
/**
* Women's under-17 EHF EURO qualification on eurohandball.com. The whole tournament is stored so the
* picker can open Portugal–Italy (and the rest of the weekend) before the nominated sheet is published.
* The sheet, when it is out, writes shirt numbers and headshots onto W17 / ITA-W17 / …
*/
private async applyYouthEuros(now: Date, season: string, result: RefreshResult): Promise<void> {
const { db, log } = this.deps;
let matches: Awaited<ReturnType<EhfProvider["euroCupMenMatches"]>>;
try {
matches = await this.ehf.euroCupMenMatches(EHF_W17_EURO.competitionId, EHF_W17_EURO.contentId);
} catch (err) {
result.errors.push(`ehf w17: ${(err as Error).message}`);
return;
}
const listed = matches.flatMap((m) => {
const home = youthNationalTeam(m.homeNation, EHF_W17_EURO.side);
const away = youthNationalTeam(m.awayNation, EHF_W17_EURO.side);
if (!home || !away) return [];
return [{ match: m, home, away }];
});
if (!listed.length) return;
const comp = await db.sportsCompetition.upsert({
where: { provider_externalId: { provider: "FPA", externalId: EHF_W17_EURO.externalId } },
create: {
provider: "FPA",
externalId: EHF_W17_EURO.externalId,
sport: "andebol",
name: EHF_W17_EURO.name,
gender: EHF_W17_EURO.gender,
season,
},
update: { name: EHF_W17_EURO.name, gender: EHF_W17_EURO.gender, season },
});
for (const row of listed) {
const homeTeamId = await this.upsertTeam("FPA", row.home);
const awayTeamId = await this.upsertTeam("FPA", row.away);
await this.foldYouthFriendly(comp.id, row.match.matchId, homeTeamId, awayTeamId, row.match.startsAt);
result.fixtures += await this.saveFixture(comp, "FPA", {
externalId: row.match.matchId,
competition: EHF_W17_EURO.externalId,
season,
home: row.home,
away: row.away,
startsAt: row.match.startsAt,
timeKnown: true,
round: youthEuroRound(row.match.round, row.match.group),
venue: row.match.venue,
city: row.match.city,
});
}
const due = listed.filter((row) => Math.abs(row.match.startsAt.getTime() - now.getTime()) <= EHF_EURO_CUP_MEN.sheetWindowMs);
for (const row of due) {
if (this.deps.ehfDelayMs) await new Promise((r) => setTimeout(r, this.deps.ehfDelayMs));
let sheet: Awaited<ReturnType<EhfProvider["nationalSheet"]>>;
try {
sheet = await this.ehf.nationalSheet(row.match.matchId);
} catch (err) {
result.errors.push(`ehf w17 sheet ${row.match.matchId}: ${(err as Error).message}`);
continue;
}
if (!sheet) continue;
const sides = [
{ nation: sheet.homeNation, players: sheet.home },
{ nation: sheet.awayNation, players: sheet.away },
];
for (const side of sides) {
const team = youthNationalTeam(side.nation, EHF_W17_EURO.side);
if (!team) continue;
const teamId = await this.upsertTeam("FPA", team);
const field = side.players.filter((p) => p.position !== "Equipa técnica");
result.players += await this.mergeNationalSheet(teamId, season, field, []);
await this.fillNationalPhotos(teamId, season);
}
log.info(
{ matchId: row.match.matchId, home: sheet.homeNation, away: sheet.awayNation, players: sheet.home.length + sheet.away.length },
"sports: w17 sheet",
);
}
}
/**
* Write EHF sheet players onto a national team. For Portugal, keep the CIPA from the FPA call-up when the
* name matches; still take the shirt number and headshot from the sheet.
+35
View File
@@ -75,6 +75,8 @@ class FakeNextcloud {
class FakeZerozero {
logins = 0;
removed: string[] = [];
/** Paths of POST /api/photo-sync/… after each upload (the public game, not only the desk). */
syncs: string[] = [];
uploads = new Map<string, { gameId: string; meta: Record<string, string>; data: Buffer; length: number }>();
password = "zz-pass";
@@ -129,6 +131,10 @@ class FakeZerozero {
this.uploads.set(id, { gameId: url.searchParams.get("match_id")!, meta, data: Buffer.alloc(0), length: Number(h.get("upload-length")) });
return new Response(null, { status: 201, headers: { location: `/upload/${id}` } });
}
if (method === "POST" && url.pathname.startsWith("/api/photo-sync/")) {
this.syncs.push(url.pathname);
return Response.json({ synced: 1, failed: 0, failures: [] });
}
const gone = /^\/api\/images\/(.+)$/.exec(url.pathname);
if (gone && method === "DELETE") {
this.removed.push(gone[1]!);
@@ -622,6 +628,8 @@ describe("delivery", () => {
expect(first.meta).toMatchObject({ match_id: "12627747", artist: "Peter Spark / Kapta+", filename: "PS_SC Torreense x Sunderland_1.jpg", filetype: "image/jpeg" });
expect(first.data.length).toBe(first.length);
expect((await sharp(first.data).metadata()).width).toBe(3000);
// The desk upload is not the public game: each photo is published there before the delivery is done.
expect(zz.syncs).toEqual(["/api/photo-sync/img-1", "/api/photo-sync/img-2"]);
// Signed in once for the whole batch.
expect(zz.logins).toBe(1);
@@ -644,6 +652,7 @@ describe("delivery", () => {
expect(zz.removed).toEqual([itemA.remotePath!.split("/")[1]]);
// Same name ({n} kept), shown once in the game.
expect(zz.uploads.get(resent.remotePath!.split("/")[1]!)!.meta.filename).toBe(zz.uploads.get(itemA.remotePath!.split("/")[1]!)!.meta.filename);
expect(zz.syncs.at(-1)).toBe(`/api/photo-sync/${resent.remotePath!.split("/")[1]}`);
expect(await delivery.queueEdited()).toBe(0);
// A reject that bypassed the library PATCH (flag flipped in the DB) is still taken back on the next sweep.
@@ -842,6 +851,32 @@ describe("delivery", () => {
expect(broadcaster.sent.filter((s) => s.message.type === "delivery.updated").map((s) => (s.message as { item: { status: string } }).item.status)).toEqual(["QUEUED", "QUEUED", "FAILED", "DONE"]);
});
it("retry is idempotent when the item leaves FAILED between render and click (BIT-33418)", async () => {
const { orgId, token, target } = await setup();
const id = await photo("race.jpg", "2026:09:23 21:10:00");
await delivery.enqueue({ organizationId: orgId, targetId: target.id, photoIds: [id], again: false, requestedById: (await ctx.db.user.findFirstOrThrow()).id });
const [claimed] = await delivery.claim(5);
nc.status = 401;
expect(await delivery.process(claimed!)).toMatchObject({ status: "FAILED", attempts: 1 });
nc.status = undefined;
// Between the desktop rendering the FAILED row and the user clicking "Repetir", the queue worker
// requeued the item (autopilot, queueEdited, queueOrphanRetracts, …) so it is no longer FAILED.
const itemId = (await ctx.db.deliveryItem.findFirstOrThrow({ where: { photoId: id, targetId: target.id } })).id;
await ctx.db.deliveryItem.update({ where: { id: itemId }, data: { status: "QUEUED", attempts: 0, nextAttemptAt: new Date(), lastError: null } });
// The retry must not 404 — it returns the current state, so the desktop's promise resolves and no
// unhandledrejection reaches the error hub.
const retry = await ctx.app.inject({ method: "POST", url: `/v1/orgs/${orgId}/deliveries/${itemId}/retry`, headers: bearer(token) });
expect(retry.statusCode).toBe(200);
expect(retry.json()).toMatchObject({ id: itemId, status: "QUEUED", attempts: 0 });
// A truly missing item still 404s.
const ghost = await ctx.app.inject({ method: "POST", url: `/v1/orgs/${orgId}/deliveries/00000000-0000-4000-8000-000000000000/retry`, headers: bearer(token) });
expect(ghost.statusCode).toBe(404);
expect(ghost.json()).toMatchObject({ error: "item_not_found" });
});
it("writes long venues whole in IIM and XMP, flagged as UTF-8", async () => {
const src = path.join(dir, "src.jpg");
await writeFile(src, await sharp({ create: { width: 300, height: 200, channels: 3, background: "#123456" } }).jpeg().toBuffer());
+140
View File
@@ -733,6 +733,28 @@ describe("sports data service", () => {
log: quiet,
fetch: (async (url, init) => {
const u = String(url);
if (u.includes("GetStandingMatches") && u.includes("contentId=139009"))
return {
ok: true,
status: 200,
json: async () => ({
matches: [
{
matchID: "202712010502014",
venue: {
date: { utc: kick.toISOString() },
place: { hallName: "Pavilhão da Associação Atlética de Águas Santas", cityName: "Àguas Santas" },
},
homeTeam: { team: { nationAbbreviation: "POR" } },
guestTeam: { team: { nationAbbreviation: "ITA" } },
comp: { round: { name: "Qualification Tournaments" }, group: { name: "C" } },
},
],
rounds: [],
}),
text: async () => "",
arrayBuffer: async () => new ArrayBuffer(0),
};
if (u.includes("GetStandingMatches"))
return {
ok: true,
@@ -751,6 +773,45 @@ describe("sports data service", () => {
text: async () => "",
arrayBuffer: async () => new ArrayBuffer(0),
};
if (u.includes("GetMatchDetails") && u.includes("202712010502014"))
return {
ok: true,
status: 200,
json: async () => ({
matchDetails: {
details: {
homeTeam: {
team: { nationAbbreviation: "POR" },
players: [
{
id: "ehf-w17-costa",
shirtNumber: "7",
playingPosition: "Centre Back",
person: { firstName: "Maria", lastName: "Costa", nationAbbreviation: "POR" },
newPhoto: { w512: "https://res.ehf.eu/photo/w17-costa.jpg" },
},
],
officials: [],
},
guestTeam: {
team: { nationAbbreviation: "ITA" },
players: [
{
id: "ehf-w17-rossi",
shirtNumber: "9",
playingPosition: "Left Wing",
person: { firstName: "Giulia", lastName: "Rossi", nationAbbreviation: "ITA" },
newPhoto: { w512: "https://res.ehf.eu/photo/w17-rossi.jpg" },
},
],
officials: [],
},
},
},
}),
text: async () => "",
arrayBuffer: async () => new ArrayBuffer(0),
};
if (u.includes("GetMatchDetails") && u.includes("202811130101002"))
return {
ok: true,
@@ -848,6 +909,85 @@ describe("sports data service", () => {
expect(friendly?.startsAt.toISOString()).toBe("2026-11-05T20:00:00.000Z");
expect(friendly?.venue).toBe("Pavilhão Municipal Fernando Lima");
expect(friendly?.city).toBe("Caminha");
const w17 = await ctx.db.sportsFixture.findFirst({
where: { externalId: "202712010502014" },
include: { homeTeam: true, awayTeam: true, competition: true },
});
expect(w17?.competition.name).toBe("W17 EHF EURO");
expect(w17?.competition.gender).toBe("F");
expect(w17?.round).toBe("Qualificação C");
expect(w17?.venue).toBe("Pavilhão da Associação Atlética de Águas Santas");
expect(w17?.city).toBe("Àguas Santas");
expect(w17?.homeTeam.externalId).toBe("W17");
expect(w17?.homeTeam.name).toBe("Portugal");
expect(w17?.awayTeam.externalId).toBe("ITA-W17");
expect(w17?.awayTeam.name).toBe("Itália");
expect(await ctx.db.sportsPlayer.findFirstOrThrow({ where: { teamId: w17!.homeTeam.id, name: "Maria Costa" } })).toMatchObject({
number: "7",
photoUrl: "https://res.ehf.eu/photo/w17-costa.jpg",
});
expect(await ctx.db.sportsPlayer.findFirstOrThrow({ where: { teamId: w17!.awayTeam.id, name: "Giulia Rossi" } })).toMatchObject({
number: "9",
externalId: "ehf-w17-rossi",
});
const { org } = await seedUser(ctx.db, "[email protected]", { org: "w17dup", role: "OWNER" });
const friendlyComp = await ctx.db.sportsCompetition.create({
data: { provider: "FPA", externalId: "W17-AMIG", sport: "andebol", name: "Sub-17 feminina", gender: "F", season: w17!.season },
});
const duplicate = await ctx.db.sportsFixture.create({
data: {
competitionId: friendlyComp.id,
externalId: "w17-por-ita-20261127",
season: w17!.season,
homeTeamId: w17!.homeTeam.id,
awayTeamId: w17!.awayTeam.id,
startsAt: w17!.startsAt,
timeKnown: true,
round: "Particular",
},
});
const opened = await ctx.db.event.create({
data: {
organizationId: org!.id,
home: "Portugal",
away: "Itália",
startsAt: w17!.startsAt,
ingestFrom: w17!.startsAt,
ingestUntil: w17!.startsAt,
iptcTemplate: {},
fixtureId: duplicate.id,
},
});
await sports.syncNationalCallUps(kick);
const paired = await ctx.db.sportsFixture.findMany({
where: { homeTeamId: w17!.homeTeam.id, awayTeamId: w17!.awayTeam.id, startsAt: w17!.startsAt },
});
expect(paired.map((row) => row.externalId)).toEqual(["202712010502014"]);
expect((await ctx.db.event.findUniqueOrThrow({ where: { id: opened.id } })).fixtureId).toBe(w17!.id);
await ctx.db.sportsFixture.delete({ where: { id: w17!.id } });
const campOnly = await ctx.db.sportsFixture.create({
data: {
competitionId: friendlyComp.id,
externalId: "w17-por-ita-20261127",
season: w17!.season,
homeTeamId: w17!.homeTeam.id,
awayTeamId: w17!.awayTeam.id,
startsAt: w17!.startsAt,
timeKnown: true,
round: "Particular",
},
});
await ctx.db.event.update({ where: { id: opened.id }, data: { fixtureId: campOnly.id } });
await sports.syncNationalCallUps(kick);
const adopted = await ctx.db.sportsFixture.findMany({
where: { homeTeamId: w17!.homeTeam.id, awayTeamId: w17!.awayTeam.id, startsAt: w17!.startsAt },
include: { competition: true },
});
expect(adopted).toHaveLength(1);
expect(adopted[0]).toMatchObject({ id: campOnly.id, externalId: "202712010502014", competition: { name: "W17 EHF EURO" } });
expect((await ctx.db.event.findUniqueOrThrow({ where: { id: opened.id } })).fixtureId).toBe(campOnly.id);
});
});
+1 -1
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) e UEFA (Champions, Liga Europa, Conference, Champions feminina e de futsal) dos próximos dias (ao pesquisar, também os dos últimos 10 dias). Preenche o evento e junta os plantéis às pessoas. As fotos de 2 h antes até 4 h depois do apito vão para este evento.",
pickMatchHelp: "Jogos da Liga Portugal, FPF, FPA, EHF Euro Cup (seleções), W17 EHF EURO (qualificação de sub-17 feminina) e UEFA (Champions, Liga Europa, Conference, Champions feminina e de futsal) dos próximos dias (ao pesquisar, também os dos últimos 10 dias). Preenche o evento e junta os plantéis às pessoas. As fotos de 2 h antes até 4 h depois do apito vão para este evento.",
squadFromMatch: "Usar o plantel de um jogo",
squadFromMatchHelp: "Treino ou sessão: fica com os jogadores desse jogo, sem ser o jogo (legenda e hora são as tuas).",
searchMatch: "Equipa, competição ou pavilhão",
+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)}>
<button className="pr-quiet" onClick={() => void api.retryDelivery(orgId, i.id).then(load, () => load())}>
{t.retry}
</button>
)}
+14 -4
View File
@@ -330,7 +330,12 @@ every 6 hours (`SPORTS_SYNC=off` turns it off). It is shared by every organisati
sides (`M19`, `ESP-M19`), and merges the Men's EHF EURO Cup match sheets from `www.eurohandball.com`
(`GetStandingMatches` / `GetMatchDetails` — same shape as club sheets, with shirt numbers and `res.ehf.eu`
headshots for the nominated 16). Portuguese CIPAs from the FPA call-up stay as `externalId` when the name
matches; photo/number come from the sheet. Youth camps (sub-17, sub-19, sub-20, men or women) come from
matches; photo/number come from the sheet. The same pass reads the Women's U17 EHF EURO qualification
(`W17-EURO`, content `139009`: Portugal–Italy `202712010502014`, 27 Nov 2026 19:00 in Águas Santas, and the
rest of that tournament). Portugal is team `W17`; every other country is `<code>-W17` (Italy is `ITA-W17`). The nominated sheet
fills numbers and headshots once the EHF publishes it. The FPA camp lists that same match as a friendly
(`Sub-17 feminina`): it is folded into `W17-EURO`, and an event already opened on it stays on the one fixture.
Youth camps (sub-17, sub-19, sub-20, men or women) come from
recent posts on `portal.fpa.pt`: the call-up PDF (CIPA, no shirt number from the list order) and the
"Jogos Particulares" calendar. A sheet with a real squad replaces that age group; a post the site does not
return leaves the plantel we already have. The November 2026 M19 list and the Spain name list are only the
@@ -474,9 +479,14 @@ The same queue also delivers to SFTP, FTP/FTPS and Dropbox (`delivery/transports
- **ZeroZero** (`fotos.zerozero.pt`, `delivery/zerozero.ts`): the photographer's zerozero.pt account. The server
signs in through zerozero.pt's OAuth (`/api/auth/login` → `oauth.php` → `ax_login.php` → `/api/auth/callback`,
cookies kept in a small jar), and uploads with tus to `/api/upload?match_id=<game>` with the file name and the
author (`artist`: the photographer's name from the IPTC creator). The "folder" is the game: chosen for the
event by pasting the game's link (kept in `events.zerozero_game_id`), or found among the desk's upcoming games
by both teams and kick-off within 3 hours. The delivered item's remote path is `<game>/<image id>`
author (`artist`: the photographer's name from the IPTC creator). The upload only reaches the photographer's
desk. The public game shows the photo after publish: `POST /api/photo-sync/<image id>`, or
`POST /api/photo-sync/match/<game>` when the desk has no single-image publish (the same call as
"Sincronizar com zerozero"). A 403 signs in again once (a stale session uses that status, not 401). The same
refusal after the new login still counts as delivered: the file is on the desk. Any other publish failure fails
the delivery. The "folder" is the game:
chosen for the event by pasting the game's link (kept in `events.zerozero_game_id`), or found among the desk's
upcoming games by both teams and kick-off within 3 hours. The delivered item's remote path is `<game>/<image id>`
(`DELETE /api/images/<id>` takes it back).
Each target also has Photo Mechanic's uploader output options: fit-in-box size, JPEG quality, output