From 5eb5e95f1d1f86b9dbcc3eb4da7195a2174ad8b7 Mon Sep 17 00:00:00 2001 From: spark Date: Wed, 21 Oct 2026 23:19:19 +0100 Subject: [PATCH] Show one club for each sigla, and list countries as national teams. MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The Betclic list joins SLB with SL Benfica and AAAS with Águas Santas. A country name is a seleção. The face pass reads that club's squad for the season, including rows stored under the short code. --- apps/api/src/archive/clubs.test.ts | 84 ++++++++++++++++++++++ apps/api/src/archive/directory.ts | 4 +- apps/api/src/archive/labels.ts | 12 ++++ apps/api/src/archive/match.ts | 42 ++++++++++- apps/api/src/archive/people.ts | 19 +++-- apps/api/src/archive/viewer.ts | 5 +- apps/api/src/faces/numbers.ts | 37 +++++++++- apps/api/src/sports/fpa-siglas.ts | 81 +++++++++++++++++---- apps/site/src/app/arquivo/[id]/Browse.tsx | 69 +++++++++++------- apps/site/src/app/arquivo/[id]/api.ts | 2 +- apps/site/src/app/arquivo/[id]/archive.css | 11 +++ docs/archive.md | 6 +- 12 files changed, 314 insertions(+), 58 deletions(-) create mode 100644 apps/api/src/archive/clubs.test.ts create mode 100644 apps/api/src/archive/labels.ts diff --git a/apps/api/src/archive/clubs.test.ts b/apps/api/src/archive/clubs.test.ts new file mode 100644 index 0000000..8f3c810 --- /dev/null +++ b/apps/api/src/archive/clubs.test.ts @@ -0,0 +1,84 @@ +import { describe, expect, it } from "vitest"; +import { teamSideRows } from "./directory.js"; +import { clubTeamIds, isNationalSide, isTeam, teamMatcher } from "./match.js"; +import { clubKind } from "./people.js"; +import { isSquadSide, officialClub, sameClubName } from "../sports/fpa-siglas.js"; + +describe("one club, from the sigla list", () => { + it("joins the sigla and the name, and a sponsor written after a slash", () => { + expect(officialClub("SLB")).toBe("SL Benfica"); + expect(sameClubName("SL BENFICA")).toBe("SL Benfica"); + expect(sameClubName("Benfica")).toBe("SL Benfica"); + expect(sameClubName("Sport Lisboa e Benfica")).toBe("SL Benfica"); + expect(sameClubName("AAAS")).toBe("Águas Santas Milaneza"); + expect(sameClubName("Águas Santas")).toBe("Águas Santas Milaneza"); + expect(sameClubName("AGUAS SANTAS")).toBe("Águas Santas Milaneza"); + expect(sameClubName("FC PORTO / SOFARMA")).toBe("FC Porto"); + expect(sameClubName("SCP")).toBe("Sporting CP"); + expect(sameClubName("Sporting")).toBe("Sporting CP"); + }); + + it("does not join a youth side, or two clubs, or a different Benfica", () => { + expect(isSquadSide("SL BENFICA 'A'")).toBe(true); + expect(isSquadSide("Benfica B")).toBe(true); + expect(isSquadSide("SLB")).toBe(false); + expect(sameClubName("SL BENFICA 'A'")).toBeUndefined(); + expect(sameClubName("Benfica B")).toBeUndefined(); + expect(sameClubName("C BENFICA C BRANCO")).toBeUndefined(); + expect(sameClubName("Benfica / Porto")).toBeUndefined(); + expect(sameClubName("ALMADA AC / EXT. GIL EANES")).toBeUndefined(); + }); + + it("keeps a club code that is also a country code, and names real countries", () => { + expect(sameClubName("BEL")).toBe("CF Os Belenenses"); + expect(sameClubName("MAR")).toBe("Marítimo Madeira Andebol SAD"); + expect(isNationalSide("BEL")).toBe(false); + expect(isNationalSide("MAR")).toBe(false); + expect(isNationalSide("Espanha")).toBe(true); + expect(isNationalSide("Spain")).toBe(true); + expect(isNationalSide("ESP")).toBe(true); + expect(isNationalSide("Marrocos")).toBe(true); + expect(isNationalSide("Bélgica")).toBe(true); + expect(clubKind("Espanha")).toBe("national"); + expect(clubKind("Espanha Feminina")).toBe("national"); + expect(clubKind("SL Benfica")).toBe("club"); + expect(clubKind("BEL")).toBe("club"); + }); + + it("stores one label for the sigla and the name, and a country apart from the clubs", () => { + const rows = teamSideRows( + [ + { id: "1", home: "SLB", away: "AAAS" }, + { id: "2", home: "SL Benfica", away: "Águas Santas" }, + { id: "3", home: "ESP", away: "Portugal" }, + { id: "4", home: "SL BENFICA 'A'", away: "C BENFICA C BRANCO" }, + { id: "5", home: "BEL", away: "MAR" }, + ], + teamMatcher([]), + new Map(), + ); + const name = (id: string, raw: string) => rows.find((row) => row.eventId === id && row.raw === raw)?.name; + expect(name("1", "SLB")).toBe("SL Benfica"); + expect(name("2", "SL Benfica")).toBe("SL Benfica"); + expect(name("1", "AAAS")).toBe("Águas Santas Milaneza"); + expect(name("2", "Águas Santas")).toBe("Águas Santas Milaneza"); + expect(name("3", "ESP")).toBe("Espanha"); + expect(name("3", "Portugal")).toBe("Portugal"); + expect(name("4", "SL BENFICA 'A'")).toBe("SL BENFICA 'A'"); + expect(name("4", "C BENFICA C BRANCO")).toBe("C BENFICA C BRANCO"); + expect(name("5", "BEL")).toBe("CF Os Belenenses"); + expect(name("5", "MAR")).toBe("Marítimo Madeira Andebol SAD"); + const rowsOf = (side: string) => + clubTeamIds(side, [ + { id: "senior", name: "SL BENFICA", abbreviation: null, slug: "sl-benfica" }, + { id: "again", name: "SL Benfica", abbreviation: "SLB", slug: "sl-benfica-2" }, + { id: "youth", name: "SL BENFICA 'A'", abbreviation: null, slug: "sl-benfica-a" }, + { id: "other", name: "C BENFICA C BRANCO", abbreviation: null, slug: "c-benfica" }, + ]).map((team) => team.id); + expect(rowsOf("SLB").sort()).toEqual(["again", "senior"]); + expect(rowsOf("SL BENFICA 'A'")).toEqual([]); + expect(isTeam("MAR", { name: "Marítimo Madeira Andebol SAD", abbreviation: null, slug: "maritimo" })).toBe(true); + expect(isTeam("SLB", { name: "Sporting CP", abbreviation: "SCP", slug: "sporting-cp" })).toBe(false); + expect(isTeam("AAAS", { name: "AA Águas Santas 'B'", abbreviation: null, slug: "aa-b" })).toBe(false); + }); +}); diff --git a/apps/api/src/archive/directory.ts b/apps/api/src/archive/directory.ts index fce288a..288a1ba 100644 --- a/apps/api/src/archive/directory.ts +++ b/apps/api/src/archive/directory.ts @@ -1,5 +1,6 @@ import { Prisma } from "../generated/prisma/client.js"; import type { Db } from "../db.js"; +import { shownClub } from "./labels.js"; import { directorySides, type TeamMatch } from "./match.js"; import { clubKey } from "./people.js"; @@ -35,7 +36,8 @@ export function teamSideRows( for (const raw of sides) { if (!raw || seen.has(raw)) continue; seen.add(raw); - let name = canonical(raw); + // The sigla list and the country names win over whichever spelling the folder used. "Juntar nomes" still wins. + let name = shownClub(raw) ?? canonical(raw); if (aliasOf.size) name = aliasOf.get(clubKey(raw)) ?? aliasOf.get(clubKey(name)) ?? name; const key = fold(name); const label = byKey.get(key) ?? name; diff --git a/apps/api/src/archive/labels.ts b/apps/api/src/archive/labels.ts new file mode 100644 index 0000000..1f14c48 --- /dev/null +++ b/apps/api/src/archive/labels.ts @@ -0,0 +1,12 @@ +import { nationalSideName } from "./match.js"; +import { isSquadSide, sameClubName } from "../sports/fpa-siglas.js"; + +/** + * The one name the archive shows for a side. A sigla or a sponsor form becomes the official club ("SLB" and + * "Águas Santas" are not two clubs). A country becomes its Portuguese name ("ESP" → Espanha). A youth side is + * left alone (null), and so is a name this does not know: the caller keeps the team it already resolved. + */ +export function shownClub(raw: string): string | null { + if (!raw.trim() || isSquadSide(raw)) return null; + return sameClubName(raw) ?? nationalSideName(raw); +} diff --git a/apps/api/src/archive/match.ts b/apps/api/src/archive/match.ts index 410a6fe..3b15028 100644 --- a/apps/api/src/archive/match.ts +++ b/apps/api/src/archive/match.ts @@ -1,5 +1,5 @@ import { sameTeam, sameWords, words } from "../delivery/zerozero.js"; -import { officialSigla } from "../sports/fpa-siglas.js"; +import { officialClub, officialSigla, sameClubName } from "../sports/fpa-siglas.js"; /** * What a gallery folder's place and name say about its game. The archives are organised by season, competition @@ -396,6 +396,7 @@ const COUNTRIES: Record = { can: "Canadá", egy: "Egito", egypt: "Egito", tun: "Tunísia", alg: "Argélia", mar: "Marrocos", ang: "Angola", cpv: "Cabo Verde", jpn: "Japão", kor: "Coreia do Sul", chn: "China", qat: "Catar", ksa: "Arábia Saudita", bah: "Bahrein", kuw: "Kuwait", iri: "Irão", ind: "Índia", gbr: "Grã-Bretanha", eng: "Inglaterra", irl: "Irlanda", lux: "Luxemburgo", sui: "Suíça", + uru: "Uruguai", uruguay: "Uruguai", }; function countryName(name: string): string { @@ -404,9 +405,23 @@ function countryName(name: string): string { let countryNames: Set | null = null; +/** + * The Portuguese name when this side is a country ("ESP", "Spain", "Espanha" → Espanha). Null for a club, including + * a sigla that is also a country code ("MAR" is Marítimo, "BEL" is Belenenses). + */ +export function nationalSideName(name: string | null | undefined): string | null { + if (!name || sameClubName(name)) return null; + const n = fold(name.trim()); + if (!n) return null; + if (COUNTRIES[n]) return COUNTRIES[n]; + countryNames ??= new Set(Object.values(COUNTRIES).map(fold)); + if (!countryNames.has(n)) return null; + return Object.values(COUNTRIES).find((value) => fold(value) === n) ?? null; +} + /** A national team's side ("Portugal", "POR", "Seleção Nacional A") rather than a club. */ export function isNationalSide(name: string | null | undefined): boolean { - if (!name) return false; + if (!name || sameClubName(name)) return false; const n = fold(name.trim()); countryNames ??= new Set(Object.values(COUNTRIES).map(fold)); return !!COUNTRIES[n] || countryNames.has(n) || /sele[cç][aãoõ]/i.test(name); @@ -479,6 +494,20 @@ export function teamsNamed isTeam(name, t)); } +/** + * Every stored row of this side's club ("SLB" and "SL BENFICA" are one club, including rows per season). + * One team when the side is not on the sigla list and exactly one team fits. None when it is ambiguous. + * A youth side is not the first team's rows. + */ +export function clubTeamIds(side: string, teams: T[]): T[] { + const club = sameClubName(side); + if (club) { + return teams.filter((team) => sameClubName(team.name) === club || (!!team.abbreviation && sameClubName(team.abbreviation) === club)); + } + const hits = teamsNamed(side, teams); + return hits.length === 1 ? hits : []; +} + export function isTeam(name: string, team: { name: string; abbreviation: string | null; slug: string }): boolean { const n = fold(name); if (!n) return false; @@ -491,6 +520,10 @@ export function isTeam(name: string, team: { name: string; abbreviation: string // ("Águas Santas Milaneza" is A, S, M), and these teams have no abbreviation of their own. const sigla = officialSigla(team.name); if (sigla && fold(sigla) === n) return true; + // "MAR" and "Marítimo" are one club on the sigla list, even when the stored name is not the initials. + const sideClub = officialClub(name); + const teamClub = officialClub(team.name); + if (sideClub && teamClub && sideClub === teamClub) return true; return name.trim().length <= 6 && !/\s/.test(name.trim()) && isInitials(name, team.name); } @@ -604,7 +637,8 @@ export type TeamMatch = ((name: string) => string) & { knownName(name: string): export function teamMatcher(teams: readonly TeamRef[]): TeamMatch { const prepared = teams.map((t) => { const sigla = officialSigla(t.name); - return { t, variant: isVariantSide(t.name), abbr: fold(t.abbreviation ?? ""), slug: fold(t.slug), name: fold(t.name), words: words(t.name), sigla: sigla ? fold(sigla) : "" }; + const club = officialClub(t.name) ?? ""; + return { t, variant: isVariantSide(t.name), abbr: fold(t.abbreviation ?? ""), slug: fold(t.slug), name: fold(t.name), words: words(t.name), sigla: sigla ? fold(sigla) : "", club }; }); const knownName = (raw: string): string | null => { const label = teamLabel(raw); @@ -614,6 +648,7 @@ export function teamMatcher(teams: readonly TeamRef[]): TeamMatch { const variant = isVariantSide(label); const nameWords = words(label); const short = label.trim().length <= 6 && !/\s/.test(label.trim()); + const sideClub = officialClub(label) ?? ""; const fits = new Map(); for (const p of prepared) { // The same tests as isTeam, in the same order. @@ -624,6 +659,7 @@ export function teamMatcher(teams: readonly TeamRef[]): TeamMatch { p.name === n || sameWords(nameWords, p.words) || (!!p.sigla && p.sigla === n) || + (!!sideClub && p.club === sideClub) || (short && isInitials(label, p.t.name)); if (fit) fits.set(p.name, p.t); } diff --git a/apps/api/src/archive/people.ts b/apps/api/src/archive/people.ts index cba8875..13ee955 100644 --- a/apps/api/src/archive/people.ts +++ b/apps/api/src/archive/people.ts @@ -8,6 +8,7 @@ import { cosine, inFocus, THRESHOLDS } from "../faces/math.js"; import { notFound } from "../lib/errors.js"; import type { UrlSigner } from "../storage/storage.js"; import { gallerySeasons, publishedPhotos } from "./gallery.js"; +import { shownClub } from "./labels.js"; import { isNationalSide } from "./match.js"; import type { Viewer } from "./viewer.js"; import { videoFaceCrop, videoScope } from "./video-faces.js"; @@ -73,7 +74,10 @@ export function clubKind(name: string): "national" | "club" | "other" { const n = clubKey(name); if (!n || n === "sem clube" || n === "outros") return "other"; const base = name.trim().replace(/\s+(u|sub[- ]?)\d{2}$/i, "").replace(/\s+\((m|f|masc|fem)\)$/i, "").trim(); - return isNationalSide(name) || isNationalSide(base) ? "national" : "club"; + if (isNationalSide(name) || isNationalSide(base)) return "national"; + // "Espanha Feminina", "Portugal Sub-18": the country is the seleção, the rest is the squad. + const first = name.trim().split(/\s+/)[0] ?? ""; + return first && first !== name.trim() && isNationalSide(first) ? "national" : "club"; } /** The face, as a box in the preview's frame (an edited photo's preview is its crop). */ @@ -191,10 +195,13 @@ export async function registerArchivePeopleRoutes(app: FastifyInstance, deps: De // "Juntar nomes": other names of a club count as the club. const aliases = await db.archiveClubAlias.findMany({ where: { sourceId: v.s }, select: { aliasKey: true, alias: true, name: true } }); const aliasOf = new Map(aliases.map((a) => [a.aliasKey, a.name])); - const clubOf = (s: string) => aliasOf.get(clubKey(s)) ?? s; - const wanted = query.club ? clubKey(clubOf(query.club)) : null; + const labelOf = (s: string) => { + const base = shownClub(s) ?? s; + return aliasOf.get(clubKey(s)) ?? aliasOf.get(clubKey(base)) ?? base; + }; + const wanted = query.club ? clubKey(labelOf(query.club)) : null; const words = fold(query.q ?? "").split(/\s+/).filter(Boolean); - const shown = rows.filter((r) => (!wanted || (r.club && clubKey(clubOf(r.club)) === wanted)) && words.every((w) => fold(`${r.name} ${r.club ?? ""} ${r.number ?? ""}`).includes(w))); + const shown = rows.filter((r) => (!wanted || (r.club && clubKey(labelOf(r.club)) === wanted)) && words.every((w) => fold(`${r.name} ${r.club ?? ""} ${r.number ?? ""}`).includes(w))); // A face for those without a reference photo: their sharpest face in the visible photos. const noRef = shown.filter((r) => !r.reference).map((r) => r.id); const faces = noRef.length @@ -231,7 +238,7 @@ export async function registerArchivePeopleRoutes(app: FastifyInstance, deps: De GROUP BY btrim(name)`; const clubs = new Map }>(); const add = (raw: string, people: number, games: number) => { - const name = clubOf(raw); + const name = labelOf(raw); const key = clubKey(name); const cur = clubs.get(key) ?? { name, people: 0, games: 0, also: new Set() }; cur.people += people; @@ -246,7 +253,7 @@ export async function registerArchivePeopleRoutes(app: FastifyInstance, deps: De .map((r) => ({ id: r.id, name: r.name, - club: r.club, + club: r.club ? labelOf(r.club) : null, number: r.number, photos: Number(r.confirmed), probable: Number(r.probable), diff --git a/apps/api/src/archive/viewer.ts b/apps/api/src/archive/viewer.ts index 7d8e115..1eb30dc 100644 --- a/apps/api/src/archive/viewer.ts +++ b/apps/api/src/archive/viewer.ts @@ -12,7 +12,7 @@ import { CloudClient, pollLogin, startLogin } from "./nextcloud.js"; import { GALLERY_KINDS, galleryMemberIds, gallerySeasons, listStoredGalleries, publishedPhotos, seasonOf } from "./gallery.js"; import { readStoredRaws, readStoredTeams } from "./directory.js"; import type { FaceService } from "../faces/service.js"; -import { faceBox, facesOfPhotos, registerArchivePeopleRoutes } from "./people.js"; +import { clubKind, faceBox, facesOfPhotos, registerArchivePeopleRoutes } from "./people.js"; import { registerArchiveDownloadRoutes } from "./downloads.js"; import { registerArchiveReviewRoutes } from "./review.js"; import type { ArchiveService } from "./service.js"; @@ -485,7 +485,8 @@ export async function registerArchiveViewerRoutes( const source = await db.cloudSource.findUnique({ where: { id: sourceId }, select: { directoryBuiltAt: true } }); // The worker has not written this archive's teams yet. The page keeps its spinner; this answer is a read. if (!source?.directoryBuiltAt) return { teams: [], ready: false }; - return { teams: await readStoredTeams(db, sourceId, visible), ready: true }; + const teams = await readStoredTeams(db, sourceId, visible); + return { teams: teams.map((team) => ({ ...team, kind: clubKind(team.name) })), ready: true }; }); /** The players named on the viewer's photos (a session's folder per athlete, the editors' tags). */ diff --git a/apps/api/src/faces/numbers.ts b/apps/api/src/faces/numbers.ts index 2ac4393..0f24b08 100644 --- a/apps/api/src/faces/numbers.ts +++ b/apps/api/src/faces/numbers.ts @@ -1,4 +1,4 @@ -import { isExhibition, isNationalSide, seasonOf, teamsNamed } from "../archive/match.js"; +import { clubTeamIds, isExhibition, isNationalSide, seasonOf, teamsNamed } from "../archive/match.js"; import type { Db } from "../db.js"; import { normLabel } from "../jersey/service.js"; import { selectionKey, selectionNeedles } from "./selection.js"; @@ -63,6 +63,7 @@ export async function numberContext(db: Db, eventId: string, now = new Date()): const folders = await db.cloudFolder.findMany({ where: { eventId }, select: { path: true }, take: 8 }); side = selectionKey([e.home, e.away ?? "", e.competition ?? "", ...folders.map((f) => f.path)]); } + const linked = [e.homeTeamId, e.awayTeamId].filter((t): t is string => !!t); return { organizationId: e.organizationId, eventId, @@ -72,10 +73,42 @@ export async function numberContext(db: Db, eventId: string, now = new Date()): side, current: season === seasonOf(day(now)), official: !!e.fixture, - teamIds: [e.homeTeamId, e.awayTeamId].filter((t): t is string => !!t), + teamIds: national ? linked : await squadIds(db, eventId, [e.home, e.away ?? ""], linked, season), }; } +/** Teams of one sport, kept briefly: a face pass asks this for every photo of a game. */ +const teamsBySport = new Map(); +const TEAMS_TTL_MS = 10 * 60_000; + +/** + * The squad rows for this game. The sigla and the full name are one club, and a club stored once per competition + * still counts as that club. Only rows that have players in the season. A national game keeps the ids it was + * given (the caller does not ask). + */ +async function squadIds(db: Db, eventId: string, sides: string[], linked: string[], season: string): Promise { + const sport = await eventSport(db, eventId); + if (!sport) return linked; + let cached = teamsBySport.get(sport); + if (!cached || Date.now() - cached.at > TEAMS_TTL_MS) { + const teams = await db.sportsTeam.findMany({ + where: { sport: { equals: sport, mode: "insensitive" } }, + select: { id: true, name: true, abbreviation: true, slug: true }, + }); + cached = { at: Date.now(), teams }; + teamsBySport.set(sport, cached); + } + const ids = [...new Set([...linked, ...sides.filter(Boolean).flatMap((side) => clubTeamIds(side, cached!.teams).map((team) => team.id))])]; + if (!ids.length) return []; + const rows = await db.sportsPlayer.findMany({ + where: { teamId: { in: ids }, season }, + select: { teamId: true }, + distinct: ["teamId"], + }); + const withSquad = rows.map((row) => row.teamId); + return withSquad.length ? withSquad : linked; +} + /** * Fills a game's missing clubs from the teams of its sport, when the side names exactly one of them. * A session, a national team, or an exhibition is left alone. Idempotent. diff --git a/apps/api/src/sports/fpa-siglas.ts b/apps/api/src/sports/fpa-siglas.ts index c100055..78c10a8 100644 --- a/apps/api/src/sports/fpa-siglas.ts +++ b/apps/api/src/sports/fpa-siglas.ts @@ -6,33 +6,38 @@ * event's homeShort/awayShort from the club name when they are not set. Matching is by a normalised name, so case, * accents, punctuation and sponsor dashes do not matter; a club not listed simply keeps the full name (no harm). * + * The same list is how the archive shows one club once. Folders and older seasons write the sigla ("SLB", "AAAS") + * or a sponsor ("FC Porto / Sofarma"); the directory uses the official name. Codes that are a club here stay a + * club even when the letters are also a country ("BEL" Belenenses, "MAR" Marítimo). A youth side ("SL Benfica B", + * "SL BENFICA 'A'") is not the first team. + * * Update once per season when the federation changes club names or sponsors. */ /** Each short code with the club-name forms it may appear as (official name first, then safe variants). */ const CLUBS: ReadonlyArray = [ - // Andebol 1 (masculino) + // Andebol 1 (masculino). Extra forms are the siglas and names the archive folders have used for this club. ["ABC", ["ABC de Braga", "ABC Braga"]], ["ADC", ["AD Carvalhos Sernox", "AD Carvalhos"]], ["AAAS", ["Águas Santas Milaneza", "Águas Santas", "AA Águas Santas"]], - ["AAA", ["Avanca Bioria Bondalti", "Avanca"]], - ["CFB", ["CF Os Belenenses", "Os Belenenses"]], - ["FCP", ["FC Porto"]], + ["AAA", ["Avanca Bioria Bondalti", "Avanca", "AA Avanca", "AVA"]], + ["CFB", ["CF Os Belenenses", "Os Belenenses", "Belenenses", "BEL"]], + ["FCP", ["FC Porto", "Porto"]], ["GCST", ["GC Santo Tirso Retrotarget", "GC Santo Tirso"]], - ["CSM", ["Marítimo Madeira Andebol SAD", "Marítimo Madeira"]], - ["PAC", ["Póvoa AC Bodegão CCR Proteu", "Póvoa AC"]], - ["SLB", ["SL Benfica"]], - ["SCP", ["Sporting CP"]], - ["VSC", ["Vitória SC"]], + ["CSM", ["Marítimo Madeira Andebol SAD", "Marítimo Madeira", "Marítimo", "CS Maritimo", "CS Maritimo Madeira", "MAR"]], + ["PAC", ["Póvoa AC Bodegão CCR Proteu", "Póvoa AC", "Povoa", "Povoa Andebol Clube", "POV"]], + ["SLB", ["SL Benfica", "Benfica", "Sport Lisboa e Benfica"]], + ["SCP", ["Sporting CP", "Sporting", "Sporting Clube de Portugal"]], + ["VSC", ["Vitória SC", "Vitória", "Vitoria", "VIT"]], // Campeonato Betclic (feminino) ["SPS", ["ADA São Pedro do Sul Multisac", "ADA São Pedro do Sul"]], - ["ALA", ["Alavarium"]], + ["ALA", ["Alavarium", "Alavarium AC"]], ["CALE", ["CA Leça"]], ["CDF", ["CD Feirense Movit", "CD Feirense"]], - ["GIL", ["CDE Gil Eanes"]], - ["CJAG", ["CJ Almeida Garrett Gesti Douro UAE", "CJ Almeida Garrett"]], + ["GIL", ["CDE Gil Eanes", "CDES Gil Eanes"]], + ["CJAG", ["CJ Almeida Garrett Gesti Douro UAE", "CJ Almeida Garrett", "CJ A. Garrett", "Almeida Garrett", "Clube Jovem Almeida Garrett"]], ["JUVE", ["Juve Lis"]], - ["MAD", ["Madeira SAD"]], + ["MAD", ["Madeira SAD", "Madeira Andebol SAD", "Mad Max"]], ]; /** Lower-case, accent-free, non-alphanumerics collapsed to single spaces: "CD Feirense -Movit" -> "cd feirense movit". */ @@ -46,10 +51,56 @@ function normalise(name: string): string { } const BY_NAME = new Map(); -for (const [sigla, names] of CLUBS) for (const name of names) BY_NAME.set(normalise(name), sigla); +const BY_SIGLA = new Map(); +const CANONICAL = new Map(); +for (const [sigla, names] of CLUBS) { + CANONICAL.set(sigla, names[0] ?? sigla); + BY_SIGLA.set(normalise(sigla), sigla); + for (const name of names) BY_NAME.set(normalise(name), sigla); +} + +/** A reserve, youth or quoted squad ("Benfica B", "SL BENFICA 'A'"), not the first team. "SLB" and "CFB" are not. */ +export function isSquadSide(name: string): boolean { + const n = name.normalize("NFD").replace(/\p{Diacritic}/gu, ""); + if (/['"´]\s*[abc]\s*['"´]/i.test(n)) return true; + if (/\b(sub[\s-]?\d{2}|u[\s-]?\d{2}|feminin[oa]s?|juniores|juvenis|iniciados|infantis|benjamins|revelacao)\b/i.test(n)) return true; + return /(?:^|\s)b$/i.test(n.trim()); +} + +/** A part written as its own club ("AC", "FC", "EXT."), so a slash name is not one club plus a sponsor. */ +function looksLikeClub(part: string): boolean { + const n = normalise(part); + return /\b(?:fc|sc|cf|cd|ud|gd|ad|cr|ac|sad|gc|ca|oc|cs|sl|cp|ext|colegio|clube|associacao)\b/.test(n); +} /** The official short code for a club name, or undefined when it is not in the list (then keep the full name). */ export function officialSigla(name: string | null | undefined): string | undefined { if (!name) return undefined; - return BY_NAME.get(normalise(name)); + const key = normalise(name); + return BY_SIGLA.get(key) ?? BY_NAME.get(key); +} + +/** The list's club for this sigla or name ("SLB", "SL Benfica" → "SL Benfica"). Undefined when it is not that club. */ +export function officialClub(name: string | null | undefined): string | undefined { + const sigla = officialSigla(name); + return sigla ? CANONICAL.get(sigla) : undefined; +} + +/** + * One club's official name. "FC Porto / Sofarma" is FC Porto (the sponsor is not a club). "Benfica / Porto" is not + * one club. A youth side stays unnamed here, so it is not folded into the first team. + */ +export function sameClubName(name: string | null | undefined): string | undefined { + if (!name) return undefined; + const trimmed = name.trim(); + if (!trimmed || isSquadSide(trimmed)) return undefined; + const direct = officialClub(trimmed); + if (direct) return direct; + const parts = trimmed.split(/\s*\/\s*/).map((part) => part.trim()).filter(Boolean); + if (parts.length < 2 || parts.some((part) => isSquadSide(part))) return undefined; + const found = [...new Set(parts.map((part) => officialClub(part)).filter((club): club is string => !!club))]; + if (found.length !== 1) return undefined; + const sponsor = parts.filter((part) => !officialClub(part)); + if (sponsor.some((part) => looksLikeClub(part))) return undefined; + return found[0]; } diff --git a/apps/site/src/app/arquivo/[id]/Browse.tsx b/apps/site/src/app/arquivo/[id]/Browse.tsx index 60a2f45..1582141 100644 --- a/apps/site/src/app/arquivo/[id]/Browse.tsx +++ b/apps/site/src/app/arquivo/[id]/Browse.tsx @@ -209,6 +209,16 @@ export function Browse({ [clubs], ); const shownTeams = useMemo(() => (teams ?? []).filter((t) => fold(t.name).includes(fold(q.trim()))), [teams, q]); + /** Clubs, then national teams. A country is a seleção, not another club. */ + const teamGroups = useMemo(() => { + const visible = shownTeams.slice(0, teamsShown); + const clubs = visible.filter((t) => t.kind !== "national"); + const nationals = visible.filter((t) => t.kind === "national"); + return [ + clubs.length ? { label: "Clubes", items: clubs } : null, + nationals.length ? { label: "Seleções", items: nationals } : null, + ].filter((group): group is { label: string; items: typeof visible } => !!group); + }, [shownTeams, teamsShown]); const shownPlayers = useMemo(() => (players ?? []).filter((p) => fold(p.name).includes(fold(q.trim()))).slice(0, 300), [players, q]); let emptyPeople = ""; @@ -664,34 +674,39 @@ export function Browse({
{!teams && !failed && } {teams && shownTeams.length === 0 &&

Nenhuma equipa com esse nome.

} -
- {shownTeams.slice(0, teamsShown).map((t) => ( -
- - + {teamGroups.map((grp) => ( +
+ {teamGroups.length > 1 &&

{grp.label}

} +
+ {grp.items.map((t) => ( +
+ + +
+ ))}
- ))} -
+
+ ))} {shownTeams.length > teamsShown && (