From 02ae2ac53c32f1957f3c0d58b26ee8780657d707 Mon Sep 17 00:00:00 2001 From: Anass El Jabiry Date: Sun, 9 Aug 2026 23:59:25 +0200 Subject: [PATCH 1/9] refactor(shared-types): move supported image media types out of the api The web read EXT_BY_MEDIA_TYPE and SUPPORTED_IMAGE_MIME_TYPES through `@repo/api/constants`, coupling the frontend to the backend just to know which MIME types the receipt upload accepts. Move them to `@repo/shared-types`, which both apps already depend on, and drop the api's `./constants` entry point along with its barrel file. --- apps/api/package.json | 4 ---- apps/api/src/constants.ts | 1 - apps/api/src/storage/receipt-storage.ts | 15 ++++----------- .../src/features/session/api/analyze-receipt.ts | 2 +- libs/shared-types/src/index.ts | 1 + libs/shared-types/src/lib/media-types.ts | 12 ++++++++++++ 6 files changed, 18 insertions(+), 17 deletions(-) delete mode 100644 apps/api/src/constants.ts create mode 100644 libs/shared-types/src/lib/media-types.ts diff --git a/apps/api/package.json b/apps/api/package.json index 880e1d0..35dd4d9 100644 --- a/apps/api/package.json +++ b/apps/api/package.json @@ -7,10 +7,6 @@ ".": { "types": "./src/app.ts", "default": "./src/app.ts" - }, - "./constants": { - "types": "./src/constants.ts", - "default": "./src/constants.ts" } } } diff --git a/apps/api/src/constants.ts b/apps/api/src/constants.ts deleted file mode 100644 index 2fb3c82..0000000 --- a/apps/api/src/constants.ts +++ /dev/null @@ -1 +0,0 @@ -export * from './storage/receipt-storage'; diff --git a/apps/api/src/storage/receipt-storage.ts b/apps/api/src/storage/receipt-storage.ts index c70de28..d5b1fb7 100644 --- a/apps/api/src/storage/receipt-storage.ts +++ b/apps/api/src/storage/receipt-storage.ts @@ -1,15 +1,8 @@ -export const EXT_BY_MEDIA_TYPE = { - 'image/jpeg': 'jpg', - 'image/png': 'png', - 'image/webp': 'webp', - 'image/gif': 'gif', -} as const; - -export type SupportedImageMimeType = keyof typeof EXT_BY_MEDIA_TYPE; - -export const SUPPORTED_IMAGE_MIME_TYPES = Object.keys( +export { EXT_BY_MEDIA_TYPE, -) as SupportedImageMimeType[]; + SUPPORTED_IMAGE_MIME_TYPES, + type SupportedImageMimeType, +} from '@repo/shared-types'; export interface ReceiptStorage { save(bytes: Uint8Array, mediaType: string): Promise<{ id: string }>; diff --git a/apps/web/src/features/session/api/analyze-receipt.ts b/apps/web/src/features/session/api/analyze-receipt.ts index 0248e0a..87a861a 100644 --- a/apps/web/src/features/session/api/analyze-receipt.ts +++ b/apps/web/src/features/session/api/analyze-receipt.ts @@ -1,4 +1,4 @@ -import { SUPPORTED_IMAGE_MIME_TYPES } from '@repo/api/constants'; +import { SUPPORTED_IMAGE_MIME_TYPES } from '@repo/shared-types'; import { useMutation, useQueryClient } from '@tanstack/react-query'; import { z } from 'zod'; import { api, apiError } from '@/lib/api-client'; diff --git a/libs/shared-types/src/index.ts b/libs/shared-types/src/index.ts index 6380c76..7bafc55 100644 --- a/libs/shared-types/src/index.ts +++ b/libs/shared-types/src/index.ts @@ -1 +1,2 @@ +export * from './lib/media-types'; export * from './lib/object-id'; diff --git a/libs/shared-types/src/lib/media-types.ts b/libs/shared-types/src/lib/media-types.ts new file mode 100644 index 0000000..e69fa20 --- /dev/null +++ b/libs/shared-types/src/lib/media-types.ts @@ -0,0 +1,12 @@ +export const EXT_BY_MEDIA_TYPE = { + 'image/jpeg': 'jpg', + 'image/png': 'png', + 'image/webp': 'webp', + 'image/gif': 'gif', +} as const; + +export type SupportedImageMimeType = keyof typeof EXT_BY_MEDIA_TYPE; + +export const SUPPORTED_IMAGE_MIME_TYPES = Object.keys( + EXT_BY_MEDIA_TYPE, +) as SupportedImageMimeType[]; From 7a9a24e758daca40a69660c4dc55228ace2eafc7 Mon Sep 17 00:00:00 2001 From: Anass El Jabiry Date: Sun, 9 Aug 2026 23:59:33 +0200 Subject: [PATCH 2/9] chore(dev): seed the fake-gcs bucket from .dev/gcs fake-gcs-server creates buckets from the layout under /data on startup, so mounting `.dev/gcs` gives the dev stack the `snapsplit-receipts` bucket without the app having to create it on first use. --- .dev/gcs/snapsplit-receipts/.gitkeep | 0 compose.yaml | 1 + 2 files changed, 1 insertion(+) create mode 100644 .dev/gcs/snapsplit-receipts/.gitkeep diff --git a/.dev/gcs/snapsplit-receipts/.gitkeep b/.dev/gcs/snapsplit-receipts/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/compose.yaml b/compose.yaml index fd4b525..fb519b9 100644 --- a/compose.yaml +++ b/compose.yaml @@ -18,6 +18,7 @@ services: - 4443:4443 volumes: - fake-gcs-data:/storage + - ./.dev/gcs:/data mongo-express: image: mongo-express From dc88af529812528b90572f20fab5d44c7be74929 Mon Sep 17 00:00:00 2001 From: Anass El Jabiry Date: Mon, 10 Aug 2026 00:01:42 +0200 Subject: [PATCH 3/9] refactor(api): generalize receipt storage into a keyed object storage MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `ReceiptStorage` mixed three concerns: talking to GCS, minting the file id from the media type, and creating the bucket on demand when running against the emulator. That made the interface untestable in isolation and tied every caller to receipts. Split them apart: - `ObjectStorage` now takes the key explicitly, so it knows nothing about receipts. `GcsObjectStorage` receives its prefix, bucket and endpoint through the constructor instead of reading `Bun.env` on the spot. - `createReceiptStorage(env)` in `storage/index.ts` wires the receipts bucket and is the only place that touches the environment. - The receipt-specific rules — how a file id is minted and how it maps to the public `/receipts/:fileId` path — move to `modules/receipt/service.ts` and are now covered by unit tests. - `ensureBucket()` is gone: the dev bucket is seeded from `.dev/gcs`, and in production the bucket is provisioned by infra. `createReceiptModule(storage)` mirrors `createSessionModule` so the route can be exercised with a fake storage. --- apps/api/.env.example | 2 + apps/api/src/app.ts | 6 ++ .../modules/receipt/__test__/index.spec.ts | 48 ++++++++++++++ .../modules/receipt/__test__/service.spec.ts | 27 ++++++++ apps/api/src/modules/receipt/index.ts | 64 ++++++++++--------- apps/api/src/modules/receipt/service.ts | 21 ++++++ .../modules/session/__test__/index.spec.ts | 22 +++++-- .../modules/session/__test__/service.spec.ts | 29 +++++---- apps/api/src/modules/session/index.ts | 4 +- apps/api/src/modules/session/model.ts | 2 +- apps/api/src/modules/session/service.ts | 12 ++-- apps/api/src/storage/__test__/index.spec.ts | 18 ++++++ apps/api/src/storage/gcs.ts | 60 +++++++---------- apps/api/src/storage/index.ts | 14 ++++ apps/api/src/storage/object-storage.ts | 11 ++++ apps/api/src/storage/receipt-storage.ts | 11 ---- apps/api/test/fixtures.ts | 7 +- 17 files changed, 252 insertions(+), 106 deletions(-) create mode 100644 apps/api/src/modules/receipt/__test__/index.spec.ts create mode 100644 apps/api/src/modules/receipt/__test__/service.spec.ts create mode 100644 apps/api/src/modules/receipt/service.ts create mode 100644 apps/api/src/storage/__test__/index.spec.ts create mode 100644 apps/api/src/storage/index.ts create mode 100644 apps/api/src/storage/object-storage.ts delete mode 100644 apps/api/src/storage/receipt-storage.ts diff --git a/apps/api/.env.example b/apps/api/.env.example index 36cf85b..62da47e 100644 --- a/apps/api/.env.example +++ b/apps/api/.env.example @@ -4,6 +4,8 @@ GOOGLE_GENERATIVE_AI_API_KEY=your-gemini-api-key # GEMINI_MODEL=gemini-3.1-flash-lite # Max extraction attempts until the parsed receipt is self-consistent. Defaults to 3. # RECEIPT_EXTRACTION_MAX_ATTEMPTS=3 +# In dev this bucket is seeded by the emulator from .dev/gcs/ (compose.yaml); +# the app never creates buckets itself. In production it is provisioned by infra. GCS_BUCKET=snapsplit-receipts # Dev only: point the GCS client at the fake-gcs-server emulator (compose.yaml). # Leave unset in production so the client uses real GCS via ADC. diff --git a/apps/api/src/app.ts b/apps/api/src/app.ts index bece2ad..601ce01 100644 --- a/apps/api/src/app.ts +++ b/apps/api/src/app.ts @@ -27,3 +27,9 @@ export const app = new Elysia() .get('/', () => ({ hello: 'snapsplit' })); export type App = typeof app; + +export { + EXT_BY_MEDIA_TYPE, + SUPPORTED_IMAGE_MIME_TYPES, + type SupportedImageMimeType, +} from './storage/object-storage'; diff --git a/apps/api/src/modules/receipt/__test__/index.spec.ts b/apps/api/src/modules/receipt/__test__/index.spec.ts new file mode 100644 index 0000000..46f4aa6 --- /dev/null +++ b/apps/api/src/modules/receipt/__test__/index.spec.ts @@ -0,0 +1,48 @@ +import { describe, expect, it, mock } from 'bun:test'; +import type { ObjectStorage } from '../../../storage/object-storage'; +import { createReceiptModule } from '../index'; +import { receiptUrl } from '../service'; + +function fakeStorage(overrides: Partial = {}): ObjectStorage { + return { + save: mock(async () => {}), + get: mock(async () => null), + delete: mock(async () => {}), + ...overrides, + }; +} + +function get(storage: ObjectStorage, path: string) { + return createReceiptModule(storage).handle( + new Request(`http://localhost${path}`), + ); +} + +describe('GET /receipts/:fileId', () => { + // A 200 is only reachable if the route matched, so this fails the moment the + // module prefix and receiptUrl() stop agreeing on the same path. + it('serves the path that receiptUrl builds', async () => { + const storage = fakeStorage({ + get: mock(async () => ({ + bytes: Buffer.from([1, 2, 3]), + mediaType: 'image/png', + })), + }); + + const res = await get(storage, receiptUrl('abc.png')); + + expect(res.status).toBe(200); + expect(res.headers.get('content-type')).toBe('image/png'); + expect(new Uint8Array(await res.arrayBuffer())).toEqual( + new Uint8Array([1, 2, 3]), + ); + expect(storage.get).toHaveBeenCalledWith('abc.png'); + }); + + it('returns 404 when no image is stored under that id', async () => { + const res = await get(fakeStorage(), receiptUrl('missing.png')); + + expect(res.status).toBe(404); + expect(await res.text()).toBe('Not found'); + }); +}); diff --git a/apps/api/src/modules/receipt/__test__/service.spec.ts b/apps/api/src/modules/receipt/__test__/service.spec.ts new file mode 100644 index 0000000..dc7e8ba --- /dev/null +++ b/apps/api/src/modules/receipt/__test__/service.spec.ts @@ -0,0 +1,27 @@ +import { describe, expect, it } from 'bun:test'; +import { receiptFileId, receiptUrl } from '../service'; + +describe('receiptUrl', () => { + it('builds the public path served by the receipt module', () => { + expect(receiptUrl('abc.jpg')).toBe('/receipts/abc.jpg'); + }); +}); + +describe('receiptFileId', () => { + it('extracts the stored file id from a receipt url', () => { + expect(receiptFileId('/receipts/abc.jpg')).toBe('abc.jpg'); + }); + + it('round-trips whatever receiptUrl built', () => { + expect(receiptFileId(receiptUrl('abc.jpg'))).toBe('abc.jpg'); + }); + + it('returns null for a url that is not a receipt', () => { + expect(receiptFileId('https://cdn.example.com/abc.jpg')).toBeNull(); + }); + + it('returns null for the empty default url', () => { + expect(receiptFileId('')).toBeNull(); + expect(receiptFileId('/receipts/')).toBeNull(); + }); +}); diff --git a/apps/api/src/modules/receipt/index.ts b/apps/api/src/modules/receipt/index.ts index 55ba44f..3825745 100644 --- a/apps/api/src/modules/receipt/index.ts +++ b/apps/api/src/modules/receipt/index.ts @@ -1,6 +1,8 @@ import { Elysia, status, t } from 'elysia'; -import { gcsReceiptStorage } from '../../storage/gcs'; -import { SUPPORTED_IMAGE_MIME_TYPES } from '../../storage/receipt-storage'; +import { receiptStorage } from '../../storage'; +import type { ObjectStorage } from '../../storage/object-storage'; +import { SUPPORTED_IMAGE_MIME_TYPES } from '../../storage/object-storage'; +import { RECEIPT_BASE_PATH } from './service'; const receiptImageContent = Object.fromEntries( SUPPORTED_IMAGE_MIME_TYPES.map((type) => [ @@ -9,34 +11,38 @@ const receiptImageContent = Object.fromEntries( ]), ); -export const receiptModule = new Elysia({ - prefix: '/receipts', - name: 'receipt', -}).get( - '/:fileId', - async ({ params: { fileId } }) => { - const file = await gcsReceiptStorage.get(fileId); - if (!file) return status(404, 'Not found'); +export function createReceiptModule(storage: ObjectStorage) { + return new Elysia({ + prefix: RECEIPT_BASE_PATH, + name: 'receipt', + }).get( + '/:fileId', + async ({ params: { fileId } }) => { + const file = await storage.get(fileId); + if (!file) return status(404, 'Not found'); - return new Response(new Uint8Array(file.bytes), { - headers: { 'content-type': file.mediaType }, - }); - }, - { - params: t.Object({ fileId: t.String() }), - detail: { - summary: 'Serve a stored receipt image', - tags: ['Receipts'], - responses: { - 200: { - description: 'The stored receipt image bytes', - content: receiptImageContent, - }, - 404: { - description: 'No receipt image exists for the given fileId', - content: { 'text/plain': { schema: { type: 'string' } } }, + return new Response(new Uint8Array(file.bytes), { + headers: { 'content-type': file.mediaType }, + }); + }, + { + params: t.Object({ fileId: t.String() }), + detail: { + summary: 'Serve a stored receipt image', + tags: ['Receipts'], + responses: { + 200: { + description: 'The stored receipt image bytes', + content: receiptImageContent, + }, + 404: { + description: 'No receipt image exists for the given fileId', + content: { 'text/plain': { schema: { type: 'string' } } }, + }, }, }, }, - }, -); + ); +} + +export const receiptModule = createReceiptModule(receiptStorage); diff --git a/apps/api/src/modules/receipt/service.ts b/apps/api/src/modules/receipt/service.ts new file mode 100644 index 0000000..0db2e92 --- /dev/null +++ b/apps/api/src/modules/receipt/service.ts @@ -0,0 +1,21 @@ +import { randomUUID } from 'node:crypto'; +import { + EXT_BY_MEDIA_TYPE, + type SupportedImageMimeType, +} from '../../storage/object-storage'; + +export const RECEIPT_BASE_PATH = '/receipts'; + +export function newReceiptFileId(mediaType: string) { + const ext = EXT_BY_MEDIA_TYPE[mediaType as SupportedImageMimeType] ?? 'bin'; + return `${randomUUID()}.${ext}`; +} + +export function receiptUrl(id: string) { + return `${RECEIPT_BASE_PATH}/${id}`; +} + +export function receiptFileId(url: string) { + const prefix = `${RECEIPT_BASE_PATH}/`; + return url.startsWith(prefix) ? url.slice(prefix.length) || null : null; +} diff --git a/apps/api/src/modules/session/__test__/index.spec.ts b/apps/api/src/modules/session/__test__/index.spec.ts index 76f3e42..27d5f45 100644 --- a/apps/api/src/modules/session/__test__/index.spec.ts +++ b/apps/api/src/modules/session/__test__/index.spec.ts @@ -9,7 +9,7 @@ import { } from 'bun:test'; import type { ExtractedReceipt, ExtractReceipt } from '../../../ai/receipt'; import { Session } from '../../../schemas'; -import type { ReceiptStorage } from '../../../storage/receipt-storage'; +import type { ObjectStorage } from '../../../storage/object-storage'; import { hashToken } from '../../auth/service'; import { createSessionModule } from '../index'; import { buildDraftPayload, SessionService } from '../service'; @@ -30,15 +30,20 @@ const extracted: ExtractedReceipt = { ], }; -function fakeStorage(overrides: Partial = {}): ReceiptStorage { +function fakeStorage(overrides: Partial = {}): ObjectStorage { return { - save: mock(async () => ({ id: 'stored-123' })), + save: mock(async () => {}), get: mock(async () => null), delete: mock(async () => {}), ...overrides, }; } +/** The key the service minted for the one image it stored. */ +function storedKey(storage: ObjectStorage) { + return (storage.save as ReturnType).mock.calls[0][0] as string; +} + function moduleWith(extract: ExtractReceipt, storage = fakeStorage()) { return createSessionModule(new SessionService(extract, storage)); } @@ -77,7 +82,11 @@ describe('POST /sessions/analyze', () => { }); it('returns 200 with the serialized draft view', async () => { - const app = moduleWith(mock(async () => extracted)); + const storage = fakeStorage(); + const app = moduleWith( + mock(async () => extracted), + storage, + ); const res = await app.handle(analyzeRequest(imageFile('image/png'))); @@ -85,8 +94,9 @@ describe('POST /sessions/analyze', () => { expect(await res.json()).toMatchObject({ status: 'draft', merchant: 'Bar Paco', - receiptImageUrl: '/receipts/stored-123', + receiptImageUrl: `/receipts/${storedKey(storage)}`, }); + expect(storedKey(storage)).toMatch(/\.png$/); }); it('returns 422 when the image field is missing', async () => { @@ -147,7 +157,7 @@ describe('POST /sessions/analyze', () => { expect(res.status).toBe(500); expect(await res.text()).toBe('Failed to create draft session'); - expect(storage.delete).toHaveBeenCalledWith('stored-123'); + expect(storage.delete).toHaveBeenCalledWith(storedKey(storage)); }); }); diff --git a/apps/api/src/modules/session/__test__/service.spec.ts b/apps/api/src/modules/session/__test__/service.spec.ts index 2a926da..5a8cbed 100644 --- a/apps/api/src/modules/session/__test__/service.spec.ts +++ b/apps/api/src/modules/session/__test__/service.spec.ts @@ -10,7 +10,7 @@ import { import type { HydratedDocument } from 'mongoose'; import type { ExtractedReceipt, ExtractReceipt } from '../../../ai/receipt'; import { Session } from '../../../schemas'; -import type { ReceiptStorage } from '../../../storage/receipt-storage'; +import type { ObjectStorage } from '../../../storage/object-storage'; import { hashToken } from '../../auth/service'; import type { SessionModel } from '../model'; import { buildDraftPayload, SessionService, toSessionView } from '../service'; @@ -123,15 +123,23 @@ function imageBody( return { image: new File([bytes], 'receipt.jpg', { type }) }; } -function fakeStorage(overrides: Partial = {}): ReceiptStorage { +function fakeStorage(overrides: Partial = {}): ObjectStorage { return { - save: mock(async () => ({ id: 'stored-123' })), + save: mock(async () => {}), get: mock(async () => null), delete: mock(async () => {}), ...overrides, }; } +function saveCall(storage: ObjectStorage) { + return (storage.save as ReturnType).mock.calls[0] as [ + string, + Uint8Array, + string, + ]; +} + describe('SessionService.createDraftFromImage', () => { beforeEach(() => { spyOn(console, 'error').mockImplementation(() => {}); @@ -162,18 +170,16 @@ describe('SessionService.createDraftFromImage', () => { expect(extract.mock.calls[0][0]).toEqual(bytes); expect(extract.mock.calls[0][1]).toBe('image/png'); expect(storage.save).toHaveBeenCalledTimes(1); - expect((storage.save as ReturnType).mock.calls[0][0]).toEqual( - bytes, - ); - expect((storage.save as ReturnType).mock.calls[0][1]).toBe( - 'image/png', - ); + const [key, storedBytes, storedMediaType] = saveCall(storage); + expect(storedBytes).toEqual(bytes); + expect(storedMediaType).toBe('image/png'); + expect(key).toMatch(/\.png$/); // The happy path returns the serialized session view, not a status error. expect(result).toMatchObject({ status: 'draft', merchant: 'Bar Paco', - receiptImageUrl: '/receipts/stored-123', + receiptImageUrl: `/receipts/${key}`, }); const created = result as SessionModel['draftSessionCreatedResponse']; expect(created.lineItems).toHaveLength(2); @@ -215,8 +221,7 @@ describe('SessionService.createDraftFromImage', () => { code: 500, response: 'Failed to create draft session', }); - // The orphaned upload is cleaned up so storage doesn't leak. - expect(storage.delete).toHaveBeenCalledWith('stored-123'); + expect(storage.delete).toHaveBeenCalledWith(saveCall(storage)[0]); }); }); diff --git a/apps/api/src/modules/session/index.ts b/apps/api/src/modules/session/index.ts index f0cf9a9..8144d1d 100644 --- a/apps/api/src/modules/session/index.ts +++ b/apps/api/src/modules/session/index.ts @@ -1,7 +1,7 @@ import { Elysia, t } from 'elysia'; import { extractReceipt } from '../../ai/receipt'; import { authPlugin } from '../../plugins/auth'; -import { gcsReceiptStorage } from '../../storage/gcs'; +import { receiptStorage } from '../../storage'; import { AuthModel } from '../auth/model'; import { SessionModel } from './model'; import { SessionService, toSessionView } from './service'; @@ -112,5 +112,5 @@ export function createSessionModule(service: SessionService) { } export const sessionModule = createSessionModule( - new SessionService(extractReceipt, gcsReceiptStorage), + new SessionService(extractReceipt, receiptStorage), ); diff --git a/apps/api/src/modules/session/model.ts b/apps/api/src/modules/session/model.ts index 863e462..3a80083 100644 --- a/apps/api/src/modules/session/model.ts +++ b/apps/api/src/modules/session/model.ts @@ -1,6 +1,6 @@ import { t } from 'elysia'; import { objectId } from '../../model'; -import { SUPPORTED_IMAGE_MIME_TYPES } from '../../storage/receipt-storage'; +import { SUPPORTED_IMAGE_MIME_TYPES } from '../../storage/object-storage'; const lineItemView = t.Object({ id: t.String(), diff --git a/apps/api/src/modules/session/service.ts b/apps/api/src/modules/session/service.ts index cb79401..b52b1d8 100644 --- a/apps/api/src/modules/session/service.ts +++ b/apps/api/src/modules/session/service.ts @@ -2,8 +2,9 @@ import { status } from 'elysia'; import type { HydratedDocument } from 'mongoose'; import type { ExtractedReceipt, ExtractReceipt } from '../../ai/receipt'; import { type LineItem, type Participant, Session } from '../../schemas'; -import type { ReceiptStorage } from '../../storage/receipt-storage'; +import type { ObjectStorage } from '../../storage/object-storage'; import { generateToken, hashToken } from '../auth/service'; +import { newReceiptFileId, receiptUrl } from '../receipt/service'; import { SessionModel } from './model'; type LineItemInput = Pick< @@ -71,7 +72,7 @@ export function toSessionView( export class SessionService { constructor( private readonly extract: ExtractReceipt, - private readonly storage: ReceiptStorage, + private readonly storage: ObjectStorage, ) {} async createDraftFromImage({ image }: SessionModel['analyzeBody']) { @@ -85,14 +86,15 @@ export class SessionService { return status(502, SessionModel.analysisFailed.const); } - const { id } = await this.storage.save(bytes, image.type); + const fileId = newReceiptFileId(image.type); + await this.storage.save(fileId, bytes, image.type); try { const token = generateToken(); const deviceTokenHash = hashToken(token); const payload = buildDraftPayload( deviceTokenHash, extracted, - `/receipts/${id}`, + receiptUrl(fileId), ); const session = await new Session(payload).save(); const [owner] = session.participants; @@ -101,7 +103,7 @@ export class SessionService { auth: { participantId: String(owner._id), token }, }; } catch (error) { - await this.storage.delete(id).catch(() => {}); + await this.storage.delete(fileId).catch(() => {}); console.error('Failed to persist draft session:', error); return status(500, SessionModel.draftCreationFailed.const); } diff --git a/apps/api/src/storage/__test__/index.spec.ts b/apps/api/src/storage/__test__/index.spec.ts new file mode 100644 index 0000000..8a133ae --- /dev/null +++ b/apps/api/src/storage/__test__/index.spec.ts @@ -0,0 +1,18 @@ +import { describe, expect, it } from 'bun:test'; +import { createReceiptStorage } from '../index'; + +describe('createReceiptStorage', () => { + it('builds a storage without reading the process environment', () => { + const storage = createReceiptStorage({ GCS_BUCKET: 'a-bucket' }); + + expect(typeof storage.save).toBe('function'); + expect(typeof storage.get).toBe('function'); + expect(typeof storage.delete).toBe('function'); + }); + + it('defers client construction, so a missing bucket only fails on use', () => { + const storage = createReceiptStorage({}); + + expect(storage.get('any-key')).rejects.toThrow('GCS_BUCKET is not set'); + }); +}); diff --git a/apps/api/src/storage/gcs.ts b/apps/api/src/storage/gcs.ts index 287808b..139bdc9 100644 --- a/apps/api/src/storage/gcs.ts +++ b/apps/api/src/storage/gcs.ts @@ -1,57 +1,47 @@ -import { randomUUID } from 'node:crypto'; import { type Bucket, Storage } from '@google-cloud/storage'; -import { - EXT_BY_MEDIA_TYPE, - type ReceiptStorage, - type SupportedImageMimeType, -} from './receipt-storage'; +import type { ObjectStorage } from './object-storage'; -const PREFIX = 'receipts'; - -export function extFromMediaType(mediaType: string): string { - return EXT_BY_MEDIA_TYPE[mediaType as SupportedImageMimeType] ?? 'bin'; +export interface GcsObjectStorageOptions { + prefix: string; + bucketName?: string; + apiEndpoint?: string; } -export class GcsReceiptStorage implements ReceiptStorage { +export class GcsObjectStorage implements ObjectStorage { + private readonly prefix: string; + private readonly bucketName?: string; + private readonly apiEndpoint?: string; private bucketInstance?: Bucket; - private ensured = false; - constructor(private readonly bucketName = Bun.env.GCS_BUCKET) {} + constructor({ prefix, bucketName, apiEndpoint }: GcsObjectStorageOptions) { + this.prefix = prefix; + this.bucketName = bucketName; + this.apiEndpoint = apiEndpoint; + } - private get isEmulator(): boolean { - return Boolean(Bun.env.GCS_EMULATOR_HOST); + private objectName(key: string): string { + return this.prefix ? `${this.prefix}/${key}` : key; } private bucket(): Bucket { if (!this.bucketInstance) { if (!this.bucketName) throw new Error('GCS_BUCKET is not set'); - const emulator = Bun.env.GCS_EMULATOR_HOST; - const storage = emulator - ? new Storage({ apiEndpoint: emulator, projectId: 'dev' }) + const storage = this.apiEndpoint + ? new Storage({ apiEndpoint: this.apiEndpoint, projectId: 'dev' }) : new Storage(); this.bucketInstance = storage.bucket(this.bucketName); } return this.bucketInstance; } - private async ensureBucket(): Promise { - if (!this.isEmulator || this.ensured) return; - const [exists] = await this.bucket().exists(); - if (!exists) await this.bucket().create(); - this.ensured = true; - } - - async save(bytes: Uint8Array, mediaType: string): Promise<{ id: string }> { - await this.ensureBucket(); - const id = `${randomUUID()}.${extFromMediaType(mediaType)}`; + async save(key: string, bytes: Uint8Array, mediaType: string): Promise { await this.bucket() - .file(`${PREFIX}/${id}`) + .file(this.objectName(key)) .save(Buffer.from(bytes), { contentType: mediaType }); - return { id }; } - async get(id: string): Promise<{ bytes: Buffer; mediaType: string } | null> { - const file = this.bucket().file(`${PREFIX}/${id}`); + async get(key: string): Promise<{ bytes: Buffer; mediaType: string } | null> { + const file = this.bucket().file(this.objectName(key)); const [exists] = await file.exists(); if (!exists) return null; const [metadata] = await file.getMetadata(); @@ -62,11 +52,9 @@ export class GcsReceiptStorage implements ReceiptStorage { }; } - async delete(id: string): Promise { + async delete(key: string): Promise { await this.bucket() - .file(`${PREFIX}/${id}`) + .file(this.objectName(key)) .delete({ ignoreNotFound: true }); } } - -export const gcsReceiptStorage = new GcsReceiptStorage(); diff --git a/apps/api/src/storage/index.ts b/apps/api/src/storage/index.ts new file mode 100644 index 0000000..1b1ee8c --- /dev/null +++ b/apps/api/src/storage/index.ts @@ -0,0 +1,14 @@ +import { GcsObjectStorage } from './gcs'; +import type { ObjectStorage } from './object-storage'; + +type StorageEnv = Partial>; + +export function createReceiptStorage(env: StorageEnv = Bun.env): ObjectStorage { + return new GcsObjectStorage({ + prefix: 'receipts', + bucketName: env.GCS_BUCKET, + apiEndpoint: env.GCS_EMULATOR_HOST, + }); +} + +export const receiptStorage: ObjectStorage = createReceiptStorage(); diff --git a/apps/api/src/storage/object-storage.ts b/apps/api/src/storage/object-storage.ts new file mode 100644 index 0000000..9177ba5 --- /dev/null +++ b/apps/api/src/storage/object-storage.ts @@ -0,0 +1,11 @@ +export { + EXT_BY_MEDIA_TYPE, + SUPPORTED_IMAGE_MIME_TYPES, + type SupportedImageMimeType, +} from '@repo/shared-types'; + +export interface ObjectStorage { + save(key: string, bytes: Uint8Array, mediaType: string): Promise; + get(key: string): Promise<{ bytes: Buffer; mediaType: string } | null>; + delete(key: string): Promise; +} diff --git a/apps/api/src/storage/receipt-storage.ts b/apps/api/src/storage/receipt-storage.ts deleted file mode 100644 index d5b1fb7..0000000 --- a/apps/api/src/storage/receipt-storage.ts +++ /dev/null @@ -1,11 +0,0 @@ -export { - EXT_BY_MEDIA_TYPE, - SUPPORTED_IMAGE_MIME_TYPES, - type SupportedImageMimeType, -} from '@repo/shared-types'; - -export interface ReceiptStorage { - save(bytes: Uint8Array, mediaType: string): Promise<{ id: string }>; - get(id: string): Promise<{ bytes: Buffer; mediaType: string } | null>; - delete(id: string): Promise; -} diff --git a/apps/api/test/fixtures.ts b/apps/api/test/fixtures.ts index 2f40915..34a3e67 100644 --- a/apps/api/test/fixtures.ts +++ b/apps/api/test/fixtures.ts @@ -1,5 +1,5 @@ import type { ExtractedReceipt, ExtractReceipt } from '../src/ai/receipt'; -import type { ReceiptStorage } from '../src/storage/receipt-storage'; +import type { ObjectStorage } from '../src/storage/object-storage'; export const extracted: ExtractedReceipt = { merchant: 'Bar Paco', @@ -38,10 +38,9 @@ export function analyzeRequest(file = imageFile()) { export const fakeExtract: ExtractReceipt = async () => extracted; -export function fakeStorage(): ReceiptStorage { - let saved = 0; +export function fakeStorage(): ObjectStorage { return { - save: async () => ({ id: `stored-${++saved}.png` }), + save: async () => {}, get: async () => null, delete: async () => {}, }; From ef3969f049a6189d3a470aa3c6f9e58071f0a50a Mon Sep 17 00:00:00 2001 From: Anass El Jabiry Date: Mon, 10 Aug 2026 00:02:04 +0200 Subject: [PATCH 4/9] feat(api): delete a session and its receipt image MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `DELETE /sessions/:sessionId` lets the payer discard a session — a draft they no longer want, or a settled bill. Only the owner may call it, so the route reuses the `owner: true` guard from the auth plugin and answers 204 with an empty body. The stored image is dropped alongside the document, mapping the session's `receiptImageUrl` back to a storage key with `receiptFileId`. A failing storage delete does not fail the request: the document is already gone and a leftover object is cheaper than a session the owner cannot remove. --- .../modules/session/__test__/index.spec.ts | 90 +++++++++++++++++++ .../modules/session/__test__/service.spec.ts | 62 +++++++++++++ apps/api/src/modules/session/index.ts | 14 +++ apps/api/src/modules/session/model.ts | 1 + apps/api/src/modules/session/service.ts | 15 +++- 5 files changed, 181 insertions(+), 1 deletion(-) diff --git a/apps/api/src/modules/session/__test__/index.spec.ts b/apps/api/src/modules/session/__test__/index.spec.ts index 27d5f45..33135c7 100644 --- a/apps/api/src/modules/session/__test__/index.spec.ts +++ b/apps/api/src/modules/session/__test__/index.spec.ts @@ -377,6 +377,96 @@ describe('GET /sessions/:sessionId', () => { }); }); +describe('DELETE /sessions/:sessionId', () => { + beforeEach(() => { + spyOn(console, 'error').mockImplementation(() => {}); + spyOn(Session.prototype, 'deleteOne').mockImplementation((async () => ({ + deletedCount: 1, + })) as never); + }); + + afterEach(() => { + mock.restore(); + }); + + it('returns 204 with an empty body and drops the receipt image', async () => { + const session = draftSession(); + mockLookup(session); + const storage = fakeStorage(); + const app = moduleWith( + mock(async () => extracted), + storage, + ); + + const res = await app.handle( + request(`/sessions/${session._id}`, { method: 'DELETE' }), + ); + + expect(res.status).toBe(204); + expect(await res.text()).toBe(''); + expect(Session.prototype.deleteOne).toHaveBeenCalledTimes(1); + expect(storage.delete).toHaveBeenCalledWith('abc.jpg'); + }); + + it('returns 403 for a guest token and keeps the session', async () => { + const session = sessionWithGuest(); + mockLookup(session); + const app = moduleWith(mock(async () => extracted)); + + const res = await app.handle( + request(`/sessions/${session._id}`, { + method: 'DELETE', + token: GUEST_TOKEN, + }), + ); + + expect(res.status).toBe(403); + expect(await res.text()).toBe('Forbidden'); + expect(Session.prototype.deleteOne).not.toHaveBeenCalled(); + }); + + it('returns 401 without an Authorization header', async () => { + const session = draftSession(); + mockLookup(session); + const app = moduleWith(mock(async () => extracted)); + + const res = await app.handle( + request(`/sessions/${session._id}`, { method: 'DELETE', token: null }), + ); + + expect(res.status).toBe(401); + expect(await res.text()).toBe('Unauthorized'); + expect(Session.prototype.deleteOne).not.toHaveBeenCalled(); + }); + + it('returns 403 when the token belongs to another session', async () => { + mockLookup(draftSession()); + const app = moduleWith(mock(async () => extracted)); + + const res = await app.handle( + request('/sessions/507f1f77bcf86cd799439011', { method: 'DELETE' }), + ); + + expect(res.status).toBe(403); + expect(await res.text()).toBe('Forbidden'); + expect(Session.prototype.deleteOne).not.toHaveBeenCalled(); + }); + + it('maps an unexpected error to 500 via onError', async () => { + spyOn(Session, 'findOne').mockImplementation((() => { + throw new Error('mongo down'); + }) as never); + const app = moduleWith(mock(async () => extracted)); + + const res = await app.handle( + request('/sessions/507f191e810c19729de860ea', { method: 'DELETE' }), + ); + + expect(res.status).toBe(500); + expect(await res.text()).toBe('Unexpected server error'); + }); +}); + describe('DELETE /sessions/:sessionId/line-items/:lineItemId', () => { beforeEach(() => { spyOn(console, 'error').mockImplementation(() => {}); diff --git a/apps/api/src/modules/session/__test__/service.spec.ts b/apps/api/src/modules/session/__test__/service.spec.ts index 5a8cbed..988f225 100644 --- a/apps/api/src/modules/session/__test__/service.spec.ts +++ b/apps/api/src/modules/session/__test__/service.spec.ts @@ -238,6 +238,68 @@ function lineItemService() { ); } +describe('SessionService.deleteSession', () => { + beforeEach(() => { + spyOn(console, 'error').mockImplementation(() => {}); + }); + + afterEach(() => { + mock.restore(); + }); + + it('deletes the document and its stored receipt image', async () => { + const deleteOne = spyOn(Session.prototype, 'deleteOne').mockImplementation( + (async () => ({ deletedCount: 1 })) as never, + ); + const storage = fakeStorage(); + const session = draftSession(); + + const result = await new SessionService( + mock(async () => extracted), + storage, + ).deleteSession(session); + + expect(deleteOne).toHaveBeenCalledTimes(1); + expect(storage.delete).toHaveBeenCalledWith('abc.jpg'); + expect(result).toMatchObject({ code: 204 }); + }); + + it('skips the storage call when there is no receipt image', async () => { + spyOn(Session.prototype, 'deleteOne').mockImplementation((async () => ({ + deletedCount: 1, + })) as never); + const storage = fakeStorage(); + const session = draftSession(); + session.receiptImageUrl = ''; + + await new SessionService( + mock(async () => extracted), + storage, + ).deleteSession(session); + + expect(storage.delete).not.toHaveBeenCalled(); + }); + + it('still succeeds when deleting the stored image fails', async () => { + const deleteOne = spyOn(Session.prototype, 'deleteOne').mockImplementation( + (async () => ({ deletedCount: 1 })) as never, + ); + const storage = fakeStorage({ + delete: mock(async () => { + throw new Error('gcs down'); + }), + }); + + const result = await new SessionService( + mock(async () => extracted), + storage, + ).deleteSession(draftSession()); + + expect(deleteOne).toHaveBeenCalledTimes(1); + expect(result).toMatchObject({ code: 204 }); + }); +}); + describe('SessionService.addLineItem', () => { beforeEach(() => { spyOn(console, 'error').mockImplementation(() => {}); diff --git a/apps/api/src/modules/session/index.ts b/apps/api/src/modules/session/index.ts index 8144d1d..03132c3 100644 --- a/apps/api/src/modules/session/index.ts +++ b/apps/api/src/modules/session/index.ts @@ -46,6 +46,20 @@ export function createSessionModule(service: SessionService) { tags: ['Sessions'], }, }) + .delete('/:sessionId', ({ session }) => service.deleteSession(session), { + owner: true, + params: SessionModel.sessionParams, + response: { + 204: SessionModel.noContent, + 401: AuthModel.unauthorized, + 403: AuthModel.forbidden, + 500: SessionModel.internalError, + }, + detail: { + summary: 'Delete a session and its receipt image', + tags: ['Sessions'], + }, + }) .post( '/:sessionId/line-items', ({ session, body }) => service.addLineItem(session, body), diff --git a/apps/api/src/modules/session/model.ts b/apps/api/src/modules/session/model.ts index 3a80083..1db8f4e 100644 --- a/apps/api/src/modules/session/model.ts +++ b/apps/api/src/modules/session/model.ts @@ -46,6 +46,7 @@ export const SessionModel = { sessionView, t.Object({ auth: authView }), ]), + noContent: t.Void(), analysisFailed: t.Literal('Receipt analysis failed'), draftCreationFailed: t.Literal('Failed to create draft session'), internalError: t.Literal('Unexpected server error'), diff --git a/apps/api/src/modules/session/service.ts b/apps/api/src/modules/session/service.ts index b52b1d8..a870740 100644 --- a/apps/api/src/modules/session/service.ts +++ b/apps/api/src/modules/session/service.ts @@ -4,7 +4,11 @@ import type { ExtractedReceipt, ExtractReceipt } from '../../ai/receipt'; import { type LineItem, type Participant, Session } from '../../schemas'; import type { ObjectStorage } from '../../storage/object-storage'; import { generateToken, hashToken } from '../auth/service'; -import { newReceiptFileId, receiptUrl } from '../receipt/service'; +import { + newReceiptFileId, + receiptFileId, + receiptUrl, +} from '../receipt/service'; import { SessionModel } from './model'; type LineItemInput = Pick< @@ -109,6 +113,15 @@ export class SessionService { } } + async deleteSession(session: HydratedDocument) { + await session.deleteOne(); + + const fileId = receiptFileId(session.receiptImageUrl); + if (fileId) await this.storage.delete(fileId).catch(() => {}); + + return status(204, undefined); + } + async addLineItem( session: HydratedDocument, input: SessionModel['lineItemCreateBody'], From fd4e085b6646e2aa6d94ee6cb1ee7bea0bef0654 Mon Sep 17 00:00:00 2001 From: Anass El Jabiry Date: Tue, 11 Aug 2026 01:04:22 +0200 Subject: [PATCH 5/9] feat(web): discard the draft session when retaking the photo "Retake photo" was a plain link back to home, which left the draft session and its receipt image behind on the server. It now deletes the session first, drops its device token and cached query, and navigates home once the request settles. Also drop the header back link: leaving the review screen without resolving the draft is exactly what that route no longer allows. --- .../features/session/api/delete-session.ts | 44 +++++++++++++++++ .../session/components/session-draft.tsx | 47 +++++++++++-------- apps/web/tsconfig.app.json | 7 +-- 3 files changed, 73 insertions(+), 25 deletions(-) create mode 100644 apps/web/src/features/session/api/delete-session.ts diff --git a/apps/web/src/features/session/api/delete-session.ts b/apps/web/src/features/session/api/delete-session.ts new file mode 100644 index 0000000..94dfc59 --- /dev/null +++ b/apps/web/src/features/session/api/delete-session.ts @@ -0,0 +1,44 @@ +import { useMutation, useQueryClient } from '@tanstack/react-query'; +import { api, apiError } from '@/lib/api-client'; +import type { MutationConfig } from '@/lib/react-query'; +import { clearToken } from '@/utils/device-token'; +import { getSessionQueryOptions } from './get-session'; + +export const deleteSession = async ({ + sessionId, +}: { + sessionId: string; +}): Promise => { + return api + .sessions({ sessionId }) + .delete() + .then(({ error }) => { + if (error) throw apiError(error.value, 'Failed to discard the session'); + }); +}; + +type UseDeleteSessionOptions = { + sessionId: string; + mutationConfig?: MutationConfig; +}; + +export const useDeleteSession = ({ + sessionId, + mutationConfig, +}: UseDeleteSessionOptions) => { + const queryClient = useQueryClient(); + + const { onSuccess, ...restConfig } = mutationConfig || {}; + + return useMutation({ + onSuccess: (...args) => { + clearToken(sessionId); + queryClient.removeQueries({ + queryKey: getSessionQueryOptions(sessionId).queryKey, + }); + onSuccess?.(...args); + }, + ...restConfig, + mutationFn: deleteSession, + }); +}; diff --git a/apps/web/src/features/session/components/session-draft.tsx b/apps/web/src/features/session/components/session-draft.tsx index c3d1d2d..a3e0059 100644 --- a/apps/web/src/features/session/components/session-draft.tsx +++ b/apps/web/src/features/session/components/session-draft.tsx @@ -1,5 +1,5 @@ import { useForm } from '@tanstack/react-form'; -import { Link } from '@tanstack/react-router'; +import { useNavigate } from '@tanstack/react-router'; import { AlertTriangle, Camera, @@ -7,8 +7,8 @@ import { ChevronLeft, Link as LinkIcon, } from 'lucide-react'; -import { Button, buttonVariants } from 'shadcn-ui/button'; -import { cn } from 'shadcn-ui-utils/cn'; +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'; @@ -39,13 +39,6 @@ function ReviewHeader({ session }: { session: Session }) { return (
- - -

Review receipt

{subtitle && ( @@ -121,20 +114,34 @@ function ConfirmButton({ session }: { session: Session }) { ); } +function RetakePhotoButton({ session }: { session: Session }) { + const navigate = useNavigate(); + const deleteSession = useDeleteSession({ sessionId: session.id }); + + return ( + + ); +} + function ReviewFooter({ session }: { session: Session }) { return (
- - - Retake photo - +
diff --git a/apps/web/tsconfig.app.json b/apps/web/tsconfig.app.json index 520b9e7..39510a1 100644 --- a/apps/web/tsconfig.app.json +++ b/apps/web/tsconfig.app.json @@ -22,13 +22,10 @@ "include": ["src/**/*.js", "src/**/*.jsx", "src/**/*.ts", "src/**/*.tsx"], "references": [ { - "path": "../../libs/shared-types/tsconfig.lib.json" - }, - { - "path": "../../libs/shadcn-ui-utils/tsconfig.lib.json" + "path": "../api" }, { - "path": "../api" + "path": "../../libs/shared-types/tsconfig.lib.json" }, { "path": "../../libs/shadcn-ui/tsconfig.lib.json" From 3988cc7a437dc0f24e382f9a809f45572fd14205 Mon Sep 17 00:00:00 2001 From: aek676 Date: Tue, 11 Aug 2026 11:07:56 +0200 Subject: [PATCH 6/9] refactor(api): drop the unused media type re-export from the app MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `app.ts` re-exported `EXT_BY_MEDIA_TYPE`, `SUPPORTED_IMAGE_MIME_TYPES` and `SupportedImageMimeType` next to the `App` type, but nothing consumed them: `apps/web/src/lib/api-client.ts` is the only importer of `@repo/api` and it takes `import type { App }` alone. The `./constants` subpath they used to be reachable through is gone too. They are value exports on a module that transitively pulls in `mongoose` and `@google-cloud/storage`, so importing them from here would drag the server into the browser bundle — the coupling that moving the media types to `@repo/shared-types` set out to remove. Consumers already take them from `@repo/shared-types` or from `storage/object-storage`. --- apps/api/src/app.ts | 6 ------ 1 file changed, 6 deletions(-) diff --git a/apps/api/src/app.ts b/apps/api/src/app.ts index 601ce01..bece2ad 100644 --- a/apps/api/src/app.ts +++ b/apps/api/src/app.ts @@ -27,9 +27,3 @@ export const app = new Elysia() .get('/', () => ({ hello: 'snapsplit' })); export type App = typeof app; - -export { - EXT_BY_MEDIA_TYPE, - SUPPORTED_IMAGE_MIME_TYPES, - type SupportedImageMimeType, -} from './storage/object-storage'; From b8c10f92e1e0e13fa8534658b7985f57907b826e Mon Sep 17 00:00:00 2001 From: aek676 Date: Tue, 11 Aug 2026 11:08:04 +0200 Subject: [PATCH 7/9] fix(web): forget a discarded session even when the delete fails `clearToken` and `removeQueries` ran in the mutation's `onSuccess` while the button navigated home on `onSettled`, so a failed `DELETE` left for home with the device token still stored and the session still cached. Pressing back returned the user to the draft they had just discarded, alive and editable. Discarding is local-first: "Retake photo" is both a delete and an intent to move on, and the intent does not hang on the server answering. The device now forgets the session either way, and a document left behind expires with its TTL. Clearing the token before leaving is safe because `expireSession` treats a session it holds no token for as already handled, so a late refetch neither toasts nor redirects. --- apps/web/src/features/session/api/delete-session.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/apps/web/src/features/session/api/delete-session.ts b/apps/web/src/features/session/api/delete-session.ts index 94dfc59..53ea8b2 100644 --- a/apps/web/src/features/session/api/delete-session.ts +++ b/apps/web/src/features/session/api/delete-session.ts @@ -28,15 +28,15 @@ export const useDeleteSession = ({ }: UseDeleteSessionOptions) => { const queryClient = useQueryClient(); - const { onSuccess, ...restConfig } = mutationConfig || {}; + const { onSettled, ...restConfig } = mutationConfig || {}; return useMutation({ - onSuccess: (...args) => { + onSettled: (...args) => { clearToken(sessionId); queryClient.removeQueries({ queryKey: getSessionQueryOptions(sessionId).queryKey, }); - onSuccess?.(...args); + onSettled?.(...args); }, ...restConfig, mutationFn: deleteSession, From 1157904f9224c828f31a6dd29a8a7915aafa8168 Mon Sep 17 00:00:00 2001 From: aek676 Date: Tue, 11 Aug 2026 11:08:10 +0200 Subject: [PATCH 8/9] chore(web): drop the ChevronLeft import left behind by the header link Removing the header back link took away the icon's only consumer. Biome reports it as `lint/correctness/noUnusedImports`, but only as a warning, so `nx lint web` stayed green with it in place. --- apps/web/src/features/session/components/session-draft.tsx | 1 - 1 file changed, 1 deletion(-) diff --git a/apps/web/src/features/session/components/session-draft.tsx b/apps/web/src/features/session/components/session-draft.tsx index a3e0059..17fcf46 100644 --- a/apps/web/src/features/session/components/session-draft.tsx +++ b/apps/web/src/features/session/components/session-draft.tsx @@ -4,7 +4,6 @@ import { AlertTriangle, Camera, CheckCircle2, - ChevronLeft, Link as LinkIcon, } from 'lucide-react'; import { Button } from 'shadcn-ui/button'; From b80f1c0b1237442beacf4fb4540d131eb440a57d Mon Sep 17 00:00:00 2001 From: aek676 Date: Tue, 11 Aug 2026 11:16:46 +0200 Subject: [PATCH 9/9] refactor(api): move the shared objectId schema out of the src root `src/model.ts` held a single Elysia schema and sat next to `index.ts` and `app.ts`, where the rest of the tree is folders by responsibility. It also collided by name with the per-module `modules/session/model.ts` and `modules/auth/model.ts`, so `'../model'` and `'../../model'` read as if they pointed at a module's own schemas when they pointed at a global one. It now lives in `src/common/model.ts`, alongside `plugins/`, `schemas/` and `storage/`, which leaves an obvious home for the next validation schema shared across modules. The two importers, `plugins/auth.ts` and `modules/session/model.ts`, are the only ones in the repo. `OBJECT_ID_PATTERN` stays in `@repo/shared-types`. The binding to `t.String` does not follow it there: that lib is framework-agnostic and `apps/web` consumes it through a `export *` barrel, so an Elysia schema would pull typebox into the browser bundle's type graph. --- apps/api/src/{ => common}/model.ts | 0 apps/api/src/modules/session/model.ts | 2 +- apps/api/src/plugins/auth.ts | 2 +- 3 files changed, 2 insertions(+), 2 deletions(-) rename apps/api/src/{ => common}/model.ts (100%) diff --git a/apps/api/src/model.ts b/apps/api/src/common/model.ts similarity index 100% rename from apps/api/src/model.ts rename to apps/api/src/common/model.ts diff --git a/apps/api/src/modules/session/model.ts b/apps/api/src/modules/session/model.ts index 1db8f4e..5eddb10 100644 --- a/apps/api/src/modules/session/model.ts +++ b/apps/api/src/modules/session/model.ts @@ -1,5 +1,5 @@ import { t } from 'elysia'; -import { objectId } from '../../model'; +import { objectId } from '../../common/model'; import { SUPPORTED_IMAGE_MIME_TYPES } from '../../storage/object-storage'; const lineItemView = t.Object({ diff --git a/apps/api/src/plugins/auth.ts b/apps/api/src/plugins/auth.ts index 1ba4c81..1b91497 100644 --- a/apps/api/src/plugins/auth.ts +++ b/apps/api/src/plugins/auth.ts @@ -1,5 +1,5 @@ import { Elysia, status, t } from 'elysia'; -import { objectId } from '../model'; +import { objectId } from '../common/model'; import { AuthModel } from '../modules/auth/model'; import { hashToken } from '../modules/auth/service'; import { Session } from '../schemas';