Compare commits

..
Author SHA1 Message Date
spark 4474dd74e1 feat(library): split the toolbar into filters and quiet tools
ci / typescript (pull_request) Failing after 2m42s
ci / rust (pull_request) Successful in 10m59s
The library kept every action in one wrapping row of equal buttons. Filters stay on the first row; sources and event tools are text on the second; gallery, move and remove sit on the selection bar.
2026-11-06 22:17:05 +00:00
58 changed files with 105 additions and 1548 deletions

No files matched your search

+2 -2
View File
@@ -110,7 +110,7 @@ export async function buildApp({ config, db, realtime, fetchImpl, reporter: give
: (realtime ?? silentBroadcaster);
app.addHook("onClose", async () => broadcaster.close());
const secrets = config.DELIVERY_SECRET_KEY ? new SecretBox(config.DELIVERY_SECRET_KEY) : undefined;
const sports = new SportsService({ db, storage, signer, log: app.log, fetch: fetchImpl ?? fetch });
const sports = new SportsService({ db, storage, log: app.log, fetch: fetchImpl ?? fetch });
// Archive clouds: the API connects them, matches galleries and streams originals; the worker walks and indexes.
const archive = new ArchiveService({ db, secrets, log: app.log, syncSquads: (id) => sports.syncEventSquads(id), ligaSeason: (season) => sports.importLigaSeason(season), storageRoot: config.STORAGE_ROOT, minFreeBytes: config.ARCHIVE_MIN_FREE_GB * 1e9, storage, ...(fetchImpl && { fetchImpl }) });
const delivery = new DeliveryService({ db, storage, secrets, broadcaster, log: app.log, originals: archive, ...(fetchImpl && { fetchImpl }) });
@@ -136,7 +136,7 @@ export async function buildApp({ config, db, realtime, fetchImpl, reporter: give
});
await registerAuthRoutes(app, { db, config, sessions });
await registerMeRoutes(app, { db, sessions, broadcaster });
await registerMeRoutes(app, { db, sessions });
await registerCalendarRoutes(app, { sessions, calendar: new CalendarService({ db, secrets, ...(fetchImpl && { fetchImpl }) }) });
await registerOrgRoutes(app, { db, sessions });
await registerEventRoutes(app, { db, sessions, sports, broadcaster });
+2 -12
View File
@@ -3,17 +3,7 @@ import { PrismaClient } from "./generated/prisma/client.js";
export type Db = PrismaClient;
/**
* `connections`: the pool's size (node-postgres keeps 10 by default); the worker sizes it to what it runs at once.
*
* `transactionOptions` raises Prisma's default `maxWait` (2000ms) for any call that doesn't set its own —
* including the implicit transaction Prisma opens around a single `upsert()` — so brief pool contention
* doesn't surface as "Unable to start a transaction in the given time". Call sites with their own long-running
* `$transaction(fn, { maxWait, timeout })` options (e.g. `rebuildDirectory`, `assignGalleries`) override this.
*/
/** `connections`: the pool's size (node-postgres keeps 10 by default); the worker sizes it to what it runs at once. */
export function createDb(databaseUrl: string, connections?: number): Db {
return new PrismaClient({
adapter: new PrismaPg({ connectionString: databaseUrl, ...(connections && { max: connections }) }),
transactionOptions: { maxWait: 10_000, timeout: 10_000 },
});
return new PrismaClient({ adapter: new PrismaPg({ connectionString: databaseUrl, ...(connections && { max: connections }) }) });
}
+1 -1
View File
@@ -621,7 +621,7 @@ export class FaceService {
const onTeam = team ? await this.playersOfTeam([first.p], team.teamId) : null;
if (team && onTeam?.has(first.p.id)) suggestionScore = faceNumberKitScore(first.s, read.score, team.sure);
else suggestionScore = faceAndNumberScore(first.s, read.score);
} else if (read && firstNumber && firstNumber !== read.number) {
} else if (read && firstNumber && firstNumber !== read.number && read.votes >= 2) {
suggestionScore = Math.round(first.s * 0.8 * 1000) / 1000;
}
} else if (read && allowNumber) {
+2 -11
View File
@@ -1,11 +1,10 @@
import { DeskCommand, MODULES } from "@photoreport/contracts";
import { MODULES } from "@photoreport/contracts";
import type { FastifyInstance } from "fastify";
import { z } from "zod";
import { currentUserId, requireAuth } from "../auth/guard.js";
import type { SessionService } from "../auth/sessions.js";
import type { Db } from "../db.js";
import { notFound } from "../lib/errors.js";
import { silentBroadcaster, type Broadcaster } from "../realtime.js";
const PreferencesBody = z.object({
editorModules: z
@@ -14,9 +13,8 @@ const PreferencesBody = z.object({
.transform((mods) => [...new Set(mods)]),
});
export async function registerMeRoutes(app: FastifyInstance, deps: { db: Db; sessions: SessionService; broadcaster?: Broadcaster }) {
export async function registerMeRoutes(app: FastifyInstance, deps: { db: Db; sessions: SessionService }) {
const { db } = deps;
const broadcaster = deps.broadcaster ?? silentBroadcaster;
const authenticate = requireAuth(deps.sessions);
app.get("/v1/me", { preHandler: authenticate }, async (req) => {
@@ -54,11 +52,4 @@ export async function registerMeRoutes(app: FastifyInstance, deps: { db: Db; ses
});
return { editorModules: prefs.editorModules };
});
/** The assistant asks the open PhotoReport of this person to change module, photo or tool. */
app.post("/v1/me/desk", { preHandler: authenticate }, async (req) => {
const command = DeskCommand.parse(req.body);
broadcaster.desk(currentUserId(req), command);
return { ok: true as const };
});
}
+3 -37
View File
@@ -1,4 +1,4 @@
import { LIBRARY_CHANNEL, type DeskCommand, type LibraryMessage, roomForOrg, roomForUser } from "@photoreport/contracts";
import { LIBRARY_CHANNEL, type LibraryMessage, roomForOrg, roomForUser } from "@photoreport/contracts";
import type { Server as HttpServer } from "node:http";
import pg from "pg";
import { Server } from "socket.io";
@@ -8,23 +8,17 @@ import type { Db } from "./db.js";
/** Anything that can push library messages to the people of an organization. */
export interface Broadcaster {
library(organizationId: string, message: LibraryMessage): void;
/** The open PhotoReport of this user: change module, photo or tool. */
desk(userId: string, command: DeskCommand): void;
close(): Promise<void>;
}
export const silentBroadcaster: Broadcaster = { library: () => {}, desk: () => {}, close: async () => {} };
export const silentBroadcaster: Broadcaster = { library: () => {}, close: async () => {} };
/** Records messages; used by tests. */
export class MemoryBroadcaster implements Broadcaster {
readonly sent: { organizationId: string; message: LibraryMessage }[] = [];
readonly deskSent: { userId: string; command: DeskCommand }[] = [];
library(organizationId: string, message: LibraryMessage): void {
this.sent.push({ organizationId, message });
}
desk(userId: string, command: DeskCommand): void {
this.deskSent.push({ userId, command });
}
async close(): Promise<void> {}
}
@@ -33,8 +27,6 @@ export class MemoryBroadcaster implements Broadcaster {
* delivers to its own sockets, the ingest worker only publishes. No Redis, no sticky sessions.
*/
const PG_CHANNEL = "photoreport_realtime";
/** Window instructions, delivered to one person's sockets (not the whole organization). */
const DESK_CHANNEL = "photoreport_desk";
/** NOTIFY payloads are limited to 8000 bytes; batch updates are split so each message fits. */
const IDS_PER_MESSAGE = 100;
@@ -121,14 +113,8 @@ export function attachRealtime(
if (closed) return;
const client = new pg.Client({ connectionString: deps.databaseUrl });
client.on("notification", (n) => {
if (!n.payload) return;
if (n.channel !== PG_CHANNEL || !n.payload) return;
try {
if (n.channel === DESK_CHANNEL) {
const { userId, command } = JSON.parse(n.payload) as { userId: string; command: DeskCommand };
io.to(roomForUser(userId)).emit("desk", command);
return;
}
if (n.channel !== PG_CHANNEL) return;
const { organizationId, message } = JSON.parse(n.payload) as Envelope;
io.to(roomForOrg(organizationId)).emit(LIBRARY_CHANNEL, message);
} catch (err) {
@@ -146,7 +132,6 @@ export function attachRealtime(
return;
}
await client.query(`LISTEN ${PG_CHANNEL}`);
await client.query(`LISTEN ${DESK_CHANNEL}`);
listener = client;
};
const ready = listen().catch((err) => {
@@ -154,18 +139,8 @@ export function attachRealtime(
if (!closed) retry = setTimeout(() => void listen().catch(onError), 1000);
});
const desk = (userId: string, command: DeskCommand) => {
if (closed) return;
const q = pool.query("SELECT pg_notify($1, $2)", [DESK_CHANNEL, JSON.stringify({ userId, command })]).catch((err) => {
if (closed && isPoolEndedError(err)) return;
onError(err);
});
trackPending(pending)(q);
};
return {
library: publisher(pool, onError, () => closed, trackPending(pending)),
desk,
close: async () => {
if (closed) return;
closed = true;
@@ -184,17 +159,8 @@ export function createRemoteBroadcaster(databaseUrl: string, onError: (err: unkn
const pool = new pg.Pool({ connectionString: databaseUrl, max: 1 });
let closed = false;
const pending = new Set<Promise<unknown>>();
const desk = (userId: string, command: DeskCommand) => {
if (closed) return;
const q = pool.query("SELECT pg_notify($1, $2)", [DESK_CHANNEL, JSON.stringify({ userId, command })]).catch((err) => {
if (closed && isPoolEndedError(err)) return;
onError(err);
});
trackPending(pending)(q);
};
return {
library: publisher(pool, onError, () => closed, trackPending(pending)),
desk,
close: async () => {
if (closed) return;
closed = true;
+7 -11
View File
@@ -8,7 +8,7 @@ import type { IngestLogger } from "../ingest/service.js";
import { DEFAULT_CODE_LIST } from "../library/iptc.js";
import { badRequest, notFound } from "../lib/errors.js";
import { waitUntil } from "../lib/idle.js";
import type { LocalStorage, UrlSigner } from "../storage/storage.js";
import type { LocalStorage } from "../storage/storage.js";
import { type CodeClash, type SquadForCodes, buildCodeLines, hasGeneratedBlock, mergeGenerated, slugify, toTsv } from "./codegen.js";
import { fetchYouthCamps, youthAbbrev } from "./fpa-youth.js";
import { samePlayer } from "./identity.js";
@@ -98,7 +98,6 @@ const SPORT: Record<SportsProvider, string> = { LIGA: "futebol", FPF: "futebol",
export interface SportsDeps {
db: Db;
storage: LocalStorage;
signer: UrlSigner;
log: IngestLogger;
fetch: Fetch;
/** Pause between FPF pages (be gentle with the site). */
@@ -559,7 +558,7 @@ export class SportsService {
result.players += await this.saveNationalCallUp(snamId, season, SNAM_EURO_CUP_2026);
result.players += await this.saveNationalCallUp(suiId, season, SUI_EURO_CUP_2026);
// The calendar first. Reading the call-up PDFs takes minutes and must not hide tonight's game.
result.fixtures += await this.saveM19Friendlies(season, now);
result.fixtures += await this.saveM19Friendlies(season);
// The federation's recent youth posts (PDF + calendar). The November M19 list below is only the
// first seed, so a later camp is not put back to this one when the site is briefly down.
const youth = await this.importFpaYouth(season, result);
@@ -577,12 +576,12 @@ export class SportsService {
}
/** The two Portugal–Spain under-19 friendlies (Caminha 5 Nov, Salceda 7 Nov 2026). Picking the fixture links the plantel. */
private async saveM19Friendlies(season: string, now: Date): Promise<number> {
private async saveM19Friendlies(season: string): Promise<number> {
const { db } = this.deps;
const comp = await db.sportsCompetition.upsert({
where: { provider_externalId: { provider: "FPA", externalId: "M19-AMIG" } },
create: { provider: "FPA", externalId: "M19-AMIG", sport: "andebol", name: "Sub-19 masculina", gender: "M", season, lastIngestAt: now },
update: { name: "Sub-19 masculina", season, lastIngestAt: now },
create: { provider: "FPA", externalId: "M19-AMIG", sport: "andebol", name: "Sub-19 masculina", gender: "M", season },
update: { name: "Sub-19 masculina", season },
});
const por = NATIONAL_SIDES.find((s) => s.externalId === "M19");
const esp = NATIONAL_SIDES.find((s) => s.externalId === "ESP-M19");
@@ -1458,10 +1457,7 @@ export class SportsService {
try {
await this.savePlayers(team.id, season, await this.liga.squad(team.externalId, season), "api");
} catch (err) {
// Same not-yet-published 400 as importLigaSquads/backfillLigaRegister: expected, kept out of the error hub.
if (err instanceof ProviderHttpError && err.status === 400)
log.info({ err, team: team.id }, "sports: liga squad not published yet for this team");
else log.warn({ err, team: team.id }, "sports: liga squad re-read failed");
log.warn({ err, team: team.id }, "sports: liga squad re-read failed");
}
}
for (const team of [event.homeTeam, event.awayTeam]) {
@@ -1784,7 +1780,7 @@ export class SportsService {
where: { id: { in: ids }, referenceKey: { not: null } },
select: { id: true },
});
for (const person of people) out.set(person.id, this.deps.signer.personUrl(person.id));
for (const person of people) out.set(person.id, this.deps.storage.personUrl(person.id));
return out;
}
+1 -1
View File
@@ -103,7 +103,7 @@ if (!renderEngine) log.warn("RENDER_BIN not set: edited photos get no new thumbn
const develop = new DevelopService({ db, storage, signer, broadcaster, log, engine: renderEngine });
const renders = renderEngine ? new RenderWorker(develop, { concurrency: capacity.render, intervalMs: 500, log }) : undefined;
const sportsService = new SportsService({ db, storage, signer, log, fetch });
const sportsService = new SportsService({ db, storage, log, fetch });
// Archive clouds: walked for new galleries, each image indexed as a preview whose original stays in the cloud.
// A big backlog: many downloads from the cloud in flight, previews made by as many as the machine's share.
const videoTools = findVideoTools({ ffmpeg: config.FFMPEG_BIN, ffprobe: config.FFPROBE_BIN }, homedir());
+6 -8
View File
@@ -135,9 +135,8 @@ describe("learning from corrections", () => {
expect(c?.deltas["light.exposure"]).toBe(0.35);
expect(c?.deltas["light.shadows"]).toBe(12);
expect(c?.deltas["wb.temp"]).toBe(300);
// Scale is linear (cropBias.ts): the crop only narrows in x here, so it is the geometric mean of the two axes.
expect(c?.cropScale).toBeCloseTo(0.866, 2);
expect(c?.cropBias?.scale).toBeCloseTo(0.866, 2);
expect(c?.cropScale).toBeCloseTo(0.75, 2);
expect(c?.cropBias?.scale).toBeCloseTo(0.75, 2);
// A reset is "less of everything the autopilot did" for tone; white balance says nothing then.
expect(correctionOf(auto, fold([set({ "light.exposure": 0.2, "wb.temp": 5200 }), { command: "develop.reset" }]))).toEqual({
deltas: { "light.exposure": -0.2 },
@@ -152,8 +151,7 @@ describe("learning from corrections", () => {
const rows = [0.3, 0.25, 0.35, 0.3, -0.1].map((e, i) => ({ deltas: { "light.exposure": e, "light.contrast": i % 2 ? 8 : -8 }, cropScale: 0.7 }));
const style = styleOf(rows, null);
expect(style.offsets).toEqual({ "light.exposure": 0.3 });
// 0.7 is below the 0.75 floor (never suggest tighter than that), so it saturates there.
expect(style.cropFactor).toBeCloseTo(0.75, 2);
expect(style.cropFactor).toBeCloseTo(0.7, 2);
expect(styleOf(rows.slice(0, 4), null).offsets).toEqual({});
const open = [1.1, 1.12, 1.08, 1.15, 1.09].map((s) => ({
deltas: { "__crop.scale": s, "__crop.dx": 0.02, "__crop.dy": -0.03, "__crop.dAngle": 0 },
@@ -396,7 +394,7 @@ describe("autopilot", () => {
// The photographer lifts the exposure (0.2 -> 0.5) and crops tighter on five of them.
for (const id of photos.slice(0, 5)) {
const auto = fold((await ctx.db.photoEdit.findMany({ where: { photoId: id }, orderBy: { seq: "asc" } })).map((e) => e.command as never));
const r = auto.crop!.rect;
const r = auto.crop!;
const shrink = (a: number, b: number) => [a + (b - a) * 0.08, b - (b - a) * 0.08] as const;
const [x0, x1] = shrink(r.x0, r.x1);
const [y0, y1] = shrink(r.y0, r.y1);
@@ -414,8 +412,8 @@ describe("autopilot", () => {
await autopilot.decideBursts(new Date(Date.now() + 20_000));
const edits = await ctx.db.photoEdit.findMany({ where: { photoId: next }, orderBy: { seq: "asc" } });
expect((edits[0]!.command as { params: { values: Record<string, number> } }).params.values).toEqual({ "light.exposure": 0.5, "light.contrast": 10 });
const before = fold((await ctx.db.photoEdit.findMany({ where: { photoId: photos[5]! }, orderBy: { seq: "asc" } })).map((e) => e.command as never)).crop!.rect;
const after = fold(edits.map((e) => e.command as never)).crop!.rect;
const before = fold((await ctx.db.photoEdit.findMany({ where: { photoId: photos[5]! }, orderBy: { seq: "asc" } })).map((e) => e.command as never)).crop!;
const after = fold(edits.map((e) => e.command as never)).crop!;
expect(after.x1 - after.x0).toBeLessThan(before.x1 - before.x0);
expect(((await ctx.db.photo.findUniqueOrThrow({ where: { id: next } })).autopilot as { style: { samples: number } }).style.samples).toBe(5);
+4 -8
View File
@@ -7,7 +7,7 @@ import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest";
import { BLOCK_START, buildCodeLines, mergeGenerated, teamPrefix, toTsv } from "../src/sports/codegen.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, UrlSigner } from "../src/storage/storage.js";
import { LocalStorage } from "../src/storage/storage.js";
import { bearer, createTestApp, login, resetDb, seedUser, type TestContext } from "./helpers.js";
const quiet = { info: () => {}, warn: () => {} };
@@ -349,7 +349,7 @@ describe("sports data service", () => {
sites = fakeSites(state);
ctx = await createTestApp({ STORAGE_ROOT: path.join(dir, "storage") }, undefined, sites.fetcher as unknown as typeof fetch);
state.png = await sharp({ create: { width: 200, height: 200, channels: 4, background: { r: 200, g: 0, b: 0, alpha: 0.5 } } }).png().toBuffer();
sports = new SportsService({ db: ctx.db, storage: new LocalStorage(ctx.config.STORAGE_ROOT), signer: new UrlSigner(ctx.config.JWT_SECRET, ctx.config.FILE_URL_TTL_SEC), log: quiet, fetch: sites.fetcher, fpfDelayMs: 0, uefaDelayMs: 0, fpaDelayMs: 0 });
sports = new SportsService({ db: ctx.db, storage: new LocalStorage(ctx.config.STORAGE_ROOT), log: quiet, fetch: sites.fetcher, fpfDelayMs: 0, uefaDelayMs: 0, fpaDelayMs: 0 });
});
afterAll(async () => {
await ctx.app.close();
@@ -383,7 +383,6 @@ describe("sports data service", () => {
["EHF", "el-women", "20262027"],
["LIGA", "ligaportugalbetclic", "20262027"],
["LIGA", "ligaportugalmeusuper", "20262027"],
["FPA", "M19-AMIG", "20262027"],
["UEFA", "1", "20262027"],
["UEFA", "2019", "20262027"],
["UEFA", "14", "20262027"],
@@ -396,8 +395,6 @@ describe("sports data service", () => {
["MADEIRA SAD", "ABC DE BRAGA", "2026-10-14T18:30:00.000Z"],
["Torreense", "Sunderland", "2026-10-15T16:45:00.000Z"],
["SL Benfica", "FC Porto", "2026-10-18T19:30:00.000Z"],
["Portugal", "Espanha", "2026-11-05T20:00:00.000Z"],
["Espanha", "Portugal", "2026-11-07T17:30:00.000Z"],
]);
const benfica = await ctx.db.sportsTeam.findFirstOrThrow({ where: { name: "SL Benfica" } });
expect((await sports.squad(benfica.id)).map((p) => [p.number, p.name])).toEqual([
@@ -672,7 +669,7 @@ describe("sports data service", () => {
if (u.pathname.endsWith("/141/373/4")) return json([{ ...fpaGame("900002", "2026-03-07", AGUAS, GIL, [25, 27]), ID_ASSOCIACAO: "8" }, regional]) as never;
return json([]) as never;
};
const service = new SportsService({ db: ctx.db, storage: new LocalStorage(ctx.config.STORAGE_ROOT), signer: new UrlSigner(ctx.config.JWT_SECRET, ctx.config.FILE_URL_TTL_SEC), log: quiet, fetch: fetcher, fpfDelayMs: 0, uefaDelayMs: 0, fpaDelayMs: 0 });
const service = new SportsService({ db: ctx.db, storage: new LocalStorage(ctx.config.STORAGE_ROOT), log: quiet, fetch: fetcher, fpfDelayMs: 0, uefaDelayMs: 0, fpaDelayMs: 0 });
expect(await service.importFpaSeason("20252026")).toBe(2);
const saved = await ctx.db.sportsFixture.findMany({ where: { season: "20252026", externalId: { in: ["900001", "900002", "900003"] } }, select: { externalId: true } });
expect(saved.map((f) => f.externalId).sort()).toEqual(["900001", "900002"]);
@@ -726,7 +723,6 @@ describe("sports data service", () => {
sports = new SportsService({
db: ctx.db,
storage: new LocalStorage(ctx.config.STORAGE_ROOT),
signer: new UrlSigner(ctx.config.JWT_SECRET, ctx.config.FILE_URL_TTL_SEC),
log: quiet,
fetch: (async (url, init) => {
const u = String(url);
@@ -830,7 +826,7 @@ describe("sports data service", () => {
const m19 = await ctx.db.sportsTeam.findFirstOrThrow({ where: { provider: "FPA", externalId: "M19" } });
expect(await ctx.db.sportsPlayer.findFirstOrThrow({ where: { teamId: m19.id, name: "Santiago Póvoas" } })).toMatchObject({
externalId: "228107",
number: "12",
number: null,
});
expect(await ctx.db.sportsPlayer.count({ where: { teamId: m19.id, goneAt: null } })).toBe(22);
const espM19 = await ctx.db.sportsTeam.findFirstOrThrow({ where: { provider: "FPA", externalId: "ESP-M19" } });
-25
View File
@@ -1,25 +0,0 @@
import { deskPath, type DeskCommand } from "@photoreport/contracts";
import { describe, expect, it } from "vitest";
import { deskState } from "./desk.js";
const show = (patch: Partial<DeskCommand>): DeskCommand => ({ module: "library", ...patch });
describe("deskPath", () => {
it("opens the library at the front page", () => {
expect(deskPath(show({ module: "library" }))).toBe("/");
});
it("opens one photo in develop", () => {
expect(deskPath(show({ module: "develop", photoId: "11111111-1111-4111-8111-111111111111" }))).toBe("/develop/11111111-1111-4111-8111-111111111111");
});
it("opens a shop tab", () => {
expect(deskPath(show({ module: "shop", section: "orders" }))).toBe("/shop?tab=orders");
});
});
describe("deskState", () => {
it("asks develop to start on the crop", () => {
expect(deskState(show({ module: "develop", tool: "crop" }))).toEqual({ crop: true });
});
});
-12
View File
@@ -1,12 +0,0 @@
import { deskPath, type DeskCommand } from "@photoreport/contracts";
export { deskPath };
export type { DeskCommand };
/** Where a develop tool is asked for. Crop and white balance already open from this state. */
export function deskState(command: DeskCommand): { crop?: boolean; picking?: boolean; spotting?: boolean } | null {
if (command.tool === "crop") return { crop: true };
if (command.tool === "wb") return { picking: true };
if (command.tool === "spot") return { spotting: true };
return null;
}
+1 -1
View File
@@ -15,7 +15,7 @@ export interface ScanStatus {
failed: number;
}
const btn = "pr-quiet disabled:opacity-40";
const btn = "h-8 border border-black bg-cell px-3 text-[12px] text-ink hover:bg-cell-on disabled:opacity-40";
/**
* Local catalogue (desktop): folders on this computer whose photos the editor opens straight from disk, at full
+1 -1
View File
@@ -111,7 +111,7 @@ function CardDialog({ onClose }: { onClose: () => void }) {
<h2 className="font-semibold uppercase tracking-wide text-ink">{t.card.title}</h2>
<div className="flex items-center gap-2">
<SnapshotMenu kind="card" current={s} onApply={setS} />
<button onClick={onClose} className="pr-quiet">
<button onClick={onClose} className="h-6 border border-black bg-cell px-2 text-[12px] text-ink hover:bg-cell-on">
{t.card.close}
</button>
</div>
+5 -5
View File
@@ -438,11 +438,11 @@ export function CardScan({
{t.cardScan.reopen}
</button>
{running ? (
<button type="button" onClick={cancelScan} className="pr-quiet">
<button type="button" onClick={cancelScan} className="h-7 border border-black bg-cell px-2.5 text-[12px] text-ink hover:bg-cell-on">
{t.cardScan.cancel}
</button>
) : (
<button type="button" onClick={onDismiss} className="pr-quiet">
<button type="button" onClick={onDismiss} className="h-7 border border-black bg-cell px-2.5 text-[12px] text-ink hover:bg-cell-on">
{t.cardScan.close}
</button>
)}
@@ -477,7 +477,7 @@ export function CardScan({
aria-label={t.cardScan.search}
className="h-7 min-w-[220px] flex-1 border border-black bg-cell px-2 text-[13px] text-ink"
/>
<button type="button" onClick={() => void pick()} className="pr-quiet">
<button type="button" onClick={() => void pick()} className="h-7 border border-black bg-cell px-2.5 text-[12px] text-ink hover:bg-cell-on">
{t.cardScan.pick}
</button>
<input
@@ -496,11 +496,11 @@ export function CardScan({
}}
/>
{running && (
<button type="button" onClick={cancelScan} className="pr-quiet">
<button type="button" onClick={cancelScan} className="h-7 border border-black bg-cell px-2.5 text-[12px] text-ink hover:bg-cell-on">
{t.cardScan.cancel}
</button>
)}
<button type="button" onClick={hide} className="pr-quiet">
<button type="button" onClick={hide} className="h-7 border border-black bg-cell px-2.5 text-[12px] text-ink hover:bg-cell-on">
{t.cardScan.close}
</button>
</div>
+2 -2
View File
@@ -294,7 +294,7 @@ export function EventSettingsButton(props: {
setOpen(false);
})
}
className="pr-quiet disabled:opacity-40"
className="h-7 border border-black bg-cell px-3 text-[12px] text-ink hover:bg-cell-on disabled:opacity-40"
title={event.archivedAt ? L.unarchiveHelp : L.archiveHelp}
>
{event.archivedAt ? L.unarchive : L.archive}
@@ -332,7 +332,7 @@ export function EventSettingsButton(props: {
type="button"
disabled={busy}
onClick={() => setConfirm(true)}
className="pr-quiet text-danger disabled:opacity-40"
className="h-7 border border-black bg-cell px-3 text-[12px] text-[#e8857a] hover:bg-cell-on disabled:opacity-40"
>
{L.delete}
</button>
+2 -2
View File
@@ -261,7 +261,7 @@ export function FacesView({ api, orgId, eventId, canAnalyse, refreshKey }: { api
</Link>
{selected.length === 2 && (
<button
className="pr-quiet"
className="h-7 border border-black bg-cell px-3 text-[12px] text-ink hover:bg-cell-on"
onClick={() => {
const [a, b] = selected as [string, string];
const sizeOf = (id: string) => groups?.find((g) => g.id === id)?.size ?? 0;
@@ -280,7 +280,7 @@ export function FacesView({ api, orgId, eventId, canAnalyse, refreshKey }: { api
)}
{canAnalyse && (
<button
className="pr-quiet ml-auto"
className="ml-auto h-7 border border-black bg-cell px-3 text-[12px] text-ink hover:bg-cell-on"
onClick={() =>
void api.analyseEventFaces(eventId).then(
(r) => {
+1 -1
View File
@@ -80,7 +80,7 @@ export function FilterBar(props: { filter: LibraryFilter; onChange: (f: LibraryF
<select
value={f.delivery}
onChange={(e) => set({ delivery: e.target.value as LibraryFilter["delivery"] })}
className={`pr-field ${f.delivery === "any" ? "" : "text-ink"}`}
className={`h-6 border border-black bg-cell px-1 text-[12px] ${f.delivery === "any" ? "text-muted" : "text-ink"}`}
>
{DELIVERY.map((d) => (
<option key={d} value={d}>
+3 -3
View File
@@ -202,7 +202,7 @@ export function FolderDevelop(props: {
return (
<div className="flex min-h-0 flex-1 flex-col">
<div className="flex flex-wrap items-center gap-2 border-b border-line bg-raised px-3 py-1.5 text-[12px]">
<button type="button" onClick={onClose} className="pr-quiet">
<button type="button" onClick={onClose} className="h-6 border border-black bg-cell px-2.5 text-[12px] text-ink hover:bg-cell-on">
{t.folderDevelop.back}
</button>
<span className="min-w-0 flex-1 truncate text-ink" title={file.path}>
@@ -213,7 +213,7 @@ export function FolderDevelop(props: {
title={t.folderDevelop.presetHelp}
disabled={!opened || !engine || saving}
onClick={() => void applyInterior(path, false)}
className="pr-quiet disabled:opacity-40"
className="h-6 border border-black bg-cell px-2.5 text-[12px] text-ink hover:bg-cell-on disabled:opacity-40"
>
{t.folderDevelop.preset}
</button>
@@ -221,7 +221,7 @@ export function FolderDevelop(props: {
type="button"
disabled={!opened || !settings || saving}
onClick={() => void save()}
className="pr-go disabled:opacity-40"
className="h-6 border border-black bg-accent px-2.5 text-[12px] text-white disabled:opacity-40"
>
{t.folderDevelop.save}
</button>
+3 -3
View File
@@ -277,7 +277,7 @@ export function FolderSheet(props: {
type="button"
title={t.folderSheet.developTitle}
onClick={() => onDevelop(focus)}
className="pr-quiet"
className="h-6 border border-black bg-cell px-2.5 text-[12px] text-ink hover:bg-cell-on"
>
{t.folderSheet.develop}
</button>
@@ -289,7 +289,7 @@ export function FolderSheet(props: {
title={t.folderSheet.mergeTitle}
disabled={merging}
onClick={runMerge}
className="pr-quiet disabled:opacity-40"
className="h-6 border border-black bg-cell px-2.5 text-[12px] text-ink hover:bg-cell-on disabled:opacity-40"
>
{t.merge.button}
</button>
@@ -312,7 +312,7 @@ export function FolderSheet(props: {
)}
</span>
)}
<button type="button" onClick={onClose} className="pr-quiet ml-auto">
<button type="button" onClick={onClose} className="ml-auto h-6 border border-black bg-cell px-2.5 text-[12px] text-ink hover:bg-cell-on">
{t.folderSheet.close}
</button>
</div>
+1 -1
View File
@@ -583,7 +583,7 @@ export function LocalFtpButton({ ftp, events, openEventId }: { ftp: LocalFtpStat
<div className="flex items-center gap-2">
{running ? (
<button onClick={() => void ftp.stop()} className="pr-quiet">
<button onClick={() => void ftp.stop()} className="h-7 border border-black bg-cell px-3 text-ink hover:bg-cell-on">
{L.stop}
</button>
) : (
+1 -1
View File
@@ -313,7 +313,7 @@ export function SendButton(props: { api: ApiClient; orgId: string; selection: Ph
)}
{note && <span className="text-[11px] text-ok">{note}</span>}
{already.length > 0 && (
<button onClick={() => void send(already, true)} disabled={busy} title={t.sendAgainHelp} className="pr-quiet disabled:opacity-40">
<button onClick={() => void send(already, true)} disabled={busy} title={t.sendAgainHelp} className="h-6 border border-black bg-cell px-2 text-[12px] text-ink hover:bg-cell-on">
{t.sendAgain(already.length)}
</button>
)}
+2 -2
View File
@@ -24,7 +24,7 @@ export function SnapshotMenu<T>({ kind, current, onApply }: { kind: string; curr
refresh();
setOpen((value) => !value);
}}
className="pr-quiet"
className="h-6 border border-black bg-cell px-2 text-[12px] text-ink hover:bg-cell-on"
>
{t.snapshots.button}
</button>
@@ -50,7 +50,7 @@ export function SnapshotMenu<T>({ kind, current, onApply }: { kind: string; curr
setItems(saveSnapshot(kind, name, current));
setName("");
}}
className="pr-quiet shrink-0"
className="h-7 shrink-0 border border-black bg-cell px-2 text-ink hover:bg-cell-on"
>
{t.snapshots.save}
</button>
+2 -2
View File
@@ -99,7 +99,7 @@ export function SquadsButton({ api, event, canEdit, onSaved, facesTick = 0, sele
setShowFaces(next);
prefs.set(FACES_PREF, next ? "1" : "0");
}}
className={`pr-quiet ${showFaces ? "is-on" : ""}`}
className={`h-6 border border-black px-2 ${showFaces ? "bg-accent text-white" : "bg-cell text-ink hover:bg-cell-on"}`}
>
{t.sports.showFaces}
</button>
@@ -148,7 +148,7 @@ export function SquadsButton({ api, event, canEdit, onSaved, facesTick = 0, sele
<div className="flex items-center gap-2 border-t border-line px-3 py-2">
{status && <span className="mr-auto text-muted">{status}</span>}
{linked && canEdit && (
<button disabled={busy} onClick={() => void sync()} className="pr-quiet ml-auto disabled:opacity-50">
<button disabled={busy} onClick={() => void sync()} className="ml-auto h-7 border border-black bg-cell px-3 hover:bg-cell-on disabled:opacity-50">
{t.sports.squadsSync}
</button>
)}
+2 -2
View File
@@ -458,11 +458,11 @@ export function UsbCameraButton({
<p className="mb-3 text-[11px] text-faint">{L.rawKept}</p>
{status && (
<div className="flex gap-2">
<button onClick={() => void usb.setTether(!status.tether)} className="pr-quiet">
<button onClick={() => void usb.setTether(!status.tether)} className="h-7 border border-black bg-cell px-3 text-ink hover:bg-cell-on">
{status.tether ? L.turnOff : L.turnOn}
</button>
{on && (
<button onClick={() => void usb.syncClock()} className="pr-quiet">
<button onClick={() => void usb.syncClock()} className="h-7 border border-black bg-cell px-3 text-ink hover:bg-cell-on">
{L.clockSync}
</button>
)}
+1 -4
View File
@@ -1,4 +1,4 @@
import { LIBRARY_CHANNEL, type DeskCommand, type LibraryMessage } from "@photoreport/contracts";
import { LIBRARY_CHANNEL, type LibraryMessage } from "@photoreport/contracts";
import type { ApiClient } from "@photoreport/sdk";
import { useEffect, useRef, useState } from "react";
import { io } from "socket.io-client";
@@ -40,9 +40,6 @@ export function useLibraryLive(api: ApiClient, onMessage: (message: LibraryMessa
socket.on("disconnect", () => setState("offline"));
socket.on("connect_error", () => setState("offline"));
socket.on(LIBRARY_CHANNEL, (message: LibraryMessage) => handler.current(message));
socket.on("desk", (command: DeskCommand) => {
window.dispatchEvent(new CustomEvent("photoreport-desk", { detail: command }));
});
return () => {
socket.close();
};
+8 -8
View File
@@ -200,7 +200,7 @@ function SourceCard({ api, source, isAdmin, active, onSelect, onChange, onRemove
<button
type="button"
onClick={() => void navigator.clipboard?.writeText(viewerUrl).then(() => (setCopied(true), setTimeout(() => setCopied(false), 1500)))}
className="pr-quiet"
className="h-6 border border-black bg-cell px-2 text-[11px] text-ink hover:bg-cell-on"
>
{copied ? A.copied : A.copy}
</button>
@@ -252,7 +252,7 @@ function SourceCard({ api, source, isAdmin, active, onSelect, onChange, onRemove
className="h-6 min-w-[220px] border border-black bg-cell px-2 text-[11px] text-ink"
/>
{name.trim() && name.trim() !== source.name && (
<button type="submit" disabled={busy} className="pr-quiet disabled:opacity-40">
<button type="submit" disabled={busy} className="h-6 border border-black bg-cell px-2 text-[11px] text-ink hover:bg-cell-on disabled:opacity-40">
{A.hostnameSave}
</button>
)}
@@ -276,7 +276,7 @@ function SourceCard({ api, source, isAdmin, active, onSelect, onChange, onRemove
className="h-6 min-w-[220px] border border-black bg-cell px-2 font-mono text-[11px] text-ink"
/>
{hostname.trim() !== (source.hostname ?? "") && (
<button type="submit" disabled={busy} className="pr-quiet disabled:opacity-40">
<button type="submit" disabled={busy} className="h-6 border border-black bg-cell px-2 text-[11px] text-ink hover:bg-cell-on disabled:opacity-40">
{A.hostnameSave}
</button>
)}
@@ -288,12 +288,12 @@ function SourceCard({ api, source, isAdmin, active, onSelect, onChange, onRemove
<div className="flex flex-wrap gap-2 border-t border-line pt-3">
{source.status !== "LOGIN" && (
<button type="button" disabled={busy} onClick={() => run(() => api.scanCloudSource(source.id))} className="pr-quiet disabled:opacity-40">
<button type="button" disabled={busy} onClick={() => run(() => api.scanCloudSource(source.id))} className="h-8 border border-black bg-cell px-3 text-[12px] text-ink hover:bg-cell-on disabled:opacity-40">
{A.scanNow}
</button>
)}
{isAdmin && source.account && (
<button type="button" disabled={busy} onClick={() => run(() => api.updateCloudSource(source.id, { paused: source.status !== "PAUSED" }))} className="pr-quiet disabled:opacity-40">
<button type="button" disabled={busy} onClick={() => run(() => api.updateCloudSource(source.id, { paused: source.status !== "PAUSED" }))} className="h-8 border border-black bg-cell px-3 text-[12px] text-ink hover:bg-cell-on disabled:opacity-40">
{source.status === "PAUSED" ? A.resume : A.pause}
</button>
)}
@@ -308,7 +308,7 @@ function SourceCard({ api, source, isAdmin, active, onSelect, onChange, onRemove
return s;
})
}
className="pr-quiet disabled:opacity-40"
className="h-8 border border-black bg-cell px-3 text-[12px] text-ink hover:bg-cell-on disabled:opacity-40"
>
{A.reauthorise}
</button>
@@ -441,10 +441,10 @@ function Galleries({ api, source }: { api: ApiClient; source: CloudSource }) {
{A.galleries} · {source.name}
</span>
<span className="flex gap-2 normal-case tracking-normal">
<button type="button" disabled={check?.busy} onClick={() => runCheck(false)} className="pr-quiet disabled:opacity-40" title="Volta a ligar já cada galeria de jogo oficial ao seu jogo, com as regras de hoje">
<button type="button" disabled={check?.busy} onClick={() => runCheck(false)} className="h-6 border border-black bg-cell px-2 text-[12px] text-ink hover:bg-cell-on disabled:opacity-40" title="Volta a ligar já cada galeria de jogo oficial ao seu jogo, com as regras de hoje">
{check?.busy ? "A rever…" : "Rever jogos"}
</button>
<button type="button" disabled={check?.busy} onClick={() => runCheck(true)} className="pr-quiet disabled:opacity-40" title="Revê todas as galerias (pode demorar)">
<button type="button" disabled={check?.busy} onClick={() => runCheck(true)} className="h-6 border border-black bg-cell px-2 text-[12px] text-muted hover:bg-cell-on disabled:opacity-40" title="Revê todas as galerias (pode demorar)">
Rever tudo
</button>
</span>
+1 -1
View File
@@ -6,7 +6,7 @@ import { t } from "../i18n.js";
const eur = (cents: number) => new Intl.NumberFormat("pt-PT", { style: "currency", currency: "EUR" }).format(cents / 100);
const input = "h-8 w-full border border-black bg-[#161617] px-2 text-[13px] text-ink placeholder:text-faint focus:border-accent focus:outline-none";
const btn = "pr-quiet disabled:opacity-40";
const btn = "h-7 border border-black bg-cell px-2 text-[11px] text-ink hover:bg-cell-on disabled:opacity-40";
const td = "border-b border-line px-3 py-1.5";
const ERRORS: Record<string, string> = {
digital_product_not_found: "Escolhe um produto digital.",
+5 -5
View File
@@ -136,7 +136,7 @@ export function DeliveryPage() {
</td>
<td className="border-b border-line px-3 py-1.5 text-right">
{i.status === "FAILED" && (
<button className="pr-quiet" onClick={() => void api.retryDelivery(orgId, i.id).then(load)}>
<button className="h-6 border border-black bg-cell px-2 text-[11px] hover:bg-cell-on" onClick={() => void api.retryDelivery(orgId, i.id).then(load)}>
{t.retry}
</button>
)}
@@ -184,7 +184,7 @@ export function DeliveryPage() {
</dl>
<div className="flex gap-2 px-3 pb-3">
<button
className="pr-quiet"
className="h-7 flex-1 border border-black bg-cell px-3 text-[12px] hover:bg-cell-on"
onClick={() => {
setNote("A ligar…");
api.testDeliveryTarget(orgId, target.id).then(
@@ -200,10 +200,10 @@ export function DeliveryPage() {
</button>
{isAdmin && (
<>
<button className="pr-quiet" onClick={() => setEditing(target)}>
<button className="h-7 border border-black bg-cell px-3 text-[12px] hover:bg-cell-on" onClick={() => setEditing(target)}>
Editar
</button>
<button className="pr-quiet" title="Mesmo servidor e credenciais, outro nome e pasta" onClick={() => setCopyName(`${target.name} (cópia)`)}>
<button className="h-7 border border-black bg-cell px-3 text-[12px] hover:bg-cell-on" title="Mesmo servidor e credenciais, outro nome e pasta" onClick={() => setCopyName(`${target.name} (cópia)`)}>
Duplicar
</button>
</>
@@ -226,7 +226,7 @@ export function DeliveryPage() {
}}
>
<input autoFocus aria-label="Nome da cópia" className="h-7 flex-1 border border-black bg-[#161617] px-2 text-[12px]" value={copyName} onChange={(e) => setCopyName(e.target.value)} />
<button className="pr-go">OK</button>
<button className="h-7 border border-black bg-cell px-3 text-[12px] hover:bg-cell-on">OK</button>
</form>
)}
{target.shareLinks === false ? (
+20 -21
View File
@@ -684,18 +684,16 @@ export function DevelopPage() {
// R in the library: the photo opens here with the crop tool on, once it is loaded (opening a photo turns it off).
const location = useLocation();
// W: with the white balance eyedropper.
const asked = location.state as { crop?: boolean; picking?: boolean; spotting?: boolean } | null;
const asked = location.state as { crop?: boolean; picking?: boolean } | null;
const cropAsked = asked?.crop === true;
const pickAsked = asked?.picking === true;
const spotAsked = asked?.spotting === true;
const loadedId = session?.loaded ? session.photoId : null;
useEffect(() => {
if ((!cropAsked && !pickAsked && !spotAsked) || !loadedId || loadedId !== current?.id) return;
if ((!cropAsked && !pickAsked) || !loadedId || loadedId !== current?.id) return;
if (canEdit && cropAsked) setCropping(true);
if (canEdit && pickAsked) setPicking(true);
if (canEdit && spotAsked) setSpotting(true);
navigate(".", { replace: true, state: null });
}, [cropAsked, pickAsked, spotAsked, loadedId, current?.id, canEdit, navigate]);
}, [cropAsked, pickAsked, loadedId, current?.id, canEdit, navigate]);
// Entering crop on a photo that was never cropped: it starts with the default aspect (the last one chosen).
const defaulted = useRef(new Set<string>());
@@ -730,16 +728,16 @@ export function DevelopPage() {
{canCull && orgId && scope && !scope.startsWith("search:") && !scope.startsWith("face:") && (
<MergeButton api={api} orgId={orgId} eventId={scope === "inbox" ? null : scope} photos={photos} selectedIds={[...selected]} />
)}
<button className="pr-quiet disabled:opacity-40" disabled={!session?.canUndo} onClick={() => session?.undo()}>
<button className="h-6 border border-black bg-cell px-2.5 disabled:opacity-40" disabled={!session?.canUndo} onClick={() => session?.undo()}>
{t.dev.undo}
</button>
<button className="pr-quiet disabled:opacity-40" disabled={!session?.canRedo} onClick={() => session?.redo()}>
<button className="h-6 border border-black bg-cell px-2.5 disabled:opacity-40" disabled={!session?.canRedo} onClick={() => session?.redo()}>
{t.dev.redo}
</button>
<button className={`pr-quiet ${oneToOne ? "is-on" : ""}`} aria-pressed={oneToOne} title={t.dev.oneToOneHelp} onClick={() => setOneToOne(!oneToOne)}>
<button className={`h-6 border border-black px-2.5 ${oneToOne ? "bg-accent text-white" : "bg-cell"}`} aria-pressed={oneToOne} title={t.dev.oneToOneHelp} onClick={() => setOneToOne(!oneToOne)}>
1:1
</button>
<button className={`pr-quiet ${before ? "is-on" : ""}`} aria-pressed={before} onClick={() => setBefore(!before)}>
<button className={`h-6 border border-black px-2.5 ${before ? "bg-accent text-white" : "bg-cell"}`} aria-pressed={before} onClick={() => setBefore(!before)}>
{before ? t.dev.before : t.dev.after}
</button>
<span className={`min-w-20 text-right font-mono text-[11px] ${session?.offline ? "text-[#f0a35a]" : "text-faint"}`} role="status">
@@ -846,13 +844,14 @@ export function DevelopPage() {
</div>
{spotting && (
<Section title={t.dev.spot}>
<div className="pr-chips mb-2">
<div className="mb-2 flex flex-wrap gap-1">
{SPOT_MODES.map((m) => (
<button
key={m.id}
disabled={!canEdit}
onClick={() => setSpotMode(m.id)}
aria-pressed={spotMode === m.id}
className={`h-6 border border-black px-2 text-[11px] disabled:opacity-40 ${spotMode === m.id ? "bg-cell-on text-ink" : "bg-cell text-muted"}`}
>
{t.dev[m.labelKey]}
</button>
@@ -926,13 +925,13 @@ export function DevelopPage() {
disabled={!canEdit || !session?.loaded || !sourceSize}
onClick={() => void autoCrop()}
title={t.dev.autoCropHelp}
className="pr-quiet disabled:opacity-40"
className="h-7 border border-black bg-cell px-3 text-[12px] disabled:opacity-40"
>
{t.dev.auto}
</button>
<span className="text-[11px] text-faint">{t.dev.aspect}</span>
</div>
<div className="pr-chips mb-2">
<div className="mb-2 flex flex-wrap gap-1">
{ASPECTS.map((a) => {
// "Original" stays lit after X turns it (W:H or H:W of the photo).
const on =
@@ -946,7 +945,7 @@ export function DevelopPage() {
key={a.label}
disabled={!canEdit || !sourceSize}
onClick={() => setAspect(a.value)}
aria-pressed={on}
className={`h-6 border border-black px-2 text-[11px] disabled:opacity-40 ${on ? "bg-cell-on text-ink" : "bg-cell text-muted"}`}
>
{a.label}
</button>
@@ -959,19 +958,19 @@ export function DevelopPage() {
onClick={toggleLock}
aria-pressed={!!crop.aspect}
title={t.dev.cropLockHelp}
className={`pr-quiet disabled:opacity-40 ${crop.aspect ? "is-on" : ""}`}
className={`h-6 border border-black px-2 text-[11px] disabled:opacity-40 ${crop.aspect ? "bg-cell-on text-ink" : "bg-cell text-muted"}`}
>
{t.dev.cropLock}
</button>
<button disabled={!canEdit || !sourceSize} onClick={swapCrop} title={t.dev.cropSwapHelp} className="pr-quiet disabled:opacity-40">
<button disabled={!canEdit || !sourceSize} onClick={swapCrop} title={t.dev.cropSwapHelp} className="h-6 border border-black bg-cell px-2 text-[11px] text-muted disabled:opacity-40">
{t.dev.cropSwap}
</button>
<button disabled={!canEdit || !sourceSize} onClick={resetCrop} title={t.dev.cropResetHelp} className="pr-quiet disabled:opacity-40">
<button disabled={!canEdit || !sourceSize} onClick={resetCrop} title={t.dev.cropResetHelp} className="h-6 border border-black bg-cell px-2 text-[11px] text-muted disabled:opacity-40">
{t.dev.cropReset}
</button>
<label className="ml-auto flex items-center gap-1 text-[11px] text-faint" title={t.dev.guidesHelp}>
{t.dev.guides}
<select value={guide} onChange={(e) => chooseGuide(e.target.value as Guide)} className="pr-field">
<select value={guide} onChange={(e) => chooseGuide(e.target.value as Guide)} className="h-6 border border-black bg-cell px-1 text-[11px] text-ink">
{GUIDES.map((g) => (
<option key={g} value={g}>
{t.dev.guideNames[g]}
@@ -996,7 +995,7 @@ export function DevelopPage() {
disabled={!canEdit || !session?.loaded}
onClick={() => void autoLevel()}
title={t.dev.levelHelp}
className="pr-quiet mb-1 shrink-0 disabled:opacity-40"
className="mb-1 h-6 shrink-0 border border-black bg-cell px-2 text-[11px] disabled:opacity-40"
>
{t.dev.level}
</button>
@@ -1019,7 +1018,7 @@ export function DevelopPage() {
/>
<div className="flex flex-wrap gap-2 p-3">
<button
className="pr-quiet disabled:opacity-40"
className="h-7 border border-black bg-cell px-3 text-[12px] disabled:opacity-40"
disabled={!session?.loaded}
onClick={() => {
if (!session) return;
@@ -1045,7 +1044,7 @@ export function DevelopPage() {
/>
)}
<button
className="pr-quiet disabled:opacity-40"
className="h-7 border border-black bg-cell px-3 text-[12px] disabled:opacity-40"
disabled={!canEdit || !clip}
onClick={() => {
if (!session || !clip) return;
@@ -1056,7 +1055,7 @@ export function DevelopPage() {
{t.dev.paste}
</button>
<button
className="pr-quiet ml-auto disabled:opacity-40"
className="ml-auto h-7 border border-black bg-cell px-3 text-[12px] text-muted disabled:opacity-40"
disabled={!canEdit || !session?.loaded}
onClick={() => {
session?.edit({ command: "develop.reset" });
+1 -1
View File
@@ -8,7 +8,7 @@ import { openExternal } from "../platform.js";
const eur = (cents: number) => new Intl.NumberFormat("pt-PT", { style: "currency", currency: "EUR" }).format(cents / 100);
const day = (iso: string) => new Date(iso).toLocaleDateString("pt-PT");
const input = "h-8 w-full border border-black bg-[#161617] px-2 text-[13px] text-ink placeholder:text-faint focus:border-accent focus:outline-none";
const btn = "pr-quiet disabled:opacity-40";
const btn = "h-7 border border-black bg-cell px-2 text-[11px] text-ink hover:bg-cell-on disabled:opacity-40";
const th = "border-b border-line px-3 py-2 font-semibold";
const td = "border-b border-line px-3 py-1.5";
const errorText = (err: unknown) => (err instanceof ApiError ? (t.shop.errors[err.code] ?? err.code) : t.unexpectedError);
+1 -1
View File
@@ -5,7 +5,7 @@ import { t } from "../i18n.js";
const eur = (cents: number) => new Intl.NumberFormat("pt-PT", { style: "currency", currency: "EUR" }).format(cents / 100);
const input = "h-8 w-full border border-black bg-[#161617] px-2 text-[13px] text-ink placeholder:text-faint focus:border-accent focus:outline-none";
const btn = "pr-quiet disabled:opacity-40";
const btn = "h-8 border border-black bg-cell px-3 text-[12px] text-ink hover:bg-cell-on disabled:opacity-40";
const td = "border-b border-line px-3 py-1.5";
const errorText = (err: unknown) => (err instanceof ApiError ? (t.shop.errors[err.code] ?? t.invoicing.errors[err.code] ?? err.code) : t.unexpectedError);
+1 -10
View File
@@ -191,15 +191,6 @@ export function LibraryPage() {
[api, orgId, state.scope],
);
useEffect(() => {
const onOpen = (ev: Event) => {
const id = (ev as CustomEvent<string>).detail;
if (typeof id === "string" && id) void open(id).catch(() => setError(t.unexpectedError));
};
window.addEventListener("photoreport-open-event", onOpen);
return () => window.removeEventListener("photoreport-open-event", onOpen);
}, [open]);
useEffect(() => {
if (!orgId) return;
let alive = true;
@@ -805,7 +796,7 @@ export function LibraryPage() {
<span>{t.dropPartial}</span>
<button
type="button"
className="pr-quiet"
className="h-7 border border-black bg-cell px-2.5 text-ink hover:bg-cell-on"
onClick={() => {
setDropPartial(false);
fileInput.current?.click();
+1 -1
View File
@@ -70,7 +70,7 @@ export function MetadataPage() {
}`}
>
<span className="flex items-center justify-between gap-2">
<span className="text-[14px] font-semibold">{it.title}</span>
<span className="font-display text-[15px] font-semibold uppercase tracking-wide">{it.title}</span>
{it.badge && <span className={`font-mono text-[10.5px] max-md:hidden ${it.id === "faces" ? (it.on ? "text-ok" : "text-faint") : "text-faint"}`}>{it.badge}</span>}
</span>
<span className="mt-0.5 block text-[12px] leading-snug text-faint max-md:hidden">{it.hint}</span>
+1 -1
View File
@@ -6,7 +6,7 @@ import { t } from "../i18n.js";
const eur = (cents: number) => new Intl.NumberFormat("pt-PT", { style: "currency", currency: "EUR" }).format(cents / 100);
const input = "h-8 w-full border border-black bg-[#161617] px-2 text-[13px] text-ink placeholder:text-faint focus:border-accent focus:outline-none";
const btn = "pr-quiet disabled:opacity-40";
const btn = "h-7 border border-black bg-cell px-2 text-[11px] text-ink hover:bg-cell-on disabled:opacity-40";
const th = "border-b border-line px-3 py-2 font-semibold";
const td = "border-b border-line px-3 py-1.5";
const errorText = (err: unknown) => (err instanceof ApiError ? (t.press.errors[err.code] ?? t.shop.errors[err.code] ?? err.code) : t.unexpectedError);
+4 -4
View File
@@ -9,8 +9,8 @@ import { PageHeader } from "./Shell.js";
import { API_URL, eventsUrlFor } from "../api.js";
const input = "h-8 w-full border border-black bg-[#161617] px-2 text-[13px] text-ink placeholder:text-faint focus:border-accent focus:outline-none";
const btn = "pr-quiet disabled:opacity-40";
const primary = "pr-go";
const btn = "h-7 border border-black bg-cell px-2.5 text-[12px] text-ink hover:bg-cell-on disabled:opacity-40";
const primary = "h-8 bg-accent px-4 font-display text-[15px] font-semibold uppercase tracking-wide text-white hover:bg-accent-strong disabled:opacity-50";
const STATUS_COLOR: Record<PrintJobSummary["status"], string> = {
PAYMENT: "text-faint",
@@ -239,12 +239,12 @@ export function KioskPanel({ event, onChange }: { event: PrintEventSummary; onCh
</div>
)}
<div className="flex gap-2">
<button className="pr-quiet" onClick={make}>
<button className="h-7 border border-black bg-cell px-2 text-[11px] text-ink hover:bg-cell-on" onClick={make}>
{event.kiosk ? "Novo link" : "Ligar quiosque"}
</button>
{event.kiosk && (
<button
className="pr-quiet"
className="h-7 border border-black bg-cell px-2 text-[11px] text-ink hover:bg-cell-on"
onClick={() =>
void api.disablePrintKiosk(event.id).then(() => {
setLink(null);
+1 -1
View File
@@ -4,7 +4,7 @@ import { useCallback, useEffect, useMemo, useState } from "react";
import { useAuth } from "../auth.js";
import { t } from "../i18n.js";
const btn = "pr-quiet disabled:opacity-40";
const btn = "h-7 border border-black bg-cell px-2.5 text-[12px] text-ink hover:bg-cell-on disabled:opacity-40";
const LABELS = ["PURPLE", "GREEN", "BLUE", "YELLOW", "RED"] as const;
const SWATCH: Record<(typeof LABELS)[number], string> = { RED: "#d64545", YELLOW: "#d8b33a", GREEN: "#4c9a52", BLUE: "#4a78c9", PURPLE: "#8d5bc4" };
+2 -21
View File
@@ -1,7 +1,5 @@
import { hasRole } from "@photoreport/sdk";
import { useEffect } from "react";
import { NavLink, Outlet, useNavigate } from "react-router";
import { deskPath, deskState, type DeskCommand } from "../desk.js";
import { NavLink, Outlet } from "react-router";
import { useAuth } from "../auth.js";
import { Bell } from "../components/Bell.js";
import { Logo } from "../components/ui.js";
@@ -142,7 +140,6 @@ export function Shell() {
</div>
</details>
</header>
<DeskHost />
<UpdateNotice />
<UiReadyNotice />
<LocalDeliveries />
@@ -159,22 +156,6 @@ export function Shell() {
);
}
/** Follows the assistant: the open window changes module, photo or tool. */
function DeskHost() {
const navigate = useNavigate();
useEffect(() => {
const onDesk = (ev: Event) => {
const command = (ev as CustomEvent<DeskCommand>).detail;
if (!command || typeof command.module !== "string") return;
navigate(deskPath(command), { state: deskState(command) });
if (command.eventId) window.dispatchEvent(new CustomEvent("photoreport-open-event", { detail: command.eventId }));
};
window.addEventListener("photoreport-desk", onDesk);
return () => window.removeEventListener("photoreport-desk", onDesk);
}, [navigate]);
return null;
}
function initials(name: string): string {
return name
.split(/\s+/)
@@ -187,7 +168,7 @@ function initials(name: string): string {
export function PageHeader({ title, children }: { title: string; children?: React.ReactNode }) {
return (
<header className="flex h-12 items-center justify-between border-b border-line bg-panel px-6">
<h1 className="text-[15px] font-semibold">{title}</h1>
<h1 className="font-display text-lg font-semibold uppercase tracking-wide">{title}</h1>
{children}
</header>
);
+3 -3
View File
@@ -16,8 +16,8 @@ const TABS: Tab[] = ["galleries", "orders", "products", "sites", "earnings", "af
const eur = (cents: number) => new Intl.NumberFormat("pt-PT", { style: "currency", currency: "EUR" }).format(cents / 100);
const input = "h-8 w-full border border-black bg-[#161617] px-2 text-[13px] text-ink placeholder:text-faint focus:border-accent focus:outline-none";
const btn = "pr-quiet disabled:opacity-40";
const primary = "pr-go";
const btn = "h-8 border border-black bg-cell px-3 text-[12px] text-ink hover:bg-cell-on disabled:opacity-40";
const primary = "h-8 bg-accent px-4 font-display text-[15px] font-semibold uppercase tracking-wide text-white hover:bg-accent-strong disabled:opacity-50";
const errorText = (err: unknown) => (err instanceof ApiError ? (t.shop.errors[err.code] ?? err.code) : t.unexpectedError);
@@ -43,7 +43,7 @@ export function ShopPage() {
<PageHeader title={t.shop.title}>
<nav className="flex gap-1" aria-label={t.shop.title}>
{tabs.map((x) => (
<button key={x} onClick={() => setTab(x)} aria-pressed={tab === x} className={`pr-quiet ${tab === x ? "is-on" : ""}`}>
<button key={x} onClick={() => setTab(x)} aria-pressed={tab === x} className={`h-7 px-3 text-[12px] ${tab === x ? "bg-cell-on text-ink" : "text-faint hover:text-muted"}`}>
{t.shop.tabs[x]}
</button>
))}
-56
View File
@@ -111,62 +111,6 @@ body {
color: var(--color-accent);
}
/* A set of choices inside a panel: the active one is underlined, the rest stay text. */
.pr-chips {
display: flex;
flex-wrap: wrap;
gap: 2px;
}
.pr-chips button {
height: 28px;
padding: 0 8px;
border: none;
border-bottom: 2px solid transparent;
background: transparent;
color: var(--color-faint);
font-size: 12px;
}
.pr-chips button:hover {
color: var(--color-ink);
}
.pr-chips button[aria-pressed="true"] {
color: var(--color-ink);
border-bottom-color: var(--color-accent);
}
.pr-chips button:disabled {
opacity: 0.4;
}
/* A choice sitting in a toolbar, not a form field. */
.pr-field {
height: 28px;
border: none;
background: transparent;
color: var(--color-muted);
font-size: 12px;
}
.pr-field:focus {
outline: none;
color: var(--color-ink);
}
/* The one action on a screen. */
.pr-go {
height: 32px;
padding: 0 14px;
border: none;
background: var(--color-accent);
color: #fff;
font-size: 13px;
font-weight: 600;
}
.pr-go:hover {
background: var(--color-accent-strong);
}
.pr-go:disabled {
opacity: 0.5;
}
/* Develop sliders: thin track drawn by the panel, small round thumb (Lightroom-like). */
.pr-range {
-webkit-appearance: none;
-21
View File
@@ -1,21 +0,0 @@
{
"name": "@photoreport/mcp",
"version": "0.1.0",
"private": true,
"type": "module",
"bin": {
"photoreport-mcp": "dist/index.js"
},
"scripts": {
"build": "tsc -p tsconfig.json",
"typecheck": "tsc -p tsconfig.json --noEmit",
"test": "vitest run",
"start": "node dist/index.js"
},
"dependencies": {
"@modelcontextprotocol/server": "^2.3.1",
"@photoreport/contracts": "workspace:*",
"@photoreport/sdk": "workspace:*",
"zod": "^4.2.0"
}
}
-16
View File
@@ -1,16 +0,0 @@
import { getControl } from "@photoreport/contracts";
/** Checks each develop value against the engine's control list before it is sent. */
export function developValues(input: Record<string, number>): Record<string, number> {
const out: Record<string, number> = {};
for (const [id, value] of Object.entries(input)) {
const control = getControl(id);
if (!control) throw new Error(`Unknown control "${id}". Call photoreport_develop_controls for the ids and ranges.`);
if (!Number.isFinite(value) || value < control.min || value > control.max) {
throw new Error(`${id} is ${value}. It must be between ${control.min} and ${control.max} (default ${control.default}).`);
}
out[id] = value;
}
if (Object.keys(out).length === 0) throw new Error("No controls to change.");
return out;
}
-31
View File
@@ -1,31 +0,0 @@
#!/usr/bin/env node
/**
* PhotoReport assistant. Speaks MCP over stdio and calls the PhotoReport API
* as the signed-in photographer. Stdout is the protocol; logs go to stderr.
*/
import { pathToFileURL } from "node:url";
import { McpServer } from "@modelcontextprotocol/server";
import { serveStdio } from "@modelcontextprotocol/server/stdio";
import { registerAccount } from "./tools/account.js";
import { registerDelivery } from "./tools/delivery.js";
import { registerDevelop } from "./tools/develop.js";
import { registerLibrary } from "./tools/library.js";
import { registerScreen } from "./tools/screen.js";
import { registerTeach } from "./tools/teach.js";
export function createServer(): McpServer {
const server = new McpServer({ name: "photoreport", version: "0.1.0" });
registerAccount(server);
registerScreen(server);
registerLibrary(server);
registerDevelop(server);
registerDelivery(server);
registerTeach(server);
return server;
}
const isMain = process.argv[1] !== undefined && import.meta.url === pathToFileURL(process.argv[1]).href;
if (isMain) {
serveStdio(createServer);
console.error("photoreport-mcp on stdio");
}
-29
View File
@@ -1,29 +0,0 @@
import type { McpServer } from "@modelcontextprotocol/server";
import { failText } from "./session.js";
type ToolContent = { type: "text"; text: string } | { type: "image"; data: string; mimeType: string };
type ToolResult = { content: ToolContent[]; isError?: boolean };
/** Tool results the model reads. Lists are already capped by the caller. */
export function text(body: string): ToolResult {
return { content: [{ type: "text", text: body }] };
}
export function textAndImages(body: string, images: { data: string; mimeType: string }[]): ToolResult {
return {
content: [
{ type: "text", text: body },
...images.map((image) => ({ type: "image" as const, data: image.data, mimeType: image.mimeType })),
],
};
}
export async function guard(work: () => Promise<ToolResult>): Promise<ToolResult> {
try {
return await work();
} catch (err) {
return { isError: true, content: [{ type: "text", text: failText(err) }] };
}
}
export type Server = McpServer;
-62
View File
@@ -1,62 +0,0 @@
import { describe, expect, it } from "vitest";
import type { PhotoSummary } from "@photoreport/contracts";
import { developValues } from "./edits.js";
import { reviewPhotos } from "./review.js";
function photo(patch: Partial<PhotoSummary>): PhotoSummary {
return {
id: "p",
eventId: "e",
originalName: "a.jpg",
name: "a.jpg",
sha256: "abc",
originalStored: true,
status: "READY",
width: 1000,
height: 800,
capturedAt: null,
cameraModel: null,
lens: null,
focalLength: null,
aperture: null,
exposureTime: null,
iso: null,
rating: 0,
flag: "NONE",
colorLabel: "NONE",
players: [],
uploader: null,
developSeq: 0,
urls: { thumb: "", preview: "", source: "" },
...patch,
};
}
describe("reviewPhotos", () => {
it("counts the frames a photographer still has to look at", () => {
const report = reviewPhotos([
photo({ id: "1", name: "pick.jpg", flag: "PICK" }),
photo({ id: "2", name: "bad.jpg", status: "FAILED", error: "truncated" }),
photo({ id: "3", name: "sent.jpg", flag: "PICK", developSeq: 4, delivery: "DONE", players: ["Ana"] }),
]);
expect(report.picks).toBe(2);
expect(report.uneditedPicks).toBe(1);
expect(report.failed).toBe(1);
expect(report.unsentPicks).toBe(1);
expect(report.lookAt.map((note) => note.name)).toEqual(["pick.jpg", "bad.jpg"]);
});
});
describe("developValues", () => {
it("refuses a control the engine does not have", () => {
expect(() => developValues({ "light.nope": 1 })).toThrow(/Unknown control/);
});
it("refuses a value outside the range", () => {
expect(() => developValues({ "light.exposure": 99 })).toThrow(/between/);
});
it("keeps a value inside the range", () => {
expect(developValues({ "light.exposure": 0.2 })).toEqual({ "light.exposure": 0.2 });
});
});
-75
View File
@@ -1,75 +0,0 @@
import type { PhotoSummary } from "@photoreport/contracts";
export interface ReviewNote {
id: string;
name: string;
reasons: string[];
}
export interface ReviewReport {
total: number;
ready: number;
failed: number;
processing: number;
picks: number;
rejects: number;
unrated: number;
uneditedPicks: number;
withoutPlayers: number;
deliveryFailed: number;
unsentPicks: number;
lookAt: ReviewNote[];
}
/**
* What a photographer (or the assistant) should look at. Sharpness is not on the photo row: a face tool
* answers that. This uses the catalogue: flags, ratings, edits, players and delivery.
*/
export function reviewPhotos(photos: PhotoSummary[], limit = 20): ReviewReport {
const lookAt: ReviewNote[] = [];
let ready = 0;
let failed = 0;
let processing = 0;
let picks = 0;
let rejects = 0;
let unrated = 0;
let uneditedPicks = 0;
let withoutPlayers = 0;
let deliveryFailed = 0;
let unsentPicks = 0;
for (const photo of photos) {
if (photo.status === "READY") ready += 1;
else if (photo.status === "FAILED") failed += 1;
else processing += 1;
if (photo.flag === "PICK") picks += 1;
if (photo.flag === "REJECT") rejects += 1;
if (photo.rating === 0 && photo.flag === "NONE") unrated += 1;
if (photo.flag === "PICK" && photo.developSeq === 0) uneditedPicks += 1;
if (photo.players.length === 0 && photo.flag !== "REJECT") withoutPlayers += 1;
if (photo.delivery === "FAILED") deliveryFailed += 1;
if (photo.flag === "PICK" && photo.delivery !== "DONE" && photo.delivery !== "QUEUED") unsentPicks += 1;
const reasons: string[] = [];
if (photo.status === "FAILED") reasons.push(photo.error ? `failed to read (${photo.error})` : "failed to read");
if (photo.delivery === "FAILED") reasons.push("delivery failed");
if (photo.flag === "PICK" && photo.developSeq === 0) reasons.push("pick with no edit yet");
if (photo.flag === "NONE" && photo.rating === 0 && photo.status === "READY") reasons.push("not culled");
if (reasons.length && lookAt.length < limit) lookAt.push({ id: photo.id, name: photo.name, reasons });
}
return {
total: photos.length,
ready,
failed,
processing,
picks,
rejects,
unrated,
uneditedPicks,
withoutPlayers,
deliveryFailed,
unsentPicks,
lookAt,
};
}
-118
View File
@@ -1,118 +0,0 @@
import { chmod, mkdir, readFile, writeFile } from "node:fs/promises";
import { homedir } from "node:os";
import { dirname, join } from "node:path";
import { ApiClient, ApiError, type RefreshTokenStore } from "@photoreport/sdk";
/** Where the assistant's refresh token lives. Never printed. */
export const sessionFile = process.env.PHOTOREPORT_SESSION_FILE ?? join(homedir(), ".config", "photoreport", "mcp-session.json");
interface Saved {
refreshToken?: string;
deviceCode?: string;
userCode?: string;
}
async function readSaved(): Promise<Saved> {
try {
const parsed = JSON.parse(await readFile(sessionFile, "utf8")) as unknown;
if (!parsed || typeof parsed !== "object") return {};
return parsed as Saved;
} catch {
return {};
}
}
async function writeSaved(next: Saved): Promise<void> {
await mkdir(dirname(sessionFile), { recursive: true });
await writeFile(sessionFile, JSON.stringify(next), { mode: 0o600 });
await chmod(sessionFile, 0o600);
}
const store: RefreshTokenStore = {
async get() {
const saved = await readSaved();
return saved.refreshToken ?? process.env.PHOTOREPORT_REFRESH_TOKEN ?? null;
},
async set(token: string) {
const saved = await readSaved();
saved.refreshToken = token;
delete saved.deviceCode;
delete saved.userCode;
await writeSaved(saved);
},
async clear() {
const saved = await readSaved();
delete saved.refreshToken;
await writeSaved(saved);
},
};
export const api = new ApiClient({
baseUrl: (process.env.PHOTOREPORT_API_URL ?? "https://api.next.photoreport.pt").replace(/\/$/, ""),
refreshStore: store,
});
const SIGN_IN = "Not signed in. Call photoreport_connect, approve the code in PhotoReport (the bell, or the link), then photoreport_connect_finish.";
/** Restores the saved session, or signs in with PHOTOREPORT_EMAIL and PHOTOREPORT_PASSWORD when both are set. */
export async function ensureSession(): Promise<void> {
if (api.isAuthenticated) return;
const email = process.env.PHOTOREPORT_EMAIL;
const password = process.env.PHOTOREPORT_PASSWORD;
if (email && password) {
await api.login(email, password, "PhotoReport assistant");
return;
}
if (!(await api.resume())) throw new Error(SIGN_IN);
}
let cachedOrg: string | null = process.env.PHOTOREPORT_ORG_ID ?? null;
/** The organization to work in: the argument, PHOTOREPORT_ORG_ID, or the account's first one. */
export async function orgId(given?: string): Promise<string> {
if (given) return given;
if (cachedOrg) return cachedOrg;
await ensureSession();
const me = await api.me();
const id = me.memberships[0]?.organization.id;
if (!id) throw new Error("This account belongs to no organization.");
cachedOrg = id;
return id;
}
export async function beginConnect(): Promise<{ userCode: string; url: string; expiresIn: number }> {
const grant = await api.startDeviceLogin("PhotoReport assistant");
const saved = await readSaved();
saved.deviceCode = grant.deviceCode;
saved.userCode = grant.userCode;
await writeSaved(saved);
return { userCode: grant.userCode, url: grant.verificationUriComplete, expiresIn: grant.expiresIn };
}
export async function finishConnect(): Promise<"approved" | "pending" | "expired" | "denied"> {
const saved = await readSaved();
if (!saved.deviceCode) throw new Error("No sign-in in progress. Call photoreport_connect first.");
const result = await api.pollDeviceLogin(saved.deviceCode);
if (result.status === "approved") return "approved";
if (result.status === "pending" || result.status === "slow_down") return "pending";
if (result.status === "denied") return "denied";
return "expired";
}
export async function disconnect(): Promise<void> {
await ensureSession();
await api.logout();
cachedOrg = process.env.PHOTOREPORT_ORG_ID ?? null;
}
/** What the model should read when a call fails. */
export function failText(err: unknown): string {
if (err instanceof ApiError) {
if (err.status === 401) return `${SIGN_IN} (${err.code})`;
if (err.status === 403) return `Not allowed (${err.code}). This account's role cannot do that.`;
if (err.status === 404) return `Not found (${err.code}). Check the id from a list tool.`;
return `The API refused the call (${err.status} ${err.code}).`;
}
if (err instanceof Error) return err.message;
return "The call failed.";
}
-96
View File
@@ -1,96 +0,0 @@
import * as z from "zod/v4";
import { api, beginConnect, disconnect, ensureSession, finishConnect, orgId } from "../session.js";
import { guard, text, type Server } from "../result.js";
export function registerAccount(server: Server): void {
server.registerTool(
"photoreport_connect",
{
title: "Sign in to PhotoReport",
description: "Starts a sign-in. Returns a short code and a link. The photographer approves it in the PhotoReport app, then call photoreport_connect_finish. The refresh token stays on this computer and is never returned.",
annotations: { readOnlyHint: false, openWorldHint: true, idempotentHint: true },
},
async () =>
guard(async () => {
const grant = await beginConnect();
return text(`Approve this code in PhotoReport: ${grant.userCode}\n${grant.url}\nIt expires in ${grant.expiresIn} seconds. Then call photoreport_connect_finish.`);
}),
);
server.registerTool(
"photoreport_connect_finish",
{
title: "Finish PhotoReport sign-in",
description: "Checks whether the photographer approved photoreport_connect. Call again in a few seconds while the status is pending.",
annotations: { readOnlyHint: false, openWorldHint: true },
},
async () =>
guard(async () => {
const status = await finishConnect();
if (status === "approved") return text("Signed in. Call photoreport_whoami to see the account and organization.");
if (status === "pending") return text("Still waiting. Ask the photographer to approve the code, then call this again.");
if (status === "denied") return text("The photographer refused. Call photoreport_connect to start again.");
return text("The code expired. Call photoreport_connect to start again.");
}),
);
server.registerTool(
"photoreport_disconnect",
{
title: "Sign out of PhotoReport",
description: "Forgets the assistant's PhotoReport session on this computer.",
annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: true },
},
async () =>
guard(async () => {
await disconnect();
return text("Signed out.");
}),
);
server.registerTool(
"photoreport_whoami",
{
title: "Who is signed in",
description: "The signed-in photographer and their organizations. Use the organization id in later calls when they belong to more than one. Example: who am I working as?",
annotations: { readOnlyHint: true, openWorldHint: true },
},
async () =>
guard(async () => {
await ensureSession();
const me = await api.me();
const lines = [`${me.user.name} <${me.user.email}>`];
for (const membership of me.memberships) {
lines.push(`- ${membership.organization.name} (${membership.organization.id}) role ${membership.role}`);
}
if (me.memberships.length === 0) lines.push("No organization.");
return text(lines.join("\n"));
}),
);
server.registerTool(
"photoreport_list_events",
{
title: "List events",
description: "Events in the organization, newest ingest window first as the API returns them. Use this to find the match the photographer is shooting before listing photos or sending. Pass archived to include closed events.",
inputSchema: z.object({
organizationId: z.string().optional().describe("Organization id. Defaults to PHOTOREPORT_ORG_ID or the account's first organization."),
archived: z.boolean().default(false).describe("Include archived events."),
}),
annotations: { readOnlyHint: true, openWorldHint: true },
},
async ({ organizationId, archived }) =>
guard(async () => {
await ensureSession();
const id = await orgId(organizationId);
const { events } = await api.listEvents(id, archived ? { includeArchived: true } : {});
if (events.length === 0) return text("No events.");
const lines = events.slice(0, 40).map((event) => {
const match = event.away ? `${event.home} x ${event.away}` : event.home;
return `- ${match} (${event.id}) ${event.startsAt} · ${event.photoCount} photos${event.archivedAt ? " · archived" : ""}`;
});
if (events.length > 40) lines.push(`… ${events.length - 40} more. Narrow by asking for one event id.`);
return text(lines.join("\n"));
}),
);
}
-136
View File
@@ -1,136 +0,0 @@
import type { PhotoQuery } from "@photoreport/sdk";
import * as z from "zod/v4";
import { api, ensureSession, orgId } from "../session.js";
import { guard, text, type Server } from "../result.js";
export function registerDelivery(server: Server): void {
server.registerTool(
"photoreport_list_destinations",
{
title: "List send destinations",
description: "Where photos can be sent (FTP, SFTP, Nextcloud, a local folder, and the rest). Use the name or id with photoreport_send_photos. Example: where can I send this match?",
inputSchema: z.object({ organizationId: z.string().optional() }),
annotations: { readOnlyHint: true, openWorldHint: true },
},
async ({ organizationId }) =>
guard(async () => {
await ensureSession();
const id = await orgId(organizationId);
const { targets } = await api.listDeliveryTargets(id);
if (targets.length === 0) return text("No destinations. Create one in Entregar.");
return text(targets.map((target) => `- ${target.name} (${target.id}) · ${target.kind}`).join("\n"));
}),
);
server.registerTool(
"photoreport_send_photos",
{
title: "Send photos",
description: "Sends photos to one destination. Pass photoIds, or an eventId plus picksOnly to send that event's picks (up to limit, ready photos, rejects are left out by the server). originals sends the camera file instead of the destination's resize. again sends photos that destination already has. Example: send the picks of this event to Cofina, at most 40.",
inputSchema: z.object({
organizationId: z.string().optional(),
destination: z.string().describe("Destination id or name."),
photoIds: z.array(z.string()).max(500).optional(),
eventId: z.string().optional().describe("Used when photoIds is omitted."),
picksOnly: z.boolean().default(true),
limit: z.number().int().min(1).max(300).default(40),
originals: z.boolean().default(false),
again: z.boolean().default(false),
}),
annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: true },
},
async (input) =>
guard(async () => {
await ensureSession();
const id = await orgId(input.organizationId);
const { targets } = await api.listDeliveryTargets(id);
const target = targets.find((item) => item.id === input.destination || item.name.toLowerCase() === input.destination.toLowerCase());
if (!target) throw new Error(`No destination named "${input.destination}". Call photoreport_list_destinations.`);
let ids = input.photoIds ?? [];
if (ids.length === 0) {
if (!input.eventId) throw new Error("Pass photoIds or an eventId.");
const query: PhotoQuery = { event: input.eventId, limit: input.limit };
if (input.picksOnly) query.flag = "PICK";
const page = await api.listPhotos(id, query);
ids = page.photos.filter((photo) => photo.status === "READY" && photo.flag !== "REJECT").map((photo) => photo.id);
}
if (ids.length === 0) return text("Nothing to send. No ready photos matched.");
const result = await api.deliver(id, target.id, ids, input.again, input.originals);
const skipped = result.skipped.map((item) => `${item.photoId} ${item.reason}`).join(", ");
return text(`Queued ${result.queued.length} to ${target.name}.${result.skipped.length ? ` Skipped ${result.skipped.length}: ${skipped}.` : ""} Call photoreport_delivery_status to watch them.`);
}),
);
server.registerTool(
"photoreport_send_best",
{
title: "Send the best of a match",
description: "Sends the best N moments of an event, spread over the match, to one destination. dryRun only lists the choice and sends nothing. Example: send the best 30 of this match to Cofina.",
inputSchema: z.object({
organizationId: z.string().optional(),
destination: z.string(),
eventId: z.string(),
count: z.number().int().min(1).max(300).default(30),
dryRun: z.boolean().default(false),
again: z.boolean().default(false),
originals: z.boolean().default(false),
}),
annotations: { readOnlyHint: false, openWorldHint: true },
},
async (input) =>
guard(async () => {
await ensureSession();
const id = await orgId(input.organizationId);
const { targets } = await api.listDeliveryTargets(id);
const target = targets.find((item) => item.id === input.destination || item.name.toLowerCase() === input.destination.toLowerCase());
if (!target) throw new Error(`No destination named "${input.destination}". Call photoreport_list_destinations.`);
const result = await api.deliverBest(id, { targetId: target.id, eventId: input.eventId, count: input.count, dryRun: input.dryRun, again: input.again, originals: input.originals });
if (input.dryRun) return text(`Would send ${result.chosen.length} photos. Nothing was queued.`);
return text(`Queued ${result.queued.length} of ${result.chosen.length} chosen for ${target.name}. Skipped ${result.skipped.length}.`);
}),
);
server.registerTool(
"photoreport_delivery_status",
{
title: "Delivery status",
description: "Recent deliveries and how many are queued, running, done or failed. Pass a destination id to narrow it.",
inputSchema: z.object({
organizationId: z.string().optional(),
destinationId: z.string().optional(),
}),
annotations: { readOnlyHint: true, openWorldHint: true },
},
async (input) =>
guard(async () => {
await ensureSession();
const id = await orgId(input.organizationId);
const query: { targetId?: string } = {};
if (input.destinationId) query.targetId = input.destinationId;
const page = await api.listDeliveries(id, query);
const counts = Object.entries(page.counts).map(([status, count]) => `${status} ${count}`).join(" · ");
const lines = [counts || "No deliveries.", ...page.items.slice(0, 20).map((item) => `- ${item.status} ${item.remotePath ?? item.photoId} (${item.id})${item.lastError ? ` · ${item.lastError}` : ""}`)];
return text(lines.join("\n"));
}),
);
server.registerTool(
"photoreport_retry_delivery",
{
title: "Retry a delivery",
description: "Retries one failed delivery. The id comes from photoreport_delivery_status.",
inputSchema: z.object({
organizationId: z.string().optional(),
deliveryId: z.string(),
}),
annotations: { readOnlyHint: false, idempotentHint: true, openWorldHint: true },
},
async ({ organizationId, deliveryId }) =>
guard(async () => {
await ensureSession();
const id = await orgId(organizationId);
const item = await api.retryDelivery(id, deliveryId);
return text(`Delivery ${item.id} is ${item.status}.`);
}),
);
}
-128
View File
@@ -1,128 +0,0 @@
import { CONTROLS, type Module } from "@photoreport/contracts";
import { randomUUID } from "node:crypto";
import * as z from "zod/v4";
import { api, ensureSession } from "../session.js";
import { developValues } from "../edits.js";
import { guard, text, type Server } from "../result.js";
const CLIENT = "photoreport-mcp";
export function registerDevelop(server: Server): void {
server.registerTool(
"photoreport_develop_controls",
{
title: "Develop controls",
description: "The edit controls the engine accepts, with min, max and default. Call this before photoreport_edit_photo when the control id is not already known. Common ones: light.exposure, light.contrast, light.highlights, light.shadows, light.whites, light.blacks, color.temperature, color.tint, detail.sharpenAmount.",
inputSchema: z.object({
module: z.string().optional().describe("One module: basic controls live under light and color ids. Pass crop, detail, optics, vignette, or leave empty for the basic light and colour ids."),
}),
annotations: { readOnlyHint: true, openWorldHint: false },
},
async ({ module }) =>
guard(async () => {
const wanted = module ? CONTROLS.filter((control) => control.module === (module as Module) || control.id.startsWith(`${module}.`)) : CONTROLS.filter((control) => control.id.startsWith("light.") || control.id.startsWith("color.") || control.id.startsWith("detail."));
const lines = wanted.slice(0, 80).map((control) => `- ${control.id} (${control.label}) ${control.min}…${control.max}, default ${control.default}`);
if (wanted.length > 80) lines.push(`… ${wanted.length - 80} more. Pass a module name.`);
if (lines.length === 0) return text("No controls for that module. Modules include crop, basic, detail, optics, vignette, colorGrading.");
return text(lines.join("\n"));
}),
);
server.registerTool(
"photoreport_develop_state",
{
title: "Develop state",
description: "The current edit of one photo: snapshot sequence and the commands applied after it. Use photoreport_edit_photo to change it.",
inputSchema: z.object({ photoId: z.string() }),
annotations: { readOnlyHint: true, openWorldHint: true },
},
async ({ photoId }) =>
guard(async () => {
await ensureSession();
const state = await api.developState(photoId);
const lines = [`Sequence ${state.developSeq}, snapshot ${state.snapshotSeq}, ${state.ops.length} later edits.`];
for (const op of state.ops.slice(-12)) lines.push(`- ${op.seq} ${op.command.command}`);
return text(lines.join("\n"));
}),
);
server.registerTool(
"photoreport_edit_photo",
{
title: "Edit a photo",
description: "Applies develop commands to one photo. Values must be inside the control ranges (photoreport_develop_controls). Crop rect is 0..1 of the frame. reset clears the edit first. The same command is safe to retry: each call has its own id and the server stores it once. Example: raise exposure by setting light.exposure to 0.4 on photo <id>.",
inputSchema: z.object({
photoId: z.string(),
values: z.record(z.string(), z.number()).optional().describe("Control id to value, for example { \"light.exposure\": 0.3, \"light.contrast\": 10 }."),
reset: z.boolean().default(false).describe("Clear the edit before applying values."),
crop: z
.object({
x0: z.number().min(0).max(1),
y0: z.number().min(0).max(1),
x1: z.number().min(0).max(1),
y1: z.number().min(0).max(1),
angle: z.number().min(-45).max(45).default(0),
aspectW: z.number().int().positive().nullable().default(null),
aspectH: z.number().int().positive().nullable().default(null),
})
.optional(),
}),
annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: true },
},
async (input) =>
guard(async () => {
await ensureSession();
const ops: { opId: string; command: { command: "develop.reset" } | { command: "develop.set"; params: { values: Record<string, number> } } | { command: "crop.set"; params: { rect: { x0: number; y0: number; x1: number; y1: number }; angle: number; aspect: [number, number] | null } } }[] = [];
if (input.reset) ops.push({ opId: randomUUID(), command: { command: "develop.reset" } });
if (input.values) ops.push({ opId: randomUUID(), command: { command: "develop.set", params: { values: developValues(input.values) } } });
if (input.crop) {
if (input.crop.x0 >= input.crop.x1 || input.crop.y0 >= input.crop.y1) throw new Error("The crop must have a positive size (x0 < x1 and y0 < y1).");
const aspect = input.crop.aspectW && input.crop.aspectH ? ([input.crop.aspectW, input.crop.aspectH] as [number, number]) : null;
ops.push({
opId: randomUUID(),
command: { command: "crop.set", params: { rect: { x0: input.crop.x0, y0: input.crop.y0, x1: input.crop.x1, y1: input.crop.y1 }, angle: input.crop.angle, aspect } },
});
}
if (ops.length === 0) throw new Error("Nothing to change. Pass values, crop, or reset.");
const result = await api.postEdits(input.photoId, { clientId: CLIENT, ops });
return text(`Edited. Sequence is now ${result.developSeq}. The preview updates when the render worker finishes.`);
}),
);
server.registerTool(
"photoreport_set_autopilot",
{
title: "Set autopilot",
description: "Turns the event autopilot on or off and sets how it edits arriving photos (crop, level, tone, white balance, look). New camera photos are edited on the desktop and the server with these rules. It does not re-edit photos already in the event.",
inputSchema: z.object({
eventId: z.string(),
enabled: z.boolean(),
crop: z.boolean().default(true),
level: z.boolean().default(true),
tone: z.boolean().default(true),
whiteBalance: z.boolean().default(true),
toneStrength: z.number().min(0).max(1).default(0.75),
look: z.enum(["agency", "natural", "none"]).default("none"),
framing: z.enum(["tight", "full"]).default("tight"),
}),
annotations: { readOnlyHint: false, idempotentHint: true, openWorldHint: true },
},
async (input) =>
guard(async () => {
await ensureSession();
const event = await api.updateEvent(input.eventId, {
autopilot: {
enabled: input.enabled,
crop: input.crop,
level: input.level,
tone: input.tone,
whiteBalance: input.whiteBalance,
toneStrength: input.toneStrength,
look: input.look,
framing: input.framing,
},
});
return text(`Autopilot on ${event.title}: ${input.enabled ? "on" : "off"}.`);
}),
);
}
-273
View File
@@ -1,273 +0,0 @@
import type { PhotoSummary } from "@photoreport/contracts";
import type { PhotoQuery } from "@photoreport/sdk";
import * as z from "zod/v4";
import { api, ensureSession, orgId } from "../session.js";
import { reviewPhotos } from "../review.js";
import { guard, text, type Server } from "../result.js";
const Flag = z.enum(["PICK", "REJECT", "NONE"]);
const Color = z.enum(["NONE", "RED", "YELLOW", "GREEN", "BLUE", "PURPLE"]);
function line(photo: PhotoSummary): string {
const exposure = [photo.focalLength ? `${photo.focalLength}mm` : "", photo.aperture ? `f/${photo.aperture}` : "", photo.iso ? `ISO ${photo.iso}` : ""].filter(Boolean).join(" ");
const mark = photo.flag === "NONE" ? "" : ` ${photo.flag}`;
const stars = photo.rating > 0 ? ` ${photo.rating}★` : "";
const players = photo.players.length ? ` · ${photo.players.join(", ")}` : "";
return `- ${photo.name} (${photo.id})${mark}${stars}${photo.colorLabel !== "NONE" ? ` ${photo.colorLabel}` : ""} · ${photo.status}${photo.delivery ? `/${photo.delivery}` : ""}${photo.developSeq ? " · edited" : ""}${players}${exposure ? ` · ${exposure}` : ""}`;
}
async function loadEvent(organization: string, eventId: string): Promise<PhotoSummary[]> {
const photos: PhotoSummary[] = [];
let offset = 0;
for (;;) {
const page = await api.listPhotos(organization, { event: eventId, offset, limit: 500 });
photos.push(...page.photos);
offset += page.photos.length;
if (page.photos.length === 0 || offset >= page.total || photos.length >= 1000) break;
}
return photos;
}
export function registerLibrary(server: Server): void {
server.registerTool(
"photoreport_list_photos",
{
title: "List photos",
description: "Photos of one event or the inbox. Filter by flag, minimum stars, or photos with no players. Returns names and ids for photoreport_photo, photoreport_set_photos and photoreport_send_photos. Example: the picks of event <id>.",
inputSchema: z.object({
organizationId: z.string().optional(),
eventId: z.string().describe("Event id, or inbox for photos no event claimed."),
flag: z.enum(["PICK", "REJECT", "NONE", "UNREJECTED"]).optional(),
minRating: z.number().int().min(0).max(5).optional(),
withoutPlayers: z.boolean().default(false),
status: z.enum(["PROCESSING", "READY", "FAILED"]).optional(),
offset: z.number().int().min(0).default(0),
limit: z.number().int().min(1).max(80).default(40),
}),
annotations: { readOnlyHint: true, openWorldHint: true },
},
async (input) =>
guard(async () => {
await ensureSession();
const id = await orgId(input.organizationId);
const query: PhotoQuery = { event: input.eventId, offset: input.offset, limit: input.limit };
if (input.flag) query.flag = input.flag;
if (input.minRating !== undefined) query.minRating = input.minRating;
if (input.withoutPlayers) query.withoutPlayers = true;
if (input.status) query.status = input.status;
const page = await api.listPhotos(id, query);
const lines = [`${page.photos.length} of ${page.total}, offset ${page.offset}`];
lines.push(...page.photos.map(line));
if (page.offset + page.photos.length < page.total) lines.push(`More: offset ${page.offset + page.photos.length}.`);
return text(lines.join("\n"));
}),
);
server.registerTool(
"photoreport_search",
{
title: "Search the library",
description: "Search across events by name, team, file name or a person id. Use photoreport_list_photos when the event is already known.",
inputSchema: z.object({
organizationId: z.string().optional(),
query: z.string().optional().describe("Text: name, team, competition, file name."),
personId: z.string().optional(),
limit: z.number().int().min(1).max(40).default(20),
}),
annotations: { readOnlyHint: true, openWorldHint: true },
},
async (input) =>
guard(async () => {
await ensureSession();
const id = await orgId(input.organizationId);
const query: { q?: string; personId?: string; limit: number } = { limit: input.limit };
if (input.query) query.q = input.query;
if (input.personId) query.personId = input.personId;
const found = await api.search(id, query);
const lines = [`${found.total} photos`];
lines.push(...found.photos.map(line));
if (found.suggested.length) {
lines.push("Suggested (face, not confirmed):");
lines.push(...found.suggested.map(line));
}
return text(lines.join("\n"));
}),
);
server.registerTool(
"photoreport_review_event",
{
title: "Review an event",
description: "Looks through an event (up to 1000 photos) and says what still needs the photographer: unread files, failed deliveries, picks with no edit, frames not culled, photos with no player. It does not judge sharpness from pixels. For one frame, call photoreport_photo. For shirt numbers, call photoreport_jersey_queue. Example: are the photos of this match in good shape?",
inputSchema: z.object({
organizationId: z.string().optional(),
eventId: z.string(),
}),
annotations: { readOnlyHint: true, openWorldHint: true },
},
async ({ organizationId, eventId }) =>
guard(async () => {
await ensureSession();
const id = await orgId(organizationId);
const photos = await loadEvent(id, eventId);
const report = reviewPhotos(photos);
const lines = [
`${report.total} photos · ${report.ready} ready · ${report.processing} processing · ${report.failed} failed`,
`${report.picks} picks · ${report.rejects} rejects · ${report.unrated} not culled`,
`${report.uneditedPicks} picks with no edit · ${report.withoutPlayers} without a player · ${report.deliveryFailed} deliveries failed · ${report.unsentPicks} picks not sent`,
];
if (report.lookAt.length === 0) lines.push("Nothing in the catalogue asks for a look. Sharpness and shirt numbers are separate tools.");
else {
lines.push("Look at:");
for (const note of report.lookAt) lines.push(`- ${note.name} (${note.id}): ${note.reasons.join("; ")}`);
}
return text(lines.join("\n"));
}),
);
server.registerTool(
"photoreport_photo",
{
title: "One photo",
description: "One photo: exposure, marks, players, faces found on it, and whether it has been edited. Preview URL is included so a client that can open images can look. Use photoreport_edit_photo to change the develop settings.",
inputSchema: z.object({ photoId: z.string() }),
annotations: { readOnlyHint: true, openWorldHint: true },
},
async ({ photoId }) =>
guard(async () => {
await ensureSession();
const [faces, develop, iptc] = await Promise.all([
api.photoFaces(photoId),
api.developState(photoId),
api.photoIptc(photoId).catch(() => null),
]);
const lines = [`Faces: ${faces.status}, ${faces.faces.length}`];
for (const face of faces.faces) {
const who = face.person?.name ?? (face.suggestion ? `${face.suggestion.name} (suggested)` : "unnamed");
const visible = face.inPreview ? "in the crop" : "cropped out";
lines.push(`- ${who} · ${visible} · box ${face.x0.toFixed(2)},${face.y0.toFixed(2)}–${face.x1.toFixed(2)},${face.y1.toFixed(2)}`);
}
lines.push(`Develop sequence ${develop.developSeq}. ${develop.ops.length} edits after the snapshot.`);
if (iptc && iptc.issues.length) {
lines.push("IPTC:");
for (const issue of iptc.issues) lines.push(`- ${issue.field}: ${issue.detail}`);
}
return text(lines.join("\n"));
}),
);
server.registerTool(
"photoreport_set_photos",
{
title: "Mark photos",
description: "Sets the flag, stars, colour or players on one or many photos, or moves them to another event. This is the cull, not the develop edit (use photoreport_edit_photo for exposure and crop). Example: flag these ids as picks.",
inputSchema: z.object({
organizationId: z.string().optional(),
photoIds: z.array(z.string()).min(1).max(500),
flag: Flag.optional(),
rating: z.number().int().min(0).max(5).optional(),
color: Color.optional(),
players: z.array(z.string()).max(30).optional().describe("Replaces the player list."),
eventId: z.string().nullable().optional().describe("Move the photos to this event. Null sends them to the inbox."),
}),
annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: true },
},
async (input) =>
guard(async () => {
await ensureSession();
const id = await orgId(input.organizationId);
const patch: {
flag?: "PICK" | "REJECT" | "NONE";
rating?: number;
colorLabel?: "NONE" | "RED" | "YELLOW" | "GREEN" | "BLUE" | "PURPLE";
players?: string[];
eventId?: string | null;
} = {};
if (input.flag) patch.flag = input.flag;
if (input.rating !== undefined) patch.rating = input.rating;
if (input.color) patch.colorLabel = input.color;
if (input.players) patch.players = input.players;
if (input.eventId !== undefined) patch.eventId = input.eventId;
const result = await api.updatePhotos(id, input.photoIds, patch);
return text(`Updated ${result.updated} photos.`);
}),
);
server.registerTool(
"photoreport_squads",
{
title: "Event squads",
description: "The two teams of a match and whether each athlete has an enrolled face. Use this before naming faces or checking who is missing from the photos.",
inputSchema: z.object({ eventId: z.string() }),
annotations: { readOnlyHint: true, openWorldHint: true },
},
async ({ eventId }) =>
guard(async () => {
await ensureSession();
const squads = await api.eventSquads(eventId);
const lines: string[] = [];
for (const side of squads.sides) {
lines.push(`${side.team.name}`);
for (const player of side.players) {
const face = player.hasFace ? "face enrolled" : player.faceUrl ? "squad photo only" : "no face";
lines.push(`- ${player.number ?? "?"} ${player.name} (${face})`);
}
}
if (lines.length === 0) return text("No squad on this event. photoreport_sync_squads pulls the official list when the match is linked.");
return text(lines.join("\n"));
}),
);
server.registerTool(
"photoreport_sync_squads",
{
title: "Sync squads",
description: "Pulls the official squad for an event that is linked to a match. Does nothing useful when the event has no fixture.",
inputSchema: z.object({ eventId: z.string() }),
annotations: { readOnlyHint: false, idempotentHint: true, openWorldHint: true },
},
async ({ eventId }) =>
guard(async () => {
await ensureSession();
const result = await api.syncEventSquads(eventId);
return text(`Squad sync: ${result.created} created, ${result.updated} updated, ${result.headshots} headshots.`);
}),
);
server.registerTool(
"photoreport_list_galleries",
{
title: "List galleries",
description: "Galleries of the organization. Use the id with photoreport_add_to_gallery.",
inputSchema: z.object({ organizationId: z.string().optional() }),
annotations: { readOnlyHint: true, openWorldHint: true },
},
async ({ organizationId }) =>
guard(async () => {
await ensureSession();
const id = await orgId(organizationId);
const { galleries } = await api.listGalleries(id);
if (galleries.length === 0) return text("No galleries.");
return text(galleries.slice(0, 40).map((gallery) => `- ${gallery.title} (${gallery.id}) · ${gallery.photoCount} photos${gallery.publishedAt ? " · published" : ""}`).join("\n"));
}),
);
server.registerTool(
"photoreport_add_to_gallery",
{
title: "Add photos to a gallery",
description: "Adds photos to a gallery. Does not publish it. Example: put these picks in the match gallery.",
inputSchema: z.object({
galleryId: z.string(),
photoIds: z.array(z.string()).min(1).max(500),
}),
annotations: { readOnlyHint: false, idempotentHint: true, openWorldHint: true },
},
async ({ galleryId, photoIds }) =>
guard(async () => {
await ensureSession();
await api.changeGalleryPhotos(galleryId, { add: photoIds });
return text(`Added ${photoIds.length} photos to the gallery.`);
}),
);
}
-59
View File
@@ -1,59 +0,0 @@
import { execFile } from "node:child_process";
import { promisify } from "node:util";
import type { DeskCommand } from "@photoreport/contracts";
import * as z from "zod/v4";
import { api, ensureSession } from "../session.js";
import { guard, text, type Server } from "../result.js";
const exec = promisify(execFile);
/** Brings the installed PhotoReport window forward. The command still goes to whichever copy is signed in. */
async function raiseApp(): Promise<string> {
try {
if (process.platform === "darwin") {
await exec("open", ["-a", "PhotoReport"]);
return "PhotoReport is in front.";
}
if (process.platform === "win32") {
await exec("cmd", ["/c", "start", "", "PhotoReport"]);
return "PhotoReport was asked to open.";
}
} catch {
return "PhotoReport is not installed under that name. Open it yourself. The signed-in window still follows.";
}
return "Open PhotoReport. The signed-in window still follows.";
}
const Modules = ["library", "develop", "metadata", "delivery", "shop", "print", "archive", "faces", "numbers", "help", "preferences", "members"] as const;
export function registerScreen(server: Server): void {
server.registerTool(
"photoreport_show",
{
title: "Open a PhotoReport window",
description:
"Opens the PhotoReport application on this computer and moves the signed-in window. Use it to change tabs and to open a photo. module is library, develop, metadata, delivery, shop, print, archive, faces, numbers, help, preferences or members. photoId opens that photo in Revelar. eventId opens that event in the library. tool crop, spot or wb opens that tool on the photo. section is a shop tab (orders, products) or a metadata section (iptc, codes, people, faces). Example: open this photo and start the crop. The photographer sees the window move. Do this before saying a photo was shown.",
inputSchema: z.object({
module: z.enum(Modules),
photoId: z.string().optional(),
eventId: z.string().optional(),
tool: z.enum(["crop", "spot", "wb"]).optional(),
section: z.string().max(40).optional(),
}),
annotations: { readOnlyHint: false, idempotentHint: true, openWorldHint: true },
},
async (input) =>
guard(async () => {
await ensureSession();
const raised = await raiseApp();
const command: DeskCommand = { module: input.module };
if (input.photoId) command.photoId = input.photoId;
if (input.eventId) command.eventId = input.eventId;
if (input.tool) command.tool = input.tool;
if (input.section) command.section = input.section;
await api.desk(command);
const where = [input.module, input.photoId, input.eventId, input.tool, input.section].filter(Boolean).join(" · ");
return text(`${raised} Showing ${where}. If the window was signed out, sign in and call this again.`);
}),
);
}
-135
View File
@@ -1,135 +0,0 @@
import type { JerseySample } from "@photoreport/sdk";
import * as z from "zod/v4";
import { api, ensureSession, orgId } from "../session.js";
import { guard, text, textAndImages, type Server } from "../result.js";
async function cropImage(sample: JerseySample): Promise<{ data: string; mimeType: string } | null> {
try {
const response = await fetch(api.absolute(sample.crop), { signal: AbortSignal.timeout(15_000) });
if (!response.ok) return null;
const bytes = Buffer.from(await response.arrayBuffer());
if (bytes.length === 0 || bytes.length > 1_500_000) return null;
const mime = response.headers.get("content-type")?.split(";")[0] ?? "image/jpeg";
return { data: bytes.toString("base64"), mimeType: mime };
} catch {
return null;
}
}
export function registerTeach(server: Server): void {
server.registerTool(
"photoreport_jersey_queue",
{
title: "Shirt numbers to check",
description: "Crops of shirt numbers waiting to be taught, with the model's guess. The first few crops are attached as images so you can see whether the number is readable. Say the digits when they are clear, or illegible when the crop does not show a number, then call photoreport_jersey_review. Do not guess a number you cannot see. Example: show me numbers to teach.",
inputSchema: z.object({
organizationId: z.string().optional(),
status: z.enum(["PENDING", "CONFIRMED", "ILLEGIBLE", "SKIPPED"]).default("PENDING"),
limit: z.number().int().min(1).max(12).default(4),
}),
annotations: { readOnlyHint: true, openWorldHint: true },
},
async (input) =>
guard(async () => {
await ensureSession();
const id = await orgId(input.organizationId);
const page = await api.jerseySamples(id, input.status, input.limit);
const counts = Object.entries(page.stats.counts).map(([status, count]) => `${status} ${count}`).join(" · ");
const lines = [`Collected ${page.collected}. ${counts || "No counts."}`];
const images: { data: string; mimeType: string }[] = [];
for (const sample of page.samples) {
lines.push(`- ${sample.id} · ${sample.region} · guess ${sample.suggested ?? "none"} · player ${sample.person ?? "unknown"}`);
const image = await cropImage(sample);
if (image) images.push(image);
}
if (page.samples.length === 0) lines.push("Nothing in this queue.");
else lines.push("The images follow in the same order. Confirm with photoreport_jersey_review.");
return textAndImages(lines.join("\n"), images);
}),
);
server.registerTool(
"photoreport_jersey_review",
{
title: "Teach a shirt number",
description: "Records what the crop shows. CONFIRMED needs the digits you can see (label). ILLEGIBLE means the number is not readable. SKIPPED leaves it out of the dataset. The sample id comes from photoreport_jersey_queue.",
inputSchema: z.object({
sampleId: z.string(),
status: z.enum(["CONFIRMED", "ILLEGIBLE", "SKIPPED"]),
label: z.string().max(4).optional().describe("The digits you can see. Required when status is CONFIRMED."),
}),
annotations: { readOnlyHint: false, idempotentHint: true, openWorldHint: true },
},
async (input) =>
guard(async () => {
await ensureSession();
if (input.status === "CONFIRMED" && !input.label) throw new Error("A confirmed number needs the digits in label.");
const sample = await api.reviewJerseySample(input.sampleId, input.status, input.label ?? null);
return text(`Sample ${sample.id} is ${sample.status}${sample.label ? ` (${sample.label})` : ""}.`);
}),
);
server.registerTool(
"photoreport_face_groups",
{
title: "Faces in an event",
description: "People the faces worker grouped in one event, with the suggestion and how many photos. Unnamed groups are the ones to teach with photoreport_confirm_face.",
inputSchema: z.object({ eventId: z.string() }),
annotations: { readOnlyHint: true, openWorldHint: true },
},
async ({ eventId }) =>
guard(async () => {
await ensureSession();
const page = await api.faceGroups(eventId);
const lines = [`${page.groups.length} groups · ${page.pending} photos still running · ${page.unclear} unclear${page.available === false ? " · faces are off for this organization" : ""}`];
for (const group of page.groups.slice(0, 40)) {
const who = group.person?.name ?? (group.suggestion ? `${group.suggestion.name} suggested ${Math.round(group.suggestion.score * 100)}%` : "unnamed");
const number = group.number ? ` · shirt ${group.number.value}` : "";
lines.push(`- ${who} (${group.id}) · ${group.size} photos${number}${group.ignored ? " · ignored" : ""}`);
}
return text(lines.join("\n"));
}),
);
server.registerTool(
"photoreport_confirm_face",
{
title: "Name a face group",
description: "Names every photo in a face group as one person. Pass personId from the squad, or a name (and club, number) to create the person. The group id comes from photoreport_face_groups.",
inputSchema: z.object({
groupId: z.string(),
personId: z.string().optional(),
name: z.string().optional(),
club: z.string().optional(),
number: z.string().max(4).optional(),
}),
annotations: { readOnlyHint: false, idempotentHint: true, openWorldHint: true },
},
async (input) =>
guard(async () => {
await ensureSession();
if (!input.personId && !input.name) throw new Error("Pass personId or a name.");
const who = input.personId
? { personId: input.personId }
: { name: input.name as string, ...(input.club ? { club: input.club } : {}), ...(input.number ? { number: input.number } : {}) };
const result = await api.confirmFaceGroup(input.groupId, who);
return text(`Named as ${result.person.name}.`);
}),
);
server.registerTool(
"photoreport_analyse_faces",
{
title: "Analyse faces",
description: "Queues face detection for an event. The organization must have biometrics on. This does not name anyone; use photoreport_face_groups afterwards.",
inputSchema: z.object({ eventId: z.string() }),
annotations: { readOnlyHint: false, idempotentHint: true, openWorldHint: true },
},
async ({ eventId }) =>
guard(async () => {
await ensureSession();
const result = await api.analyseEventFaces(eventId);
return text(`Queued ${result.queued} photos for faces.`);
}),
);
}
-9
View File
@@ -1,9 +0,0 @@
{
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"outDir": "dist",
"rootDir": "src",
"lib": ["ES2023"]
},
"include": ["src"]
}
-28
View File
@@ -1,28 +0,0 @@
import { z } from "zod";
/** Modules the assistant can open. `library` is the front page. */
export const DESK_MODULES = ["library", "develop", "metadata", "delivery", "shop", "print", "archive", "faces", "numbers", "help", "preferences", "members"] as const;
/**
* One instruction for the PhotoReport window that is open and signed in as this person.
* The API delivers it on the realtime socket. It does not change photos by itself.
*/
export const DeskCommand = z.object({
module: z.enum(DESK_MODULES),
photoId: z.uuid().optional(),
eventId: z.uuid().optional(),
/** Develop only: open that tool on the photo. */
tool: z.enum(["crop", "spot", "wb"]).optional(),
/** Shop tab or metadata section, when that module has one. */
section: z.string().max(40).optional(),
});
export type DeskCommand = z.infer<typeof DeskCommand>;
/** Where the window should go. Library is `/`, not `/library`. */
export function deskPath(command: DeskCommand): string {
if (command.module === "library") return "/";
if (command.module === "develop") return command.photoId ? `/develop/${command.photoId}` : "/develop";
if (command.module === "shop" && command.section) return `/shop?tab=${encodeURIComponent(command.section)}`;
if (command.module === "metadata" && command.section) return `/metadata?s=${encodeURIComponent(command.section)}`;
return `/${command.module}`;
}
-1
View File
@@ -1,5 +1,4 @@
export * from "./commands.js";
export * from "./desk.js";
export * from "./controls.js";
export * from "./library.js";
export * from "./shop.js";
+1 -6
View File
@@ -1,4 +1,4 @@
import type { BundleInput, BundleSummary, PressAccountInput, PressAccountSummary, PressStatement, NotificationView, AffiliateInput, AffiliateSummary, EarningsOverview, EarningsSettings, MemberPayoutInput, MyEarnings, PayeeAccount, PayoutInput, PayoutView, CodeGeneratorSettings, CodeLine, ConfirmFaceGroup, DeliveryItemSummary, DeskCommand, DevelopState, EditLogEntry, FaceGroupSummary, GalleryInput, GalleryPhotosChange, GallerySummary, Module, OrderView, PhotoPatch, PhotoSummary, PostEdits, PrinterSummary, PrintEventInput, PrintEventSummary, PrintJobSummary, ProductInput, ProofingReport, ProductSummary, SiteInfo, SiteInput, StationSummary } from "@photoreport/contracts";
import type { BundleInput, BundleSummary, PressAccountInput, PressAccountSummary, PressStatement, NotificationView, AffiliateInput, AffiliateSummary, EarningsOverview, EarningsSettings, MemberPayoutInput, MyEarnings, PayeeAccount, PayoutInput, PayoutView, CodeGeneratorSettings, CodeLine, ConfirmFaceGroup, DeliveryItemSummary, DevelopState, EditLogEntry, FaceGroupSummary, GalleryInput, GalleryPhotosChange, GallerySummary, Module, OrderView, PhotoPatch, PhotoSummary, PostEdits, PrinterSummary, PrintEventInput, PrintEventSummary, PrintJobSummary, ProductInput, ProofingReport, ProductSummary, SiteInfo, SiteInput, StationSummary } from "@photoreport/contracts";
import type { AgendaEntry, ArchiveStorage, CardScan, FaceIdentify, FaceRoster, CloudFolderSummary, CloudSource, CloudTreeFolder, InvoiceSummary, AutopilotStyle, DeliveryTarget, DeliveryTargetInput, JerseySample, JerseyStats, PersonSummary, PhotoFace, PhotoLookup, ShopSettings, SquadPerson, DeviceGrant, FtpAccount, FtpPlan, EventInput, EventSquads, EventSummary, FtpTargetAccount, IptcIssue, SportsCompetition, SportsFixture, SportsPlayer, SportsTeam, Me, Member, PhotoQuery, RealEstateFrame, RealEstateGrouping, Role, ZerozeroGame } from "./types.js";
/**
@@ -241,11 +241,6 @@ export class ApiClient {
return this.request<Me>("GET", "/v1/me");
}
/** Asks the open PhotoReport of this person to show a module, a photo or a tool. */
desk(command: DeskCommand) {
return this.request<{ ok: true }>("POST", "/v1/me/desk", command);
}
updateEditorModules(editorModules: Module[]) {
return this.request<{ editorModules: Module[] }>("PUT", "/v1/me/preferences", { editorModules });
}
-1
View File
@@ -237,7 +237,6 @@ export interface PhotoQuery {
flag?: "PICK" | "REJECT" | "NONE" | "UNREJECTED";
minRating?: number;
withoutPlayers?: boolean;
status?: "PROCESSING" | "READY" | "FAILED";
offset?: number;
limit?: number;
}
-32
View File
@@ -212,21 +212,6 @@ importers:
specifier: ^2.12.2
version: 2.12.2
apps/mcp:
dependencies:
'@modelcontextprotocol/server':
specifier: ^2.3.1
version: 2.4.0
'@photoreport/contracts':
specifier: workspace:*
version: link:../../packages/contracts
'@photoreport/sdk':
specifier: workspace:*
version: link:../../packages/sdk
zod:
specifier: ^4.2.0
version: 4.6.5
apps/print-agent:
dependencies:
'@photoreport/contracts':
@@ -832,14 +817,6 @@ packages:
resolution: {integrity: sha512-9I2Zn6+NJLfaGoz9jN3lpwDgAYvfGeNYdbAIjJOqzs4Tpc+VU3Jqq4IofSUBKajiDS8k9fZIg18/z13mpk1bsA==}
engines: {node: '>=8'}
'@modelcontextprotocol/[email protected]':
resolution: {integrity: sha512-z8QBKqdfXLPzkLQuG4xp8hrVEMm1PZ1IgxMN2sMbJiFiAKOWXnAzogXn2W4aqIBlP1ea6U5yiqVquvUNM1Cj6Q==}
engines: {node: '>=20'}
'@modelcontextprotocol/[email protected]':
resolution: {integrity: sha512-rgR9yxSaAJ+bcsi/XroT/S2AfPiIWloXAnrdfYSCms9ivVju0ishu/wW0J21Ho6+ZOR1r7RyeRbjiRuF87ix5Q==}
engines: {node: '>=20'}
'@napi-rs/[email protected]':
resolution: {integrity: sha512-oTXEIha4SsuXdTA4Iyskj0kpdx2yVXdhd75c2v3xGrHFfVMsbhTPZU/nMPL4sWKo4pBHm3aucLaqGlF696dTyQ==}
engines: {node: ^22.20 || ^24.12 || >=25}
@@ -3651,15 +3628,6 @@ snapshots:
'@lukeed/[email protected]': {}
'@modelcontextprotocol/[email protected]':
dependencies:
zod: 4.6.5
'@modelcontextprotocol/[email protected]':
dependencies:
'@modelcontextprotocol/core': 2.4.0
zod: 4.6.5
'@napi-rs/[email protected]':
optional: true