diff --git a/apps/api/src/archive/people.ts b/apps/api/src/archive/people.ts index ac57a89..cba8875 100644 --- a/apps/api/src/archive/people.ts +++ b/apps/api/src/archive/people.ts @@ -7,7 +7,7 @@ import { boxInCrop, cropOfSettings } from "../faces/frame.js"; import { cosine, inFocus, THRESHOLDS } from "../faces/math.js"; import { notFound } from "../lib/errors.js"; import type { UrlSigner } from "../storage/storage.js"; -import { publishedPhotos } from "./gallery.js"; +import { gallerySeasons, publishedPhotos } from "./gallery.js"; import { isNationalSide } from "./match.js"; import type { Viewer } from "./viewer.js"; import { videoFaceCrop, videoScope } from "./video-faces.js"; @@ -30,7 +30,37 @@ interface Deps { const SourceParams = z.object({ sourceId: z.uuid() }); const PersonParams = SourceParams.extend({ personId: z.uuid() }); const FaceParams = SourceParams.extend({ faceId: z.uuid() }); -const PeopleQuery = z.object({ q: z.string().trim().max(80).optional(), club: z.string().trim().max(120).optional() }); +const PeopleQuery = z.object({ + q: z.string().trim().max(80).optional(), + club: z.string().trim().max(120).optional(), + season: z.string().trim().max(16).optional(), +}); + +/** "2025/26", "2025/2026" or "20252026" → 2025. Null when it is not a season, so the list stays everyone. */ +export function seasonYear(raw: string | null | undefined): number | null { + const s = (raw ?? "").trim(); + if (!s) return null; + const slash = /^(\d{4})\s*\/\s*(\d{2}|\d{4})$/.exec(s); + if (slash) { + const start = Number(slash[1]); + const end = Number(slash[2]); + if (slash[2]!.length === 4) return end === start + 1 ? start : null; + if (end === (start + 1) % 100) return start; + return null; + } + const compact = /^(\d{4})(\d{4})$/.exec(s.replace(/\s/g, "")); + if (compact && Number(compact[2]) === Number(compact[1]) + 1) return Number(compact[1]); + return null; +} + +/** The event's season, July to June in Lisbon, when a year was asked for. */ +function inSeason(year: number | null): Prisma.Sql { + if (year == null) return Prisma.sql`TRUE`; + return Prisma.sql`( + extract(year FROM e.starts_at AT TIME ZONE 'Europe/Lisbon')::int + - CASE WHEN extract(month FROM e.starts_at AT TIME ZONE 'Europe/Lisbon') >= 7 THEN 0 ELSE 1 END + ) = ${year}`; +} const PhotosQuery = z.object({ level: z.enum(["all", "confirmed"]).default("all"), limit: z.coerce.number().int().min(1).max(600).default(300) }); /** How club names are compared: lowercase, no accents, single spaces. */ @@ -137,13 +167,15 @@ export async function registerArchivePeopleRoutes(app: FastifyInstance, deps: De const v = viewerOf(req, sourceId); const query = PeopleQuery.parse(req.query); const visible = await visibleFolders(v); - if (visible !== "all" && !visible.length) return { people: [], clubs: [] }; + if (visible !== "all" && !visible.length) return { people: [], clubs: [], seasons: [] }; const scope = visible === "all" ? Prisma.sql`cf.source_id = ${v.s}::uuid AND cf.status = 'DONE' AND cf.photo_id IS NOT NULL AND ${publishedPhotos}` : Prisma.sql`cf.source_id = ${v.s}::uuid AND cf.status = 'DONE' AND cf.photo_id IS NOT NULL AND cf.folder_id = ANY(${visible}::uuid[]) AND ${publishedPhotos}`; const folderLimit = visible === "all" ? Prisma.sql`cf.source_id = ${v.s}::uuid AND cf.published` : Prisma.sql`cf.source_id = ${v.s}::uuid AND cf.published AND cf.id = ANY(${visible}::uuid[])`; + const year = seasonYear(query.season); + const seasonSql = inSeason(year); const rows = await db.$queryRaw<{ id: string; name: string; club: string | null; number: string | null; reference: boolean; off: boolean; confirmed: bigint; probable: bigint }[]>` SELECT p.id, p.name, p.club, p.number, p.reference_key IS NOT NULL AS reference, p.recognition_off_at IS NOT NULL AS off, count(DISTINCT f.photo_id) FILTER (WHERE g.person_id = p.id) AS confirmed, @@ -152,7 +184,8 @@ export async function registerArchivePeopleRoutes(app: FastifyInstance, deps: De JOIN faces f ON f.group_id = g.id JOIN cloud_files cf ON cf.photo_id = f.photo_id JOIN people p ON p.id = coalesce(g.person_id, g.suggested_person_id) - WHERE g.ignored_at IS NULL AND ${scope} + JOIN events e ON e.id = g.event_id + WHERE g.ignored_at IS NULL AND ${scope} AND ${seasonSql} GROUP BY p.id`; const fold = (s: string) => s.normalize("NFD").replace(/[̀-ͯ]/g, "").toLowerCase(); // "Juntar nomes": other names of a club count as the club. @@ -170,7 +203,8 @@ export async function registerArchivePeopleRoutes(app: FastifyInstance, deps: De FROM faces f JOIN face_groups g ON g.id = f.group_id JOIN cloud_files cf ON cf.photo_id = f.photo_id - WHERE coalesce(g.person_id, g.suggested_person_id) = ANY(${noRef}::uuid[]) AND g.ignored_at IS NULL AND ${scope} + JOIN events e ON e.id = g.event_id + WHERE coalesce(g.person_id, g.suggested_person_id) = ANY(${noRef}::uuid[]) AND g.ignored_at IS NULL AND ${scope} AND ${seasonSql} ORDER BY coalesce(g.person_id, g.suggested_person_id), (g.person_id IS NOT NULL) DESC, f.sharpness DESC NULLS LAST, f.score DESC` : []; const facePhotos = await db.photo.findMany({ where: { id: { in: faces.map((f) => f.photo_id) } }, select: { id: true, width: true, height: true, renderedSeq: true, developSnapshot: true } }); @@ -188,11 +222,11 @@ export async function registerArchivePeopleRoutes(app: FastifyInstance, deps: De FROM ( SELECT e.id AS event_id, e.home AS name FROM cloud_folders cf JOIN events e ON e.id = cf.event_id - WHERE ${folderLimit} AND cf.photo_count > 0 AND cf.matched_by IS DISTINCT FROM 'FOLDER' AND btrim(e.home) <> '' + WHERE ${folderLimit} AND cf.photo_count > 0 AND cf.matched_by IS DISTINCT FROM 'FOLDER' AND btrim(e.home) <> '' AND ${seasonSql} UNION ALL SELECT e.id, e.away FROM cloud_folders cf JOIN events e ON e.id = cf.event_id - WHERE ${folderLimit} AND cf.photo_count > 0 AND cf.matched_by IS DISTINCT FROM 'FOLDER' AND btrim(e.away) <> '' + WHERE ${folderLimit} AND cf.photo_count > 0 AND cf.matched_by IS DISTINCT FROM 'FOLDER' AND btrim(e.away) <> '' AND ${seasonSql} ) sides GROUP BY btrim(name)`; const clubs = new Map }>(); @@ -224,6 +258,7 @@ export async function registerArchivePeopleRoutes(app: FastifyInstance, deps: De clubs: [...clubs.values()] .sort((a, b) => b.people - a.people || b.games - a.games || a.name.localeCompare(b.name)) .map(({ name, people, also }) => ({ name, people, kind: clubKind(name), ...(also.size && { also: [...also].sort() }) })), + seasons: await gallerySeasons(db, v.s, visible), }; }); diff --git a/apps/api/src/archive/season-year.test.ts b/apps/api/src/archive/season-year.test.ts new file mode 100644 index 0000000..17cb76d --- /dev/null +++ b/apps/api/src/archive/season-year.test.ts @@ -0,0 +1,14 @@ +import { describe, expect, it } from "vitest"; +import { seasonYear } from "./people.js"; + +describe("seasonYear", () => { + it("reads a season label and leaves anything else as every season", () => { + expect(seasonYear("2025/26")).toBe(2025); + expect(seasonYear("1999/00")).toBe(1999); + expect(seasonYear("2025/2026")).toBe(2025); + expect(seasonYear("20252026")).toBe(2025); + expect(seasonYear("")).toBeNull(); + expect(seasonYear("2025/27")).toBeNull(); + expect(seasonYear(undefined)).toBeNull(); + }); +}); diff --git a/apps/api/src/sports/providers.ts b/apps/api/src/sports/providers.ts index 1996f45..6f2d916 100644 --- a/apps/api/src/sports/providers.ts +++ b/apps/api/src/sports/providers.ts @@ -131,12 +131,59 @@ export const LIGA_COMPETITIONS = [ const foldComp = (s: string) => s.normalize("NFD").replace(/[\u0300-\u036f]/g, "").toLowerCase().replace(/\s+/g, " ").trim(); +/** The domestic club competitions: first division, second division, league cup. Not the cups of other countries. */ +const CLUB_TIERS = new Set(["Liga 1", "Liga 2", "Taça"]); + +export interface LigaClubCompetition { + externalId: string; + name: string; +} + +export interface LigaClubSeason { + id: string; + competitions: LigaClubCompetition[]; +} + +/** + * Seasons the federation still lists, each with the club competitions of that year. + * The slug changes with the sponsor (Liga NOS, Liga Sagres, Betclic). A numeric id is a foreign competition. + */ +export function clubSeasons(payload: unknown): LigaClubSeason[] { + if (!Array.isArray(payload)) return []; + const out: LigaClubSeason[] = []; + for (const row of payload) { + if (!row || typeof row !== "object") continue; + const id = str((row as { id?: unknown }).id)?.replace(/\D/g, "") ?? ""; + if (!/^\d{8}$/.test(id)) continue; + const comps = (row as { competitions?: unknown }).competitions; + if (!Array.isArray(comps)) continue; + const seen = new Set(); + const competitions: LigaClubCompetition[] = []; + for (const c of comps) { + if (!c || typeof c !== "object") continue; + const tier = str((c as { competition?: unknown }).competition); + if (!tier || !CLUB_TIERS.has(tier)) continue; + const externalId = str((c as { externalId?: unknown }).externalId); + if (!externalId || /^\d+$/.test(externalId) || seen.has(externalId)) continue; + seen.add(externalId); + competitions.push({ externalId, name: str((c as { name?: unknown }).name) ?? externalId }); + } + if (competitions.length) out.push({ id, competitions }); + } + return out; +} + 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" }; constructor(private readonly fetcher: Fetch) {} + /** Every season the federation still publishes, with that year's club competitions. */ + async seasons(): Promise { + return clubSeasons(await this.api("seasons", {})); + } + private async api(path: string, params: Record): Promise { const u = new URL(`${LigaProvider.BASE}/${path}`); for (const [k, v] of Object.entries(params)) u.searchParams.set(k, v); diff --git a/apps/api/src/sports/seasons.test.ts b/apps/api/src/sports/seasons.test.ts new file mode 100644 index 0000000..f785299 --- /dev/null +++ b/apps/api/src/sports/seasons.test.ts @@ -0,0 +1,31 @@ +import { describe, expect, it } from "vitest"; +import { clubSeasons } from "./providers.js"; + +describe("clubSeasons", () => { + it("keeps the two divisions and the league cup, under the name of that year", () => { + const seasons = clubSeasons([ + { + id: "20262027", + competitions: [ + { externalId: "ligaportugalbetclic", name: "Liga Portugal Betclic", competition: "Liga 1" }, + { externalId: "ligaportugalmeusuper", name: "Liga Portugal Meu Super", competition: "Liga 2" }, + { externalId: "allianzcup", name: "Allianz Cup", competition: "Taça" }, + { externalId: "218549", name: "Taça de Portugal", competition: "" }, + { externalId: "219487", name: "UEFA Champions League", competition: "" }, + ], + }, + { + id: "20172018", + competitions: [ + { externalId: "liganos", name: "Liga NOS", competition: "Liga 1" }, + { externalId: "ledmanligapro", name: "LEDMAN LigaPro", competition: "Liga 2" }, + { externalId: "taçactt", name: "Taça CTT", competition: "Taça" }, + { externalId: "taçactt", name: "Taça CTT", competition: "Taça" }, + ], + }, + ]); + expect(seasons.map((s) => s.id)).toEqual(["20262027", "20172018"]); + expect(seasons[0]?.competitions.map((c) => c.externalId)).toEqual(["ligaportugalbetclic", "ligaportugalmeusuper", "allianzcup"]); + expect(seasons[1]?.competitions.map((c) => c.externalId)).toEqual(["liganos", "ledmanligapro", "taçactt"]); + }); +}); diff --git a/apps/api/src/sports/service.ts b/apps/api/src/sports/service.ts index 4961412..668ab36 100644 --- a/apps/api/src/sports/service.ts +++ b/apps/api/src/sports/service.ts @@ -17,6 +17,7 @@ import { FpaProvider, FpfProvider, LIGA_COMPETITIONS, + type LigaClubCompetition, LigaProvider, type OfficialData, type PlayerData, @@ -240,84 +241,89 @@ export class SportsService { /** * Every Liga club and every player the federation still publishes, season by season, newest first. - * A photo of a club five years ago then has that season's squad, including players who have since moved. - * Stops at the first past season that lists no teams. The current season being empty (pre-season) does not stop it. - * `stopped` is checked between requests so a shutdown leaves within one call. + * The list is the seasons endpoint, so an older name of the same league (Liga NOS, Liga Sagres) is read too. + * One competition missing in a year does not stop the older years. `stopped` is checked between requests. */ async backfillLigaRegister(stopped: () => boolean): Promise { await this.ensureCatalog(); - const comps = await this.deps.db.sportsCompetition.findMany({ where: { provider: "LIGA" } }); - let season = seasonOf(new Date()); + let seasons: { id: string; competitions: LigaClubCompetition[] }[]; + try { + seasons = await this.liga.seasons(); + } catch (err) { + this.deps.log.warn({ err }, "sports: liga seasons not read"); + return 0; + } let saved = 0; - for (let year = 0; year < 25 && !stopped(); year++) { - let sawTeams = false; - let failed = 0; - for (const c of comps) { + for (const season of seasons) { + if (stopped()) return saved; + for (const comp of season.competitions) { if (stopped()) return saved; - const key = `${c.externalId}:${season}`; - if (this.registerDone.has(key)) { - sawTeams = true; - continue; - } + const key = `${comp.externalId}:${season.id}`; + if (this.registerDone.has(key)) continue; let teams: TeamData[]; try { - teams = await this.liga.teams(c.externalId, season); + teams = await this.liga.teams(comp.externalId, season.id); } catch (err) { const missing = err instanceof ProviderHttpError ? err.status === 404 : err instanceof Error && err.message.startsWith("liga: unexpected"); if (missing) { this.registerDone.add(key); continue; } - failed++; - // Liga 400s competition/teams until it opens that season for that competition (future season, not yet - // scheduled): same not-yet-published shape as the squad case below, so kept out of the error hub. + // Liga 400s competition/teams until it opens that season (a future season, not yet scheduled). if (err instanceof ProviderHttpError && err.status === 400) - this.deps.log.info({ err, competition: c.externalId, season }, "sports: liga teams not published yet for this competition"); - else this.deps.log.warn({ err, competition: c.externalId, season }, "sports: liga teams not read"); + this.deps.log.info({ err, competition: comp.externalId, season: season.id }, "sports: liga teams not published yet for this competition"); + else this.deps.log.warn({ err, competition: comp.externalId, season: season.id }, "sports: liga teams not read"); continue; } if (!teams.length) { this.registerDone.add(key); continue; } - sawTeams = true; + const competitionId = await this.ligaCompetitionId(comp, season.id); let complete = true; for (const t of teams) { if (stopped()) return saved; const teamId = await this.upsertTeam("LIGA", t); await this.deps.db.sportsCompetitionTeam.upsert({ - where: { competitionId_teamId_season: { competitionId: c.id, teamId, season } }, - create: { competitionId: c.id, teamId, season }, + where: { competitionId_teamId_season: { competitionId, teamId, season: season.id } }, + create: { competitionId, teamId, season: season.id }, update: {}, }); - const have = await this.deps.db.sportsPlayer.count({ where: { teamId, season } }); + const have = await this.deps.db.sportsPlayer.count({ where: { teamId, season: season.id } }); if (have > 0) continue; - const claim = `${teamId}:${season}`; + const claim = `${teamId}:${season.id}`; if (this.squadClaimed.has(claim)) continue; this.squadClaimed.add(claim); try { - saved += await this.savePlayers(teamId, season, await this.liga.squad(t.externalId, season), "api"); + saved += await this.savePlayers(teamId, season.id, await this.liga.squad(t.externalId, season.id), "api"); } catch (err) { complete = false; this.squadClaimed.delete(claim); - // Same not-yet-published 400 as importLigaSquads above: expected, kept out of the error hub. if (err instanceof ProviderHttpError && err.status === 400) - this.deps.log.info({ err, team: t.name, season }, "sports: liga squad not published yet for this team"); - else this.deps.log.warn({ err, team: t.name, season }, "sports: liga squad not read"); + this.deps.log.info({ err, team: t.name, season: season.id }, "sports: liga squad not published yet for this team"); + else this.deps.log.warn({ err, team: t.name, season: season.id }, "sports: liga squad not read"); } } if (complete) this.registerDone.add(key); } - if (failed === comps.length && comps.length) break; - if (year > 0 && !sawTeams) break; - const start = Number(season.slice(0, 4)) - 1; - if (!Number.isFinite(start) || start < 2000) break; - season = `${start}${start + 1}`; } if (saved) this.deps.log.info({ saved }, "sports: liga register imported"); return saved; } + /** The competition row for a season's club league. A historical sponsor stays out of the six-hour refresh. */ + private async ligaCompetitionId(comp: LigaClubCompetition, season: string): Promise { + const existing = await this.deps.db.sportsCompetition.findUnique({ + where: { provider_externalId: { provider: "LIGA", externalId: comp.externalId } }, + }); + if (existing) return existing.id; + const modern = LIGA_COMPETITIONS.some((c) => c.externalId === comp.externalId); + const row = await this.deps.db.sportsCompetition.create({ + data: { provider: "LIGA", externalId: comp.externalId, sport: "futebol", name: comp.name, gender: "M", season, active: modern }, + }); + return row.id; + } + /** * A whole past FPA season (the archive's folders of other seasons): the federation's national games of every * level, club by club. It starts from the clubs of today's agenda and follows every club met in those games, so diff --git a/apps/site/src/app/arquivo/[id]/Browse.tsx b/apps/site/src/app/arquivo/[id]/Browse.tsx index 951eb37..60a2f45 100644 --- a/apps/site/src/app/arquivo/[id]/Browse.tsx +++ b/apps/site/src/app/arquivo/[id]/Browse.tsx @@ -71,6 +71,8 @@ export function Browse({ const [joinInto, setJoinInto] = useState(""); const [joinNote, setJoinNote] = useState(null); const [peopleTick, setPeopleTick] = useState(0); + /** People stay everyone until a season is chosen. Separate from the gallery filter. */ + const [peopleSeason, setPeopleSeason] = useState(null); const guard = useCallback( (err: unknown) => { @@ -132,12 +134,15 @@ export function Browse({ }).catch((err) => !cancel && guard(err)); cached(`/v1/archive/${sourceId}/directory/players`, token, (body) => !cancel && setPlayers(body.players ?? [])).catch(() => !cancel && setPlayers([])); } - if (tab === "people") cached(`/v1/archive/${sourceId}/people`, token, (body) => !cancel && setPeople(body)).catch((err) => !cancel && guard(err)); + if (tab === "people") { + const peopleUrl = peopleSeason ? `/v1/archive/${sourceId}/people?season=${encodeURIComponent(peopleSeason)}` : `/v1/archive/${sourceId}/people`; + cached(peopleUrl, token, (body) => !cancel && setPeople(body)).catch((err) => !cancel && guard(err)); + } return () => { cancel = true; clearTimeout(retry); }; - }, [tab, sourceId, token, guard, attempt, teamsTry, peopleTick]); + }, [tab, sourceId, token, guard, attempt, teamsTry, peopleTick, peopleSeason]); /** Joins (or parts) club names, then reads people and teams again. */ const joinClubs = (path: "merge" | "unmerge", body: unknown, done: string) => { @@ -209,6 +214,7 @@ export function Browse({ let emptyPeople = ""; if (people && shownPeople.length === 0) { if (club && !people.people.some((p) => clubNames?.has(fold(p.club ?? "")))) emptyPeople = "Ainda não há pessoas identificadas desta equipa."; + else if (peopleSeason && !people.people.length) emptyPeople = "Ainda não há pessoas identificadas nesta época."; else if (people.people.length) emptyPeople = "Ninguém com esse nome."; else emptyPeople = "Ainda não há pessoas identificadas nestas galerias. Abre uma foto e clica numa cara para encontrar mais fotos dela."; } @@ -475,7 +481,30 @@ export function Browse({ {tab === "people" && ( <> -

Pessoas

+
+

Pessoas

+ {!!people?.seasons?.length && ( + + )} +
{people && people.clubs.length > 1 && (