diff --git a/apps/api/src/sports/service.ts b/apps/api/src/sports/service.ts index cdf1156..d030731 100644 --- a/apps/api/src/sports/service.ts +++ b/apps/api/src/sports/service.ts @@ -9,6 +9,7 @@ import { 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"; +import { tallyOf, tallySquadPhotos } from "./squadPhotos.js"; import { type Fetch, type FixtureData, @@ -746,17 +747,8 @@ export class SportsService { JOIN photos ph ON ph.id = f.photo_id WHERE g.event_id = ${eventId}::uuid AND g.ignored_at IS NULL AND ph.event_id = ${eventId}::uuid AND (g.person_id IS NOT NULL OR g.suggested_person_id IS NOT NULL)`; - const photosOf = new Map; likely: Set }>(); - for (const r of rows) { - const entry = photosOf.get(r.person_id) ?? { confirmed: new Set(), likely: new Set() }; - (r.confirmed ? entry.confirmed : entry.likely).add(r.photo_id); - photosOf.set(r.person_id, entry); - } - const counts = (personId: string | null) => { - const e = personId ? photosOf.get(personId) : undefined; - if (!e) return { confirmed: 0, likely: 0 }; - return { confirmed: e.confirmed.size, likely: [...e.likely].filter((id) => !e.confirmed.has(id)).length }; - }; + const photosOf = tallySquadPhotos(rows); + const counts = (personId: string | null) => tallyOf(photosOf, personId); for (const [side, team] of [ ["home", event.homeTeam], ["away", event.awayTeam], @@ -771,16 +763,20 @@ export class SportsService { sides.push({ side, team: { id: team.id, name: team.name, abbreviation: team.abbreviation, logoUrl: team.logoUrl }, - players: players.map((p) => ({ - id: p.id, - number: p.number, - name: p.name, - fullName: p.fullName, - position: p.position, - hasPhoto: !!p.photoUrl, - personId: personOf.get(p.id) ?? null, - photos: counts(personOf.get(p.id) ?? null), - })), + players: players.map((p) => { + const tally = counts(personOf.get(p.id) ?? null); + return { + id: p.id, + number: p.number, + name: p.name, + fullName: p.fullName, + position: p.position, + hasPhoto: !!p.photoUrl, + personId: personOf.get(p.id) ?? null, + photos: { confirmed: tally.confirmed, likely: tally.likely }, + photoIds: tally.photoIds, + }; + }), }); } return { eventId, sides }; diff --git a/apps/api/src/sports/squadPhotos.test.ts b/apps/api/src/sports/squadPhotos.test.ts new file mode 100644 index 0000000..d0b96f6 --- /dev/null +++ b/apps/api/src/sports/squadPhotos.test.ts @@ -0,0 +1,18 @@ +import { describe, expect, it } from "vitest"; +import { tallyOf, tallySquadPhotos } from "./squadPhotos.js"; + +describe("squad photo tallies", () => { + it("counts a photo once when it is both confirmed and only suggested", () => { + const index = tallySquadPhotos([ + { person_id: "rui", photo_id: "p1", confirmed: true }, + { person_id: "rui", photo_id: "p2", confirmed: true }, + { person_id: "rui", photo_id: "p2", confirmed: false }, + { person_id: "rui", photo_id: "p3", confirmed: false }, + { person_id: "tiago", photo_id: "p4", confirmed: false }, + ]); + expect(tallyOf(index, "rui")).toEqual({ confirmed: 2, likely: 1, photoIds: ["p1", "p2", "p3"] }); + expect(tallyOf(index, "tiago")).toEqual({ confirmed: 0, likely: 1, photoIds: ["p4"] }); + expect(tallyOf(index, null)).toEqual({ confirmed: 0, likely: 0, photoIds: [] }); + expect(tallyOf(index, "missing")).toEqual({ confirmed: 0, likely: 0, photoIds: [] }); + }); +}); diff --git a/apps/api/src/sports/squadPhotos.ts b/apps/api/src/sports/squadPhotos.ts new file mode 100644 index 0000000..377e033 --- /dev/null +++ b/apps/api/src/sports/squadPhotos.ts @@ -0,0 +1,39 @@ +/** One face row: the person it names, the photo, and whether that name is confirmed. */ +export interface SquadPhotoRow { + person_id: string; + photo_id: string; + confirmed: boolean; +} + +export interface SquadPhotoTally { + confirmed: number; + likely: number; + /** Confirmed photos, then the ones only suggested. A photo that is both is listed once. */ + photoIds: string[]; +} + +/** + * Photos of each person in one event. A photo with a confirmed face and a suggestion of the same person + * counts once, as confirmed. The id list is what the library shows when that player is picked. + */ +export function tallySquadPhotos(rows: readonly SquadPhotoRow[]): Map { + const buckets = new Map; likely: Set }>(); + for (const row of rows) { + if (!row.person_id || !row.photo_id) continue; + const bucket = buckets.get(row.person_id) ?? { confirmed: new Set(), likely: new Set() }; + if (row.confirmed) bucket.confirmed.add(row.photo_id); + else bucket.likely.add(row.photo_id); + buckets.set(row.person_id, bucket); + } + const out = new Map(); + for (const [personId, bucket] of buckets) { + const likely = [...bucket.likely].filter((id) => !bucket.confirmed.has(id)); + out.set(personId, { confirmed: bucket.confirmed.size, likely: likely.length, photoIds: [...bucket.confirmed, ...likely] }); + } + return out; +} + +export function tallyOf(index: Map, personId: string | null): SquadPhotoTally { + if (!personId) return { confirmed: 0, likely: 0, photoIds: [] }; + return index.get(personId) ?? { confirmed: 0, likely: 0, photoIds: [] }; +} diff --git a/apps/api/test/sports.test.ts b/apps/api/test/sports.test.ts index 73de870..ad7be37 100644 --- a/apps/api/test/sports.test.ts +++ b/apps/api/test/sports.test.ts @@ -546,10 +546,12 @@ describe("sports data service", () => { await face(p3!.id, likely.id); await face(p4!.id, doubtful.id); await face(p1!.id, ignored.id); // "not a person" / ignored: never counted - const squads = (await ctx.app.inject({ method: "GET", url: `/v1/events/${eventId}/squads`, headers: bearer(token) })).json() as { sides: { players: { name: string; photos: { confirmed: number; likely: number } }[] }[] }; - const photosOf = (name: string) => squads.sides.flatMap((s) => s.players).find((p) => p.name === name)!.photos; - expect(photosOf("Rui Lopes")).toEqual({ confirmed: 2, likely: 1 }); - expect(photosOf("Tiago Ferreira")).toEqual({ confirmed: 0, likely: 1 }); + const squads = (await ctx.app.inject({ method: "GET", url: `/v1/events/${eventId}/squads`, headers: bearer(token) })).json() as { sides: { players: { name: string; photos: { confirmed: number; likely: number }; photoIds: string[] }[] }[] }; + const player = (name: string) => squads.sides.flatMap((s) => s.players).find((p) => p.name === name)!; + expect(player("Rui Lopes").photos).toEqual({ confirmed: 2, likely: 1 }); + expect(player("Rui Lopes").photoIds.slice().sort()).toEqual([p1!.id, p2!.id, p3!.id].sort()); + expect(player("Tiago Ferreira").photos).toEqual({ confirmed: 0, likely: 1 }); + expect(player("Tiago Ferreira").photoIds).toEqual([p4!.id]); }); it("FPA: a past season, club by club, following every club met (national games only)", async () => { diff --git a/apps/app/src/i18n.ts b/apps/app/src/i18n.ts index 05f7308..328092c 100644 --- a/apps/app/src/i18n.ts +++ b/apps/app/src/i18n.ts @@ -58,6 +58,7 @@ export const t = { deliveryStates: { any: "Todas", unsent: "Por enviar", queued: "A enviar", sent: "Enviadas", failed: "Com erro" }, noPlayersFilter: "Sem jogador", clearFilter: "Limpar filtro", + clearPlayers: "Limpar jogadores", sendN: (n: number) => (n ? `Enviar ${n}` : "Enviar"), outputSelection: "As selecionadas", outputBest: "As melhores", diff --git a/apps/app/src/library/Squads.test.tsx b/apps/app/src/library/Squads.test.tsx new file mode 100644 index 0000000..6f0c684 --- /dev/null +++ b/apps/app/src/library/Squads.test.tsx @@ -0,0 +1,62 @@ +import type { ApiClient, EventSquads, EventSummary } from "@photoreport/sdk"; +import { fireEvent, render, screen, waitFor } from "@testing-library/react"; +import { useMemo, useState } from "react"; +import { describe, expect, it, vi } from "vitest"; +import { SquadsButton } from "./Squads.js"; +import { type PlayerPick, samePicks } from "./squadFilter.js"; + +const squads: EventSquads = { + eventId: "e1", + sides: [ + { + side: "home", + team: { id: "t1", name: "ÁGUAS SANTAS MILANEZA", abbreviation: "ASM", logoUrl: null }, + players: [ + { id: "pl1", number: "5", name: "Miguel Baptista", fullName: null, position: null, hasPhoto: false, personId: "pe1", photos: { confirmed: 0, likely: 2 }, photoIds: ["a", "b"] }, + { id: "pl2", number: "7", name: "Gabriel", fullName: null, position: null, hasPhoto: false, personId: null, photos: { confirmed: 0, likely: 0 }, photoIds: [] }, + ], + }, + { + side: "away", + team: { id: "t2", name: "SPORTING CP", abbreviation: "SCP", logoUrl: null }, + players: [ + { id: "pl3", number: "2", name: "Edney Oliveira", fullName: null, position: null, hasPhoto: false, personId: "pe3", photos: { confirmed: 1, likely: 0 }, photoIds: ["b", "c"] }, + ], + }, + ], +}; + +function Harness() { + const [picks, setPicks] = useState([]); + const ids = useMemo(() => picks.map((p) => p.id), [picks]); + return ( + <> + {}} + selectedIds={ids} + onPlayers={(next) => setPicks((cur) => (samePicks(cur, next) ? cur : next))} + /> +

{picks.map((p) => p.photoIds.join("+")).join("|")}

+ + ); +} + +describe("squad panel", () => { + it("filters to each player that is clicked, and drops one on a second click", async () => { + render(); + fireEvent.click(screen.getByRole("button", { name: "Plantéis" })); + const miguel = await screen.findByRole("button", { name: /Miguel Baptista/ }); + expect((screen.getByRole("button", { name: /Gabriel/ }) as HTMLButtonElement).disabled).toBe(true); + fireEvent.click(miguel); + await waitFor(() => expect(screen.getByTestId("picked").textContent).toBe("a+b")); + expect(miguel.getAttribute("aria-pressed")).toBe("true"); + fireEvent.click(screen.getByRole("button", { name: /Edney Oliveira/ })); + await waitFor(() => expect(screen.getByTestId("picked").textContent).toBe("a+b|b+c")); + fireEvent.click(miguel); + await waitFor(() => expect(screen.getByTestId("picked").textContent).toBe("b+c")); + expect(miguel.getAttribute("aria-pressed")).toBe("false"); + }); +}); diff --git a/apps/app/src/library/Squads.tsx b/apps/app/src/library/Squads.tsx index c807700..a7c91f2 100644 --- a/apps/app/src/library/Squads.tsx +++ b/apps/app/src/library/Squads.tsx @@ -2,12 +2,14 @@ import { ApiError, type ApiClient, type EventSquads, type EventSummary } from "@ import { useEffect, useState } from "react"; import { t } from "../i18n.js"; import { FixturePicker } from "./EventForm.js"; +import { type PlayerPick, picksFrom } from "./squadFilter.js"; /** * The open event's squads (from the federations): who is who by number, and whether each player is already a person * of the organisation (faces and jersey numbers name people). An older event can be linked to its match here. + * Picking players filters the grid to their photos (click again to drop one). */ -export function SquadsButton({ api, event, canEdit, onSaved }: { api: ApiClient; event: EventSummary; canEdit: boolean; onSaved: (e: EventSummary) => void }) { +export function SquadsButton({ api, event, canEdit, onSaved, facesTick = 0, selectedIds = [], onPlayers }: { api: ApiClient; event: EventSummary; canEdit: boolean; onSaved: (e: EventSummary) => void; facesTick?: number; selectedIds?: readonly string[]; onPlayers?: (picks: PlayerPick[]) => void }) { const [open, setOpen] = useState(false); const [squads, setSquads] = useState(null); const [status, setStatus] = useState(null); @@ -15,9 +17,30 @@ export function SquadsButton({ api, event, canEdit, onSaved }: { api: ApiClient; const linked = !!(event.homeTeamId || event.awayTeamId); useEffect(() => { - if (!open || !linked) return; - api.eventSquads(event.id).then(setSquads, () => setSquads(null)); - }, [api, open, linked, event.id, event.homeTeamId, event.awayTeamId]); + if (!linked || (!open && selectedIds.length === 0)) return; + let alive = true; + api.eventSquads(event.id).then( + (s) => alive && setSquads(s), + () => alive && setSquads(null), + ); + return () => { + alive = false; + }; + // selectedIds.length: a closed panel still reloads while a player filter is on. + }, [api, open, linked, event.id, event.homeTeamId, event.awayTeamId, facesTick, selectedIds.length]); + + useEffect(() => { + if (!onPlayers || !squads || selectedIds.length === 0) return; + onPlayers(picksFrom(squads, selectedIds)); + // The squad list was reloaded (new face counts). Keep the same players, with their new photos. + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [squads]); + + const toggle = (playerId: string) => { + if (!squads || !onPlayers) return; + const next = selectedIds.includes(playerId) ? selectedIds.filter((id) => id !== playerId) : [...selectedIds, playerId]; + onPlayers(picksFrom(squads, next)); + }; const fail = (err: unknown) => setStatus(err instanceof ApiError ? err.code : t.unexpectedError); const sync = async () => { @@ -67,24 +90,36 @@ export function SquadsButton({ api, event, canEdit, onSaved }: { api: ApiClient;

{s.team.name}

    - {s.players.map((p) => ( -
  • - {p.number ?? "–"} - {p.name} - - {!p.personId ? ( - · - ) : p.photos && p.photos.confirmed + p.photos.likely > 0 ? ( - <> - {p.photos.confirmed > 0 && {p.photos.confirmed}} - {p.photos.likely > 0 && {p.photos.confirmed > 0 ? " " : ""}+{p.photos.likely}} - - ) : ( - 0 - )} - -
  • - ))} + {s.players.map((p) => { + const on = selectedIds.includes(p.id); + return ( +
  • + +
  • + ); + })}
))} diff --git a/apps/app/src/library/squadFilter.test.ts b/apps/app/src/library/squadFilter.test.ts new file mode 100644 index 0000000..76859e1 --- /dev/null +++ b/apps/app/src/library/squadFilter.test.ts @@ -0,0 +1,33 @@ +import type { EventSquads } from "@photoreport/sdk"; +import { describe, expect, it } from "vitest"; +import { photoIdsOf, picksFrom } from "./squadFilter.js"; + +const squads: EventSquads = { + eventId: "e", + sides: [ + { + side: "home", + team: { id: "t1", name: "Águas Santas", abbreviation: "ASM", logoUrl: null }, + players: [ + { id: "pl1", number: "5", name: "Miguel Baptista", fullName: null, position: null, hasPhoto: false, personId: "pe1", photos: { confirmed: 1, likely: 1 }, photoIds: ["a", "b"] }, + { id: "pl2", number: "7", name: "Gabriel", fullName: null, position: null, hasPhoto: false, personId: null, photos: { confirmed: 0, likely: 0 }, photoIds: [] }, + ], + }, + { + side: "away", + team: { id: "t2", name: "Sporting", abbreviation: "SCP", logoUrl: null }, + players: [ + { id: "pl3", number: "2", name: "Edney Oliveira", fullName: null, position: null, hasPhoto: false, personId: "pe3", photos: { confirmed: 0, likely: 1 }, photoIds: ["b", "c"] }, + ], + }, + ], +}; + +describe("squad player filter", () => { + it("keeps the photos of every picked player, once", () => { + const picks = picksFrom(squads, ["pl3", "pl1", "pl2"]); + expect(picks.map((p) => p.name)).toEqual(["Miguel Baptista", "Edney Oliveira"]); + expect([...(photoIdsOf(picks) ?? [])].sort()).toEqual(["a", "b", "c"]); + expect(photoIdsOf([])).toBeNull(); + }); +}); diff --git a/apps/app/src/library/squadFilter.ts b/apps/app/src/library/squadFilter.ts new file mode 100644 index 0000000..afb986e --- /dev/null +++ b/apps/app/src/library/squadFilter.ts @@ -0,0 +1,40 @@ +import type { EventSquads } from "@photoreport/sdk"; + +/** A player picked in the squad panel, and the photos of them in this event. */ +export interface PlayerPick { + id: string; + name: string; + photoIds: string[]; +} + +/** The picked players, in squad order. Someone who is not a person yet cannot filter. */ +export function picksFrom(squads: EventSquads, playerIds: readonly string[]): PlayerPick[] { + const want = new Set(playerIds); + const picks: PlayerPick[] = []; + for (const side of squads.sides) { + for (const player of side.players) { + if (!want.has(player.id) || !player.personId) continue; + picks.push({ id: player.id, name: player.name, photoIds: player.photoIds ?? [] }); + } + } + return picks; +} + +export function samePicks(a: readonly PlayerPick[], b: readonly PlayerPick[]): boolean { + if (a.length !== b.length) return false; + for (let i = 0; i < a.length; i++) { + const left = a[i]!; + const right = b[i]!; + if (left.id !== right.id || left.name !== right.name || left.photoIds.length !== right.photoIds.length) return false; + for (let j = 0; j < left.photoIds.length; j++) if (left.photoIds[j] !== right.photoIds[j]) return false; + } + return true; +} + +/** Photos of any of the picked players. Null means the squad filter is off. */ +export function photoIdsOf(picks: readonly PlayerPick[]): Set | null { + if (!picks.length) return null; + const ids = new Set(); + for (const pick of picks) for (const id of pick.photoIds) ids.add(id); + return ids; +} diff --git a/apps/app/src/pages/LibraryPage.tsx b/apps/app/src/pages/LibraryPage.tsx index 8b76352..cd081c9 100644 --- a/apps/app/src/pages/LibraryPage.tsx +++ b/apps/app/src/pages/LibraryPage.tsx @@ -20,6 +20,7 @@ import { LocalFtpButton } from "../library/LocalFtp.js"; import { CardIngestButton } from "../library/CardIngest.js"; import { AutopilotButton } from "../library/Autopilot.js"; import { SquadsButton } from "../library/Squads.js"; +import { type PlayerPick, photoIdsOf, samePicks } from "../library/squadFilter.js"; import { initialLibrary, isMac, type LibraryFilter, libraryReducer, matchesFilter, patchForKey, pmPatchForKey } from "../library/store.js"; import { cache, type CachedEvents } from "../offline/cache.js"; import { localPhotos } from "../offline/local.js"; @@ -50,6 +51,8 @@ export function LibraryPage() { const { open: openFolderScan, syncGames } = useFolderScan(); const [state, dispatch] = useReducer(libraryReducer, initialLibrary); const [filter, setFilterState] = useState(() => savedFilter(orgId)); + const [players, setPlayers] = useState([]); + const onPlayers = useCallback((next: PlayerPick[]) => setPlayers((cur) => (samePicks(cur, next) ? cur : next)), []); useEffect(() => setFilterState(savedFilter(orgId)), [orgId]); const setFilter = useCallback( (f: LibraryFilter) => { @@ -220,7 +223,22 @@ export function LibraryPage() { const sentCount = uploads.items.filter((i) => i.status === "done" || i.status === "duplicate").length; const overall = uploads.items.length ? uploads.items.reduce((sum, i) => sum + (i.status === "failed" ? 1 : i.progress), 0) / uploads.items.length : 0; - const visible = useMemo(() => state.photos.filter((p) => matchesFilter(p, filter)), [state.photos, filter]); + const playerIds = useMemo(() => photoIdsOf(players), [players]); + const visible = useMemo(() => state.photos.filter((p) => matchesFilter(p, filter) && (playerIds === null || playerIds.has(p.id))), [state.photos, filter, playerIds]); + const selectedPlayerIds = useMemo(() => players.map((p) => p.id), [players]); + useEffect(() => { + setPlayers([]); + }, [uploadInto]); + useEffect(() => { + if (!playerIds) return; + if (state.focus && playerIds.has(state.focus)) return; + const next = state.photos.filter((p) => playerIds.has(p.id) && matchesFilter(p, filter)); + const first = next[0]; + if (!first) return; + dispatch({ type: "select", id: first.id, mode: "single", visible: next.map((p) => p.id) }); + // Only when the picked players change. The photos and the other filters are the ones of this render. + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [playerIds]); const visibleIds = useMemo(() => visible.map((p) => p.id), [visible]); const byId = useMemo(() => new Map(state.photos.map((p) => [p.id, p])), [state.photos]); const focus = (state.focus && byId.get(state.focus)) || null; @@ -367,6 +385,16 @@ export function LibraryPage() {
+ {players.length > 0 && ( + + p.name).join(", ")}> + {players.map((p) => p.name).join(", ")} + + + + )} {canCull && state.scope && state.scope !== "inbox" && !state.scope.startsWith("search:") && !state.scope.startsWith("face:") && (