Compare commits

...
Author SHA1 Message Date
spark 72d9c17a4d Event pages without a storefront on the domain; desktop 0.3.2 with the manifest step fixed
ci / typescript (push) Failing after 20m33s
ci / rust (push) Successful in 21m28s
desktop-release / build (deb,appimage, linux-x86_64, ubuntu-latest) (push) Successful in 45m20s
events.next showed "Este domínio não tem site configurado" for /e/ pages: they now render on their own. The release's manifest step ended under pipefail when one of the two bundle folders didn't exist.

Claude-Session: https://claude.ai/code/session_01HT6iXLYUUp9pJz5Kza9xCW
2026-10-13 11:33:28 +01:00
spark ff8488fd93 Kiosk with photobooth on a tablet, Windows print agent, face boxes that follow the crop
ci / rust (push) Successful in 16m17s
ci / typescript (push) Failing after 16m55s
Impressão → Quiosque: a secret link for a tablet (photographer's photos, front camera photobooth, name and copies; paid prints at the counter). Print agent: Windows spooler through PowerShell. Loupe: face boxes in the edited preview's frame.

Claude-Session: https://claude.ai/code/session_01HT6iXLYUUp9pJz5Kza9xCW
2026-10-13 11:29:23 +01:00
27 changed files with 878 additions and 21 deletions

No files matched your search

+6 -1
View File
@@ -68,7 +68,12 @@ jobs:
if: env.TAURI_SIGNING_PRIVATE_KEY != ''
shell: bash
run: |
dir=$(ls -d apps/desktop/src-tauri/target/*/release/bundle apps/desktop/src-tauri/target/release/bundle 2>/dev/null | head -1)
# The bundle folder: target/<triple>/release/bundle (cross builds) or target/release/bundle. (A plain `ls` of
# both exits 2 for the one that doesn't exist, which ended the step under pipefail.)
dir=""
for d in apps/desktop/src-tauri/target/*/release/bundle apps/desktop/src-tauri/target/release/bundle; do
if [[ -d "$d" ]]; then dir="$d"; break; fi
done
node infra/desktop/update-manifest.mjs "$dir" ${{ matrix.platform }} "${GITHUB_REF_NAME}"
- uses: actions/upload-artifact@v3
with:
@@ -0,0 +1,2 @@
-- AlterTable
ALTER TABLE "print_events" ADD COLUMN "kiosk_token_hash" TEXT;
+2
View File
@@ -966,6 +966,8 @@ model PrintEvent {
galleryId String? @map("gallery_id") @db.Uuid
/// The printer jobs go to unless an operator moves them.
printerId String? @map("printer_id") @db.Uuid
/// Kiosk mode (a tablet at the event): SHA-256 of the secret in the kiosk link; null: no kiosk.
kioskTokenHash String? @map("kiosk_token_hash")
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
+61
View File
@@ -0,0 +1,61 @@
/**
* Face boxes are found on the photo as it arrived; the previews the app shows are the edited ones (straightened
* and cropped). This maps a box from the original frame into the rendered one, with the crop maths the editor
* and the engine use (apps/api/src/composition/geometry.ts): the crop is a box, normalised to the photo's size,
* in the frame rotated by the straighten angle about its centre.
*/
export interface Box {
x0: number;
y0: number;
x1: number;
y1: number;
}
export interface Crop {
rect: Box;
angle: number;
}
/** The crop in a develop settings document (LightCraft JSON); null when the photo isn't cropped or straightened. */
export function cropOfSettings(settings: unknown): Crop | null {
const g = (settings as { crop?: { geometry?: { rect?: Box; angle?: number } } } | null)?.crop?.geometry;
if (!g) return null;
const rect = g.rect ?? { x0: 0, y0: 0, x1: 1, y1: 1 };
const angle = g.angle ?? 0;
if (!angle && rect.x0 <= 0 && rect.y0 <= 0 && rect.x1 >= 1 && rect.y1 >= 1) return null;
return { rect, angle };
}
/**
* `box` (normalised, original frame) in the cropped frame, or null when it falls outside the crop. A box cut by the
* crop's edge is clipped to it. `w` × `h`: the photo's size in pixels (the rotation is in pixels).
*/
export function boxInCrop(box: Box, crop: Crop | null, w: number, h: number): Box | null {
if (!crop) return box;
const a = (crop.angle * Math.PI) / 180;
const [c, s] = [Math.cos(a), Math.sin(a)];
const corners = [
[box.x0, box.y0],
[box.x1, box.y0],
[box.x0, box.y1],
[box.x1, box.y1],
].map(([nx, ny]) => {
// Original -> straightened: rotate by +angle about the centre (the inverse of insideRotated's mapping).
const px = nx! * w - w / 2;
const py = ny! * h - h / 2;
return [(px * c - py * s + w / 2) / w, (px * s + py * c + h / 2) / h] as const;
});
const xs = corners.map((p) => p[0]);
const ys = corners.map((p) => p[1]);
const { rect } = crop;
const rw = rect.x1 - rect.x0;
const rh = rect.y1 - rect.y0;
const out = {
x0: (Math.min(...xs) - rect.x0) / rw,
y0: (Math.min(...ys) - rect.y0) / rh,
x1: (Math.max(...xs) - rect.x0) / rw,
y1: (Math.max(...ys) - rect.y0) / rh,
};
if (out.x1 <= 0 || out.y1 <= 0 || out.x0 >= 1 || out.y0 >= 1) return null;
return { x0: Math.max(0, out.x0), y0: Math.max(0, out.y0), x1: Math.min(1, out.x1), y1: Math.min(1, out.y1) };
}
+5 -1
View File
@@ -1,3 +1,4 @@
import { boxInCrop, cropOfSettings } from "./frame.js";
import { ConfirmFaceGroup, type FaceGroupSummary } from "@photoreport/contracts";
import type { FastifyInstance } from "fastify";
import { z } from "zod";
@@ -135,10 +136,12 @@ export async function registerFaceRoutes(app: FastifyInstance, deps: { db: Db; s
/** Faces of one photo with their names, for boxes in the loupe. */
app.get("/v1/photos/:photoId/faces", { preHandler: authenticate }, async (req) => {
const { photoId } = PhotoParams.parse(req.params);
const photo = await db.photo.findUnique({ where: { id: photoId }, select: { organizationId: true, facesStatus: true } });
const photo = await db.photo.findUnique({ where: { id: photoId }, select: { organizationId: true, facesStatus: true, width: true, height: true, renderedSeq: true, developSnapshot: true } });
if (!photo) throw notFound("photo_not_found");
await requireMembership(db, req, photo.organizationId, "INGESTER");
const list = await db.face.findMany({ where: { photoId }, include: { group: { include: { person: true, suggested: true } } }, orderBy: { x0: "asc" } });
// The previews are the edited photo: boxes are also given in its (cropped, straightened) frame.
const crop = photo.renderedSeq > 0 ? cropOfSettings(photo.developSnapshot) : null;
return {
status: photo.facesStatus,
faces: list.map((f) => ({
@@ -148,6 +151,7 @@ export async function registerFaceRoutes(app: FastifyInstance, deps: { db: Db; s
y0: f.y0,
x1: f.x1,
y1: f.y1,
inPreview: boxInCrop(f, crop, photo.width ?? 1, photo.height ?? 1),
score: f.score,
person: personOut(f.group?.person ?? null),
suggestion: f.group?.suggested ? personOut(f.group.suggested) : null,
+71
View File
@@ -71,6 +71,31 @@ export async function registerPrintRoutes(app: FastifyInstance, deps: { db: Db;
}),
);
/** Kiosk link for a tablet at the event: a new secret each time (shown once; the old link stops working). */
app.post(
"/v1/print-events/:id/kiosk",
{ preHandler: authenticate },
handle(async (req) => {
const { id } = IdParams.parse(req.params);
const e = await eventInOrg(req, id);
await requireMembership(db, req, e.organizationId, "EDITOR");
const token = await print.enableKiosk(e);
return { path: `/e/${e.slug}/quiosque?k=${token}` };
}),
);
app.delete(
"/v1/print-events/:id/kiosk",
{ preHandler: authenticate },
handle(async (req, reply) => {
const { id } = IdParams.parse(req.params);
const e = await eventInOrg(req, id);
await requireMembership(db, req, e.organizationId, "EDITOR");
await print.disableKiosk(e);
return reply.code(204).send();
}),
);
app.get("/v1/print-events/:id/jobs", { preHandler: authenticate }, async (req) => {
const { id } = IdParams.parse(req.params);
await eventInOrg(req, id);
@@ -214,6 +239,52 @@ export async function registerPrintRoutes(app: FastifyInstance, deps: { db: Db;
}),
);
// ---- kiosk (a tablet at the event, behind the kiosk link) ---------------------------------------
const KioskToken = z.string().min(16).max(64);
const Copies = z.coerce.number().int().min(1).max(5).default(1);
app.get(
"/v1/public/print/:slug/kiosk",
handle(async (req) => {
const { slug } = SlugParams.parse(req.params);
const { k } = z.object({ k: KioskToken }).parse(req.query);
return print.kioskView(slug, k);
}),
);
app.post(
"/v1/public/print/:slug/kiosk/pick",
{ config: { rateLimit: { max: 60, timeWindow: "1 minute" } } },
handle(async (req, reply) => {
const { slug } = SlugParams.parse(req.params);
const body = z.object({ k: KioskToken, photoId: z.uuid(), name: z.string().trim().max(60).optional(), copies: Copies }).parse(req.body);
const job = await print.kioskPrint(slug, body.k, { photoId: body.photoId }, { name: body.name || null, copies: body.copies });
return reply.code(201).send({ id: job.id, status: job.status });
}),
);
/** The photobooth: a picture taken with the tablet's camera (multipart: `k`, optional `name` and `copies`, then `file`). */
app.post(
"/v1/public/print/:slug/kiosk/capture",
{ config: { rateLimit: { max: 60, timeWindow: "1 minute" } } },
handle(async (req, reply) => {
const { slug } = SlugParams.parse(req.params);
const fields: Record<string, string> = {};
let data: Buffer | undefined;
for await (const part of req.parts({ limits: { fileSize: MAX_UPLOAD, files: 1 } })) {
if (part.type === "file") {
data = await part.toBuffer();
if (part.file.truncated) throw badRequest("file_too_large");
} else fields[part.fieldname] = String(part.value);
}
if (!data) throw badRequest("file_missing");
const k = KioskToken.parse(fields.k);
const job = await print.kioskPrint(slug, k, { image: data }, { name: fields.name?.trim().slice(0, 60) || null, copies: Copies.parse(fields.copies ?? 1) });
return reply.code(201).send({ id: job.id, status: job.status });
}),
);
// ---- the print agent ----------------------------------------------------------------------------
app.post(
+69 -3
View File
@@ -1,4 +1,4 @@
import { createHash, randomBytes, randomInt } from "node:crypto";
import { createHash, randomBytes, randomInt, timingSafeEqual } from "node:crypto";
import {
type AgentHeartbeat,
type ClaimedJob,
@@ -10,6 +10,7 @@ import {
type PrinterSummary,
type PublicPrintEvent,
type StationSummary,
type KioskView,
} from "@photoreport/contracts";
import type { Db } from "../db.js";
import type { PrintEvent, PrintJob, PrintStation, Printer, Prisma } from "../generated/prisma/client.js";
@@ -114,6 +115,7 @@ export class PrintService {
template: PrintTemplate.parse(e.template ?? {}),
galleryId: e.galleryId,
printerId: e.printerId,
kiosk: !!e.kioskTokenHash,
counts: { waiting, printed },
};
}
@@ -215,7 +217,7 @@ export class PrintService {
}
/** Lays out the print file and queues it (or holds it for approval). */
async createJob(event: PrintEvent, source: "GUEST" | "GALLERY" | "OPERATOR", image: string | Buffer, extra: { guestName?: string | null; guestKey?: string | null; photoId?: string | null; copies?: number }): Promise<PrintJob> {
async createJob(event: PrintEvent, source: "GUEST" | "GALLERY" | "OPERATOR", image: string | Buffer, extra: { guestName?: string | null; guestKey?: string | null; photoId?: string | null; copies?: number; kiosk?: boolean }): Promise<PrintJob> {
const { db, storage } = this.deps;
let file: Buffer;
try {
@@ -236,7 +238,8 @@ export class PrintService {
fileKey,
size: event.size,
copies: extra.copies ?? 1,
status: source === "OPERATOR" ? "QUEUED" : event.priceCents > 0 ? "PAYMENT" : event.requireApproval ? "APPROVAL" : "QUEUED",
// At the kiosk a paid print is paid at the counter: it waits for the operator's OK instead of Stripe.
status: source === "OPERATOR" ? "QUEUED" : event.priceCents > 0 ? (extra.kiosk ? "APPROVAL" : "PAYMENT") : event.requireApproval ? "APPROVAL" : "QUEUED",
guestName: extra.guestName ?? null,
guestKey: extra.guestKey ?? null,
},
@@ -310,6 +313,67 @@ export class PrintService {
return this.createJob(event, "GALLERY", await this.sourceFor(photo), { guestName: guest.name, guestKey: guest.key, photoId });
}
// ---- kiosk ---------------------------------------------------------------------------------------
/** A new kiosk link secret (the old one stops working); only its hash is kept. */
async enableKiosk(event: PrintEvent): Promise<string> {
const token = randomBytes(18).toString("base64url");
await this.deps.db.printEvent.update({ where: { id: event.id }, data: { kioskTokenHash: kioskHash(token) } });
return token;
}
async disableKiosk(event: PrintEvent): Promise<void> {
await this.deps.db.printEvent.update({ where: { id: event.id }, data: { kioskTokenHash: null } });
}
/** The event behind a kiosk link; a wrong or revoked secret is a 404, like an unknown event. */
async kioskEvent(slug: string, token: string): Promise<{ event: PrintEvent; view: PublicPrintEvent }> {
const found = await this.publicEvent(slug);
const hash = found.event.kioskTokenHash;
const given = kioskHash(token);
if (!hash || hash.length !== given.length || !timingSafeEqual(Buffer.from(hash), Buffer.from(given))) throw new PrintError("event_not_found", 404);
return found;
}
private kioskKey(event: PrintEvent) {
return `kiosk-${event.id}`;
}
async kioskView(slug: string, token: string): Promise<KioskView> {
const { event, view } = await this.kioskEvent(slug, token);
const recent = await this.deps.db.printJob.findMany({
where: { printEventId: event.id, guestKey: this.kioskKey(event), createdAt: { gt: new Date(Date.now() - 6 * 3600_000) } },
orderBy: { createdAt: "desc" },
take: 8,
});
const jobs = await Promise.all(
recent.map(async (j) => ({
id: j.id,
status: j.status,
guestName: j.guestName,
ahead: j.status === "QUEUED" || j.status === "APPROVAL" ? await this.deps.db.printJob.count({ where: { printEventId: event.id, status: { in: ["QUEUED", "APPROVAL"] }, createdAt: { lt: j.createdAt } } }) : 0,
preview: this.previewUrl(j),
createdAt: j.createdAt.toISOString(),
})),
);
return { ...view, payAtCounter: event.priceCents > 0, jobs };
}
/**
* A print from the kiosk: one of the photographer's photos, or a picture taken with the tablet's camera
* (photobooth). The tablet is shared and staffed, so the per-guest limit doesn't apply.
*/
async kioskPrint(slug: string, token: string, what: { photoId: string } | { image: Buffer }, guest: { name: string | null; copies: number }): Promise<PrintJob> {
const { db } = this.deps;
const { event } = await this.kioskEvent(slug, token);
if (!event.active) throw new PrintError("event_closed", 409);
const common = { guestName: guest.name, guestKey: this.kioskKey(event), copies: guest.copies, kiosk: true };
if ("image" in what) return this.createJob(event, "GUEST", what.image, common);
if (!event.galleryId || !(await db.galleryPhoto.findUnique({ where: { galleryId_photoId: { galleryId: event.galleryId, photoId: what.photoId } } }))) throw new PrintError("photo_not_found", 404);
const photo = await db.photo.findUniqueOrThrow({ where: { id: what.photoId } });
return this.createJob(event, "GALLERY", await this.sourceFor(photo), { ...common, photoId: what.photoId });
}
async guestJobs(slug: string, guestKey: string): Promise<GuestJob[]> {
const { db } = this.deps;
const event = await db.printEvent.findUnique({ where: { slug } });
@@ -473,3 +537,5 @@ export class PrintService {
return this.deps.storage.resolve(job.fileKey);
}
}
const kioskHash = (token: string) => createHash("sha256").update(token).digest("hex");
+39
View File
@@ -0,0 +1,39 @@
import { describe, expect, it } from "vitest";
import { insideRotated } from "../src/composition/geometry.js";
import { boxInCrop, cropOfSettings } from "../src/faces/frame.js";
describe("face boxes on edited previews", () => {
it("leaves an uncropped photo alone", () => {
const box = { x0: 0.2, y0: 0.2, x1: 0.3, y1: 0.35 };
expect(boxInCrop(box, cropOfSettings({ crop: { geometry: { rect: { x0: 0, y0: 0, x1: 1, y1: 1 }, angle: 0 } } }), 6000, 4000)).toEqual(box);
expect(cropOfSettings(null)).toBeNull();
});
it("moves and scales the box into the crop, and drops faces left outside", () => {
const crop = cropOfSettings({ crop: { geometry: { rect: { x0: 0.25, y0: 0.2, x1: 0.75, y1: 0.7 } } } })!;
const inside = boxInCrop({ x0: 0.5, y0: 0.4, x1: 0.55, y1: 0.5 }, crop, 6000, 4000)!;
expect(inside.x0).toBeCloseTo(0.5);
expect(inside.y0).toBeCloseTo(0.4);
expect(inside.x1).toBeCloseTo(0.6);
expect(inside.y1).toBeCloseTo(0.6);
expect(boxInCrop({ x0: 0.05, y0: 0.1, x1: 0.1, y1: 0.15 }, crop, 6000, 4000)).toBeNull();
// Cut by the crop's edge: clipped.
expect(boxInCrop({ x0: 0.2, y0: 0.3, x1: 0.3, y1: 0.4 }, crop, 6000, 4000)!.x0).toBe(0);
});
it("follows the straighten angle the same way the crop is checked against the photo", () => {
const crop = { rect: { x0: 0.1, y0: 0.1, x1: 0.9, y1: 0.9 }, angle: 5 };
// A tiny box at a point of the original lands where insideRotated (straightened -> original) would send it back.
const p = boxInCrop({ x0: 0.7, y0: 0.3, x1: 0.7, y1: 0.3 }, { rect: { x0: 0, y0: 0, x1: 1, y1: 1 }, angle: 5 }, 6000, 4000)!;
expect(insideRotated({ x0: p.x0, y0: p.y0, x1: p.x0, y1: p.y0 }, 5, 6000, 4000)).toBe(true);
const back = (() => {
const a = (-5 * Math.PI) / 180;
const px = p.x0 * 6000 - 3000;
const py = p.y0 * 4000 - 2000;
return [(px * Math.cos(a) - py * Math.sin(a) + 3000) / 6000, (px * Math.sin(a) + py * Math.cos(a) + 2000) / 4000];
})();
expect(back[0]).toBeCloseTo(0.7, 6);
expect(back[1]).toBeCloseTo(0.3, 6);
expect(boxInCrop({ x0: 0.45, y0: 0.45, x1: 0.55, y1: 0.55 }, crop, 6000, 4000)).not.toBeNull();
});
});
+31 -1
View File
@@ -55,7 +55,7 @@ describe("printing", () => {
async function setup(event: Record<string, unknown> = {}) {
const { org } = await seedUser(ctx.db, "[email protected]", { org: "events", role: "OWNER" });
const token = (await login(ctx.app, "[email protected]")).body.accessToken;
const api = (method: "GET" | "POST" | "PATCH" | "PUT", url: string, payload?: unknown) => ctx.app.inject({ method, url, headers: bearer(token), ...(payload !== undefined && { payload: payload as object }) });
const api = (method: "GET" | "POST" | "PATCH" | "PUT" | "DELETE", url: string, payload?: unknown) => ctx.app.inject({ method, url, headers: bearer(token), ...(payload !== undefined && { payload: payload as object }) });
const created = await api("POST", `/v1/orgs/${org!.id}/print-events`, { name: "Casamento Ana & Rui", template: { bandText: "Ana & Rui · 11.10.2026" }, ...event });
expect(created.statusCode).toBe(201);
return { orgId: org!.id, api, event: created.json() as { id: string; slug: string } };
@@ -85,6 +85,36 @@ describe("printing", () => {
expect(broadcaster.sent.filter((s) => s.message.type === "print.updated")).toHaveLength(3);
});
it("runs a kiosk on a tablet behind a secret link: gallery picks and photobooth shots, paid ones at the counter", async () => {
const { event, api } = await setup({ guestLimit: 1, priceCents: 300 });
expect((await ctx.app.inject({ method: "GET", url: `/v1/public/print/${event.slug}/kiosk?k=nothing-here-0123456789` })).statusCode).toBe(404);
const { path: link } = (await api("POST", `/v1/print-events/${event.id}/kiosk`, {})).json() as { path: string };
expect(link).toMatch(new RegExp(`^/e/${event.slug}/quiosque\\?k=[\\w-]{20,}$`));
const k = link.split("k=")[1]!;
expect((await api("GET", `/v1/orgs/${(await ctx.db.printEvent.findUniqueOrThrow({ where: { id: event.id } })).organizationId}/print-events`)).json().events[0]).toMatchObject({ kiosk: true });
const view = (await ctx.app.inject({ method: "GET", url: `/v1/public/print/${event.slug}/kiosk?k=${k}` })).json() as { payAtCounter: boolean; jobs: unknown[] };
expect(view).toMatchObject({ payAtCounter: true, jobs: [] });
// Two shots from the camera: the guest limit doesn't apply to the shared tablet, and paid prints wait for the counter.
const shot = async (name: string) => ctx.app.inject({ method: "POST", url: `/v1/public/print/${event.slug}/kiosk/capture`, ...multipart({ k, name, copies: "2" }, await photo("#aa3355")) });
expect((await shot("Mesa 4")).json()).toMatchObject({ status: "APPROVAL" });
expect((await shot("Mesa 7")).json()).toMatchObject({ status: "APPROVAL" });
expect(stripeCalls).toHaveLength(0);
const after = (await ctx.app.inject({ method: "GET", url: `/v1/public/print/${event.slug}/kiosk?k=${k}` })).json() as { jobs: { guestName: string; ahead: number }[] };
expect(after.jobs.map((j) => j.guestName)).toEqual(["Mesa 7", "Mesa 4"]);
expect(after.jobs.map((j) => j.ahead)).toEqual([1, 0]);
expect((await api("GET", `/v1/print-events/${event.id}/jobs`)).json().jobs[0]).toMatchObject({ copies: 2 });
// A photo that isn't in the event's gallery is refused; a new link retires the old one, and switching off ends it.
expect((await ctx.app.inject({ method: "POST", url: `/v1/public/print/${event.slug}/kiosk/pick`, payload: { k, photoId: "00000000-0000-4000-8000-000000000000" } })).json()).toMatchObject({ error: "photo_not_found" });
const { path: second } = (await api("POST", `/v1/print-events/${event.id}/kiosk`, {})).json() as { path: string };
expect((await ctx.app.inject({ method: "GET", url: `/v1/public/print/${event.slug}/kiosk?k=${k}` })).statusCode).toBe(404);
expect((await ctx.app.inject({ method: "GET", url: `/v1/public/print/${event.slug}/kiosk?k=${second.split("k=")[1]}` })).statusCode).toBe(200);
expect((await api("DELETE", `/v1/print-events/${event.id}/kiosk`)).statusCode).toBe(204);
expect((await ctx.app.inject({ method: "GET", url: `/v1/public/print/${event.slug}/kiosk?k=${second.split("k=")[1]}` })).statusCode).toBe(404);
});
it("holds jobs for approval when the event asks for it", async () => {
const { event, api } = await setup({ requireApproval: true });
const { id } = (await upload(event.slug)).json() as { id: string };
+24
View File
@@ -0,0 +1,24 @@
import { fireEvent, render, screen, waitFor } from "@testing-library/react";
import type { PrintEventSummary } from "@photoreport/contracts";
import type { ApiClient } from "@photoreport/sdk";
import { describe, expect, it, vi } from "vitest";
import { AuthProvider } from "../auth.js";
import { KioskPanel } from "./PrintPage.js";
const event = { id: "e1", slug: "casamento", name: "Casamento", priceCents: 300, kiosk: false } as PrintEventSummary;
describe("kiosk panel", () => {
it("makes a kiosk link on the events site and says paid prints are paid at the counter", async () => {
const enablePrintKiosk = vi.fn(async () => ({ path: "/e/casamento/quiosque?k=secret-0123456789abcdef" }));
const onChange = vi.fn();
render(
<AuthProvider api={{ resume: vi.fn(async () => false), enablePrintKiosk } as unknown as ApiClient}>
<KioskPanel event={event} onChange={onChange} />
</AuthProvider>,
);
expect(screen.getByText(/paga ao balcão/)).toBeTruthy();
fireEvent.click(screen.getByText("Ligar quiosque"));
await waitFor(() => expect(screen.getByText("https://events.photoreport.pt/e/casamento/quiosque?k=secret-0123456789abcdef")).toBeTruthy());
expect(onChange).toHaveBeenCalled();
});
});
+4 -1
View File
@@ -199,7 +199,10 @@ export function LibraryPage() {
if (!loupe || !focus || !canCull) return;
let alive = true;
api.photoFaces(focus.id).then(
(r) => alive && setLoupeFaces(r.faces.map((f) => ({ id: f.id, x0: f.x0, y0: f.y0, x1: f.x1, y1: f.y1, label: f.person?.name ?? f.suggestion?.name ?? null, suggested: !f.person }))),
(r) => alive && setLoupeFaces(
// The loupe shows the edited preview: boxes in its frame, faces cropped out left out.
r.faces.flatMap((f) => (f.inPreview ? [{ id: f.id, ...f.inPreview, label: f.person?.name ?? f.suggestion?.name ?? null, suggested: !f.person }] : [])),
),
() => {},
);
return () => {
+62
View File
@@ -191,6 +191,7 @@ export function PrintPage() {
<aside className="w-80 shrink-0 space-y-0 border-l border-line bg-panel max-lg:w-full">
{event && <EventPanel event={event} galleries={galleries} printers={printers} canEdit={canEdit} onChange={loadEvents} />}
{event && canEdit && <KioskPanel event={event} onChange={loadEvents} />}
<Printers orgId={orgId} printers={printers} stations={stations} isAdmin={isAdmin} canEdit={canEdit} onChange={loadPrinters} />
</aside>
</div>
@@ -198,6 +199,67 @@ export function PrintPage() {
);
}
/**
* Kiosk mode: a tablet at the event shows the photographer's photos big, takes pictures with its camera
* (photobooth) and sends prints to the queue. Its link carries a secret (shown when made; a new one retires it).
*/
export function KioskPanel({ event, onChange }: { event: PrintEventSummary; onChange: () => void }) {
const { api } = useAuth();
const [link, setLink] = useState<string | null>(null);
const [qr, setQr] = useState("");
useEffect(() => {
setLink(null);
}, [event.id]);
useEffect(() => {
if (!link) return setQr("");
QRCode.toString(link, { type: "svg", margin: 1, errorCorrectionLevel: "M" }).then(setQr, () => setQr(""));
}, [link]);
const make = () =>
void api.enablePrintKiosk(event.id).then((r) => {
setLink(guestUrl(event.slug).replace(/\/e\/[^/]+$/, "") + r.path);
onChange();
});
return (
<div className="border-b border-line">
<div className="panel-head">
<span>Quiosque</span>
<span className="normal-case tracking-normal text-faint">{event.kiosk ? "ligado" : "desligado"}</span>
</div>
<div className="space-y-2 p-3 text-[12px] text-muted">
<p className="text-[11px] text-faint">
Um tablet no evento mostra as fotos em grande, tira fotos com a câmara (photobooth) e manda imprimir.
{event.priceCents > 0 && " Como as impressões são pagas, as do quiosque ficam à espera da tua aprovação: o convidado paga ao balcão."}
</p>
{link && (
<div className="space-y-2">
<div className="mx-auto w-40 bg-white p-2" dangerouslySetInnerHTML={{ __html: qr }} aria-label={link} />
<p className="break-all font-mono text-[10.5px] text-ink">{link}</p>
<p className="text-[11px] text-faint">Abre este link no tablet (ou lê o código). Não volta a ser mostrado: um novo link desliga este.</p>
</div>
)}
<div className="flex gap-2">
<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="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);
onChange();
})
}
>
Desligar
</button>
)}
</div>
</div>
</div>
);
}
function EventPanel({ event, galleries, printers, canEdit, onChange }: { event: PrintEventSummary; galleries: GallerySummary[]; printers: PrinterSummary[]; canEdit: boolean; onChange: () => void }) {
const { api } = useAuth();
const [qr, setQr] = useState<string>("");
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@photoreport/desktop",
"version": "0.3.1",
"version": "0.3.2",
"private": true,
"type": "module",
"scripts": {
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "photoreport-desktop"
version = "0.3.1"
version = "0.3.2"
edition = "2024"
publish = false
description = "PhotoReport desktop: the web app in a native shell, with keychain sign-in and (later) local FTP and the native engine."
+1 -1
View File
@@ -1,7 +1,7 @@
{
"$schema": "https://schema.tauri.app/config/2",
"productName": "PhotoReport",
"version": "0.3.1",
"version": "0.3.2",
"identifier": "pt.photoreport.desktop",
"build": {
"devUrl": "http://localhost:5173",
+7 -2
View File
@@ -1,6 +1,6 @@
# apps/print-agent
Runs on the computer next to the printers (macOS or Linux with CUPS). It pairs with PhotoReport once, tells the
Runs on the computer next to the printers (macOS or Linux with CUPS, or Windows with the printer's driver). It pairs with PhotoReport once, tells the
server which printers it sees, takes print jobs for printers loaded with the job's paper, prints them and
reports back. Jobs from a station that dies mid-print go back to the queue after five minutes.
@@ -15,4 +15,9 @@ node apps/print-agent/dist/cli.js run
printers (Gutenprint, Mitsubishi CP-D90DW): 10x15 `w288h432`, 15x20 `w432h576`, 20x30 `w576h864`; override
with `"media": {"15x20": "..."}` in the config file (`~/.config/photoreport-print-agent/config.json`).
- `--folder <dir>` at pairing prints into folders instead (training, tests without paper).
- Windows: not yet (needs a provider for the Windows spooler).
- Windows: the spooler, through Windows PowerShell 5.1 and .NET (nothing else to install besides Node 22). It picks
the driver's paper that matches the job's size (4x6, 5x7, 6x8 or 8x12 in), prints without margins and turns
the photo to the paper. If a driver names a size differently, set `"paper": {"15x20": [600, 800]}` (hundredths
of an inch) in the config, `%APPDATA%\PhotoReport\photoreport-print-agent\config.json`. To start it with
Windows: `schtasks /Create /SC ONLOGON /TN "PhotoReport impressao" /TR "node C:\photoreport\apps\print-agent\dist\cli.js run"`.
Still to confirm on a real Windows computer with a dye-sub printer (DNP, Mitsubishi).
+21
View File
@@ -1,3 +1,4 @@
import { parseWindowsPrinters, WINDOWS_PAPER, windowsProvider } from "./providers.js";
import { describe, expect, it } from "vitest";
import { PrintAgent, pair } from "./agent.js";
import { parseLpstat, type PrintProvider } from "./providers.js";
@@ -55,4 +56,24 @@ describe("print agent", () => {
await agent.once();
expect(results).toEqual([{ ok: false, error: "lp: printer offline" }]);
});
it("lists and prints through the Windows spooler, values passed outside the script", async () => {
expect(parseWindowsPrinters('{"Name":"DNP DS620","Status":"Normal"}')).toEqual([{ systemName: "DNP DS620", state: "idle" }]);
expect(parseWindowsPrinters('[{"Name":"A","Status":"Printing"},{"Name":"B","Status":"Offline"}]').map((p) => p.state)).toEqual(["printing", "offline"]);
expect(parseWindowsPrinters("")).toEqual([]);
const calls: { file: string; args: string[]; env?: NodeJS.ProcessEnv }[] = [];
const runner = async (file: string, args: string[], opts: { env?: NodeJS.ProcessEnv }) => {
calls.push({ file, args, ...(opts.env && { env: opts.env }) });
return { stdout: '{"Name":"Mitsubishi CP-D90DW","Status":"Normal"}' };
};
const win = windowsProvider(WINDOWS_PAPER, runner);
expect(await win.list()).toEqual([{ systemName: "Mitsubishi CP-D90DW", state: "idle" }]);
await win.print("Sala \"VIP\" D90", "C:\\Temp\\job 1.jpg", { size: "15x20", copies: 2 });
const job = calls[1]!;
expect(job.file).toBe("powershell.exe");
expect(job.args.slice(0, 4)).toEqual(["-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass"]);
expect(job.args.at(-1)).not.toContain("VIP");
expect(job.env).toMatchObject({ PR_PRINTER: 'Sala "VIP" D90', PR_FILE: "C:\\Temp\\job 1.jpg", PR_COPIES: "2", PR_PAPER_W: "600", PR_PAPER_H: "800" });
});
});
+9 -4
View File
@@ -3,18 +3,22 @@ import { chmod, mkdir, readFile, writeFile } from "node:fs/promises";
import { homedir, hostname } from "node:os";
import path from "node:path";
import { PrintAgent, pair } from "./agent.js";
import { CUPS_MEDIA, cupsProvider, folderProvider } from "./providers.js";
import { CUPS_MEDIA, cupsProvider, folderProvider, WINDOWS_PAPER, windowsProvider } from "./providers.js";
const VERSION = "0.1.0";
const CONFIG = process.env.PR_AGENT_CONFIG ?? path.join(homedir(), ".config", "photoreport-print-agent", "config.json");
// Windows keeps per-user settings in %APPDATA%; macOS and Linux in ~/.config.
const CONFIG_DIR = process.platform === "win32" && process.env.APPDATA ? path.join(process.env.APPDATA, "PhotoReport") : path.join(homedir(), ".config");
const CONFIG = process.env.PR_AGENT_CONFIG ?? path.join(CONFIG_DIR, "photoreport-print-agent", "config.json");
interface Config {
api: string;
token: string;
provider?: "cups" | "folder";
provider?: "cups" | "windows" | "folder";
folder?: string;
folderPrinters?: string[];
media?: Record<string, string>;
/** Windows: paper per size in hundredths of an inch ([width, height]), when a driver names it differently. */
paper?: Record<string, [number, number]>;
}
const usage = `PhotoReport print agent ${VERSION}
@@ -33,8 +37,9 @@ async function load(): Promise<Config> {
}
}
function provider(c: Pick<Config, "provider" | "folder" | "folderPrinters" | "media">) {
function provider(c: Pick<Config, "provider" | "folder" | "folderPrinters" | "media" | "paper">) {
if (c.provider === "folder") return folderProvider(c.folder ?? path.join(homedir(), "photoreport-prints"), c.folderPrinters);
if (c.provider === "windows" || (!c.provider && process.platform === "win32")) return windowsProvider({ ...WINDOWS_PAPER, ...c.paper });
return cupsProvider({ ...CUPS_MEDIA, ...c.media });
}
+83
View File
@@ -73,3 +73,86 @@ export function folderProvider(root: string, names: string[] = ["Teste"]): Print
},
};
}
/**
* Paper sizes in hundredths of an inch (the unit of .NET's PaperSize) for the Windows spooler:
* 10x15 = 4x6 in, 13x18 = 5x7 in, 15x20 = 6x8 in, 20x30 = 8x12 in.
*/
export const WINDOWS_PAPER: Record<string, [number, number]> = {
"10x15": [400, 600],
"13x18": [500, 700],
"15x20": [600, 800],
"20x30": [800, 1200],
};
/** `Get-Printer` as JSON (one object, or an array): name and status. */
export function parseWindowsPrinters(json: string): LocalPrinter[] {
if (!json.trim()) return [];
const raw = JSON.parse(json) as { Name: string; Status?: string | null } | { Name: string; Status?: string | null }[];
return (Array.isArray(raw) ? raw : [raw]).map((p) => {
const s = String(p.Status ?? "").toLowerCase();
return { systemName: p.Name, state: s === "normal" || s === "" ? "idle" : s === "printing" ? "printing" : s.slice(0, 120) };
});
}
const LIST_PS = `Get-Printer | Select-Object Name,@{n='Status';e={"$($_.PrinterStatus)"}} | ConvertTo-Json -Compress`;
/**
* Prints one photo through the Windows spooler with .NET (System.Drawing, in Windows PowerShell 5.1, no install):
* the paper of the job's size when the driver has it, no margins, the photo turned to the paper's orientation and
* fitted (the server already laid it out at the paper's proportions). Values come in environment variables, never
* inside the script, so names with quotes or spaces can't break it.
*/
const PRINT_PS = `
$ErrorActionPreference = 'Stop'
Add-Type -AssemblyName System.Drawing
$img = [System.Drawing.Image]::FromFile($env:PR_FILE)
$doc = New-Object System.Drawing.Printing.PrintDocument
$doc.PrinterSettings.PrinterName = $env:PR_PRINTER
if (-not $doc.PrinterSettings.IsValid) { throw "printer not found: $($env:PR_PRINTER)" }
$doc.PrinterSettings.Copies = [int]$env:PR_COPIES
$w = [int]$env:PR_PAPER_W; $h = [int]$env:PR_PAPER_H
if ($w -gt 0) {
$paper = $doc.PrinterSettings.PaperSizes | Where-Object { ([math]::Abs($_.Width - $w) -le 25 -and [math]::Abs($_.Height - $h) -le 25) -or ([math]::Abs($_.Width - $h) -le 25 -and [math]::Abs($_.Height - $w) -le 25) } | Select-Object -First 1
if ($paper) { $doc.DefaultPageSettings.PaperSize = $paper }
}
$doc.DefaultPageSettings.Landscape = ($img.Width -gt $img.Height)
$doc.DefaultPageSettings.Margins = New-Object System.Drawing.Printing.Margins(0, 0, 0, 0)
$doc.OriginAtMargins = $false
$doc.DocumentName = 'PhotoReport ' + [System.IO.Path]::GetFileName($env:PR_FILE)
$doc.add_PrintPage({
param($sender, $e)
$b = $e.PageBounds
$scale = [math]::Min($b.Width / $img.Width, $b.Height / $img.Height)
$dw = $img.Width * $scale; $dh = $img.Height * $scale
$e.Graphics.InterpolationMode = [System.Drawing.Drawing2D.InterpolationMode]::HighQualityBicubic
$e.Graphics.DrawImage($img, [single](($b.Width - $dw) / 2), [single](($b.Height - $dh) / 2), [single]$dw, [single]$dh)
$e.HasMorePages = $false
})
try { $doc.Print() } finally { $img.Dispose() }
`;
type Runner = (file: string, args: string[], opts: { timeout: number; env?: NodeJS.ProcessEnv }) => Promise<{ stdout: string }>;
const powershell = (script: string) => ["-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-Command", script];
/** The Windows spooler (any installed printer driver, e.g. DNP or Mitsubishi), through Windows PowerShell. */
export function windowsProvider(paper: Record<string, [number, number]> = WINDOWS_PAPER, runner: Runner = run as unknown as Runner): PrintProvider {
return {
async list() {
try {
const { stdout } = await runner("powershell.exe", powershell(LIST_PS), { timeout: 20_000 });
return parseWindowsPrinters(stdout);
} catch {
return [];
}
},
async print(printer, file, opts) {
const [w, h] = paper[opts.size] ?? [0, 0];
await runner("powershell.exe", powershell(PRINT_PS), {
timeout: 120_000,
env: { ...process.env, PR_PRINTER: printer, PR_FILE: file, PR_COPIES: String(opts.copies), PR_PAPER_W: String(w), PR_PAPER_H: String(h) },
});
},
};
}
@@ -0,0 +1,318 @@
"use client";
import type { KioskView } from "@photoreport/contracts";
import { useCallback, useEffect, useRef, useState } from "react";
const IDLE_MS = 60_000;
const THANKS_MS = 7_000;
const STATUS: Record<KioskView["jobs"][number]["status"], string> = {
PAYMENT: "a pagar",
APPROVAL: "à espera do balcão",
QUEUED: "na fila",
PRINTING: "a imprimir",
DONE: "pronta",
FAILED: "falhou",
CANCELLED: "cancelada",
};
type Screen = { kind: "grid" } | { kind: "photo"; id: string; preview: string } | { kind: "camera" } | { kind: "shot"; blob: Blob; url: string } | { kind: "sent"; status: string };
const dark = "#0e0e0f";
const accent = "#e2001a";
const big: React.CSSProperties = { height: 72, padding: "0 32px", fontSize: 26, fontWeight: 700, border: 0, borderRadius: 14, color: "#fff", background: accent, cursor: "pointer" };
const ghost: React.CSSProperties = { ...big, background: "#2a2a2c" };
/**
* The kiosk: full screen, touch only, no account. Guests tap one of the photographer's photos (or take one with the
* tablet's camera), say their name and how many copies, and it goes to the event's print queue. After a minute
* without a touch it goes back to the start, so the next guest never sees the previous one's choice.
*/
export function Kiosk({ slug, token }: { slug: string; token: string }) {
const [view, setView] = useState<KioskView | null>(null);
const [failed, setFailed] = useState<string | null>(null);
const [screen, setScreen] = useState<Screen>({ kind: "grid" });
const [name, setName] = useState("");
const [copies, setCopies] = useState(1);
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
const idle = useRef<ReturnType<typeof setTimeout>>(undefined);
const load = useCallback(async () => {
const res = await fetch(`/v1/public/print/${encodeURIComponent(slug)}/kiosk?k=${encodeURIComponent(token)}`, { cache: "no-store" }).catch(() => null);
if (!res) return; // offline for a moment: keep what is on screen
if (res.status === 404) return setFailed("Este link de quiosque já não é válido. Pede um novo na app (Impressão → Quiosque).");
if (res.ok) {
setFailed(null);
setView((await res.json()) as KioskView);
}
}, [slug, token]);
const reset = useCallback(() => {
setScreen((s) => {
if (s.kind === "shot") URL.revokeObjectURL(s.url);
return { kind: "grid" };
});
setName("");
setCopies(1);
setError(null);
}, []);
// New photos arrive during the event; the strip of recent prints follows the queue.
useEffect(() => {
void load();
const t = setInterval(load, 15_000);
return () => clearInterval(t);
}, [load]);
// Back to the start after a minute without a touch.
useEffect(() => {
const poke = () => {
clearTimeout(idle.current);
idle.current = setTimeout(reset, IDLE_MS);
};
poke();
for (const e of ["pointerdown", "keydown"]) window.addEventListener(e, poke);
return () => {
clearTimeout(idle.current);
for (const e of ["pointerdown", "keydown"]) window.removeEventListener(e, poke);
};
}, [reset]);
// Keep the screen on while the kiosk is open (where the browser allows it).
useEffect(() => {
let lock: { release: () => Promise<void> } | null = null;
const take = async () => {
try {
lock = (await (navigator as unknown as { wakeLock?: { request: (t: string) => Promise<{ release: () => Promise<void> }> } }).wakeLock?.request("screen")) ?? null;
} catch {
lock = null;
}
};
void take();
const again = () => document.visibilityState === "visible" && void take();
document.addEventListener("visibilitychange", again);
return () => {
document.removeEventListener("visibilitychange", again);
void lock?.release().catch(() => {});
};
}, []);
const finish = async (res: Response | null) => {
setBusy(false);
if (!res?.ok) {
const code = res ? ((await res.json().catch(() => ({}))) as { error?: string }).error : undefined;
setError(code === "event_closed" ? "As impressões deste evento estão fechadas." : "Não foi possível enviar. Tenta outra vez.");
return;
}
const { status } = (await res.json()) as { status: string };
setScreen({ kind: "sent", status });
void load();
setTimeout(reset, THANKS_MS);
};
const printPhoto = async (photoId: string) => {
setBusy(true);
await finish(
await fetch(`/v1/public/print/${encodeURIComponent(slug)}/kiosk/pick`, {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ k: token, photoId, copies, ...(name.trim() && { name: name.trim() }) }),
}).catch(() => null),
);
};
const printShot = async (blob: Blob) => {
setBusy(true);
const form = new FormData();
form.append("k", token);
form.append("copies", String(copies));
if (name.trim()) form.append("name", name.trim());
form.append("file", blob, "photobooth.jpg");
await finish(await fetch(`/v1/public/print/${encodeURIComponent(slug)}/kiosk/capture`, { method: "POST", body: form }).catch(() => null));
};
const fullscreen = () => void document.documentElement.requestFullscreen?.().catch(() => {});
const shell: React.CSSProperties = { position: "fixed", inset: 0, zIndex: 1000, background: dark, color: "#f2f2f2", display: "flex", flexDirection: "column", fontFamily: "inherit", userSelect: "none", touchAction: "manipulation" };
if (failed || !token) return <div style={{ ...shell, alignItems: "center", justifyContent: "center", padding: 40, fontSize: 24, textAlign: "center" }}>{failed ?? "Falta o código do quiosque no link."}</div>;
if (!view) return <div style={{ ...shell, alignItems: "center", justifyContent: "center", fontSize: 24 }}>A carregar…</div>;
const price = view.priceCents ? `${(view.priceCents / 100).toFixed(2).replace(".", ",")} € por foto, paga no balcão` : null;
return (
<div style={shell}>
<header style={{ display: "flex", alignItems: "center", gap: 16, padding: "18px 28px", borderBottom: "1px solid #222" }}>
<div style={{ flex: 1 }}>
<div style={{ fontSize: 30, fontWeight: 800 }}>{view.name}</div>
<div style={{ fontSize: 16, color: "#9a9a9e" }}>
Impressão {view.size.replace("x", " × ")} cm{price ? ` · ${price}` : " · grátis"}
</div>
</div>
{screen.kind === "grid" && (
<button style={big} onClick={() => setScreen({ kind: "camera" })} disabled={!view.active}>
📷 Tirar foto
</button>
)}
<button style={{ ...ghost, height: 48, fontSize: 16, padding: "0 16px" }} onClick={fullscreen} aria-label="Ecrã inteiro">
⛶
</button>
</header>
<main style={{ flex: 1, overflow: "auto", position: "relative" }}>
{!view.active && <p style={{ padding: 40, fontSize: 26, textAlign: "center" }}>As impressões deste evento estão fechadas.</p>}
{view.active && screen.kind === "grid" && (
<>
{view.photos.length === 0 ? (
<p style={{ padding: 40, fontSize: 24, textAlign: "center", color: "#9a9a9e" }}>As fotos do fotógrafo aparecem aqui assim que chegarem. Entretanto, tira uma foto com o tablet.</p>
) : (
<div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(220px, 1fr))", gap: 10, padding: 16 }}>
{view.photos.map((p) => (
<button key={p.id} onClick={() => setScreen({ kind: "photo", id: p.id, preview: p.preview })} style={{ padding: 0, border: 0, background: "#1a1a1c", borderRadius: 10, overflow: "hidden", aspectRatio: "1", cursor: "pointer" }} aria-label="Escolher esta foto">
<img src={p.thumb} alt="" loading="lazy" style={{ width: "100%", height: "100%", objectFit: "cover", display: "block" }} />
</button>
))}
</div>
)}
</>
)}
{screen.kind === "camera" && <Camera onShot={(blob) => setScreen({ kind: "shot", blob, url: URL.createObjectURL(blob) })} onCancel={reset} />}
{(screen.kind === "photo" || screen.kind === "shot") && (
<div style={{ display: "grid", gridTemplateColumns: "minmax(0, 3fr) minmax(320px, 2fr)", gap: 28, padding: 28, height: "100%", boxSizing: "border-box" }}>
<div style={{ display: "flex", alignItems: "center", justifyContent: "center", minHeight: 0 }}>
<figure style={{ margin: 0, background: view.template.borderMm ? "#fff" : "transparent", padding: view.template.borderMm ? 12 : 0, maxHeight: "100%" }}>
<img src={screen.kind === "photo" ? screen.preview : screen.url} alt="" style={{ display: "block", maxWidth: "100%", maxHeight: "62vh", objectFit: "contain" }} />
{view.template.bandText && (
<figcaption style={{ background: view.template.bandColor, color: view.template.textColor, textAlign: "center", padding: "10px 8px", fontSize: 20, fontWeight: 600 }}>{view.template.bandText}</figcaption>
)}
</figure>
</div>
<div style={{ display: "flex", flexDirection: "column", gap: 20, justifyContent: "center" }}>
<label style={{ display: "grid", gap: 8, fontSize: 20 }}>
O teu nome (para te chamarmos)
<input value={name} onChange={(e) => setName(e.target.value)} maxLength={60} style={{ height: 64, fontSize: 26, padding: "0 16px", borderRadius: 12, border: "1px solid #333", background: "#18181a", color: "#fff" }} />
</label>
<div style={{ display: "flex", alignItems: "center", gap: 16, fontSize: 22 }}>
Cópias
<button style={{ ...ghost, width: 72, padding: 0 }} onClick={() => setCopies((c) => Math.max(1, c - 1))} aria-label="Menos uma cópia">
−
</button>
<span style={{ fontSize: 34, fontWeight: 800, minWidth: 40, textAlign: "center" }}>{copies}</span>
<button style={{ ...ghost, width: 72, padding: 0 }} onClick={() => setCopies((c) => Math.min(5, c + 1))} aria-label="Mais uma cópia">
+
</button>
</div>
{error && (
<p role="alert" style={{ color: "#ff8a8a", fontSize: 20, margin: 0 }}>
{error}
</p>
)}
<button style={big} disabled={busy} onClick={() => void (screen.kind === "photo" ? printPhoto(screen.id) : printShot(screen.blob))}>
{busy ? "A enviar…" : copies > 1 ? `Imprimir ${copies}` : "Imprimir"}
</button>
<button style={ghost} disabled={busy} onClick={() => (screen.kind === "shot" ? setScreen({ kind: "camera" }) : reset())}>
{screen.kind === "shot" ? "Repetir a foto" : "Voltar"}
</button>
</div>
</div>
)}
{screen.kind === "sent" && (
<div style={{ display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center", height: "100%", gap: 18, textAlign: "center", padding: 40 }}>
<div style={{ fontSize: 64 }}>✓</div>
<div style={{ fontSize: 40, fontWeight: 800 }}>{name.trim() ? `Obrigado, ${name.trim()}!` : "Obrigado!"}</div>
<div style={{ fontSize: 24, color: "#bdbdc2" }}>{screen.status === "APPROVAL" ? (view.payAtCounter ? "Paga no balcão e a foto sai logo a seguir." : "A foto sai assim que a equipa a aprovar.") : "A tua foto está na fila. Levanta-a junto da impressora."}</div>
<button style={ghost} onClick={reset}>
Começar de novo
</button>
</div>
)}
</main>
{view.jobs.length > 0 && screen.kind === "grid" && (
<footer style={{ display: "flex", gap: 12, padding: "12px 20px", borderTop: "1px solid #222", overflowX: "auto" }} aria-label="Últimas impressões">
{view.jobs.map((j) => (
<div key={j.id} style={{ display: "flex", alignItems: "center", gap: 10, background: "#18181a", borderRadius: 10, padding: 8, minWidth: 220 }}>
<img src={j.preview} alt="" style={{ width: 56, height: 56, objectFit: "cover", borderRadius: 6 }} />
<div>
<div style={{ fontSize: 16, fontWeight: 700 }}>{j.guestName ?? "Sem nome"}</div>
<div style={{ fontSize: 14, color: j.status === "DONE" ? "#7ad38a" : "#9a9a9e" }}>
{STATUS[j.status]}
{j.ahead > 0 && (j.status === "QUEUED" || j.status === "APPROVAL") ? ` · ${j.ahead} à frente` : ""}
</div>
</div>
</div>
))}
</footer>
)}
</div>
);
}
/** The photobooth: the tablet's front camera, a 3-2-1 countdown, then the picture (mirrored on screen, not on paper). */
function Camera({ onShot, onCancel }: { onShot: (blob: Blob) => void; onCancel: () => void }) {
const video = useRef<HTMLVideoElement>(null);
const [count, setCount] = useState<number | null>(null);
const [problem, setProblem] = useState<string | null>(null);
useEffect(() => {
let stream: MediaStream | null = null;
navigator.mediaDevices
?.getUserMedia({ video: { facingMode: "user", width: { ideal: 1920 }, height: { ideal: 1440 } }, audio: false })
.then((s) => {
stream = s;
if (video.current) {
video.current.srcObject = s;
void video.current.play();
}
})
.catch(() => setProblem("Não foi possível abrir a câmara. Autoriza a câmara neste browser."));
if (!navigator.mediaDevices) setProblem("Este browser não dá acesso à câmara.");
return () => stream?.getTracks().forEach((t) => t.stop());
}, []);
useEffect(() => {
if (count === null) return;
if (count === 0) {
const v = video.current;
if (!v || !v.videoWidth) return setCount(null);
const canvas = document.createElement("canvas");
canvas.width = v.videoWidth;
canvas.height = v.videoHeight;
canvas.getContext("2d")!.drawImage(v, 0, 0);
canvas.toBlob((b) => b && onShot(b), "image/jpeg", 0.92);
return;
}
const t = setTimeout(() => setCount(count - 1), 1000);
return () => clearTimeout(t);
}, [count, onShot]);
if (problem) {
return (
<div style={{ padding: 40, textAlign: "center", fontSize: 22 }}>
<p>{problem}</p>
<button style={ghost} onClick={onCancel}>
Voltar
</button>
</div>
);
}
return (
<div style={{ position: "relative", height: "100%", display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center", gap: 20, padding: 20, boxSizing: "border-box" }}>
<video ref={video} playsInline muted style={{ maxWidth: "100%", maxHeight: "70vh", borderRadius: 14, transform: "scaleX(-1)", background: "#000" }} />
{count !== null && count > 0 && <div style={{ position: "absolute", fontSize: 220, fontWeight: 900, color: "#fff", textShadow: "0 4px 30px rgba(0,0,0,.6)" }}>{count}</div>}
<div style={{ display: "flex", gap: 16 }}>
<button style={big} disabled={count !== null} onClick={() => setCount(3)}>
Tirar foto
</button>
<button style={ghost} onClick={onCancel}>
Voltar
</button>
</div>
</div>
);
}
@@ -0,0 +1,12 @@
import type { Metadata } from "next";
import { Kiosk } from "./Kiosk";
export const dynamic = "force-dynamic";
export const metadata: Metadata = { title: "Quiosque", robots: { index: false } };
/** Kiosk mode: a tablet at the event (link with its secret made in the app, Impressão → Quiosque). */
export default async function KioskPage({ params, searchParams }: { params: Promise<{ slug: string }>; searchParams: Promise<{ k?: string }> }) {
const { slug } = await params;
const { k } = await searchParams;
return <Kiosk slug={slug} token={k ?? ""} />;
}
+9
View File
@@ -6,6 +6,7 @@ import "@fontsource/barlow-condensed/800.css";
import "@fontsource/space-mono/400.css";
import "./globals.css";
import type { Metadata } from "next";
import { headers } from "next/headers";
import Link from "next/link";
import type { ReactNode } from "react";
import { CartLink } from "../components/CartLink";
@@ -27,6 +28,14 @@ export default async function RootLayout({ children }: { children: ReactNode })
site = await getSite();
} catch (err) {
if (!(err instanceof NotFound)) throw err;
// The events domain (events.photoreport.pt) has no storefront: its event pages (QR page, kiosk) stand alone.
if ((await headers()).get("x-pr-path")?.startsWith("/e/")) {
return (
<html lang="pt">
<body>{children}</body>
</html>
);
}
return (
<html lang="pt">
<body>
+8 -3
View File
@@ -1,10 +1,15 @@
import { type NextRequest, NextResponse } from "next/server";
/** An affiliate link (`?ref=CODE`) is remembered for 30 days; the order sends it and the API credits the affiliate. */
/**
* An affiliate link (`?ref=CODE`) is remembered for 30 days; the order sends it and the API credits the affiliate.
* The path is passed on to the layout (`x-pr-path`): the event pages (`/e/…`) work on a domain without a site.
*/
export function middleware(req: NextRequest) {
const headers = new Headers(req.headers);
headers.set("x-pr-path", req.nextUrl.pathname);
const ref = req.nextUrl.searchParams.get("ref")?.trim();
if (!ref || !/^[A-Za-z0-9_-]{3,40}$/.test(ref)) return NextResponse.next();
const res = NextResponse.next();
if (!ref || !/^[A-Za-z0-9_-]{3,40}$/.test(ref)) return NextResponse.next({ request: { headers } });
const res = NextResponse.next({ request: { headers } });
res.cookies.set("pr_ref", ref.toUpperCase(), { maxAge: 30 * 24 * 3600, path: "/", sameSite: "lax", secure: req.nextUrl.protocol === "https:" });
return res;
}
+12 -2
View File
@@ -132,6 +132,15 @@ it when files must be served from more than one host.
they agree. A package's price is spread over its photos, so order lines, VAT, shares and refunds work as before
(the line reads "<product> · <package>"); a press discount applies on top. The gallery page lists the packages
and has "Comprar todas" for the whole-gallery one. Orders take up to 1000 lines for that.
- Kiosk (Impressão → Quiosque; `/e/<slug>/quiosque?k=<secret>` on the events site): a tablet at the event shows
the photographer's photos big and the front camera as a photobooth (3-2-1, then the picture), takes the guest's
name and copies (1-5) and sends the print to the queue. Only the hash of the link's secret is kept; a new link
retires the old one. The tablet is shared and staffed, so the per-guest limit doesn't apply; on a paid event the
kiosk's prints wait for approval (paid at the counter) instead of going through Stripe. Full screen, screen kept
on, back to the start after a minute without a touch.
- Faces on edited photos: boxes are stored in the original frame; `GET /v1/photos/:id/faces` also gives each box in
the rendered preview's frame (`inPreview`, the crop and straighten of the snapshot it was rendered from; null when
cropped out), which is what the loupe draws (`apps/api/src/faces/frame.ts`).
- PATCH bodies are parsed with `patchOf(schema)` (contracts): zod's `.partial()` keeps defaults, which made a
title change turn a private gallery public; galleries, sites and print events use it.
- Products per organization: JPEG downloads (long edge, 0 = original) and prints (size, lead days); prices are
@@ -306,8 +315,9 @@ run on the `next` containers (the phase gate).
invoices through InvoiceXpress, press accounts on credit with a monthly invoice, photo packages, download
limits, FTP packages with quotas).
4. Events and printing (done: QR guest page, print layout with band and border, approval and limits, queue
in the app, print agent with CUPS and pairing, paper per printer, paid prints through Stripe. Open: kiosk mode
on a tablet, photobooth capture, Windows agent, a real event printed).
in the app, print agent with CUPS and pairing, paper per printer, paid prints through Stripe, kiosk mode on a
tablet with photobooth capture, Windows agent (spooler through PowerShell). Open: the Windows agent on real
hardware, a real event printed).
5. Player identification: faces (done: detect, group, confirm, propagate, suggest across events), jersey
numbers with squads, global search (parity with old projects validated).
6. Cutover: final import, redirects, old projects read-only, then switched off.
+9
View File
@@ -59,6 +59,8 @@ export interface PrintEventSummary {
template: PrintTemplate;
galleryId: string | null;
printerId: string | null;
/** A kiosk link is on (the link itself is only shown when made). */
kiosk: boolean;
counts: { waiting: number; printed: number };
}
@@ -116,6 +118,13 @@ export interface PublicPrintEvent {
photos: { id: string; thumb: string; preview: string }[];
}
/** What the kiosk (a tablet at the event, `/e/<slug>/quiosque?k=…`) shows: the event and its latest prints. */
export interface KioskView extends PublicPrintEvent {
/** Paid events: the kiosk sends prints for approval and the guest pays at the counter. */
payAtCounter: boolean;
jobs: { id: string; status: PrintJobStatus; guestName: string | null; ahead: number; preview: string; createdAt: string }[];
}
export interface GuestJob {
id: string;
status: PrintJobStatus;
+9
View File
@@ -565,6 +565,15 @@ export class ApiClient {
return this.request<PrintEventSummary>("POST", `/v1/orgs/${orgId}/print-events`, input);
}
/** A new kiosk link (path with its secret, shown once); the previous one stops working. */
enablePrintKiosk(id: string) {
return this.request<{ path: string }>("POST", `/v1/print-events/${id}/kiosk`);
}
disablePrintKiosk(id: string) {
return this.request<void>("DELETE", `/v1/print-events/${id}/kiosk`);
}
updatePrintEvent(id: string, input: Partial<PrintEventInput>) {
return this.request<PrintEventSummary>("PATCH", `/v1/print-events/${id}`, input);
}
+2
View File
@@ -271,6 +271,8 @@ export interface PhotoFace {
y0: number;
x1: number;
y1: number;
/** The box on the edited preview (crop and straighten applied); null: cropped out. */
inPreview: { x0: number; y0: number; x1: number; y1: number } | null;
score: number;
person: PersonSummary | null;
suggestion: PersonSummary | null;