From 6d4bb4f19e5ee25af53efaeb942a1f21f9c14c09 Mon Sep 17 00:00:00 2001 From: spark Date: Fri, 20 Nov 2026 18:14:30 +0000 Subject: [PATCH 1/2] =?UTF-8?q?Seed=20Ta=C3=A7a=20de=20Portugal=20in=20the?= =?UTF-8?q?=20sports=20catalogue=20and=20parse=20FPF=20Details=20fixtures.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The cup is FPF (not Liga Portugal); without it the event picker only showed handball. Also fix kick-off parsing when day and time are stuck together in the HTML. --- apps/api/src/sports/fpf.test.ts | 68 +++++++++++++++++++++++ apps/api/src/sports/providers.ts | 92 ++++++++++++++++++++++++++++++-- apps/api/src/sports/service.ts | 12 +++++ apps/api/test/sports.test.ts | 3 +- docs/ARCHITECTURE.md | 6 ++- 5 files changed, 173 insertions(+), 8 deletions(-) create mode 100644 apps/api/src/sports/fpf.test.ts diff --git a/apps/api/src/sports/fpf.test.ts b/apps/api/src/sports/fpf.test.ts new file mode 100644 index 0000000..d8bb780 --- /dev/null +++ b/apps/api/src/sports/fpf.test.ts @@ -0,0 +1,68 @@ +import * as cheerio from "cheerio"; +import { describe, expect, it } from "vitest"; +import { fpfDate, fpfSeasonId, parseFpfDetailsFixtures } from "./providers.js"; + +describe("FPF catalogue helpers", () => { + it("maps the football season to FPF's seasonId", () => { + expect(fpfSeasonId(new Date("2026-11-20T12:00:00Z"))).toBe("106"); + expect(fpfSeasonId(new Date("2027-08-01T12:00:00Z"))).toBe("107"); + }); + + it("reads the kick-off when the day and time are stuck together", () => { + const now = new Date("2026-11-20T12:00:00Z"); + expect(fpfDate("20 nov20:45", now)).toMatchObject({ timeKnown: true }); + expect(fpfDate("20 nov20:45", now)!.at.toISOString()).toBe("2026-11-20T20:45:00.000Z"); + }); + + it("reads Taça-style Details games without GetClassification links", () => { + const html = ` +

TAÇA DE PORTUGAL

+
+
4.ª Eliminatória
+
+
+
Fc Porto Sad
+ 20 nov
20:45
+
Usc Paredes
+
+
Estadio Do Dragao
+
+
Vencedor Jogo A x B
+ 16 dez
15:00
+
Vencedor Jogo C x D
+
+
Recinto A Indicar
+ +
+
Sporting Cp Sad
+ 21 nov
18:00
+
União D. Serra
+
+
Estádio José Alvalade
+
+
+
`; + const fixtures = parseFpfDetailsFixtures(cheerio.load(html), { + competitionId: "25263", + seasonId: "106", + competitionName: "Taça de Portugal", + now: new Date("2026-11-20T12:00:00Z"), + }); + expect(fixtures).toHaveLength(2); + expect(fixtures[0]).toMatchObject({ + home: { name: "Fc Porto Sad" }, + away: { name: "Usc Paredes" }, + timeKnown: true, + round: "4.ª Eliminatória", + venue: "Estadio Do Dragao", + }); + expect(fixtures[0]!.startsAt.toISOString()).toBe("2026-11-20T20:45:00.000Z"); + expect(fixtures[0]!.externalId).toContain("25263-"); + expect(fixtures[1]).toMatchObject({ + externalId: "2687999", + home: { name: "Sporting Cp Sad" }, + away: { name: "União D. Serra" }, + venue: "Estádio José Alvalade", + }); + }); +}); diff --git a/apps/api/src/sports/providers.ts b/apps/api/src/sports/providers.ts index 254ba17..88d2130 100644 --- a/apps/api/src/sports/providers.ts +++ b/apps/api/src/sports/providers.ts @@ -894,11 +894,81 @@ function fpaFixture(r: Record): FixtureData | null { // --- FPF (resultados.fpf.pt, HTML) -------------------------------------------------------------------------------- +/** + * Competitions we always follow. The Taça de Portugal is FPF's (not Liga Portugal's calendar). `externalId` is the + * resultados.fpf.pt competitionId; the seasonId advances with {@link fpfSeasonId}. + */ +export const FPF_COMPETITIONS = [{ externalId: "25263", name: "Taça de Portugal", gender: "M" }] as const; + +/** FPF's seasonId: 106 is 2026/27. Advances by one each July. */ +export function fpfSeasonId(now = new Date()): string { + const start = Number(seasonOf(now).slice(0, 4)); + return String(106 + (start - 2026)); +} + const MONTHS: Record = { jan: 1, fev: 2, mar: 3, abr: 4, mai: 5, jun: 6, jul: 7, ago: 8, set: 9, out: 10, nov: 11, dez: 12 }; +/** "Vencedor Jogo …" on a later round: not a real club yet. */ +function isFpfUndecidedSide(name: string): boolean { + return /^vencedor\b/i.test(name.trim()); +} + +/** + * Games listed on the competition Details page (accordion rounds). Some rounds wrap each game in a match link; + * others (e.g. Taça 4.ª eliminatória) only print the teams and kick-off — then the id is derived from the kick-off + * and the two clubs so a re-read stays stable. + */ +export function parseFpfDetailsFixtures( + $: cheerio.CheerioAPI, + opts: { competitionId: string; seasonId: string; competitionName: string; now?: Date }, +): FixtureData[] { + const now = opts.now ?? new Date(); + const out: FixtureData[] = []; + const items = $(".accordion-item"); + const roots = items.length ? items.toArray() : [$.root().get(0)!].filter(Boolean); + for (const item of roots) { + const root = $(item); + const roundLabel = root.find(".accordion-title").first().text().replace(/\s+/g, " ").trim() || null; + root.find(".game").each((_, gameEl) => { + const game = $(gameEl); + const homeName = game.find(".home-team").first().text().replace(/\s+/g, " ").trim(); + const awayName = game.find(".away-team").first().text().replace(/\s+/g, " ").trim(); + if (!homeName || !awayName) return; + if (isFpfUndecidedSide(homeName) || isFpfUndecidedSide(awayName)) return; + const when = fpfDate(game.find(".game-schedule").text(), now); + if (!when) return; + const parentLink = game.closest("a.game-link"); + const matchId = parentLink.length ? /matchId=(\d+)/i.exec(parentLink.attr("href") ?? "")?.[1] ?? null : null; + const stadiumText = parentLink.length + ? parentLink.find(".game-list-stadium small").first().text().trim() + : game.nextAll(".game-list-stadium").first().find("small").text().trim(); + const score = /(\d+)\s*-\s*(\d+)/.exec(game.find(".score span").first().text()); + const home = { externalId: slugify(homeName), name: homeName }; + const away = { externalId: slugify(awayName), name: awayName }; + const stamp = when.at.toISOString().slice(0, 16).replace(/[-:T]/g, ""); + out.push({ + externalId: matchId ?? `${opts.competitionId}-${stamp}-${home.externalId}-${away.externalId}`, + competition: opts.competitionId, + competitionName: opts.competitionName, + season: opts.seasonId, + home, + away, + startsAt: when.at, + timeKnown: when.timeKnown, + round: roundLabel, + ...fpfPlace(stadiumText), + homeScore: score ? Number(score[1]) : null, + awayScore: score ? Number(score[2]) : null, + }); + }); + } + return out; +} + /** "12 out 15:00" (no year on the site): the year that puts it nearest to `now`. */ export function fpfDate(text: string, now: Date): { at: Date; timeKnown: boolean } | null { - const m = /(\d{1,2})\s*(?:de\s+)?([a-zç]{3})[a-zç]*\.?(?:\s+(\d{4}))?(?:\D+(\d{1,2}:\d{2}))?/i.exec(text.toLowerCase()); + // Cheerio's .text() on "20 nov
20:45" can yield "20 nov20:45" with no space before the time. + const m = /(\d{1,2})\s*(?:de\s+)?([a-zç]{3})[a-zç]*\.?(?:\s+(\d{4}))?(?:\D*(\d{1,2}:\d{2}))?/i.exec(text.toLowerCase().replace(/\s+/g, " ").trim()); if (!m) return null; const month = MONTHS[m[2]!.slice(0, 3)]; if (!month) return null; @@ -948,6 +1018,14 @@ export class FpfProvider { for (const m of ($.html().match(/GetClassificationAndMatchesByFixture\?fixtureId=(\d+)/g) ?? [])) rounds.add(m.replace(/\D/g, "")); const teams = new Map(); const fixtures: FixtureData[] = []; + const seen = new Set(); + const addFixture = (f: FixtureData) => { + if (seen.has(f.externalId)) return; + seen.add(f.externalId); + teams.set(f.home.externalId, f.home); + teams.set(f.away.externalId, f.away); + fixtures.push(f); + }; let n = 0; for (const round of rounds) { n++; @@ -959,14 +1037,13 @@ export class FpfProvider { const homeName = game.find(".home-team").text().trim(); const awayName = game.find(".away-team").text().trim(); if (!matchId || !homeName || !awayName) return; + if (isFpfUndecidedSide(homeName) || isFpfUndecidedSide(awayName)) return; const home = { externalId: slugify(homeName), name: homeName }; const away = { externalId: slugify(awayName), name: awayName }; - teams.set(home.externalId, home); - teams.set(away.externalId, away); const when = fpfDate(game.find(".game-schedule").text(), now); if (!when) return; const score = /(\d+)\s*-\s*(\d+)/.exec(game.find(".score span").first().text()); - fixtures.push({ + addFixture({ externalId: matchId, competition: competitionId, competitionName: name, @@ -976,12 +1053,17 @@ export class FpfProvider { startsAt: when.at, timeKnown: when.timeKnown, round: roundLabel, - ...fpfPlace(r(link).next(".game-list-stadium").find("small").text().trim()), + ...fpfPlace(r(link).find(".game-list-stadium small").first().text().trim() || r(link).next(".game-list-stadium").find("small").text().trim()), homeScore: score ? Number(score[1]) : null, awayScore: score ? Number(score[2]) : null, }); }); } + // Cups such as the Taça de Portugal list rounds on the Details page (accordion) and often omit the + // GetClassificationAndMatchesByFixture links the older divisions use. Read those games too. + for (const f of parseFpfDetailsFixtures($, { competitionId, seasonId, competitionName: name, now })) { + addFixture(f); + } return { name, teams: [...teams.values()], fixtures }; } diff --git a/apps/api/src/sports/service.ts b/apps/api/src/sports/service.ts index cce3527..fca0b93 100644 --- a/apps/api/src/sports/service.ts +++ b/apps/api/src/sports/service.ts @@ -37,6 +37,8 @@ import { fpaShortName, lisbonTime, FpfProvider, + FPF_COMPETITIONS, + fpfSeasonId, LIGA_COMPETITIONS, type LigaClubCompetition, LigaProvider, @@ -158,6 +160,16 @@ export class SportsService { await this.deps.db.sportsCompetition.create({ data: { provider: "EHF", externalId: c.externalId, sport: "andebol", name: c.name, gender: c.gender, season } }); else if (existing.season < season) await this.deps.db.sportsCompetition.update({ where: { id: existing.id }, data: { season, lastIngestAt: null } }); } + const fpfSeason = fpfSeasonId(now); + for (const c of FPF_COMPETITIONS) { + const existing = await this.deps.db.sportsCompetition.findUnique({ where: { provider_externalId: { provider: "FPF", externalId: c.externalId } } }); + if (!existing) + await this.deps.db.sportsCompetition.create({ + data: { provider: "FPF", externalId: c.externalId, sport: "futebol", name: c.name, gender: c.gender, season: fpfSeason }, + }); + else if (existing.season !== fpfSeason) + await this.deps.db.sportsCompetition.update({ where: { id: existing.id }, data: { season: fpfSeason, lastIngestAt: null } }); + } } private due(c: SportsCompetition, now: Date): boolean { diff --git a/apps/api/test/sports.test.ts b/apps/api/test/sports.test.ts index f5c91f7..05853bb 100644 --- a/apps/api/test/sports.test.ts +++ b/apps/api/test/sports.test.ts @@ -5,7 +5,7 @@ import { CodeGeneratorSettings } from "@photoreport/contracts"; import sharp from "sharp"; import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest"; import { BLOCK_START, buildCodeLines, mergeGenerated, teamPrefix, toTsv } from "../src/sports/codegen.js"; -import { type Fetch, fpaEpochFor, fpaProva, fpaShortName, fpfDate, lisbonTime, parseFpaBoletim, parseFpaClubTerms, parseFpaMatchPage, parseFpaReferees, parseFpfLineups, seasonOf } from "../src/sports/providers.js"; +import { type Fetch, fpaEpochFor, fpaProva, fpaShortName, fpfDate, fpfSeasonId, lisbonTime, parseFpaBoletim, parseFpaClubTerms, parseFpaMatchPage, parseFpaReferees, parseFpfLineups, seasonOf } from "../src/sports/providers.js"; import { SportsService } from "../src/sports/service.js"; import { LocalStorage, UrlSigner } from "../src/storage/storage.js"; import { bearer, createTestApp, login, resetDb, seedUser, type TestContext } from "./helpers.js"; @@ -111,6 +111,7 @@ describe("federation data", () => { const now = new Date("2026-12-20T12:00:00Z"); expect(fpfDate("10 jan 15:00", now)!.at.toISOString()).toBe("2027-01-10T15:00:00.000Z"); expect(fpfDate("12 out", now)).toMatchObject({ timeKnown: false }); + expect(fpfSeasonId(new Date("2026-11-20T12:00:00Z"))).toBe("106"); const sheet = ["Equipas Iniciais", ...Array.from({ length: 22 }, (_, i) => `${i + 1} Jogador ${i + 1}${i === 0 ? " (GR)" : ""}`), "Suplentes", "30 Suplente A", "31 Suplente B", "Treinadores"].join("\n"); const { home, away } = parseFpfLineups(sheet); expect(home).toHaveLength(12); diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index cd67343..5042383 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -341,8 +341,10 @@ every 6 hours (`SPORTS_SYNC=off` turns it off). It is shared by every organisati existing FPA Nextcloud account and never sent on arrival. FPA licence or an older EHF club photo fills gaps. People and reference faces are created when the event syncs those teams (`POST …/squads/sync`), not on every sports refresh. Example match: Portugal–Switzerland `202811130101002`. -- **FPF** (`resultados.fpf.pt`, HTML): competitions are added by link. It gives teams and fixtures, and squads - from each match sheet, read from 1 h before to 2 h after kick-off. +- **FPF** (`resultados.fpf.pt`, HTML): the Taça de Portugal is seeded in the catalogue; other competitions are + added by link. It gives teams and fixtures (Details page and round sheets), and squads from each match sheet, + read from 1 h before to 2 h after kick-off. The federation's Cloudflare challenge blocks datacentre IPs: when + the worker cannot reach the site, fixtures must be seeded another way until the IP is allowed or a proxy is set. - **EHF** (the JSON `ehfcl`, `ehfel` and `ehfec.eurohandball.com` read; not a documented API): men's and women's Champions League, European League and European Cup. Fixtures with venue, and squads from the match sheet once it is published: the nominated players (number, position, photo) and the bench staff (letters A, B, …; the sheet -- 2.47.3 From bdbb5c364a48cbcfe8ad7afb087b44aae954d1b1 Mon Sep 17 00:00:00 2001 From: spark Date: Fri, 20 Nov 2026 18:34:10 +0000 Subject: [PATCH 2/2] =?UTF-8?q?test(sports):=20serve=20FPF=20Ta=C3=A7a=20D?= =?UTF-8?q?etails=20in=20the=20fake=20site=20and=20expect=20the=20seeded?= =?UTF-8?q?=20FPF=20competition?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Sonnet 5.5 --- apps/api/test/sports.test.ts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/apps/api/test/sports.test.ts b/apps/api/test/sports.test.ts index 05853bb..0e805b2 100644 --- a/apps/api/test/sports.test.ts +++ b/apps/api/test/sports.test.ts @@ -233,6 +233,7 @@ const fakeSites = (state: { benfica: { shirtNumber: number; name: string; photos const u = new URL(url); const json = (body: unknown) => ({ ok: true, status: 200, json: async () => body, text: async () => JSON.stringify(body), arrayBuffer: async () => new ArrayBuffer(0) }); const bytes = (b: Buffer) => ({ ok: true, status: 200, json: async () => ({}), text: async () => b.toString("latin1"), arrayBuffer: async () => b.buffer.slice(b.byteOffset, b.byteOffset + b.byteLength) as ArrayBuffer }); + if (u.host === "resultados.fpf.pt" && u.pathname === "/Competition/Details") return bytes(Buffer.from("

TAÇA DE PORTUGAL

", "utf8")); if (state.handball && u.host === "ws.fpa.pt" && u.pathname.includes("getJogosClubeEpocaEscalao")) return json(u.pathname.endsWith("/140/374/4") ? [fpaGame("323264", "2026-09-23", VITORIA, AGUAS, [33, 29]), fpaGame("323500", "2026-10-17", VITORIA, AGUAS, null)] : []); if (state.handball && u.host === "portal.fpa.pt" && u.pathname.startsWith("/clube/id/")) return bytes(Buffer.from(CLUB_PAGE, "utf8")); @@ -373,7 +374,8 @@ describe("sports data service", () => { const r = await sports.refreshDue(now); expect(r.errors).toEqual([]); const comps = await ctx.db.sportsCompetition.findMany({ orderBy: { name: "asc" } }); - expect(comps.map((c) => [c.provider, c.externalId, c.season])).toEqual([ + expect(comps.filter((c) => c.provider === "FPF").map((c) => [c.externalId, c.season])).toEqual([["25263", "106"]]); + expect(comps.filter((c) => c.provider !== "FPF").map((c) => [c.provider, c.externalId, c.season])).toEqual([ ["LIGA", "allianzcup", "20262027"], ["FPA", "PO09", "20262027"], ["EHF", "cl-men", "20262027"], -- 2.47.3