From 9d79270859c21cbebcb86ea1672678d5c333b104 Mon Sep 17 00:00:00 2001 From: spark Date: Mon, 19 Oct 2026 10:55:15 +0000 Subject: [PATCH] Archive: open a tournament in place, and add people by their FPA licence. - A tournament's tile opens its galleries in place of the tiles (they opened below the whole list, out of sight). - The FPA licence (CIPA) is not the id the federation keeps registrations under: the portal page gives that id, then every registration (season, role, club) is read. A person can be added by licence number from Pessoas or while naming a face in the review ("198159" offers the federation's person); the licence photo becomes the reference, so coaches, delegates and staff are recognised in event photos no match report covers. - people.licence: the same licence is always the same person, also when a match report names them later. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_017sovZz1NXBwx4VySojoyA1 --- .../migration.sql | 3 + apps/api/prisma/schema.prisma | 3 + apps/api/src/app.ts | 2 +- apps/api/src/archive/review.ts | 78 +++++++++- apps/api/src/archive/viewer.ts | 5 +- apps/api/src/sports/providers.ts | 81 +++++++++++ apps/api/src/sports/service.ts | 70 ++++++++- apps/api/test/archive.test.ts | 24 +++- apps/api/test/sports.test.ts | 30 ++++ .../site/src/app/arquivo/[id]/ArchiveView.tsx | 2 +- apps/site/src/app/arquivo/[id]/Browse.tsx | 135 ++++++++++++++++-- apps/site/src/app/arquivo/[id]/Review.tsx | 67 +++++++-- apps/site/src/app/arquivo/[id]/api.ts | 26 ++++ apps/site/src/app/arquivo/[id]/archive.css | 76 ++++++++++ 14 files changed, 564 insertions(+), 38 deletions(-) create mode 100644 apps/api/prisma/migrations/20261019180000_person_licence/migration.sql diff --git a/apps/api/prisma/migrations/20261019180000_person_licence/migration.sql b/apps/api/prisma/migrations/20261019180000_person_licence/migration.sql new file mode 100644 index 0000000..ea873fa --- /dev/null +++ b/apps/api/prisma/migrations/20261019180000_person_licence/migration.sql @@ -0,0 +1,3 @@ +-- Handball: a person's federation licence number (CIPA). +ALTER TABLE "people" ADD COLUMN "licence" TEXT; +CREATE UNIQUE INDEX "people_organization_id_licence_key" ON "people"("organization_id", "licence"); diff --git a/apps/api/prisma/schema.prisma b/apps/api/prisma/schema.prisma index 94cccb5..0759171 100644 --- a/apps/api/prisma/schema.prisma +++ b/apps/api/prisma/schema.prisma @@ -654,6 +654,8 @@ model Person { referenceEmbedding Float[] @default([]) @map("reference_embedding") /// The squad entry this person came from (kept in step when squads change). sportsPlayerId String? @map("sports_player_id") @db.Uuid + /// Handball: the federation licence number (CIPA), when the person was added by it or seen on a match report. + licence String? /// Face recognition turned off for this person (an archive editor): no centroid, no reference, never suggested; /// still named by hand. recognitionOffAt DateTime? @map("recognition_off_at") @@ -668,6 +670,7 @@ model Person { @@unique([organizationId, name]) @@unique([organizationId, sportsPlayerId]) + @@unique([organizationId, licence]) @@map("people") } diff --git a/apps/api/src/app.ts b/apps/api/src/app.ts index 34bcb16..f76cb86 100644 --- a/apps/api/src/app.ts +++ b/apps/api/src/app.ts @@ -145,7 +145,7 @@ export async function buildApp({ config, db, realtime, fetchImpl, reporter: give await registerArchiveRoutes(app, { db, sessions, archive, storageRoot: config.STORAGE_ROOT, minFreeBytes: config.ARCHIVE_MIN_FREE_GB * 1e9 }); // The API never runs the face engine: it confirms and merges groups; the worker detects and groups. const faces = new FaceService({ db, storage, broadcaster, log: app.log }); - await registerArchiveViewerRoutes(app, { db, secrets, signer, archive, tokens: new ViewerTokens(config.JWT_SECRET), faces, storage, secret: config.JWT_SECRET, fetchImpl }); + await registerArchiveViewerRoutes(app, { db, secrets, signer, archive, tokens: new ViewerTokens(config.JWT_SECRET), faces, storage, secret: config.JWT_SECRET, fetchImpl, sports }); await registerCompositionRoutes(app, { db, sessions, storage, storageRoot: config.STORAGE_ROOT }); await registerSearchRoutes(app, { db, sessions, signer }); await registerFtpRoutes(app, { db, sessions, ingestRoot: config.INGEST_ROOT, hookSecret: config.SFTPGO_HOOK_KEY }); diff --git a/apps/api/src/archive/review.ts b/apps/api/src/archive/review.ts index 227f9d5..d0ad163 100644 --- a/apps/api/src/archive/review.ts +++ b/apps/api/src/archive/review.ts @@ -6,6 +6,8 @@ import type { Db } from "../db.js"; import { FaceRejected, type FaceService } from "../faces/service.js"; import { AppError, forbidden, notFound } from "../lib/errors.js"; import type { UrlSigner } from "../storage/storage.js"; +import { fpaLatestRole, type SportsService } from "../sports/service.js"; +import type { FpaMember } from "../sports/providers.js"; import { galleryMemberIds } from "./gallery.js"; import { clubKey, faceBox } from "./people.js"; import type { Viewer } from "./viewer.js"; @@ -26,6 +28,8 @@ interface Deps { faces: FaceService; viewerOf: (req: FastifyRequest, sourceId?: string) => Viewer; editableFolders: (v: Viewer) => Promise; + /** Handball: people by their federation licence (CIPA), for FPA archives. */ + sports?: Pick | undefined; /** After "Juntar nomes": lists built with the old names are dropped. */ onClubsChanged?: (sourceId: string) => void; } @@ -45,6 +49,7 @@ const ReviewQuery = z.object({ const Act = z.object({ action: z.enum(["confirm", "reject", "ignore", "undo"]), personId: z.uuid().optional() }); const ChooseQuery = z.object({ q: z.string().trim().min(2).max(80) }); const Merge = z.object({ into: z.string().trim().min(1).max(120), names: z.array(z.string().trim().min(1).max(120)).min(1).max(20) }); +const Licence = z.object({ licence: z.string().trim().regex(/^\d{3,9}$/) }); const Unmerge = z.object({ name: z.string().trim().min(1).max(120) }); const Recognition = z.object({ enabled: z.boolean(), removeConfirmed: z.boolean().default(false) }); @@ -91,11 +96,11 @@ export async function registerArchiveReviewRoutes(app: FastifyInstance, deps: De const v = viewerOf(req, sourceId); const { q } = ChooseQuery.parse(req.query); if (!(await editScope(v))) throw forbidden("archive_edit_required"); - const source = await db.cloudSource.findUnique({ where: { id: sourceId }, select: { organizationId: true } }); + const source = await db.cloudSource.findUnique({ where: { id: sourceId }, select: { organizationId: true, look: true } }); if (!source) throw notFound("source_not_found"); const like = `%${q.replace(/[\\%_]/g, "")}%`; - const rows = await db.$queryRaw<{ id: string; name: string; club: string | null; number: string | null; reference: boolean }[]>` - SELECT p.id, p.name, + const rows = await db.$queryRaw<{ id: string; name: string; club: string | null; number: string | null; reference: boolean; licence: string | null }[]>` + SELECT p.id, p.name, p.licence, COALESCE(p.club, t.name) AS club, COALESCE(p.number, sp.number) AS number, p.reference_key IS NOT NULL AS reference @@ -111,14 +116,77 @@ export async function registerArchiveReviewRoutes(app: FastifyInstance, deps: De OR COALESCE(sp.full_name, '') ILIKE ${like} OR p.number = ${q} OR sp.number = ${q} + OR p.licence = ${q} + OR sp.external_id = ${q} ) - ORDER BY (p.number = ${q} OR sp.number = ${q}) DESC, (p.reference_key IS NOT NULL) DESC, length(p.name) + ORDER BY (p.licence = ${q} OR sp.external_id = ${q}) DESC, (p.number = ${q} OR sp.number = ${q}) DESC, (p.reference_key IS NOT NULL) DESC, length(p.name) LIMIT 8`; + // A licence number nobody here has yet: who the federation says it is, to add them. + const fpa = fpaArchive(source) && /^\d{5,9}$/.test(q) && !rows.some((r) => r.licence === q) ? await memberOf(q) : null; return { - people: rows.map((r) => ({ id: r.id, name: r.name, club: r.club, number: r.number, reference: r.reference ? signer.personUrl(r.id) : null })), + people: rows.map((r) => ({ id: r.id, name: r.name, club: r.club, number: r.number, reference: r.reference ? signer.personUrl(r.id) : null, ...(r.licence && { licence: r.licence }) })), + ...(fpa && { fpa: memberOut(fpa) }), }; }); + /** Handball archives look people up by licence. Kept a while: typing a number asks once per number. */ + const fpaArchive = (source: { look: string | null }) => !!deps.sports && source.look === "fpa"; + const members = new Map }>(); + const memberOf = (licence: string): Promise => { + const hit = members.get(licence); + if (hit && Date.now() - hit.at < 30 * 60_000) return hit.member; + const member = deps.sports!.fpa.member(licence).catch(() => null); + members.set(licence, { at: Date.now(), member }); + if (members.size > 500) for (const [k, m] of members) if (Date.now() - m.at > 30 * 60_000) members.delete(k); + return member; + }; + const memberOut = (m: FpaMember) => { + const latest = fpaLatestRole(m); + return { + licence: m.licence, + name: m.name, + photo: m.photo, + club: latest?.club ?? null, + role: latest ? `${latest.role} · ${latest.season}` : m.registeredAs, + // Every season, newest first, as "2024/25 · Treinador · Estarreja AC" (no birth date: not needed here). + history: [...m.registrations] + .sort((a, b) => b.season.localeCompare(a.season)) + .slice(0, 12) + .map((r) => [r.season, r.level ? `${r.role} ${r.level}` : r.role, r.club].filter(Boolean).join(" · ")), + }; + }; + + /** Who a licence number is, for those who review (to add them before naming a face). */ + app.get("/v1/archive/:sourceId/fpa/:licence", async (req) => { + const { sourceId } = SourceParams.parse(req.params); + const { licence } = Licence.parse(req.params); + const v = viewerOf(req, sourceId); + if (!(await editScope(v))) throw forbidden("archive_edit_required"); + const source = await db.cloudSource.findUnique({ where: { id: sourceId }, select: { organizationId: true, look: true } }); + if (!source || !fpaArchive(source)) throw notFound("fpa_not_available"); + const member = await memberOf(licence); + if (!member) throw notFound("fpa_member_not_found"); + const person = await db.person.findFirst({ where: { organizationId: source.organizationId, licence }, select: { id: true, name: true } }); + return { member: memberOut(member), person }; + }); + + /** + * Adds (or brings up to date) a person from their licence: name, club, and the licence photo as the reference, + * so recognition finds them in event photos where no match report names them. + */ + app.post("/v1/archive/:sourceId/people/from-licence", async (req) => { + const { sourceId } = SourceParams.parse(req.params); + const v = viewerOf(req, sourceId); + if (!(await editScope(v))) throw forbidden("archive_edit_required"); + const { licence } = Licence.parse(req.body); + const source = await db.cloudSource.findUnique({ where: { id: sourceId }, select: { organizationId: true, look: true } }); + if (!source || !fpaArchive(source)) throw notFound("fpa_not_available"); + const done = await deps.sports!.personFromFpaLicence(source.organizationId, licence); + members.delete(licence); + await log(v, done.created ? "person_from_licence" : "person_licence_update", { personId: done.person.id }); + return { person: { ...done.person, licence, reference: done.reference }, created: done.created, member: memberOut(done.member) }; + }); + /** * Face groups to review in the viewer's editable folders, one card per group: its sharpest faces, who it is * (named) or might be (suggested, with how sure), its event; and the people with suggestions waiting. diff --git a/apps/api/src/archive/viewer.ts b/apps/api/src/archive/viewer.ts index a4d4d18..6143557 100644 --- a/apps/api/src/archive/viewer.ts +++ b/apps/api/src/archive/viewer.ts @@ -10,6 +10,7 @@ import { AppError, badRequest, notFound, unauthorized } from "../lib/errors.js"; import type { LocalStorage, UrlSigner } from "../storage/storage.js"; import { CloudClient, pollLogin, startLogin } from "./nextcloud.js"; import { GALLERY_KINDS, galleryMemberIds, gallerySeasons, listStoredGalleries, publishedPhotos, seasonOf } from "./gallery.js"; +import type { SportsService } from "../sports/service.js"; import { directorySides, teamMatcher, type TeamMatch } from "./match.js"; import type { FaceService } from "../faces/service.js"; import { clubKey, faceBox, facesOfPhotos, registerArchivePeopleRoutes } from "./people.js"; @@ -105,7 +106,7 @@ const ListQuery = z.object({ export async function registerArchiveViewerRoutes( app: FastifyInstance, - deps: { db: Db; secrets: SecretBox | undefined; signer: UrlSigner; archive: ArchiveService; tokens: ViewerTokens; faces: FaceService; storage: LocalStorage; secret: string; fetchImpl?: typeof fetch | undefined }, + deps: { db: Db; secrets: SecretBox | undefined; signer: UrlSigner; archive: ArchiveService; tokens: ViewerTokens; faces: FaceService; storage: LocalStorage; secret: string; fetchImpl?: typeof fetch | undefined; sports?: Pick | undefined }, ) { const { db, signer, tokens } = deps; const fetchImpl = deps.fetchImpl ?? fetch; @@ -726,7 +727,7 @@ export async function registerArchiveViewerRoutes( }); await registerArchivePeopleRoutes(app, { db, signer, viewerOf, visibleFolders }); - await registerArchiveReviewRoutes(app, { db, signer, faces: deps.faces, viewerOf, editableFolders, onClubsChanged: (sourceId) => forgetLists(sourceId, "teams") }); + await registerArchiveReviewRoutes(app, { db, signer, faces: deps.faces, viewerOf, editableFolders, sports: deps.sports, onClubsChanged: (sourceId) => forgetLists(sourceId, "teams") }); await registerArchiveDownloadRoutes(app, { db, storage: deps.storage, secret: deps.secret, viewerOf, visibleFolders }); } diff --git a/apps/api/src/sports/providers.ts b/apps/api/src/sports/providers.ts index 1996f45..4f3f24b 100644 --- a/apps/api/src/sports/providers.ts +++ b/apps/api/src/sports/providers.ts @@ -374,6 +374,23 @@ export class FpaProvider { return parseFpaMatchPage(await this.html(`${FpaProvider.PORTAL}/jogo/${encodeURIComponent(gameId)}/`)); } + /** + * Someone registered with the federation, by licence number (CIPA, as printed on match reports and the portal): + * name, licence photo and every registration (season, as what, where). The portal's page gives the federation's + * internal id, which the registrations are kept under (it is not the licence number). Null when unknown. + */ + async member(licence: string): Promise { + if (!/^\d{1,9}$/.test(licence)) return null; + const page = parseFpaMemberPage(await this.html(`${FpaProvider.PORTAL}/associado/${encodeURIComponent(licence)}/`)); + if (!page) return null; + let registrations: FpaRegistration[] = []; + if (page.internalId) { + const rows = await get(this.fetcher, `${FpaProvider.WS}/getCipaInscricoes/${encodeURIComponent(page.internalId)}`, { accept: "application/json" }, "json"); + if (Array.isArray(rows)) registrations = (rows as Record[]).map(fpaRegistration).filter((r): r is FpaRegistration => !!r); + } + return { ...page, licence, registrations }; + } + /** An athlete's licence photo (by licence number), if the federation has one. */ async athletePhoto(cipa: string): Promise { const html = await this.html(`${FpaProvider.PORTAL}/associado/${encodeURIComponent(cipa)}/`); @@ -381,6 +398,70 @@ export class FpaProvider { } } +/** A registration of a member for one season: athlete, coach, official, table official or referee. */ +export interface FpaRegistration { + season: string; + kind: "athlete" | "coach" | "official" | "table" | "referee" | "other"; + /** "Atleta", "Treinador", "Delegado técnico", "Árbitro regional"... */ + role: string; + /** The club or team ("AA AVANCA", "Sel.Nac.M"); null for referees. */ + club: string | null; + clubName: string | null; + /** The age level for athletes ("Juvenis F"). */ + level: string | null; + association: string | null; +} + +export interface FpaMember { + licence: string; + internalId: string | null; + name: string; + photo: string | null; + /** "Árbitro, Oficial, Técnico, Atleta", as the portal says. */ + registeredAs: string | null; + registrations: FpaRegistration[]; +} + +const FPA_KINDS: Record = { AT01: "athlete", TEC: "coach", OFI: "official", OMS: "table", ARB: "referee" }; + +function fpaRegistration(r: Record): FpaRegistration | null { + const season = str(r.EPO_DESCRICAO); + if (!season) return null; + const code = str(r.GCI_TIP_INSCRICAO_TI013) ?? ""; + const kind = FPA_KINDS[code] ?? (code.startsWith("AT") ? "athlete" : "other"); + const detail = str(r.FOF_ABREV) ?? str(r.CJU_ABREV); + const role = + kind === "athlete" ? "Atleta" : kind === "coach" ? "Treinador" : kind === "table" ? "Oficial de mesa" : kind === "referee" ? (detail ?? "Árbitro") : (detail ? detail.charAt(0) + detail.slice(1).toLowerCase() : "Oficial"); + return { season, kind, role: fpaAccents(role), club: str(r.CLU_ABREV), clubName: str(r.CLU_NOME), level: str(r.ESC_DESCRICAO), association: str(r.ASS_ABREV) }; +} + +/** The federation's codes are written without accents ("Delegado tecnico", "Funcionario"). */ +function fpaAccents(s: string): string { + const fix: Record = { tecnico: "técnico", tecnica: "técnica", funcionario: "funcionário", medico: "médico", fisioterapeuta: "fisioterapeuta", seccionista: "seccionista", estagiario: "estagiário", arb: "Árb" }; + return s.replace(/\p{L}+/gu, (w) => { + const f = fix[w.toLowerCase()]; + if (!f) return w; + return w[0] === w[0]!.toUpperCase() ? f[0]!.toUpperCase() + f.slice(1) : f; + }); +} + +/** A member's page on the portal: name, photo, the internal id its history is under. Null for an unknown licence. */ +export function parseFpaMemberPage(html: string): Omit | null { + const $ = cheerio.load(html); + const box = $(".association-detail"); + const name = box.find("h3").first().text().replace(/\s+/g, " ").trim(); + if (!box.length || !name) return null; + let registeredAs: string | null = null; + box.find("tr").each((_, tr) => { + const cells = $(tr).children("td"); + if (/inscrito como/i.test(cells.first().text())) registeredAs = cells.eq(1).text().replace(/\s+/g, " ").trim() || null; + }); + const photo = box.find("img").attr("src") ?? null; + // The history table's settings carry the internal id ("cipa":"203445"); the photo's file name ends with it too. + const internalId = /TABLE_CONTENT_\d+\s*=\s*\{[^;]*?"cipa"\s*:\s*"(\d+)"/.exec(html)?.[1] ?? /FOTO_CIPA\/\d+_(\d+)\./i.exec(photo ?? "")?.[1] ?? null; + return { name, photo: photo && /^https:\/\/si\.fpa\.pt\//.test(photo) ? photo : null, registeredAs, internalId }; +} + export interface FpaBoletim { /** Whether the report has the teams yet (it is filled in after the match). */ available: boolean; diff --git a/apps/api/src/sports/service.ts b/apps/api/src/sports/service.ts index 9f143eb..543d84a 100644 --- a/apps/api/src/sports/service.ts +++ b/apps/api/src/sports/service.ts @@ -5,7 +5,7 @@ import type { Db } from "../db.js"; import type { SportsCompetition, SportsPlayer, SportsProvider } from "../generated/prisma/client.js"; import type { IngestLogger } from "../ingest/service.js"; import { DEFAULT_CODE_LIST } from "../library/iptc.js"; -import { badRequest, notFound } from "../lib/errors.js"; +import { AppError, badRequest, notFound } from "../lib/errors.js"; import { waitUntil } from "../lib/idle.js"; import type { LocalStorage } from "../storage/storage.js"; import { type CodeClash, type SquadForCodes, buildCodeLines, hasGeneratedBlock, mergeGenerated, slugify, toTsv } from "./codegen.js"; @@ -13,7 +13,10 @@ import { tallyOf, tallySquadPhotos } from "./squadPhotos.js"; import { type Fetch, type FixtureData, + type FpaMember, FpaProvider, + type FpaRegistration, + fpaShortName, FpfProvider, LIGA_COMPETITIONS, LigaProvider, @@ -938,6 +941,9 @@ export class SportsService { const { db, log } = this.deps; let person = await db.person.findUnique({ where: { organizationId_sportsPlayerId: { organizationId: orgId, sportsPlayerId: p.id } } }); let created = false; + // Handball: someone added by their licence number is the same person on the match report. + if (!person && team.provider === "FPA" && p.externalId) + person = await db.person.findFirst({ where: { organizationId: orgId, licence: p.externalId, sportsPlayerId: null } }); if (!person) { const byName = await db.person.findUnique({ where: { organizationId_name: { organizationId: orgId, name: p.name } } }); if (byName && !byName.sportsPlayerId && (!byName.club || byName.club === club || byName.club === team.name)) person = byName; @@ -978,6 +984,51 @@ export class SportsService { if (photo && !person.referenceKey) headshots.push({ personId: person.id, url: photo }); } + /** + * A person from their handball federation licence (CIPA): the name, club and role of their latest registration, + * and (with biometrics on) the licence photo as the reference, so they are recognised in event photos too (a + * coach, a delegate, a former player), not only where a match report names them. The same licence is always the + * same person: one already added, or seen on a match report, is brought up to date instead. + */ + async personFromFpaLicence(orgId: string, licence: string): Promise<{ person: { id: string; name: string; club: string | null }; member: FpaMember; created: boolean; reference: boolean }> { + const { db, log } = this.deps; + const member = await this.fpa.member(licence.trim()); + if (!member) throw notFound("fpa_member_not_found"); + const org = await db.organization.findUnique({ where: { id: orgId }, select: { biometricsEnabled: true } }); + if (!org) throw notFound("organization_not_found"); + const latest = fpaLatestRole(member); + const club = latest?.club ?? null; + let person = await db.person.findUnique({ where: { organizationId_licence: { organizationId: orgId, licence: member.licence } } }); + if (!person) { + // Seen on a match report: the squad entry with this licence. + const players = await db.sportsPlayer.findMany({ where: { externalId: member.licence, team: { provider: "FPA" } }, select: { id: true } }); + if (players.length) person = await db.person.findFirst({ where: { organizationId: orgId, sportsPlayerId: { in: players.map((p) => p.id) }, licence: null } }); + } + let created = false; + if (!person) { + const short = fpaShortName(member.name); + const same = await db.person.findUnique({ where: { organizationId_name: { organizationId: orgId, name: short } } }); + // A name taken by someone else (another licence, another club): the full name. + const name = !same ? short : member.name; + const other = same ? await db.person.findUnique({ where: { organizationId_name: { organizationId: orgId, name } } }) : null; + if (other && other.licence && other.licence !== member.licence) throw new AppError(409, "person_name_taken"); + person = other ?? (await db.person.create({ data: { organizationId: orgId, name, club, licence: member.licence } })); + created = !other; + } + if (person.licence !== member.licence || (!person.club && club)) { + person = await db.person.update({ where: { id: person.id }, data: { licence: member.licence, ...(!person.club && club && { club }) } }); + } + let reference = false; + if (org.biometricsEnabled && member.photo && !person.referenceKey && !person.recognitionOffAt) { + try { + reference = await this.saveHeadshot(orgId, person.id, member.photo); + } catch (err) { + log.warn({ err, licence: member.licence }, "sports: fpa licence photo failed"); + } + } + return { person: { id: person.id, name: person.name, club: person.club }, member, created, reference }; + } + private async saveHeadshot(orgId: string, personId: string, src: string): Promise { const u = new URL(src); if (u.protocol !== "https:" || !HEADSHOT_HOSTS.includes(u.hostname)) return false; @@ -1102,3 +1153,20 @@ export class SportsWorker { if (!drained) this.opts.log.warn({}, "sports: stop timed out with work still running"); } } + +/** The role a member is best known by now: the latest season's, a player or coach before an official. */ +export function fpaLatestRole(member: FpaMember): { season: string; role: string; club: string | null } | null { + const order: FpaRegistration["kind"][] = ["athlete", "coach", "official", "table", "referee", "other"]; + const regs = [...member.registrations].sort((a, b) => b.season.localeCompare(a.season) || order.indexOf(a.kind) - order.indexOf(b.kind) || Number(a.club === "F.A.P.") - Number(b.club === "F.A.P.")); + const r = regs[0]; + if (!r) return null; + return { season: r.season, role: r.role, club: r.clubName ? fpaClubName(r.clubName) : r.club }; +} + +/** "Estarreja Andebol Clube" as is; "Selecções Nacionais Masculinas" → "Seleção Nacional Masculina"; capitals fixed. */ +export function fpaClubName(name: string): string { + const sel = /^selec[cç][oõ]es nacionais (masculinas|femininas)/i.exec(name); + if (sel) return `Seleção Nacional ${sel[1]!.toLowerCase().startsWith("m") ? "Masculina" : "Feminina"}`; + if (/^federa[cç]ao andebol portugal$/i.test(name)) return "Federação de Andebol de Portugal"; + return name === name.toUpperCase() ? name.toLowerCase().replace(/(^|\s)\p{L}/gu, (m) => m.toUpperCase()) : name; +} diff --git a/apps/api/test/archive.test.ts b/apps/api/test/archive.test.ts index 5be2175..b29ceb5 100644 --- a/apps/api/test/archive.test.ts +++ b/apps/api/test/archive.test.ts @@ -544,7 +544,18 @@ describe("archive from a Nextcloud", () => { let ownerId: string; let worker: ArchiveService; - const fetchProxy: typeof fetch = (input, init) => cloud.fetch(input, init); + // The cloud, and the handball federation's portal for a licence lookup. + const fetchProxy: typeof fetch = (input, init) => { + const u = new URL(typeof input === "string" ? input : input instanceof URL ? input.href : input.url); + if (u.host === "portal.fpa.pt") + return Promise.resolve( + u.pathname === "/associado/198159/" + ? new Response('

Maria Ema Bastos Silva

', { headers: { "content-type": "text/html" } }) + : new Response("", { headers: { "content-type": "text/html" } }), + ); + if (u.host === "ws.fpa.pt") return Promise.resolve(Response.json([{ EPO_DESCRICAO: "2024/25", GCI_TIP_INSCRICAO_TI013: "TEC", CLU_ABREV: "ESTARREJA AC", CLU_NOME: "Estarreja Andebol Clube" }])); + return cloud.fetch(input, init); + }; beforeAll(async () => { storageRoot = await mkdtemp(path.join(tmpdir(), "pr-archive-test-")); @@ -1110,6 +1121,17 @@ describe("archive from a Nextcloud", () => { const scoped = res.json() as { gallery: { id: string; title: string } | null; counts: Record }; expect(scoped.gallery?.id).toBe(gid); expect(scoped.counts.suggested).toBe(2); + // Handball archives: a licence number nobody has yet is looked up at the federation, and the person added. + await ctx.db.cloudSource.update({ where: { id: source.id }, data: { look: "fpa" } }); + res = await ctx.app.inject({ method: "GET", url: `/v1/archive/${source.id}/people/search?q=198159`, headers: as(editor) }); + expect(res.json()).toMatchObject({ people: [], fpa: { licence: "198159", name: "Maria Ema Bastos Silva", club: "Estarreja Andebol Clube", role: "Treinador · 2024/25" } }); + res = await ctx.app.inject({ method: "POST", url: `/v1/archive/${source.id}/people/from-licence`, headers: as(reader), payload: { licence: "198159" } }); + expect(res.statusCode).toBe(403); + res = await ctx.app.inject({ method: "POST", url: `/v1/archive/${source.id}/people/from-licence`, headers: as(editor), payload: { licence: "198159" } }); + expect(res.json()).toMatchObject({ created: true, person: { name: "Maria Silva", club: "Estarreja Andebol Clube", licence: "198159" } }); + res = await ctx.app.inject({ method: "GET", url: `/v1/archive/${source.id}/people/search?q=198159`, headers: as(editor) }); + expect(res.json().fpa).toBeUndefined(); + expect(res.json().people).toMatchObject([{ name: "Maria Silva", licence: "198159" }]); // "Juntar nomes" is for those who edit everything. res = await ctx.app.inject({ method: "POST", url: `/v1/archive/${source.id}/clubs/merge`, headers: as(editor), payload: { into: "Sporting CP", names: ["Sporting"] } }); expect(res.statusCode).toBe(403); diff --git a/apps/api/test/sports.test.ts b/apps/api/test/sports.test.ts index ad7be37..ca4cbd3 100644 --- a/apps/api/test/sports.test.ts +++ b/apps/api/test/sports.test.ts @@ -243,6 +243,8 @@ const fakeSites = (state: { benfica: { shirtNumber: number; name: string; photos "utf8", ), ); + if (state.handball && u.host === "portal.fpa.pt" && u.pathname === "/associado/198159/") return bytes(Buffer.from(MEMBER_PAGE, "utf8")); + if (state.handball && u.host === "ws.fpa.pt" && u.pathname === "/index.php/getCipaInscricoes/203445") return json(MEMBER_REGISTRATIONS); const licence = /^\/associado\/(100001|185283)\/$/.exec(u.pathname)?.[1]; if (state.handball && u.host === "portal.fpa.pt" && licence) return bytes(Buffer.from(``, "utf8")); @@ -468,6 +470,25 @@ describe("sports data service", () => { 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("FPA: a person from their licence number (name, latest role, licence photo), the same one on match reports", async () => { + state.handball = true; + const { org } = await seedUser(ctx.db, "foto@fpa.pt", { org: "fpa", role: "OWNER" }); + await ctx.db.organization.update({ where: { id: org!.id }, data: { biometricsEnabled: true } }); + const member = await sports.fpa.member("198159"); + expect(member).toMatchObject({ name: "Maria Ema Bastos Silva", internalId: "203445", photo: "https://si.fpa.pt/blob/obj_anexo/FOTO_CIPA/636722_203445.JPG" }); + expect(member!.registrations.map((r) => [r.season, r.kind, r.club])).toEqual([ + ["2010/11", "athlete", "ADA CANELAS"], + ["2024/25", "coach", "ESTARREJA AC"], + ["2025/26", "official", "Sel.Nac.M"], + ]); + expect(await sports.fpa.member("99999999")).toBeNull(); + const first = await sports.personFromFpaLicence(org!.id, "198159"); + expect(first).toMatchObject({ created: true, reference: true, person: { name: "Maria Silva", club: "Seleção Nacional Masculina" } }); + const again = await sports.personFromFpaLicence(org!.id, "198159"); + expect(again).toMatchObject({ created: false, person: { id: first.person.id } }); + expect((await ctx.db.person.findUniqueOrThrow({ where: { id: first.person.id } })).licence).toBe("198159"); + }); + it("keeps sports data to members and FPF links to admins", async () => { const { user } = await seedUser(ctx.db, "foto@abola.pt", { org: "abola", role: "PHOTOGRAPHER" }); const token = (await login(ctx.app, user.email)).body.accessToken; @@ -617,3 +638,12 @@ describe("sports data service", () => { ]); }); }); + +const MEMBER_PAGE = `
+

Maria Ema Bastos Silva

CIPA198159
Inscrito comoOficial, Técnico, Atleta
+`; +const MEMBER_REGISTRATIONS = [ + { EPO_DESCRICAO: "2010/11", GCI_TIP_INSCRICAO_TI013: "AT01", CLU_ABREV: "ADA CANELAS", CLU_NOME: "Associacao Desportiva Arsenal Canelas", ESC_DESCRICAO: "Iniciados F" }, + { EPO_DESCRICAO: "2024/25", GCI_TIP_INSCRICAO_TI013: "TEC", CLU_ABREV: "ESTARREJA AC", CLU_NOME: "Estarreja Andebol Clube" }, + { EPO_DESCRICAO: "2025/26", GCI_TIP_INSCRICAO_TI013: "OFI", CLU_ABREV: "Sel.Nac.M", CLU_NOME: "Selecções Nacionais Masculinas", FOF_ABREV: "DELEGADO TECNICO" }, +]; diff --git a/apps/site/src/app/arquivo/[id]/ArchiveView.tsx b/apps/site/src/app/arquivo/[id]/ArchiveView.tsx index f03a1db..49a0721 100644 --- a/apps/site/src/app/arquivo/[id]/ArchiveView.tsx +++ b/apps/site/src/app/arquivo/[id]/ArchiveView.tsx @@ -220,7 +220,7 @@ export function ArchiveView({ info, start }: { info: ArchiveInfo; start?: View } ) : ( - go({ kind: "gallery", id })} onPerson={(id) => go({ kind: "person", id })} canReview={!!me?.canReview} canManage={!!me?.canManagePeople} /> + go({ kind: "gallery", id })} onPerson={(id) => go({ kind: "person", id })} canReview={!!me?.canReview} canManage={!!me?.canManagePeople} fpa={info.look === "fpa"} /> )} diff --git a/apps/site/src/app/arquivo/[id]/Browse.tsx b/apps/site/src/app/arquivo/[id]/Browse.tsx index 07de155..f4b9b14 100644 --- a/apps/site/src/app/arquivo/[id]/Browse.tsx +++ b/apps/site/src/app/arquivo/[id]/Browse.tsx @@ -1,7 +1,7 @@ "use client"; import { useCallback, useEffect, useMemo, useState } from "react"; -import { cached, call, fold, forget, initials, KIND_LABEL, prefetch, shortDay, Unauthorised, type Directory, type GalleryCard, type GalleryKind, type GallerySort, type PeopleList } from "./api"; +import { addFromLicence, cached, call, fold, forget, initials, KIND_LABEL, prefetch, shortDay, Unauthorised, type Directory, type FpaCard, type GalleryCard, type GalleryKind, type GallerySort, type PeopleList } from "./api"; import { Icon, Loading, PersonFace } from "./parts"; export type Tab = "galleries" | "people" | "teams" | "review"; @@ -23,7 +23,10 @@ export function Browse({ onPerson, canReview = false, canManage = false, + fpa = false, }: { + /** A handball archive: people can be added by their federation licence (for those who review). */ + fpa?: boolean; /** The viewer edits the whole archive: may join a club's names ("Juntar nomes"). */ canManage?: boolean; /** The viewer edits on the cloud: sees the suggestions waiting for confirmation. */ @@ -133,6 +136,12 @@ export function Browse({ }; }, [tab, sourceId, token, guard, attempt, teamsTry, peopleTick]); + useEffect(() => { + if (openGroup) document.getElementById("arq-group-open")?.scrollIntoView({ block: "start", behavior: "smooth" }); + }, [openGroup]); + // Another filter: back to the tournaments' tiles. + useEffect(() => setOpenGroup(null), [kind, season, sort, q, team, player]); + /** Joins (or parts) club names, then reads people and teams again. */ const joinClubs = (path: "merge" | "unmerge", body: unknown, done: string) => { setJoinNote(null); @@ -295,6 +304,22 @@ export function Browse({ groups.delete(name); } const open = openGroup ? groups.get(openGroup) : undefined; + // A tournament opened: its galleries in place of the tiles (not below them, out of sight). + if (open) + return ( +
+
+ +

{openGroup}

+ + {open.length} galerias · {open.reduce((n, g) => n + g.photoCount, 0)} fotos + +
+
{open.map(card)}
+
+ ); return ( <> {(groups.size > 0 || loose.length > 0) && ( @@ -321,19 +346,6 @@ export function Browse({ {loose.map(card)} )} - {open && ( -
-
-

{openGroup}

- {open.length} galerias - - -
-
{open.map(card)}
-
- )} ); }; @@ -476,7 +488,10 @@ export function Browse({ {tab === "people" && ( <> -

Pessoas

+
+

Pessoas

+ {fpa && canReview && } +
{people && people.clubs.length > 1 && (
+ ); + return ( +
+
+ + + +
+ {state === "missing" &&

A federação não tem ninguém com esse número.

} + {state === "failed" &&

Não foi possível falar com a federação. Tenta outra vez.

} + {found && ( +
+ +
+ {found.member.name} + + Licença {found.member.licence} + {found.member.role ? ` · ${found.member.role}` : ""} + {found.member.club ? ` · ${found.member.club}` : ""} + + {found.member.history.length > 0 && ( +
    + {found.member.history.map((h) => ( +
  • {h}
  • + ))} +
+ )} + {found.person ? ( + + ) : ( + + )} + A foto da licença passa a ser a referência para o reconhecimento facial. +
+
+ )} +
+ ); +} diff --git a/apps/site/src/app/arquivo/[id]/Review.tsx b/apps/site/src/app/arquivo/[id]/Review.tsx index f29d3c1..2d9d38a 100644 --- a/apps/site/src/app/arquivo/[id]/Review.tsx +++ b/apps/site/src/app/arquivo/[id]/Review.tsx @@ -1,7 +1,7 @@ "use client"; import { useCallback, useEffect, useState } from "react"; -import { call, forget, Forbidden, shortDay, Unauthorised, type Me, type ReviewGroup, type ReviewPerson, type ReviewResult, type ReviewStatus } from "./api"; +import { addFromLicence, call, forget, Forbidden, shortDay, Unauthorised, type Me, type PeopleSearch, type ReviewGroup, type ReviewResult, type ReviewStatus } from "./api"; import { FaceCrop, Icon, Loading, PersonFace } from "./parts"; const STATUS: [ReviewStatus, string][] = [ @@ -51,10 +51,12 @@ export function Review({ const [selected, setSelected] = useState>(new Set()); const [error, setError] = useState(null); const [attempt, setAttempt] = useState(0); - const searchPeople = useCallback(async (q: string): Promise => { - const { body } = await call<{ people: ReviewPerson[] }>(`/v1/archive/${sourceId}/people/search?q=${encodeURIComponent(q)}`, token); - return body.people; + const searchPeople = useCallback(async (q: string): Promise => { + const { body } = await call(`/v1/archive/${sourceId}/people/search?q=${encodeURIComponent(q)}`, token); + return body; }, [sourceId, token]); + /** A face named by licence number: the person is added from the federation first. */ + const addLicence = useCallback(async (licence: string) => (await addFromLicence(sourceId, token, licence)).id, [sourceId, token]); useEffect(() => { let cancel = false; @@ -252,6 +254,7 @@ export function Review({ onToggle={() => togglePile(pile)} onAct={(a, p) => void act(pile.map((g) => g.id), a, p)} searchPeople={searchPeople} + addLicence={addLicence} /> ))}
@@ -296,26 +299,43 @@ export function Review({ ); } -function NameSearch({ placeholder, searchPeople, onPick }: { placeholder: string; searchPeople: (q: string) => Promise; onPick: (id: string) => void }) { +function NameSearch({ + placeholder, + searchPeople, + onPick, + addLicence, +}: { + placeholder: string; + searchPeople: (q: string) => Promise; + onPick: (id: string) => void; + addLicence?: (licence: string) => Promise; +}) { const [q, setQ] = useState(""); - const [hits, setHits] = useState([]); + const [hits, setHits] = useState([]); + const [fpa, setFpa] = useState(null); + const [adding, setAdding] = useState(false); + const [failed, setFailed] = useState(false); useEffect(() => { const query = q.trim(); + setFailed(false); if (query.length < 2) { setHits([]); + setFpa(null); return; } let cancel = false; const timer = setTimeout(() => { searchPeople(query).then( - (rows) => { - if (!cancel) setHits(rows); + (found) => { + if (cancel) return; + setHits(found.people); + setFpa(found.fpa ?? null); }, () => { if (!cancel) setHits([]); }, ); - }, 200); + }, /^\d+$/.test(query) ? 450 : 200); return () => { cancel = true; clearTimeout(timer); @@ -329,10 +349,31 @@ function NameSearch({ placeholder, searchPeople, onPick }: { placeholder: string {p.name} - {[p.number ? `nº ${p.number}` : null, p.club].filter(Boolean).join(" · ")} + {[p.number ? `nº ${p.number}` : null, p.club, p.licence ? `licença ${p.licence}` : null].filter(Boolean).join(" · ")} ))} + {fpa && addLicence && ( + + )} + {failed && Não foi possível adicionar. Tenta outra vez.} ); } @@ -363,6 +404,7 @@ function Card({ onToggle, onAct, searchPeople, + addLicence, }: { groups: ReviewGroup[]; status: ReviewStatus; @@ -370,7 +412,8 @@ function Card({ selected: boolean; onToggle: () => void; onAct: (a: Action, personId?: string) => void; - searchPeople: (q: string) => Promise; + searchPeople: (q: string) => Promise; + addLicence: (licence: string) => Promise; }) { const g = groups[0]!; const who = g.person ?? g.suggested; @@ -421,7 +464,7 @@ function Card({ )} {g.notThem.length > 0 && Não é: {g.notThem.map((n) => n.name).join(", ")}} {(status === "unnamed" || status === "suggested") && ( - onAct("confirm", id)} /> + onAct("confirm", id)} /> )}
diff --git a/apps/site/src/app/arquivo/[id]/api.ts b/apps/site/src/app/arquivo/[id]/api.ts index ea76962..25ebd86 100644 --- a/apps/site/src/app/arquivo/[id]/api.ts +++ b/apps/site/src/app/arquivo/[id]/api.ts @@ -164,6 +164,32 @@ export interface ReviewPerson { number: string | null; reference: string | null; recognitionOff?: boolean; + licence?: string; +} + +/** Someone registered with the handball federation, by licence number (CIPA). */ +export interface FpaCard { + licence: string; + name: string; + photo: string | null; + club: string | null; + /** "Treinador · 2024/25". */ + role: string | null; + /** "2024/25 · Treinador · ESTARREJA AC", newest first. */ + history: string[]; +} + +export interface PeopleSearch { + people: ReviewPerson[]; + /** A licence number nobody here has yet (FPA archives). */ + fpa?: FpaCard; +} + +/** Adds (or updates) a person from their licence; returns who. */ +export async function addFromLicence(sourceId: string, token: string, licence: string): Promise<{ id: string; name: string; reference: boolean }> { + const { body } = await call<{ person: { id: string; name: string; reference: boolean } }>(`/v1/archive/${sourceId}/people/from-licence`, token, { method: "POST", body: JSON.stringify({ licence }) }); + forget(`/v1/archive/${sourceId}/people`); + return body.person; } export interface ReviewGroup { diff --git a/apps/site/src/app/arquivo/[id]/archive.css b/apps/site/src/app/arquivo/[id]/archive.css index 01a31e4..79e8598 100644 --- a/apps/site/src/app/arquivo/[id]/archive.css +++ b/apps/site/src/app/arquivo/[id]/archive.css @@ -2617,3 +2617,79 @@ .arq-aside > * { flex-shrink: 0; } +.arq-group-open { + scroll-margin-top: 140px; +} +.arq-group-open .arq-kind-head { + flex-wrap: wrap; + align-items: center; +} +.arq-group-open .arq-kind-head .arq-link { + white-space: nowrap; +} + +/* Pessoas: add someone by their federation licence. */ +.arq-people-head { + display: flex; + flex-wrap: wrap; + align-items: center; + justify-content: space-between; + gap: 12px 24px; +} +.arq-licence { + display: flex; + flex-direction: column; + gap: 12px; + flex: 1 1 100%; + padding: 16px; + border-radius: var(--r); + background: var(--panel); + box-shadow: inset 0 0 0 1px var(--line); +} +.arq-licence-form { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 10px; +} +.arq-licence-form input { + height: 44px; + width: 220px; + max-width: 100%; + padding: 0 14px; + border-radius: 999px; + border: 1px solid var(--line); + background: var(--card); + color: var(--ink); + font-size: 16px; +} +.arq-licence-card { + display: flex; + flex-wrap: wrap; + gap: 16px; +} +.arq-licence-card > div { + display: flex; + flex-direction: column; + align-items: flex-start; + gap: 6px; + flex: 1 1 260px; + min-width: 0; +} +.arq-licence-card strong { + font-size: 20px; +} +.arq-licence-card ul { + margin: 4px 0; + padding-left: 18px; + font-size: 14px; + color: var(--muted); + columns: 2 220px; +} +.arq-fpa-hit { + box-shadow: inset 0 0 0 1px var(--line); +} +.arq-fpa-add { + color: var(--tag-c) !important; + font-weight: 700; +} -- 2.47.3