Seed Taça de Portugal in the sports catalogue and parse FPF Details fixtures.
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.
This commit is contained in:
1 parent
7c0e92b5ae
commit
6d4bb4f19e
5 files changed
+173
-8
No files matched your search
@@ -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 = `
|
||||
<h2>TAÇA DE PORTUGAL</h2>
|
||||
<div class="accordion-item">
|
||||
<div class="accordion-title">4.ª Eliminatória</div>
|
||||
<div class="accordion-content">
|
||||
<div class="game">
|
||||
<div class="home-team">Fc Porto Sad</div>
|
||||
<span class="game-schedule">20 nov<br />20:45</span>
|
||||
<div class="away-team">Usc Paredes</div>
|
||||
</div>
|
||||
<div class="game-list-stadium"><small>Estadio Do Dragao</small></div>
|
||||
<div class="game">
|
||||
<div class="home-team">Vencedor Jogo A x B</div>
|
||||
<span class="game-schedule">16 dez<br />15:00</span>
|
||||
<div class="away-team">Vencedor Jogo C x D</div>
|
||||
</div>
|
||||
<div class="game-list-stadium"><small>Recinto A Indicar</small></div>
|
||||
<a class="game-link" href="/Match/GetMatchInformation?matchId=2687999">
|
||||
<div class="game">
|
||||
<div class="home-team">Sporting Cp Sad</div>
|
||||
<span class="game-schedule">21 nov<br />18:00</span>
|
||||
<div class="away-team">União D. Serra</div>
|
||||
</div>
|
||||
<div class="game-list-stadium"><small>Estádio José Alvalade</small></div>
|
||||
</a>
|
||||
</div>
|
||||
</div>`;
|
||||
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",
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -894,11 +894,81 @@ function fpaFixture(r: Record<string, unknown>): 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<string, number> = { 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<br />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<string, TeamData>();
|
||||
const fixtures: FixtureData[] = [];
|
||||
const seen = new Set<string>();
|
||||
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 };
|
||||
}
|
||||
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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
|
||||
|
||||
Reference in new issue
Block a user