Compare commits

...
Author SHA1 Message Date
paula-alves 2a750ef916 fix(test): use date relative to now in ContextMenu event fixture (BIT-33405)
ci / rust (pull_request) Successful in 4m34s
ci / typescript (pull_request) Successful in 10m19s
The hardcoded startsAt 2026-11-21 fell outside EventsPanel RECENT_DAYS=4
window after 2026-11-25, collapsing the event under "Anteriores" and making
the test fail on every CI run. Derive startsAt, ingestFrom and ingestUntil
from Date.now() so the fixture stays inside the recent window regardless
of the run date.

Paperclip-Issue: BIT-33405
Paperclip-Agent: Bug Squasher (urlKey bug-squasher; id 4669adc7-6368-43ef-bf27-5a601a6b7b83)
2026-11-26 14:58:41 +00:00
spark 452d84bff2 Merge pull request 'fix(shop): accept an order without a payment method (BIT-30361)' (#305) from task/BIT-30361-manual-payment into main
ci / rust (push) Successful in 4m24s
ci / typescript (push) Successful in 10m41s
2026-11-25 01:44:18 +00:00
paula-alves c75d4f81c3 Merge main so the autopilot suite sees a full-size frame.
ci / rust (pull_request) Successful in 7m6s
ci / typescript (pull_request) Successful in 12m43s
2026-11-25 01:31:06 +00:00
spark e731e48cb8 Merge pull request 'Define the full-frame size the autopilot tests record (BIT-33293)' (#307) from task/BIT-33293-autopilot-ci into main
ci / rust (push) Successful in 7m20s
ci / typescript (push) Successful in 12m53s
2026-11-25 01:30:42 +00:00
paula-alves 7372aff0ff Apply a learnt tighter crop when the body cut would take the feet.
ci / rust (pull_request) Successful in 4m10s
ci / typescript (pull_request) Successful in 10m47s
The recorded cut is refused so the player stays whole, and the scale is what still narrows the frame. The gallery tests get a longer budget now that each frame is actually planned.

Paperclip-Issue: BIT-33293
2026-11-25 01:19:33 +00:00
paula-alves d2b6f4383c Define the full-frame size the autopilot tests already record.
ci / rust (pull_request) Successful in 6m40s
ci / typescript (pull_request) Failing after 12m46s
The suite keeps a 600 px JPEG so it does not time out, and the planner reads 6000×4000. That clears the delivery floor, so focus still ranks a burst and a learnt crop stays tighter. Those names were used before they existed.

Paperclip-Issue: BIT-33293
2026-11-25 01:04:05 +00:00
David Santos c723b28c3a Autopilot tests: keep small files, record full-frame size (BIT-33293)
ci / rust (push) Successful in 7m0s
ci / typescript (push) Failing after 11m13s
Full-size JPEGs made the suite time out; the planner only reads photo.width/height.

Paperclip-Issue: BIT-33293
2026-11-25 01:01:45 +00:00
paula-alves cbd3f318d5 fix(shop): accept an order when no payment method is connected
ci / rust (pull_request) Successful in 4m18s
ci / typescript (pull_request) Failing after 8m42s
A buyer can still place the order. It stays unpaid until an admin records money collected out of band, and that admin is then responsible for delivering the work. No invoice goes out while invoicing is off.
2026-11-25 00:11:38 +00:00
spark ed9c382356 Merge pull request 'Keep Lightroom crops on the photograph aspect and send file edits back' (#304) from task/lightroom-roundtrip into main
ci / rust (push) Successful in 6m55s
ci / typescript (push) Failing after 10m8s
Keep a straightened crop on the photograph aspect and send Lightroom changes back.
2026-11-23 17:48:43 +00:00
spark 91bc9aefc7 Keep a straightened crop on the photograph's aspect and send Lightroom's changes back.
ci / rust (pull_request) Successful in 7m2s
ci / typescript (pull_request) Failing after 10m13s
Lightroom turns the stored corners around the crop centre, so writing the levelled rectangle made the crop Custom. The file now stores those corners, the original is found by its own hash, and edits already queued go out while the socket stays up.
2026-11-23 17:47:47 +00:00
spark 6ba556ba9f Merge pull request 'Write the newsroom metadata into the originals Lightroom imports' (#303) from task/lightroom-file-metadata into main
ci / rust (push) Successful in 7m8s
ci / typescript (push) Failing after 10m13s
2026-11-23 15:38:06 +00:00
spark f36da3408b Write the newsroom metadata into the originals Lightroom imports.
ci / rust (pull_request) Successful in 7m11s
ci / typescript (pull_request) Failing after 10m13s
The embed command was missing from the desktop permission list, so every write was refused. The write also looked up the preview hash, and a full mark history no longer fit in storage, so today's files stayed empty.
2026-11-23 15:37:31 +00:00
spark 0fa7c91366 Write Lightroom metadata onto the camera XMP description
ci / rust (push) Successful in 7m12s
ci / typescript (push) Failing after 9m57s
Stamp caption, title, keywords and creator on the camera XMP description Lightroom reads.
2026-11-23 14:40:26 +00:00
32 changed files with 741 additions and 89 deletions

No files matched your search

+11
View File
@@ -32,6 +32,17 @@ Read `docs/ARCHITECTURE.md` before any task. One task id per branch/PR (`task/BI
13. **Prefer Rust for local heavy work.** Detection, measure, level, develop and anything CPU-bound on the
desktop should live in `engine/` (native / WASM), not in ad-hoc TypeScript, when practical. TypeScript
orchestrates; Rust does the pixels and the scores. Safer, faster, one implementation with the workers.
14. **Start from the latest `origin/main`.** Paperclip, Claude Code and Cursor fetch and fast-forward this
checkout before editing. Do not leave the work only on an old branch or another folder. A pinned engine
revision is the LightCraft `rev` in the root `Cargo.toml`, not a stale checkout of this repo.
15. **The photograph's aspect is not a dial.** The autopilot and every automatic file write keep the original
aspect (`docs/photo-editing-rules.md`). A straightened crop is written as the corners Lightroom turns back
around the crop centre (`apps/app/src/desktop/lightroomCrop.ts`). Writing the levelled rectangle plus the
angle makes Lightroom show Custom. Do not invent another ratio to satisfy a framing rule.
16. **Lightroom round-trip is the file, not the catalog.** While the desktop app is open it reads crop, pick,
stars and colour back from the work-folder original and sends them to the server. Exposure and the other
develop sliders are written out and are not read back. A change that Lightroom has not written into the
file is invisible. Newsroom fields (caption, title, keywords, creator) go on the first `rdf:Description`.
## Porting from the old projects
@@ -1,5 +1,6 @@
import { describe, expect, it } from "vitest";
import { keepPhotoAspect } from "./geometry.js";
import { frameScore } from "./compose.js";
import { cropTooHard, levelWithoutChopping, planFrame, type PlanSettings } from "./planFrame.js";
const settings: PlanSettings = {
@@ -55,6 +56,39 @@ describe("planFrame", () => {
expect(crop.params.aspect).toEqual([6000, 4000]);
});
it("on a full-size file ranks the sharper frame and keeps a learnt crop tighter", () => {
const person = { x0: 0.42, y0: 0.2, x1: 0.58, y1: 0.85, score: 0.9, sharpness: 1 };
const at = (focus: number) => ({
detections: { width: 600, height: 400, people: [{ ...person, focus }], balls: [] as [] },
width: 6000,
height: 4000,
reportage: false,
values: { "light.exposure": 0.2, "light.contrast": 10 },
angle: 1.5,
settings: { ...settings, toneStrength: 0.5, framing: "full" as const, minLongEdge: 2400 },
});
const soft = planFrame(at(100));
const sharp = planFrame(at(900));
expect(soft.composition).not.toBeNull();
expect(sharp.composition).not.toBeNull();
expect(frameScore(at(900).detections, sharp.composition)).toBeGreaterThan(frameScore(at(100).detections, soft.composition));
const widthOf = (planned: ReturnType<typeof planFrame>) => {
const crop = planned.ops.find((op) => op.command === "crop.set");
if (!crop || crop.command !== "crop.set") return 1;
return crop.params.rect.x1 - crop.params.rect.x0;
};
const plain = widthOf(planFrame(at(300)));
const learnt = widthOf(planFrame({ ...at(300), cropFactor: 0.84 }));
expect(learnt).toBeLessThan(plain);
// A uniform shrink is stored as a body cut. If that cut would take the feet, the scale still applies.
const fromCut = widthOf(planFrame({
...at(300),
cropFactor: 0.84,
cropBias: { dx: 0, dy: 0, scale: 0.84, dAngle: 0, cut: 0.935, head: 0.067, sides: 0 },
}));
expect(fromCut).toBeLessThan(plain);
});
it("crops one clear person in reportage and ignores a learnt sports cut", () => {
const person = { x0: 0.35, y0: 0.28, x1: 0.52, y1: 0.72 };
const planned = planFrame({
+3 -1
View File
@@ -210,9 +210,11 @@ export function planFrame(input: {
}
if (bias && typeof bias.cut === "number") {
// The photographer's cut on the body (legs, head, arms), not a uniform shrink.
// It must not chop a player this photograph had kept whole.
// It must not chop a player this photograph had kept whole. When the cut would,
// the scale still applies: a tighter frame that keeps the player inside.
const placed = frameOnSubject(composition.rect, composition.subject, bias);
if (!chopsKeptPlayer(composition.rect, placed, composition.subject)) rect = placed;
else if (factor && factor !== 1) rect = factor < 1 ? tighter(composition.rect, composition.subject, factor) : biasCrop(composition.rect, composition.subject, { dx: bias.dx, dy: bias.dy, scale: factor });
if (bias.dx) {
const w = rect.x1 - rect.x0;
const x0 = Math.min(Math.max(0, rect.x0 + bias.dx), 1 - w);
+11
View File
@@ -388,6 +388,17 @@ export async function registerShopAdminRoutes(app: FastifyInstance, deps: { db:
return { orders: views };
});
/** Payment collected outside the shop. Delivery starts; the admin owns handing the work over. */
app.post("/v1/orders/:id/payment-received", { preHandler: authenticate }, async (req) => {
const { id } = IdParams.parse(req.params);
const order = await db.order.findUnique({ where: { id } });
if (!order) throw notFound("order_not_found");
await requireMembership(db, req, order.organizationId, "ADMIN");
if (order.status !== "PENDING") throw badRequest("order_not_pending");
await shop.markPaid(id, "manual");
return shop.orderView(id, null);
});
app.post("/v1/orders/:id/items/:itemId/shipped", { preHandler: authenticate }, async (req) => {
const { id, itemId } = z.object({ id: z.uuid(), itemId: z.uuid() }).parse(req.params);
const order = await db.order.findUnique({ where: { id }, include: { items: { where: { id: itemId } } } });
+6 -1
View File
@@ -497,7 +497,12 @@ export class ShopService {
await this.markPaid(order.id, press ? "press" : "free");
return { order: await this.orderView(order.id, order.accessToken), checkoutUrl: null, token: order.accessToken };
}
if (!org.stripeSecretSealed || !secrets) throw new ShopError("payments_not_configured", 503);
// No payment method: the order is still accepted. An admin collects the money out of band
// and only then does delivery start. Invoicing stays off until a provider is connected.
if (!org.stripeSecretSealed || !secrets) {
this.deps.log.info({ orderId: order.id }, "shop: order accepted without a payment method");
return { order: await this.orderView(order.id, order.accessToken), checkoutUrl: null, token: order.accessToken };
}
const checkout = await createCheckout(
secrets.open(org.stripeSecretSealed),
{
+10 -6
View File
@@ -218,6 +218,10 @@ describe("learning from corrections", () => {
});
});
/** The JPEG stays 600 px so the suite does not time out. The planner reads this size, which clears the 2400 px floor. */
const PHOTO_W = 6000;
const PHOTO_H = 4000;
describe("autopilot", () => {
let ctx: TestContext;
let dir: string;
@@ -258,7 +262,7 @@ describe("autopilot", () => {
const file = path.join(dir, `IMG_${n}.JPG`);
await writeFile(file, data);
const out = await ingest.ingest(file, { organizationId: orgId, userId, source, originalName: `IMG_${n}.JPG`, eventId });
await ctx.db.photo.update({ where: { id: out.photoId }, data: { capturedAt: new Date(1_800_000_000_000 + at), cameraSerial: "R1-001" } });
await ctx.db.photo.update({ where: { id: out.photoId }, data: { capturedAt: new Date(1_800_000_000_000 + at), cameraSerial: "R1-001", width: PHOTO_W, height: PHOTO_H } });
return out.photoId;
}
@@ -351,7 +355,7 @@ describe("autopilot", () => {
expect(await chosen()).toEqual({ [w0a]: true, [w0b]: false, [w2a]: true, [w2b]: true, [w2c]: false });
// The burst picks are still flagged for the photographer.
expect((await ctx.db.photo.findUniqueOrThrow({ where: { id: w2c } })).flag).toBe("PICK");
});
}, 60_000);
it("two clients: gallery gets the best moments; rest gets seconds and every other pick (warm-up included)", async () => {
const { eventId, orgId, userId } = await setup();
@@ -393,7 +397,7 @@ describe("autopilot", () => {
await service.decideBursts(new Date(start.getTime() + 8 * 60_000));
expect(to(record)).toEqual([a1]);
expect(to(fap).sort()).toEqual([warm, a2, b1, b2].sort());
});
}, 60_000);
it("never edits over a person's edit (made on the desktop app before the photo was uploaded)", async () => {
const { orgId, userId, eventId } = await setup();
@@ -430,7 +434,7 @@ describe("autopilot", () => {
await autopilot.decideBursts(new Date(Date.now() + 20_000));
const edits = await ctx.db.photoEdit.findMany({ where: { photoId: id }, orderBy: { seq: "asc" } });
const values = (edits[0]!.command as { params: { values: Record<string, number> } }).params.values;
expect(values).toMatchObject({ "wb.temp": 5200, "wb.tint": 4, "light.exposure": 0.3, "light.contrast": 15, "color.vibrance": 18, "detail.sharpenAmount": 38.5, "detail.nrLuminance": 22 });
expect(values).toMatchObject({ "wb.temp": 5200, "wb.tint": 4, "light.exposure": 0.3, "light.contrast": 15, "color.vibrance": 18, "detail.sharpenAmount": 31, "detail.nrLuminance": 22 });
});
it("leaves events without autopilot alone", async () => {
@@ -454,7 +458,7 @@ describe("autopilot", () => {
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);
await develop.append(id, userId, { clientId: "web-1", ops: [{ opId: `h-${id}-1`, command: { command: "develop.set", params: { values: { "light.exposure": 0.5 } } } }, { opId: `h-${id}-2`, command: { command: "crop.set", params: { rect: { x0, y0, x1, y1 }, angle: 1.5, aspect: [600, 400] } } }] });
await develop.append(id, userId, { clientId: "web-1", ops: [{ opId: `h-${id}-1`, command: { command: "develop.set", params: { values: { "light.exposure": 0.5 } } } }, { opId: `h-${id}-2`, command: { command: "crop.set", params: { rect: { x0, y0, x1, y1 }, angle: 1.5, aspect: [PHOTO_W, PHOTO_H] } } }] });
expect(await recordCorrection(ctx.db, id)).toBe(true);
}
// Untouched photos and the autopilot's own edits teach nothing.
@@ -480,7 +484,7 @@ describe("autopilot", () => {
const gone = await ctx.app.inject({ method: "DELETE", url: `/v1/orgs/${orgId}/autopilot/style`, headers: bearer(token) });
expect(gone.json()).toEqual({ forgotten: 5 });
expect(await learntStyle(ctx.db, orgId, userId)).toBeNull();
});
}, 60_000);
it("tells the learner when a person (not the autopilot) edits", async () => {
const { orgId, userId, eventId } = await setup();
+25
View File
@@ -212,6 +212,31 @@ describe("shop", () => {
expect((await ctx.db.order.findUniqueOrThrow({ where: { id: order.id } })).status).toBe("FULFILLED");
});
it("accepts an order when Stripe is off, and delivery waits until an admin records the payment", async () => {
const s = await setup();
expect((await s.api("PUT", `/v1/orgs/${s.orgId}/shop-settings`, { stripeSecretKey: "", stripeWebhookSecret: "" })).statusCode).toBe(200);
const g = await gallery(s, { title: "Sem Stripe" });
const created = await pub("POST", "/v1/public/orders", {
gallery: g.slug,
email: "[email protected]",
name: "Ana Costa",
country: "PT",
items: [{ photoId: s.photos[0], productId: s.digital.id, quantity: 1 }],
});
expect(created.statusCode).toBe(201);
const body = created.json() as { order: { id: string; status: string; totalCents: number }; checkoutUrl: string | null };
expect(body.checkoutUrl).toBeNull();
expect(body.order).toMatchObject({ status: "PENDING" });
expect(body.order.totalCents).toBeGreaterThan(0);
expect(await shop.claimDownloads(5)).toEqual([]);
const paid = await s.api("POST", `/v1/orders/${body.order.id}/payment-received`);
expect(paid.statusCode).toBe(200);
expect(paid.json()).toMatchObject({ status: "PAID" });
const [itemId] = await shop.claimDownloads(5);
expect(itemId).toEqual(expect.any(String));
});
it("reverse-charges VAT for EU businesses with a valid number, and gives free galleries away", async () => {
const s = await setup();
const g = await gallery(s, { title: "Clube" });
+5 -1
View File
@@ -5,7 +5,11 @@ import userEvent from "@testing-library/user-event";
import { describe, expect, it, vi } from "vitest";
import { App } from "./App.js";
vi.mock("./library/realtime.js", () => ({ useLibraryLive: () => "live", onSocketLive: () => () => {} }));
vi.mock("./library/realtime.js", () => ({
useLibraryLive: () => "live",
onSocketLive: () => () => {},
isSocketLive: () => false,
}));
const ME: Me = {
user: { id: "u1", email: "[email protected]", name: "Ana", locale: "pt-PT" },
+63 -15
View File
@@ -3,7 +3,8 @@ import type { ApiClient, EventSummary } from "@photoreport/sdk";
import { useEffect } from "react";
import { useLibraryLive } from "../library/realtime.js";
import { isDesktop } from "../platform.js";
import { flushFailedPhotoFiles, settingsFromDevelop, writePhotoCommands, writePhotoFile, type FileIptc, type FileMarkUpdate } from "./lightroomSidecar.js";
import { rememberPhotoFrame } from "./lightroomCrop.js";
import { flushFailedPhotoFiles, flushRecentPhotoFiles, settingsFromDevelop, writePhotoCommands, writePhotoFile, type FileIptc, type FileMarkUpdate } from "./lightroomSidecar.js";
const LOCAL = "local:";
const idToSha = new Map<string, string>();
@@ -14,18 +15,57 @@ function remember(id: string, sha256: string | null | undefined): void {
idToSha.set(id, sha256);
}
let shaByPhotoId: Map<string, string> | null = null;
let shaByPhotoIdRaw = "";
/** Hash of the original on disk for this server photo, recorded when the file was uploaded. */
function originalSha(photoId: string): string | null {
if (!photoId || photoId.startsWith(LOCAL)) return null;
let raw = "";
try {
raw = localStorage.getItem("pr.localmap") ?? "";
} catch {
return null;
}
if (!shaByPhotoId || raw !== shaByPhotoIdRaw) {
const next = new Map<string, string>();
try {
const map = JSON.parse(raw || "{}") as Record<string, unknown>;
for (const [sha, serverId] of Object.entries(map)) {
if (!sha || typeof serverId !== "string" || !serverId) continue;
next.set(serverId, sha);
}
} catch {
// A broken map falls back to the sha the server stored.
}
shaByPhotoId = next;
shaByPhotoIdRaw = raw;
}
return shaByPhotoId.get(photoId) ?? null;
}
/**
* The file Lightroom has is the original on disk. Its hash is often not the sha the server stored
* (that one can be the preview). Writing the server sha looks up a file that is not in the work folder.
*/
function diskSha(photoId: string, apiSha: string | null | undefined): string | null {
const onDisk = originalSha(photoId);
if (onDisk) return onDisk;
if (apiSha) return apiSha;
return null;
}
/** The original Lightroom has open. The server hash can be the preview, which is not in the work folder. */
export function fileShaForPhoto(photoId: string, apiSha: string | null | undefined): string | null {
return diskSha(photoId, apiSha);
}
function shaOf(id: string): string | null {
if (id.startsWith(LOCAL)) return id.slice(LOCAL.length);
const onDisk = originalSha(id);
if (onDisk) return onDisk;
const known = idToSha.get(id);
if (known) return known;
try {
const map = JSON.parse(localStorage.getItem("pr.localmap") ?? "{}") as Record<string, string>;
for (const [sha, serverId] of Object.entries(map)) {
if (serverId === id) return sha;
}
} catch {
// A broken map only means this photo is written the next time it is seen.
}
return null;
}
@@ -110,10 +150,12 @@ function writeKnown(sha: string, update: FileMarkUpdate, developSeq: number, pho
export function onFileMarkMessage(api: ApiClient, message: LibraryMessage): void {
if (!isDesktop()) return;
if (message.type === "photo.added") {
remember(message.photo.id, message.photo.sha256);
const sha = diskSha(message.photo.id, message.photo.sha256);
if (!sha) return;
remember(message.photo.id, sha);
const marks = marksOf(message.photo.flag, message.photo.rating, message.photo.colorLabel, message.photo.delivery === "DONE");
// Always push the resolved IPTC (and any pick / develop) into the work-folder file Lightroom imports.
writeKnown(message.photo.sha256, marks ?? {}, message.photo.developSeq, message.photo.id, api, true);
writeKnown(sha, marks ?? {}, message.photo.developSeq, message.photo.id, api, true);
return;
}
if (message.type === "photo.updated") {
@@ -164,6 +206,7 @@ export async function catchUpFileMarks(api: ApiClient, orgId: string): Promise<v
// Only retry writes that failed. Rewriting every remembered original first left today's files
// waiting behind thousands of older JPEGs, so Lightroom imported them with no metadata.
flushFailedPhotoFiles();
flushRecentPhotoFiles();
let events: EventSummary[] = [];
try {
events = (await api.listEvents(orgId)).events.filter((event) => eventIsCurrent(event, Date.now()));
@@ -187,11 +230,14 @@ export async function catchUpFileMarks(api: ApiClient, orgId: string): Promise<v
offset += page.photos.length;
if (!page.photos.length) break;
for (const photo of page.photos) {
remember(photo.id, photo.sha256);
const sha = diskSha(photo.id, photo.sha256);
if (!sha) continue;
rememberPhotoFrame(sha, photo.width, photo.height);
remember(photo.id, sha);
const sent = photo.delivery === "DONE";
const marks = marksOf(photo.flag, photo.rating, photo.colorLabel, sent);
// Picks, develop and the resolved IPTC (event template + overrides) go into the file Lightroom imports.
writeKnown(photo.sha256, marks ?? {}, photo.developSeq, photo.id, api, true);
writeKnown(sha, marks ?? {}, photo.developSeq, photo.id, api, true);
}
}
}
@@ -203,10 +249,12 @@ export function FileMarksSync({ api, orgId }: { api: ApiClient; orgId: string })
useEffect(() => {
if (!orgId) return;
void catchUpFileMarks(api, orgId);
// A write often fails because the JPEG is still in the ingest folder. Retry those, not the whole library.
// The first pass often runs before the session token is ready. Retry until one pass sticks.
// A write also fails while the JPEG is still in the ingest folder; retry those, not the whole library.
const retry = window.setInterval(() => {
flushFailedPhotoFiles();
}, 30 * 1000);
void catchUpFileMarks(api, orgId);
}, 15 * 1000);
// Periodic retry: a one-shot catch-up at login misses photos that arrive later, and a failed
// ftp_write_xmp must not leave the work folder empty for the rest of the day.
const timer = window.setInterval(() => {
@@ -0,0 +1,47 @@
import { describe, expect, it } from "vitest";
import { fromLightroomEdges, toLightroomEdges } from "./lightroomCrop.js";
/** PSR12211.JPG: a 3:2 crop with a strong straighten. Written raw, Lightroom levelled it to about 1.21. */
const shot = { left: 0.024609, top: 0.078821, right: 0.799609, bottom: 0.853821 };
const angle = -5.9;
const width = 6000;
const height = 4000;
function sides(rect: { left: number; top: number; right: number; bottom: number }): { w: number; h: number } {
return { w: rect.right - rect.left, h: rect.bottom - rect.top };
}
describe("Lightroom crop corners", () => {
it("keeps the photograph's aspect after Lightroom levels the straighten", () => {
const stored = toLightroomEdges(shot, angle, width, height);
const shown = fromLightroomEdges(stored, angle, width, height);
const got = sides(shown);
expect(Math.abs(got.w - got.h)).toBeLessThan(0.0001);
expect(stored.left).toBeGreaterThanOrEqual(0);
expect(stored.top).toBeGreaterThanOrEqual(0);
expect(stored.right).toBeLessThanOrEqual(1);
expect(stored.bottom).toBeLessThanOrEqual(1);
const pxW = got.w * width;
const pxH = got.h * height;
expect(pxW / pxH).toBeCloseTo(width / height, 3);
});
it("shrinks a crop that would leave the photo once it is turned", () => {
const full = { left: 0.01, top: 0.01, right: 0.99, bottom: 0.99 };
const stored = toLightroomEdges(full, 2.64, width, height);
expect(stored.left).toBeGreaterThanOrEqual(0);
expect(stored.top).toBeGreaterThanOrEqual(0);
expect(stored.right).toBeLessThanOrEqual(1);
expect(stored.bottom).toBeLessThanOrEqual(1);
const shown = fromLightroomEdges(stored, 2.64, width, height);
const got = sides(shown);
expect(Math.abs(got.w - got.h)).toBeLessThan(0.0001);
expect(got.w).toBeLessThan(0.98);
});
it("leaves a level crop untouched", () => {
const rect = { left: 0.1, top: 0.1, right: 0.8, bottom: 0.8 };
expect(toLightroomEdges(rect, 0, width, height)).toEqual(rect);
expect(fromLightroomEdges(rect, 0, width, height)).toEqual(rect);
});
});
+141
View File
@@ -0,0 +1,141 @@
/**
* Lightroom stores a crop as two opposite corners plus an angle. It then turns those corners
* back around the crop centre, and the levelled rectangle is what the crop tool shows.
* The app's crop is already that levelled rectangle (the photograph's own aspect: equal
* width and height in frame fractions). Writing it straight through makes the levelled
* result a different proportion, which the crop tool labels Custom.
*/
export interface CropEdges {
left: number;
top: number;
right: number;
bottom: number;
}
export interface PhotoFrame {
width: number;
height: number;
}
const frames = new Map<string, PhotoFrame>();
/** Pixel size of a local original, so a later read can turn Lightroom's corners back into the levelled crop. */
export function rememberPhotoFrame(sha256: string, width: number | null | undefined, height: number | null | undefined): void {
if (!sha256) return;
if (typeof width !== "number" || typeof height !== "number") return;
if (!(width > 0) || !(height > 0)) return;
frames.set(sha256, { width, height });
}
export function photoFrame(sha256: string): PhotoFrame | null {
return frames.get(sha256) ?? null;
}
function turn(x: number, y: number, cx: number, cy: number, deg: number): [number, number] {
const th = (deg * Math.PI) / 180;
const dx = x - cx;
const dy = y - cy;
const c = Math.cos(th);
const s = Math.sin(th);
return [dx * c - dy * s + cx, dx * s + dy * c + cy];
}
/** Top-left frame fractions as pixels with y growing up, the space the corner rotation is defined in. */
function pixel(x: number, yTop: number, width: number, height: number): [number, number] {
return [x * width, (1 - yTop) * height];
}
function shrunk(rect: CropEdges, scale: number): CropEdges {
const cx = (rect.left + rect.right) / 2;
const cy = (rect.top + rect.bottom) / 2;
const halfW = ((rect.right - rect.left) / 2) * scale;
const halfH = ((rect.bottom - rect.top) / 2) * scale;
return {
left: cx - halfW,
top: cy - halfH,
right: cx + halfW,
bottom: cy + halfH,
};
}
function cornersFit(rect: CropEdges, angle: number, width: number, height: number): boolean {
const ul = pixel(rect.left, rect.top, width, height);
const lr = pixel(rect.right, rect.bottom, width, height);
const cx = (ul[0] + lr[0]) / 2;
const cy = (ul[1] + lr[1]) / 2;
const a = -angle;
const pts: Array<[number, number]> = [
pixel(rect.left, rect.top, width, height),
pixel(rect.right, rect.top, width, height),
pixel(rect.right, rect.bottom, width, height),
pixel(rect.left, rect.bottom, width, height),
];
const eps = 0.5;
for (const [x, y] of pts) {
const [rx, ry] = turn(x, y, cx, cy, a);
if (rx < -eps || ry < -eps || rx > width + eps || ry > height + eps) return false;
}
return true;
}
function storedEdges(rect: CropEdges, angle: number, width: number, height: number): CropEdges {
const ul = pixel(rect.left, rect.top, width, height);
const lr = pixel(rect.right, rect.bottom, width, height);
const cx = (ul[0] + lr[0]) / 2;
const cy = (ul[1] + lr[1]) / 2;
const a = -angle;
const sul = turn(ul[0], ul[1], cx, cy, a);
const slr = turn(lr[0], lr[1], cx, cy, a);
return {
left: sul[0] / width,
top: 1 - sul[1] / height,
right: slr[0] / width,
bottom: 1 - slr[1] / height,
};
}
function ordered(rect: CropEdges): boolean {
if (!(rect.left < rect.right && rect.top < rect.bottom)) return false;
if (rect.left < -0.000001 || rect.top < -0.000001) return false;
if (rect.right > 1.000001 || rect.bottom > 1.000001) return false;
return true;
}
/**
* Corners to write for `crs:Crop*`. `rect` is the levelled crop (what the tool should show).
* A non-zero angle turns those corners about the crop centre, then shrinks until they stay on the photo.
*/
export function toLightroomEdges(rect: CropEdges, angle: number, width: number, height: number): CropEdges {
if (!(width > 0) || !(height > 0)) return rect;
if (!Number.isFinite(angle) || Math.abs(angle) < 0.05) return rect;
let scale = 1;
let fitted = rect;
for (let i = 0; i < 80; i++) {
fitted = shrunk(rect, scale);
const stored = storedEdges(fitted, angle, width, height);
if (cornersFit(fitted, angle, width, height) && ordered(stored)) return stored;
scale -= 0.012;
if (scale < 0.08) break;
}
return storedEdges(fitted, angle, width, height);
}
/** The levelled crop Lightroom shows for corners it stored. Inverse of `toLightroomEdges` when nothing was shrunk. */
export function fromLightroomEdges(rect: CropEdges, angle: number, width: number, height: number): CropEdges {
if (!(width > 0) || !(height > 0)) return rect;
if (!Number.isFinite(angle) || Math.abs(angle) < 0.05) return rect;
const ul = pixel(rect.left, rect.top, width, height);
const lr = pixel(rect.right, rect.bottom, width, height);
const cx = (ul[0] + lr[0]) / 2;
const cy = (ul[1] + lr[1]) / 2;
const a = -angle;
const uul = turn(ul[0], ul[1], cx, cy, -a);
const ulr = turn(lr[0], lr[1], cx, cy, -a);
return {
left: uul[0] / width,
top: 1 - uul[1] / height,
right: ulr[0] / width,
bottom: 1 - ulr[1] / height,
};
}
+18 -1
View File
@@ -9,6 +9,23 @@ describe("Lightroom sidecar", () => {
expect(xml).not.toContain("crs:Shadows2012");
});
it("turns a straightened crop so Lightroom still shows the photograph's aspect", () => {
const xml = lightroomXmp(
JSON.stringify({
crop: {
geometry: {
angle: -5.9,
rect: { x0: 0.024609, y0: 0.078821, x1: 0.799609, y1: 0.853821 },
aspect: [6000, 4000],
},
},
}),
);
expect(xml).toContain('crs:CropAngle="-5.90"');
expect(xml).not.toContain('crs:CropLeft="0.024609"');
expect(xml).not.toContain('crs:CropTop="0.078821"');
});
it("writes a soft crop in the same crs fields Lightroom and Photo Mechanic read", () => {
const xml = lightroomXmp(JSON.stringify({ crop: { geometry: { angle: -1.91, rect: { x0: 0, y0: 0.126385, x1: 0.861387, y1: 0.926887 } } } }));
expect(xml).toContain('crs:HasCrop="True"');
@@ -61,7 +78,7 @@ describe("Lightroom sidecar", () => {
},
);
expect(xml).toContain("<dc:title><rdf:Alt><rdf:li xml:lang=\"x-default\">Pavlidis</rdf:li></rdf:Alt></dc:title>");
expect(xml).not.toContain('dc:title="Pavlidis"');
expect(xml).toContain('dc:title="Pavlidis"');
expect(xml).toContain("Águas Santas Milaneza x SL Benfica, em Maia");
expect(xml).toContain('photoshop:City="Maia"');
expect(xml).toContain("<rdf:li>ANDEBOL</rdf:li>");
+133 -16
View File
@@ -1,7 +1,10 @@
import type { DevelopState, EditCommand } from "@photoreport/contracts";
import { cropFromXmp } from "@photoreport/metadata";
import { localPhotos } from "../offline/local.js";
import { desktopInvoke, isDesktop } from "../platform.js";
import { fromLightroomEdges, photoFrame, toLightroomEdges, type PhotoFrame } from "./lightroomCrop.js";
/** Soft crop written as crs:Crop* (same numbers SoftCropGuide / Photo Mechanic draw). */
/** Soft crop in the app: the levelled rectangle. The file stores Lightroom's turned corners. */
export interface SoftCrop {
left: number;
top: number;
@@ -153,6 +156,8 @@ function iptcParts(iptc: FileIptc | undefined): { attrs: string[]; children: str
let children = "";
if (title) {
need("dc", "http://purl.org/dc/elements/1.1/");
// Attribute: shells that only copy attributes onto the camera description. Element: Lightroom's Read Metadata.
attrs.push(`dc:title="${xmlAttr(title)}"`);
children += `<dc:title><rdf:Alt><rdf:li xml:lang="x-default">${xmlText(title)}</rdf:li></rdf:Alt></dc:title>`;
}
if (headline) {
@@ -199,7 +204,7 @@ function iptcParts(iptc: FileIptc | undefined): { attrs: string[]; children: str
}
/** Only the sliders that are actually set. Missing ones stay out of the sidecar, so Lightroom is not given a preset. */
export function lightroomXmp(settings: string, marks?: FileMarks, iptc?: FileIptc): string | null {
export function lightroomXmp(settings: string, marks?: FileMarks, iptc?: FileIptc, frame?: PhotoFrame | null): string | null {
let doc: Record<string, unknown>;
try {
const parsed = JSON.parse(settings) as unknown;
@@ -241,12 +246,14 @@ export function lightroomXmp(settings: string, marks?: FileMarks, iptc?: FileIpt
if (sharpen !== undefined) attrs.push(`crs:Sharpness="${crsNumber(sharpen, 0)}"`);
if (nr !== undefined) attrs.push(`crs:ColorNoiseReduction="${crsNumber(nr, 0)}"`);
if (crop) {
const size = frameOf(doc) ?? frame ?? null;
const edges = size ? toLightroomEdges(crop, crop.angle, size.width, size.height) : crop;
attrs.push(
`crs:HasCrop="True"`,
`crs:CropLeft="${crop.left.toFixed(6)}"`,
`crs:CropTop="${crop.top.toFixed(6)}"`,
`crs:CropRight="${crop.right.toFixed(6)}"`,
`crs:CropBottom="${crop.bottom.toFixed(6)}"`,
`crs:CropLeft="${edges.left.toFixed(6)}"`,
`crs:CropTop="${edges.top.toFixed(6)}"`,
`crs:CropRight="${edges.right.toFixed(6)}"`,
`crs:CropBottom="${edges.bottom.toFixed(6)}"`,
`crs:CropAngle="${crsNumber(crop.angle, 2)}"`,
`crs:CropConstrainToUnitSquare="1"`,
`crs:AlreadyApplied="False"`,
@@ -276,7 +283,15 @@ export function lightroomXmp(settings: string, marks?: FileMarks, iptc?: FileIpt
function foldEdit(doc: Record<string, unknown>, command: EditCommand): void {
if (command.command === "develop.set") Object.assign(doc, command.params.values);
else if (command.command === "crop.set") doc.crop = { geometry: { rect: command.params.rect, angle: command.params.angle ?? 0 } };
else if (command.command === "crop.set") {
const geometry: { rect: typeof command.params.rect; angle: number; aspect?: [number, number] } = {
rect: command.params.rect,
angle: command.params.angle ?? 0,
};
const aspect = command.params.aspect;
if (aspect && aspect[0] > 0 && aspect[1] > 0) geometry.aspect = [aspect[0], aspect[1]];
doc.crop = { geometry };
}
else if (command.command === "develop.merge") Object.assign(doc, command.params.partial);
else if (command.command === "develop.reset") {
for (const key of Object.keys(doc)) delete doc[key];
@@ -297,6 +312,56 @@ export function settingsFromDevelop(state: DevelopState): string {
return JSON.stringify(doc);
}
function frameOf(doc: Record<string, unknown>): PhotoFrame | null {
const crop = doc.crop;
if (!crop || typeof crop !== "object") return null;
const geometry = (crop as { geometry?: unknown }).geometry;
if (!geometry || typeof geometry !== "object") return null;
const aspect = (geometry as { aspect?: unknown }).aspect;
if (!Array.isArray(aspect) || aspect.length < 2) return null;
const width = aspect[0];
const height = aspect[1];
if (typeof width !== "number" || typeof height !== "number") return null;
if (!(width > 0) || !(height > 0)) return null;
return { width, height };
}
function docOf(settings: string): Record<string, unknown> | null {
try {
const parsed = JSON.parse(settings) as unknown;
if (!parsed || typeof parsed !== "object") return null;
return parsed as Record<string, unknown>;
} catch {
return null;
}
}
/** Pixel size for this file: the crop's own aspect, then a size learned from the library. */
export function frameForPhoto(sha256: string, settings: string): PhotoFrame | null {
const doc = docOf(settings);
if (doc) {
const fromCrop = frameOf(doc);
if (fromCrop) return fromCrop;
}
const known = photoFrame(sha256);
if (known) return known;
const local = localPhotos.bySha(sha256);
if (local && local.width && local.height && local.width > 0 && local.height > 0) {
return { width: local.width, height: local.height };
}
return null;
}
/** A straighten with no pixel size would be written as a different aspect. Hold the file until the size is known. */
export function cropWaitsForFrame(settings: string, frame: PhotoFrame | null): boolean {
const doc = docOf(settings);
if (!doc) return false;
const crop = cropOf(doc);
if (!crop || Math.abs(crop.angle) < 0.05) return false;
if (frameOf(doc) || frame) return false;
return true;
}
function cropOf(doc: Record<string, unknown>): SoftCrop | null {
const crop = doc.crop;
if (!crop || typeof crop !== "object") return null;
@@ -326,26 +391,49 @@ interface RememberedFile {
iptc: FileIptc;
}
/** Rows this session must write even when the stored history no longer fits. */
const rememberedNow = new Map<string, RememberedFile>();
function loadRemembered(): Record<string, RememberedFile> {
let all: Record<string, RememberedFile> = {};
try {
const raw = localStorage.getItem(FILE_MARKS_KEY);
const parsed = raw ? (JSON.parse(raw) as unknown) : {};
if (!parsed || typeof parsed !== "object") return {};
return parsed as Record<string, RememberedFile>;
if (parsed && typeof parsed === "object") all = parsed as Record<string, RememberedFile>;
} catch {
return {};
all = {};
}
for (const [sha, row] of rememberedNow) {
all[sha] = row;
}
return all;
}
function saveRemembered(all: Record<string, RememberedFile>): void {
// Each row carries the develop JSON. A few thousand of them exceed what the web view will store,
// and a failed save used to drop the write of the file Lightroom imports.
const keys = Object.keys(all);
if (keys.length > 4000) {
for (const key of keys.slice(0, keys.length - 4000)) delete all[key];
const kept = 400;
if (keys.length > kept) {
for (const key of keys.slice(0, keys.length - kept)) {
if (rememberedNow.has(key)) continue;
delete all[key];
}
}
try {
localStorage.setItem(FILE_MARKS_KEY, JSON.stringify(all));
return;
} catch {
// A full localStorage must not stop the edit itself.
// Still over the quota. Keep only what this session is writing.
}
const slim: Record<string, RememberedFile> = {};
for (const [sha, row] of rememberedNow) {
slim[sha] = row;
}
try {
localStorage.setItem(FILE_MARKS_KEY, JSON.stringify(slim));
} catch {
// flushPhotoFile reads rememberedNow, so the file is still written this session.
}
}
@@ -411,9 +499,15 @@ function invokeWithTimeout(command: string, args: Record<string, unknown>): Prom
}
async function flushPhotoFile(sha256: string): Promise<void> {
const row = loadRemembered()[sha256];
const row = rememberedNow.get(sha256) ?? loadRemembered()[sha256];
if (!row) return;
const xml = lightroomXmp(row.settings, { flag: row.flag, rating: row.rating, colorLabel: row.colorLabel, sent: row.sent }, iptcOf(row.iptc));
const frame = frameForPhoto(sha256, row.settings);
// Without the pixel size a straighten is written as another aspect. Wait, and retry.
if (cropWaitsForFrame(row.settings, frame)) {
flushFailed.add(sha256);
return;
}
const xml = lightroomXmp(row.settings, { flag: row.flag, rating: row.rating, colorLabel: row.colorLabel, sent: row.sent }, iptcOf(row.iptc), frame);
if (!xml) return;
// Write the file first. Soft-crop bookkeeping must not block or abort the Lightroom packet.
try {
@@ -428,7 +522,13 @@ async function flushPhotoFile(sha256: string): Promise<void> {
try {
const { noteOwnSoftCropWrite } = await import("./softCropWatch.js");
const writtenFlag = row.sent || row.flag === "PICK" ? "PICK" : row.flag === "REJECT" ? "REJECT" : row.flag === "NONE" ? "NONE" : undefined;
noteOwnSoftCropWrite(sha256, softCropFromSettings(row.settings), writtenFlag);
const raw = cropFromXmp(xml);
let noted = softCropFromSettings(row.settings);
if (raw && frame && Math.abs(raw.angle) >= 0.05) {
const back = fromLightroomEdges(raw, raw.angle, frame.width, frame.height);
noted = { left: back.left, top: back.top, right: back.right, bottom: back.bottom, angle: raw.angle };
}
noteOwnSoftCropWrite(sha256, noted, writtenFlag);
} catch {
// Watcher is optional; the file already has the marks.
}
@@ -446,6 +546,22 @@ export function flushFailedPhotoFiles(): void {
for (const sha256 of flushFailed) scheduleFlush(sha256);
}
/**
* The photos remembered most recently (today's event is at the end of the list). Written first,
* so a catch-up that has not reached the server yet still updates the files Lightroom imports.
*/
export function flushRecentPhotoFiles(): void {
if (!isDesktop()) return;
const keys = Object.keys(loadRemembered());
const start = Math.max(0, keys.length - 120);
const recent = keys.slice(start);
for (let index = recent.length - 1; index >= 0; index -= 1) {
const sha256 = recent[index];
if (!sha256) continue;
scheduleFlush(sha256);
}
}
/** The original just moved into the work folder. Write the marks already waiting for it. */
export function retryPhotoFile(sha256: string): void {
if (!isDesktop() || !sha256) return;
@@ -495,6 +611,7 @@ export function writePhotoFile(sha256: string, update: FileMarkUpdate): void {
iptc: "iptc" in update ? iptcOf(update.iptc) : prev.iptc,
};
all[sha256] = next;
rememberedNow.set(sha256, next);
saveRemembered(all);
scheduleFlush(sha256);
}
+11 -1
View File
@@ -1,5 +1,6 @@
import { cropFromXmp, type SoftCrop, xmpPacketFromJpeg } from "@photoreport/metadata";
import { desktopInvoke, isDesktop } from "../platform.js";
import { fromLightroomEdges, photoFrame } from "./lightroomCrop.js";
const cache = new Map<string, SoftCrop | null>();
const inflight = new Map<string, Promise<SoftCrop | null>>();
@@ -39,7 +40,16 @@ export async function softCropFor(sha256: string): Promise<SoftCrop | null> {
const work = (async () => {
try {
const xmp = await localXmpText(sha256);
const crop = xmp ? cropFromXmp(xmp) : null;
const raw = xmp ? cropFromXmp(xmp) : null;
if (!raw || Math.abs(raw.angle) < 0.05) {
cache.set(sha256, raw);
return raw;
}
const frame = photoFrame(sha256);
// The file stores turned corners. Without the photo size they are not the crop to draw.
if (!frame) return raw;
const back = fromLightroomEdges(raw, raw.angle, frame.width, frame.height);
const crop = { left: back.left, top: back.top, right: back.right, bottom: back.bottom, angle: raw.angle };
cache.set(sha256, crop);
return crop;
} catch {
+15 -1
View File
@@ -2,6 +2,7 @@ import { colorClassFromXmp, cropFromXmp, libraryMarksFromXmp, type SoftCrop, typ
import type { ColorLabel, PhotoFlag } from "@photoreport/contracts";
import { desktopInvoke, isDesktop } from "../platform.js";
import { offlineQueue } from "../offline/queue.js";
import { fromLightroomEdges, photoFrame } from "./lightroomCrop.js";
import { forgetSoftCrop, localXmpText } from "./softCrop.js";
/**
@@ -159,7 +160,20 @@ export async function reconcileSoftCrops(
});
continue;
}
const crop = cropFromXmp(xmp);
const rawCrop = cropFromXmp(xmp);
// A straighten is stored as turned corners. Without the photo size those corners are not the crop we show.
if (rawCrop && Math.abs(rawCrop.angle) >= 0.05 && !photoFrame(row.sha256)) {
next.push(row);
continue;
}
let crop = rawCrop;
if (rawCrop && Math.abs(rawCrop.angle) >= 0.05) {
const frame = photoFrame(row.sha256);
if (frame) {
const back = fromLightroomEdges(rawCrop, rawCrop.angle, frame.width, frame.height);
crop = { left: back.left, top: back.top, right: back.right, bottom: back.bottom, angle: rawCrop.angle };
}
}
const color = colorClassFromXmp(xmp);
const marks = libraryMarksFromXmp(xmp);
let colorApplied = color ? row.color : (row.color ?? "");
+4
View File
@@ -42,6 +42,8 @@ export const t = {
label: "sem ligação",
waiting: (n: number) => (n === 1 ? "1 alteração à espera de ligação" : `${n} alterações à espera de ligação`),
waitingHelp: "Feito sem ligação ao servidor: fica guardado neste computador e é enviado sozinho quando a ligação voltar.",
pending: (n: number) => (n === 1 ? "1 alteração por enviar" : `${n} alterações por enviar`),
pendingHelp: "A ligação está feita. Estas alterações seguem para o servidor.",
queuedDelivery: "Sem ligação: o envio fica à espera e sai sozinho quando a ligação voltar.",
editingOffline: "Sem ligação: as edições ficam guardadas neste computador e são enviadas quando a ligação voltar.",
},
@@ -1111,6 +1113,8 @@ export const t = {
orderStatus: { PENDING: "por pagar", PAID: "paga", FULFILLED: "concluída", CANCELLED: "cancelada", REFUNDED: "reembolsada" },
itemStatus: { PENDING: "a preparar", RUNNING: "a preparar", READY: "pronto", SHIPPED: "enviado", FAILED: "falhou" },
markShipped: "Marcar enviada",
collectPayment: "Pagamento recebido",
confirmCollectPayment: "Recebeste o pagamento fora da loja? A encomenda passa a paga e ficas responsável por entregar o trabalho.",
reverseCharge: "Autoliquidação",
noOrders: "Sem encomendas.",
productsHelp: "Preços com IVA incluído. JPEG: tamanho do lado maior (0 = original). Impressões: tamanho e prazo de envio.",
+7 -3
View File
@@ -5,6 +5,10 @@ import { EventsPanel } from "./EventsPanel.js";
import { PhotoContextMenu } from "./PhotoContextMenu.js";
function event(id: string, title: string): EventSummary {
const startsAt = new Date(Date.now() - 86_400_000);
const iso = startsAt.toISOString();
const at = (offsetMs: number) =>
new Date(startsAt.getTime() + offsetMs).toISOString();
return {
id,
organizationId: "org",
@@ -20,9 +24,9 @@ function event(id: string, title: string): EventSummary {
competitionCode: null,
round: null,
matchNumber: null,
startsAt: "2026-11-21T10:56:00.000Z",
ingestFrom: "2026-11-21T08:56:00.000Z",
ingestUntil: "2026-11-21T14:56:00.000Z",
startsAt: iso,
ingestFrom: at(-2 * 3_600_000),
ingestUntil: at(4 * 3_600_000),
iptcTemplate: {},
archivedAt: null,
photographers: [],
+10 -4
View File
@@ -1,6 +1,8 @@
import type { SoftCrop } from "@photoreport/metadata";
import type { ColorLabel, PhotoSummary } from "@photoreport/contracts";
import { memo, useEffect, useRef, useState } from "react";
import { fileShaForPhoto } from "../desktop/fileMarks.js";
import { rememberPhotoFrame } from "../desktop/lightroomCrop.js";
import { softCropFor } from "../desktop/softCrop.js";
import { watchSoftCropPhoto } from "../desktop/softCropWatch.js";
import { t } from "../i18n.js";
@@ -41,19 +43,23 @@ const Cell = memo(function Cell({ photo, index, src, orgId, selected, focused, o
const [softCrop, setSoftCrop] = useState<SoftCrop | null>(null);
useEffect(() => setImgFailed(false), [shown]);
useEffect(() => {
if (!isDesktop() || !photo.sha256) {
const sha = fileShaForPhoto(photo.id, photo.sha256);
if (!isDesktop() || !sha) {
setSoftCrop(null);
return;
}
if (orgId) watchSoftCropPhoto(orgId, photo.id, photo.sha256);
if (orgId) {
rememberPhotoFrame(sha, photo.width, photo.height);
watchSoftCropPhoto(orgId, photo.id, sha);
}
let alive = true;
void softCropFor(photo.sha256).then((crop) => {
void softCropFor(sha).then((crop) => {
if (alive) setSoftCrop(crop);
});
return () => {
alive = false;
};
}, [orgId, photo.id, photo.sha256]);
}, [orgId, photo.id, photo.sha256, photo.width, photo.height]);
return (
<button
ref={ref}
+33 -3
View File
@@ -6,10 +6,24 @@ import { io } from "socket.io-client";
export type LiveState = "connecting" | "live" | "offline";
const liveListeners = new Set<() => void>();
let liveSockets = 0;
/** At least one library socket is connected. Several screens each open their own. */
export function isSocketLive(): boolean {
return liveSockets > 0;
}
function noteSocket(up: boolean): void {
if (up) liveSockets += 1;
else liveSockets = Math.max(0, liveSockets - 1);
if (!up) return;
for (const fn of [...liveListeners]) fn();
}
/** The library socket connected. Waiting edits go out on this, not on a timer. */
export function onSocketLive(fn: () => void): () => void {
liveListeners.add(fn);
if (liveSockets > 0) fn();
return () => liveListeners.delete(fn);
}
@@ -33,17 +47,33 @@ export function useLibraryLive(api: ApiClient, onMessage: (message: LibraryMessa
);
},
});
let connected = false;
const mark = (up: boolean) => {
if (up === connected) return;
connected = up;
noteSocket(up);
};
socket.on("connect", () => {
setState("live");
for (const fn of liveListeners) fn();
mark(true);
});
socket.on("disconnect", () => {
setState("offline");
mark(false);
});
socket.on("connect_error", () => {
setState("offline");
mark(false);
});
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.off("connect");
socket.off("disconnect");
socket.off("connect_error");
mark(false);
socket.close();
};
}, [api]);
+23
View File
@@ -86,6 +86,29 @@ describe("offline queue", () => {
expect(q.size).toBe(0);
});
it("sends a pick queued after the photo is already on the server", async () => {
const q = new OfflineQueue("o1", store);
q.uploaded("abc", "server-1");
q.enqueueEdit(localId("abc"), { command: "develop.set", params: { values: { "light.exposure": 0.4 } } });
q.add({ kind: "patch", ids: [localId("abc")], patch: { flag: "PICK" } });
const sent: string[][] = [];
const edits: string[] = [];
const api = {
updatePhotos: vi.fn(async (_org: string, ids: string[]) => {
sent.push(ids);
return { updated: ids.length };
}),
postEdits: vi.fn(async (photoId: string) => {
edits.push(photoId);
return { developSeq: 1, ops: [] };
}),
} as unknown as ApiClient;
await q.flush(api);
expect(sent).toEqual([["server-1"]]);
expect(edits).toEqual(["server-1"]);
expect(q.size).toBe(0);
});
it("drops what the server refuses for good", async () => {
const q = new OfflineQueue("o1", store);
q.add({ kind: "patch", ids: ["gone"], patch: { flag: "PICK" } });
+27 -10
View File
@@ -202,34 +202,51 @@ export class OfflineQueue {
/** Develop edits made offline on photos no longer open (or uploaded since). Repeated ops are ignored by the server. */
private async flushOutboxes(api: ApiClient): Promise<void> {
let changed = false;
const notify = () => {
if (!changed) return;
changed = false;
for (const fn of this.listeners) fn();
};
for (const key of this.outboxKeys()) {
const photoId = key.slice(OUTBOX.length);
let photoId = key.slice(OUTBOX.length);
if (isLocalId(photoId)) {
// Edited in Revelar before (and after) the upload: those edits follow the photo.
// Edited before the upload finished: those edits follow the photo, then go out in this same pass.
const id = this.serverId(photoId);
if (id) this.uploaded(photoId.slice(LOCAL.length), id);
continue;
if (!id) continue;
this.uploaded(photoId.slice(LOCAL.length), id);
photoId = id;
changed = true;
}
const storeKey = `${OUTBOX}${photoId}`;
let ops: { opId: string; command: unknown }[];
try {
ops = JSON.parse(this.store.get(key) ?? "[]") as { opId: string; command: unknown }[];
ops = JSON.parse(this.store.get(storeKey) ?? "[]") as { opId: string; command: unknown }[];
} catch {
this.store.remove(key);
this.store.remove(storeKey);
changed = true;
continue;
}
if (!ops.length) {
this.store.remove(key);
this.store.remove(storeKey);
changed = true;
continue;
}
try {
await api.postEdits(photoId, { clientId: "offline-queue", ops } as unknown as Parameters<ApiClient["postEdits"]>[1]);
} catch (err) {
if (isNetworkError(err) || (err instanceof ApiError && (err.status === 401 || err.status === 429))) return;
if (isNetworkError(err) || (err instanceof ApiError && (err.status === 401 || err.status === 429))) {
notify();
return;
}
}
// Sent (or refused for good). An editor still open on the photo keeps its own copy and resends harmlessly.
if (this.store.get(key) === JSON.stringify(ops)) this.store.remove(key);
if (this.store.get(storeKey) === JSON.stringify(ops)) {
this.store.remove(storeKey);
changed = true;
}
}
for (const fn of this.listeners) fn();
notify();
}
}
+29 -8
View File
@@ -1,7 +1,7 @@
import type { PhotoPatch } from "@photoreport/contracts";
import type { ApiClient } from "@photoreport/sdk";
import { useEffect, useSyncExternalStore } from "react";
import { onSocketLive } from "../library/realtime.js";
import { isSocketLive, onSocketLive } from "../library/realtime.js";
import { localPhotos } from "./local.js";
import { isLocalId, isNetworkError, offlineQueue, type OfflineQueue } from "./queue.js";
@@ -9,23 +9,44 @@ import { isLocalId, isNetworkError, offlineQueue, type OfflineQueue } from "./qu
* Sends what was kept while the socket was down, the moment it is live again. A change made while the socket is
* already live goes out in `patchPhotos` itself. The socket is the clock: down, keep it; live, send it.
*/
const SEND_DELAY_MS = 40;
const SEND_AGAIN_MS = 1500;
const SEND_TRIES = 5;
export function useOfflineSync(api: ApiClient, orgId: string): void {
useEffect(() => {
if (!orgId) return;
const queue = offlineQueue(orgId);
return onSocketLive(() => {
let tries = 0;
const send = () => {
let tries = 0;
let timer = 0;
const send = () => {
if (!isSocketLive()) return;
window.clearTimeout(timer);
timer = window.setTimeout(() => {
void queue.flush(api).then(() => {
// Still waiting (the link dropped mid-send): try again while this connection stays up.
if (queue.size > 0 && tries < 5) {
// Still waiting (the link dropped mid-send, or a photo was still uploading): try again.
if (queue.size > 0 && isSocketLive() && tries < SEND_TRIES) {
tries += 1;
window.setTimeout(send, 1500);
window.setTimeout(send, SEND_AGAIN_MS);
}
if (queue.size === 0) tries = 0;
});
};
}, SEND_DELAY_MS);
};
// A pick made while the socket is already up never sees another "connect". Send those too.
const stopLive = onSocketLive(() => {
tries = 0;
send();
});
const stopQueue = queue.subscribe(() => {
tries = 0;
send();
});
return () => {
window.clearTimeout(timer);
stopLive();
stopQueue();
};
}, [api, orgId]);
}
+15 -9
View File
@@ -38,6 +38,8 @@ import { ALL_PHOTOS, applyPatch, isMac, type LibraryFilter, matchesFilter, patch
import { t } from "../i18n.js";
import { useLibraryLive } from "../library/realtime.js";
import { forgetSoftCrop, softCropFor } from "../desktop/softCrop.js";
import { fileShaForPhoto } from "../desktop/fileMarks.js";
import { rememberPhotoFrame } from "../desktop/lightroomCrop.js";
import { onSoftCropApplied, watchSoftCropPhoto } from "../desktop/softCropWatch.js";
import { writeLightroomSidecar } from "../desktop/lightroomSidecar.js";
import { isDesktop, localOriginalToView, prefs } from "../platform.js";
@@ -235,25 +237,29 @@ export function DevelopPage() {
// Embed the develop crop into the JPEG as crs:Crop* (AlreadyApplied=False), the same Soft Crop Photo Mechanic reads.
useEffect(() => {
if (!isDesktop() || !session?.loaded || session.hasPending || session.seq < 1 || !current?.sha256) return;
const sha = current.sha256;
const sha = current?.id ? fileShaForPhoto(current.id, current.sha256) : null;
if (!isDesktop() || !session?.loaded || session.hasPending || session.seq < 1 || !sha) return;
const settings = session.settings;
const timer = setTimeout(() => {
forgetSoftCrop(sha);
void writeLightroomSidecar(sha, settings);
}, 500);
return () => clearTimeout(timer);
}, [session, version, current?.sha256]);
}, [session, version, current?.id, current?.sha256]);
// Watch the local file while this photo is open: Lightroom / Photo Mechanic crop changes become develop crops.
useEffect(() => {
if (!isDesktop() || !orgId || !current?.id || !current.sha256) return;
watchSoftCropPhoto(orgId, current.id, current.sha256);
}, [orgId, current?.id, current?.sha256]);
if (!isDesktop() || !orgId || !current?.id) return;
const sha = fileShaForPhoto(current.id, current.sha256);
if (!sha) return;
rememberPhotoFrame(sha, current.width, current.height);
watchSoftCropPhoto(orgId, current.id, sha);
}, [orgId, current?.id, current?.sha256, current?.width, current?.height]);
// A file that already has a Lightroom soft crop and no develop crop yet: start from that rectangle.
useEffect(() => {
if (!isDesktop() || !session?.loaded || !current?.sha256 || session.hasPending || session.seq > 0) return;
const sha = current?.id ? fileShaForPhoto(current.id, current.sha256) : null;
if (!isDesktop() || !session?.loaded || !sha || session.hasPending || session.seq > 0) return;
const currentCrop = cropOf(session.settings);
const full =
currentCrop.rect.x0 <= 0.001 &&
@@ -263,7 +269,7 @@ export function DevelopPage() {
Math.abs(currentCrop.angle) < 0.05;
if (!full) return;
let alive = true;
void softCropFor(current.sha256).then((soft) => {
void softCropFor(sha).then((soft) => {
if (!alive || !soft || !session) return;
session.edit(
{
@@ -280,7 +286,7 @@ export function DevelopPage() {
return () => {
alive = false;
};
}, [session, version, current?.sha256]);
}, [session, version, current?.id, current?.sha256]);
// Soft crop applied by the file watcher while this session is open: paint it immediately.
useEffect(() => {
+2 -2
View File
@@ -902,8 +902,8 @@ export function LibraryPage() {
)}
<span className="ml-auto flex items-center gap-3 font-mono text-[11px] text-faint">
{waitingChanges > 0 && (
<span className="text-star" title={t.offline.waitingHelp}>
{t.offline.waiting(waitingChanges)}
<span className="text-star" title={live === "live" ? t.offline.pendingHelp : t.offline.waitingHelp}>
{live === "live" ? t.offline.pending(waitingChanges) : t.offline.waiting(waitingChanges)}
</span>
)}
<span>
+10
View File
@@ -387,6 +387,16 @@ function Orders({ orgId, isAdmin }: { orgId: string; isAdmin: boolean }) {
{o.invoice.number}
</a>
)}
{isAdmin && o.status === "PENDING" && !o.checkoutUrl && o.totalCents > 0 && (
<button
className="ml-3 underline"
onClick={() => {
if (window.confirm(t.shop.confirmCollectPayment)) void api.recordPayment(o.id).then(replace);
}}
>
{t.shop.collectPayment}
</button>
)}
{isAdmin && (o.status === "PAID" || o.status === "FULFILLED") && (
<button
className="ml-3 underline"
+1
View File
@@ -32,6 +32,7 @@ fn main() {
"ftp_retry",
"ftp_read",
"ftp_sent",
"ftp_write_xmp",
"ftp_open_folder",
"ftp_save_settings",
"local_original",
@@ -29,6 +29,7 @@
"allow-ftp-retry",
"allow-ftp-read",
"allow-ftp-sent",
"allow-ftp-write-xmp",
"allow-ftp-open-folder",
"allow-ftp-save-settings",
"allow-local-original",
@@ -0,0 +1,11 @@
# Automatically generated - DO NOT EDIT!
[[permission]]
identifier = "allow-ftp-write-xmp"
description = "Enables the ftp_write_xmp command without any pre-configured scope."
commands.allow = ["ftp_write_xmp"]
[[permission]]
identifier = "deny-ftp-write-xmp"
description = "Denies the ftp_write_xmp command without any pre-configured scope."
commands.deny = ["ftp_write_xmp"]
+3 -1
View File
@@ -39,7 +39,9 @@ export default async function OrderPage({ params, searchParams }: { params: Prom
</header>
{order.status === "PENDING" && (
<p className="notice" style={{ marginTop: 24 }}>
Assim que o pagamento for confirmado (por Multibanco pode demorar algumas horas) as fotos aparecem aqui e enviamos-te um email.
{order.checkoutUrl
? "Assim que o pagamento for confirmado (por Multibanco pode demorar algumas horas) as fotos aparecem aqui e enviamos-te um email."
: "A encomenda ficou registada. O pagamento combina-se à parte; quando estiver confirmado, as fotos aparecem aqui e enviamos-te um email."}
{order.checkoutUrl && (
<>
{" "}
+24 -6
View File
@@ -396,8 +396,9 @@ A match does not stop when the venue's internet does. The desktop app keeps work
photo in the event of its capture time (the same rule as the server), with id `local:<sha256>`. It can be culled,
named and edited before it is uploaded; the server's copy replaces it when the upload is done, keeping what was done.
- **Changes wait, in order** (`offline/queue.ts`, localStorage): culling, players, IPTC and "send to" made without a
network are kept and sent when the server answers (every 10 s and on `online`); changes to a photo not uploaded yet
wait for it. Develop edits use the per-photo outbox (`develop/session.ts`) and follow the photo to its server id.
network are kept and sent when the socket is up, including a change made while it was already up. Changes to a
photo not uploaded yet wait for it. Develop edits use the per-photo outbox (`develop/session.ts`) and follow the
photo to its server id.
- **Uploads wait instead of failing**: the queue pauses on a network error and resumes when the connection is back.
- The autopilot runs on the server when the photo arrives, and never over a person's edit (made offline first).
@@ -490,13 +491,30 @@ fields onto that first description — caption and title as `rdf:Alt`, keywords
`rdf:Seq` — because Lightroom Classic reads that description on import and on Read Metadata from Files and
ignores the same fields on a second packet. A write that fails while the file is still in the ingest folder
is retried once the original is filed, and again while the app stays open. A catch-up pass covers photos
already picked before this screen was open, without rewriting every older original first.
already picked before this screen was open, without rewriting every older original first. The write addresses
the original by the hash recorded when that file was uploaded (`pr.localmap`), not by the preview hash the
server may store on the photo.
**Cull marks from disk into the library (XMP → library).** On local FTP arrival, hand import, and server
ingest, PhotoReport reads the same XMP fields back into the library (pick / reject / stars / colour). Soft
crop becomes a develop `crop.set`. The desktop watcher re-reads work-folder originals while the app is open,
so a pick or crop painted in Lightroom / Photo Mechanic lands without another import. The 2048 px FTP preview
is never the source of marks — the original JPEG is.
crop becomes a develop `crop.set`. The desktop watcher re-reads work-folder originals while the app is open
(every few seconds, for photos on screen and photos that arrived on this computer), so a pick, a star, a colour
or a crop painted in Lightroom / Photo Mechanic lands without another import and is sent to the server. The
2048 px FTP preview is never the source of marks — the original JPEG is, found by the hash recorded at upload
(`pr.localmap`), not by the preview hash the server may store.
What comes back from the file: the crop, the pick or reject, the stars and the colour. Exposure, white balance
and the other develop sliders are written out for Lightroom, and are not read back. Lightroom has to write the
change into the file (automatically write changes into XMP, or save metadata to the file). A change that stays
only in the Lightroom catalog is invisible.
A straightened crop is stored as the corners Lightroom turns back around the crop centre. Writing the levelled
rectangle plus the angle makes Lightroom show another proportion (Custom). The levelled result is always the
photograph's own aspect. The autopilot never chooses another one (`docs/photo-editing-rules.md`).
A photo that was already delivered is sent again to that same destination about a minute after the edit
settles, under the same file name, replacing the previous file. A destination that takes the untouched
original is not sent again: it has no edit to carry.
**Cull marks on delivery.** The same pick / reject / stars / colour are written into the delivered JPEG
(plus digiKam `PickLabel` and IPTC Urgency for Photo Mechanic). When the desktop app is open it watches local
+3
View File
@@ -44,6 +44,9 @@ Following the AP and NPPA codes:
- **Shape:** the autopilot keeps the photograph's own aspect (non-negotiable). The crop may move anywhere across
the frame, including a tighter window, but it is not turned into another format. A square, a 4:5, a 16:9, or a
portrait crop of a landscape frame is not an autopilot crop. An editor, by hand, may still choose another aspect.
A file written for Lightroom stores a straightened crop as the corners Lightroom turns back around the crop
centre, so the crop tool still shows this aspect. Writing the levelled rectangle together with the angle makes
Lightroom call it Custom.
- **Lead room (sport):** leave space in the direction the player looks or runs; put their back nearer the opposite
edge. Dead space behind the facing direction is wrong. Without a reliable facing signal (face on the body, or
the ball in play), keep the subject centred as before. Reportage and open team frames do not force lead room.
+5
View File
@@ -591,6 +591,11 @@ export class ApiClient {
return this.request<OrderView>("POST", `/v1/orders/${orderId}/items/${itemId}/shipped`);
}
/** Payment taken outside the shop. The caller is responsible for delivering the work. */
recordPayment(orderId: string) {
return this.request<OrderView>("POST", `/v1/orders/${orderId}/payment-received`);
}
retryOrder(orderId: string) {
return this.request<OrderView>("POST", `/v1/orders/${orderId}/retry`);
}