899b45f (#111) added the six EHF club competitions to the catalog and to
refreshDue. The fake sites in test/sports.test.ts did not know
*.eurohandball.com, so every EHF season page answered 404, refreshDue
returned six errors and "reads the Liga and FPA, and only again after six
hours" failed on main.
The fake now serves an EHF season page with its ids and empty match lists,
and the expected competitions include the six EHF ones (no fixtures yet).
631 lines
39 KiB
TypeScript
631 lines
39 KiB
TypeScript
import { mkdtemp, rm } from "node:fs/promises";
|
|
import { tmpdir } from "node:os";
|
|
import path from "node:path";
|
|
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, fpaProva, fpaShortName, fpfDate, lisbonTime, parseFpaBoletim, parseFpaClubTerms, parseFpaMatchPage, parseFpaReferees, parseFpfLineups, seasonOf } from "../src/sports/providers.js";
|
|
import { SportsService } from "../src/sports/service.js";
|
|
import { LocalStorage } from "../src/storage/storage.js";
|
|
import { bearer, createTestApp, login, resetDb, seedUser, type TestContext } from "./helpers.js";
|
|
|
|
const quiet = { info: () => {}, warn: () => {} };
|
|
const settings = (s: Partial<CodeGeneratorSettings> = {}) => CodeGeneratorSettings.parse(s);
|
|
|
|
describe("player codes", () => {
|
|
it("derives prefixes from the team like the old app", () => {
|
|
expect(teamPrefix("sl-benfica", "short")).toBe("b");
|
|
expect(teamPrefix("sl-benfica", "long")).toBe("slb");
|
|
expect(teamPrefix("fc-porto", "long")).toBe("fcp");
|
|
expect(teamPrefix("", "long")).toBe("t");
|
|
});
|
|
|
|
it("fills templates, keeps extra columns and reports clashing codes", () => {
|
|
const squads = [
|
|
{ teamId: "1", slug: "sl-benfica", teamName: "SL Benfica", players: [{ number: "14", name: "Vangelis Pavlidis", position: "Avançado" }, { number: null, name: "Sem Número" }] },
|
|
{ teamId: "2", slug: "boavista-fc", teamName: "Boavista", players: [{ number: "14", name: "Outro" }] },
|
|
];
|
|
const { lines, clashes } = buildCodeLines(squads, settings({ prefix: "short", template: "{nome}, {posicao} do {equipa}", extraTemplates: ["{nome} ({numero})"] }));
|
|
expect(lines.map((l) => [l.code, l.value, l.more])).toEqual([
|
|
["b14", "Vangelis Pavlidis, Avançado do SL Benfica", ["Vangelis Pavlidis (14)"]],
|
|
["f14", "Outro, do Boavista", ["Outro (14)"]],
|
|
]);
|
|
expect(clashes).toEqual([]);
|
|
const both = buildCodeLines(squads, settings({ prefix: "short", teamPrefixes: { "2": "b" } }));
|
|
expect(both.clashes).toEqual([{ code: "b14", values: ["Vangelis Pavlidis (SL Benfica)", "Outro (Boavista)"] }]);
|
|
expect(toTsv(lines)).toBe("b14\tVangelis Pavlidis, Avançado do SL Benfica\tVangelis Pavlidis (14)\nf14\tOutro, do Boavista\tOutro (14)");
|
|
});
|
|
|
|
it("puts generated codes in a block and keeps the editor's own lines", () => {
|
|
const first = mergeGenerated("arb\tÁrbitro João\n", "slb14\tPavlidis");
|
|
expect(first.startsWith(BLOCK_START)).toBe(true);
|
|
expect(first).toContain("slb14\tPavlidis");
|
|
expect(first.trimEnd().endsWith("arb\tÁrbitro João")).toBe(true);
|
|
const again = mergeGenerated(first, "slb14\tPavlidis\nslb1\tTrubin");
|
|
expect(again.match(/slb14/g)).toHaveLength(1);
|
|
expect(again).toContain("slb1\tTrubin");
|
|
expect(again).toContain("arb\tÁrbitro João");
|
|
});
|
|
});
|
|
|
|
describe("federation data", () => {
|
|
it("reads Lisbon wall-clock times (summer and winter)", () => {
|
|
expect(lisbonTime("2026-10-14", "19:30").at.toISOString()).toBe("2026-10-14T18:30:00.000Z");
|
|
expect(lisbonTime("2026-12-01", "19:30").at.toISOString()).toBe("2026-12-01T19:30:00.000Z");
|
|
expect(lisbonTime("2026-12-01").timeKnown).toBe(false);
|
|
expect(seasonOf(new Date("2026-10-13"))).toBe("20262027");
|
|
expect(seasonOf(new Date("2027-03-01"))).toBe("20262027");
|
|
});
|
|
|
|
it("reads the FPA match report: numbers and licences, the officials' letters, the referees", () => {
|
|
const r = parseFpaBoletim(BOLETIM);
|
|
expect(r.available).toBe(true);
|
|
expect(r.home.map((p) => [p.number, p.name, p.externalId, p.position])).toEqual([
|
|
["1", "Rui Lopes", "100001", null],
|
|
["7", "Tiago Ferreira", "100002", null],
|
|
["A", "Paulo Antunes", null, "Oficial A"],
|
|
["B", "Nuno Rocha", null, "Oficial B"],
|
|
]);
|
|
expect(r.home[0]!.fullName).toBe("Rui Manuel Sousa Lopes");
|
|
expect(r.away.map((p) => [p.number, p.name])).toEqual([
|
|
["5", "João Alves"],
|
|
["A", "Sérgio Paiva"],
|
|
]);
|
|
expect(r.referees).toEqual([
|
|
{ name: "Duarte Sá", fullName: "Duarte Miguel Sá", role: "REFEREE", externalId: "185283" },
|
|
{ name: "Inês Mota", fullName: "Inês Mota", role: "REFEREE", externalId: "183622" },
|
|
{ name: "Carlos Mesa", fullName: "Carlos Mesa", role: "TABLE_OFFICIAL", externalId: "213551" },
|
|
{ name: "Mário Delegado", fullName: "Mário Delegado", role: "DELEGATE", externalId: null },
|
|
]);
|
|
expect(parseFpaBoletim("<html><body><table><tr><td>Equipa A :: X</td></tr></table></body></html>").available).toBe(false);
|
|
expect(fpaShortName("Ana Lima")).toBe("Ana Lima");
|
|
expect(parseFpaClubTerms(CLUB_PAGE)).toEqual({
|
|
season: "374",
|
|
seasons: [
|
|
{ id: "374", season: "20262027" },
|
|
{ id: "373", season: "20252026" },
|
|
],
|
|
levels: [{ id: "59", name: "Seniores M - ACR" }, { id: "4", name: "Seniores M" }, { id: "11", name: "Seniores F" }],
|
|
});
|
|
expect(parseFpaReferees("<body><a>Cursos Árbitros</a><table><tr><td>Árbitros</td>\n<td>Ana Lima, Bruno Costa</td></tr><tr><td>Delegados</td><td>Mário Silva</td></tr><tr><td>Oficiais de Mesa</td><td>Rita Sá, Luís Mota</td></tr></table></body>")).toEqual([
|
|
{ name: "Ana Lima", role: "REFEREE" },
|
|
{ name: "Bruno Costa", role: "REFEREE" },
|
|
{ name: "Rita Sá", role: "TABLE_OFFICIAL" },
|
|
{ name: "Luís Mota", role: "TABLE_OFFICIAL" },
|
|
]);
|
|
const page = parseFpaMatchPage(MATCH_PAGE);
|
|
expect([...page.benchCipa.home]).toEqual([
|
|
["A", "81778"],
|
|
["B", "36457"],
|
|
]);
|
|
expect([...page.benchCipa.away]).toEqual([["A", "114813"]]);
|
|
});
|
|
|
|
it("parses FPA competitions, FPF dates and FPF match sheets", () => {
|
|
expect(fpaProva("PO01 - Campeonato Betclic Masculino")).toEqual({ code: "PO01", name: "Campeonato Betclic Masculino" });
|
|
expect(fpaProva("PO01A - Divisao de Honra Masculina")).toEqual({ code: "PO01A", name: "Divisao de Honra Masculina" });
|
|
expect(fpaProva("PARTICULARES SELECOES NACIONAIS")).toBeNull();
|
|
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 });
|
|
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);
|
|
expect(home[0]).toMatchObject({ number: "1", name: "Jogador 1", position: "Guarda-Redes" });
|
|
expect(away[0]).toMatchObject({ number: "12", name: "Jogador 12" });
|
|
expect(away.at(-1)).toMatchObject({ number: "31", name: "Suplente B" });
|
|
});
|
|
});
|
|
|
|
// --- the federations, offline ---------------------------------------------------------------------------------------
|
|
|
|
// UEFA's match JSON (match.uefa.com), trimmed to what is read.
|
|
const TORREENSE = { id: "2603107", internationalName: "Torreense", teamCode: "TOR", logoUrl: "https://img.uefa.com/imgml/TP/teams/logos/70x70/2603107.png" };
|
|
const SUNDERLAND = { id: "53360", internationalName: "Sunderland", teamCode: "SUN" };
|
|
const LYON = { id: "5312", internationalName: "Lyon", teamCode: "LYO" };
|
|
const UEFA_MATCHES = [
|
|
{
|
|
id: "2049001",
|
|
kickOffTime: { date: "2026-10-01", dateTime: "2026-10-01T19:00:00Z", utcOffsetInHours: 1 },
|
|
homeTeam: LYON,
|
|
awayTeam: TORREENSE,
|
|
stadium: { translations: { name: { EN: "OL Stadium" } }, city: { EN: "Lyon", PT: "Lyon" } },
|
|
score: { total: { home: 1, away: 2 } },
|
|
status: "FINISHED",
|
|
matchday: { name: "MD1", longName: "Matchday 1" },
|
|
referees: [],
|
|
},
|
|
{
|
|
id: "2050091",
|
|
kickOffTime: { date: "2026-10-15", dateTime: "2026-10-15T16:45:00Z", utcOffsetInHours: 1 },
|
|
homeTeam: TORREENSE,
|
|
awayTeam: SUNDERLAND,
|
|
stadium: { name: { EN: "Estádio Dr. Magalhães Pessoa" }, city: { EN: "Leiria" } },
|
|
score: null,
|
|
status: "UPCOMING",
|
|
lineupStatus: "NOT_AVAILABLE",
|
|
matchday: { name: "MD2", longName: "Matchday 2" },
|
|
referees: [
|
|
{ person: { translations: { name: { EN: "Enea Jorgji" } } }, role: "REFEREE" },
|
|
{ person: { name: { EN: "Denis Rexha" } }, role: "ASSISTANT_REFEREE_ONE" },
|
|
{ person: { name: { EN: "Ridiger Çokaj" } }, role: "ASSISTANT_REFEREE_TWO" },
|
|
{ person: { name: { EN: "Juxhin Xhaja" } }, role: "FOURTH_OFFICIAL" },
|
|
{ person: { name: { EN: "Daniele Doveri" } }, role: "VIDEO_ASSISTANT_REFEREE" },
|
|
{ person: { name: { EN: "Thibault De Gendt" } }, role: "UEFA_DELEGATE" },
|
|
],
|
|
},
|
|
];
|
|
const uefaPlayer = (id: string, name: string, extra: object = {}) => ({ id, internationalName: name, imageUrl: `https://img.uefa.com/imgml/TP/players/1/2027/324x324/${id}.jpg`, ...extra });
|
|
const UEFA_SHEET = {
|
|
homeTeam: { field: [{ jerseyNumber: 1, type: "GOALKEEPER", player: uefaPlayer("9001", "Lucas Perri") }], bench: [], coaches: [] },
|
|
awayTeam: {
|
|
field: [
|
|
{ jerseyNumber: 1, type: "GOALKEEPER", player: uefaPlayer("8001", "Lucas Paes") },
|
|
{ jerseyNumber: 9, type: "PLAYER", player: uefaPlayer("8002", "Stopira", { fieldPosition: "FORWARD", translations: { fieldPosition: { PT: "Avançado" } } }) },
|
|
],
|
|
bench: [{ jerseyNumber: 21, type: "PLAYER", player: uefaPlayer("8003", "Manuel Pozo") }],
|
|
coaches: [{ role: "COACH", person: { id: "7001", translations: { name: { EN: "Luís Tralhão" } } } }],
|
|
},
|
|
};
|
|
|
|
/** A handball match report as the FPA prints it (invented people), in its own charset. */
|
|
const tr = (...cells: string[]) => `<tr>${cells.map((c) => `<td class="texto">${c}</td>`).join("")}</tr>`;
|
|
const BOLETIM = `<html><head><meta http-equiv="Content-Type" content="text/html; charset=windows-1252"><title>FAP :: Boletim do Jogo n. 28</title></head><body>
|
|
<table><tr><td><table class="tabela">${tr("Resultado 1ª Parte", "A", "B")}${tr("14", "10", "19", "19", "", "", "33", "29")}</table></td></tr></table>
|
|
<table class="tabela"><tr><td class="textob" colspan="11">Equipa A :: VITÓRIA SC </td></tr>
|
|
${tr("Nº", "CIPA", "Nome", "G", "A", "2'", "2'", "2'", "D", "E", "TP")}
|
|
${tr("1", "100001", "Rui Manuel Sousa Lopes", "0")}
|
|
${tr("07", "100002", "Tiago Ferreira", "4")}
|
|
${tr("Oficial A", "Grau 3", "Paulo Jorge Antunes", "X")}
|
|
${tr("Oficial B", "Grau 4", "Nuno Miguel Rocha", "")}
|
|
</table>
|
|
<table>${tr("1º Time-out 09:33 2º Time-out --:--")}</table>
|
|
<table class="tabela"><tr><td class="textob" colspan="11">Equipa B :: ÁGUAS SANTAS MILANEZA</td></tr>
|
|
${tr("Nº", "CIPA", "Nome", "G")}
|
|
${tr("5", "100003", "João Pedro Gonçalves Alves", "6")}
|
|
${tr("Oficial A", "Trei. Estagiário Grau 2", "Sérgio Paiva", "")}
|
|
</table>
|
|
<table>${tr("Árbitro 1")}${tr("Nome:", "Duarte Miguel Sá")}${tr("CIPA:", "185283")}${tr("Árbitro 2")}${tr("Nome:", "Inês Mota")}${tr("CIPA:", "183622")}
|
|
${tr("Oficial Mesa 1")}${tr("Nome:", "Carlos Mesa")}${tr("CIPA:", "213551")}${tr("Delegado 1")}${tr("Nome:", "Mário Delegado")}</table>
|
|
</body></html>`;
|
|
const pane = (id: string, rows: [string, string, string][]) =>
|
|
`<div class="module-table bulletin__team-players js-module-tabs-pane" data-pane="${id}"><div class="module-table__header"><div>Nº</div><div>Nº CIPA</div><div>Nome</div></div><div class="module-table__content">${rows
|
|
.map(([n, cipa, name]) => `<div class="module-table__row"><div>${n}</div><div><a href="/associado/${cipa}/" title="Ver ${name}">${cipa}</a></div><div>${name}</div></div>`)
|
|
.join("")}</div></div>`;
|
|
/** The match page once played: referees by name, and a pane per team with every licence number. */
|
|
const MATCH_PAGE = `<html><body><table><tr><td>Árbitros</td><td>Duarte Sá, Inês Mota</td></tr></table>${pane("team-a", [
|
|
["1", "100001", "Rui Lopes"],
|
|
["Oficial A", "81778", "Paulo Antunes"],
|
|
["Oficial B", "36457", "Nuno Rocha"],
|
|
])}${pane("team-b", [["Oficial A", "114813", "Sérgio Paiva"]])}</body></html>`;
|
|
const CLUB_PAGE = `<script>var TABLE_CONTENT_1 = {"title":"Resultados","club_id":"140","dropdowns":[{"tabId":"all","id":"season","label":"\\u00c9poca","options":[{"term_id":"374","name":"\\u00c9poca 2026/27"},{"term_id":"373","name":"\\u00c9poca 2025/26"}]},{"tabId":"all","id":"level","label":"Escal\\u00f5es","options":[{"term_id":"59","name":"Seniores M - ACR"},{"term_id":"4","name":"Seniores M"},{"term_id":"11","name":"Seniores F"}]}]};</script>`;
|
|
const fpaGame = (id: string, day: string, home: [string, string, string], away: [string, string, string], goals: [number, number] | null) => ({
|
|
ID_PROVA_JOGO: id,
|
|
JOG_DATA: day,
|
|
JOG_HORA: "16:00",
|
|
JOG_NUM_JOGO: "28",
|
|
EQUIPA_CASA_ID: home[0],
|
|
CLUBE_CASA_ID: home[1],
|
|
EQUIPA_CASA: home[2],
|
|
EQUIPA_FORA_ID: away[0],
|
|
CLUBE_FORA_ID: away[1],
|
|
EQUIPA_FORA: away[2],
|
|
GOLOS_CASA: goals ? String(goals[0]) : null,
|
|
GOLOS_FORA: goals ? String(goals[1]) : null,
|
|
LOCAL: "DESP. UNIDADE VIMARANENSE",
|
|
FASE: "1a Fase",
|
|
PROVA: "PO01 - Campeonato Betclic Masculino",
|
|
PRO_SEXO: "M",
|
|
});
|
|
const VITORIA: [string, string, string] = ["43045", "140", "VITÓRIA SC"];
|
|
const AGUAS: [string, string, string] = ["42964", "141", "ÁGUAS SANTAS MILANEZA"];
|
|
|
|
const BENFICA = { id: 1, external_id: "278", name: "SL Benfica", abbreviation: "SLB", logo: "https://www.ligaportugal.pt/l/slb.png" };
|
|
const PORTO = { id: 2, external_id: "157", name: "FC Porto", abbreviation: "FCP" };
|
|
const fakeSites = (state: { benfica: { shirtNumber: number; name: string; photos?: string }[]; png: Buffer; handball?: boolean }) => {
|
|
const calls: string[] = [];
|
|
const fetcher: Fetch = async (url) => {
|
|
calls.push(url);
|
|
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 (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"));
|
|
if (state.handball && u.host === "si.fpa.pt" && u.pathname.includes("print_boletim"))
|
|
return bytes(u.searchParams.get("P_ID_PROVA_JOGO") === "323264" ? Buffer.from(BOLETIM, "latin1") : Buffer.from("<html><body></body></html>"));
|
|
if (state.handball && u.host === "portal.fpa.pt" && u.pathname === "/jogo/323264/") return bytes(Buffer.from(MATCH_PAGE, "utf8"));
|
|
if (state.handball && u.host === "portal.fpa.pt" && u.pathname === "/jogo/323500/")
|
|
return bytes(
|
|
Buffer.from(
|
|
"<html><body><h2>Jogo 41</h2><table><tr><td>Árbitros</td><td>Duarte Sá, Bruno Costa</td></tr><tr><td>Delegados</td><td>Mário</td></tr><tr><td>Oficiais de Mesa</td><td>Carlos Mesa</td></tr></table></body></html>",
|
|
"utf8",
|
|
),
|
|
);
|
|
const licence = /^\/associado\/(100001|185283)\/$/.exec(u.pathname)?.[1];
|
|
if (state.handball && u.host === "portal.fpa.pt" && licence)
|
|
return bytes(Buffer.from(`<html><body><img src="https://si.fpa.pt/blob/obj_anexo/FOTO_CIPA/555_${licence}.JPG"></body></html>`, "utf8"));
|
|
if (state.handball && u.host === "portal.fpa.pt" && u.pathname.startsWith("/associado/")) return bytes(Buffer.from('<html><body><img src="https://portal.fpa.pt/wp-content/themes/fap/no-image.png"></body></html>'));
|
|
if (state.handball && u.host === "si.fpa.pt" && u.pathname.includes("FOTO_CIPA")) return bytes(state.png);
|
|
if (u.host === "ws.fpa.pt")
|
|
return json([
|
|
...(state.handball ? [fpaGame("323500", "2026-10-17", VITORIA, AGUAS, null)] : []),
|
|
{
|
|
ID_PROVA_JOGO: "323405",
|
|
JOG_DATA: "2026-10-14",
|
|
JOG_HORA: "19:30",
|
|
JOG_NUM_JOGO: "169",
|
|
EQUIPA_CASA_ID: "43041",
|
|
EQUIPA_FORA_ID: "42959",
|
|
EQUIPA_CASA: "MADEIRA SAD",
|
|
EQUIPA_FORA: "ABC DE BRAGA",
|
|
LOCAL: "ESC. BARTOLOMEU PERESTRELO",
|
|
FASE: "1a fase",
|
|
PROVA: "PO09 - Campeonato Betclic Feminino",
|
|
PRO_SEXO: "F",
|
|
GOLOS_CASA: null,
|
|
GOLOS_FORA: null,
|
|
},
|
|
]);
|
|
if (u.host === "match.uefa.com") {
|
|
if (u.pathname === "/v5/matches") return json(u.searchParams.get("competitionId") === "14" && u.searchParams.get("offset") === "0" ? UEFA_MATCHES : []);
|
|
if (u.pathname === "/v5/matches/2049001/lineups") return json(UEFA_SHEET);
|
|
if (u.pathname.endsWith("/lineups")) return json({ homeTeam: { field: [], bench: [], coaches: [] }, awayTeam: { field: [], bench: [], coaches: [] } });
|
|
}
|
|
if (u.pathname.endsWith("/competition/teams")) return json(u.searchParams.get("competition") === "ligaportugalbetclic" ? [BENFICA, PORTO] : []);
|
|
if (u.pathname.endsWith("/team/squad"))
|
|
return json(
|
|
u.searchParams.get("id") === "278"
|
|
? { players: state.benfica }
|
|
: {
|
|
players: [{ shirtNumber: 99, name: "Diogo Costa", position: "Guarda-Redes" }],
|
|
technical_team: [
|
|
{ external_id: "9001", name: "Francesco Farioli", fullName: "Francesco Farioli", position: "Treinador Principal" },
|
|
{ external_id: "9002", name: "Treinador da B", position: "Treinador Principal B" },
|
|
],
|
|
},
|
|
);
|
|
if (u.pathname.endsWith("/competition/round/8/nominations"))
|
|
return json([
|
|
{ fixture: { fixtureCode: "10802" }, refereeName: "Outro Árbitro" },
|
|
{
|
|
fixture: { fixtureCode: "10801" },
|
|
refereeName: "João Pinheiro",
|
|
refereePhoto: "https://www.ligaportugal.pt/backoffice/assets/Joao_Pinheiro.png",
|
|
referee: { external_id: "67456", name: "João Pinheiro", fullName: "João Pedro Pinheiro", photos: "https://www.ligaportugal.pt/backoffice/assets/Joao_Pinheiro.png" },
|
|
refereeAux1: { external_id: "67479", name: "Luciano Maia", fullName: "Luciano Maia", photos: "" },
|
|
refereeAux2Name: "Hugo Marques",
|
|
var: { external_id: "59631", name: "Manuel Mota" },
|
|
fieldDelegate: { external_id: "77318", name: "Rodrigo Viana" },
|
|
},
|
|
]);
|
|
if (u.pathname.includes("/calendar/matches/month/10"))
|
|
return json([
|
|
{
|
|
date: "2026-10-18",
|
|
fixtures: [{ seasonCode: "20262027", competitionName: "Liga Portugal Betclic", fixtureCode: "10801", round: 8, fixtureNumber: 1, matchDate: "2026-10-18T19:30:00Z", homeTeam: BENFICA, awayTeam: PORTO }],
|
|
},
|
|
]);
|
|
if (u.pathname.includes("/calendar/")) return json([]);
|
|
// EHF club competitions: the season pages exist but list no matches yet.
|
|
if (u.host.endsWith(".eurohandball.com")) {
|
|
if (u.pathname.endsWith("/matches/")) return bytes(Buffer.from(`<div data-competition-id="ehf" data-currentcontentid="1"></div>`, "utf8"));
|
|
if (u.pathname.startsWith("/umbraco/api/competitionmatchesapi/")) return json({ matches: [], hasPastMatches: false, hasFutureMatches: false });
|
|
}
|
|
if (u.host === "www.ligaportugal.pt" && u.pathname.endsWith(".png"))
|
|
return { ok: true, status: 200, json: async () => ({}), text: async () => "", arrayBuffer: async () => state.png.buffer.slice(state.png.byteOffset, state.png.byteOffset + state.png.byteLength) as ArrayBuffer };
|
|
return { ok: false, status: 404, json: async () => ({}), text: async () => "", arrayBuffer: async () => new ArrayBuffer(0) };
|
|
};
|
|
return { fetcher, calls };
|
|
};
|
|
|
|
describe("sports data service", () => {
|
|
let ctx: TestContext;
|
|
let dir: string;
|
|
let sports: SportsService;
|
|
let sites: ReturnType<typeof fakeSites>;
|
|
const state = { benfica: [] as { shirtNumber: number; name: string; photos?: string }[], png: Buffer.alloc(0), handball: false };
|
|
|
|
beforeAll(async () => {
|
|
dir = await mkdtemp(path.join(tmpdir(), "pr-sports-"));
|
|
sites = fakeSites(state);
|
|
ctx = await createTestApp({ STORAGE_ROOT: path.join(dir, "storage") }, undefined, sites.fetcher as unknown as typeof fetch);
|
|
state.png = await sharp({ create: { width: 200, height: 200, channels: 4, background: { r: 200, g: 0, b: 0, alpha: 0.5 } } }).png().toBuffer();
|
|
sports = new SportsService({ db: ctx.db, storage: new LocalStorage(ctx.config.STORAGE_ROOT), log: quiet, fetch: sites.fetcher, fpfDelayMs: 0, uefaDelayMs: 0, fpaDelayMs: 0 });
|
|
});
|
|
afterAll(async () => {
|
|
await ctx.app.close();
|
|
await ctx.db.$disconnect();
|
|
await rm(dir, { recursive: true, force: true });
|
|
});
|
|
beforeEach(async () => {
|
|
await resetDb(ctx.db);
|
|
state.handball = false;
|
|
state.benfica = [
|
|
{ shirtNumber: 14, name: "Vangelis Pavlidis", photos: "https://www.ligaportugal.pt/p/pavlidis.png" },
|
|
{ shirtNumber: 1, name: "Anatoliy Trubin" },
|
|
];
|
|
});
|
|
|
|
const now = new Date("2026-10-13T10:00:00Z");
|
|
|
|
it("reads the Liga and FPA, and only again after six hours", async () => {
|
|
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([
|
|
["LIGA", "allianzcup", "20262027"],
|
|
["FPA", "PO09", "20262027"],
|
|
["EHF", "cl-men", "20262027"],
|
|
["EHF", "cl-women", "20262027"],
|
|
["EHF", "ec-men", "20262027"],
|
|
["EHF", "ec-women", "20262027"],
|
|
["EHF", "el-men", "20262027"],
|
|
["EHF", "el-women", "20262027"],
|
|
["LIGA", "ligaportugalbetclic", "20262027"],
|
|
["LIGA", "ligaportugalmeusuper", "20262027"],
|
|
["UEFA", "1", "20262027"],
|
|
["UEFA", "2019", "20262027"],
|
|
["UEFA", "14", "20262027"],
|
|
["UEFA", "27", "20262027"],
|
|
["UEFA", "28", "20262027"],
|
|
]);
|
|
const fixtures = await ctx.db.sportsFixture.findMany({ include: { homeTeam: true, awayTeam: true }, orderBy: { startsAt: "asc" } });
|
|
expect(fixtures.map((f) => [f.homeTeam.name, f.awayTeam.name, f.startsAt.toISOString()])).toEqual([
|
|
["Lyon", "Torreense", "2026-10-01T19:00:00.000Z"],
|
|
["MADEIRA SAD", "ABC DE BRAGA", "2026-10-14T18:30:00.000Z"],
|
|
["Torreense", "Sunderland", "2026-10-15T16:45:00.000Z"],
|
|
["SL Benfica", "FC Porto", "2026-10-18T19:30:00.000Z"],
|
|
]);
|
|
const benfica = await ctx.db.sportsTeam.findFirstOrThrow({ where: { name: "SL Benfica" } });
|
|
expect((await sports.squad(benfica.id)).map((p) => [p.number, p.name])).toEqual([
|
|
["1", "Anatoliy Trubin"],
|
|
["14", "Vangelis Pavlidis"],
|
|
]);
|
|
|
|
const before = sites.calls.length;
|
|
await sports.refreshDue(new Date(now.getTime() + 3600_000));
|
|
expect(sites.calls.length).toBe(before);
|
|
await sports.refreshDue(new Date(now.getTime() + 7 * 3600_000));
|
|
expect(sites.calls.length).toBeGreaterThan(before);
|
|
});
|
|
|
|
it("builds the organisation's code list and keeps it current when a squad changes", async () => {
|
|
const { org, user } = await seedUser(ctx.db, "[email protected]", { org: "abola", role: "EDITOR" });
|
|
await sports.refreshDue(now);
|
|
const betclic = await ctx.db.sportsCompetition.findFirstOrThrow({ where: { externalId: "ligaportugalbetclic" } });
|
|
await ctx.db.codeList.create({ data: { organizationId: org!.id, name: "default", content: "arb\tÁrbitro\n" } });
|
|
await ctx.db.person.create({ data: { organizationId: org!.id, name: "Ana Andebol", club: "ABC Braga", number: "7" } });
|
|
const token = (await login(ctx.app, user.email)).body.accessToken;
|
|
|
|
const preview = await ctx.app.inject({
|
|
method: "POST",
|
|
url: `/v1/orgs/${org!.id}/code-generator/preview`,
|
|
headers: bearer(token),
|
|
payload: { competitionIds: [betclic.id], template: "{nome} ({equipa})" },
|
|
});
|
|
expect(preview.statusCode).toBe(200);
|
|
expect(preview.json().lines.map((l: { code: string; value: string }) => `${l.code}=${l.value}`)).toEqual([
|
|
"fcp99=Diogo Costa (FC Porto)",
|
|
"slb1=Anatoliy Trubin (SL Benfica)",
|
|
"slb14=Vangelis Pavlidis (SL Benfica)",
|
|
"abc7=Ana Andebol (ABC Braga)",
|
|
]);
|
|
|
|
const apply = await ctx.app.inject({ method: "POST", url: `/v1/orgs/${org!.id}/code-generator/apply`, headers: bearer(token), payload: { competitionIds: [betclic.id] } });
|
|
expect(apply.json()).toMatchObject({ generated: 4, entries: 5, issues: [] });
|
|
const list = (await ctx.app.inject({ method: "GET", url: `/v1/orgs/${org!.id}/code-list`, headers: bearer(token) })).json().content as string;
|
|
expect(list).toContain("slb14\tVangelis Pavlidis");
|
|
expect(list).toContain("arb\tÁrbitro");
|
|
|
|
// Pavlidis changes number, Trubin leaves: the next read updates the list on its own.
|
|
state.benfica = [{ shirtNumber: 9, name: "Vangelis Pavlidis" }];
|
|
await sports.refreshDue(new Date(now.getTime() + 7 * 3600_000));
|
|
const after = (await ctx.db.codeList.findFirstOrThrow({ where: { organizationId: org!.id } })).content;
|
|
expect(after).toContain("slb9\tVangelis Pavlidis");
|
|
expect(after).not.toContain("Trubin");
|
|
expect(after).toContain("arb\tÁrbitro");
|
|
});
|
|
|
|
it("creates an event from a match and turns its squads into people, headshots included", async () => {
|
|
const { org, user } = await seedUser(ctx.db, "[email protected]", { org: "abola", role: "ADMIN" });
|
|
await ctx.db.organization.update({ where: { id: org!.id }, data: { biometricsEnabled: true } });
|
|
await ctx.db.person.create({ data: { organizationId: org!.id, name: "Anatoliy Trubin", club: null } }); // typed by hand earlier
|
|
await sports.refreshDue(now);
|
|
const token = (await login(ctx.app, user.email)).body.accessToken;
|
|
|
|
const list = (await ctx.app.inject({ method: "GET", url: `/v1/sports/fixtures?from=2026-10-12&q=benfica`, headers: bearer(token) })).json();
|
|
expect(list.fixtures).toHaveLength(1);
|
|
const fixture = list.fixtures[0];
|
|
expect(fixture).toMatchObject({ competition: { name: "Liga Portugal Betclic" }, home: { name: "SL Benfica" }, away: { name: "FC Porto" }, round: "8" });
|
|
|
|
const created = await ctx.app.inject({
|
|
method: "POST",
|
|
url: `/v1/orgs/${org!.id}/events`,
|
|
headers: bearer(token),
|
|
payload: { home: "SL Benfica", away: "FC Porto", startsAt: fixture.startsAt, fixtureId: fixture.id },
|
|
});
|
|
expect(created.statusCode).toBe(201);
|
|
expect(created.json()).toMatchObject({ fixtureId: fixture.id, homeTeamId: fixture.home.id, awayTeamId: fixture.away.id });
|
|
const eventId = created.json().id as string;
|
|
|
|
const sync = await ctx.app.inject({ method: "POST", url: `/v1/events/${eventId}/squads/sync`, headers: bearer(token) });
|
|
expect(sync.statusCode).toBe(200);
|
|
const people = await ctx.db.person.findMany({ where: { organizationId: org!.id }, orderBy: { name: "asc" } });
|
|
expect(people.map((p) => [p.name, p.club, p.number, !!p.sportsPlayerId])).toEqual([
|
|
["Anatoliy Trubin", "SL Benfica", "1", true],
|
|
["Diogo Costa", "FC Porto", "99", true],
|
|
["Francesco Farioli", "FC Porto", null, true], // the head coach, from the club's staff (not the B team's)
|
|
["Hugo Marques", "Arbitragem", null, false], // the round's nominations: the referee team on the pitch
|
|
["João Pinheiro", "Arbitragem", null, true],
|
|
["Luciano Maia", "Arbitragem", null, true],
|
|
["Vangelis Pavlidis", "SL Benfica", "14", true],
|
|
]);
|
|
// The referee comes with his official photo; the VAR and the delegates are not on the pitch.
|
|
expect(people.find((p) => p.name === "João Pinheiro")).toMatchObject({ referenceStatus: "PENDING" });
|
|
const pavlidis = people.find((p) => p.name === "Vangelis Pavlidis")!;
|
|
expect(pavlidis).toMatchObject({ referenceStatus: "PENDING" });
|
|
expect(pavlidis.referenceKey).toBeTruthy();
|
|
|
|
const squads = (await ctx.app.inject({ method: "GET", url: `/v1/events/${eventId}/squads`, headers: bearer(token) })).json();
|
|
expect(squads.sides.map((s: { side: string; players: { number: string; personId: string | null }[] }) => [s.side, s.players.map((p) => `${p.number}:${!!p.personId}`)])).toEqual([
|
|
["home", ["1:true", "14:true"]],
|
|
["away", ["99:true", "null:true"]],
|
|
]);
|
|
|
|
// Again: nothing new.
|
|
expect((await ctx.app.inject({ method: "POST", url: `/v1/events/${eventId}/squads/sync`, headers: bearer(token) })).json()).toMatchObject({ created: 0, updated: 0 });
|
|
expect((await ctx.app.inject({ method: "POST", url: `/v1/orgs/${org!.id}/events`, headers: bearer(token), payload: { home: "a", away: "b", startsAt: fixture.startsAt, homeTeamId: org!.id } })).statusCode).toBe(400);
|
|
});
|
|
|
|
it("keeps sports data to members and FPF links to admins", async () => {
|
|
const { user } = await seedUser(ctx.db, "[email protected]", { org: "abola", role: "PHOTOGRAPHER" });
|
|
const token = (await login(ctx.app, user.email)).body.accessToken;
|
|
expect((await ctx.app.inject({ method: "GET", url: "/v1/sports/competitions", headers: bearer(token) })).statusCode).toBe(200);
|
|
expect((await ctx.app.inject({ method: "GET", url: "/v1/sports/competitions" })).statusCode).toBe(401);
|
|
expect((await ctx.app.inject({ method: "POST", url: "/v1/sports/competitions", headers: bearer(token), payload: { url: "competitionId=1&seasonId=105" } })).statusCode).toBe(403);
|
|
});
|
|
it("FPA: squads from the match reports, licence photos and the referees of the event", async () => {
|
|
state.handball = true;
|
|
const { org, user } = await seedUser(ctx.db, "[email protected]", { org: "vitoria", role: "OWNER" });
|
|
await ctx.db.organization.update({ where: { id: org!.id }, data: { biometricsEnabled: true } });
|
|
const r = await sports.refreshFpa(now);
|
|
expect(r.errors).toEqual([]);
|
|
const vitoria = await ctx.db.sportsTeam.findFirstOrThrow({ where: { provider: "FPA", externalId: "43045" } });
|
|
expect((await sports.squad(vitoria.id)).map((p) => [p.number, p.name])).toEqual([
|
|
["1", "Rui Lopes"],
|
|
["7", "Tiago Ferreira"],
|
|
["A", "Paulo Antunes"],
|
|
["B", "Nuno Rocha"],
|
|
]);
|
|
// The game already played is kept, its report read once (with its referees).
|
|
const played = await ctx.db.sportsFixture.findFirstOrThrow({ where: { externalId: "323264" } });
|
|
expect(played.lineupAt).not.toBeNull();
|
|
expect(played).toMatchObject({ homeScore: 33, awayScore: 29 });
|
|
expect((played.officials as { name: string }[]).map((o) => o.name)).toEqual(["Duarte Sá", "Inês Mota", "Carlos Mesa", "Mário Delegado"]);
|
|
// The bench officials' licence comes from the match page; the referees and table officials are kept by licence.
|
|
expect((await ctx.db.sportsPlayer.findFirstOrThrow({ where: { teamId: vitoria.id, number: "A" } })).externalId).toBe("81778");
|
|
const refs = await ctx.db.sportsTeam.findFirstOrThrow({ where: { provider: "FPA", externalId: "ARBITRAGEM" } });
|
|
expect((await sports.squad(refs.id)).map((p) => [p.name, p.externalId, p.fullName])).toEqual([
|
|
["Carlos Mesa", "213551", "Carlos Mesa"],
|
|
["Duarte Sá", "185283", "Duarte Miguel Sá"],
|
|
["Inês Mota", "183622", "Inês Mota"],
|
|
]);
|
|
// A second refresh starts no team again.
|
|
const before = sites.calls.length;
|
|
await sports.refreshFpa(new Date(now.getTime() + 7 * 3600_000));
|
|
expect(sites.calls.slice(before).filter((u) => u.includes("/clube/") || u.includes("print_boletim"))).toEqual([]);
|
|
|
|
const token = (await login(ctx.app, user.email)).body.accessToken;
|
|
const next = await ctx.db.sportsFixture.findFirstOrThrow({ where: { externalId: "323500" } });
|
|
const created = await ctx.app.inject({
|
|
method: "POST",
|
|
url: `/v1/orgs/${org!.id}/events`,
|
|
headers: bearer(token),
|
|
payload: { home: "VITÓRIA SC", away: "ÁGUAS SANTAS MILANEZA", startsAt: next.startsAt.toISOString(), fixtureId: next.id },
|
|
});
|
|
expect(created.statusCode).toBe(201);
|
|
expect((await ctx.app.inject({ method: "POST", url: `/v1/events/${created.json().id}/squads/sync`, headers: bearer(token) })).statusCode).toBe(200);
|
|
const people = await ctx.db.person.findMany({ where: { organizationId: org!.id }, orderBy: { name: "asc" } });
|
|
expect(people.map((p) => [p.name, p.club, p.number, !!p.referenceKey])).toEqual([
|
|
["Bruno Costa", "Arbitragem", null, false],
|
|
["Carlos Mesa", "Arbitragem", null, false],
|
|
["Duarte Sá", "Arbitragem", null, true],
|
|
["João Alves", "ÁGUAS SANTAS MILANEZA", "5", false],
|
|
["Nuno Rocha", "VITÓRIA SC", "B", false],
|
|
["Paulo Antunes", "VITÓRIA SC", "A", false],
|
|
["Rui Lopes", "VITÓRIA SC", "1", true],
|
|
["Sérgio Paiva", "ÁGUAS SANTAS MILANEZA", "A", false],
|
|
["Tiago Ferreira", "VITÓRIA SC", "7", false],
|
|
]);
|
|
|
|
// Photos of each player in the event: confirmed faces, and faces suggested as them, not confirmed yet.
|
|
const eventId = created.json().id as string;
|
|
const byName = new Map(people.map((p) => [p.name, p.id]));
|
|
const shot = (n: number) => ctx.db.photo.create({ data: { organizationId: org!.id, eventId, originalName: `IMG_${n}.JPG`, byteSize: 1, storageKey: `k${n}`, sha256: `sha${n}`, status: "READY", source: "UPLOAD" } });
|
|
const group = (data: { personId?: string; suggestedPersonId?: string; suggestionScore?: number }) => ctx.db.faceGroup.create({ data: { organizationId: org!.id, eventId, model: "m", ...data } });
|
|
const face = (photoId: string, groupId: string) => ctx.db.face.create({ data: { organizationId: org!.id, photoId, groupId, x0: 0, y0: 0, x1: 0.1, y1: 0.1, score: 0.9, model: "m" } });
|
|
const [p1, p2, p3, p4] = await Promise.all([shot(1), shot(2), shot(3), shot(4)]);
|
|
const confirmed = await group({ personId: byName.get("Rui Lopes")! });
|
|
const likely = await group({ suggestedPersonId: byName.get("Rui Lopes")!, suggestionScore: 0.8 });
|
|
const doubtful = await group({ suggestedPersonId: byName.get("Tiago Ferreira")!, suggestionScore: 0.5 });
|
|
const ignored = await ctx.db.faceGroup.create({ data: { organizationId: org!.id, eventId, model: "m", suggestedPersonId: byName.get("Tiago Ferreira")!, suggestionScore: 0.9, ignoredAt: new Date() } });
|
|
await face(p1!.id, confirmed.id);
|
|
await face(p2!.id, confirmed.id);
|
|
await face(p2!.id, likely.id); // already confirmed in this photo: counted once
|
|
await face(p3!.id, likely.id);
|
|
await face(p4!.id, doubtful.id);
|
|
await face(p1!.id, ignored.id); // "not a person" / ignored: never counted
|
|
const squads = (await ctx.app.inject({ method: "GET", url: `/v1/events/${eventId}/squads`, headers: bearer(token) })).json() as { sides: { players: { name: string; photos: { confirmed: number; likely: number }; photoIds: string[] }[] }[] };
|
|
const player = (name: string) => squads.sides.flatMap((s) => s.players).find((p) => p.name === name)!;
|
|
expect(player("Rui Lopes").photos).toEqual({ confirmed: 2, likely: 1 });
|
|
expect(player("Rui Lopes").photoIds.slice().sort()).toEqual([p1!.id, p2!.id, p3!.id].sort());
|
|
expect(player("Tiago Ferreira").photos).toEqual({ confirmed: 0, likely: 1 });
|
|
expect(player("Tiago Ferreira").photoIds).toEqual([p4!.id]);
|
|
});
|
|
|
|
it("FPA: a past season, club by club, following every club met (national games only)", async () => {
|
|
const calls: string[] = [];
|
|
const json = (body: unknown) => ({ ok: true, status: 200, json: async () => body, text: async () => JSON.stringify(body), arrayBuffer: async () => new ArrayBuffer(0) });
|
|
const page = (b: string) => ({ ok: true, status: 200, json: async () => ({}), text: async () => b, arrayBuffer: async () => new TextEncoder().encode(b).buffer as ArrayBuffer });
|
|
const GIL: [string, string, string] = ["50001", "142", "CDE GIL EANES"];
|
|
const regional = { ...fpaGame("900003", "2025-11-01", AGUAS, GIL, [20, 20]), ID_ASSOCIACAO: "3" };
|
|
const fetcher: Fetch = async (url) => {
|
|
calls.push(url);
|
|
const u = new URL(url);
|
|
if (u.pathname.includes("getAgendaJogosFAP")) return json([{ ...fpaGame("990001", "2026-10-30", VITORIA, VITORIA, null), ID_ASSOCIACAO: "8" }]) as never;
|
|
if (u.host === "portal.fpa.pt") return page(CLUB_PAGE) as never;
|
|
if (u.pathname.endsWith("/140/373/4")) return json([{ ...fpaGame("900001", "2025-10-04", VITORIA, AGUAS, [30, 28]), ID_ASSOCIACAO: "8" }]) as never;
|
|
if (u.pathname.endsWith("/141/373/4")) return json([{ ...fpaGame("900002", "2026-03-07", AGUAS, GIL, [25, 27]), ID_ASSOCIACAO: "8" }, regional]) as never;
|
|
return json([]) as never;
|
|
};
|
|
const service = new SportsService({ db: ctx.db, storage: new LocalStorage(ctx.config.STORAGE_ROOT), log: quiet, fetch: fetcher, fpfDelayMs: 0, uefaDelayMs: 0, fpaDelayMs: 0 });
|
|
expect(await service.importFpaSeason("20252026")).toBe(2);
|
|
const saved = await ctx.db.sportsFixture.findMany({ where: { season: "20252026", externalId: { in: ["900001", "900002", "900003"] } }, select: { externalId: true } });
|
|
expect(saved.map((f) => f.externalId).sort()).toEqual(["900001", "900002"]);
|
|
// Águas Santas (met in Vitória's games) and Gil Eanes (met in Águas Santas') were read too.
|
|
expect(calls.some((c) => c.includes("/clube/id/141/"))).toBe(true);
|
|
expect(calls.some((c) => c.includes("/clube/id/142/"))).toBe(true);
|
|
});
|
|
|
|
it("UEFA: matches with the referee team, squads from match sheets, and the referees as people of the event", async () => {
|
|
const { org, user } = await seedUser(ctx.db, "[email protected]", { org: "torreense", role: "OWNER" });
|
|
await sports.refreshDue(now);
|
|
const uel = await ctx.db.sportsCompetition.findFirstOrThrow({ where: { provider: "UEFA", externalId: "14" } });
|
|
expect(uel).toMatchObject({ name: "UEFA Europa League", sport: "futebol", lastError: null });
|
|
const torreense = await ctx.db.sportsTeam.findFirstOrThrow({ where: { provider: "UEFA", externalId: "2603107" } });
|
|
// The squad, from Matchday 1's sheet: numbers, goalkeeper, position in Portuguese, the coach.
|
|
expect((await sports.squad(torreense.id)).map((p) => [p.number, p.name, p.position])).toEqual([
|
|
["1", "Lucas Paes", "Guarda-Redes"],
|
|
["9", "Stopira", "Avançado"],
|
|
["21", "Manuel Pozo", null],
|
|
[null, "Luís Tralhão", "Treinador"],
|
|
]);
|
|
// The next match's sheet is not out yet: read again around kick-off.
|
|
const next = await ctx.db.sportsFixture.findFirstOrThrow({ where: { externalId: "2050091" } });
|
|
expect(next).toMatchObject({ round: "Matchday 2", venue: "Estádio Dr. Magalhães Pessoa, Leiria", lineupAt: null });
|
|
expect((next.officials as { role: string }[]).map((o) => o.role)).toContain("REFEREE");
|
|
|
|
const token = (await login(ctx.app, user.email)).body.accessToken;
|
|
const list = (await ctx.app.inject({ method: "GET", url: `/v1/sports/fixtures?from=2026-10-12&q=Torreense`, headers: bearer(token) })).json();
|
|
const fixture = list.fixtures.find((f: { id: string }) => f.id === next.id);
|
|
expect(fixture).toMatchObject({ competition: { name: "UEFA Europa League" }, home: { name: "Torreense" }, away: { name: "Sunderland" } });
|
|
const created = await ctx.app.inject({ method: "POST", url: `/v1/orgs/${org!.id}/events`, headers: bearer(token), payload: { home: "Torreense", away: "Sunderland", startsAt: fixture.startsAt, fixtureId: fixture.id } });
|
|
expect(created.statusCode).toBe(201);
|
|
await ctx.app.inject({ method: "POST", url: `/v1/events/${created.json().id}/squads/sync`, headers: bearer(token) });
|
|
const people = await ctx.db.person.findMany({ where: { organizationId: org!.id }, orderBy: { name: "asc" } });
|
|
// Players and coach of Torreense, and the referee team on the pitch (not the VAR or the delegate).
|
|
expect(people.map((p) => [p.name, p.club, p.number])).toEqual([
|
|
["Denis Rexha", "Arbitragem", null],
|
|
["Enea Jorgji", "Arbitragem", null],
|
|
["Juxhin Xhaja", "Arbitragem", null],
|
|
["Lucas Paes", "Torreense", "1"],
|
|
["Luís Tralhão", "Torreense", null],
|
|
["Manuel Pozo", "Torreense", "21"],
|
|
["Ridiger Çokaj", "Arbitragem", null],
|
|
["Stopira", "Torreense", "9"],
|
|
]);
|
|
});
|
|
});
|