Skip to content
Merged
Show file tree
Hide file tree
Changes from 8 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Empty file.
2 changes: 2 additions & 0 deletions apps/api/.env.example
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
4 changes: 0 additions & 4 deletions apps/api/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,6 @@
".": {
"types": "./src/app.ts",
"default": "./src/app.ts"
},
"./constants": {
"types": "./src/constants.ts",
"default": "./src/constants.ts"
}
}
}
1 change: 0 additions & 1 deletion apps/api/src/constants.ts

This file was deleted.

48 changes: 48 additions & 0 deletions apps/api/src/modules/receipt/__test__/index.spec.ts
Original file line number Diff line number Diff line change
@@ -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> = {}): 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');
});
});
27 changes: 27 additions & 0 deletions apps/api/src/modules/receipt/__test__/service.spec.ts
Original file line number Diff line number Diff line change
@@ -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();
});
});
64 changes: 35 additions & 29 deletions apps/api/src/modules/receipt/index.ts
Original file line number Diff line number Diff line change
@@ -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) => [
Expand All @@ -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);
21 changes: 21 additions & 0 deletions apps/api/src/modules/receipt/service.ts
Original file line number Diff line number Diff line change
@@ -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;
}
112 changes: 106 additions & 6 deletions apps/api/src/modules/session/__test__/index.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand All @@ -30,15 +30,20 @@ const extracted: ExtractedReceipt = {
],
};

function fakeStorage(overrides: Partial<ReceiptStorage> = {}): ReceiptStorage {
function fakeStorage(overrides: Partial<ObjectStorage> = {}): 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<typeof mock>).mock.calls[0][0] as string;
}

function moduleWith(extract: ExtractReceipt, storage = fakeStorage()) {
return createSessionModule(new SessionService(extract, storage));
}
Expand Down Expand Up @@ -77,16 +82,21 @@ describe('POST /sessions/analyze', () => {
});

it('returns 200 with the serialized draft view', async () => {
const app = moduleWith(mock<ExtractReceipt>(async () => extracted));
const storage = fakeStorage();
const app = moduleWith(
mock<ExtractReceipt>(async () => extracted),
storage,
);

const res = await app.handle(analyzeRequest(imageFile('image/png')));

expect(res.status).toBe(200);
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 () => {
Expand Down Expand Up @@ -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));
});
});

Expand Down Expand Up @@ -367,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<ExtractReceipt>(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<ExtractReceipt>(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<ExtractReceipt>(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<ExtractReceipt>(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<ExtractReceipt>(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(() => {});
Expand Down
Loading
Loading