From c894931c78e05cd9e175fc45aaf6a699ea4a396d Mon Sep 17 00:00:00 2001 From: aek676 Date: Wed, 12 Aug 2026 10:44:23 +0200 Subject: [PATCH 01/21] feat(api): confirm a draft session and publish its share code Adds POST /sessions/:sessionId/confirm. The owner publishes a reviewed draft: the session moves to `open` and gets an 8-character code drawn from an alphabet without look-alike glyphs, retried against the unique index when it collides. Confirming is refused while the draft has no lines or still holds a line below the confidence threshold. --- apps/api/src/common/mongo.ts | 9 + .../modules/session/__test__/index.spec.ts | 77 ++++++++ .../modules/session/__test__/service.spec.ts | 177 ++++++++++++++++-- apps/api/src/modules/session/index.ts | 26 +++ apps/api/src/modules/session/model.ts | 4 + apps/api/src/modules/session/service.ts | 48 +++++ 6 files changed, 326 insertions(+), 15 deletions(-) create mode 100644 apps/api/src/common/mongo.ts diff --git a/apps/api/src/common/mongo.ts b/apps/api/src/common/mongo.ts new file mode 100644 index 0000000..6744169 --- /dev/null +++ b/apps/api/src/common/mongo.ts @@ -0,0 +1,9 @@ +export function isDuplicateKeyError(error: unknown, key?: string): boolean { + if (typeof error !== 'object' || error === null) return false; + const { code, keyPattern } = error as { + code?: number; + keyPattern?: Record; + }; + if (code !== 11000) return false; + return key === undefined || keyPattern === undefined || key in keyPattern; +} \ No newline at end of file diff --git a/apps/api/src/modules/session/__test__/index.spec.ts b/apps/api/src/modules/session/__test__/index.spec.ts index 33135c7..aedf894 100644 --- a/apps/api/src/modules/session/__test__/index.spec.ts +++ b/apps/api/src/modules/session/__test__/index.spec.ts @@ -531,3 +531,80 @@ describe('DELETE /sessions/:sessionId/line-items/:lineItemId', () => { expect(session.lineItems).toHaveLength(1); }); }); + +describe('POST /sessions/:sessionId/confirm', () => { + beforeEach(() => { + spyOn(console, 'error').mockImplementation(() => {}); + spyOn(Session.prototype, 'save').mockImplementation(async function ( + this: unknown, + ) { + return this; + }); + }); + + afterEach(() => { + mock.restore(); + }); + + it('returns 200 with the published session and its code', async () => { + const session = draftSession(); + mockLookup(session); + const app = moduleWith(mock(async () => extracted)); + + const res = await app.handle( + request(`/sessions/${session._id}/confirm`, { method: 'POST' }), + ); + + expect(res.status).toBe(200); + const body = await res.json(); + expect(body.status).toBe('open'); + expect(body.code).toMatch(/^[ABCDEFGHJKLMNPQRSTUVWXYZ23456789]{8}$/); + }); + + it('returns 403 for a guest token and leaves the session in draft', async () => { + const session = sessionWithGuest(); + mockLookup(session); + const app = moduleWith(mock(async () => extracted)); + + const res = await app.handle( + request(`/sessions/${session._id}/confirm`, { + method: 'POST', + token: GUEST_TOKEN, + }), + ); + + expect(res.status).toBe(403); + expect(session.status).toBe('draft'); + expect(session.code).toBeUndefined(); + }); + + it('returns 401 without a token', async () => { + const session = draftSession(); + mockLookup(session); + const app = moduleWith(mock(async () => extracted)); + + const res = await app.handle( + request(`/sessions/${session._id}/confirm`, { + method: 'POST', + token: null, + }), + ); + + expect(res.status).toBe(401); + expect(session.status).toBe('draft'); + }); + + it('returns 409 when the session is already published', async () => { + const session = draftSession(); + session.status = 'open'; + mockLookup(session); + const app = moduleWith(mock(async () => extracted)); + + const res = await app.handle( + request(`/sessions/${session._id}/confirm`, { method: 'POST' }), + ); + + expect(res.status).toBe(409); + expect(await res.text()).toBe('Session is not editable'); + }); +}); diff --git a/apps/api/src/modules/session/__test__/service.spec.ts b/apps/api/src/modules/session/__test__/service.spec.ts index 988f225..cc5b7f8 100644 --- a/apps/api/src/modules/session/__test__/service.spec.ts +++ b/apps/api/src/modules/session/__test__/service.spec.ts @@ -13,7 +13,12 @@ import { Session } from '../../../schemas'; import type { ObjectStorage } from '../../../storage/object-storage'; import { hashToken } from '../../auth/service'; import type { SessionModel } from '../model'; -import { buildDraftPayload, SessionService, toSessionView } from '../service'; +import { + buildDraftPayload, + generateSessionCode, + SessionService, + toSessionView, +} from '../service'; const deviceTokenHash = hashToken('device-token-abc'); @@ -88,6 +93,7 @@ describe('toSessionView', () => { const view = toSessionView(doc); expect(view.id).toBe(String(doc._id)); + expect(view.code).toBeNull(); expect(view.status).toBe('draft'); expect(view.merchant).toBe('Bar Paco'); expect(view.receiptImageUrl).toBe('/receipts/abc.jpg'); @@ -231,7 +237,7 @@ function draftSession() { ); } -function lineItemService() { +function sessionService() { return new SessionService( mock(async () => extracted), fakeStorage(), @@ -317,7 +323,7 @@ describe('SessionService.addLineItem', () => { it('appends a hand-entered line with a computed total and full confidence', async () => { const session = draftSession(); - const result = (await lineItemService().addLineItem(session, { + const result = (await sessionService().addLineItem(session, { name: 'Vino', quantity: 2, unitPriceCents: 300, @@ -338,7 +344,7 @@ describe('SessionService.addLineItem', () => { const session = draftSession(); session.status = 'open'; - const result = await lineItemService().addLineItem(session, { + const result = await sessionService().addLineItem(session, { name: 'Vino', quantity: 1, unitPriceCents: 100, @@ -369,7 +375,7 @@ describe('SessionService.updateLineItem', () => { const session = draftSession(); const id = String(session.lineItems[0]._id); - const result = (await lineItemService().updateLineItem(session, id, { + const result = (await sessionService().updateLineItem(session, id, { quantity: 5, })) as SessionModel['draftSessionResponse']; @@ -386,7 +392,7 @@ describe('SessionService.updateLineItem', () => { const session = draftSession(); const id = String(session.lineItems[1]._id); - const result = (await lineItemService().updateLineItem(session, id, { + const result = (await sessionService().updateLineItem(session, id, { name: 'Tapa de jamón', })) as SessionModel['draftSessionResponse']; @@ -400,7 +406,7 @@ describe('SessionService.updateLineItem', () => { const session = draftSession(); const id = String(session.lineItems[1]._id); - const result = (await lineItemService().updateLineItem(session, id, { + const result = (await sessionService().updateLineItem(session, id, { quantity: 2, })) as SessionModel['draftSessionResponse']; @@ -416,7 +422,7 @@ describe('SessionService.updateLineItem', () => { const session = draftSession(); const id = String(session.lineItems[1]._id); - const result = (await lineItemService().updateLineItem( + const result = (await sessionService().updateLineItem( session, id, {}, @@ -430,7 +436,7 @@ describe('SessionService.updateLineItem', () => { const session = draftSession(); const id = String(session.lineItems[0]._id); - const result = (await lineItemService().updateLineItem(session, id, { + const result = (await sessionService().updateLineItem(session, id, { name: 'Cerveza', })) as SessionModel['draftSessionResponse']; @@ -442,7 +448,7 @@ describe('SessionService.updateLineItem', () => { }); it('returns 404 when the line item is missing', async () => { - const result = await lineItemService().updateLineItem( + const result = await sessionService().updateLineItem( draftSession(), '507f1f77bcf86cd799439011', { name: 'x' }, @@ -458,7 +464,7 @@ describe('SessionService.updateLineItem', () => { const session = draftSession(); session.status = 'closed'; - const result = await lineItemService().updateLineItem(session, 'lid', { + const result = await sessionService().updateLineItem(session, 'lid', { name: 'x', }); @@ -487,7 +493,7 @@ describe('SessionService.deleteLineItem', () => { const session = draftSession(); const id = String(session.lineItems[0]._id); - const result = (await lineItemService().deleteLineItem( + const result = (await sessionService().deleteLineItem( session, id, )) as SessionModel['draftSessionResponse']; @@ -503,7 +509,7 @@ describe('SessionService.deleteLineItem', () => { session.totalCents = 100; const id = String(session.lineItems[0]._id); - const result = (await lineItemService().deleteLineItem( + const result = (await sessionService().deleteLineItem( session, id, )) as SessionModel['draftSessionResponse']; @@ -512,7 +518,7 @@ describe('SessionService.deleteLineItem', () => { }); it('returns 404 when the line item is missing', async () => { - const result = await lineItemService().deleteLineItem( + const result = await sessionService().deleteLineItem( draftSession(), '507f1f77bcf86cd799439011', ); @@ -527,11 +533,152 @@ describe('SessionService.deleteLineItem', () => { const session = draftSession(); session.status = 'closed'; - const result = await lineItemService().deleteLineItem(session, 'lid'); + const result = await sessionService().deleteLineItem(session, 'lid'); + + expect(result).toMatchObject({ + code: 409, + response: 'Session is not editable', + }); + }); +}); + +const CODE_PATTERN = /^[ABCDEFGHJKLMNPQRSTUVWXYZ23456789]{8}$/; + +describe('generateSessionCode', () => { + it('draws 8 characters from the unambiguous alphabet', () => { + // Over many draws, an I/O/0/1 slipping into the alphabet would show up here. + for (let i = 0; i < 200; i++) + expect(generateSessionCode()).toMatch(CODE_PATTERN); + }); + + it('does not repeat itself', () => { + const codes = new Set(Array.from({ length: 100 }, generateSessionCode)); + + expect(codes.size).toBe(100); + }); +}); + +/** The shared `extracted` fixture fails review, by design. */ +const confirmable: ExtractedReceipt = { + ...extracted, + lineItems: extracted.lineItems.map((item) => ({ + ...item, + aiConfidence: 0.9, + })), +}; + +function confirmableSession() { + return new Session( + buildDraftPayload(deviceTokenHash, confirmable, '/receipts/abc.jpg'), + ); +} + +function duplicateKeyError() { + return Object.assign(new Error('E11000 duplicate key'), { + code: 11000, + keyPattern: { code: 1 }, + }); +} + +describe('SessionService.confirmSession', () => { + beforeEach(() => { + spyOn(console, 'error').mockImplementation(() => {}); + spyOn(Session.prototype, 'save').mockImplementation(async function ( + this: unknown, + ) { + return this; + }); + }); + + afterEach(() => { + mock.restore(); + }); + + it('publishes the session with a share code', async () => { + const session = confirmableSession(); + + const result = (await sessionService().confirmSession( + session, + )) as SessionModel['draftSessionResponse']; + + expect(result.status).toBe('open'); + expect(result.code).toMatch(CODE_PATTERN); + expect(session.status).toBe('open'); + expect(session.code).toBe(result.code); + }); + + it('returns 409 when the session is not a draft', async () => { + const session = confirmableSession(); + session.status = 'open'; + + const result = await sessionService().confirmSession(session); expect(result).toMatchObject({ code: 409, response: 'Session is not editable', }); }); + + it('returns 409 when there is nothing to split', async () => { + const session = confirmableSession(); + session.lineItems.splice(0); + + const result = await sessionService().confirmSession(session); + + expect(result).toMatchObject({ + code: 409, + response: 'Session has no items to split', + }); + }); + + it('returns 409 while an item is still below the confidence threshold', async () => { + const session = confirmableSession(); + session.lineItems[1].aiConfidence = 0.4; + + const result = await sessionService().confirmSession(session); + + expect(result).toMatchObject({ + code: 409, + response: 'Some items still need review', + }); + expect(session.code).toBeUndefined(); + }); + + it('regenerates the code when the unique index rejects a duplicate', async () => { + const attempted: (string | null)[] = []; + spyOn(Session.prototype, 'save').mockImplementation(async function ( + this: HydratedDocument, + ) { + attempted.push(this.code ?? null); + if (attempted.length === 1) throw duplicateKeyError(); + return this; + }); + + const result = (await sessionService().confirmSession( + confirmableSession(), + )) as SessionModel['draftSessionResponse']; + + expect(attempted).toHaveLength(2); + expect(attempted[0]).not.toBe(attempted[1]); + expect(result.code).toBe(attempted[1]); + }); + + it('returns 500 once the code attempts run out', async () => { + spyOn(Session.prototype, 'save').mockRejectedValue(duplicateKeyError()); + + const result = await sessionService().confirmSession(confirmableSession()); + + expect(result).toMatchObject({ + code: 500, + response: 'Failed to generate a session code', + }); + }); + + it('lets an unrelated write failure bubble up to the module handler', async () => { + spyOn(Session.prototype, 'save').mockRejectedValue(new Error('mongo down')); + + expect( + sessionService().confirmSession(confirmableSession()), + ).rejects.toThrow('mongo down'); + }); }); diff --git a/apps/api/src/modules/session/index.ts b/apps/api/src/modules/session/index.ts index 03132c3..84fb104 100644 --- a/apps/api/src/modules/session/index.ts +++ b/apps/api/src/modules/session/index.ts @@ -122,6 +122,32 @@ export function createSessionModule(service: SessionService) { tags: ['Sessions'], }, }, + ) + .post( + '/:sessionId/confirm', + ({ session }) => service.confirmSession(session), + { + owner: true, + params: SessionModel.sessionParams, + response: { + 200: SessionModel.draftSessionResponse, + 401: AuthModel.unauthorized, + 403: AuthModel.forbidden, + 409: t.Union([ + SessionModel.sessionNotDraft, + SessionModel.sessionEmpty, + SessionModel.sessionNeedsReview, + ]), + 500: t.Union([ + SessionModel.codeGenerationFailed, + SessionModel.internalError, + ]), + }, + detail: { + summary: 'Confirm a draft session and publish its share code', + tags: ['Sessions'], + }, + }, ); } diff --git a/apps/api/src/modules/session/model.ts b/apps/api/src/modules/session/model.ts index 5eddb10..3cd0de2 100644 --- a/apps/api/src/modules/session/model.ts +++ b/apps/api/src/modules/session/model.ts @@ -13,6 +13,7 @@ const lineItemView = t.Object({ const sessionView = t.Object({ id: t.String(), + code: t.Nullable(t.String()), status: t.String(), merchant: t.Nullable(t.String()), date: t.Nullable(t.String()), @@ -52,6 +53,9 @@ export const SessionModel = { internalError: t.Literal('Unexpected server error'), lineItemNotFound: t.Literal('Line item not found'), sessionNotDraft: t.Literal('Session is not editable'), + sessionEmpty: t.Literal('Session has no items to split'), + sessionNeedsReview: t.Literal('Some items still need review'), + codeGenerationFailed: t.Literal('Failed to generate a session code'), } as const; export type SessionModel = { diff --git a/apps/api/src/modules/session/service.ts b/apps/api/src/modules/session/service.ts index a870740..4858bd3 100644 --- a/apps/api/src/modules/session/service.ts +++ b/apps/api/src/modules/session/service.ts @@ -1,6 +1,7 @@ import { status } from 'elysia'; import type { HydratedDocument } from 'mongoose'; import type { ExtractedReceipt, ExtractReceipt } from '../../ai/receipt'; +import { isDuplicateKeyError } from '../../common/mongo'; import { type LineItem, type Participant, Session } from '../../schemas'; import type { ObjectStorage } from '../../storage/object-storage'; import { generateToken, hashToken } from '../auth/service'; @@ -11,6 +12,21 @@ import { } from '../receipt/service'; import { SessionModel } from './model'; +const CODE_ALPHABET = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789'; +const CODE_LENGTH = 8; +const CODE_ATTEMPTS = 5; + +export const LOW_CONFIDENCE_THRESHOLD = 0.7; + +export function generateSessionCode() { + const bytes = new Uint8Array(CODE_LENGTH); + crypto.getRandomValues(bytes); + return Array.from( + bytes, + (byte) => CODE_ALPHABET[byte % CODE_ALPHABET.length], + ).join(''); +} + type LineItemInput = Pick< LineItem, 'name' | 'quantity' | 'unitPriceCents' | 'lineTotalCents' | 'aiConfidence' @@ -56,6 +72,7 @@ export function toSessionView( ): SessionModel['draftSessionResponse'] { return { id: String(session._id), + code: session.code ?? null, status: session.status, merchant: session.merchant ?? null, date: session.date ? session.date.toISOString().slice(0, 10) : null, @@ -189,4 +206,35 @@ export class SessionService { await session.save(); return toSessionView(session); } + + async confirmSession(session: HydratedDocument) { + if (session.status !== 'draft') + return status(409, SessionModel.sessionNotDraft.const); + + if (session.lineItems.length === 0) + return status(409, SessionModel.sessionEmpty.const); + + if ( + session.lineItems.some( + (item) => item.aiConfidence < LOW_CONFIDENCE_THRESHOLD, + ) + ) + return status(409, SessionModel.sessionNeedsReview.const); + + session.status = 'open'; + for (let attempt = 0; attempt < CODE_ATTEMPTS; attempt++) { + session.code = generateSessionCode(); + try { + await session.save(); + return toSessionView(session); + } catch (error) { + if (!isDuplicateKeyError(error, 'code')) throw error; + } + } + + console.error( + `Exhausted ${CODE_ATTEMPTS} code attempts for session ${session._id}`, + ); + return status(500, SessionModel.codeGenerationFailed.const); + } } From 5bf7d6a3b357e9cc4d84b724dcf53b08915d5c79 Mon Sep 17 00:00:00 2001 From: aek676 Date: Wed, 12 Aug 2026 10:44:30 +0200 Subject: [PATCH 02/21] test(api): pin what the totalCents accumulator does today MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Characterization tests over the integration suite. The draft is seeded with the total the AI read off the receipt, while `totalCents` is then kept by adding and subtracting line deltas — so the gap the draft is born with survives every edit, the delete clamp moves it on its own, and confirm publishes it unchecked. They assert today's behaviour, not the wanted one. The ones that flip when the accumulator goes are the ones naming the gap. --- apps/api/test/session-totals.spec.ts | 291 +++++++++++++++++++++++++++ 1 file changed, 291 insertions(+) create mode 100644 apps/api/test/session-totals.spec.ts diff --git a/apps/api/test/session-totals.spec.ts b/apps/api/test/session-totals.spec.ts new file mode 100644 index 0000000..b83f798 --- /dev/null +++ b/apps/api/test/session-totals.spec.ts @@ -0,0 +1,291 @@ +import { describe, expect, it } from 'bun:test'; +import { Types } from 'mongoose'; +import type { ExtractedReceipt, ExtractReceipt } from '../src/ai/receipt'; +import { createSessionModule } from '../src/modules/session'; +import { SessionService } from '../src/modules/session/service'; +import { Session } from '../src/schemas'; +import { analyzeRequest } from './fixtures'; +import { testStorage } from './setup'; + +/** + * Characterization tests: they pin what the incremental `totalCents` arithmetic + * does today, not what it should do. When the accumulator is replaced, the tests + * that flip are the ones naming the gap. + */ + +const CODE_PATTERN = /^[ABCDEFGHJKLMNPQRSTUVWXYZ23456789]{8}$/; + +/** Lines add up to 950, and every one of them reads clearly. */ +const lineItems = [ + { + name: 'Caña', + quantity: 3, + unitPriceCents: 200, + lineTotalCents: 600, + aiConfidence: 0.9, + }, + { + name: 'Tapa', + quantity: 1, + unitPriceCents: 350, + lineTotalCents: 350, + aiConfidence: 0.9, + }, +]; + +const receipt = (totalCents: number): ExtractedReceipt => ({ + merchant: 'Bar Paco', + date: '2026-07-07', + currency: 'EUR', + totalCents, + lineItems, +}); + +/** The printed total matches the lines the AI read. */ +const coherent = receipt(950); +/** The AI read the printed total but missed lines worth 32.80. */ +const overstated = receipt(4230); +/** The AI misread the printed total as lower than the lines it did read. */ +const understated = receipt(100); + +const extractOf = + (extracted: ExtractedReceipt): ExtractReceipt => + async () => + extracted; + +type SessionApp = ReturnType; + +const appFor = (extracted: ExtractedReceipt): SessionApp => + createSessionModule(new SessionService(extractOf(extracted), testStorage())); + +const coherentApp = appFor(coherent); +const overstatedApp = appFor(overstated); +const understatedApp = appFor(understated); + +type Draft = { + id: string; + totalCents: number; + lineItems: { id: string; name: string; lineTotalCents: number }[]; + auth: { participantId: string; token: string }; +}; + +async function createDraft(app: SessionApp) { + const res = await app.handle(analyzeRequest()); + expect(res.status).toBe(200); + return (await res.json()) as Draft; +} + +function authorized(draft: Draft, extra: HeadersInit = {}) { + return { authorization: `Bearer ${draft.auth.token}`, ...extra }; +} + +async function addLineItem( + app: SessionApp, + draft: Draft, + body: { name: string; quantity: number; unitPriceCents: number }, +) { + const res = await app.handle( + new Request(`http://localhost/sessions/${draft.id}/line-items`, { + method: 'POST', + headers: authorized(draft, { 'content-type': 'application/json' }), + body: JSON.stringify(body), + }), + ); + expect(res.status).toBe(200); + return (await res.json()) as Draft; +} + +async function patchLineItem( + app: SessionApp, + draft: Draft, + lineItemId: string, + patch: Partial<{ name: string; quantity: number; unitPriceCents: number }>, +) { + const res = await app.handle( + new Request( + `http://localhost/sessions/${draft.id}/line-items/${lineItemId}`, + { + method: 'PATCH', + headers: authorized(draft, { 'content-type': 'application/json' }), + body: JSON.stringify(patch), + }, + ), + ); + expect(res.status).toBe(200); + return (await res.json()) as Draft; +} + +async function removeLineItem( + app: SessionApp, + draft: Draft, + lineItemId: string, +) { + const res = await app.handle( + new Request( + `http://localhost/sessions/${draft.id}/line-items/${lineItemId}`, + { method: 'DELETE', headers: authorized(draft) }, + ), + ); + expect(res.status).toBe(200); + return (await res.json()) as Draft; +} + +function confirm(app: SessionApp, draft: Draft) { + return app.handle( + new Request(`http://localhost/sessions/${draft.id}/confirm`, { + method: 'POST', + headers: authorized(draft), + }), + ); +} + +/** Measures the stored document, not the view the API hands back. */ +async function storedTotals(sessionId: string) { + const raw = await Session.collection.findOne({ + _id: new Types.ObjectId(sessionId), + }); + if (!raw) throw new Error(`session ${sessionId} is gone`); + + const stored = raw as unknown as { + totalCents: number; + lineItems: { lineTotalCents: number }[]; + }; + const lineSum = stored.lineItems.reduce( + (sum, item) => sum + item.lineTotalCents, + 0, + ); + + return { + totalCents: stored.totalCents, + lineSum, + gap: stored.totalCents - lineSum, + lineCount: stored.lineItems.length, + }; +} + +describe('totalCents against the sum of the line items', () => { + it('is born already apart when the receipt total outruns the lines', async () => { + const draft = await createDraft(overstatedApp); + + expect(await storedTotals(draft.id)).toEqual({ + totalCents: 4230, + lineSum: 950, + gap: 3280, + lineCount: 2, + }); + }); + + it('keeps the gap it was born with, whatever the owner edits', async () => { + const draft = await createDraft(overstatedApp); + expect((await storedTotals(draft.id)).gap).toBe(3280); + + const added = await addLineItem(overstatedApp, draft, { + name: 'Vino', + quantity: 2, + unitPriceCents: 300, + }); + expect(await storedTotals(draft.id)).toMatchObject({ + totalCents: 4830, + lineSum: 1550, + gap: 3280, + }); + + await patchLineItem(overstatedApp, draft, added.lineItems[0].id, { + quantity: 5, + }); + expect(await storedTotals(draft.id)).toMatchObject({ + totalCents: 5230, + lineSum: 1950, + gap: 3280, + }); + + await removeLineItem(overstatedApp, draft, added.lineItems[1].id); + expect(await storedTotals(draft.id)).toMatchObject({ + totalCents: 4880, + lineSum: 1600, + gap: 3280, + }); + }); + + it('still claims 32.80 once every line is gone', async () => { + const draft = await createDraft(overstatedApp); + + for (const lineItem of draft.lineItems) + await removeLineItem(overstatedApp, draft, lineItem.id); + + expect(await storedTotals(draft.id)).toEqual({ + totalCents: 3280, + lineSum: 0, + gap: 3280, + lineCount: 0, + }); + }); + + it('moves the gap on its own when the clamp catches a negative total', async () => { + const draft = await createDraft(understatedApp); + expect(await storedTotals(draft.id)).toMatchObject({ + totalCents: 100, + lineSum: 950, + gap: -850, + }); + + // 100 - 600 would be -500, so the clamp rewrites the total to 0. + await removeLineItem(understatedApp, draft, draft.lineItems[0].id); + + expect(await storedTotals(draft.id)).toEqual({ + totalCents: 0, + lineSum: 350, + gap: -350, + lineCount: 1, + }); + }); + + it('never drifts by itself: the arithmetic is exact when the seed is', async () => { + const draft = await createDraft(coherentApp); + expect(await storedTotals(draft.id)).toMatchObject({ gap: 0 }); + + const withWine = await addLineItem(coherentApp, draft, { + name: 'Vino', + quantity: 2, + unitPriceCents: 300, + }); + const withDessert = await addLineItem(coherentApp, draft, { + name: 'Postre', + quantity: 1, + unitPriceCents: 450, + }); + await patchLineItem(coherentApp, draft, withDessert.lineItems[0].id, { + quantity: 5, + }); + await patchLineItem(coherentApp, draft, withDessert.lineItems[1].id, { + unitPriceCents: 400, + }); + await patchLineItem(coherentApp, draft, withWine.lineItems[2].id, { + name: 'Vino tinto', + }); + await removeLineItem(coherentApp, draft, withDessert.lineItems[3].id); + + expect(await storedTotals(draft.id)).toEqual({ + totalCents: 2000, + lineSum: 2000, + gap: 0, + lineCount: 3, + }); + }); + + it('publishes the gap: confirm opens the session and nothing checks the total', async () => { + const draft = await createDraft(overstatedApp); + + const res = await confirm(overstatedApp, draft); + + expect(res.status).toBe(200); + const body = (await res.json()) as { status: string; code: string }; + expect(body.status).toBe('open'); + expect(body.code).toMatch(CODE_PATTERN); + expect(await storedTotals(draft.id)).toMatchObject({ + totalCents: 4230, + lineSum: 950, + gap: 3280, + }); + }); +}); From c739bbe90df91cd8643f1c7d7c794916992c2a9b Mon Sep 17 00:00:00 2001 From: aek676 Date: Wed, 12 Aug 2026 10:44:37 +0200 Subject: [PATCH 03/21] refactor(web): drop the client-side receipt total check The check compared the line items against `totalCents`, but the API moves that total by the same delta as every line edit, so a draft that was born out of balance could never be brought back into it. The warning had no way to clear and the confirm button stayed disabled for good. Removed here so the balance rule can be rebuilt on an API that keeps the printed total fixed. --- .../session/components/session-draft.tsx | 41 +++------------- .../session/utils/receipt-totals.spec.ts | 48 ------------------- .../features/session/utils/receipt-totals.ts | 24 ---------- 3 files changed, 7 insertions(+), 106 deletions(-) delete mode 100644 apps/web/src/features/session/utils/receipt-totals.spec.ts delete mode 100644 apps/web/src/features/session/utils/receipt-totals.ts diff --git a/apps/web/src/features/session/components/session-draft.tsx b/apps/web/src/features/session/components/session-draft.tsx index 17fcf46..957ce3a 100644 --- a/apps/web/src/features/session/components/session-draft.tsx +++ b/apps/web/src/features/session/components/session-draft.tsx @@ -1,15 +1,9 @@ import { useForm } from '@tanstack/react-form'; import { useNavigate } from '@tanstack/react-router'; -import { - AlertTriangle, - Camera, - CheckCircle2, - Link as LinkIcon, -} from 'lucide-react'; +import { Camera, Link as LinkIcon } from 'lucide-react'; import { Button } from 'shadcn-ui/button'; import { useDeleteSession } from '@/features/session/api/delete-session'; import { LOW_CONFIDENCE_THRESHOLD } from '@/features/session/line-item/components/line-item-row'; -import { receiptTotals } from '@/features/session/utils/receipt-totals'; import type { Session } from '@/types/session'; import { formatCents } from '@/utils/money'; @@ -49,44 +43,23 @@ function ReviewHeader({ session }: { session: Session }) { } function ReceiptSummary({ session }: { session: Session }) { - const totals = receiptTotals(session); - return ( -
-
- Total - - {formatCents(session.totalCents, session.currency)} - -
- {totals.matches ? ( -
- - Items sum to total -
- ) : ( -
- - - Items add up to{' '} - {formatCents(totals.itemsTotalCents, session.currency)},{' '} - {formatCents(Math.abs(totals.discrepancyCents), session.currency)}{' '} - {totals.discrepancyCents > 0 ? 'over' : 'under'} the receipt total - -
- )} +
+ Total + + {formatCents(session.totalCents, session.currency)} +
); } function ConfirmButton({ session }: { session: Session }) { - const totals = receiptTotals(session); const hasItems = session.lineItems.length > 0; const hasLowConfidence = session.lineItems.some( (item) => item.aiConfidence < LOW_CONFIDENCE_THRESHOLD, ); - const canConfirm = totals.matches && hasItems && !hasLowConfidence; + const canConfirm = hasItems && !hasLowConfidence; const form = useForm({ defaultValues: {}, diff --git a/apps/web/src/features/session/utils/receipt-totals.spec.ts b/apps/web/src/features/session/utils/receipt-totals.spec.ts deleted file mode 100644 index c37df33..0000000 --- a/apps/web/src/features/session/utils/receipt-totals.spec.ts +++ /dev/null @@ -1,48 +0,0 @@ -import { describe, expect, it } from 'vitest'; -import { receiptTotals } from '@/features/session/utils/receipt-totals'; - -function lineItem(lineTotalCents: number) { - return { - id: 'l1', - name: 'Beer', - quantity: 1, - unitPriceCents: lineTotalCents, - lineTotalCents, - aiConfidence: 1, - }; -} - -describe('receiptTotals', () => { - it('sums line totals', () => { - const totals = receiptTotals({ - lineItems: [lineItem(600), lineItem(1400)], - totalCents: 2000, - }); - expect(totals.itemsTotalCents).toBe(2000); - expect(totals.discrepancyCents).toBe(0); - expect(totals.matches).toBe(true); - }); - - it('tolerates rounding discrepancies of up to two cents', () => { - const totals = receiptTotals({ - lineItems: [lineItem(999)], - totalCents: 1001, - }); - expect(totals.discrepancyCents).toBe(-2); - expect(totals.matches).toBe(true); - }); - - it('flags larger discrepancies', () => { - const totals = receiptTotals({ - lineItems: [lineItem(500)], - totalCents: 1000, - }); - expect(totals.discrepancyCents).toBe(-500); - expect(totals.matches).toBe(false); - }); - - it('handles empty receipts', () => { - const totals = receiptTotals({ lineItems: [], totalCents: 0 }); - expect(totals.matches).toBe(true); - }); -}); diff --git a/apps/web/src/features/session/utils/receipt-totals.ts b/apps/web/src/features/session/utils/receipt-totals.ts deleted file mode 100644 index f2fc75f..0000000 --- a/apps/web/src/features/session/utils/receipt-totals.ts +++ /dev/null @@ -1,24 +0,0 @@ -import type { Session } from '@/types/session'; - -export const TOTAL_TOLERANCE_CENTS = 2; - -export interface ReceiptTotals { - itemsTotalCents: number; - discrepancyCents: number; - matches: boolean; -} - -export function receiptTotals( - session: Pick, -): ReceiptTotals { - const itemsTotalCents = session.lineItems.reduce( - (sum, item) => sum + item.lineTotalCents, - 0, - ); - const discrepancyCents = itemsTotalCents - session.totalCents; - return { - itemsTotalCents, - discrepancyCents, - matches: Math.abs(discrepancyCents) <= TOTAL_TOLERANCE_CENTS, - }; -} From f2c3a08997167f71c88ab5b6f840b52244e949b3 Mon Sep 17 00:00:00 2001 From: aek676 Date: Wed, 12 Aug 2026 10:52:05 +0200 Subject: [PATCH 04/21] fix(api): keep the receipt total fixed and check it on confirm MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `totalCents` was seeded with the total the AI read off the receipt and then kept as a running tally of the line edits, so it moved by the same delta as the lines it was supposed to be reconciled against. A draft born out of balance stayed out of balance by exactly that amount: no sequence of edits could close the gap, and the delete clamp moved it on its own once the total ran below zero. The total now means one thing — what the receipt says — and stays put while the owner reviews. Confirm is the gate: it refuses to publish until the items add up to it exactly, so nothing reaches the split with a total the lines disagree with. Adds PATCH /sessions/:sessionId for the other half of the reconciliation: when the AI misread the printed total, the owner corrects the target instead of being locked out of confirming. --- apps/api/src/common/mongo.ts | 2 +- .../modules/session/__test__/index.spec.ts | 98 +++++++++++- .../modules/session/__test__/service.spec.ts | 144 +++++++++++++++-- apps/api/src/modules/session/index.ts | 21 +++ apps/api/src/modules/session/model.ts | 10 ++ apps/api/src/modules/session/service.ts | 39 +++-- apps/api/test/auth-flow.spec.ts | 5 +- apps/api/test/session-totals.spec.ts | 146 ++++++++++-------- 8 files changed, 376 insertions(+), 89 deletions(-) diff --git a/apps/api/src/common/mongo.ts b/apps/api/src/common/mongo.ts index 6744169..2f0823b 100644 --- a/apps/api/src/common/mongo.ts +++ b/apps/api/src/common/mongo.ts @@ -6,4 +6,4 @@ export function isDuplicateKeyError(error: unknown, key?: string): boolean { }; if (code !== 11000) return false; return key === undefined || keyPattern === undefined || key in keyPattern; -} \ No newline at end of file +} diff --git a/apps/api/src/modules/session/__test__/index.spec.ts b/apps/api/src/modules/session/__test__/index.spec.ts index aedf894..e7597a7 100644 --- a/apps/api/src/modules/session/__test__/index.spec.ts +++ b/apps/api/src/modules/session/__test__/index.spec.ts @@ -377,6 +377,87 @@ describe('GET /sessions/:sessionId', () => { }); }); +describe('PATCH /sessions/:sessionId', () => { + beforeEach(() => { + spyOn(console, 'error').mockImplementation(() => {}); + spyOn(Session.prototype, 'save').mockImplementation(async function ( + this: unknown, + ) { + return this; + }); + }); + + afterEach(() => { + mock.restore(); + }); + + it('corrects the receipt total and returns 200 with the updated view', async () => { + const session = draftSession(); + mockLookup(session); + const app = moduleWith(mock(async () => extracted)); + + const res = await app.handle( + request(`/sessions/${session._id}`, { + method: 'PATCH', + body: { totalCents: 1600 }, + }), + ); + + expect(res.status).toBe(200); + expect(await res.json()).toMatchObject({ totalCents: 1600 }); + }); + + it('returns 422 for a negative total', async () => { + const session = draftSession(); + mockLookup(session); + const app = moduleWith(mock(async () => extracted)); + + const res = await app.handle( + request(`/sessions/${session._id}`, { + method: 'PATCH', + body: { totalCents: -1 }, + }), + ); + + expect(res.status).toBe(422); + expect(session.totalCents).toBe(600); + }); + + it('returns 403 for a guest token and keeps the total', async () => { + const session = sessionWithGuest(); + mockLookup(session); + const app = moduleWith(mock(async () => extracted)); + + const res = await app.handle( + request(`/sessions/${session._id}`, { + method: 'PATCH', + body: { totalCents: 1600 }, + token: GUEST_TOKEN, + }), + ); + + expect(res.status).toBe(403); + expect(session.totalCents).toBe(600); + }); + + it('returns 409 once the session is published', async () => { + const session = draftSession(); + session.status = 'open'; + mockLookup(session); + const app = moduleWith(mock(async () => extracted)); + + const res = await app.handle( + request(`/sessions/${session._id}`, { + method: 'PATCH', + body: { totalCents: 1600 }, + }), + ); + + expect(res.status).toBe(409); + expect(await res.text()).toBe('Session is not editable'); + }); +}); + describe('DELETE /sessions/:sessionId', () => { beforeEach(() => { spyOn(console, 'error').mockImplementation(() => {}); @@ -496,7 +577,7 @@ describe('DELETE /sessions/:sessionId/line-items/:lineItemId', () => { expect(res.status).toBe(200); const body = await res.json(); expect(body.lineItems).toHaveLength(0); - expect(body.totalCents).toBe(0); + expect(body.totalCents).toBe(600); }); it('returns 404 when the line item is missing', async () => { @@ -594,6 +675,21 @@ describe('POST /sessions/:sessionId/confirm', () => { expect(session.status).toBe('draft'); }); + it('returns 409 when the items fall short of the receipt total', async () => { + const session = draftSession(); + session.totalCents = 1600; + mockLookup(session); + const app = moduleWith(mock(async () => extracted)); + + const res = await app.handle( + request(`/sessions/${session._id}/confirm`, { method: 'POST' }), + ); + + expect(res.status).toBe(409); + expect(await res.text()).toBe('Items do not add up to the receipt total'); + expect(session.status).toBe('draft'); + }); + it('returns 409 when the session is already published', async () => { const session = draftSession(); session.status = 'open'; diff --git a/apps/api/src/modules/session/__test__/service.spec.ts b/apps/api/src/modules/session/__test__/service.spec.ts index cc5b7f8..e8789f1 100644 --- a/apps/api/src/modules/session/__test__/service.spec.ts +++ b/apps/api/src/modules/session/__test__/service.spec.ts @@ -16,6 +16,7 @@ import type { SessionModel } from '../model'; import { buildDraftPayload, generateSessionCode, + lineSumCents, SessionService, toSessionView, } from '../service'; @@ -306,6 +307,75 @@ describe('SessionService.deleteSession', () => { }); }); +describe('SessionService.updateSession', () => { + beforeEach(() => { + spyOn(console, 'error').mockImplementation(() => {}); + spyOn(Session.prototype, 'save').mockImplementation(async function ( + this: unknown, + ) { + return this; + }); + }); + + afterEach(() => { + mock.restore(); + }); + + it('corrects a total the AI misread off the receipt', async () => { + const session = draftSession(); + + const result = (await sessionService().updateSession(session, { + totalCents: 950, + })) as SessionModel['draftSessionResponse']; + + expect(result.totalCents).toBe(950); + expect(result.lineItems).toHaveLength(2); + }); + + it('corrects the merchant and the date', async () => { + const session = draftSession(); + + const result = (await sessionService().updateSession(session, { + merchant: 'Bar Pepe', + date: '2026-07-08', + })) as SessionModel['draftSessionResponse']; + + expect(result.merchant).toBe('Bar Pepe'); + expect(result.date).toBe('2026-07-08'); + expect(result.totalCents).toBe(4230); + }); + + it('leaves everything untouched for an empty patch', async () => { + const session = draftSession(); + + const result = (await sessionService().updateSession( + session, + {}, + )) as SessionModel['draftSessionResponse']; + + expect(result).toMatchObject({ + merchant: 'Bar Paco', + date: '2026-07-07', + totalCents: 4230, + }); + }); + + it('returns 409 when the session is not a draft', async () => { + const session = draftSession(); + session.status = 'open'; + + const result = await sessionService().updateSession(session, { + totalCents: 950, + }); + + expect(result).toMatchObject({ + code: 409, + response: 'Session is not editable', + }); + expect(session.totalCents).toBe(4230); + }); +}); + describe('SessionService.addLineItem', () => { beforeEach(() => { spyOn(console, 'error').mockImplementation(() => {}); @@ -337,7 +407,21 @@ describe('SessionService.addLineItem', () => { lineTotalCents: 600, aiConfidence: 1, }); - expect(result.totalCents).toBe(4830); + }); + + it('leaves the receipt total where the owner can still reach it', async () => { + const session = draftSession(); + + const result = (await sessionService().addLineItem(session, { + name: 'Vino', + quantity: 2, + unitPriceCents: 300, + })) as SessionModel['draftSessionResponse']; + + // The missing line brings the items up to the printed total, it does not + // push the target further away. + expect(result.totalCents).toBe(4230); + expect(lineSumCents(session)).toBe(1550); }); it('returns 409 when the session is not a draft', async () => { @@ -385,7 +469,7 @@ describe('SessionService.updateLineItem', () => { lineTotalCents: 1000, aiConfidence: 1, }); - expect(result.totalCents).toBe(4630); + expect(result.totalCents).toBe(4230); }); it('clears the low-confidence flag when the name is corrected', async () => { @@ -415,7 +499,7 @@ describe('SessionService.updateLineItem', () => { lineTotalCents: 700, aiConfidence: 1, }); - expect(result.totalCents).toBe(4580); + expect(result.totalCents).toBe(4230); }); it('leaves confidence untouched for an empty patch', async () => { @@ -489,7 +573,7 @@ describe('SessionService.deleteLineItem', () => { mock.restore(); }); - it('removes the line and subtracts its total from the session', async () => { + it('removes the line and leaves the receipt total alone', async () => { const session = draftSession(); const id = String(session.lineItems[0]._id); @@ -501,20 +585,17 @@ describe('SessionService.deleteLineItem', () => { expect(session.lineItems).toHaveLength(1); expect(result.lineItems).toHaveLength(1); expect(result.lineItems[0]).toMatchObject({ name: 'Tapa' }); - expect(result.totalCents).toBe(3630); + expect(result.totalCents).toBe(4230); }); - it('clamps the session total at 0 instead of going negative', async () => { + it('keeps the total readable once every line is gone', async () => { const session = draftSession(); - session.totalCents = 100; - const id = String(session.lineItems[0]._id); - const result = (await sessionService().deleteLineItem( - session, - id, - )) as SessionModel['draftSessionResponse']; + for (const id of session.lineItems.map((item) => String(item._id))) + await sessionService().deleteLineItem(session, id); - expect(result.totalCents).toBe(0); + expect(session.lineItems).toHaveLength(0); + expect(session.totalCents).toBe(4230); }); it('returns 404 when the line item is missing', async () => { @@ -558,9 +639,13 @@ describe('generateSessionCode', () => { }); }); -/** The shared `extracted` fixture fails review, by design. */ +/** + * The shared `extracted` fixture fails review by design: it reads a total the + * lines fall short of, and one of those lines is barely legible. + */ const confirmable: ExtractedReceipt = { ...extracted, + totalCents: 950, lineItems: extracted.lineItems.map((item) => ({ ...item, aiConfidence: 0.9, @@ -644,6 +729,37 @@ describe('SessionService.confirmSession', () => { expect(session.code).toBeUndefined(); }); + it('returns 409 while the items fall short of the receipt total', async () => { + const session = confirmableSession(); + session.totalCents = 1100; + + const result = await sessionService().confirmSession(session); + + expect(result).toMatchObject({ + code: 409, + response: 'Items do not add up to the receipt total', + }); + expect(session.status).toBe('draft'); + expect(session.code).toBeUndefined(); + }); + + it('publishes once the owner has brought the two together', async () => { + const session = confirmableSession(); + session.totalCents = 1100; + + await sessionService().addLineItem(session, { + name: 'Vino', + quantity: 1, + unitPriceCents: 150, + }); + const result = (await sessionService().confirmSession( + session, + )) as SessionModel['draftSessionResponse']; + + expect(lineSumCents(session)).toBe(1100); + expect(result.status).toBe('open'); + }); + it('regenerates the code when the unique index rejects a duplicate', async () => { const attempted: (string | null)[] = []; spyOn(Session.prototype, 'save').mockImplementation(async function ( diff --git a/apps/api/src/modules/session/index.ts b/apps/api/src/modules/session/index.ts index 84fb104..fb5d94b 100644 --- a/apps/api/src/modules/session/index.ts +++ b/apps/api/src/modules/session/index.ts @@ -46,6 +46,26 @@ export function createSessionModule(service: SessionService) { tags: ['Sessions'], }, }) + .patch( + '/:sessionId', + ({ session, body }) => service.updateSession(session, body), + { + owner: true, + params: SessionModel.sessionParams, + body: SessionModel.sessionUpdateBody, + response: { + 200: SessionModel.draftSessionResponse, + 401: AuthModel.unauthorized, + 403: AuthModel.forbidden, + 409: SessionModel.sessionNotDraft, + 500: SessionModel.internalError, + }, + detail: { + summary: 'Edit the receipt details of a draft session', + tags: ['Sessions'], + }, + }, + ) .delete('/:sessionId', ({ session }) => service.deleteSession(session), { owner: true, params: SessionModel.sessionParams, @@ -137,6 +157,7 @@ export function createSessionModule(service: SessionService) { SessionModel.sessionNotDraft, SessionModel.sessionEmpty, SessionModel.sessionNeedsReview, + SessionModel.sessionTotalMismatch, ]), 500: t.Union([ SessionModel.codeGenerationFailed, diff --git a/apps/api/src/modules/session/model.ts b/apps/api/src/modules/session/model.ts index 3cd0de2..888ef21 100644 --- a/apps/api/src/modules/session/model.ts +++ b/apps/api/src/modules/session/model.ts @@ -28,6 +28,14 @@ const authView = t.Object({ token: t.String(), }); +const sessionUpdateBody = t.Partial( + t.Object({ + merchant: t.String({ minLength: 1 }), + date: t.String({ format: 'date' }), + totalCents: t.Integer({ minimum: 0 }), + }), +); + const lineItemCreateBody = t.Object({ name: t.String({ minLength: 1 }), quantity: t.Integer({ minimum: 0 }), @@ -39,6 +47,7 @@ export const SessionModel = { image: t.File({ type: [...SUPPORTED_IMAGE_MIME_TYPES], maxSize: '10m' }), }), sessionParams: t.Object({ sessionId: objectId }), + sessionUpdateBody, lineItemParams: t.Object({ sessionId: objectId, lineItemId: objectId }), lineItemCreateBody, lineItemUpdateBody: t.Partial(lineItemCreateBody), @@ -55,6 +64,7 @@ export const SessionModel = { sessionNotDraft: t.Literal('Session is not editable'), sessionEmpty: t.Literal('Session has no items to split'), sessionNeedsReview: t.Literal('Some items still need review'), + sessionTotalMismatch: t.Literal('Items do not add up to the receipt total'), codeGenerationFailed: t.Literal('Failed to generate a session code'), } as const; diff --git a/apps/api/src/modules/session/service.ts b/apps/api/src/modules/session/service.ts index 4858bd3..a258fa9 100644 --- a/apps/api/src/modules/session/service.ts +++ b/apps/api/src/modules/session/service.ts @@ -67,6 +67,14 @@ export function buildDraftPayload( }; } +/** + * What the line items add up to. `totalCents` holds the total printed on the + * receipt instead, so the two only meet once the owner has reviewed the draft. + */ +export function lineSumCents(session: HydratedDocument): number { + return session.lineItems.reduce((sum, item) => sum + item.lineTotalCents, 0); +} + export function toSessionView( session: HydratedDocument, ): SessionModel['draftSessionResponse'] { @@ -139,6 +147,21 @@ export class SessionService { return status(204, undefined); } + async updateSession( + session: HydratedDocument, + patch: SessionModel['sessionUpdateBody'], + ) { + if (session.status !== 'draft') + return status(409, SessionModel.sessionNotDraft.const); + + if (patch.merchant !== undefined) session.merchant = patch.merchant; + if (patch.date !== undefined) session.date = new Date(patch.date); + if (patch.totalCents !== undefined) session.totalCents = patch.totalCents; + + await session.save(); + return toSessionView(session); + } + async addLineItem( session: HydratedDocument, input: SessionModel['lineItemCreateBody'], @@ -146,15 +169,13 @@ export class SessionService { if (session.status !== 'draft') return status(409, SessionModel.sessionNotDraft.const); - const lineTotalCents = input.quantity * input.unitPriceCents; session.lineItems.push({ name: input.name, quantity: input.quantity, unitPriceCents: input.unitPriceCents, - lineTotalCents, + lineTotalCents: input.quantity * input.unitPriceCents, aiConfidence: 1, }); - session.totalCents += lineTotalCents; await session.save(); return toSessionView(session); } @@ -174,11 +195,8 @@ export class SessionService { if (patch.quantity !== undefined) lineItem.quantity = patch.quantity; if (patch.unitPriceCents !== undefined) lineItem.unitPriceCents = patch.unitPriceCents; - if (patch.quantity !== undefined || patch.unitPriceCents !== undefined) { - const previousLineTotalCents = lineItem.lineTotalCents; + if (patch.quantity !== undefined || patch.unitPriceCents !== undefined) lineItem.lineTotalCents = lineItem.quantity * lineItem.unitPriceCents; - session.totalCents += lineItem.lineTotalCents - previousLineTotalCents; - } if ( patch.name !== undefined || @@ -198,10 +216,6 @@ export class SessionService { const lineItem = session.lineItems.id(lineItemId); if (!lineItem) return status(404, SessionModel.lineItemNotFound.const); - session.totalCents = Math.max( - 0, - session.totalCents - lineItem.lineTotalCents, - ); session.lineItems.pull(lineItemId); await session.save(); return toSessionView(session); @@ -221,6 +235,9 @@ export class SessionService { ) return status(409, SessionModel.sessionNeedsReview.const); + if (lineSumCents(session) !== session.totalCents) + return status(409, SessionModel.sessionTotalMismatch.const); + session.status = 'open'; for (let attempt = 0; attempt < CODE_ATTEMPTS; attempt++) { session.code = generateSessionCode(); diff --git a/apps/api/test/auth-flow.spec.ts b/apps/api/test/auth-flow.spec.ts index bb6e185..1234b56 100644 --- a/apps/api/test/auth-flow.spec.ts +++ b/apps/api/test/auth-flow.spec.ts @@ -73,7 +73,10 @@ describe('full thread: /analyze issues a token that opens its session', () => { ); expect(res.status).toBe(200); - expect(await res.json()).toMatchObject({ totalCents: 950 }); + expect((await res.json()).lineItems).toMatchObject([ + { name: 'Caña' }, + { name: 'Tapa', lineTotalCents: 350 }, + ]); const raw = await Session.collection.findOne({ _id: new Types.ObjectId(draft.id), diff --git a/apps/api/test/session-totals.spec.ts b/apps/api/test/session-totals.spec.ts index b83f798..1a2840a 100644 --- a/apps/api/test/session-totals.spec.ts +++ b/apps/api/test/session-totals.spec.ts @@ -8,9 +8,9 @@ import { analyzeRequest } from './fixtures'; import { testStorage } from './setup'; /** - * Characterization tests: they pin what the incremental `totalCents` arithmetic - * does today, not what it should do. When the accumulator is replaced, the tests - * that flip are the ones naming the gap. + * `totalCents` holds the total printed on the receipt, read once by the AI and + * never moved by an edit. The line items are what the owner reconciles against + * it, and confirm is the gate: a draft only publishes when the two agree. */ const CODE_PATTERN = /^[ABCDEFGHJKLMNPQRSTUVWXYZ23456789]{8}$/; @@ -43,8 +43,8 @@ const receipt = (totalCents: number): ExtractedReceipt => ({ /** The printed total matches the lines the AI read. */ const coherent = receipt(950); -/** The AI read the printed total but missed lines worth 32.80. */ -const overstated = receipt(4230); +/** The AI read the printed total but missed a line worth 1.50. */ +const overstated = receipt(1100); /** The AI misread the printed total as lower than the lines it did read. */ const understated = receipt(100); @@ -130,6 +130,20 @@ async function removeLineItem( return (await res.json()) as Draft; } +function patchSession( + app: SessionApp, + draft: Draft, + patch: Partial<{ merchant: string; date: string; totalCents: number }>, +) { + return app.handle( + new Request(`http://localhost/sessions/${draft.id}`, { + method: 'PATCH', + headers: authorized(draft, { 'content-type': 'application/json' }), + body: JSON.stringify(patch), + }), + ); +} + function confirm(app: SessionApp, draft: Draft) { return app.handle( new Request(`http://localhost/sessions/${draft.id}/confirm`, { @@ -164,20 +178,19 @@ async function storedTotals(sessionId: string) { } describe('totalCents against the sum of the line items', () => { - it('is born already apart when the receipt total outruns the lines', async () => { + it('is born apart when the receipt total outruns the lines', async () => { const draft = await createDraft(overstatedApp); expect(await storedTotals(draft.id)).toEqual({ - totalCents: 4230, + totalCents: 1100, lineSum: 950, - gap: 3280, + gap: 150, lineCount: 2, }); }); - it('keeps the gap it was born with, whatever the owner edits', async () => { + it('holds the printed total still while the owner edits lines', async () => { const draft = await createDraft(overstatedApp); - expect((await storedTotals(draft.id)).gap).toBe(3280); const added = await addLineItem(overstatedApp, draft, { name: 'Vino', @@ -185,97 +198,74 @@ describe('totalCents against the sum of the line items', () => { unitPriceCents: 300, }); expect(await storedTotals(draft.id)).toMatchObject({ - totalCents: 4830, + totalCents: 1100, lineSum: 1550, - gap: 3280, }); await patchLineItem(overstatedApp, draft, added.lineItems[0].id, { quantity: 5, }); expect(await storedTotals(draft.id)).toMatchObject({ - totalCents: 5230, + totalCents: 1100, lineSum: 1950, - gap: 3280, }); await removeLineItem(overstatedApp, draft, added.lineItems[1].id); expect(await storedTotals(draft.id)).toMatchObject({ - totalCents: 4880, + totalCents: 1100, lineSum: 1600, - gap: 3280, }); }); - it('still claims 32.80 once every line is gone', async () => { + it('still reads the printed total once every line is gone', async () => { const draft = await createDraft(overstatedApp); for (const lineItem of draft.lineItems) await removeLineItem(overstatedApp, draft, lineItem.id); expect(await storedTotals(draft.id)).toEqual({ - totalCents: 3280, + totalCents: 1100, lineSum: 0, - gap: 3280, + gap: 1100, lineCount: 0, }); }); - it('moves the gap on its own when the clamp catches a negative total', async () => { + it('never rewrites a total the lines have overshot', async () => { const draft = await createDraft(understatedApp); - expect(await storedTotals(draft.id)).toMatchObject({ - totalCents: 100, - lineSum: 950, - gap: -850, - }); - // 100 - 600 would be -500, so the clamp rewrites the total to 0. + // Dropping 6.00 worth of lines used to drive the total negative and clamp + // it to 0. It is not the running tally any more, so it does not move. await removeLineItem(understatedApp, draft, draft.lineItems[0].id); expect(await storedTotals(draft.id)).toEqual({ - totalCents: 0, + totalCents: 100, lineSum: 350, - gap: -350, + gap: -250, lineCount: 1, }); }); +}); - it('never drifts by itself: the arithmetic is exact when the seed is', async () => { - const draft = await createDraft(coherentApp); - expect(await storedTotals(draft.id)).toMatchObject({ gap: 0 }); +describe('confirming a draft against its receipt total', () => { + it('refuses to publish while the lines fall short', async () => { + const draft = await createDraft(overstatedApp); - const withWine = await addLineItem(coherentApp, draft, { - name: 'Vino', - quantity: 2, - unitPriceCents: 300, - }); - const withDessert = await addLineItem(coherentApp, draft, { - name: 'Postre', - quantity: 1, - unitPriceCents: 450, - }); - await patchLineItem(coherentApp, draft, withDessert.lineItems[0].id, { - quantity: 5, - }); - await patchLineItem(coherentApp, draft, withDessert.lineItems[1].id, { - unitPriceCents: 400, - }); - await patchLineItem(coherentApp, draft, withWine.lineItems[2].id, { - name: 'Vino tinto', - }); - await removeLineItem(coherentApp, draft, withDessert.lineItems[3].id); + const res = await confirm(overstatedApp, draft); - expect(await storedTotals(draft.id)).toEqual({ - totalCents: 2000, - lineSum: 2000, - gap: 0, - lineCount: 3, - }); + expect(res.status).toBe(409); + expect(await res.text()).toBe('Items do not add up to the receipt total'); + expect(await storedTotals(draft.id)).toMatchObject({ gap: 150 }); }); - it('publishes the gap: confirm opens the session and nothing checks the total', async () => { + it('publishes once the owner keys in the line the AI missed', async () => { const draft = await createDraft(overstatedApp); + await addLineItem(overstatedApp, draft, { + name: 'Café', + quantity: 1, + unitPriceCents: 150, + }); const res = await confirm(overstatedApp, draft); expect(res.status).toBe(200); @@ -283,9 +273,43 @@ describe('totalCents against the sum of the line items', () => { expect(body.status).toBe('open'); expect(body.code).toMatch(CODE_PATTERN); expect(await storedTotals(draft.id)).toMatchObject({ - totalCents: 4230, - lineSum: 950, - gap: 3280, + totalCents: 1100, + lineSum: 1100, + gap: 0, }); }); + + it('publishes once the owner corrects a total the AI misread', async () => { + const draft = await createDraft(understatedApp); + + const patched = await patchSession(understatedApp, draft, { + totalCents: 950, + }); + expect(patched.status).toBe(200); + + const res = await confirm(understatedApp, draft); + + expect(res.status).toBe(200); + expect(await storedTotals(draft.id)).toMatchObject({ gap: 0 }); + }); + + it('publishes a draft that was already balanced when it arrived', async () => { + const draft = await createDraft(coherentApp); + + const res = await confirm(coherentApp, draft); + + expect(res.status).toBe(200); + expect((await res.json()).code).toMatch(CODE_PATTERN); + }); + + it('freezes the receipt total once the session is published', async () => { + const draft = await createDraft(coherentApp); + expect((await confirm(coherentApp, draft)).status).toBe(200); + + const res = await patchSession(coherentApp, draft, { totalCents: 5000 }); + + expect(res.status).toBe(409); + expect(await res.text()).toBe('Session is not editable'); + expect(await storedTotals(draft.id)).toMatchObject({ totalCents: 950 }); + }); }); From 9831293f24c03c68101c1203a313178c75d1f5ea Mon Sep 17 00:00:00 2001 From: aek676 Date: Wed, 12 Aug 2026 13:29:17 +0200 Subject: [PATCH 05/21] chore(api): sort the schema barrel alphabetically The re-exports were in no particular order, so every new schema landed wherever the last one did. Alphabetical from here on. --- apps/api/src/schemas/index.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/apps/api/src/schemas/index.ts b/apps/api/src/schemas/index.ts index b0f00d2..af6d6b7 100644 --- a/apps/api/src/schemas/index.ts +++ b/apps/api/src/schemas/index.ts @@ -1,4 +1,4 @@ -export * from './session'; -export * from './participant'; -export * from './lineItem'; export * from './claim'; +export * from './lineItem'; +export * from './participant'; +export * from './session'; From 9be32a5be15b4aeea3d3ad70de03226e9b8556ae Mon Sep 17 00:00:00 2001 From: aek676 Date: Wed, 12 Aug 2026 13:29:59 +0200 Subject: [PATCH 06/21] refactor(api): type the session view's status from its schema enum The view declared `status` as a bare string while the schema has always restricted it to draft/open/closed, so the generated API types told clients nothing about the values they can expect. It now reuses the `STATUS` tuple the Mongoose schema is built from, which also retires the `Status` alias nothing was importing. --- apps/api/src/modules/session/model.ts | 5 ++++- apps/api/src/schemas/session.ts | 1 - 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/apps/api/src/modules/session/model.ts b/apps/api/src/modules/session/model.ts index 888ef21..caaebb3 100644 --- a/apps/api/src/modules/session/model.ts +++ b/apps/api/src/modules/session/model.ts @@ -1,7 +1,10 @@ import { t } from 'elysia'; import { objectId } from '../../common/model'; +import { STATUS } from '../../schemas'; import { SUPPORTED_IMAGE_MIME_TYPES } from '../../storage/object-storage'; +const status = t.UnionEnum([...STATUS]); + const lineItemView = t.Object({ id: t.String(), name: t.String(), @@ -14,7 +17,7 @@ const lineItemView = t.Object({ const sessionView = t.Object({ id: t.String(), code: t.Nullable(t.String()), - status: t.String(), + status, merchant: t.Nullable(t.String()), date: t.Nullable(t.String()), currency: t.String(), diff --git a/apps/api/src/schemas/session.ts b/apps/api/src/schemas/session.ts index b670d18..fff6df0 100644 --- a/apps/api/src/schemas/session.ts +++ b/apps/api/src/schemas/session.ts @@ -3,7 +3,6 @@ import { lineItemSchema } from './lineItem'; import { participantSchema } from './participant'; export const STATUS = ['draft', 'open', 'closed'] as const; -export type Status = (typeof STATUS)[number]; const sessionSchema = new Schema( { From 3fce47e1d2e73b966feac30cdb9131fd9bae91fe Mon Sep 17 00:00:00 2001 From: aek676 Date: Wed, 12 Aug 2026 13:30:09 +0200 Subject: [PATCH 07/21] feat(api): let the receipt total follow the line items MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `totalCents` means what the receipt printed, and confirm refuses to publish until the items add up to it. That leaves the owner stuck whenever there is no printed total to reconcile against — a hand-written bill, a total the AI could not read — with no way out but typing the sum themselves and retyping it after every edit. A session now records where its total comes from. `totalSource: 'items'` hands it over: the total adopts the current line sum and is recomputed on every add, edit and delete, so the gap confirm checks stays closed by construction. Typing a total takes the reins back, and asking for both in the same patch is a 409 instead of a silent winner. Existing and new drafts default to 'receipt', so nothing changes until the owner asks for it. The patch body only accepts 'items': going back to a fixed total means sending the number it should be. --- .../modules/session/__test__/service.spec.ts | 112 +++++++++++++++ apps/api/src/modules/session/index.ts | 5 +- apps/api/src/modules/session/model.ts | 8 +- apps/api/src/modules/session/service.ts | 24 +++- apps/api/src/schemas/session.ts | 9 ++ apps/api/test/session-totals.spec.ts | 129 +++++++++++++++++- 6 files changed, 279 insertions(+), 8 deletions(-) diff --git a/apps/api/src/modules/session/__test__/service.spec.ts b/apps/api/src/modules/session/__test__/service.spec.ts index e8789f1..a6358a3 100644 --- a/apps/api/src/modules/session/__test__/service.spec.ts +++ b/apps/api/src/modules/session/__test__/service.spec.ts @@ -374,6 +374,118 @@ describe('SessionService.updateSession', () => { }); expect(session.totalCents).toBe(4230); }); + + it('adopts the items sum when the owner hands the total over', async () => { + const session = draftSession(); + + const result = (await sessionService().updateSession(session, { + totalSource: 'items', + })) as SessionModel['draftSessionResponse']; + + expect(result.totalSource).toBe('items'); + expect(result.totalCents).toBe(950); + }); + + it('returns 409 when the patch both fixes and hands over the total', async () => { + const session = draftSession(); + + const result = await sessionService().updateSession(session, { + totalCents: 1200, + totalSource: 'items', + }); + + expect(result).toMatchObject({ + code: 409, + response: 'Cannot set a total while it follows the items', + }); + expect(session.totalCents).toBe(4230); + expect(session.totalSource).toBe('receipt'); + }); + + it('goes back to a fixed total when the owner types one in', async () => { + const session = draftSession(); + session.totalSource = 'items'; + + const result = (await sessionService().updateSession(session, { + totalCents: 1200, + })) as SessionModel['draftSessionResponse']; + + expect(result.totalSource).toBe('receipt'); + expect(result.totalCents).toBe(1200); + }); +}); + +describe('a total handed over to the items', () => { + beforeEach(() => { + spyOn(console, 'error').mockImplementation(() => {}); + spyOn(Session.prototype, 'save').mockImplementation(async function ( + this: unknown, + ) { + return this; + }); + }); + + afterEach(() => { + mock.restore(); + }); + + function followingSession() { + const session = draftSession(); + session.totalSource = 'items'; + session.totalCents = 950; + return session; + } + + it('follows an added line', async () => { + const session = followingSession(); + + const result = (await sessionService().addLineItem(session, { + name: 'Vino', + quantity: 2, + unitPriceCents: 300, + })) as SessionModel['draftSessionResponse']; + + expect(result.totalCents).toBe(1550); + }); + + it('follows an edited line', async () => { + const session = followingSession(); + const id = String(session.lineItems[0]._id); + + const result = (await sessionService().updateLineItem(session, id, { + quantity: 5, + })) as SessionModel['draftSessionResponse']; + + expect(result.totalCents).toBe(1350); + }); + + it('follows a deleted line', async () => { + const session = followingSession(); + const id = String(session.lineItems[0]._id); + + const result = (await sessionService().deleteLineItem( + session, + id, + )) as SessionModel['draftSessionResponse']; + + expect(result.totalCents).toBe(350); + }); + + it('never trips the confirm gate', async () => { + const session = followingSession(); + for (const item of session.lineItems) item.aiConfidence = 1; + + await sessionService().addLineItem(session, { + name: 'Vino', + quantity: 2, + unitPriceCents: 300, + }); + const result = (await sessionService().confirmSession( + session, + )) as SessionModel['draftSessionResponse']; + + expect(result.status).toBe('open'); + }); }); describe('SessionService.addLineItem', () => { diff --git a/apps/api/src/modules/session/index.ts b/apps/api/src/modules/session/index.ts index fb5d94b..d2389ae 100644 --- a/apps/api/src/modules/session/index.ts +++ b/apps/api/src/modules/session/index.ts @@ -57,7 +57,10 @@ export function createSessionModule(service: SessionService) { 200: SessionModel.draftSessionResponse, 401: AuthModel.unauthorized, 403: AuthModel.forbidden, - 409: SessionModel.sessionNotDraft, + 409: t.Union([ + SessionModel.sessionNotDraft, + SessionModel.totalPatchConflict, + ]), 500: SessionModel.internalError, }, detail: { diff --git a/apps/api/src/modules/session/model.ts b/apps/api/src/modules/session/model.ts index caaebb3..8e05fc3 100644 --- a/apps/api/src/modules/session/model.ts +++ b/apps/api/src/modules/session/model.ts @@ -1,9 +1,10 @@ import { t } from 'elysia'; import { objectId } from '../../common/model'; -import { STATUS } from '../../schemas'; +import { STATUS, TOTAL_SOURCE, type TotalSource } from '../../schemas'; import { SUPPORTED_IMAGE_MIME_TYPES } from '../../storage/object-storage'; const status = t.UnionEnum([...STATUS]); +const totalSource = t.UnionEnum([...TOTAL_SOURCE]); const lineItemView = t.Object({ id: t.String(), @@ -22,6 +23,7 @@ const sessionView = t.Object({ date: t.Nullable(t.String()), currency: t.String(), totalCents: t.Number(), + totalSource, receiptImageUrl: t.String(), lineItems: t.Array(lineItemView), }); @@ -36,6 +38,7 @@ const sessionUpdateBody = t.Partial( merchant: t.String({ minLength: 1 }), date: t.String({ format: 'date' }), totalCents: t.Integer({ minimum: 0 }), + totalSource: t.Literal('items' satisfies TotalSource), }), ); @@ -65,6 +68,9 @@ export const SessionModel = { internalError: t.Literal('Unexpected server error'), lineItemNotFound: t.Literal('Line item not found'), sessionNotDraft: t.Literal('Session is not editable'), + totalPatchConflict: t.Literal( + 'Cannot set a total while it follows the items', + ), sessionEmpty: t.Literal('Session has no items to split'), sessionNeedsReview: t.Literal('Some items still need review'), sessionTotalMismatch: t.Literal('Items do not add up to the receipt total'), diff --git a/apps/api/src/modules/session/service.ts b/apps/api/src/modules/session/service.ts index a258fa9..ccddea4 100644 --- a/apps/api/src/modules/session/service.ts +++ b/apps/api/src/modules/session/service.ts @@ -67,10 +67,6 @@ export function buildDraftPayload( }; } -/** - * What the line items add up to. `totalCents` holds the total printed on the - * receipt instead, so the two only meet once the owner has reviewed the draft. - */ export function lineSumCents(session: HydratedDocument): number { return session.lineItems.reduce((sum, item) => sum + item.lineTotalCents, 0); } @@ -86,6 +82,7 @@ export function toSessionView( date: session.date ? session.date.toISOString().slice(0, 10) : null, currency: session.currency, totalCents: session.totalCents, + totalSource: session.totalSource, receiptImageUrl: session.receiptImageUrl, lineItems: session.lineItems.map((item) => ({ id: String(item._id), @@ -154,9 +151,15 @@ export class SessionService { if (session.status !== 'draft') return status(409, SessionModel.sessionNotDraft.const); + if (patch.totalCents !== undefined && patch.totalSource === 'items') + return status(409, SessionModel.totalPatchConflict.const); + if (patch.merchant !== undefined) session.merchant = patch.merchant; if (patch.date !== undefined) session.date = new Date(patch.date); - if (patch.totalCents !== undefined) session.totalCents = patch.totalCents; + if (patch.totalSource === 'items' || patch.totalCents !== undefined) { + session.totalSource = patch.totalSource ?? 'receipt'; + session.totalCents = patch.totalCents ?? lineSumCents(session); + } await session.save(); return toSessionView(session); @@ -176,6 +179,10 @@ export class SessionService { lineTotalCents: input.quantity * input.unitPriceCents, aiConfidence: 1, }); + + if (session.totalSource === 'items') + session.totalCents = lineSumCents(session); + await session.save(); return toSessionView(session); } @@ -205,6 +212,9 @@ export class SessionService { ) lineItem.aiConfidence = 1; + if (session.totalSource === 'items') + session.totalCents = lineSumCents(session); + await session.save(); return toSessionView(session); } @@ -217,6 +227,10 @@ export class SessionService { if (!lineItem) return status(404, SessionModel.lineItemNotFound.const); session.lineItems.pull(lineItemId); + + if (session.totalSource === 'items') + session.totalCents = lineSumCents(session); + await session.save(); return toSessionView(session); } diff --git a/apps/api/src/schemas/session.ts b/apps/api/src/schemas/session.ts index fff6df0..6086024 100644 --- a/apps/api/src/schemas/session.ts +++ b/apps/api/src/schemas/session.ts @@ -4,6 +4,9 @@ import { participantSchema } from './participant'; export const STATUS = ['draft', 'open', 'closed'] as const; +export const TOTAL_SOURCE = ['receipt', 'items'] as const; +export type TotalSource = (typeof TOTAL_SOURCE)[number]; + const sessionSchema = new Schema( { code: String, @@ -17,6 +20,12 @@ const sessionSchema = new Schema( date: Date, currency: { type: String, default: 'EUR' }, totalCents: { type: Number, min: 0, default: 0 }, + totalSource: { + type: String, + enum: TOTAL_SOURCE, + required: true, + default: 'receipt', + }, receiptImageUrl: { type: String, default: '' }, closedAt: Date, participants: [participantSchema], diff --git a/apps/api/test/session-totals.spec.ts b/apps/api/test/session-totals.spec.ts index 1a2840a..d92c73c 100644 --- a/apps/api/test/session-totals.spec.ts +++ b/apps/api/test/session-totals.spec.ts @@ -133,7 +133,12 @@ async function removeLineItem( function patchSession( app: SessionApp, draft: Draft, - patch: Partial<{ merchant: string; date: string; totalCents: number }>, + patch: Partial<{ + merchant: string; + date: string; + totalCents: number; + totalSource: 'items'; + }>, ) { return app.handle( new Request(`http://localhost/sessions/${draft.id}`, { @@ -162,6 +167,7 @@ async function storedTotals(sessionId: string) { const stored = raw as unknown as { totalCents: number; + totalSource: string; lineItems: { lineTotalCents: number }[]; }; const lineSum = stored.lineItems.reduce( @@ -171,6 +177,7 @@ async function storedTotals(sessionId: string) { return { totalCents: stored.totalCents, + totalSource: stored.totalSource, lineSum, gap: stored.totalCents - lineSum, lineCount: stored.lineItems.length, @@ -183,6 +190,7 @@ describe('totalCents against the sum of the line items', () => { expect(await storedTotals(draft.id)).toEqual({ totalCents: 1100, + totalSource: 'receipt', lineSum: 950, gap: 150, lineCount: 2, @@ -225,6 +233,7 @@ describe('totalCents against the sum of the line items', () => { expect(await storedTotals(draft.id)).toEqual({ totalCents: 1100, + totalSource: 'receipt', lineSum: 0, gap: 1100, lineCount: 0, @@ -240,6 +249,7 @@ describe('totalCents against the sum of the line items', () => { expect(await storedTotals(draft.id)).toEqual({ totalCents: 100, + totalSource: 'receipt', lineSum: 350, gap: -250, lineCount: 1, @@ -313,3 +323,120 @@ describe('confirming a draft against its receipt total', () => { expect(await storedTotals(draft.id)).toMatchObject({ totalCents: 950 }); }); }); + +describe('handing the total over to the items', () => { + it('adopts the items sum and keeps following every edit', async () => { + const draft = await createDraft(overstatedApp); + expect(await storedTotals(draft.id)).toMatchObject({ gap: 150 }); + + const handed = await patchSession(overstatedApp, draft, { + totalSource: 'items', + }); + expect(handed.status).toBe(200); + expect(await storedTotals(draft.id)).toMatchObject({ + totalCents: 950, + gap: 0, + }); + + const added = await addLineItem(overstatedApp, draft, { + name: 'Vino', + quantity: 2, + unitPriceCents: 300, + }); + expect(await storedTotals(draft.id)).toMatchObject({ + totalCents: 1550, + gap: 0, + }); + + await patchLineItem(overstatedApp, draft, added.lineItems[0].id, { + quantity: 5, + }); + expect(await storedTotals(draft.id)).toMatchObject({ gap: 0 }); + + await removeLineItem(overstatedApp, draft, added.lineItems[2].id); + expect(await storedTotals(draft.id)).toMatchObject({ gap: 0 }); + + const res = await confirm(overstatedApp, draft); + expect(res.status).toBe(200); + }); + + it('typing a total takes the reins back from the items', async () => { + const draft = await createDraft(overstatedApp); + await patchSession(overstatedApp, draft, { totalSource: 'items' }); + + const res = await patchSession(overstatedApp, draft, { totalCents: 2000 }); + expect(res.status).toBe(200); + + await addLineItem(overstatedApp, draft, { + name: 'Vino', + quantity: 1, + unitPriceCents: 100, + }); + expect(await storedTotals(draft.id)).toMatchObject({ + totalCents: 2000, + lineSum: 1050, + }); + }); + + // The update body used to carry the full `totalSource` enum, and `t.UnionEnum` + // ships a `default` that Elysia writes into every body — so a patch that never + // mentioned the total still arrived with one, and dropped the session back to + // the receipt. Only the route sees it: the service is handed a clean patch. + it('keeps following the items when an unrelated field is edited', async () => { + const draft = await createDraft(overstatedApp); + await patchSession(overstatedApp, draft, { totalSource: 'items' }); + + const res = await patchSession(overstatedApp, draft, { + merchant: 'Bar Pepe', + }); + expect(res.status).toBe(200); + expect(await storedTotals(draft.id)).toMatchObject({ + totalSource: 'items', + gap: 0, + }); + + await addLineItem(overstatedApp, draft, { + name: 'Vino', + quantity: 2, + unitPriceCents: 300, + }); + expect(await storedTotals(draft.id)).toMatchObject({ + totalCents: 1550, + gap: 0, + }); + }); + + it('rejects handing the total back to the receipt without a number', async () => { + const draft = await createDraft(overstatedApp); + await patchSession(overstatedApp, draft, { totalSource: 'items' }); + + const res = await overstatedApp.handle( + new Request(`http://localhost/sessions/${draft.id}`, { + method: 'PATCH', + headers: authorized(draft, { 'content-type': 'application/json' }), + body: JSON.stringify({ totalSource: 'receipt' }), + }), + ); + + expect(res.status).toBe(422); + expect(await storedTotals(draft.id)).toMatchObject({ + totalCents: 950, + gap: 0, + }); + }); + + it('rejects fixing a total and handing it over in the same patch', async () => { + const draft = await createDraft(overstatedApp); + + const res = await patchSession(overstatedApp, draft, { + totalCents: 2000, + totalSource: 'items', + }); + + expect(res.status).toBe(409); + expect(await res.text()).toBe( + 'Cannot set a total while it follows the items', + ); + expect(await storedTotals(draft.id)).toMatchObject({ totalCents: 1100 }); + }); +}); From e721fbf70a801967e0f157d8751c8a2f462724f4 Mon Sep 17 00:00:00 2001 From: aek676 Date: Wed, 12 Aug 2026 14:35:01 +0200 Subject: [PATCH 08/21] feat(web): add a bare currency formatter --- apps/web/src/utils/__test__/money.spec.ts | 18 +++++++++++++++++- apps/web/src/utils/money.ts | 8 ++++++++ 2 files changed, 25 insertions(+), 1 deletion(-) diff --git a/apps/web/src/utils/__test__/money.spec.ts b/apps/web/src/utils/__test__/money.spec.ts index fedb27f..cf98e69 100644 --- a/apps/web/src/utils/__test__/money.spec.ts +++ b/apps/web/src/utils/__test__/money.spec.ts @@ -1,5 +1,10 @@ import { describe, expect, it } from 'vitest'; -import { currencyFormat, currencySymbol, formatCents } from '@/utils/money'; +import { + currencyFormat, + currencySymbol, + formatCents, + formatCentsBare, +} from '@/utils/money'; /** Locale separators are routinely not ASCII whitespace. */ const NBSP = ' '; @@ -12,6 +17,17 @@ describe('formatCents', () => { }); }); +describe('formatCentsBare', () => { + it('formats the amount without a currency symbol', () => { + expect(formatCentsBare(4230, 'EUR')).toMatch(/^42[.,]30$/); + expect(formatCentsBare(0, 'EUR')).toMatch(/^0[.,]00$/); + }); + + it('takes the fraction digits from the currency', () => { + expect(formatCentsBare(4230, 'JPY')).toBe('42'); + }); +}); + describe('currencySymbol', () => { it('returns the narrow symbol for a currency', () => { expect(currencySymbol('EUR')).toBe('€'); diff --git a/apps/web/src/utils/money.ts b/apps/web/src/utils/money.ts index cef256a..ce165e2 100644 --- a/apps/web/src/utils/money.ts +++ b/apps/web/src/utils/money.ts @@ -5,6 +5,14 @@ export function formatCents(cents: number, currency: string): string { }).format(cents / 100); } +export function formatCentsBare(cents: number, currency: string): string { + const { decimalScale } = currencyFormat(currency); + return new Intl.NumberFormat(undefined, { + minimumFractionDigits: decimalScale, + maximumFractionDigits: decimalScale, + }).format(cents / 100); +} + export interface CurrencyFormat { symbol: string; prefix: string; From e4f5d0a1e7df1ade6854f884c215488eca20bee2 Mon Sep 17 00:00:00 2001 From: aek676 Date: Wed, 12 Aug 2026 14:35:06 +0200 Subject: [PATCH 09/21] feat(web): let the client update the session's receipt total --- .../features/session/api/update-session.ts | 59 ++++++++ .../session/components/edit-receipt-total.tsx | 129 ++++++++++++++++++ .../utils/__test__/receipt-totals.spec.ts | 48 +++++++ .../features/session/utils/receipt-totals.ts | 22 +++ 4 files changed, 258 insertions(+) create mode 100644 apps/web/src/features/session/api/update-session.ts create mode 100644 apps/web/src/features/session/components/edit-receipt-total.tsx create mode 100644 apps/web/src/features/session/utils/__test__/receipt-totals.spec.ts create mode 100644 apps/web/src/features/session/utils/receipt-totals.ts diff --git a/apps/web/src/features/session/api/update-session.ts b/apps/web/src/features/session/api/update-session.ts new file mode 100644 index 0000000..50d7dea --- /dev/null +++ b/apps/web/src/features/session/api/update-session.ts @@ -0,0 +1,59 @@ +import { useMutation, useQueryClient } from '@tanstack/react-query'; +import { z } from 'zod'; +import { api, apiError } from '@/lib/api-client'; +import type { MutationConfig } from '@/lib/react-query'; +import type { Session } from '@/types/session'; +import { getSessionQueryOptions } from './get-session'; + +export const receiptTotalInputSchema = z.object({ + totalCents: z.int().min(0, 'Must be at least 0'), +}); + +export const updateSessionInputSchema = z.union([ + receiptTotalInputSchema, + z.object({ totalSource: z.literal('items') }), +]); + +export type UpdateSessionInput = z.infer; + +export const updateSession = async ({ + sessionId, + data, +}: { + sessionId: string; + data: UpdateSessionInput; +}): Promise => { + return api + .sessions({ sessionId }) + .patch(data) + .then(({ data, error }) => { + if (error) + throw apiError(error.value, 'Failed to update the receipt total'); + return data; + }); +}; + +type UseUpdateSessionOptions = { + sessionId: string; + mutationConfig?: MutationConfig; +}; + +export const useUpdateSession = ({ + sessionId, + mutationConfig, +}: UseUpdateSessionOptions) => { + const queryClient = useQueryClient(); + + const { onSuccess, ...restConfig } = mutationConfig || {}; + + return useMutation({ + onSuccess: (...args) => { + queryClient.invalidateQueries({ + queryKey: getSessionQueryOptions(sessionId).queryKey, + }); + onSuccess?.(...args); + }, + ...restConfig, + mutationFn: updateSession, + }); +}; diff --git a/apps/web/src/features/session/components/edit-receipt-total.tsx b/apps/web/src/features/session/components/edit-receipt-total.tsx new file mode 100644 index 0000000..dded878 --- /dev/null +++ b/apps/web/src/features/session/components/edit-receipt-total.tsx @@ -0,0 +1,129 @@ +import { useForm } from '@tanstack/react-form'; +import { Pencil } from 'lucide-react'; +import { useState } from 'react'; + +import { Button } from 'shadcn-ui/button'; +import { + Dialog, + DialogClose, + DialogContent, + DialogFooter, + DialogHeader, + DialogTitle, + DialogTrigger, +} from 'shadcn-ui/dialog'; +import { Field, FieldError, FieldGroup, FieldLabel } from 'shadcn-ui/field'; + +import { CurrencyInput } from '@/components/ui/form/currency-input'; +import { + receiptTotalInputSchema, + useUpdateSession, +} from '@/features/session/api/update-session'; +import type { Session } from '@/types/session'; + +interface EditReceiptTotalProps { + session: Session; +} + +export function EditReceiptTotal({ session }: EditReceiptTotalProps) { + const [open, setOpen] = useState(false); + + return ( + + + + + } + /> + + + Edit receipt total + + setOpen(false)} + /> + + + ); +} + +type EditReceiptTotalFormProps = { + session: Session; + onSaved: () => void; +}; + +function EditReceiptTotalForm({ session, onSaved }: EditReceiptTotalFormProps) { + const updateSession = useUpdateSession({ sessionId: session.id }); + const form = useForm({ + defaultValues: { + totalCents: session.totalCents, + }, + validators: { + onSubmit: receiptTotalInputSchema, + }, + onSubmit: async ({ value }) => { + updateSession.mutate( + { sessionId: session.id, data: value }, + { onSuccess: onSaved }, + ); + }, + }); + + return ( +
{ + event.preventDefault(); + form.handleSubmit(); + }} + > + + + {(field) => { + const isInvalid = + field.state.meta.isTouched && !field.state.meta.isValid; + return ( + + + Total + + field.handleChange(cents)} + /> + {isInvalid && } + + ); + }} + + + + }> + Cancel + + ({ + canSubmit: s.canSubmit, + isDirty: s.isDirty, + })} + > + {({ canSubmit, isDirty }) => ( + + )} + + +
+ ); +} diff --git a/apps/web/src/features/session/utils/__test__/receipt-totals.spec.ts b/apps/web/src/features/session/utils/__test__/receipt-totals.spec.ts new file mode 100644 index 0000000..bdadc25 --- /dev/null +++ b/apps/web/src/features/session/utils/__test__/receipt-totals.spec.ts @@ -0,0 +1,48 @@ +import { describe, expect, it } from 'vitest'; +import { receiptTotals } from '@/features/session/utils/receipt-totals'; + +function lineItem(lineTotalCents: number) { + return { + id: 'l1', + name: 'Beer', + quantity: 1, + unitPriceCents: lineTotalCents, + lineTotalCents, + aiConfidence: 1, + }; +} + +describe('receiptTotals', () => { + it('sums line totals', () => { + const totals = receiptTotals({ + lineItems: [lineItem(600), lineItem(1400)], + totalCents: 2000, + }); + expect(totals.itemsTotalCents).toBe(2000); + expect(totals.discrepancyCents).toBe(0); + expect(totals.matches).toBe(true); + }); + + it('flags rounding discrepancies of a couple of cents', () => { + const totals = receiptTotals({ + lineItems: [lineItem(999)], + totalCents: 1001, + }); + expect(totals.discrepancyCents).toBe(-2); + expect(totals.matches).toBe(false); + }); + + it('flags larger discrepancies', () => { + const totals = receiptTotals({ + lineItems: [lineItem(500)], + totalCents: 1000, + }); + expect(totals.discrepancyCents).toBe(-500); + expect(totals.matches).toBe(false); + }); + + it('handles empty receipts', () => { + const totals = receiptTotals({ lineItems: [], totalCents: 0 }); + expect(totals.matches).toBe(true); + }); +}); diff --git a/apps/web/src/features/session/utils/receipt-totals.ts b/apps/web/src/features/session/utils/receipt-totals.ts new file mode 100644 index 0000000..1458afa --- /dev/null +++ b/apps/web/src/features/session/utils/receipt-totals.ts @@ -0,0 +1,22 @@ +import type { Session } from '@/types/session'; + +export interface ReceiptTotals { + itemsTotalCents: number; + discrepancyCents: number; + matches: boolean; +} + +export function receiptTotals( + session: Pick, +): ReceiptTotals { + const itemsTotalCents = session.lineItems.reduce( + (sum, item) => sum + item.lineTotalCents, + 0, + ); + const discrepancyCents = itemsTotalCents - session.totalCents; + return { + itemsTotalCents, + discrepancyCents, + matches: discrepancyCents === 0, + }; +} From 1dca840e3dd22072f2e6ec4203efafa6de8838b5 Mon Sep 17 00:00:00 2001 From: aek676 Date: Wed, 12 Aug 2026 14:35:10 +0200 Subject: [PATCH 10/21] feat(web): surface receipt/items total mismatches in the review screen --- .../session/components/session-draft.tsx | 68 ++++++++++++++++--- 1 file changed, 60 insertions(+), 8 deletions(-) diff --git a/apps/web/src/features/session/components/session-draft.tsx b/apps/web/src/features/session/components/session-draft.tsx index 957ce3a..8000924 100644 --- a/apps/web/src/features/session/components/session-draft.tsx +++ b/apps/web/src/features/session/components/session-draft.tsx @@ -1,11 +1,14 @@ import { useForm } from '@tanstack/react-form'; import { useNavigate } from '@tanstack/react-router'; -import { Camera, Link as LinkIcon } from 'lucide-react'; +import { AlertTriangle, Camera, Link as LinkIcon } from 'lucide-react'; import { Button } from 'shadcn-ui/button'; import { useDeleteSession } from '@/features/session/api/delete-session'; +import { useUpdateSession } from '@/features/session/api/update-session'; +import { EditReceiptTotal } from '@/features/session/components/edit-receipt-total'; import { LOW_CONFIDENCE_THRESHOLD } from '@/features/session/line-item/components/line-item-row'; +import { receiptTotals } from '@/features/session/utils/receipt-totals'; import type { Session } from '@/types/session'; -import { formatCents } from '@/utils/money'; +import { formatCents, formatCentsBare } from '@/utils/money'; interface ReviewLayoutProps { session: Session; @@ -43,23 +46,72 @@ function ReviewHeader({ session }: { session: Session }) { } function ReceiptSummary({ session }: { session: Session }) { + const totals = receiptTotals(session); + const updateSession = useUpdateSession({ sessionId: session.id }); + return ( -
- Total - - {formatCents(session.totalCents, session.currency)} - +
+
+ Total +
+ + {!totals.matches && ( + <> + + {formatCentsBare(totals.itemsTotalCents, session.currency)} + + {' / '} + + )} + {formatCents(session.totalCents, session.currency)} + + +
+
+ {session.totalSource === 'items' && ( + + Kept in sync with the items + + )} + {!totals.matches && ( +
+
+ + + {formatCents(Math.abs(totals.discrepancyCents), session.currency)}{' '} + {totals.discrepancyCents > 0 ? 'over' : 'under'} the receipt total + +
+ {session.lineItems.length > 0 && ( + + )} +
+ )}
); } function ConfirmButton({ session }: { session: Session }) { + const totals = receiptTotals(session); const hasItems = session.lineItems.length > 0; const hasLowConfidence = session.lineItems.some( (item) => item.aiConfidence < LOW_CONFIDENCE_THRESHOLD, ); - const canConfirm = hasItems && !hasLowConfidence; + const canConfirm = totals.matches && hasItems && !hasLowConfidence; const form = useForm({ defaultValues: {}, From db73072fa58c5a0847a7407a29eca976317d9b77 Mon Sep 17 00:00:00 2001 From: Anass El Jabiry Date: Wed, 12 Aug 2026 19:20:08 +0200 Subject: [PATCH 11/21] fix(api): scope the integration test run to the test directory Bun treats the trailing argument as a path filter, so a bare `test` also matched the unit specs colocated under `src/**/__test__`. Anchoring it to `test/` keeps the two targets from overlapping. --- apps/api/project.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apps/api/project.json b/apps/api/project.json index 185c516..808e61f 100644 --- a/apps/api/project.json +++ b/apps/api/project.json @@ -33,7 +33,7 @@ "cache": false, "options": { "cwd": "apps/api", - "command": "bun test --preload ./test/setup.ts --coverage-dir coverage/integration test" + "command": "bun test --preload ./test/setup.ts --coverage-dir coverage/integration test/" } }, "build": { From c96d19df59158902fd8cc3050dfcf3ded3775cd6 Mon Sep 17 00:00:00 2001 From: Anass El Jabiry Date: Wed, 12 Aug 2026 19:20:20 +0200 Subject: [PATCH 12/21] test(api): await the write-failure rejection assertion Without the `await` the assertion resolved after the test had already finished, so the spec passed no matter what `confirmSession` rejected with. --- apps/api/src/modules/session/__test__/service.spec.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apps/api/src/modules/session/__test__/service.spec.ts b/apps/api/src/modules/session/__test__/service.spec.ts index a6358a3..09ec187 100644 --- a/apps/api/src/modules/session/__test__/service.spec.ts +++ b/apps/api/src/modules/session/__test__/service.spec.ts @@ -905,7 +905,7 @@ describe('SessionService.confirmSession', () => { it('lets an unrelated write failure bubble up to the module handler', async () => { spyOn(Session.prototype, 'save').mockRejectedValue(new Error('mongo down')); - expect( + await expect( sessionService().confirmSession(confirmableSession()), ).rejects.toThrow('mongo down'); }); From 6db5a7ac033cd480bf65f129e2a6183edc1d7eda Mon Sep 17 00:00:00 2001 From: Anass El Jabiry Date: Wed, 12 Aug 2026 19:20:20 +0200 Subject: [PATCH 13/21] test(api): pin that only code collisions are retried on confirm A duplicate-key error raised on any other index must reach the module handler untouched rather than burn a code-generation attempt. --- .../src/modules/session/__test__/service.spec.ts | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/apps/api/src/modules/session/__test__/service.spec.ts b/apps/api/src/modules/session/__test__/service.spec.ts index 09ec187..d249a3b 100644 --- a/apps/api/src/modules/session/__test__/service.spec.ts +++ b/apps/api/src/modules/session/__test__/service.spec.ts @@ -909,4 +909,18 @@ describe('SessionService.confirmSession', () => { sessionService().confirmSession(confirmableSession()), ).rejects.toThrow('mongo down'); }); + + it('lets a duplicate on another key bubble up instead of retrying', async () => { + const save = spyOn(Session.prototype, 'save').mockRejectedValue( + Object.assign(new Error('E11000 duplicate key'), { + code: 11000, + keyPattern: { 'participants.deviceTokenHash': 1 }, + }), + ); + + await expect( + sessionService().confirmSession(confirmableSession()), + ).rejects.toThrow('E11000 duplicate key'); + expect(save).toHaveBeenCalledTimes(1); + }); }); From e109101b84a1cfde9cba6d55d400c4eaaa22976f Mon Sep 17 00:00:00 2001 From: Anass El Jabiry Date: Wed, 12 Aug 2026 19:20:43 +0200 Subject: [PATCH 14/21] test(api): cover session code collisions against a real unique index Scripts `crypto.getRandomValues` so two confirms draw the same code, then checks both ends of the retry loop against Mongo: the second session publishes with a fresh code, and when every attempt collides the session stays a draft with the taken code still owned by the first. --- apps/api/test/session-code-collision.spec.ts | 109 +++++++++++++++++++ 1 file changed, 109 insertions(+) create mode 100644 apps/api/test/session-code-collision.spec.ts diff --git a/apps/api/test/session-code-collision.spec.ts b/apps/api/test/session-code-collision.spec.ts new file mode 100644 index 0000000..6f7a1b7 --- /dev/null +++ b/apps/api/test/session-code-collision.spec.ts @@ -0,0 +1,109 @@ +import { afterEach, beforeAll, describe, expect, it, spyOn } from 'bun:test'; +import { Types } from 'mongoose'; +import { createSessionModule } from '../src/modules/session'; +import { SessionService } from '../src/modules/session/service'; +import { Session } from '../src/schemas'; +import { analyzeRequest, fakeExtract } from './fixtures'; +import { testStorage } from './setup'; + +const CODE_PATTERN = /^[ABCDEFGHJKLMNPQRSTUVWXYZ23456789]{8}$/; +/** Bytes of 0 always land on the alphabet's first letter. */ +const COLLIDING_CODE = 'AAAAAAAA'; + +const spies: { mockRestore: () => void }[] = []; + +const app = createSessionModule(new SessionService(fakeExtract, testStorage())); + +type Draft = { id: string; auth: { token: string } }; + +async function createDraft() { + const res = await app.handle(analyzeRequest()); + expect(res.status).toBe(200); + return (await res.json()) as Draft; +} + +function confirm(draft: Draft) { + return app.handle( + new Request(`http://localhost/sessions/${draft.id}/confirm`, { + method: 'POST', + headers: { authorization: `Bearer ${draft.auth.token}` }, + }), + ); +} + +function scriptCodeDraws(...bytes: number[]) { + let call = 0; + const spy = spyOn(crypto, 'getRandomValues').mockImplementation((array) => { + const byte = bytes[Math.min(call++, bytes.length - 1)]; + if (array) + new Uint8Array(array.buffer, array.byteOffset, array.byteLength).fill( + byte, + ); + return array; + }); + spies.push(spy); + return spy; +} + +async function storedSession(sessionId: string) { + return (await Session.collection.findOne({ + _id: new Types.ObjectId(sessionId), + })) as unknown as { status: string; code?: string } | null; +} + +beforeAll(async () => { + await Session.syncIndexes(); +}); + +afterEach(() => { + for (const spy of spies.splice(0).reverse()) spy.mockRestore(); +}); + +describe('confirming when the drawn code is already taken', () => { + it('retries past the collision and publishes with a fresh code', async () => { + const first = await createDraft(); + const second = await createDraft(); + + scriptCodeDraws(0); + expect((await confirm(first)).status).toBe(200); + + scriptCodeDraws(0, 1); + const res = await confirm(second); + + expect(res.status).toBe(200); + const body = (await res.json()) as { status: string; code: string }; + expect(body.status).toBe('open'); + expect(body.code).toMatch(CODE_PATTERN); + expect(body.code).not.toBe(COLLIDING_CODE); + + const [storedFirst, storedSecond] = await Promise.all([ + storedSession(first.id), + storedSession(second.id), + ]); + expect(storedFirst?.code).toBe(COLLIDING_CODE); + expect(storedSecond?.status).toBe('open'); + expect(storedSecond?.code).toBe(body.code); + }); + + it('gives up after every attempt draws the taken code', async () => { + const first = await createDraft(); + const second = await createDraft(); + + scriptCodeDraws(0); + expect((await confirm(first)).status).toBe(200); + + spies.push(spyOn(console, 'error').mockImplementation(() => {})); + scriptCodeDraws(0); + const res = await confirm(second); + + expect(res.status).toBe(500); + expect(await res.text()).toBe('Failed to generate a session code'); + + const stored = await storedSession(second.id); + expect(stored?.status).toBe('draft'); + expect(stored?.code).toBeUndefined(); + expect( + await Session.collection.countDocuments({ code: COLLIDING_CODE }), + ).toBe(1); + }); +}); From 3261df4c0c71a15145e812cc599645f007fdbaa1 Mon Sep 17 00:00:00 2001 From: Anass El Jabiry Date: Wed, 12 Aug 2026 22:32:53 +0200 Subject: [PATCH 15/21] test(api): type the getRandomValues mock generically --- apps/api/test/session-code-collision.spec.ts | 18 ++++++++++-------- 1 file changed, 10 insertions(+), 8 deletions(-) diff --git a/apps/api/test/session-code-collision.spec.ts b/apps/api/test/session-code-collision.spec.ts index 6f7a1b7..30e1bc4 100644 --- a/apps/api/test/session-code-collision.spec.ts +++ b/apps/api/test/session-code-collision.spec.ts @@ -33,14 +33,16 @@ function confirm(draft: Draft) { function scriptCodeDraws(...bytes: number[]) { let call = 0; - const spy = spyOn(crypto, 'getRandomValues').mockImplementation((array) => { - const byte = bytes[Math.min(call++, bytes.length - 1)]; - if (array) - new Uint8Array(array.buffer, array.byteOffset, array.byteLength).fill( - byte, - ); - return array; - }); + const spy = spyOn(crypto, 'getRandomValues').mockImplementation( + (array: T): T => { + const byte = bytes[Math.min(call++, bytes.length - 1)]; + if (array) + new Uint8Array(array.buffer, array.byteOffset, array.byteLength).fill( + byte, + ); + return array; + }, + ); spies.push(spy); return spy; } From a47fbee448923c5e1a93702a0993df8aa2d193c7 Mon Sep 17 00:00:00 2001 From: Anass El Jabiry Date: Wed, 12 Aug 2026 22:32:59 +0200 Subject: [PATCH 16/21] feat(web): confirm a draft session from the review screen Replace the placeholder confirm button with a real mutation against POST /sessions/:id/confirm, seeding the response into the session query so the screen reacts to the published share code. --- .../features/session/api/confirm-session.ts | 45 +++++++++++++++++++ .../components/confirm-session-button.tsx | 33 ++++++++++++++ .../session/components/session-draft.tsx | 41 ++--------------- 3 files changed, 81 insertions(+), 38 deletions(-) create mode 100644 apps/web/src/features/session/api/confirm-session.ts create mode 100644 apps/web/src/features/session/components/confirm-session-button.tsx diff --git a/apps/web/src/features/session/api/confirm-session.ts b/apps/web/src/features/session/api/confirm-session.ts new file mode 100644 index 0000000..cfffb32 --- /dev/null +++ b/apps/web/src/features/session/api/confirm-session.ts @@ -0,0 +1,45 @@ +import { useMutation, useQueryClient } from '@tanstack/react-query'; +import { api, apiError } from '@/lib/api-client'; +import type { MutationConfig } from '@/lib/react-query'; +import type { Session } from '@/types/session'; +import { getSessionQueryOptions } from './get-session'; + +export const confirmSession = async ({ + sessionId, +}: { + sessionId: string; +}): Promise => { + return api + .sessions({ sessionId }) + .confirm.post() + .then(({ data, error }) => { + if (error) throw apiError(error.value, 'Failed to confirm the session'); + return data; + }); +}; + +type UseConfirmSessionOptions = { + sessionId: string; + mutationConfig?: MutationConfig; +}; + +export const useConfirmSession = ({ + sessionId, + mutationConfig, +}: UseConfirmSessionOptions) => { + const queryClient = useQueryClient(); + + const { onSuccess, ...restConfig } = mutationConfig || {}; + + return useMutation({ + onSuccess: (session, ...args) => { + queryClient.setQueryData( + getSessionQueryOptions(sessionId).queryKey, + session, + ); + onSuccess?.(session, ...args); + }, + ...restConfig, + mutationFn: confirmSession, + }); +}; diff --git a/apps/web/src/features/session/components/confirm-session-button.tsx b/apps/web/src/features/session/components/confirm-session-button.tsx new file mode 100644 index 0000000..b40ba8a --- /dev/null +++ b/apps/web/src/features/session/components/confirm-session-button.tsx @@ -0,0 +1,33 @@ +import { Link as LinkIcon } from 'lucide-react'; +import { Button } from 'shadcn-ui/button'; +import { useConfirmSession } from '@/features/session/api/confirm-session'; +import { LOW_CONFIDENCE_THRESHOLD } from '@/features/session/line-item/components/line-item-row'; +import { receiptTotals } from '@/features/session/utils/receipt-totals'; +import type { Session } from '@/types/session'; + +interface ConfirmSessionButtonProps { + session: Session; +} + +export function ConfirmSessionButton({ session }: ConfirmSessionButtonProps) { + const totals = receiptTotals(session); + const hasItems = session.lineItems.length > 0; + const hasLowConfidence = session.lineItems.some( + (item) => item.aiConfidence < LOW_CONFIDENCE_THRESHOLD, + ); + + const canConfirm = totals.matches && hasItems && !hasLowConfidence; + const confirmSession = useConfirmSession({ sessionId: session.id }); + + return ( + + ); +} \ No newline at end of file diff --git a/apps/web/src/features/session/components/session-draft.tsx b/apps/web/src/features/session/components/session-draft.tsx index 8000924..da64086 100644 --- a/apps/web/src/features/session/components/session-draft.tsx +++ b/apps/web/src/features/session/components/session-draft.tsx @@ -1,11 +1,10 @@ -import { useForm } from '@tanstack/react-form'; import { useNavigate } from '@tanstack/react-router'; -import { AlertTriangle, Camera, Link as LinkIcon } from 'lucide-react'; +import { AlertTriangle, Camera } from 'lucide-react'; import { Button } from 'shadcn-ui/button'; import { useDeleteSession } from '@/features/session/api/delete-session'; import { useUpdateSession } from '@/features/session/api/update-session'; +import { ConfirmSessionButton } from '@/features/session/components/confirm-session-button'; import { EditReceiptTotal } from '@/features/session/components/edit-receipt-total'; -import { LOW_CONFIDENCE_THRESHOLD } from '@/features/session/line-item/components/line-item-row'; import { receiptTotals } from '@/features/session/utils/receipt-totals'; import type { Session } from '@/types/session'; import { formatCents, formatCentsBare } from '@/utils/money'; @@ -104,40 +103,6 @@ function ReceiptSummary({ session }: { session: Session }) { ); } -function ConfirmButton({ session }: { session: Session }) { - const totals = receiptTotals(session); - const hasItems = session.lineItems.length > 0; - const hasLowConfidence = session.lineItems.some( - (item) => item.aiConfidence < LOW_CONFIDENCE_THRESHOLD, - ); - - const canConfirm = totals.matches && hasItems && !hasLowConfidence; - - const form = useForm({ - defaultValues: {}, - onSubmit: async () => { - // TODO: Implement backend endpoint and mutation - console.log('Confirm session:', session.id); - }, - }); - - return ( - - {() => ( - - )} - - ); -} - function RetakePhotoButton({ session }: { session: Session }) { const navigate = useNavigate(); const deleteSession = useDeleteSession({ sessionId: session.id }); @@ -166,7 +131,7 @@ function ReviewFooter({ session }: { session: Session }) {
- +
); From a280e34ed05c230ca49e389f20a02d4124a65846 Mon Sep 17 00:00:00 2001 From: Anass El Jabiry Date: Wed, 12 Aug 2026 22:33:04 +0200 Subject: [PATCH 17/21] feat(web): redirect a confirmed session to its share link The API already refuses every edit once a session leaves the draft status, so keep the review screen from showing an editor the server would reject. --- .../web/src/app/routes/sessions.$sessionId.review.tsx | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/apps/web/src/app/routes/sessions.$sessionId.review.tsx b/apps/web/src/app/routes/sessions.$sessionId.review.tsx index 101e779..f3c74f3 100644 --- a/apps/web/src/app/routes/sessions.$sessionId.review.tsx +++ b/apps/web/src/app/routes/sessions.$sessionId.review.tsx @@ -1,8 +1,9 @@ -import { createFileRoute, redirect } from '@tanstack/react-router'; +import { createFileRoute, Navigate, redirect } from '@tanstack/react-router'; import { Alert, AlertDescription } from 'shadcn-ui/alert'; import { Button } from 'shadcn-ui/button'; import { Spinner } from 'shadcn-ui/spinner'; + import { useSession } from '@/features/session/api/get-session'; import { ReviewLayout } from '@/features/session/components/session-draft'; import { LineItemList } from '@/features/session/line-item/components/line-item-list'; @@ -42,6 +43,14 @@ function ReviewPage() { const session = sessionQuery.data; + if (session.status !== 'draft') { + return session.code ? ( + + ) : ( + + ); + } + return ( From 6bc383e74c66f805979de648fd44953477d7814e Mon Sep 17 00:00:00 2001 From: Anass El Jabiry Date: Wed, 12 Aug 2026 22:42:08 +0200 Subject: [PATCH 18/21] style(web): add the missing trailing newline to the confirm button --- .../src/features/session/components/confirm-session-button.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apps/web/src/features/session/components/confirm-session-button.tsx b/apps/web/src/features/session/components/confirm-session-button.tsx index b40ba8a..4dd47eb 100644 --- a/apps/web/src/features/session/components/confirm-session-button.tsx +++ b/apps/web/src/features/session/components/confirm-session-button.tsx @@ -30,4 +30,4 @@ export function ConfirmSessionButton({ session }: ConfirmSessionButtonProps) { ); -} \ No newline at end of file +} From 05119bfbd2d4f33c1c52330d1745930bb3876f2e Mon Sep 17 00:00:00 2001 From: Anass El Jabiry Date: Wed, 12 Aug 2026 23:35:47 +0200 Subject: [PATCH 19/21] refactor: share the low-confidence threshold between the api and the web Both sides gated on 0.7 from their own copy. If they drifted, the review screen would enable Confirm & create link while the server answered 409 Some items still need review, which no client renders. --- apps/api/src/modules/session/service.ts | 3 +-- .../features/session/components/confirm-session-button.tsx | 2 +- .../features/session/line-item/components/line-item-row.tsx | 3 +-- libs/shared-types/src/index.ts | 1 + libs/shared-types/src/lib/confidence.ts | 5 +++++ 5 files changed, 9 insertions(+), 5 deletions(-) create mode 100644 libs/shared-types/src/lib/confidence.ts diff --git a/apps/api/src/modules/session/service.ts b/apps/api/src/modules/session/service.ts index ccddea4..30e94f8 100644 --- a/apps/api/src/modules/session/service.ts +++ b/apps/api/src/modules/session/service.ts @@ -1,3 +1,4 @@ +import { LOW_CONFIDENCE_THRESHOLD } from '@repo/shared-types'; import { status } from 'elysia'; import type { HydratedDocument } from 'mongoose'; import type { ExtractedReceipt, ExtractReceipt } from '../../ai/receipt'; @@ -16,8 +17,6 @@ const CODE_ALPHABET = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789'; const CODE_LENGTH = 8; const CODE_ATTEMPTS = 5; -export const LOW_CONFIDENCE_THRESHOLD = 0.7; - export function generateSessionCode() { const bytes = new Uint8Array(CODE_LENGTH); crypto.getRandomValues(bytes); diff --git a/apps/web/src/features/session/components/confirm-session-button.tsx b/apps/web/src/features/session/components/confirm-session-button.tsx index 4dd47eb..7b95094 100644 --- a/apps/web/src/features/session/components/confirm-session-button.tsx +++ b/apps/web/src/features/session/components/confirm-session-button.tsx @@ -1,7 +1,7 @@ +import { LOW_CONFIDENCE_THRESHOLD } from '@repo/shared-types'; import { Link as LinkIcon } from 'lucide-react'; import { Button } from 'shadcn-ui/button'; import { useConfirmSession } from '@/features/session/api/confirm-session'; -import { LOW_CONFIDENCE_THRESHOLD } from '@/features/session/line-item/components/line-item-row'; import { receiptTotals } from '@/features/session/utils/receipt-totals'; import type { Session } from '@/types/session'; diff --git a/apps/web/src/features/session/line-item/components/line-item-row.tsx b/apps/web/src/features/session/line-item/components/line-item-row.tsx index 3c10fb1..927a880 100644 --- a/apps/web/src/features/session/line-item/components/line-item-row.tsx +++ b/apps/web/src/features/session/line-item/components/line-item-row.tsx @@ -1,10 +1,9 @@ +import { LOW_CONFIDENCE_THRESHOLD } from '@repo/shared-types'; import { Money } from '@/components/ui/money'; import { DeleteLineItem } from '@/features/session/line-item/components/delete-line-item'; import { EditLineItem } from '@/features/session/line-item/components/edit-line-item'; import type { LineItem } from '@/types/session'; -export const LOW_CONFIDENCE_THRESHOLD = 0.7; - interface LineItemRowProps { sessionId: string; lineItem: LineItem; diff --git a/libs/shared-types/src/index.ts b/libs/shared-types/src/index.ts index 7bafc55..e96f4d7 100644 --- a/libs/shared-types/src/index.ts +++ b/libs/shared-types/src/index.ts @@ -1,2 +1,3 @@ +export * from './lib/confidence'; export * from './lib/media-types'; export * from './lib/object-id'; diff --git a/libs/shared-types/src/lib/confidence.ts b/libs/shared-types/src/lib/confidence.ts new file mode 100644 index 0000000..673f37f --- /dev/null +++ b/libs/shared-types/src/lib/confidence.ts @@ -0,0 +1,5 @@ +/** + * Below this, an extracted line item still needs the owner's eyes: the review + * screen flags it, and confirming a session is refused while one remains. + */ +export const LOW_CONFIDENCE_THRESHOLD = 0.7; From d98f959e2967ade14423342126a675cdab5c1c5a Mon Sep 17 00:00:00 2001 From: Anass El Jabiry Date: Wed, 12 Aug 2026 23:35:56 +0200 Subject: [PATCH 20/21] fix(api): publish a session with a conditional update MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Confirm read the session, set status and code on the hydrated document and saved it. That save emits a $set keyed on _id alone — the schema sets no optimisticConcurrency, so mongoose adds no __v predicate — and two concurrent confirms both went through, the second overwriting the first. The caller that lost held a code that was no longer stored. The publish is now a findOneAndUpdate conditioned on status: 'draft'. No match means someone else published first, which is the same 409 the route already declares, so the response contract is unchanged. A duplicate key on code still means a collision, so the redraw loop carries over. isDuplicateKeyError counted a missing keyPattern as a match, which would have retried on any duplicate arriving without one. Mongo always sends it, so the branch only widened the retry for a case that cannot happen. --- apps/api/src/common/mongo.ts | 5 +- .../modules/session/__test__/index.spec.ts | 32 +++++- .../modules/session/__test__/service.spec.ts | 106 ++++++++++++++---- apps/api/src/modules/session/service.ts | 11 +- .../test/session-confirm-concurrency.spec.ts | 62 ++++++++++ 5 files changed, 183 insertions(+), 33 deletions(-) create mode 100644 apps/api/test/session-confirm-concurrency.spec.ts diff --git a/apps/api/src/common/mongo.ts b/apps/api/src/common/mongo.ts index 2f0823b..ddc1522 100644 --- a/apps/api/src/common/mongo.ts +++ b/apps/api/src/common/mongo.ts @@ -1,9 +1,8 @@ -export function isDuplicateKeyError(error: unknown, key?: string): boolean { +export function isDuplicateKeyError(error: unknown, key: string): boolean { if (typeof error !== 'object' || error === null) return false; const { code, keyPattern } = error as { code?: number; keyPattern?: Record; }; - if (code !== 11000) return false; - return key === undefined || keyPattern === undefined || key in keyPattern; + return code === 11000 && keyPattern?.[key] !== undefined; } diff --git a/apps/api/src/modules/session/__test__/index.spec.ts b/apps/api/src/modules/session/__test__/index.spec.ts index e7597a7..cd9632e 100644 --- a/apps/api/src/modules/session/__test__/index.spec.ts +++ b/apps/api/src/modules/session/__test__/index.spec.ts @@ -185,6 +185,18 @@ function mockLookup(session: unknown) { return spyOn(Session, 'findOne').mockImplementation((() => query) as never); } +/** Stands in for the conditional publish, applying the `$set` to `target`. */ +function mockPublish(target: unknown) { + return spyOn(Session, 'findOneAndUpdate').mockImplementation((( + _filter: unknown, + update: { $set: Record }, + ) => { + if (!target) return Promise.resolve(null); + Object.assign(target, update.$set); + return Promise.resolve(target); + }) as never); +} + function request( path: string, { method = 'GET', body, token = OWNER_TOKEN as string | null } = {} as { @@ -616,11 +628,6 @@ describe('DELETE /sessions/:sessionId/line-items/:lineItemId', () => { describe('POST /sessions/:sessionId/confirm', () => { beforeEach(() => { spyOn(console, 'error').mockImplementation(() => {}); - spyOn(Session.prototype, 'save').mockImplementation(async function ( - this: unknown, - ) { - return this; - }); }); afterEach(() => { @@ -630,6 +637,7 @@ describe('POST /sessions/:sessionId/confirm', () => { it('returns 200 with the published session and its code', async () => { const session = draftSession(); mockLookup(session); + mockPublish(session); const app = moduleWith(mock(async () => extracted)); const res = await app.handle( @@ -642,6 +650,20 @@ describe('POST /sessions/:sessionId/confirm', () => { expect(body.code).toMatch(/^[ABCDEFGHJKLMNPQRSTUVWXYZ23456789]{8}$/); }); + it('returns 409 when a concurrent request published first', async () => { + const session = draftSession(); + mockLookup(session); + mockPublish(null); + const app = moduleWith(mock(async () => extracted)); + + const res = await app.handle( + request(`/sessions/${session._id}/confirm`, { method: 'POST' }), + ); + + expect(res.status).toBe(409); + expect(await res.text()).toBe('Session is not editable'); + }); + it('returns 403 for a guest token and leaves the session in draft', async () => { const session = sessionWithGuest(); mockLookup(session); diff --git a/apps/api/src/modules/session/__test__/service.spec.ts b/apps/api/src/modules/session/__test__/service.spec.ts index d249a3b..e8aae3e 100644 --- a/apps/api/src/modules/session/__test__/service.spec.ts +++ b/apps/api/src/modules/session/__test__/service.spec.ts @@ -474,6 +474,7 @@ describe('a total handed over to the items', () => { it('never trips the confirm gate', async () => { const session = followingSession(); for (const item of session.lineItems) item.aiConfidence = 1; + mockPublish(session); await sessionService().addLineItem(session, { name: 'Vino', @@ -770,13 +771,34 @@ function confirmableSession() { ); } -function duplicateKeyError() { +function duplicateKeyError(keyPattern: Record = { code: 1 }) { return Object.assign(new Error('E11000 duplicate key'), { code: 11000, - keyPattern: { code: 1 }, + keyPattern, }); } +type PublishAttempt = { filter: Record; code: string }; + +/** + * Stands in for the conditional publish, applying the `$set` to `target` so the + * returned document is the one the caller gets a view of. Every attempt is + * recorded, so a test can assert what the compare-and-swap was keyed on. + */ +function mockPublish(target: HydratedDocument | null) { + const attempts: PublishAttempt[] = []; + spyOn(Session, 'findOneAndUpdate').mockImplementation((( + filter: Record, + update: { $set: Record }, + ) => { + attempts.push({ filter, code: String(update.$set.code) }); + if (!target) return Promise.resolve(null); + Object.assign(target, update.$set); + return Promise.resolve(target); + }) as never); + return attempts; +} + describe('SessionService.confirmSession', () => { beforeEach(() => { spyOn(console, 'error').mockImplementation(() => {}); @@ -793,6 +815,7 @@ describe('SessionService.confirmSession', () => { it('publishes the session with a share code', async () => { const session = confirmableSession(); + const attempts = mockPublish(session); const result = (await sessionService().confirmSession( session, @@ -800,8 +823,32 @@ describe('SessionService.confirmSession', () => { expect(result.status).toBe('open'); expect(result.code).toMatch(CODE_PATTERN); - expect(session.status).toBe('open'); - expect(session.code).toBe(result.code); + expect(attempts).toHaveLength(1); + expect(attempts[0].code).toBe(result.code as string); + }); + + it('only publishes a session that is still a draft', async () => { + const session = confirmableSession(); + const attempts = mockPublish(session); + + await sessionService().confirmSession(session); + + expect(attempts[0].filter).toEqual({ + _id: session._id, + status: 'draft', + }); + }); + + it('returns 409 when another request published first', async () => { + const session = confirmableSession(); + mockPublish(null); + + const result = await sessionService().confirmSession(session); + + expect(result).toMatchObject({ + code: 409, + response: 'Session is not editable', + }); }); it('returns 409 when the session is not a draft', async () => { @@ -858,6 +905,7 @@ describe('SessionService.confirmSession', () => { it('publishes once the owner has brought the two together', async () => { const session = confirmableSession(); session.totalCents = 1100; + mockPublish(session); await sessionService().addLineItem(session, { name: 'Vino', @@ -873,17 +921,20 @@ describe('SessionService.confirmSession', () => { }); it('regenerates the code when the unique index rejects a duplicate', async () => { - const attempted: (string | null)[] = []; - spyOn(Session.prototype, 'save').mockImplementation(async function ( - this: HydratedDocument, - ) { - attempted.push(this.code ?? null); - if (attempted.length === 1) throw duplicateKeyError(); - return this; - }); + const session = confirmableSession(); + const attempted: string[] = []; + spyOn(Session, 'findOneAndUpdate').mockImplementation((( + _filter: unknown, + update: { $set: Record }, + ) => { + attempted.push(String(update.$set.code)); + if (attempted.length === 1) return Promise.reject(duplicateKeyError()); + Object.assign(session, update.$set); + return Promise.resolve(session); + }) as never); const result = (await sessionService().confirmSession( - confirmableSession(), + session, )) as SessionModel['draftSessionResponse']; expect(attempted).toHaveLength(2); @@ -892,7 +943,9 @@ describe('SessionService.confirmSession', () => { }); it('returns 500 once the code attempts run out', async () => { - spyOn(Session.prototype, 'save').mockRejectedValue(duplicateKeyError()); + const publish = spyOn(Session, 'findOneAndUpdate').mockRejectedValue( + duplicateKeyError(), + ); const result = await sessionService().confirmSession(confirmableSession()); @@ -900,27 +953,38 @@ describe('SessionService.confirmSession', () => { code: 500, response: 'Failed to generate a session code', }); + expect(publish).toHaveBeenCalledTimes(5); }); it('lets an unrelated write failure bubble up to the module handler', async () => { - spyOn(Session.prototype, 'save').mockRejectedValue(new Error('mongo down')); + spyOn(Session, 'findOneAndUpdate').mockRejectedValue( + new Error('mongo down'), + ); await expect( sessionService().confirmSession(confirmableSession()), ).rejects.toThrow('mongo down'); }); + it('lets a duplicate without a key pattern bubble up instead of retrying', async () => { + const publish = spyOn(Session, 'findOneAndUpdate').mockRejectedValue( + Object.assign(new Error('E11000 duplicate key'), { code: 11000 }), + ); + + await expect( + sessionService().confirmSession(confirmableSession()), + ).rejects.toThrow('E11000 duplicate key'); + expect(publish).toHaveBeenCalledTimes(1); + }); + it('lets a duplicate on another key bubble up instead of retrying', async () => { - const save = spyOn(Session.prototype, 'save').mockRejectedValue( - Object.assign(new Error('E11000 duplicate key'), { - code: 11000, - keyPattern: { 'participants.deviceTokenHash': 1 }, - }), + const publish = spyOn(Session, 'findOneAndUpdate').mockRejectedValue( + duplicateKeyError({ 'participants.deviceTokenHash': 1 }), ); await expect( sessionService().confirmSession(confirmableSession()), ).rejects.toThrow('E11000 duplicate key'); - expect(save).toHaveBeenCalledTimes(1); + expect(publish).toHaveBeenCalledTimes(1); }); }); diff --git a/apps/api/src/modules/session/service.ts b/apps/api/src/modules/session/service.ts index 30e94f8..5f444cc 100644 --- a/apps/api/src/modules/session/service.ts +++ b/apps/api/src/modules/session/service.ts @@ -251,12 +251,15 @@ export class SessionService { if (lineSumCents(session) !== session.totalCents) return status(409, SessionModel.sessionTotalMismatch.const); - session.status = 'open'; for (let attempt = 0; attempt < CODE_ATTEMPTS; attempt++) { - session.code = generateSessionCode(); try { - await session.save(); - return toSessionView(session); + const published = await Session.findOneAndUpdate( + { _id: session._id, status: 'draft' }, + { $set: { status: 'open', code: generateSessionCode() } }, + { returnDocument: 'after' }, + ); + if (!published) return status(409, SessionModel.sessionNotDraft.const); + return toSessionView(published); } catch (error) { if (!isDuplicateKeyError(error, 'code')) throw error; } diff --git a/apps/api/test/session-confirm-concurrency.spec.ts b/apps/api/test/session-confirm-concurrency.spec.ts new file mode 100644 index 0000000..459287d --- /dev/null +++ b/apps/api/test/session-confirm-concurrency.spec.ts @@ -0,0 +1,62 @@ +import { beforeAll, describe, expect, it } from 'bun:test'; +import { Types } from 'mongoose'; +import { createSessionModule } from '../src/modules/session'; +import { SessionService } from '../src/modules/session/service'; +import { Session } from '../src/schemas'; +import { analyzeRequest, fakeExtract } from './fixtures'; +import { testStorage } from './setup'; + +/** + * Confirm publishes with a conditional update keyed on `status: 'draft'`, so + * two requests racing over the same draft cannot both win: whatever code a + * caller is handed is the one that ended up stored. + */ + +const app = createSessionModule(new SessionService(fakeExtract, testStorage())); + +type Draft = { id: string; auth: { token: string } }; + +async function createDraft() { + const res = await app.handle(analyzeRequest()); + expect(res.status).toBe(200); + return (await res.json()) as Draft; +} + +function confirm(draft: Draft) { + return app.handle( + new Request(`http://localhost/sessions/${draft.id}/confirm`, { + method: 'POST', + headers: { authorization: `Bearer ${draft.auth.token}` }, + }), + ); +} + +async function storedSession(sessionId: string) { + return (await Session.collection.findOne({ + _id: new Types.ObjectId(sessionId), + })) as unknown as { status: string; code?: string } | null; +} + +beforeAll(async () => { + await Session.syncIndexes(); +}); + +describe('confirming the same draft twice at once', () => { + it('publishes once and refuses the loser', async () => { + const draft = await createDraft(); + + const [first, second] = await Promise.all([confirm(draft), confirm(draft)]); + + expect([first.status, second.status].sort()).toEqual([200, 409]); + + const [won, lost] = + first.status === 200 ? [first, second] : [second, first]; + const published = (await won.json()) as { status: string; code: string }; + expect(published.status).toBe('open'); + expect(await lost.text()).toBe('Session is not editable'); + + const stored = await storedSession(draft.id); + expect(stored?.status).toBe('open'); + expect(stored?.code).toBe(published.code); + }); +}); From 5205959821de04dab29384705628fdf9e8750e1a Mon Sep 17 00:00:00 2001 From: Anass El Jabiry Date: Thu, 13 Aug 2026 00:06:30 +0200 Subject: [PATCH 21/21] fix(web): refetch the session when a confirm is refused The cache was only written on success, and the query defaults hold a session for a minute without refetching on focus. A tab that confirmed a session already published elsewhere got the error toast and went on rendering the draft with the button live, recoverable only by reloading. Invalidating on error refetches; the review route's existing non-draft guard then carries the tab to the share link. --- apps/web/src/features/session/api/confirm-session.ts | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/apps/web/src/features/session/api/confirm-session.ts b/apps/web/src/features/session/api/confirm-session.ts index cfffb32..082cb2a 100644 --- a/apps/web/src/features/session/api/confirm-session.ts +++ b/apps/web/src/features/session/api/confirm-session.ts @@ -29,7 +29,7 @@ export const useConfirmSession = ({ }: UseConfirmSessionOptions) => { const queryClient = useQueryClient(); - const { onSuccess, ...restConfig } = mutationConfig || {}; + const { onSuccess, onError, ...restConfig } = mutationConfig || {}; return useMutation({ onSuccess: (session, ...args) => { @@ -39,6 +39,12 @@ export const useConfirmSession = ({ ); onSuccess?.(session, ...args); }, + onError: (error, ...args) => { + queryClient.invalidateQueries({ + queryKey: getSessionQueryOptions(sessionId).queryKey, + }); + onError?.(error, ...args); + }, ...restConfig, mutationFn: confirmSession, });