From 82d64ad225d6679651ecf03fe8811808c2127f38 Mon Sep 17 00:00:00 2001 From: spark Date: Fri, 6 Nov 2026 21:06:25 +0000 Subject: [PATCH] fix(sports): keep the stadium and the home club town apart The match calendar left Local and Cidade empty. The ground comes from each federation (Liga team/info, UEFA, EHF, FPA) and is stored separately from the town, then copied onto the event when the match is chosen. --- .../20261106210000_sports_place/migration.sql | 3 + apps/api/prisma/schema.prisma | 6 + apps/api/src/library/events.ts | 7 + apps/api/src/sports/ehf.test.ts | 3 +- apps/api/src/sports/place.test.ts | 27 ++++ apps/api/src/sports/providers.ts | 134 ++++++++++++++++-- apps/api/src/sports/routes.ts | 14 +- apps/api/src/sports/service.ts | 28 +++- apps/api/test/sports.test.ts | 5 +- apps/app/src/library/EventForm.tsx | 1 + docs/ARCHITECTURE.md | 8 +- packages/sdk/src/types.ts | 3 +- 12 files changed, 216 insertions(+), 23 deletions(-) create mode 100644 apps/api/prisma/migrations/20261106210000_sports_place/migration.sql create mode 100644 apps/api/src/sports/place.test.ts diff --git a/apps/api/prisma/migrations/20261106210000_sports_place/migration.sql b/apps/api/prisma/migrations/20261106210000_sports_place/migration.sql new file mode 100644 index 0000000..5e8ef08 --- /dev/null +++ b/apps/api/prisma/migrations/20261106210000_sports_place/migration.sql @@ -0,0 +1,3 @@ +-- Stadium name and the home club's town are stored apart, so a caption can say both. +ALTER TABLE "sports_teams" ADD COLUMN "city" TEXT; +ALTER TABLE "sports_fixtures" ADD COLUMN "city" TEXT; diff --git a/apps/api/prisma/schema.prisma b/apps/api/prisma/schema.prisma index ee8e082..7ae76a8 100644 --- a/apps/api/prisma/schema.prisma +++ b/apps/api/prisma/schema.prisma @@ -1314,7 +1314,10 @@ model SportsTeam { /// Lower-case, accent-free name with dashes; codes are derived from it (sl-benfica: b / slb). slug String logoUrl String? @map("logo_url") + /// The hall or stadium the club plays at. venue String? + /// The club's town, kept apart from the stadium name. + city String? createdAt DateTime @default(now()) @map("created_at") updatedAt DateTime @updatedAt @map("updated_at") @@ -1380,7 +1383,10 @@ model SportsFixture { timeKnown Boolean @default(true) @map("time_known") round String? matchNumber String? @map("match_number") + /// Stadium or hall, without the town. venue String? + /// Town of the home club. + city String? homeScore Int? @map("home_score") awayScore Int? @map("away_score") /// FPF and UEFA: when the line-ups were read from the match sheet. diff --git a/apps/api/src/library/events.ts b/apps/api/src/library/events.ts index 742d7cb..3aabe25 100644 --- a/apps/api/src/library/events.ts +++ b/apps/api/src/library/events.ts @@ -11,6 +11,7 @@ import { badRequest, conflict, forbidden, notFound } from "../lib/errors.js"; import type { Broadcaster } from "../realtime.js"; import type { SportsService } from "../sports/service.js"; import { officialSigla } from "../sports/fpa-siglas.js"; +import { splitStoredPlace } from "../sports/providers.js"; import { claimInbox } from "./adopt.js"; const HOUR = 3600_000; @@ -173,6 +174,12 @@ export async function registerEventRoutes(app: FastifyInstance, deps: { db: Db; if (body.photographerIds?.length) await assertMembers(orgId, body.photographerIds); const { photographerIds, iptcTemplate, ingestFrom, ingestUntil, autopilot, fixtureId, homeTeamId, awayTeamId, ...fields } = body; const match = await resolveMatch({ fixtureId, homeTeamId, awayTeamId }); + if (match.fixtureId && (!fields.venue || !fields.city)) { + const fixture = await db.sportsFixture.findUnique({ where: { id: match.fixtureId }, include: { homeTeam: { select: { venue: true, city: true } } } }); + const place = splitStoredPlace(fixture?.venue ?? fixture?.homeTeam.venue ?? null, fixture?.city ?? fixture?.homeTeam.city ?? null); + if (!fields.venue && place.venue) fields.venue = place.venue; + if (!fields.city && place.city) fields.city = place.city; + } // A second click (the first answer never arrived) must not create the game twice. if (match.fixtureId) { const existing = await db.event.findFirst({ where: { organizationId: orgId, fixtureId: match.fixtureId, archivedAt: null }, include, orderBy: { createdAt: "asc" } }); diff --git a/apps/api/src/sports/ehf.test.ts b/apps/api/src/sports/ehf.test.ts index 42d1a01..e4f4ca8 100644 --- a/apps/api/src/sports/ehf.test.ts +++ b/apps/api/src/sports/ehf.test.ts @@ -28,7 +28,8 @@ describe("EHF matches", () => { away: { name: "FC Porto" }, startsAt: new Date("2026-10-21T16:45:00Z"), round: "Group Phase A", - venue: "Hala Aleksandar Nikolic, Belgrade", + venue: "Hala Aleksandar Nikolic", + city: "Belgrade", homeScore: null, awayScore: 28, }); diff --git a/apps/api/src/sports/place.test.ts b/apps/api/src/sports/place.test.ts new file mode 100644 index 0000000..ca02387 --- /dev/null +++ b/apps/api/src/sports/place.test.ts @@ -0,0 +1,27 @@ +import { describe, expect, it } from "vitest"; +import { clubCity, splitStoredPlace } from "./providers.js"; + +describe("home club place", () => { + it("reads the town from the club's own name or from a stadium that names the town", () => { + expect(clubCity({ fullName: "Associação Académica de Coimbra/OAF, SDUQ, Lda", stadium: "Estádio Cidade de Coimbra" })).toBe("Coimbra"); + expect(clubCity({ fullName: "Amarante Futebol Clube SDUQ, Lda", stadium: "Estádio Municipal de Amarante" })).toBe("Amarante"); + expect(clubCity({ fullName: "Futebol Clube de Vizela – Futebol, SAD", stadium: "Estádio Futebol Clube de Vizela" })).toBe("Vizela"); + expect(clubCity({ fullName: "Futebol Clube do Porto - Futebol, SAD", stadium: "Estádio do Dragão" })).toBe("Porto"); + expect(clubCity({ fullName: "Sport Lisboa e Benfica - Futebol, SAD", stadium: "Estádio do Sport Lisboa e Benfica" })).toBe("Lisboa"); + expect(clubCity({ fullName: "UDL - União de Leiria - Futebol, SAD", stadium: "Estádio Dr. Magalhães Pessoa" })).toBe("Leiria"); + expect(clubCity({ fullName: "Portimonense - Futebol, SAD", stadium: "Portimão Estádio" })).toBe("Portimão"); + }); + + it("does not turn a person's name or the word Portugal into a town", () => { + expect(clubCity({ fullName: "Futebol Clube de Felgueiras - Futebol SAD", stadium: "Estádio Municipal Dr. Machado de Matos" })).toBe("Felgueiras"); + expect(clubCity({ fullName: "Sporting Clube de Portugal - Futebol, SAD", stadium: "Estádio José Alvalade" })).toBeNull(); + expect(clubCity({ fullName: "Leixões Sport Clube - Futebol, SAD", stadium: "Estádio do Mar" })).toBeNull(); + expect(clubCity({ fullName: "Clube Desportivo Feirense - Futebol, SAD", stadium: "Estádio Marcolino Castro" })).toBeNull(); + }); + + it("splits a venue that was stored with the town after a comma", () => { + expect(splitStoredPlace("Estádio Dr. Magalhães Pessoa, Leiria", null)).toEqual({ venue: "Estádio Dr. Magalhães Pessoa", city: "Leiria" }); + expect(splitStoredPlace("Estádio Cidade de Coimbra", null)).toEqual({ venue: "Estádio Cidade de Coimbra", city: null }); + expect(splitStoredPlace("Estádio do Dragão", "Porto")).toEqual({ venue: "Estádio do Dragão", city: "Porto" }); + }); +}); diff --git a/apps/api/src/sports/providers.ts b/apps/api/src/sports/providers.ts index b222e28..4c42f0c 100644 --- a/apps/api/src/sports/providers.ts +++ b/apps/api/src/sports/providers.ts @@ -19,7 +19,10 @@ export interface TeamData { name: string; abbreviation?: string | null; logoUrl?: string | null; + /** The hall or stadium this club plays at. */ venue?: string | null; + /** The home club's town. Separate from the stadium name: captions use both. */ + city?: string | null; /** FPA: the club the team belongs to (its games and levels are listed per club). Not stored. */ clubId?: string | null; } @@ -50,7 +53,10 @@ export interface FixtureData { timeKnown: boolean; round?: string | null; matchNumber?: string | null; + /** Stadium or hall, without the town. */ venue?: string | null; + /** Town of the home club, when the source names it. */ + city?: string | null; homeScore?: number | null; awayScore?: number | null; /** The referee team (UEFA publishes it before the match). */ @@ -111,6 +117,55 @@ export function lisbonTime(day: string, time?: string | null): { at: Date; timeK } const str = (v: unknown): string | null => (typeof v === "string" && v.trim() ? v.trim() : typeof v === "number" ? String(v) : null); + +/** A city named by the club itself: "de Vizela", "Municipal de Amarante", "Sport Lisboa". Not a person's name. */ +const PLACE_STOP = new Set(["portugal", "futebol", "sad", "sduq", "lda", "clube", "sport", "sporting", "mar", "campo"]); + +function tidyPlace(value: string): string | null { + const place = value.replace(/[/,].*$/, "").replace(/\s+(futebol|sad|sduq|lda)\b.*$/i, "").trim(); + if (!place || place.length > 40) return null; + const key = place.normalize("NFD").replace(/\p{M}/gu, "").toLowerCase(); + if (PLACE_STOP.has(key)) return null; + return place; +} + +export function clubCity(input: { fullName?: string | null; stadium?: string | null }): string | null { + const stadium = (input.stadium ?? "").replace(/\s+/g, " ").trim(); + const municipal = /^estádio municipal de\s+(.+)$/i.exec(stadium); + if (municipal && !/^(dr\.?|eng\.?º?|engenheiro|25 de )\b/i.test(municipal[1]!)) { + const city = tidyPlace(municipal[1]!); + if (city) return city; + } + const cidadeDe = /^estádio cidade de\s+(.+)$/i.exec(stadium); + if (cidadeDe) { + const city = tidyPlace(cidadeDe[1]!); + if (city) return city; + } + const leading = /^(.+?)\s+estádio$/i.exec(stadium); + if (leading) { + const city = tidyPlace(leading[1]!); + if (city) return city; + } + const full = input.fullName ?? ""; + if (/\bsport lisboa\b/i.test(full) || /\bsport lisboa\b/i.test(stadium)) return "Lisboa"; + const matches = [...full.matchAll(/\b(?:de|do|das|dos)\s+([A-ZÁÉÍÓÚÂÊÔÃÕÇÀ][\p{L}'’.-]+)/gu)]; + for (let i = matches.length - 1; i >= 0; i--) { + const city = tidyPlace(matches[i]![1]!); + if (city) return city; + } + return null; +} + +/** Older rows stored "Estádio, Leiria" in the venue. The comma splits them back into stadium and city. */ +export function splitStoredPlace(venue: string | null, city: string | null): { venue: string | null; city: string | null } { + if (city || !venue) return { venue, city }; + const cut = venue.lastIndexOf(","); + if (cut < 0) return { venue, city: null }; + const left = venue.slice(0, cut).trim(); + const right = venue.slice(cut + 1).trim(); + if (!left || !right || right.length > 40 || right.split(/\s+/).length > 4) return { venue, city: null }; + return { venue: left, city: right }; +} const url = (...vs: unknown[]): string | null => { for (const v of vs) { if (typeof v === "string" && /^https:\/\//.test(v.trim())) return v.trim(); @@ -176,9 +231,30 @@ export function clubSeasons(payload: unknown): LigaClubSeason[] { export class LigaProvider { static readonly BASE = "https://www.ligaportugal.pt/api/v1"; private static readonly HEADERS = { accept: "application/json", "accept-language": "pt-PT,pt;q=0.9", locale: "pt-PT", "x-client-platform": "web" }; + /** Stadium and town, once per club. The calendar and the teams list leave both empty; team/info has the stadium. */ + private readonly places = new Map>(); constructor(private readonly fetcher: Fetch) {} + /** The club's stadium and town. Null when Liga has not published the page. Never throws. */ + place(externalId: string, season: string): Promise<{ venue: string | null; city: string | null } | null> { + const cached = this.places.get(externalId); + if (cached) return cached; + const pending = this.readPlace(externalId, season).catch(() => null); + this.places.set(externalId, pending); + return pending; + } + + private async readPlace(externalId: string, season: string): Promise<{ venue: string | null; city: string | null } | null> { + const data = (await this.api("team/info", { id: externalId, season })) as Record; + const stadium = data.stadium && typeof data.stadium === "object" ? (data.stadium as { name?: unknown }) : null; + const venue = str(stadium?.name); + const named = str(data.city); + const city = named || clubCity({ fullName: str(data.fullName), stadium: venue }); + if (!venue && !city) return null; + return { venue, city }; + } + /** Every season the federation still publishes, with that year's club competitions. */ async seasons(): Promise { return clubSeasons(await this.api("seasons", {})); @@ -194,7 +270,15 @@ export class LigaProvider { async teams(competition: string, season: string): Promise { const list = await this.api("competition/teams", { season, competition }); if (!Array.isArray(list)) throw new Error("liga: unexpected competition/teams"); - return list.map(ligaTeam).filter((t): t is TeamData => !!t); + const teams = list.map(ligaTeam).filter((t): t is TeamData => !!t); + for (const team of teams) { + if (team.venue && team.city) continue; + const place = await this.place(team.externalId, season); + if (!place) continue; + team.venue = team.venue ?? place.venue; + team.city = team.city ?? place.city; + } + return teams; } /** The players, then the first team's coaching staff (head coach, assistants; the B team's staff is left out). */ @@ -306,6 +390,7 @@ export class LigaProvider { round: str(f.round) ?? str(f.matchweekNumber), matchNumber: str(f.fixtureNumber), venue: str((f.stadium as { name?: unknown } | undefined)?.name) ?? home.venue ?? null, + city: str((f.stadium as { city?: unknown } | undefined)?.city) ?? home.city ?? null, homeScore: finished && typeof f.homeTeamGoals === "number" ? f.homeTeamGoals : null, awayScore: finished && typeof f.awayTeamGoals === "number" ? f.awayTeamGoals : null, }); @@ -326,7 +411,8 @@ function ligaTeam(t: unknown): TeamData | null { name, abbreviation: str(o.abbreviation), logoUrl: url(o.logo, o.image), - venue: str(o.venue) ?? str(o.venueName) ?? str(o.stadium), + venue: (typeof o.stadium === "object" && o.stadium ? str((o.stadium as { name?: unknown }).name) : null) ?? str(o.venue) ?? str(o.venueName) ?? (typeof o.stadium === "string" ? str(o.stadium) : null), + city: str(o.city) || null, }; } @@ -364,6 +450,27 @@ export class FpaProvider { if (this.delayMs) await new Promise((r) => setTimeout(r, this.delayMs)); } + /** The club's hall and town (CLUBE_LOCALIDADE is often empty; the hall is REC_NOME). Never throws. */ + async club(clubId: string): Promise<{ venue: string | null; city: string | null } | null> { + const cached = this.clubs.get(clubId); + if (cached) return cached; + const pending = this.readClub(clubId).catch(() => null); + this.clubs.set(clubId, pending); + return pending; + } + + private readonly clubs = new Map>(); + + private async readClub(clubId: string): Promise<{ venue: string | null; city: string | null } | null> { + const data = await get(this.fetcher, `${FpaProvider.WS}/getClube/${encodeURIComponent(clubId)}`, { accept: "application/json" }, "json"); + const row = (Array.isArray(data) ? data[0] : data) as Record | undefined; + if (!row || typeof row !== "object") return null; + const venue = str(row.REC_NOME); + const city = str(row.CLUBE_LOCALIDADE); + if (!venue && !city) return null; + return { venue, city }; + } + /** An HTML page in whatever charset it declares (the match report is windows-1252). */ private async html(u: string): Promise { const res = await this.fetcher(u, { headers: FpaProvider.HTML, signal: AbortSignal.timeout(TIMEOUT_MS) }); @@ -768,6 +875,7 @@ function fpaFixture(r: Record): FixtureData | null { round: str(r.FASE), matchNumber: str(r.JOG_NUM_JOGO), venue: str(r.LOCAL), + city: str(r.CLUBE_LOCALIDADE), homeScore: goals(r.GOLOS_CASA ?? r.JOG_GOLOS_CASA), awayScore: goals(r.GOLOS_FORA ?? r.JOG_GOLOS_FORA), }; @@ -790,6 +898,13 @@ export function fpfDate(text: string, now: Date): { at: Date; timeKnown: boolean return candidates[0]!; } +/** FPF prints the stadium, sometimes "Estádio, Cidade". */ +function fpfPlace(text: string): { venue: string | null; city: string | null } { + const raw = text.replace(/\s+/g, " ").trim(); + if (!raw) return { venue: null, city: null }; + return splitStoredPlace(raw, null); +} + export class FpfProvider { static readonly BASE = "https://resultados.fpf.pt"; private static readonly HEADERS = { accept: "text/html", "accept-language": "pt-PT,pt;q=0.9", "user-agent": "PhotoReport/2 (sports data)" }; @@ -850,7 +965,7 @@ export class FpfProvider { startsAt: when.at, timeKnown: when.timeKnown, round: roundLabel, - venue: r(link).next(".game-list-stadium").find("small").text().trim() || null, + ...fpfPlace(r(link).next(".game-list-stadium").find("small").text().trim()), homeScore: score ? Number(score[1]) : null, awayScore: score ? Number(score[2]) : null, }); @@ -964,7 +1079,8 @@ export function uefaFixture(m: Json, competitionId: string, season: string): Fix startsAt: at, timeKnown: true, round: str(obj(m.matchday).longName) ?? str(obj(m.matchday).name) ?? str(obj(obj(m.round).metaData).name), - venue: stadium ? (city ? `${stadium}, ${city}` : stadium) : null, + venue: stadium, + city, homeScore: goals(total.home), awayScore: goals(total.away), officials, @@ -1131,7 +1247,8 @@ export function ehfFixture(row: unknown, competition: string, season: string): F startsAt: at, timeKnown: when.hasTime !== false, round: round && group ? `${round} ${group}` : round, - venue: hall && city ? `${hall}, ${city}` : (hall ?? city), + venue: hall, + city, homeScore: goals(obj(m.homeTeam)), awayScore: goals(obj(m.guestTeam)), }; @@ -1240,7 +1357,7 @@ export class EhfProvider { async euroCupMenMatches( competitionId: string, contentId: string, - ): Promise<{ matchId: string; startsAt: Date; homeNation: string | null; awayNation: string | null; venue: string | null }[]> { + ): Promise<{ matchId: string; startsAt: Date; homeNation: string | null; awayNation: string | null; venue: string | null; city: string | null }[]> { const data = await get( this.fetcher, `https://www.eurohandball.com/umbraco/api/competitionapi/GetStandingMatches?contentId=${encodeURIComponent(contentId)}&competitionId=${encodeURIComponent(competitionId)}`, @@ -1248,7 +1365,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 }[] = []; + const out: { matchId: string; startsAt: Date; homeNation: string | null; awayNation: string | null; venue: string | null; city: string | null }[] = []; for (const row of rows) { const m = obj(row); const matchId = str(m.matchID); @@ -1264,7 +1381,8 @@ export class EhfProvider { startsAt: at, homeNation: str(obj(obj(m.homeTeam).team).nationAbbreviation) ?? str(obj(obj(m.homeTeam).team).countryAbbreviation), awayNation: str(obj(obj(m.guestTeam).team).nationAbbreviation) ?? str(obj(obj(m.guestTeam).team).countryAbbreviation), - venue: hall && city ? `${hall}, ${city}` : (hall ?? city), + venue: hall, + city, }); } return out; diff --git a/apps/api/src/sports/routes.ts b/apps/api/src/sports/routes.ts index d780546..0547291 100644 --- a/apps/api/src/sports/routes.ts +++ b/apps/api/src/sports/routes.ts @@ -7,6 +7,7 @@ import type { Db } from "../db.js"; import { forbidden, notFound } from "../lib/errors.js"; import { toCsv, toTsv } from "./codegen.js"; import { fixtureTextFilter } from "./fixture-search.js"; +import { splitStoredPlace } from "./providers.js"; import type { SportsService } from "./service.js"; const OrgParams = z.object({ orgId: z.uuid() }); @@ -81,6 +82,7 @@ export async function registerSportsRoutes(app: FastifyInstance, deps: { db: Db; slug: t.slug, logoUrl: t.logoUrl, venue: t.venue, + city: t.city, players: t._count.players, })), }; @@ -120,20 +122,24 @@ export async function registerSportsRoutes(app: FastifyInstance, deps: { db: Db; include: { homeTeam: true, awayTeam: true, competition: true }, }); return { - fixtures: fixtures.map((f) => ({ + fixtures: fixtures.map((f) => { + const place = splitStoredPlace(f.venue ?? f.homeTeam.venue, f.city ?? f.homeTeam.city); + return { id: f.id, startsAt: f.startsAt, timeKnown: f.timeKnown, round: f.round, matchNumber: f.matchNumber, - venue: f.venue, + venue: place.venue, + city: place.city, homeScore: f.homeScore, awayScore: f.awayScore, sport: f.competition.sport, competition: { id: f.competition.id, name: f.competition.name, provider: f.competition.provider, code: f.competition.externalId, gender: f.competition.gender }, - home: { id: f.homeTeam.id, name: f.homeTeam.name, abbreviation: f.homeTeam.abbreviation, venue: f.homeTeam.venue }, + home: { id: f.homeTeam.id, name: f.homeTeam.name, abbreviation: f.homeTeam.abbreviation, venue: f.homeTeam.venue, city: f.homeTeam.city }, away: { id: f.awayTeam.id, name: f.awayTeam.name, abbreviation: f.awayTeam.abbreviation }, - })), + }; + }), }; }); diff --git a/apps/api/src/sports/service.ts b/apps/api/src/sports/service.ts index 3c0a5d8..5f6a50a 100644 --- a/apps/api/src/sports/service.ts +++ b/apps/api/src/sports/service.ts @@ -42,6 +42,7 @@ import { type OfficialData, type PlayerData, ProviderHttpError, + splitStoredPlace, type TeamData, EHF_COMPETITIONS, EhfProvider, @@ -595,7 +596,8 @@ export class SportsService { startsAt: lisbonTime("2026-11-05", "20:00").at, timeKnown: true, round: "Particular", - venue: "Pavilhão Municipal Fernando Lima, Caminha", + venue: "Pavilhão Municipal Fernando Lima", + city: "Caminha", }, { externalId: "m19-esp-por-20261107", @@ -606,7 +608,8 @@ export class SportsService { startsAt: lisbonTime("2026-11-07", "17:30").at, timeKnown: true, round: "Particular", - venue: "Pavilhão Municipal, Salceda de Caselas", + venue: "Pavilhão Municipal", + city: "Salceda de Caselas", }, ]; let n = 0; @@ -685,7 +688,7 @@ export class SportsService { */ private async applyEuroCupSheets(now: Date, season: string, result: RefreshResult): Promise { const { db, log } = this.deps; - let matches: { matchId: string; startsAt: Date; homeNation: string | null; awayNation: string | null; venue: string | null }[]; + let matches: { matchId: string; startsAt: Date; homeNation: string | null; awayNation: string | null; venue: string | null; city: string | null }[]; try { matches = await this.ehf.euroCupMenMatches(EHF_EURO_CUP_MEN.competitionId, EHF_EURO_CUP_MEN.contentId); } catch (err) { @@ -717,6 +720,7 @@ export class SportsService { timeKnown: true, round: "EHF Euro Cup", venue: m.venue, + city: m.city, }); } const due = matches.filter((m) => Math.abs(m.startsAt.getTime() - now.getTime()) <= EHF_EURO_CUP_MEN.sheetWindowMs); @@ -1244,6 +1248,7 @@ export class SportsService { ...(t.abbreviation ? { abbreviation: t.abbreviation } : {}), ...(t.logoUrl ? { logoUrl: t.logoUrl } : {}), ...(t.venue ? { venue: t.venue } : {}), + ...(t.city ? { city: t.city } : {}), }; const team = await this.deps.db.sportsTeam.upsert({ where, @@ -1304,6 +1309,18 @@ export class SportsService { private async saveFixture(c: SportsCompetition, provider: SportsProvider, f: FixtureData, sport?: string): Promise { const homeTeamId = await this.upsertTeam(provider, f.home, sport); const awayTeamId = await this.upsertTeam(provider, f.away, sport); + let place = splitStoredPlace(f.venue ?? null, f.city ?? null); + if (provider === "FPA" && f.home.clubId && !place.city) { + const club = await this.fpa.club(f.home.clubId); + if (club?.city) place = { ...place, city: club.city }; + if (club?.venue) { + await this.deps.db.sportsTeam.updateMany({ where: { id: homeTeamId, venue: null }, data: { venue: club.venue } }); + } + } + if (!place.venue || !place.city) { + const home = await this.deps.db.sportsTeam.findUnique({ where: { id: homeTeamId }, select: { venue: true, city: true } }); + place = { venue: place.venue ?? home?.venue ?? null, city: place.city ?? home?.city ?? null }; + } const data = { season: f.season, homeTeamId, @@ -1317,11 +1334,10 @@ export class SportsService { ...(f.officials?.length ? { officials: f.officials as unknown as object } : {}), }; // A sheet that does not name a hall must not wipe a venue we already stored (the youth article has none). - const venue = f.venue ?? null; await this.deps.db.sportsFixture.upsert({ where: { competitionId_externalId: { competitionId: c.id, externalId: f.externalId } }, - create: { competitionId: c.id, externalId: f.externalId, ...data, venue }, - update: { ...data, ...(venue ? { venue } : {}) }, + create: { competitionId: c.id, externalId: f.externalId, ...data, venue: place.venue, city: place.city }, + update: { ...data, ...(place.venue ? { venue: place.venue } : {}), ...(place.city ? { city: place.city } : {}) }, }); return 1; } diff --git a/apps/api/test/sports.test.ts b/apps/api/test/sports.test.ts index eaaed93..1bf7a35 100644 --- a/apps/api/test/sports.test.ts +++ b/apps/api/test/sports.test.ts @@ -693,7 +693,7 @@ describe("sports data service", () => { ]); // 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).toMatchObject({ round: "Matchday 2", venue: "Estádio Dr. Magalhães Pessoa", city: "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; @@ -839,7 +839,8 @@ describe("sports data service", () => { expect(friendly?.homeTeam.externalId).toBe("M19"); expect(friendly?.awayTeam.externalId).toBe("ESP-M19"); expect(friendly?.startsAt.toISOString()).toBe("2026-11-05T20:00:00.000Z"); - expect(friendly?.venue).toBe("Pavilhão Municipal Fernando Lima, Caminha"); + expect(friendly?.venue).toBe("Pavilhão Municipal Fernando Lima"); + expect(friendly?.city).toBe("Caminha"); }); }); diff --git a/apps/app/src/library/EventForm.tsx b/apps/app/src/library/EventForm.tsx index 0fc94e3..7065fc1 100644 --- a/apps/app/src/library/EventForm.tsx +++ b/apps/app/src/library/EventForm.tsx @@ -89,6 +89,7 @@ export function EventForm({ api, orgId, onClose, onCreated }: { api: ApiClient; home: teamDisplayName(f.home.name), away: teamDisplayName(f.away.name), venue: f.venue ?? f.home.venue ?? values.venue ?? "", + city: f.city ?? f.home.city ?? values.city ?? "", sport: f.sport, competition: f.competition.name, competitionCode: f.competition.provider === "FPA" ? f.competition.code : (values.competitionCode ?? ""), diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index b51fcee..5959c8c 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -282,7 +282,13 @@ hand-drawn boxes. every 6 hours (`SPORTS_SYNC=off` turns it off). It is shared by every organisation: - **Liga Portugal** (`ligaportugal.pt/api/v1`): Betclic, Meu Super and Allianz Cup stay on the six-hour refresh. - Gives teams, squads (numbers, positions, official headshots) and the season's fixtures. On start the worker reads + Gives teams, squads (numbers, positions, official headshots) and the season's fixtures. The calendar does not + name the ground: `team/info` does (the stadium). The town is that page's city when Liga fills it, otherwise the + town written in the club's own name or in a stadium that names it ("Municipal de Amarante", "Cidade de Coimbra"). + A person's name in the stadium ("Dr. Machado de Matos") is not a town. Stadium and town are stored apart + (`venue` and `city`) on the club and on the match, and choosing the match fills both on the event. The same + split is what UEFA (`stadium.city`), the EHF (`cityName`) and the FPA (`CLUBE_LOCALIDADE`, often empty; the + hall is `LOCAL` / `REC_NOME`) already publish. On start the worker reads every season the federation still lists, under the name that league had that year (Liga NOS, Liga Sagres, LigaPro), so a past season keeps the squad and the shirt numbers of that year. When that read finishes, the newest photographs already analysed are queued again for faces (thirty thousand per start). The archive's people list diff --git a/packages/sdk/src/types.ts b/packages/sdk/src/types.ts index 6f30e4d..6c19a5e 100644 --- a/packages/sdk/src/types.ts +++ b/packages/sdk/src/types.ts @@ -198,11 +198,12 @@ export interface SportsFixture { round: string | null; matchNumber: string | null; venue: string | null; + city: string | null; homeScore: number | null; awayScore: number | null; sport: string; competition: { id: string; name: string; provider: SportsProvider; code: string; gender: string | null }; - home: { id: string; name: string; abbreviation: string | null; venue: string | null }; + home: { id: string; name: string; abbreviation: string | null; venue: string | null; city: string | null }; away: { id: string; name: string; abbreviation: string | null }; } -- 2.47.3