From faaa3406d2d3974a9a56d536c8124e762553bfa0 Mon Sep 17 00:00:00 2001 From: spark Date: Wed, 28 Oct 2026 00:22:51 +0000 Subject: [PATCH 1/3] =?UTF-8?q?Arquivo:=20procura=20pela=20ficha=20FPA=20(?= =?UTF-8?q?registo=20do=20clube)=20e=20c=C3=A2mara=20no=20telem=C3=B3vel?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Match the probe to FPA licence photos from getCipClubeEpoca first, then load that person's archive photos — not only people named on match sheets. On phones, open the front camera and convert HEIC to JPEG before upload so "Tirar foto" works on iPhone. --- apps/api/src/archive/find.ts | 241 +++++++++++------- apps/api/src/faces/lookup.ts | 1 + apps/api/src/sports/providers.ts | 68 ++++- apps/api/src/sports/service.ts | 99 +++++++ apps/api/test/sports.test.ts | 27 +- .../site/src/app/arquivo/[id]/FindByPhoto.tsx | 42 ++- apps/site/src/app/arquivo/[id]/api.ts | 24 +- .../src/app/galeria/[slug]/GalleryView.tsx | 61 +++-- apps/site/src/lib/asJpeg.ts | 32 +++ docs/ARCHITECTURE.md | 9 +- 10 files changed, 480 insertions(+), 124 deletions(-) create mode 100644 apps/site/src/lib/asJpeg.ts diff --git a/apps/api/src/archive/find.ts b/apps/api/src/archive/find.ts index 5d138ea..79b75d2 100644 --- a/apps/api/src/archive/find.ts +++ b/apps/api/src/archive/find.ts @@ -15,10 +15,10 @@ import type { Viewer } from "./viewer.js"; /** * Search the archive by a photo: for editors on the cloud (same rights as "Rever rostos"), when the archive has * the option on and the organization has biometrics on. The search photo is read in memory and never kept. - * Results stay inside the folders the viewer may see. * - * Speed: face groups are ranked with pgvector HNSW (`centroid_vec`), the same path as "more of this face". - * Event ids of the viewer's scope are cached a few minutes so a second search does not re-scan cloud_files. + * Registry first: the probe is compared to registered people (FPA licence / Liga headshot centroids). A clear + * match loads that person's archive photos by person_id — no blind scan of every face group. Only when nobody + * in the registry is sure enough do we fall back to HNSW over the viewer's face groups. */ interface Deps { db: Db; @@ -33,8 +33,11 @@ const SourceParams = z.object({ sourceId: z.uuid() }); const EVENTS_TTL_MS = 5 * 60_000; const NEAREST = 400; const MAX_PHOTOS = 500; +/** How many registry candidates to keep for the editor (strong + possible). */ +const PEOPLE_LIMIT = 8; type CardLevel = "confirmed" | "probable" | "similar"; +type Via = "registry" | "faces"; const levelOf = (score: number, match: number): CardLevel => (score >= match ? "probable" : "similar"); @@ -58,7 +61,6 @@ export async function registerArchiveFindRoutes(app: FastifyInstance, deps: Deps const requireFind = async (v: Viewer) => { const editable = await editableFolders(v); if (editable !== "all" && !editable.length) throw forbidden("archive_edit_required"); - // Always read the option from the DB so turning it off takes effect at once (not cached). const source = await db.cloudSource.findUnique({ where: { id: v.s }, select: { id: true, organizationId: true, photoFindEnabled: true, organization: { select: { biometricsEnabled: true } } }, @@ -84,7 +86,7 @@ export async function registerArchiveFindRoutes(app: FastifyInstance, deps: Deps /** * Face groups in the viewer's events like the probe. Production (512-d) uses the HNSW index; shorter test - * vectors fall back to a cosine over the float array. + * vectors fall back to a cosine over the float array. Used only when the registry has no sure person. */ const nearGroups = async (eventIds: string[], embedding: number[], model: string) => { if (!eventIds.length) return [] as { id: string; personId: string | null; score: number }[]; @@ -118,86 +120,40 @@ export async function registerArchiveFindRoutes(app: FastifyInstance, deps: Deps .slice(0, NEAREST); }; - /** Starts the face engine so the first real search does not wait on model load. */ - app.get("/v1/archive/:sourceId/find/ready", async (req) => { - const { sourceId } = SourceParams.parse(req.params); - const v = viewerOf(req, sourceId); - await requireFind(v); - return { ready: lookup.available }; - }); - - /** - * A photo of the person (headshot, press cutout) against faces already indexed in the folders this editor may - * see. Best matches first. The uploaded file is not stored. - */ - app.post("/v1/archive/:sourceId/find", { config: { rateLimit: { max: 30, timeWindow: "1 minute" } } }, async (req) => { - const { sourceId } = SourceParams.parse(req.params); - const q = LookupQuery.parse(req.query); - const v = viewerOf(req, sourceId); - const source = await requireFind(v); - const scoped = await scopeOf(v); - if (!scoped) return { faces: [], used: 0, people: [], total: 0, photos: [] }; - const { sql: scope, key: scopeKey } = scoped; - - const image = await lookupImage(req); - const read = await lookup.facesIn(image).catch(lookupFailed); - const used = Math.min(q.face, read.faces.length - 1); - const probe = read.faces[used]!; - const match = (THRESHOLDS[read.model] ?? { match: 0.5 }).match; - - const eventIds = await eventsInScope(sourceId, scope, scopeKey); - if (!eventIds.length) return { faces: facesOut(read.faces), used, people: [], total: 0, photos: [] }; - - const [people, groups] = await Promise.all([ - lookup.people(source.organizationId, probe.embedding, read.model), - nearGroups(eventIds, probe.embedding, read.model), - ]); - - const best = new Map(); - const keep = (photoId: string, faceId: string, score: number, level: CardLevel, sharpness: number | null) => { - const was = best.get(photoId); - if (!was || score > was.score) best.set(photoId, { faceId, score, level, sharpness }); + /** Licence / headshot / federation label for the people the registry returned. */ + const enrichPeople = async (ids: string[]) => { + if (!ids.length) return new Map(); + const rows = await db.$queryRaw<{ id: string; licence: string | null; reference: boolean; provider: string | null }[]>` + SELECT p.id, p.licence, p.reference_key IS NOT NULL AS reference, t.provider + FROM people p + LEFT JOIN sports_players sp ON sp.id = p.sports_player_id + LEFT JOIN sports_teams t ON t.id = sp.team_id + WHERE p.id = ANY(${ids}::uuid[])`; + const asRegistry = (provider: string | null, licence: string | null): "fpa" | "liga" | "uefa" | "ehf" | "fpf" | null => { + if (licence || provider === "FPA") return "fpa"; + if (provider === "LIGA" || provider === "LPFP") return "liga"; + if (provider === "UEFA") return "uefa"; + if (provider === "EHF") return "ehf"; + if (provider === "FPF") return "fpf"; + return null; }; + return new Map( + rows.map((r) => [ + r.id, + { + licence: r.licence, + reference: r.reference ? signer.personUrl(r.id) : null, + registry: asRegistry(r.provider, r.licence), + }, + ]), + ); + }; - const sure = people.filter((p) => p.level === "strong"); - const groupIds = groups.map((g) => g.id); - - const [groupFaces, namedFaces] = await Promise.all([ - groupIds.length - ? db.$queryRaw<{ id: string; photo_id: string; group_id: string; sharpness: number | null }[]>` - SELECT f.id, f.photo_id, f.group_id, f.sharpness - FROM faces f - JOIN cloud_files cf ON cf.photo_id = f.photo_id AND ${scope} - WHERE f.group_id = ANY(${groupIds}::uuid[])` - : Promise.resolve([] as { id: string; photo_id: string; group_id: string; sharpness: number | null }[]), - sure.length - ? db.$queryRaw<{ id: string; photo_id: string; sharpness: number | null; person_id: string | null }[]>` - SELECT f.id, f.photo_id, f.sharpness, g.person_id - FROM faces f - JOIN face_groups g ON g.id = f.group_id - JOIN cloud_files cf ON cf.photo_id = f.photo_id AND ${scope} - WHERE g.ignored_at IS NULL AND g.person_id = ANY(${sure.map((p) => p.id)}::uuid[])` - : Promise.resolve([] as { id: string; photo_id: string; sharpness: number | null; person_id: string | null }[]), - ]); - - const byGroup = new Map(groups.map((g) => [g.id, g])); - for (const f of groupFaces) { - const g = byGroup.get(f.group_id)!; - const level: CardLevel = g.personId && g.score >= match ? "confirmed" : levelOf(g.score, match); - keep(f.photo_id, f.id, g.score, level, f.sharpness); - } - const scoreOf = new Map(sure.map((p) => [p.id, p.score])); - for (const f of namedFaces) { - const score = (f.person_id && scoreOf.get(f.person_id)) || sure[0]!.score; - keep(f.photo_id, f.id, score, "confirmed", f.sharpness); - } - - const hits = [...best.entries()] - .map(([photoId, h]) => ({ photoId, ...h })) - .sort((a, b) => b.score - a.score || (b.sharpness ?? 0) - (a.sharpness ?? 0)); - const shown = hits.slice(0, MAX_PHOTOS); - if (!shown.length) return { faces: facesOut(read.faces), used, people, total: 0, photos: [] }; - + const photoCards = async ( + shown: { photoId: string; faceId: string; score: number; level: CardLevel; sharpness: number | null }[], + scope: Prisma.Sql, + ) => { + if (!shown.length) return []; const ids = shown.map((h) => h.photoId); const faceIds = shown.map((h) => h.faceId); const [links, photos, faceRows] = await Promise.all([ @@ -219,8 +175,7 @@ export async function registerArchiveFindRoutes(app: FastifyInstance, deps: Deps ); const byId = new Map(photos.map((p) => [p.id, p])); const faceById = new Map(faceRows.map((f) => [f.id, f])); - - const cards = shown + return shown .filter((h) => byId.has(h.photoId) && folderOf.has(h.photoId)) .map((h) => { const p = byId.get(h.photoId)!; @@ -240,13 +195,127 @@ export async function registerArchiveFindRoutes(app: FastifyInstance, deps: Deps gallery: galleries.get(folderOf.get(h.photoId)!) ?? null, }; }); + }; + + /** Starts the face engine so the first real search does not wait on model load. */ + app.get("/v1/archive/:sourceId/find/ready", async (req) => { + const { sourceId } = SourceParams.parse(req.params); + const v = viewerOf(req, sourceId); + await requireFind(v); + return { ready: lookup.available }; + }); + + /** + * A photo of the person against the registry, then their archive photos (or a blind face-group search when + * nobody in the registry is sure). The uploaded file is not stored. + */ + app.post("/v1/archive/:sourceId/find", { config: { rateLimit: { max: 30, timeWindow: "1 minute" } } }, async (req) => { + const { sourceId } = SourceParams.parse(req.params); + const q = LookupQuery.parse(req.query); + const v = viewerOf(req, sourceId); + const source = await requireFind(v); + const scoped = await scopeOf(v); + if (!scoped) return { faces: [], used: 0, via: "faces" as Via, identity: null, people: [], total: 0, photos: [] }; + const { sql: scope, key: scopeKey } = scoped; + + const image = await lookupImage(req); + const read = await lookup.facesIn(image).catch(lookupFailed); + const used = Math.min(q.face, read.faces.length - 1); + const probe = read.faces[used]!; + const match = (THRESHOLDS[read.model] ?? { match: 0.5 }).match; + + // 1) Registry first: FPA / Liga / UEFA people with a face on file (smaller set than every photo). + const matched = await lookup.people(source.organizationId, probe.embedding, read.model, PEOPLE_LIMIT); + const extra = await enrichPeople(matched.map((p) => p.id)); + const people = matched.map((p) => { + const e = extra.get(p.id); + return { + id: p.id, + name: p.name, + club: p.club, + number: p.number, + score: p.score, + level: p.level, + licence: e?.licence ?? null, + reference: e?.reference ?? null, + registry: e?.registry ?? null, + }; + }); + const sure = people.filter((p) => p.level === "strong"); + + const best = new Map(); + const keep = (photoId: string, faceId: string, score: number, level: CardLevel, sharpness: number | null) => { + const was = best.get(photoId); + if (!was || score > was.score) best.set(photoId, { faceId, score, level, sharpness }); + }; + + let via: Via = "faces"; + + if (sure.length) { + // 2a) Known person: archive photos already named (or suggested) as them — no blind group scan. + via = "registry"; + const sureIds = sure.map((p) => p.id); + const scoreOf = new Map(sure.map((p) => [p.id, p.score])); + const named = await db.$queryRaw<{ id: string; photo_id: string; sharpness: number | null; person_id: string | null; suggested_person_id: string | null }[]>` + SELECT f.id, f.photo_id, f.sharpness, g.person_id, g.suggested_person_id + FROM faces f + JOIN face_groups g ON g.id = f.group_id + JOIN cloud_files cf ON cf.photo_id = f.photo_id AND ${scope} + WHERE g.ignored_at IS NULL + AND (g.person_id = ANY(${sureIds}::uuid[]) OR g.suggested_person_id = ANY(${sureIds}::uuid[]))`; + for (const f of named) { + const personId = f.person_id ?? f.suggested_person_id!; + const score = scoreOf.get(personId) ?? sure[0]!.score; + keep(f.photo_id, f.id, score, f.person_id ? "confirmed" : "probable", f.sharpness); + } + } else { + // 2b) Nobody sure in the registry: fall back to face groups in the viewer's galleries. + const eventIds = await eventsInScope(sourceId, scope, scopeKey); + if (!eventIds.length) { + return { faces: facesOut(read.faces), used, via, identity: null, people, total: 0, photos: [] }; + } + const groups = await nearGroups(eventIds, probe.embedding, read.model); + if (groups.length) { + const faces = await db.$queryRaw<{ id: string; photo_id: string; group_id: string; sharpness: number | null }[]>` + SELECT f.id, f.photo_id, f.group_id, f.sharpness + FROM faces f + JOIN cloud_files cf ON cf.photo_id = f.photo_id AND ${scope} + WHERE f.group_id = ANY(${groups.map((g) => g.id)}::uuid[])`; + const byGroup = new Map(groups.map((g) => [g.id, g])); + for (const f of faces) { + const g = byGroup.get(f.group_id)!; + const level: CardLevel = g.personId && g.score >= match ? "confirmed" : levelOf(g.score, match); + keep(f.photo_id, f.id, g.score, level, f.sharpness); + } + } + } + + const hits = [...best.entries()] + .map(([photoId, h]) => ({ photoId, ...h })) + .sort((a, b) => b.score - a.score || (b.sharpness ?? 0) - (a.sharpness ?? 0)); + const shown = hits.slice(0, MAX_PHOTOS); + const top = sure[0] ?? null; + const identity = top + ? { + id: top.id, + name: top.name, + club: top.club, + number: top.number, + licence: top.licence, + reference: top.reference, + registry: top.registry, + score: top.score, + } + : null; return { faces: facesOut(read.faces), used, + via, + identity, people, total: hits.length, - photos: cards, + photos: await photoCards(shown, scope), }; }); } diff --git a/apps/api/src/faces/lookup.ts b/apps/api/src/faces/lookup.ts index 950fdde..6682f0a 100644 --- a/apps/api/src/faces/lookup.ts +++ b/apps/api/src/faces/lookup.ts @@ -180,6 +180,7 @@ export class FaceLookup { / NULLIF(sqrt((SELECT sum(a * a) FROM unnest(p.centroid) AS u(a))), 0) AS score FROM people p WHERE p.organization_id = ${orgId}::uuid AND p.model = ${model} AND cardinality(p.centroid) = ${embedding.length} + AND p.recognition_off_at IS NULL AND (${only}::uuid[] IS NULL OR p.id = ANY(${only}::uuid[])) ) s WHERE score >= ${match - POSSIBLE_BELOW} diff --git a/apps/api/src/sports/providers.ts b/apps/api/src/sports/providers.ts index db9ab59..416218a 100644 --- a/apps/api/src/sports/providers.ts +++ b/apps/api/src/sports/providers.ts @@ -344,8 +344,9 @@ const FPA_GAME_OFFICIAL: [RegExp, string][] = [ /** * The FPA's public pages, the same the portal links to: the agenda (JSON), a club's games of a season and level * (JSON), the match report ("Boletim do Jogo": every player with shirt number and licence number, the bench officials - * with their letter, the referees), a match page (the referees, published before the match) and an athlete's page - * (the licence photo). Asked for sparingly and cached in the database. + * with their letter, the referees), a match page (the referees, published before the match), a club's full register + * (`getCipClubeEpoca`: every associate with licence and photo) and an athlete's page (the licence photo). Asked for + * sparingly and cached in the database. Shared shape with ehf-stats / livereport (`WsFpa.clubAssociates`). */ export class FpaProvider { static readonly AGENDA = "https://ws.fpa.pt/index.php/getAgendaJogosFAP/"; @@ -443,6 +444,69 @@ export class FpaProvider { const html = await this.html(`${FpaProvider.PORTAL}/associado/${encodeURIComponent(cipa)}/`); return /https:\/\/si\.fpa\.pt\/blob\/obj_anexo\/FOTO_CIPA\/\d+_\d+\.(?:jpe?g|png)/i.exec(html)?.[0] ?? null; } + + /** + * Everyone registered at a club for a season (athletes, coaches, officials, referees), with licence number and + * licence photo when the federation has one. This is the club register — not only the people named on a match + * sheet. Season ids are the portal's (`373` = 2025/26); see `fpaEpochFor`. + */ + async clubAssociates(clubId: string, seasonId: string): Promise { + if (!/^\d+$/.test(clubId) || !/^\d+$/.test(seasonId)) return []; + const path = ["getCipClubeEpoca", clubId, seasonId].map(encodeURIComponent).join("/"); + const rows = await get(this.fetcher, `${FpaProvider.WS}/${path}`, { accept: "application/json" }, "json"); + await this.pause(); + if (!Array.isArray(rows)) return []; + const out: FpaClubAssociate[] = []; + const seen = new Set(); + for (const raw of rows as Record[]) { + const a = fpaClubAssociate(raw); + if (!a || seen.has(a.licence)) continue; + seen.add(a.licence); + out.push(a); + } + return out; + } +} + +/** Someone on a club's FPA register for a season (from `getCipClubeEpoca`). */ +export interface FpaClubAssociate { + licence: string; + /** Federation internal id (portal history); not the printed CIPA. */ + internalId: string | null; + name: string; + photo: string | null; + kind: "athlete" | "coach" | "official" | "referee" | "other"; +} + +/** Handball seasons start in August; portal epoch ids advance one per year (2025/26 = 373). */ +export function fpaEpochFor(date: Date = new Date()): string { + const year = date.getUTCFullYear(); + const start = date.getUTCMonth() >= 7 ? year : year - 1; + return String(start - 1652); +} + +function fpaClubAssociate(r: Record): FpaClubAssociate | null { + const licence = String(r.CIP_NUMERO ?? "").trim().replace(/\.0+$/, ""); + const name = cellText(String(r.CIP_NOME ?? "")); + if (!/^\d{1,9}$/.test(licence) || !name) return null; + const photo = str(r.URL_FOTO); + const kind: FpaClubAssociate["kind"] = + String(r.ATLETA ?? "").toUpperCase() === "S" + ? "athlete" + : String(r.TECNICO ?? "").toUpperCase() === "S" + ? "coach" + : String(r.OFICIAL ?? "").toUpperCase() === "S" + ? "official" + : String(r.ARBITRO ?? "").toUpperCase() === "S" + ? "referee" + : "other"; + return { + licence, + internalId: str(r.ID_CIPA), + name, + photo: photo && /^https:\/\/si\.fpa\.pt\//i.test(photo) ? photo : null, + kind, + }; } /** A registration of a member for one season: athlete, coach, official, table official or referee. */ diff --git a/apps/api/src/sports/service.ts b/apps/api/src/sports/service.ts index 2ba2b33..931de53 100644 --- a/apps/api/src/sports/service.ts +++ b/apps/api/src/sports/service.ts @@ -14,9 +14,11 @@ import { tallyOf, tallySquadPhotos } from "./squadPhotos.js"; import { type Fetch, type FixtureData, + type FpaClubAssociate, type FpaMember, FpaProvider, type FpaRegistration, + fpaEpochFor, fpaShortName, FpfProvider, LIGA_COMPETITIONS, @@ -63,6 +65,13 @@ const FPA_REPORTS_PER_REFRESH = 30; const FPA_RETRY_MS = 3 * 86400_000; /** Reports read before licence numbers were kept, read again per refresh until none are left. */ const FPA_REREADS_PER_REFRESH = 40; +/** + * Clubs whose full FPA register (every associate with a licence photo) is pulled per refresh — not only the people + * on match sheets. Covers coaches, officials, youth and anyone else the federation lists for the club. + */ +const FPA_ASSOCIATE_CLUBS_PER_REFRESH = 12; +/** Skip a club's register again until this long has passed (the list changes slowly). */ +const FPA_ASSOCIATE_RETRY_MS = 7 * 86400_000; /** The handball referees and table officials, kept as one "team" so their licence (and photo) is known by name. */ const FPA_REFEREES_TEAM = { externalId: "ARBITRAGEM", name: REFEREES }; /** Officials of the game who become people of an event (faces to name): on the pitch, and at the table. */ @@ -508,6 +517,7 @@ export class SportsService { } await this.fpaSquads(fixtures, now, result); await this.fpaReferees(now, result); + await this.fpaAssociates(fixtures, now, result); if (result.errors.length) log.warn({ errors: result.errors.slice(0, 10) }, "sports: fpa refresh had errors"); log.info({ ...result, errors: result.errors.length }, "sports: fpa refreshed"); return result; @@ -516,6 +526,8 @@ export class SportsService { private readonly fpaTried = new Map(); /** Reports read again for licence numbers (once each: some list none). */ private readonly fpaReread = new Set(); + /** Last time a club's full associate register was pulled. */ + private readonly fpaAssociateAt = new Map(); private fpaCompetition(f: FixtureData): Promise { return this.deps.db.sportsCompetition.upsert({ @@ -1270,6 +1282,93 @@ export class SportsService { return { person: { id: person.id, name: person.name, club: person.club }, member, created, reference }; } + /** + * Full FPA club registers into people (every associate the federation lists for the club this season, with + * licence photo). Match sheets alone miss coaches, officials, youth and anyone not on a boletim — this closes + * that gap for face search. Clubs come from the agenda; a few per refresh, then again after a week. + */ + private async fpaAssociates(agenda: FixtureData[], now: Date, result: RefreshResult): Promise { + const { db, log } = this.deps; + const clubIds = [...new Set(agenda.flatMap((f) => [f.home.clubId, f.away.clubId]).filter((id): id is string => !!id && /^\d+$/.test(id)))]; + const due = clubIds.filter((id) => { + const at = this.fpaAssociateAt.get(id); + return !at || now.getTime() - at >= FPA_ASSOCIATE_RETRY_MS; + }); + if (!due.length) return; + const orgs = await db.organization.findMany({ where: { biometricsEnabled: true }, select: { id: true } }); + if (!orgs.length) return; + const epoch = fpaEpochFor(now); + let clubs = 0; + for (const clubId of due) { + if (clubs >= FPA_ASSOCIATE_CLUBS_PER_REFRESH) break; + clubs++; + this.fpaAssociateAt.set(clubId, now.getTime()); + let associates: FpaClubAssociate[]; + try { + associates = await this.fpa.clubAssociates(clubId, epoch); + } catch (err) { + result.errors.push(`fpa associates ${clubId}: ${(err as Error).message}`); + continue; + } + if (!associates.length) continue; + for (const org of orgs) { + for (const a of associates) { + try { + const done = await this.personFromFpaAssociate(org.id, a); + if (done.created) result.players++; + } catch (err) { + log.warn({ err, licence: a.licence, org: org.id }, "sports: fpa associate failed"); + } + } + } + log.info({ clubId, associates: associates.length, orgs: orgs.length }, "sports: fpa club register"); + } + } + + /** + * Someone from a club's FPA register row (licence + name + photo already known — no second portal hit). + * Same person as `personFromFpaLicence` when the licence matches. + */ + async personFromFpaAssociate( + orgId: string, + a: FpaClubAssociate, + clubName: string | null = null, + ): Promise<{ person: { id: string; name: string; club: string | null }; created: boolean; reference: boolean }> { + const { db, log } = this.deps; + const org = await db.organization.findUnique({ where: { id: orgId }, select: { biometricsEnabled: true } }); + if (!org) throw notFound("organization_not_found"); + let person = await db.person.findUnique({ where: { organizationId_licence: { organizationId: orgId, licence: a.licence } } }); + if (!person) { + const players = await db.sportsPlayer.findMany({ where: { externalId: a.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(a.name); + const same = await db.person.findUnique({ where: { organizationId_name: { organizationId: orgId, name: short } } }); + const name = !same ? short : a.name; + const other = same ? await db.person.findUnique({ where: { organizationId_name: { organizationId: orgId, name } } }) : null; + if (other && other.licence && other.licence !== a.licence) throw new AppError(409, "person_name_taken"); + person = other ?? (await db.person.create({ data: { organizationId: orgId, name, club: clubName, licence: a.licence } })); + created = !other; + } + if (person.licence !== a.licence || (!person.club && clubName)) { + person = await db.person.update({ + where: { id: person.id }, + data: { licence: a.licence, ...(!person.club && clubName ? { club: clubName } : {}) }, + }); + } + let reference = false; + if (org.biometricsEnabled && a.photo && !person.referenceKey && !person.recognitionOffAt) { + try { + reference = await this.saveHeadshot(orgId, person.id, a.photo); + } catch (err) { + log.warn({ err, licence: a.licence }, "sports: fpa associate photo failed"); + } + } + return { person: { id: person.id, name: person.name, club: person.club }, created, reference }; + } + /** The person already created for this human at another club or in another season. */ private async personForIdentity(orgId: string, p: SportsPlayer) { const match: ({ externalId: string } | { birthDate: string; fullName: string })[] = []; diff --git a/apps/api/test/sports.test.ts b/apps/api/test/sports.test.ts index 241d28a..45b8129 100644 --- a/apps/api/test/sports.test.ts +++ b/apps/api/test/sports.test.ts @@ -5,7 +5,7 @@ import { CodeGeneratorSettings } from "@photoreport/contracts"; import sharp from "sharp"; import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest"; import { BLOCK_START, buildCodeLines, mergeGenerated, teamPrefix, toTsv } from "../src/sports/codegen.js"; -import { type Fetch, fpaProva, fpaShortName, fpfDate, lisbonTime, parseFpaBoletim, parseFpaClubTerms, parseFpaMatchPage, parseFpaReferees, parseFpfLineups, seasonOf } from "../src/sports/providers.js"; +import { type Fetch, fpaEpochFor, fpaProva, fpaShortName, fpfDate, lisbonTime, parseFpaBoletim, parseFpaClubTerms, parseFpaMatchPage, parseFpaReferees, parseFpfLineups, seasonOf } from "../src/sports/providers.js"; import { SportsService } from "../src/sports/service.js"; import { LocalStorage } from "../src/storage/storage.js"; import { bearer, createTestApp, login, resetDb, seedUser, type TestContext } from "./helpers.js"; @@ -56,6 +56,8 @@ describe("federation data", () => { expect(lisbonTime("2026-12-01").timeKnown).toBe(false); expect(seasonOf(new Date("2026-10-13"))).toBe("20262027"); expect(seasonOf(new Date("2027-03-01"))).toBe("20262027"); + expect(fpaEpochFor(new Date("2026-10-27T12:00:00Z"))).toBe("374"); + expect(fpaEpochFor(new Date("2026-03-01T12:00:00Z"))).toBe("373"); }); it("reads the FPA match report: numbers and licences, the officials' letters, the referees", () => { @@ -245,6 +247,13 @@ const fakeSites = (state: { benfica: { shirtNumber: number; name: string; photos ); 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); + // Full club register (every associate, not only the match sheet): Vitória club 140, season 374. + if (state.handball && u.host === "ws.fpa.pt" && u.pathname === "/index.php/getCipClubeEpoca/140/374") + return json([ + { CIP_NUMERO: "100001", CIP_NOME: "Rui Manuel Sousa Lopes", ID_CIPA: "370001", ATLETA: "S", TECNICO: null, OFICIAL: null, ARBITRO: null, URL_FOTO: "https://si.fpa.pt/blob/obj_anexo/FOTO_CIPA/1_370001.JPG" }, + { CIP_NUMERO: "250001", CIP_NOME: "Ana Filipa Mendes Costa", ID_CIPA: "370999", ATLETA: null, TECNICO: "S", OFICIAL: null, ARBITRO: null, URL_FOTO: "https://si.fpa.pt/blob/obj_anexo/FOTO_CIPA/2_370999.JPG" }, + ]); + if (state.handball && u.host === "ws.fpa.pt" && u.pathname.includes("getCipClubeEpoca")) return json([]); const licence = /^\/associado\/(100001|185283)\/$/.exec(u.pathname)?.[1]; if (state.handball && u.host === "portal.fpa.pt" && licence) return bytes(Buffer.from(``, "utf8")); @@ -500,6 +509,22 @@ describe("sports data service", () => { expect((await ctx.db.person.findUniqueOrThrow({ where: { id: first.person.id } })).licence).toBe("198159"); }); + it("FPA: the whole club register (getCipClubeEpoca) becomes people with licence photos, not only match-sheet names", async () => { + state.handball = true; + const { org } = await seedUser(ctx.db, "registo@fpa.pt", { org: "fpa-reg", role: "OWNER" }); + await ctx.db.organization.update({ where: { id: org!.id }, data: { biometricsEnabled: true } }); + const list = await sports.fpa.clubAssociates("140", "374"); + expect(list).toEqual([ + { licence: "100001", internalId: "370001", name: "Rui Manuel Sousa Lopes", photo: "https://si.fpa.pt/blob/obj_anexo/FOTO_CIPA/1_370001.JPG", kind: "athlete" }, + { licence: "250001", internalId: "370999", name: "Ana Filipa Mendes Costa", photo: "https://si.fpa.pt/blob/obj_anexo/FOTO_CIPA/2_370999.JPG", kind: "coach" }, + ]); + const r = await sports.refreshFpa(now); + expect(r.errors).toEqual([]); + const coach = await ctx.db.person.findUnique({ where: { organizationId_licence: { organizationId: org!.id, licence: "250001" } } }); + expect(coach).toMatchObject({ name: "Ana Costa", licence: "250001" }); + expect(coach!.referenceKey).toBeTruthy(); + }); + 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; diff --git a/apps/site/src/app/arquivo/[id]/FindByPhoto.tsx b/apps/site/src/app/arquivo/[id]/FindByPhoto.tsx index afb4e0c..3517d41 100644 --- a/apps/site/src/app/arquivo/[id]/FindByPhoto.tsx +++ b/apps/site/src/app/arquivo/[id]/FindByPhoto.tsx @@ -1,6 +1,7 @@ "use client"; import { useEffect, useMemo, useState } from "react"; +import { asJpeg } from "../../../lib/asJpeg"; import { day, download, Forbidden, LEVEL, Unauthorised, type FindByPhotoResult, type Level, type Me, type PhotoFace } from "./api"; import { Lightbox } from "./Lightbox"; import { Icon } from "./parts"; @@ -43,12 +44,14 @@ export function FindByPhoto({ const search = async (next: File, face = 0) => { setBusy(true); setError(null); - setFile(next); setOnly(null); setIndex(null); - const form = new FormData(); - form.append("file", next, "foto.jpg"); try { + // Phones (esp. iPhone) often hand over HEIC; the API only reads JPEG/PNG/WebP. Decode here and send JPEG. + const jpeg = await asJpeg(next); + setFile(jpeg); + const form = new FormData(); + form.append("file", jpeg, "foto.jpg"); const res = await fetch(`/v1/archive/${sourceId}/find${face ? `?face=${face}` : ""}`, { method: "POST", body: form, @@ -63,7 +66,7 @@ export function FindByPhoto({ if (res.status === 403) throw new Forbidden(); const msg: Record = { no_face: "Não encontrámos nenhuma cara nessa foto. Experimenta uma com a cara de frente e bem iluminada.", - not_an_image: "Esse ficheiro não é uma foto.", + not_an_image: "Esse ficheiro não é uma foto. Tira outra ou escolhe um JPEG da galeria.", find_unavailable: "A procura por foto não está disponível neste arquivo.", archive_edit_required: "Só quem edita pastas na cloud pode usar esta procura.", engine_unavailable: "O reconhecimento de caras não está disponível de momento. Tenta daqui a pouco.", @@ -77,7 +80,9 @@ export function FindByPhoto({ } catch (err) { if (err instanceof Unauthorised) onExpired(); else if (err instanceof Forbidden) setError("Só quem edita pastas na cloud pode usar esta procura."); - else setError("Não foi possível pesquisar agora."); + else if (err instanceof Error && err.message === "convert_failed") + setError("Não conseguimos ler essa foto. Tira outra com a câmara ou escolhe um JPEG da galeria."); + else setError("Não foi possível pesquisar agora. Confirma a rede e tenta outra vez."); setResult(null); } finally { setBusy(false); @@ -91,7 +96,8 @@ export function FindByPhoto({ }, [result]); const photos = useMemo(() => (result ? (only ? result.photos.filter((p) => p.level === only) : result.photos) : []), [result, only]); - const person = result?.people[0] ?? null; + const person = result?.identity ?? result?.people[0] ?? null; + const licence = person && "licence" in person ? (person.licence ?? null) : null; const rememberFaces = (photoId: string, faces: PhotoFace[] | undefined) => { setResult((cur) => (cur ? { ...cur, photos: cur.photos.map((p) => (p.id === photoId ? { ...p, faces } : p)) } : cur)); @@ -116,11 +122,27 @@ export function FindByPhoto({

+