Compare commits

...
Author SHA1 Message Date
spark 9ff98530d9 Recognise a delivered game by its federation code, and ship the local copy and the game's people.
ci / rust (pull_request) Failing after 37s
ci / typescript (pull_request) Failing after 6m25s
A folder the program writes as AAAS x SCP is Águas Santas x Sporting, so the archive check that already runs when the worker starts attaches the official game. Suggestions on a linked game stay inside the two squads. An export can also keep the same file in a local folder named by the day, the game and the destination, and a gallery can pick anyone named in that game.
2026-10-18 19:29:07 +01:00
spark 6a91d3fa30 Merge pull request 'Filter the grid by the players picked in the squad' (#29) from task/squad-player-filter into main
ci / rust (push) Failing after 40s
ci / typescript (push) Failing after 6m26s
2026-10-18 18:25:59 +01:00
spark 8ecfec231f Filter the grid to the players picked in the squad list.
ci / rust (pull_request) Failing after 42s
ci / typescript (pull_request) Failing after 6m26s
The photos are the ones already counted beside each name, confirmed and suggested, and several players can stay selected at once.
2026-10-18 18:25:27 +01:00
spark c51ab4b010 Merge pull request 'Leave a photo in place until the JPEG is finished' (#28) from task/jpeg-complete into main
ci / rust (push) Failing after 38s
ci / typescript (push) Failing after 6m28s
2026-10-18 16:26:24 +01:00
27 changed files with 752 additions and 88 deletions

No files matched your search

@@ -0,0 +1,10 @@
-- A non-local export can also keep a copy in a folder on one computer.
ALTER TABLE "delivery_targets" ADD COLUMN "local_folder" TEXT;
ALTER TABLE "delivery_targets" ADD COLUMN "local_machine" TEXT;
ALTER TABLE "delivery_targets" ADD COLUMN "local_folder_template" TEXT;
-- The hidden LOCAL target that receives those copies.
ALTER TABLE "delivery_targets" ADD COLUMN "mirror_of_id" UUID;
CREATE UNIQUE INDEX "delivery_targets_mirror_of_id_key" ON "delivery_targets"("mirror_of_id");
ALTER TABLE "delivery_targets" ADD CONSTRAINT "delivery_targets_mirror_of_id_fkey" FOREIGN KEY ("mirror_of_id") REFERENCES "delivery_targets"("id") ON DELETE CASCADE ON UPDATE CASCADE;
+12 -1
View File
@@ -564,12 +564,23 @@ model DeliveryTarget {
/// Everything sent here is also sent to this target (usually a folder on a computer), with this target's IPTC:
/// a local copy of what a client got. Same organization; null: none.
copyTargetId String? @map("copy_target_id") @db.Uuid
/// A folder on one computer that also receives every file this destination exports (FTP and the rest stay as
/// they are). Not for a LOCAL target. The desktop app of `localMachine` writes under this path.
localFolder String? @map("local_folder")
/// That computer's id (`delivery_machine`).
localMachine String? @map("local_machine")
/// Subfolders under `localFolder`. `{destination}` is this target's name.
localFolderTemplate String? @map("local_folder_template")
/// Set only on the hidden LOCAL target that holds those copies; points at the export it mirrors.
mirrorOfId String? @unique @map("mirror_of_id") @db.Uuid
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
disabledAt DateTime? @map("disabled_at")
organization Organization @relation(fields: [organizationId], references: [id], onDelete: Cascade)
organization Organization @relation(fields: [organizationId], references: [id], onDelete: Cascade)
items DeliveryItem[]
mirrorOf DeliveryTarget? @relation("LocalMirror", fields: [mirrorOfId], references: [id], onDelete: Cascade)
localMirror DeliveryTarget? @relation("LocalMirror")
@@unique([organizationId, name])
@@map("delivery_targets")
+5
View File
@@ -1,4 +1,5 @@
import { sameTeam } from "../delivery/zerozero.js";
import { officialSigla } from "../sports/fpa-siglas.js";
/**
* What a gallery folder's place and name say about its game. The archives are organised by season, competition
@@ -377,6 +378,10 @@ export function isTeam(name: string, team: { name: string; abbreviation: string
if (team.abbreviation && fold(team.abbreviation) === n) return true;
if (fold(team.slug) === n || fold(team.name) === n) return true;
if (sameTeam(name, team.name)) return true;
// The delivery writes the federation's short code ("AAAS"). That is not the initials of the sponsor name
// ("Águas Santas Milaneza" is A, S, M), and these teams have no abbreviation of their own.
const sigla = officialSigla(team.name);
if (sigla && fold(sigla) === n) return true;
return name.trim().length <= 6 && !/\s/.test(name.trim()) && isInitials(name, team.name);
}
+21 -1
View File
@@ -321,7 +321,12 @@ export async function registerArchiveViewerRoutes(
...(query.player && { photo: { players: { has: query.player } } }),
...(query.person && { photo: { faces: { some: { group: { personId: query.person, ignoredAt: null } } } } }),
};
const [total, files, named, sharpest] = await Promise.all([
// People named anywhere in this game (every part the viewer may see), not only in this folder.
const rosterScope =
visible === "all"
? Prisma.sql`cf.source_id = ${folder.sourceId}::uuid AND cf.status = 'DONE'`
: Prisma.sql`cf.source_id = ${folder.sourceId}::uuid AND cf.status = 'DONE' AND cf.folder_id = ANY(${visible}::uuid[])`;
const [total, files, named, sharpest, roster] = await Promise.all([
db.cloudFile.count({ where }),
db.cloudFile.findMany({
where,
@@ -344,6 +349,19 @@ export async function registerArchiveViewerRoutes(
JOIN face_groups g ON g.id = f.group_id AND g.person_id IS NOT NULL AND g.ignored_at IS NULL
JOIN cloud_files cf ON cf.photo_id = f.photo_id AND cf.folder_id = ${folderId}::uuid AND cf.status = 'DONE'
ORDER BY g.person_id, f.sharpness DESC NULLS LAST, f.score DESC`,
folder.eventId
? db.$queryRaw<{ id: string; name: string; club: string | null; number: string | null; here: number; in_game: number }[]>`
SELECT p.id, p.name, p.club, p.number,
count(DISTINCT cf.photo_id) FILTER (WHERE cf.folder_id = ${folderId}::uuid)::int AS here,
count(DISTINCT cf.photo_id)::int AS in_game
FROM faces f
JOIN face_groups g ON g.id = f.group_id AND g.person_id IS NOT NULL AND g.ignored_at IS NULL
JOIN people p ON p.id = g.person_id
JOIN cloud_files cf ON cf.photo_id = f.photo_id AND ${rosterScope}
JOIN photos ph ON ph.id = cf.photo_id AND ph.event_id = ${folder.eventId}::uuid
GROUP BY p.id, p.name, p.club, p.number
ORDER BY p.name`
: Promise.resolve([]),
]);
const facePhotos = await db.photo.findMany({
where: { id: { in: sharpest.map((f) => f.photo_id) } },
@@ -368,6 +386,8 @@ export async function registerArchiveViewerRoutes(
cloudUrl: `${base}/f/${folder.fileId}`,
total,
people: named.map((p) => ({ id: p.id, name: p.name, count: Number(p.count), face: faceOf.get(p.id) ?? null })),
/** Everyone named in this game, so a gallery can offer them even when this part has only some. */
roster: roster.map((p) => ({ id: p.id, name: p.name, club: p.club, number: p.number, here: Number(p.here), inGame: Number(p.in_game) })),
photos: files.map((f) => ({
id: f.photo!.id,
name: f.path.split("/").pop(),
+51 -14
View File
@@ -1,7 +1,7 @@
import { createReadStream, existsSync } from "node:fs";
import { DeliveryBestRequest, DeliveryRequest } from "@photoreport/contracts";
import { bestOfEvent } from "../autopilot/best.js";
import { IptcTemplate, PathTemplateError, renderFileName, renderFolder, buildVars } from "@photoreport/metadata";
import { IptcTemplate, LOCAL_COPY_FOLDER, PathTemplateError, renderFileName, renderFolder, buildVars } from "@photoreport/metadata";
import type { FastifyInstance } from "fastify";
import { z } from "zod";
import { currentUserId, requireAuth, requireMembership } from "../auth/guard.js";
@@ -10,7 +10,7 @@ import type { Db } from "../db.js";
import { type DeliveryTarget, Prisma } from "../generated/prisma/client.js";
import { compact } from "../lib/compact.js";
import { AppError, badRequest, conflict, notFound } from "../lib/errors.js";
import { DeliveryRejected, type DeliveryService, toItemSummary } from "./service.js";
import { DeliveryRejected, syncLocalMirror, type DeliveryService, toItemSummary } from "./service.js";
import { NextcloudError } from "./nextcloud.js";
import { TransportError } from "./transports.js";
import type { SecretBox } from "./secrets.js";
@@ -59,6 +59,12 @@ const TargetBase = z.object({
iptcOverrides: IptcTemplate.partial().nullable(),
/** Everything sent here also goes to this target (a folder on a computer), with this target's IPTC; null: none. */
copyTargetId: z.uuid().nullable(),
/** Also save each exported file under this folder on one computer. Null: the export only. Not for LOCAL. */
localFolder: z.string().trim().min(1).max(300).nullable(),
/** That computer's id. Required when `localFolder` is set. */
localMachine: z.string().trim().min(8).max(120).nullable(),
/** Subfolders under `localFolder`. `{destination}` is this target's name. Null with a folder: the default. */
localFolderTemplate: z.string().trim().min(1).max(400).nullable(),
});
const checkAddress = (kind: z.infer<typeof KIND>, baseUrl: string, username: string) => {
if (!ADDRESS[kind].test(baseUrl)) throw badRequest("invalid_address", `address for ${kind} must look like ${ADDRESS[kind].source}`);
@@ -79,6 +85,9 @@ const TargetFields = TargetBase.extend({
untouched: TargetBase.shape.untouched.default(false),
iptcOverrides: TargetBase.shape.iptcOverrides.default(null),
copyTargetId: TargetBase.shape.copyTargetId.default(null),
localFolder: TargetBase.shape.localFolder.default(null),
localMachine: TargetBase.shape.localMachine.default(null),
localFolderTemplate: TargetBase.shape.localFolderTemplate.default(null),
});
const UpdateTarget = TargetBase.partial().extend({ disabled: z.boolean().optional(), resetHostKey: z.boolean().optional() });
const ListQuery = z.object({
@@ -100,17 +109,35 @@ function overridesValue(o: unknown): Prisma.InputJsonValue | typeof Prisma.DbNul
}
function publicTarget(t: DeliveryTarget) {
const { secretEnc: _secret, ...rest } = t;
const { secretEnc: _secret, mirrorOfId: _mirror, ...rest } = t;
return { ...rest, shareLinks: t.kind === "NEXTCLOUD" || t.kind === "DROPBOX" };
}
/** The local copy of an export: a real folder on a computer. A destination that is already a folder has none. */
function localCopyOf(
kind: z.infer<typeof KIND>,
fields: { localFolder: string | null; localMachine: string | null; localFolderTemplate: string | null },
): { localFolder: string | null; localMachine: string | null; localFolderTemplate: string | null } {
if (kind === "LOCAL" || !fields.localFolder) {
return { localFolder: null, localMachine: null, localFolderTemplate: null };
}
if (!ADDRESS.LOCAL.test(fields.localFolder)) throw badRequest("invalid_address", "the local folder must be an absolute path");
if (!fields.localMachine) throw badRequest("username_required");
const localFolderTemplate = fields.localFolderTemplate || LOCAL_COPY_FOLDER;
checkTemplates(localFolderTemplate, "{originalName}", { destination: "Cliente" });
return { localFolder: fields.localFolder, localMachine: fields.localMachine, localFolderTemplate };
}
/** Renders the templates against a sample event so a broken template is refused when saved, not at delivery. */
function checkTemplates(folderTemplate: string, fileNameTemplate: string) {
const sample = buildVars(
{ home: "Casa", away: "Fora", venue: "Pavilhão", city: "Cidade", sport: "andebol", competition: "Competição", competitionCode: "C01", round: "1", matchNumber: "1", startsAt: new Date("2026-09-23T19:00:00Z") },
{ capturedAt: new Date("2026-09-23T19:30:00Z"), players: ["Jogador"], sequence: 1 },
"Fotógrafo",
);
function checkTemplates(folderTemplate: string, fileNameTemplate: string, extra: Record<string, string> = {}) {
const sample = {
...buildVars(
{ home: "Casa", away: "Fora", venue: "Pavilhão", city: "Cidade", sport: "andebol", competition: "Competição", competitionCode: "C01", round: "1", matchNumber: "1", startsAt: new Date("2026-09-23T19:00:00Z") },
{ capturedAt: new Date("2026-09-23T19:30:00Z"), players: ["Jogador"], sequence: 1 },
"Fotógrafo",
),
...extra,
};
try {
return { folder: renderFolder(folderTemplate, sample), fileName: renderFileName(fileNameTemplate, sample, "IMG_0001.JPG") };
} catch (err) {
@@ -135,7 +162,7 @@ export async function registerDeliveryRoutes(
const checkCopy = async (orgId: string, selfId: string | null, copyId: string | null | undefined) => {
if (!copyId) return;
if (copyId === selfId) throw badRequest("copy_to_itself");
if (!(await db.deliveryTarget.count({ where: { id: copyId, organizationId: orgId } }))) throw badRequest("unknown_copy_target");
if (!(await db.deliveryTarget.count({ where: { id: copyId, organizationId: orgId, mirrorOfId: null } }))) throw badRequest("unknown_copy_target");
};
const seal = (password: string) => {
if (!secrets) throw new AppError(503, "delivery_not_configured", "DELIVERY_SECRET_KEY is not set");
@@ -152,7 +179,7 @@ export async function registerDeliveryRoutes(
app.get("/v1/orgs/:orgId/delivery-targets", { preHandler: authenticate }, async (req) => {
const { orgId } = OrgParams.parse(req.params);
await requireMembership(db, req, orgId, "INGESTER");
const targets = await db.deliveryTarget.findMany({ where: { organizationId: orgId }, orderBy: { name: "asc" } });
const targets = await db.deliveryTarget.findMany({ where: { organizationId: orgId, mirrorOfId: null }, orderBy: { name: "asc" } });
return { targets: targets.map(publicTarget) };
});
@@ -163,11 +190,13 @@ export async function registerDeliveryRoutes(
checkAddress(body.kind, body.baseUrl, body.username);
const example = checkTemplates(body.folderTemplate, body.fileNameTemplate);
if (await db.deliveryTarget.findUnique({ where: { organizationId_name: { organizationId: orgId, name: body.name } } })) throw conflict("name_taken");
const { password, iptcOverrides, ...fields } = body;
const { password, iptcOverrides, localFolder: _lf, localMachine: _lm, localFolderTemplate: _lt, ...fields } = body;
const local = localCopyOf(body.kind, body);
if (!password && body.kind !== "LOCAL") throw badRequest("password_required");
await checkLogins(orgId, body.arrivalLogins);
await checkCopy(orgId, null, body.copyTargetId);
const target = await db.deliveryTarget.create({ data: { ...fields, iptcOverrides: overridesValue(iptcOverrides), organizationId: orgId, secretEnc: seal(password ?? "") } });
const target = await db.deliveryTarget.create({ data: { ...fields, ...local, iptcOverrides: overridesValue(iptcOverrides), organizationId: orgId, secretEnc: seal(password ?? "") } });
await syncLocalMirror(db, secrets, target).catch(fail);
return reply.code(201).send({ ...publicTarget(target), example });
});
@@ -184,18 +213,25 @@ export async function registerDeliveryRoutes(
// Another server, another key: a changed address forgets the remembered one.
const forgetKey = body.resetHostKey === true || kind !== current.kind || baseUrl !== current.baseUrl;
const { password, disabled, resetHostKey: _reset, iptcOverrides, ...fields } = body;
const local = localCopyOf(kind, {
localFolder: fields.localFolder !== undefined ? fields.localFolder : current.localFolder,
localMachine: fields.localMachine !== undefined ? fields.localMachine : current.localMachine,
localFolderTemplate: fields.localFolderTemplate !== undefined ? fields.localFolderTemplate : current.localFolderTemplate,
});
if (fields.arrivalLogins) await checkLogins(orgId, fields.arrivalLogins);
if (fields.copyTargetId !== undefined) await checkCopy(orgId, targetId, fields.copyTargetId);
const target = await db.deliveryTarget.update({
where: { id: targetId },
data: {
...compact(fields),
...local,
...(iptcOverrides !== undefined && { iptcOverrides: overridesValue(iptcOverrides) }),
...(password !== undefined && { secretEnc: seal(password) }),
...(forgetKey && { hostFingerprint: null }),
...(disabled !== undefined && { disabledAt: disabled ? (current.disabledAt ?? new Date()) : null }),
},
});
await syncLocalMirror(db, secrets, target).catch(fail);
return { ...publicTarget(target), example };
});
@@ -209,8 +245,9 @@ export async function registerDeliveryRoutes(
if (await db.deliveryTarget.findUnique({ where: { organizationId_name: { organizationId: orgId, name: body.name } } })) throw conflict("name_taken");
const folderTemplate = body.folderTemplate ?? source.folderTemplate;
const example = checkTemplates(folderTemplate, source.fileNameTemplate);
const { id: _id, createdAt: _c, updatedAt: _u, disabledAt: _d, iptcOverrides, ...copy } = source;
const { id: _id, createdAt: _c, updatedAt: _u, disabledAt: _d, iptcOverrides, mirrorOfId: _mirror, ...copy } = source;
const target = await db.deliveryTarget.create({ data: { ...copy, iptcOverrides: overridesValue(iptcOverrides), name: body.name, folderTemplate } });
await syncLocalMirror(db, secrets, target).catch(fail);
return reply.code(201).send({ ...publicTarget(target), example });
});
+85 -17
View File
@@ -1,7 +1,7 @@
import type { DeliveryItemSummary } from "@photoreport/contracts";
import { buildVars, createdStamp, eventName, PathTemplateError, renderFileName, renderFolder } from "@photoreport/metadata";
import { buildVars, createdStamp, eventName, LOCAL_COPY_FOLDER, PathTemplateError, renderFileName, renderFolder } from "@photoreport/metadata";
import type { Db } from "../db.js";
import type { DeliveryItem } from "../generated/prisma/client.js";
import type { DeliveryItem, DeliveryTarget } from "../generated/prisma/client.js";
import type { IngestLogger } from "../ingest/service.js";
import { waitUntil } from "../lib/idle.js";
import { eventInfoOf } from "../library/event-info.js";
@@ -61,6 +61,45 @@ export function deliveredName(photo: { originalName: string; fileName: string |
/** Where a file rendered for a computer's folder waits on the server. */
export const localKey = (orgId: string, itemId: string) => `${orgId}/deliveries/${itemId}.jpg`;
/**
* Keeps the hidden LOCAL target that receives one export's local copies in step with that export (same file name
* and output). Turning the folder off disables it; the export itself is unchanged.
*/
export async function syncLocalMirror(db: Db, secrets: { seal(plain: string): string } | undefined, target: DeliveryTarget): Promise<void> {
const existing = await db.deliveryTarget.findFirst({ where: { mirrorOfId: target.id } });
const off = target.kind === "LOCAL" || !target.localFolder || !target.localMachine;
if (off) {
if (existing && !existing.disabledAt) await db.deliveryTarget.update({ where: { id: existing.id }, data: { disabledAt: new Date() } });
return;
}
const data = {
name: `local-copy:${target.id}`,
kind: "LOCAL" as const,
baseUrl: target.localFolder!,
username: target.localMachine!,
folderTemplate: target.localFolderTemplate || LOCAL_COPY_FOLDER,
fileNameTemplate: target.fileNameTemplate,
longEdge: target.longEdge,
jpegQuality: target.jpegQuality,
sharpen: target.sharpen,
dpi: target.dpi,
keepExif: target.keepExif,
srgb: target.srgb,
originals: target.originals,
untouched: target.untouched,
onArrival: false,
arrivalLogins: [] as string[],
disabledAt: null,
organizationId: target.organizationId,
};
if (existing) {
await db.deliveryTarget.update({ where: { id: existing.id }, data });
return;
}
if (!secrets) throw new DeliveryRejected("delivery_secret_key_missing");
await db.deliveryTarget.create({ data: { ...data, mirrorOfId: target.id, secretEnc: secrets.seal("") } });
}
/**
* Marks a photo's deliveries to be taken back (the photo was rejected or un-picked). Already on a destination
* (DONE) or waiting for a computer (WAITING): queued for the worker to remove. Not uploaded yet (QUEUED):
@@ -148,6 +187,8 @@ export class DeliveryService {
requestedById: string | null;
/** Set when this is the local copy of a delivery to that target. */
via?: string;
/** Photo id → sequence of the export this copies, so `{n}` in the file name matches the file that was sent. */
sequences?: ReadonlyMap<string, number>;
}): Promise<{ queued: DeliveryItem[]; skipped: { photoId: string; reason: string }[] }> {
const { db } = this.deps;
const target = await db.deliveryTarget.findFirst({ where: { id: input.targetId, organizationId: input.organizationId, disabledAt: null } });
@@ -188,9 +229,13 @@ export class DeliveryService {
let next = (last._max.sequence ?? 0) + 1;
const created: DeliveryItem[] = [];
for (const photo of group) {
// A local copy of an export keeps that export's number, so the file name is the one that was sent.
const fixed = input.sequences?.get(photo.id);
const sequence = fixed ?? next;
if (fixed === undefined || fixed >= next) next = sequence + 1;
created.push(
await tx.deliveryItem.create({
data: { organizationId: input.organizationId, targetId: target.id, photoId: photo.id, eventId, sequence: next++, requestedById: input.requestedById, viaTargetId: input.via ?? null },
data: { organizationId: input.organizationId, targetId: target.id, photoId: photo.id, eventId, sequence, requestedById: input.requestedById, viaTargetId: input.via ?? null },
}),
);
}
@@ -199,11 +244,30 @@ export class DeliveryService {
queued.push(...items);
}
for (const item of queued) this.deps.broadcaster.library(item.organizationId, { type: "delivery.updated", item: toItemSummary(item) });
// A copy of what this client gets, e.g. in a folder on the photographer's computer (one level: a copy is not copied).
if (target.copyTargetId && target.copyTargetId !== target.id && !input.via && queued.length) {
await this.enqueue({ ...input, targetId: target.copyTargetId, photoIds: queued.map((q) => q.photoId), via: target.id }).catch((err: unknown) =>
this.deps.log.warn({ err, targetId: target.id, copyTargetId: target.copyTargetId }, "delivery: local copy not queued"),
);
// Copies are not copied again. The export itself is unchanged; these are extra files.
if (!input.via && queued.length) {
const photoIds = queued.map((q) => q.photoId);
if (target.copyTargetId && target.copyTargetId !== target.id) {
await this.enqueue({ ...input, targetId: target.copyTargetId, photoIds, via: target.id }).catch((err: unknown) =>
this.deps.log.warn({ err, targetId: target.id, copyTargetId: target.copyTargetId }, "delivery: copy not queued"),
);
}
// The same export, also saved under the computer folder (date, game, destination name).
if (target.kind !== "LOCAL" && target.localFolder && target.localMachine) {
const mirror = await db.deliveryTarget.findFirst({ where: { mirrorOfId: target.id, disabledAt: null } });
if (!mirror) this.deps.log.warn({ targetId: target.id }, "delivery: local folder set but its copy target is missing");
else {
await this.enqueue({
organizationId: input.organizationId,
targetId: mirror.id,
photoIds,
again: input.again,
requestedById: input.requestedById,
via: target.id,
sequences: new Map(queued.map((q) => [q.photoId, q.sequence])),
}).catch((err: unknown) => this.deps.log.warn({ err, targetId: target.id }, "delivery: local copy not queued"));
}
}
}
return { queued, skipped };
}
@@ -397,25 +461,29 @@ export class DeliveryService {
try {
// The IPTC first: Photo Mechanic's {headline}, {caption}... in folder and file names are the photo's pad.
// With this client's own fields on top (another agency in Creator, players left to right in Title...).
// A local copy of another client's delivery is written with that client's IPTC: the same file it got.
const via = item.viaTargetId ? await db.deliveryTarget.findUnique({ where: { id: item.viaTargetId }, select: { iptcOverrides: true } }) : null;
const iptc = await iptcForPhoto(db, item.photoId, via ? via.iptcOverrides : item.target.iptcOverrides);
// A copy of another client's delivery is written with that client's IPTC. The local folder of an export is
// the same file that client got (its size, name and IPTC), filed by day, game and destination.
const viaTarget = item.viaTargetId ? await db.deliveryTarget.findUnique({ where: { id: item.viaTargetId } }) : null;
const sameExport = Boolean(item.target.mirrorOfId && viaTarget);
const recipe = sameExport && viaTarget ? viaTarget : item.target;
const iptc = await iptcForPhoto(db, item.photoId, (viaTarget ?? item.target).iptcOverrides);
const source = cloud?.file ?? storage.resolve(item.photo.storageKey);
// Photos from before the camera details were kept: read them from the file being sent.
const exif = item.photo.exif ?? (await readCameraInfo(source).then((c) => c.extra ?? null, () => null));
const vars = buildVars(eventInfoOf(item.event), photoInfoOf({ ...item.photo, exif }, { sequence: item.sequence }), item.photo.uploader?.name, { iptc: iptc?.values });
let folder = renderFolder(item.target.folderTemplate, vars);
if (item.target.kind === "ZEROZERO") folder = `${await this.zerozeroGameId(item.target, item.event)}/`;
const named = sameExport && viaTarget ? { ...vars, destination: viaTarget.name } : vars;
let folder = renderFolder(sameExport && viaTarget ? viaTarget.localFolderTemplate || LOCAL_COPY_FOLDER : item.target.folderTemplate, named);
if (!sameExport && item.target.kind === "ZEROZERO") folder = `${await this.zerozeroGameId(item.target, item.event)}/`;
// {originalName} is the name given on arrival when the photo was renamed (as Photo Mechanic renames the file).
// Untouched: the camera's own name, as a local FTP would have received it.
const fileName = renderFileName(item.target.fileNameTemplate, vars, item.target.originals && item.target.untouched ? item.photo.originalName : deliveredName(item.photo));
const fileName = renderFileName(recipe.fileNameTemplate, named, recipe.originals && recipe.untouched ? item.photo.originalName : deliveredName(item.photo));
const edit = await this.editFor(item.photoId, item.photo.developSeq);
const created = item.photo.capturedAt ? createdStamp(item.photo.capturedAt) : undefined;
const rendered = item.target.originals
? item.target.untouched
const rendered = recipe.originals
? recipe.untouched
? await readFile(source)
: await originalWithMetadata(source, iptc?.values ?? {}, created)
: await renderDelivery(source, iptc?.values ?? {}, { longEdge: item.target.longEdge, quality: item.target.jpegQuality, sharpen: item.target.sharpen, dpi: item.target.dpi, exif: item.target.keepExif, srgb: item.target.srgb }, created, edit);
: await renderDelivery(source, iptc?.values ?? {}, { longEdge: recipe.longEdge, quality: recipe.jpegQuality, sharpen: recipe.sharpen, dpi: recipe.dpi, exif: recipe.keepExif, srgb: recipe.srgb }, created, edit);
const data = rendered;
if (item.target.kind === "LOCAL") {
// Kept here until the computer's desktop app takes it (localClaim → localFile → localResult).
+29 -1
View File
@@ -266,6 +266,9 @@ export class FaceService {
const people = everyone.filter((p) => !sport || !sports.has(p.id) || sports.get(p.id) === sport);
// Numbers as worn in this event's season and competition (another season, a cup, the national team: another).
const ctx = await numberContext(db, eventId);
// A game linked to its two clubs: only those squads. Another club's player who looks alike is not a guess.
const squadIds = ctx?.teamIds.length ? await playerIdsOnSquads(db, ctx.teamIds, ctx.season) : null;
const candidates = squadIds ? people.filter((p) => p.sportsPlayerId !== null && squadIds.has(p.sportsPlayerId)) : people;
const worn = new Map<string, string | null>();
const numberOf = async (ids: string[]): Promise<Map<string, string | null>> => {
const missing = ids.filter((id) => !worn.has(id));
@@ -277,7 +280,7 @@ export class FaceService {
};
for (const g of groups) {
const { match, margin } = this.thresholds(g.model);
const ranked = people
const ranked = candidates
.filter((p) => p.model === g.model)
.map((p) => ({ p, s: cosine(p.centroid, g.centroid) }))
.sort((a, b) => b.s - a.s);
@@ -577,6 +580,31 @@ export function normSport(s: string | null | undefined): string | null {
return v;
}
/**
* Squad entries of these teams this season, plus the same player written under another season (the federation id,
* or the same name at the same club). Null when this season's squad is not here yet: then a face may still be
* matched more widely. An empty set means the squad is known and nobody outside it is a candidate.
*/
async function playerIdsOnSquads(db: Db, teamIds: string[], season: string): Promise<Set<string> | null> {
const squad = await db.sportsPlayer.findMany({
where: { teamId: { in: teamIds }, season },
select: { id: true, teamId: true, name: true, externalId: true },
});
if (!squad.length) return null;
const externalIds = [...new Set(squad.map((s) => s.externalId).filter((x): x is string => !!x))];
const same = await db.sportsPlayer.findMany({
where: {
OR: [
{ id: { in: squad.map((s) => s.id) } },
...squad.map((s) => ({ teamId: s.teamId, name: s.name })),
...(externalIds.length ? [{ externalId: { in: externalIds } }] : []),
],
},
select: { id: true },
});
return new Set(same.map((s) => s.id));
}
/** The sport of an event: its own, its official game's, or its archive cloud's (Liga: football, FPA: handball). */
export async function eventSport(db: Db, eventId: string): Promise<string | null> {
const rows = await db.$queryRaw<{ sport: string | null }[]>`
+17 -21
View File
@@ -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<string, { confirmed: Set<string>; likely: Set<string> }>();
for (const r of rows) {
const entry = photosOf.get(r.person_id) ?? { confirmed: new Set<string>(), likely: new Set<string>() };
(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 };
+18
View File
@@ -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: [] });
});
});
+39
View File
@@ -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<string, SquadPhotoTally> {
const buckets = new Map<string, { confirmed: Set<string>; likely: Set<string> }>();
for (const row of rows) {
if (!row.person_id || !row.photo_id) continue;
const bucket = buckets.get(row.person_id) ?? { confirmed: new Set<string>(), likely: new Set<string>() };
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<string, SquadPhotoTally>();
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<string, SquadPhotoTally>, personId: string | null): SquadPhotoTally {
if (!personId) return { confirmed: 0, likely: 0, photoIds: [] };
return index.get(personId) ?? { confirmed: 0, likely: 0, photoIds: [] };
}
+17
View File
@@ -169,6 +169,22 @@ describe("archive folder names", () => {
expect(isTeam("ABC", { name: "ABC de Braga / Uminho", abbreviation: null, slug: "abc-braga" })).toBe(true);
expect(isTeam("SLB", { name: "Sport Lisboa e Benfica", abbreviation: null, slug: "benfica" })).toBe(true);
expect(isTeam("SLB", { name: "Sporting Clube de Portugal", abbreviation: null, slug: "sporting" })).toBe(false);
// The program writes the federation code. "AAAS" is not the initials of the sponsor name.
const aguas = { name: "Águas Santas Milaneza", abbreviation: null, slug: "aguas-santas-milaneza" };
const sporting = { name: "Sporting CP", abbreviation: null, slug: "sporting-cp" };
expect(isTeam("AAAS", aguas)).toBe(true);
expect(isTeam("SCP", sporting)).toBe(true);
expect(isTeam("AAAS", { name: "AA Águas Santas 'B'", abbreviation: null, slug: "aa-aguas-santas-b" })).toBe(false);
const today: FixtureCandidate = {
id: "hoje",
startsAt: new Date("2026-10-18T13:00:00Z"),
season: "20262027",
round: null,
competition: { externalId: "PO01" },
homeTeam: aguas,
awayTeam: sporting,
};
expect(pickFixture(parseFolder("/FPA/Fotos/2026_2027/Competições Nacionais/PO01 - Campeonato Betclic/20261018 - AAAS x SCP")!, [today])?.id).toBe("hoje");
});
it("takes a game only when both sides are recognised, never with one guessed", () => {
@@ -686,6 +702,7 @@ describe("archive from a Nextcloud", () => {
expect(res.json().total).toBe(2);
expect(res.json().photos[0].faces).toBeUndefined();
expect(res.json().people).toEqual([expect.objectContaining({ name: "Martim Costa", count: 2 })]);
expect(res.json().roster).toEqual([expect.objectContaining({ name: "Martim Costa", here: 2, inGame: 2 })]);
res = await get(owner, `/v1/archive/photos/${p2.id}`);
expect((res.json().faces as { person: { name: string } | null }[]).map((f) => f.person?.name ?? null).sort()).toEqual(["Martim Costa", null].sort());
+50
View File
@@ -404,6 +404,56 @@ describe("delivery", () => {
expect(copied["IPTC:ObjectName"]).toBe("Rui Costa (AAAS), Miguel Silva (VSC)");
});
it("saves the same export into a computer folder named by the day, the game and the destination", async () => {
const { orgId, token, target } = await setup();
const saved = await ctx.app.inject({
method: "PATCH",
url: `/v1/orgs/${orgId}/delivery-targets/${target.id}`,
headers: bearer(token),
payload: { localFolder: "/Users/cyclop/Desktop/2026", localMachine: "desktop-0000000000000001", localFolderTemplate: "/{iptcdate} - {event} - {destination}/" },
});
expect(saved.statusCode).toBe(200);
expect(saved.json()).toMatchObject({ baseUrl: "https://cloud.test", localFolder: "/Users/cyclop/Desktop/2026", localFolderTemplate: "/{iptcdate} - {event} - {destination}/" });
const listed = (await ctx.app.inject({ method: "GET", url: `/v1/orgs/${orgId}/delivery-targets`, headers: bearer(token) })).json() as { targets: { name: string }[] };
expect(listed.targets.map((t) => t.name)).toEqual(["FPA"]);
const id = await photo("a.jpg", "2026:09:23 21:10:00");
await ctx.app.inject({ method: "POST", url: `/v1/orgs/${orgId}/deliveries`, headers: bearer(token), payload: { targetId: target.id, photoIds: [id] } });
await drain();
const sentPath = [...nc.files.keys()][0]!;
expect(sentPath.endsWith("/PS_VSC x AAAS_1.jpg")).toBe(true);
const copy = await ctx.db.deliveryItem.findFirstOrThrow({ where: { viaTargetId: target.id } });
expect([copy.status, copy.sequence, copy.remotePath]).toEqual(["WAITING", 1, "20260923 - VSC x AAAS - FPA/PS_VSC x AAAS_1.jpg"]);
const mirror = await ctx.db.deliveryTarget.findFirstOrThrow({ where: { mirrorOfId: target.id } });
expect(mirror).toMatchObject({ kind: "LOCAL", baseUrl: "/Users/cyclop/Desktop/2026", username: "desktop-0000000000000001", disabledAt: null });
const cleared = await ctx.app.inject({
method: "PATCH",
url: `/v1/orgs/${orgId}/delivery-targets/${target.id}`,
headers: bearer(token),
payload: { localFolder: null },
});
expect(cleared.statusCode).toBe(200);
expect((cleared.json() as { localFolder: null }).localFolder).toBeNull();
expect((await ctx.db.deliveryTarget.findFirstOrThrow({ where: { id: mirror.id } })).disabledAt).not.toBeNull();
const later = await photo("b.jpg", "2026:09:23 21:20:00");
await ctx.app.inject({ method: "POST", url: `/v1/orgs/${orgId}/deliveries`, headers: bearer(token), payload: { targetId: target.id, photoIds: [later] } });
await drain();
expect(await ctx.db.deliveryItem.count({ where: { viaTargetId: target.id } })).toBe(1);
// A destination that is already a folder does not grow a second copy of itself.
const localOnly = await ctx.app.inject({
method: "POST",
url: `/v1/orgs/${orgId}/delivery-targets`,
headers: bearer(token),
payload: { name: "Pasta", kind: "LOCAL", baseUrl: "/Users/cyclop/Desktop/2026", username: "desktop-0000000000000001", folderTemplate: "/{event}/", fileNameTemplate: "{originalName}", localFolder: "/tmp/outra", localMachine: "desktop-0000000000000001" },
});
expect(localOnly.statusCode).toBe(201);
expect((localOnly.json() as { localFolder: null }).localFolder).toBeNull();
});
it("waits a little for the faces to be read before sending, so the names go with the photo", async () => {
const { orgId, token, target } = await setup();
await ctx.db.organization.update({ where: { id: orgId }, data: { biometricsEnabled: true, biometricsLegalBasis: "test" } });
+6 -4
View File
@@ -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 () => {
+1
View File
@@ -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",
+62
View File
@@ -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<PlayerPick[]>([]);
const ids = useMemo(() => picks.map((p) => p.id), [picks]);
return (
<>
<SquadsButton
api={{ eventSquads: vi.fn().mockResolvedValue(squads) } as unknown as ApiClient}
event={{ id: "e1", homeTeamId: "t1", awayTeamId: "t2" } as EventSummary}
canEdit={false}
onSaved={() => {}}
selectedIds={ids}
onPlayers={(next) => setPicks((cur) => (samePicks(cur, next) ? cur : next))}
/>
<p data-testid="picked">{picks.map((p) => p.photoIds.join("+")).join("|")}</p>
</>
);
}
describe("squad panel", () => {
it("filters to each player that is clicked, and drops one on a second click", async () => {
render(<Harness />);
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");
});
});
+57 -22
View File
@@ -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<EventSquads | null>(null);
const [status, setStatus] = useState<string | null>(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;
<div key={s.side}>
<p className="mb-1 font-semibold text-ink">{s.team.name}</p>
<ul className="max-h-72 overflow-y-auto">
{s.players.map((p) => (
<li key={p.id} className="flex gap-2">
<span className="w-7 shrink-0 text-right font-mono text-accent">{p.number ?? "–"}</span>
<span className="truncate text-ink">{p.name}</span>
<span className="ml-auto shrink-0 font-mono text-[11px]" title={p.personId ? t.sports.photosHelp(p.photos?.confirmed ?? 0, p.photos?.likely ?? 0) : t.sports.notPerson}>
{!p.personId ? (
<span className="text-faint">·</span>
) : p.photos && p.photos.confirmed + p.photos.likely > 0 ? (
<>
{p.photos.confirmed > 0 && <span className="text-ink">{p.photos.confirmed}</span>}
{p.photos.likely > 0 && <span className="text-faint">{p.photos.confirmed > 0 ? " " : ""}+{p.photos.likely}</span>}
</>
) : (
<span className="text-faint">0</span>
)}
</span>
</li>
))}
{s.players.map((p) => {
const on = selectedIds.includes(p.id);
return (
<li key={p.id}>
<button
type="button"
disabled={!p.personId}
aria-pressed={on}
title={p.personId ? t.sports.photosHelp(p.photos?.confirmed ?? 0, p.photos?.likely ?? 0) : t.sports.notPerson}
onClick={() => toggle(p.id)}
className={`flex w-full gap-2 px-1 py-0.5 text-left ${on ? "bg-cell-on" : "hover:bg-cell"} disabled:cursor-default disabled:hover:bg-transparent`}
>
<span className="w-7 shrink-0 text-right font-mono text-accent">{p.number ?? "–"}</span>
<span className="truncate text-ink">{p.name}</span>
<span className="ml-auto shrink-0 font-mono text-[11px]">
{!p.personId ? (
<span className="text-faint">·</span>
) : p.photos && p.photos.confirmed + p.photos.likely > 0 ? (
<>
{p.photos.confirmed > 0 && <span className="text-ink">{p.photos.confirmed}</span>}
{p.photos.likely > 0 && <span className="text-faint">{p.photos.confirmed > 0 ? " " : ""}+{p.photos.likely}</span>}
</>
) : (
<span className="text-faint">0</span>
)}
</span>
</button>
</li>
);
})}
</ul>
</div>
))}
+79 -3
View File
@@ -1,4 +1,4 @@
import { DESTINATION_EXAMPLES, IPTC_FIELDS } from "@photoreport/metadata";
import { DESTINATION_EXAMPLES, IPTC_FIELDS, LOCAL_COPY_FOLDER } from "@photoreport/metadata";
import {
ApiError,
type ApiClient,
@@ -180,6 +180,9 @@ export function TargetForm({
arrivalLogins: target?.arrivalLogins ?? ([] as string[]),
untouched: target?.untouched ?? false,
copyTargetId: target?.copyTargetId ?? null,
localFolder: target?.localFolder ?? null,
localMachine: target?.localMachine ?? null,
localFolderTemplate: target?.localFolderTemplate || LOCAL_COPY_FOLDER,
});
// The other destinations a copy can go to (a folder on this computer, usually).
const [others, setOthers] = useState<DeliveryTarget[]>([]);
@@ -239,8 +242,12 @@ export function TargetForm({
const { password: _pw, ...base } = v;
const iptcOverrides = overridesOf(overrides);
const password = v.password;
const rest = { ...base, iptcOverrides };
const all = { ...v, iptcOverrides };
const local =
v.kind === "LOCAL" || !v.localFolder
? { localFolder: null, localMachine: null, localFolderTemplate: null }
: { localFolder: v.localFolder, localMachine: v.localMachine, localFolderTemplate: v.localFolderTemplate || LOCAL_COPY_FOLDER };
const rest = { ...base, ...local, iptcOverrides };
const all = { ...v, ...local, iptcOverrides };
if (v.kind === "LOCAL" && !v.baseUrl) {
setBusy(false);
setError("Escolhe a pasta.");
@@ -513,6 +520,75 @@ export function TargetForm({
</fieldset>
)}
</div>
{v.kind !== "LOCAL" && (
<fieldset className="space-y-2 border border-line p-3 text-[12px]">
<legend className="px-1 text-[11px] text-faint">Cópia neste computador</legend>
<p className="text-faint">
O envio (FTP, cloud, …) fica como está. Cada ficheiro enviado é gravado também numa pasta, para se ver
depois o que foi para onde. A app de computador tem de estar aberta nessa máquina.
</p>
<label className="flex items-start gap-2">
<input
type="checkbox"
className="mt-0.5"
checked={!!v.localFolder}
onChange={(e) => {
if (!e.target.checked) {
setV({ ...v, localFolder: null, localMachine: null });
return;
}
if (!isDesktop()) {
setError("A pasta escolhe-se na app de computador.");
return;
}
void Promise.all([desktopDeliveryShell.pick(), desktopDeliveryShell.machine()]).then(
([folder, machine]) => {
if (folder) setV((cur) => ({ ...cur, localFolder: folder, localMachine: machine }));
},
() => setError("Esta versão da app ainda não sabe guardar em pastas: atualiza a app."),
);
}}
/>
<span className="text-ink">Gravar também uma cópia na pasta</span>
</label>
{v.localFolder && (
<>
<div className="flex gap-2">
<span className={`${input} flex items-center truncate font-mono text-[12px]`}>{v.localFolder}</span>
{isDesktop() && (
<button
type="button"
className="h-8 shrink-0 border border-black bg-cell px-3 text-[12px] hover:bg-cell-on"
onClick={() =>
void Promise.all([desktopDeliveryShell.pick(), desktopDeliveryShell.machine()]).then(
([folder, machine]) => {
if (folder) setV((cur) => ({ ...cur, localFolder: folder, localMachine: machine }));
},
() => setError("Esta versão da app ainda não sabe guardar em pastas: atualiza a app."),
)
}
>
Escolher pasta…
</button>
)}
</div>
<label className="block">
<span className="mb-1 block text-[11px] text-faint">
Subpasta ({"{iptcdate}"} = dia da foto, {"{event}"} = jogo, {"{destination}"} = nome deste destino)
</span>
<input
className={`${input} font-mono text-[12px]`}
value={v.localFolderTemplate}
onChange={(e) => setV({ ...v, localFolderTemplate: e.target.value })}
/>
</label>
<p className="font-mono text-[11px] leading-snug text-faint">
{v.localFolder.replace(/\/$/, "")}/20261018 - Águas Santas Milaneza x Sporting CP - {v.name || "Record"}/
</p>
</>
)}
</fieldset>
)}
{others.length > 0 && (
<label className="block">
<span className="mb-1 block text-[11px] text-faint">
+33
View File
@@ -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();
});
});
+40
View File
@@ -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<string> | null {
if (!picks.length) return null;
const ids = new Set<string>();
for (const pick of picks) for (const id of pick.photoIds) ids.add(id);
return ids;
}
+9
View File
@@ -156,6 +156,15 @@ export function DeliveryPage() {
<dd className="font-mono text-[11px]">
{target.longEdge >= 12000 ? "original" : `${target.longEdge} px`} · JPEG {target.jpegQuality}
</dd>
{target.localFolder && (
<>
<dt className="text-faint">Cópia no computador</dt>
<dd className="break-all font-mono text-[11px]">
{target.localFolder}
{target.localFolderTemplate ? ` · ${target.localFolderTemplate}` : ""}
</dd>
</>
)}
<dt className="text-faint">Ligação</dt>
<dd className="break-all font-mono text-[11px]">
{target.kind} · {target.kind === "DROPBOX" ? "Dropbox" : target.baseUrl}
+30 -2
View File
@@ -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<LibraryFilter>(() => savedFilter(orgId));
const [players, setPlayers] = useState<PlayerPick[]>([]);
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() {
<div className="flex min-h-[70vh] min-w-0 flex-1 flex-col lg:min-h-0">
<div className="flex flex-wrap items-center gap-x-4 gap-y-1 border-b border-line bg-raised px-3 py-1.5 text-[12px]">
<FilterBar filter={filter} onChange={setFilter} />
{players.length > 0 && (
<span className="flex min-w-0 items-center gap-2">
<span className="max-w-72 truncate text-ink" title={players.map((p) => p.name).join(", ")}>
{players.map((p) => p.name).join(", ")}
</span>
<button type="button" onClick={() => setPlayers([])} className="text-accent hover:underline">
{t.clearPlayers}
</button>
</span>
)}
{canCull && state.scope && state.scope !== "inbox" && !state.scope.startsWith("search:") && !state.scope.startsWith("face:") && (
<button
onClick={() => setView(view === "faces" ? "grid" : "faces")}
@@ -411,7 +439,7 @@ export function LibraryPage() {
/>
)}
{canCull && openEvent && (
<SquadsButton api={api} event={openEvent} canEdit={canCreate} onSaved={(e) => setEvents((list) => list.map((x) => (x.id === e.id ? e : x)))} />
<SquadsButton api={api} event={openEvent} canEdit={canCreate} facesTick={facesTick} selectedIds={selectedPlayerIds} onPlayers={onPlayers} onSaved={(e) => setEvents((list) => list.map((x) => (x.id === e.id ? e : x)))} />
)}
{canCull && openEvent && (
<AutopilotButton api={api} event={openEvent} targets={targets} canEdit={canCreate} onSaved={(e) => setEvents((list) => list.map((x) => (x.id === e.id ? e : x)))} />
+38 -1
View File
@@ -68,6 +68,16 @@ interface GalleryPerson {
face: { src: string; box: Box | null; aspect: number } | null;
}
/** Someone named in the game, including parts of it other than the folder on screen. */
interface GamePerson {
id: string;
name: string;
club: string | null;
number: string | null;
here: number;
inGame: number;
}
interface GalleryDetail {
id: string;
title: string;
@@ -77,6 +87,8 @@ interface GalleryDetail {
cloudUrl: string;
total?: number;
people?: GalleryPerson[];
/** People named anywhere in this game. */
roster?: GamePerson[];
photos: ArchivePhoto[];
}
@@ -853,8 +865,9 @@ function Gallery({
const applyPage = useCallback((offset: number, body: GalleryDetail) => {
setG((cur) => {
const people = body.people ?? cur?.people;
const roster = body.roster ?? cur?.roster;
const photos = offset === 0 ? body.photos : [...(cur?.photos ?? []), ...body.photos];
return { ...body, people, photos, total: body.total ?? photos.length };
return { ...body, people, roster, photos, total: body.total ?? photos.length };
});
}, []);
useEffect(() => {
@@ -877,6 +890,8 @@ function Gallery({
}, [fetchPage, applyPage, only, onExpired, attempt]);
const people = g?.people ?? [];
const roster = g?.roster ?? [];
const picked = roster.find((p) => p.id === only) ?? null;
const photos = g?.photos ?? [];
const total = g?.total ?? photos.length;
const rememberFaces = useCallback((photoId: string, faces: PhotoFace[]) => {
@@ -917,6 +932,27 @@ function Gallery({
{g.title}
{g.section ? <span className="meta"> · {g.section}</span> : null}
</h2>
{roster.length > 0 && (
<label className="game-person">
<span>Pessoas do jogo</span>
<select value={only ?? ""} onChange={(e) => setOnly(e.target.value || null)} aria-label="Pessoas do jogo">
<option value="">Todas</option>
{roster.map((p) => (
<option key={p.id} value={p.id}>
{p.name}
{p.number ? ` · ${p.number}` : ""}
{p.club ? ` · ${p.club}` : ""}
{p.here > 0 ? ` (${p.here} nesta parte)` : " (noutra parte do jogo)"}
</option>
))}
</select>
{picked && (
<button type="button" className="linkish" onClick={() => onPerson(picked.id)}>
Ver todas as fotos de {picked.name}
</button>
)}
</label>
)}
{people.length > 0 && (
<ul className="gallery-people">
{people.map((p) => (
@@ -936,6 +972,7 @@ function Gallery({
))}
</ul>
)}
{picked && photos.length === 0 && <p className="empty">Sem fotos de {picked.name} nesta parte do jogo.</p>}
<div className="grid">
{photos.map((p, i) => (
<button key={p.id} type="button" className="tile" onClick={() => setIndex(i)} aria-label={p.players.join(", ") || p.name}>
+17
View File
@@ -879,6 +879,23 @@ button.chip {
align-items: center;
padding: 8px 0 16px;
}
.game-person {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 10px;
padding: 8px 0 4px;
}
.game-person span {
font-size: 12px;
letter-spacing: 0.04em;
text-transform: uppercase;
color: var(--muted, #666);
}
.game-person select {
min-width: min(100%, 280px);
max-width: 100%;
}
.gallery-people {
list-style: none;
margin: 0;
+5
View File
@@ -337,6 +337,11 @@ The same queue also delivers to SFTP, FTP/FTPS and Dropbox (`delivery/transports
with the templates' subfolders and name. It only writes inside folders chosen there with the system's folder
picker (`src-tauri/src/deliver.rs`), never a path a page passes. For testing a destination's rules, or keeping
the finished files to choose from later.
- **A local copy of any other export** (`local_folder`, not on a LOCAL target): the FTP, SFTP, Nextcloud, Dropbox
or ZeroZero send is unchanged. With the option on, the same file (that destination's size, name and IPTC) is also
saved by the desktop app under the chosen folder, in `{iptcdate} - {event} - {destination}`
(`/Users/cyclop/Desktop/2026/20261018 - Águas Santas Milaneza x Sporting CP - Record/`). The subfolder template is
editable; `{destination}` is the destination's name. A hidden LOCAL target holds the copies and is not listed.
- **Originals** (`delivery_targets.originals`, any kind): the original as it arrived, byte for byte in its image
(no resizing, no recompression, the camera's EXIF and profile kept), with the IPTC written by exiftool and the
name from the templates, like Photo Mechanic's Live Ingest destination (`{iptcdate} - {event}`,
+2 -1
View File
@@ -132,7 +132,8 @@ or a share of its root or a folder above it, sees all of it.
A gallery, a person and a face each have a URL (`/arquivo/<source>/g/<folder>`, `/p/<person>`, `/f/<face>`), so a
link survives refresh. A gallery page is 48 thumbs; the faces of a photo load when that photo is opened. The row
of people in a gallery is one query on that folder. People, similar faces and the player directory join
of faces is the people named in that folder. "Pessoas do jogo" lists everyone named in the game (every part
the viewer may see); choosing one shows their photos in this part, or all of their photos. People, similar faces and the player directory join
`cloud_files` for the source (and the viewer's folders when they do not see everything) instead of loading every
photo id. Originals still open on the cloud itself (`/f/<fileid>`).
+6
View File
@@ -65,6 +65,12 @@ export function renderFileName(template: string, vars: TemplateVars, originalFil
return /\.[a-z0-9]{2,4}$/i.test(name) ? name : name + (ext === ".jpeg" ? ".jpg" : ext);
}
/**
* Subfolders for the local copy of an export: the capture day, the game, and the destination's name
* (`20261018 - Águas Santas Milaneza x Sporting CP - Record`). `{destination}` is filled only for that copy.
*/
export const LOCAL_COPY_FOLDER = "/{iptcdate} - {event} - {destination}/";
/** Example destination rules taken from today's deliveries. */
export const DESTINATION_EXAMPLES = {
fpa: {
+13
View File
@@ -197,6 +197,8 @@ export interface EventSquads {
personId: string | null;
/** Photos of them in this event: confirmed, and taken for them by the faces (70% or more) not confirmed yet. */
photos?: { confirmed: number; likely: number };
/** Those photos, confirmed first. The library filter uses this when the player is picked. */
photoIds?: string[];
}[];
}[];
}
@@ -253,6 +255,12 @@ export interface DeliveryTarget {
iptcOverrides?: Record<string, string | string[]> | null;
/** Everything sent here also goes to this target (a folder on a computer), with this target's IPTC. */
copyTargetId?: string | null;
/** Also save each exported file under this folder on one computer. Null: the export only. */
localFolder?: string | null;
/** That computer's id. */
localMachine?: string | null;
/** Subfolders under `localFolder`. `{destination}` is this target's name. */
localFolderTemplate?: string | null;
username: string;
folderTemplate: string;
fileNameTemplate: string;
@@ -319,6 +327,11 @@ export interface DeliveryTargetInput {
/** IPTC fields this client gets instead of the event's; null: none. */
iptcOverrides?: Record<string, string | string[]> | null;
copyTargetId?: string | null;
/** Also save each exported file under this folder on one computer. Null: the export only. */
localFolder?: string | null;
localMachine?: string | null;
/** Subfolders under the folder. `{destination}` is this target's name. */
localFolderTemplate?: string | null;
}
export interface PersonSummary {