mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-12-03 09:38:54 +00:00
feat(llm-parse): read a photo, as a booking or as a receipt in Costs
Whether the AI Parsing model reads images is an admin setting now, and it lands with the two features that send a photo, so it has something to control. The setting is `vision: 'auto' | 'on' | 'off'` on the addon config. On Automatic a local Ollama is asked what the model can do (`/api/show`), and a cloud provider means no; Yes and No are applied as set. The old `multimodal` flag is not read: the admin screens wrote it false on every save, so a stored false meant nothing. The per-user toggle keeps its on/off meaning and is read by the extraction now. The lookup is server-side only: capped read, validated body, never throws, cached per server and model. GET /api/llm/capabilities answers it for the signed-in caller, and both photo pickers below ask it. The booking import takes JPG, PNG and WEBP when the model reads images. The photo goes as an image to every provider (image_url, an Anthropic image block, Ollama's native chat with `images`), capped at 1600px, and skips KDE Itinerary. A scanned PDF, which used to reach the model as empty text, has its first two pages drawn by pdf-parse and sent the same way. The rest is the import as it was: background job, review, the file attached to the booking, the linked cost. On a real qwen3.5:4b a train ticket came back as bare clock times until the router gave the model every type's field meanings, and its price as an object inside a string, which read as 4900; both are handled. Costs gets Scan receipt: a dialog laid out like the booking import's takes one photo, read on the import job queue, then reviewed in the existing expense editor pre-filled with merchant, total, currency, day and lines, the photo waiting in Receipts & Invoices to be uploaded on save. No table, no migration, no category guess, no document-type detection.
This commit is contained in:
@@ -79,6 +79,18 @@ describe('BookingImportService.preview', () => {
|
||||
expect(res.files![0].aiUsed).toBe(false);
|
||||
});
|
||||
|
||||
it('fallback-on-empty: a photo goes straight to the LLM, kitinerary is not asked', async () => {
|
||||
const { svc, extractor, llmParse } = make({
|
||||
kit: true, ai: true,
|
||||
extract: async () => [HOTEL_KI],
|
||||
parse: async () => ({ kiItems: [HOTEL_KI], warnings: [] }),
|
||||
});
|
||||
const res = await svc.preview([file('ticket.jpg')], 'fallback-on-empty', 1);
|
||||
expect(extractor.extract).not.toHaveBeenCalled();
|
||||
expect(llmParse.parse).toHaveBeenCalledWith({ buffer: expect.any(Buffer), originalName: 'ticket.jpg' }, 1);
|
||||
expect(res.items[0].needs_review).toBe(true);
|
||||
});
|
||||
|
||||
it('force-ai: skips kitinerary entirely and uses the LLM', async () => {
|
||||
const { svc, extractor, llmParse } = make({
|
||||
kit: true, ai: true,
|
||||
|
||||
@@ -7,8 +7,8 @@ import { ImportJobsService } from '../../../../src/nest/booking-import/import-jo
|
||||
import { RealtimeService } from '../../../../src/nest/realtime/realtime.service';
|
||||
|
||||
type Preview = ReturnType<typeof vi.fn>;
|
||||
function makeService(preview: Preview) {
|
||||
return new ImportJobsService({ preview } as never, new RealtimeService());
|
||||
function makeService(preview: Preview, readReceipt: Preview = vi.fn()) {
|
||||
return new ImportJobsService({ preview } as never, new RealtimeService(), { readReceipt } as never);
|
||||
}
|
||||
const files = (n: number) => Array.from({ length: n }, (_, i) => ({ originalname: `f${i}.pdf` })) as never;
|
||||
const eventsFor = (jobId: string) => broadcastToUser.mock.calls.map((c) => c[1]).filter((p) => p.jobId === jobId);
|
||||
@@ -101,3 +101,30 @@ describe('ImportJobsService', () => {
|
||||
expect(svc.get(id, 99)).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe('ImportJobsService.startReceipt', () => {
|
||||
it('reads the receipt off-request and pushes the read as the result', async () => {
|
||||
const result = { receipt: { merchant: 'Shop', date: null, total: 4, currency: 'EUR', items: [] }, warnings: [] };
|
||||
const readReceipt = vi.fn(async () => result);
|
||||
const svc = makeService(vi.fn(), readReceipt);
|
||||
const id = svc.startReceipt('7', { originalname: 'r.jpg', buffer: Buffer.from('x') } as never, 42);
|
||||
|
||||
await vi.waitFor(() => expect(svc.get(id, 42)?.status).toBe('done'));
|
||||
expect(svc.get(id, 42)).toMatchObject({ result, done: 1, total: 1 });
|
||||
expect(readReceipt).toHaveBeenCalledWith({ buffer: Buffer.from('x'), originalName: 'r.jpg' }, 42);
|
||||
expect(eventsFor(id).find((p) => p.type === 'import:done')).toMatchObject({ result, tripId: '7' });
|
||||
});
|
||||
|
||||
it('queues behind the same user\'s booking parse rather than running beside it', async () => {
|
||||
let release!: () => void;
|
||||
const preview = vi.fn(() => new Promise((resolve) => { release = () => resolve({ items: [] }); }));
|
||||
const readReceipt = vi.fn(async () => ({ receipt: null, warnings: [] }));
|
||||
const svc = makeService(preview, readReceipt);
|
||||
svc.start('7', files(1), 'force-ai', 42);
|
||||
const id = svc.startReceipt('7', { originalname: 'r.jpg', buffer: Buffer.from('x') } as never, 42);
|
||||
await new Promise((r) => setTimeout(r, 10));
|
||||
expect(readReceipt).not.toHaveBeenCalled();
|
||||
release();
|
||||
await vi.waitFor(() => expect(svc.get(id, 42)?.status).toBe('done'));
|
||||
});
|
||||
});
|
||||
|
||||
@@ -14,6 +14,7 @@ function make(over: Partial<BookingImportService> = {}) {
|
||||
canEdit: vi.fn(() => true),
|
||||
isAvailable: vi.fn(() => true),
|
||||
aiAvailable: vi.fn(() => true),
|
||||
readsImages: vi.fn(async () => true),
|
||||
preview: vi.fn(async () => ({ items: [], warnings: [], files: [] })),
|
||||
...over,
|
||||
} as unknown as BookingImportService;
|
||||
@@ -55,6 +56,28 @@ describe('ReservationImportController.preview', () => {
|
||||
expect(svc.preview).toHaveBeenCalledWith([expect.anything()], 'fallback-on-empty', 1);
|
||||
});
|
||||
|
||||
it('takes a photo when the model reads images, without asking otherwise', async () => {
|
||||
const { c, svc } = make();
|
||||
await c.preview(user, 't1', [file('ticket.JPG')], { mode: 'fallback-on-empty' });
|
||||
expect(svc.preview).toHaveBeenCalledWith([expect.anything()], 'fallback-on-empty', 1);
|
||||
(svc.readsImages as ReturnType<typeof vi.fn>).mockClear();
|
||||
await c.preview(user, 't1', [file('a.pdf')], { mode: 'fallback-on-empty' });
|
||||
expect(svc.readsImages).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('refuses a photo with 400 when the model does not read images, or AI is not asked', async () => {
|
||||
const { c, svc } = make({ readsImages: vi.fn(async () => false) });
|
||||
expect(await status(() => c.preview(user, 't1', [file('a.pdf'), file('ticket.png')], { mode: 'fallback-on-empty' }))).toBe(400);
|
||||
const { c: c2 } = make();
|
||||
expect(await status(() => c2.preview(user, 't1', [file('ticket.png')], { mode: 'no-ai' }))).toBe(400);
|
||||
expect(svc.preview).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('still refuses a file type it does not know, HEIC included', async () => {
|
||||
const { c } = make();
|
||||
expect(await status(() => c.preview(user, 't1', [file('IMG_1.heic')], { mode: 'fallback-on-empty' }))).toBe(400);
|
||||
});
|
||||
|
||||
it('defaults the mode to no-ai when omitted', async () => {
|
||||
const { c, svc } = make();
|
||||
await c.preview(user, 't1', [file()], {});
|
||||
|
||||
@@ -275,6 +275,15 @@ describe('OpenAiCompatibleClient', () => {
|
||||
expect(safeFetchLlmMock).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('sends each page of a scanned PDF as its own image_url, in order', async () => {
|
||||
const fetchFn = mockFetch(() => jsonResponse({ choices: [{ message: { content: '{"reservations":[]}' } }] }));
|
||||
const page = (n: string) => ({ mimeType: 'image/png', data: Buffer.from(n) });
|
||||
await new OpenAiCompatibleClient().extract({ ...baseInput, text: undefined, file: page('p1'), pageImages: [page('p2')] });
|
||||
const parts = JSON.parse((fetchFn.mock.calls[0][1] as RequestInit).body as string).messages[1].content;
|
||||
const urls = parts.filter((p: { type: string }) => p.type === 'image_url').map((p: { image_url: { url: string } }) => p.image_url.url);
|
||||
expect(urls).toEqual([`data:image/png;base64,${Buffer.from('p1').toString('base64')}`, `data:image/png;base64,${Buffer.from('p2').toString('base64')}`]);
|
||||
});
|
||||
|
||||
it('sends an image natively as image_url but never a file/pdf part', async () => {
|
||||
const fetchFn = mockFetch(() => jsonResponse({ choices: [{ message: { content: '{"reservations":[]}' } }] }));
|
||||
await new OpenAiCompatibleClient().extract({ ...baseInput, file: { mimeType: 'image/png', data: Buffer.from('IMG') } });
|
||||
@@ -380,6 +389,28 @@ describe('OpenAiCompatibleClient — NuExtract path', () => {
|
||||
});
|
||||
|
||||
describe('AnthropicClient', () => {
|
||||
it('sends the pages of a scanned PDF as image blocks after the first', async () => {
|
||||
const fetchFn = mockFetch(() =>
|
||||
jsonResponse({ stop_reason: 'tool_use', content: [{ type: 'tool_use', name: 'emit_reservations', input: { reservations: [] } }] }),
|
||||
);
|
||||
const page = (n: string) => ({ mimeType: 'image/png', data: Buffer.from(n) });
|
||||
await new AnthropicClient().extract({ ...baseInput, text: undefined, file: page('p1'), pageImages: [page('p2')] });
|
||||
const content = JSON.parse((fetchFn.mock.calls[0][1] as RequestInit).body as string).messages[0].content;
|
||||
expect(content.map((b: { type: string }) => b.type)).toEqual(['image', 'image', 'text']);
|
||||
expect(content[1].source.data).toBe(Buffer.from('p2').toString('base64'));
|
||||
});
|
||||
|
||||
it('sends a photo as an image block and a PDF as a document block', async () => {
|
||||
const fetchFn = mockFetch(() =>
|
||||
jsonResponse({ stop_reason: 'tool_use', content: [{ type: 'tool_use', name: 'emit_reservations', input: { reservations: [] } }] }),
|
||||
);
|
||||
await new AnthropicClient().extract({ ...baseInput, text: undefined, file: { mimeType: 'image/jpeg', data: Buffer.from('jpg') } });
|
||||
await new AnthropicClient().extract({ ...baseInput, text: undefined, file: { mimeType: 'application/pdf', data: Buffer.from('pdf') } });
|
||||
const blockOf = (i: number) => JSON.parse((fetchFn.mock.calls[i][1] as RequestInit).body as string).messages[0].content[0];
|
||||
expect(blockOf(0)).toEqual({ type: 'image', source: { type: 'base64', media_type: 'image/jpeg', data: Buffer.from('jpg').toString('base64') } });
|
||||
expect(blockOf(1).type).toBe('document');
|
||||
});
|
||||
|
||||
it('forces the emit_reservations tool and reads its input', async () => {
|
||||
const fetchFn = mockFetch(() =>
|
||||
jsonResponse({ stop_reason: 'tool_use', content: [{ type: 'tool_use', name: 'emit_reservations', input: { reservations: [{ '@type': 'LodgingReservation' }] } }] }),
|
||||
|
||||
@@ -15,6 +15,7 @@ import {
|
||||
detectFlightNumbers,
|
||||
fixArrivalDate,
|
||||
routeExtraction,
|
||||
routeImageExtraction,
|
||||
} from '../../../../src/nest/llm-parse/router/extraction-router';
|
||||
|
||||
const CTX = { baseUrl: 'http://ollama:11434/v1', model: 'qwen3:8b' };
|
||||
@@ -257,3 +258,64 @@ describe('printed 12-hour clocks and unreadable types (#2094, #2076)', () => {
|
||||
expect(flats[0].type_guessed).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe('routeImageExtraction', () => {
|
||||
it('makes one enforced call with the photo attached and lets the model pick the type', async () => {
|
||||
extractEnforced.mockResolvedValue({ type: 'train', from_name: 'Lyon', to_name: 'Paris', price: '42', currency: 'EUR' });
|
||||
const out = await routeImageExtraction([Buffer.from('photo')], CTX);
|
||||
expect(out).toEqual({ kiItems: [{ '@type': 'Mock' }], warnings: [] });
|
||||
expect(extractEnforced).toHaveBeenCalledTimes(1);
|
||||
const call = extractEnforced.mock.calls[0][0];
|
||||
expect(call.images).toEqual([Buffer.from('photo').toString('base64')]);
|
||||
expect(call.numCtx).toBe(16384);
|
||||
expect(call.user).not.toMatch(/Document:/);
|
||||
expect(mapToKi.mock.calls[0][0][0]).toMatchObject({ type: 'train', from_name: 'Lyon', price: '42', currency: 'EUR' });
|
||||
});
|
||||
|
||||
it('tells the model what each type\'s fields mean, since a photo has no keyword to pick a schema', async () => {
|
||||
extractEnforced.mockResolvedValue({ type: 'train' });
|
||||
await routeImageExtraction([Buffer.from('photo')], CTX);
|
||||
const system = extractEnforced.mock.calls[0][0].system;
|
||||
expect(system).toMatch(/from_name\/to_name = stations/);
|
||||
expect(system).toMatch(/full ISO/);
|
||||
});
|
||||
|
||||
it('reads a price the model wrapped as an object inside the string', async () => {
|
||||
extractEnforced.mockResolvedValue({ type: 'train', price: '{"amount": 49.00, "currency": "EUR"}' });
|
||||
await routeImageExtraction([Buffer.from('photo')], CTX);
|
||||
expect(mapToKi.mock.calls[0][0][0]).toMatchObject({ price: '49', currency: 'EUR' });
|
||||
|
||||
mapToKi.mockClear();
|
||||
extractEnforced.mockResolvedValue({ type: 'train', price: '{"amount": "12,50"}', currency: 'CHF' });
|
||||
await routeImageExtraction([Buffer.from('photo')], CTX);
|
||||
expect(mapToKi.mock.calls[0][0][0]).toMatchObject({ price: '12,50', currency: 'CHF' });
|
||||
|
||||
mapToKi.mockClear();
|
||||
extractEnforced.mockResolvedValue({ type: 'train', price: '{"note": "see below"}' });
|
||||
await routeImageExtraction([Buffer.from('photo')], CTX);
|
||||
expect(mapToKi.mock.calls[0][0][0]).not.toHaveProperty('price');
|
||||
});
|
||||
|
||||
it('leaves a plain price, or one that only looks like an object, as it came', async () => {
|
||||
for (const price of ['49,00 EUR', '{not json']) {
|
||||
mapToKi.mockClear();
|
||||
extractEnforced.mockResolvedValue({ type: 'train', price });
|
||||
await routeImageExtraction([Buffer.from('photo')], CTX);
|
||||
expect(mapToKi.mock.calls[0][0][0].price).toBe(price);
|
||||
}
|
||||
});
|
||||
|
||||
it('attaches every page of a scanned PDF to the one call', async () => {
|
||||
extractEnforced.mockResolvedValue({ type: 'hotel' });
|
||||
await routeImageExtraction([Buffer.from('p1'), Buffer.from('p2')], CTX);
|
||||
expect(extractEnforced).toHaveBeenCalledTimes(1);
|
||||
expect(extractEnforced.mock.calls[0][0].images).toEqual([Buffer.from('p1').toString('base64'), Buffer.from('p2').toString('base64')]);
|
||||
});
|
||||
|
||||
it('degrades to a warning when the call throws', async () => {
|
||||
extractEnforced.mockRejectedValue(new Error('timeout'));
|
||||
const out = await routeImageExtraction([Buffer.from('photo')], CTX);
|
||||
expect(out.kiItems).toEqual([]);
|
||||
expect(out.warnings[0]).toMatch(/timeout/);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { Jimp } from 'jimp';
|
||||
import { capImage, imageMimeType, IMAGE_MAX_EDGE, renderPdfPages } from '../../../../src/nest/llm-parse/image-input';
|
||||
|
||||
async function png(w: number, h: number): Promise<Buffer> {
|
||||
const image = new Jimp({ width: w, height: h, color: 0xffffffff });
|
||||
return Buffer.from(await image.getBuffer('image/png'));
|
||||
}
|
||||
|
||||
describe('imageMimeType', () => {
|
||||
it('knows the photo formats a provider reads, whatever the case', () => {
|
||||
expect(imageMimeType('a.jpg')).toBe('image/jpeg');
|
||||
expect(imageMimeType('A.JPEG')).toBe('image/jpeg');
|
||||
expect(imageMimeType('a.png')).toBe('image/png');
|
||||
expect(imageMimeType('a.webp')).toBe('image/webp');
|
||||
});
|
||||
|
||||
it('is null for everything else, HEIC included', () => {
|
||||
for (const name of ['a.heic', 'a.pdf', 'a.txt', 'jpg', 'a.jpg.pdf']) expect(imageMimeType(name)).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('capImage', () => {
|
||||
it('shrinks the long edge of a large photo to the cap, as a JPEG', async () => {
|
||||
const out = await capImage(await png(IMAGE_MAX_EDGE * 2, 1000), 'image/png');
|
||||
expect(out.mimeType).toBe('image/jpeg');
|
||||
const back = await Jimp.read(out.data);
|
||||
expect(back.width).toBe(IMAGE_MAX_EDGE);
|
||||
expect(back.height).toBe(500);
|
||||
});
|
||||
|
||||
it('caps a portrait photo by its height', async () => {
|
||||
const back = await Jimp.read((await capImage(await png(800, IMAGE_MAX_EDGE * 2), 'image/png')).data);
|
||||
expect(back.height).toBe(IMAGE_MAX_EDGE);
|
||||
expect(back.width).toBe(400);
|
||||
});
|
||||
|
||||
it('leaves a photo that is already small enough untouched', async () => {
|
||||
const data = await png(400, 300);
|
||||
expect(await capImage(data, 'image/png')).toEqual({ data, mimeType: 'image/png' });
|
||||
});
|
||||
|
||||
it('passes bytes it cannot decode through unchanged', async () => {
|
||||
const data = Buffer.from('RIFF....WEBP');
|
||||
expect(await capImage(data, 'image/webp')).toEqual({ data, mimeType: 'image/webp' });
|
||||
});
|
||||
});
|
||||
|
||||
/** A PDF with no text layer: each page is one JPEG, as a scanner writes it. */
|
||||
async function scannedPdf(pages: number): Promise<Buffer> {
|
||||
const jpg = Buffer.from(await new Jimp({ width: 300, height: 400, color: 0xddddddff }).getBuffer('image/jpeg'));
|
||||
const objects: Buffer[] = [];
|
||||
const kids = Array.from({ length: pages }, (_, i) => `${3 + i * 3} 0 R`).join(' ');
|
||||
objects.push(Buffer.from('<< /Type /Catalog /Pages 2 0 R >>'));
|
||||
objects.push(Buffer.from(`<< /Type /Pages /Kids [${kids}] /Count ${pages} >>`));
|
||||
for (let i = 0; i < pages; i++) {
|
||||
const page = 3 + i * 3;
|
||||
const content = 'q 300 0 0 400 0 0 cm /Im0 Do Q';
|
||||
objects.push(Buffer.from(`<< /Type /Page /Parent 2 0 R /MediaBox [0 0 300 400] /Resources << /XObject << /Im0 ${page + 2} 0 R >> >> /Contents ${page + 1} 0 R >>`));
|
||||
objects.push(Buffer.from(`<< /Length ${content.length} >>\nstream\n${content}\nendstream`));
|
||||
objects.push(Buffer.concat([
|
||||
Buffer.from(`<< /Type /XObject /Subtype /Image /Width 300 /Height 400 /ColorSpace /DeviceRGB /BitsPerComponent 8 /Filter /DCTDecode /Length ${jpg.length} >>\nstream\n`),
|
||||
jpg,
|
||||
Buffer.from('\nendstream'),
|
||||
]));
|
||||
}
|
||||
const parts: Buffer[] = [Buffer.from('%PDF-1.4\n')];
|
||||
const offsets: number[] = [];
|
||||
let length = parts[0].length;
|
||||
objects.forEach((body, i) => {
|
||||
offsets.push(length);
|
||||
const obj = Buffer.concat([Buffer.from(`${i + 1} 0 obj\n`), body, Buffer.from('\nendobj\n')]);
|
||||
parts.push(obj);
|
||||
length += obj.length;
|
||||
});
|
||||
const rows = offsets.map((o) => `${String(o).padStart(10, '0')} 00000 n \n`).join('');
|
||||
parts.push(Buffer.from(`xref\n0 ${objects.length + 1}\n0000000000 65535 f \n${rows}trailer\n<< /Size ${objects.length + 1} /Root 1 0 R >>\nstartxref\n${length}\n%%EOF\n`));
|
||||
return Buffer.concat(parts);
|
||||
}
|
||||
|
||||
describe('renderPdfPages', () => {
|
||||
it('draws the first two pages of a scan as images no larger than a capped photo', async () => {
|
||||
const pages = await renderPdfPages(await scannedPdf(3));
|
||||
expect(pages).toHaveLength(2);
|
||||
for (const page of pages) {
|
||||
const image = await Jimp.read(page.data);
|
||||
expect(Math.max(image.width, image.height)).toBeLessThanOrEqual(IMAGE_MAX_EDGE);
|
||||
}
|
||||
}, 30_000);
|
||||
|
||||
it('throws for bytes that are not a PDF, which the caller reports as unreadable', async () => {
|
||||
await expect(renderPdfPages(Buffer.from('not a pdf'))).rejects.toThrow();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,20 @@
|
||||
import { describe, it, expect, vi } from 'vitest';
|
||||
import { GUARDS_METADATA } from '@nestjs/common/constants';
|
||||
import { LlmCapabilitiesController } from '../../../../src/nest/llm-parse/llm-capabilities.controller';
|
||||
import { JwtAuthGuard } from '../../../../src/nest/auth/jwt-auth.guard';
|
||||
import type { LlmParseService } from '../../../../src/nest/llm-parse/llm-parse.service';
|
||||
import type { User } from '../../../../src/types';
|
||||
|
||||
describe('LlmCapabilitiesController', () => {
|
||||
it("answers whether the caller's model reads images", async () => {
|
||||
const readsImages = vi.fn(async (id: number) => id === 1);
|
||||
const c = new LlmCapabilitiesController({ readsImages } as unknown as LlmParseService);
|
||||
await expect(c.capabilities({ id: 1 } as User)).resolves.toEqual({ images: true });
|
||||
await expect(c.capabilities({ id: 2 } as User)).resolves.toEqual({ images: false });
|
||||
expect(readsImages).toHaveBeenCalledWith(2);
|
||||
});
|
||||
|
||||
it('needs a session', () => {
|
||||
expect(Reflect.getMetadata(GUARDS_METADATA, LlmCapabilitiesController)).toContain(JwtAuthGuard);
|
||||
});
|
||||
});
|
||||
@@ -64,16 +64,25 @@ describe('resolveLlmConfig', () => {
|
||||
});
|
||||
|
||||
it('uses instance config when present (and decrypts the key)', () => {
|
||||
setInstanceConfig({ provider: 'anthropic', model: 'claude-opus-4-8', apiKey: 'sk-plain', multimodal: true });
|
||||
setInstanceConfig({ provider: 'anthropic', model: 'claude-opus-4-8', apiKey: 'sk-plain', vision: 'on' });
|
||||
expect(resolver.resolve(1)).toEqual({
|
||||
provider: 'anthropic',
|
||||
model: 'claude-opus-4-8',
|
||||
baseUrl: undefined,
|
||||
apiKey: 'sk-plain',
|
||||
multimodal: true,
|
||||
vision: 'on',
|
||||
});
|
||||
});
|
||||
|
||||
it('reads the instance vision setting as auto when it is missing, unknown, or only the old multimodal flag', () => {
|
||||
for (const extra of [{}, { vision: 'maybe' }, { multimodal: false }, { multimodal: true }]) {
|
||||
setInstanceConfig({ provider: 'local', model: 'qwen3.5:4b', ...extra });
|
||||
expect(resolver.resolve(1)?.vision).toBe('auto');
|
||||
}
|
||||
setInstanceConfig({ provider: 'local', model: 'qwen3.5:4b', vision: 'off' });
|
||||
expect(resolver.resolve(1)?.vision).toBe('off');
|
||||
});
|
||||
|
||||
it('instance config with a base URL still wins for a plain user (#1772 does not touch it)', () => {
|
||||
setInstanceConfig({ provider: 'local', model: 'nuextract', baseUrl: 'http://ollama:11434' });
|
||||
setRole('user');
|
||||
@@ -89,7 +98,7 @@ describe('resolveLlmConfig', () => {
|
||||
model: 'claude-sonnet',
|
||||
baseUrl: undefined,
|
||||
apiKey: 'user-key',
|
||||
multimodal: true,
|
||||
vision: 'on',
|
||||
});
|
||||
expect(getDecryptedUserSetting).toHaveBeenCalledWith(7, 'llm_api_key');
|
||||
});
|
||||
@@ -114,7 +123,7 @@ describe('resolveLlmConfig', () => {
|
||||
model: 'gpt-4o-mini',
|
||||
baseUrl: undefined,
|
||||
apiKey: 'sk-user',
|
||||
multimodal: false,
|
||||
vision: 'off',
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { prepareLlmAddonConfigForWrite } from '../../../../src/nest/llm-parse/llm-config';
|
||||
|
||||
describe('prepareLlmAddonConfigForWrite: the vision setting', () => {
|
||||
it('stores a known mode as sent', () => {
|
||||
for (const vision of ['auto', 'on', 'off']) {
|
||||
expect(prepareLlmAddonConfigForWrite({ provider: 'local', vision }, undefined).vision).toBe(vision);
|
||||
}
|
||||
});
|
||||
|
||||
it('stores anything else as auto, so the resolver never meets a value it cannot read', () => {
|
||||
expect(prepareLlmAddonConfigForWrite({ vision: 'maybe' }, undefined).vision).toBe('auto');
|
||||
expect(prepareLlmAddonConfigForWrite({ vision: true }, undefined).vision).toBe('auto');
|
||||
});
|
||||
|
||||
it('adds no vision key to a config that sent none', () => {
|
||||
expect(prepareLlmAddonConfigForWrite({ provider: 'openai', model: 'm' }, undefined)).not.toHaveProperty('vision');
|
||||
});
|
||||
});
|
||||
@@ -68,3 +68,67 @@ describe('LlmLocalService.pull', () => {
|
||||
expect(JSON.parse(init.body)).toEqual({ model: 'nuextract', stream: true });
|
||||
});
|
||||
});
|
||||
|
||||
describe('LlmLocalService.modelCapabilities', () => {
|
||||
const showOk = (body: unknown, headers: Record<string, string> = {}) => ({
|
||||
ok: true,
|
||||
headers: { get: (name: string) => headers[name] ?? null },
|
||||
json: async () => body,
|
||||
});
|
||||
|
||||
it('asks /api/show for the model and answers its capabilities', async () => {
|
||||
const fetchFn = mockFetch(async () => showOk({ capabilities: ['completion', 'vision'] }));
|
||||
await expect(svc().modelCapabilities('http://ollama:11434/v1', 'qwen3.5:4b')).resolves.toEqual(['completion', 'vision']);
|
||||
expect(fetchFn.mock.calls[0][0]).toBe('http://ollama:11434/api/show');
|
||||
expect(JSON.parse(fetchFn.mock.calls[0][1].body)).toEqual({ model: 'qwen3.5:4b' });
|
||||
});
|
||||
|
||||
it('asks the server once per server and model, not once per call', async () => {
|
||||
const fetchFn = mockFetch(async () => showOk({ capabilities: ['completion'] }));
|
||||
const s = svc();
|
||||
await s.modelCapabilities('http://ollama:11434', 'qwen3:8b');
|
||||
await s.modelCapabilities('http://ollama:11434', 'qwen3:8b');
|
||||
expect(fetchFn).toHaveBeenCalledTimes(1);
|
||||
await s.modelCapabilities('http://ollama:11434', 'qwen3.5:4b');
|
||||
expect(fetchFn).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it('answers null for a URL it cannot use, without throwing and without a request', async () => {
|
||||
await expect(svc().modelCapabilities('not a url', 'm')).resolves.toBeNull();
|
||||
await expect(svc().modelCapabilities('ftp://x', 'm')).resolves.toBeNull();
|
||||
expect(safeFetchLlmMock).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('answers null for an unreachable server, a model it lacks, or a body that is not Ollama\'s', async () => {
|
||||
mockFetch(async () => { throw new Error('ECONNREFUSED'); });
|
||||
await expect(svc().modelCapabilities('http://a:1', 'm')).resolves.toBeNull();
|
||||
mockFetch(async () => ({ ok: false, status: 404, body: null }));
|
||||
await expect(svc().modelCapabilities('http://b:1', 'm')).resolves.toBeNull();
|
||||
mockFetch(async () => showOk({ capabilities: 'vision' }));
|
||||
await expect(svc().modelCapabilities('http://c:1', 'm')).resolves.toBeNull();
|
||||
});
|
||||
|
||||
it('does not read a body that declares itself larger than the cap', async () => {
|
||||
const json = vi.fn(async () => ({ capabilities: ['vision'] }));
|
||||
mockFetch(async () => ({ ...showOk({}), headers: { get: () => String(2 * 1024 * 1024) }, json }));
|
||||
await expect(svc().modelCapabilities('http://d:1', 'm')).resolves.toBeNull();
|
||||
expect(json).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('asks again a minute after a miss, and keeps an answer for ten', async () => {
|
||||
vi.useFakeTimers();
|
||||
try {
|
||||
const s = svc();
|
||||
mockFetch(async () => { throw new Error('down'); });
|
||||
await s.modelCapabilities('http://e:1', 'm');
|
||||
vi.advanceTimersByTime(61_000);
|
||||
mockFetch(async () => showOk({ capabilities: ['vision'] }));
|
||||
await expect(s.modelCapabilities('http://e:1', 'm')).resolves.toEqual(['vision']);
|
||||
vi.advanceTimersByTime(9 * 60_000);
|
||||
mockFetch(async () => showOk({ capabilities: [] }));
|
||||
await expect(s.modelCapabilities('http://e:1', 'm')).resolves.toEqual(['vision']);
|
||||
} finally {
|
||||
vi.useRealTimers();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
@@ -10,30 +10,49 @@ const { createLlmClient, extract } = vi.hoisted(() => {
|
||||
});
|
||||
vi.mock('../../../../src/nest/llm-parse/llm-client.factory', () => ({ createLlmClient }));
|
||||
|
||||
const { extractEnforced } = vi.hoisted(() => ({ extractEnforced: vi.fn() }));
|
||||
|
||||
const { renderPdfPages } = vi.hoisted(() => ({ renderPdfPages: vi.fn() }));
|
||||
vi.mock('../../../../src/nest/llm-parse/image-input', async (orig) => {
|
||||
const actual = await orig() as Record<string, unknown>;
|
||||
return { ...actual, renderPdfPages };
|
||||
});
|
||||
vi.mock('../../../../src/nest/llm-parse/router/ollama-format.client', async (orig) => {
|
||||
const actual = await orig() as Record<string, unknown>;
|
||||
return { ...actual, extractEnforced };
|
||||
});
|
||||
|
||||
const { extractText } = vi.hoisted(() => ({ extractText: vi.fn(async () => 'Flight AB123') }));
|
||||
vi.mock('../../../../src/nest/llm-parse/text-extract', async (orig) => {
|
||||
const actual = await orig() as Record<string, unknown>;
|
||||
return { ...actual, extractText };
|
||||
});
|
||||
|
||||
const { routeExtraction, detectFlightNumbers } = vi.hoisted(() => ({
|
||||
const { routeExtraction, routeImageExtraction, detectFlightNumbers } = vi.hoisted(() => ({
|
||||
routeExtraction: vi.fn(),
|
||||
routeImageExtraction: vi.fn(),
|
||||
detectFlightNumbers: vi.fn(() => [] as string[]),
|
||||
}));
|
||||
// The router's pure helpers stay real: the currency fallback reads the document's
|
||||
// total through extractTotalPrice.
|
||||
vi.mock('../../../../src/nest/llm-parse/router/extraction-router', async (orig) => {
|
||||
const actual = await orig() as Record<string, unknown>;
|
||||
return { ...actual, routeExtraction, detectFlightNumbers };
|
||||
return { ...actual, routeExtraction, routeImageExtraction, detectFlightNumbers };
|
||||
});
|
||||
|
||||
import { LlmParseService } from '../../../../src/nest/llm-parse/llm-parse.service';
|
||||
import type { LlmConfigResolver } from '../../../../src/nest/llm-parse/llm-config.resolver';
|
||||
import type { RuntimeEnvService } from '../../../../src/nest/app-config/runtime-env.service';
|
||||
import type { LlmLocalService } from '../../../../src/nest/llm-parse/llm-local.service';
|
||||
|
||||
const cfg = (over: Record<string, unknown> = {}) => ({ provider: 'openai', model: 'm', multimodal: false, ...over });
|
||||
const cfg = (over: Record<string, unknown> = {}) => ({ provider: 'openai', model: 'm', vision: 'off', ...over });
|
||||
const llmConfigStub = { resolve: resolveLlmConfig } as unknown as LlmConfigResolver;
|
||||
const svc = () => new LlmParseService(llmConfigStub, { isManaged: () => false } as unknown as RuntimeEnvService);
|
||||
const modelCapabilities = vi.fn();
|
||||
const svc = () => new LlmParseService(
|
||||
llmConfigStub,
|
||||
{ isManaged: () => false } as unknown as RuntimeEnvService,
|
||||
{ modelCapabilities } as unknown as LlmLocalService,
|
||||
);
|
||||
const file = (name: string, body = 'Flight AB123') => ({ buffer: Buffer.from(body), originalName: name });
|
||||
|
||||
beforeEach(() => {
|
||||
@@ -43,6 +62,9 @@ beforeEach(() => {
|
||||
extractText.mockResolvedValue('Flight AB123');
|
||||
detectFlightNumbers.mockReturnValue([]);
|
||||
routeExtraction.mockResolvedValue({ kiItems: [{ '@type': 'LodgingReservation' }], warnings: [] });
|
||||
routeImageExtraction.mockResolvedValue({ kiItems: [{ '@type': 'TrainReservation' }], warnings: [] });
|
||||
modelCapabilities.mockResolvedValue(null);
|
||||
renderPdfPages.mockResolvedValue([]);
|
||||
});
|
||||
|
||||
describe('LlmParseService', () => {
|
||||
@@ -284,3 +306,165 @@ describe('LlmParseService: cleaning up an AI answer (#2477)', () => {
|
||||
expect(res.kiItems).toEqual([plain]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('LlmParseService: a photo', () => {
|
||||
it('readsImages follows on and off whatever the provider, and never asks a server for them', async () => {
|
||||
resolveLlmConfig.mockReturnValue(cfg({ provider: 'local', vision: 'on' }));
|
||||
await expect(svc().readsImages(1)).resolves.toBe(true);
|
||||
resolveLlmConfig.mockReturnValue(cfg({ provider: 'local', vision: 'off' }));
|
||||
await expect(svc().readsImages(1)).resolves.toBe(false);
|
||||
resolveLlmConfig.mockReturnValue(cfg({ provider: 'openai', vision: 'on' }));
|
||||
await expect(svc().readsImages(1)).resolves.toBe(true);
|
||||
expect(modelCapabilities).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('readsImages on auto asks a local server, and answers no for a cloud provider', async () => {
|
||||
resolveLlmConfig.mockReturnValue(cfg({ provider: 'local', vision: 'auto', baseUrl: 'http://ollama:11434/v1', model: 'qwen3.5:4b' }));
|
||||
modelCapabilities.mockResolvedValue(['completion', 'vision']);
|
||||
await expect(svc().readsImages(1)).resolves.toBe(true);
|
||||
expect(modelCapabilities).toHaveBeenCalledWith('http://ollama:11434/v1', 'qwen3.5:4b');
|
||||
modelCapabilities.mockResolvedValue(['completion']);
|
||||
await expect(svc().readsImages(1)).resolves.toBe(false);
|
||||
modelCapabilities.mockResolvedValue(null);
|
||||
await expect(svc().readsImages(1)).resolves.toBe(false);
|
||||
|
||||
modelCapabilities.mockClear();
|
||||
for (const provider of ['openai', 'anthropic']) {
|
||||
resolveLlmConfig.mockReturnValue(cfg({ provider, vision: 'auto' }));
|
||||
await expect(svc().readsImages(1)).resolves.toBe(false);
|
||||
}
|
||||
expect(modelCapabilities).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('readsImages is false when AI parsing is not configured', async () => {
|
||||
resolveLlmConfig.mockReturnValue(null);
|
||||
await expect(svc().readsImages(1)).resolves.toBe(false);
|
||||
});
|
||||
|
||||
it('refuses a photo the model cannot read, without calling it', async () => {
|
||||
const res = await svc().parse(file('ticket.jpg', 'jpeg'), 1);
|
||||
expect(res.kiItems).toEqual([]);
|
||||
expect(res.warnings[0]).toMatch(/does not read images/);
|
||||
expect(extract).not.toHaveBeenCalled();
|
||||
expect(extractText).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('sends a photo as an image to a cloud provider, with no text', async () => {
|
||||
for (const provider of ['openai', 'anthropic']) {
|
||||
extract.mockClear();
|
||||
resolveLlmConfig.mockReturnValue(cfg({ provider, vision: 'on' }));
|
||||
await svc().parse(file('ticket.PNG', 'not really a png'), 1);
|
||||
const input = extract.mock.calls[0][0];
|
||||
// Bytes that do not decode go as they came rather than being refused.
|
||||
expect(input.file).toEqual({ mimeType: 'image/png', data: Buffer.from('not really a png') });
|
||||
expect(input.text).toBeUndefined();
|
||||
}
|
||||
expect(extractText).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('sends a photo through the local router with the image attached', async () => {
|
||||
resolveLlmConfig.mockReturnValue(cfg({ provider: 'local', vision: 'on', baseUrl: 'http://ollama:11434/v1' }));
|
||||
const res = await svc().parse(file('ticket.jpeg', 'jpeg bytes'), 1);
|
||||
expect(res.kiItems).toEqual([{ '@type': 'TrainReservation' }]);
|
||||
expect(routeImageExtraction).toHaveBeenCalledWith([Buffer.from('jpeg bytes')], expect.objectContaining({ baseUrl: 'http://ollama:11434/v1' }));
|
||||
expect(routeExtraction).not.toHaveBeenCalled();
|
||||
expect(extract).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('leaves a PDF on its text path when the model reads images', async () => {
|
||||
resolveLlmConfig.mockReturnValue(cfg({ vision: 'on' }));
|
||||
await svc().parse(file('a.pdf', '%PDF'), 1);
|
||||
expect(extract.mock.calls[0][0].file).toBeUndefined();
|
||||
expect(extractText).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('LlmParseService.readReceipt', () => {
|
||||
const RECEIPT = { merchant: 'Bäckerei', date: '2026-09-20', total: 7.5, currency: 'EUR', items: [{ name: 'Brezel', price: 2.5 }] };
|
||||
|
||||
it('says why when AI parsing is not set up, the file is not a photo, or the model reads no images', async () => {
|
||||
resolveLlmConfig.mockReturnValue(null);
|
||||
expect((await svc().readReceipt(file('r.jpg'), 1)).warnings[0]).toMatch(/not configured/);
|
||||
resolveLlmConfig.mockReturnValue(cfg({ vision: 'on' }));
|
||||
expect(await svc().readReceipt(file('r.pdf'), 1)).toEqual({ receipt: null, warnings: ['r.pdf: not a photo'] });
|
||||
resolveLlmConfig.mockReturnValue(cfg({ vision: 'off' }));
|
||||
expect((await svc().readReceipt(file('r.jpg'), 1)).warnings[0]).toMatch(/does not read images/);
|
||||
expect(extract).not.toHaveBeenCalled();
|
||||
expect(extractEnforced).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('reads through Ollama\'s native chat on a local provider, with the photo and the receipt schema', async () => {
|
||||
resolveLlmConfig.mockReturnValue(cfg({ provider: 'local', vision: 'on', baseUrl: 'http://ollama:11434/v1', model: 'qwen3.5:4b' }));
|
||||
extractEnforced.mockResolvedValue(RECEIPT);
|
||||
await expect(svc().readReceipt(file('r.jpg', 'jpeg'), 1)).resolves.toEqual({ receipt: RECEIPT, warnings: [] });
|
||||
const call = extractEnforced.mock.calls[0][0];
|
||||
expect(call).toMatchObject({ baseUrl: 'http://ollama:11434/v1', model: 'qwen3.5:4b', images: [Buffer.from('jpeg').toString('base64')] });
|
||||
expect(call.schema.required).toContain('total');
|
||||
expect(extract).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('asks a cloud client for a receipts list with the photo attached, and keeps the first', async () => {
|
||||
resolveLlmConfig.mockReturnValue(cfg({ provider: 'anthropic', vision: 'on' }));
|
||||
extract.mockResolvedValue([RECEIPT, { total: 1 }]);
|
||||
await expect(svc().readReceipt(file('r.png', 'png'), 1)).resolves.toEqual({ receipt: RECEIPT, warnings: [] });
|
||||
const input = extract.mock.calls[0][0];
|
||||
expect(input.rootKey).toBe('receipts');
|
||||
expect(input.file).toEqual({ mimeType: 'image/png', data: Buffer.from('png') });
|
||||
expect(input.text).toBeUndefined();
|
||||
});
|
||||
|
||||
it('answers a warning, not a throw, when the model fails or reads nothing', async () => {
|
||||
resolveLlmConfig.mockReturnValue(cfg({ vision: 'on' }));
|
||||
extract.mockRejectedValue(new Error('429'));
|
||||
const failed = await svc().readReceipt(file('r.jpg'), 1);
|
||||
expect(failed.receipt).toBeNull();
|
||||
expect(failed.warnings[0]).toMatch(/AI parsing failed — 429/);
|
||||
extract.mockResolvedValue([]);
|
||||
expect(await svc().readReceipt(file('r.jpg'), 1)).toEqual({ receipt: null, warnings: ['r.jpg: no receipt could be read'] });
|
||||
});
|
||||
});
|
||||
|
||||
describe('LlmParseService: a scanned PDF', () => {
|
||||
const page = (n: string) => ({ mimeType: 'image/jpeg', data: Buffer.from(n) });
|
||||
|
||||
beforeEach(() => extractText.mockResolvedValue(' '));
|
||||
|
||||
it('sends the pages as images when the text layer is empty and the model reads images', async () => {
|
||||
resolveLlmConfig.mockReturnValue(cfg({ vision: 'on' }));
|
||||
renderPdfPages.mockResolvedValue([page('p1'), page('p2')]);
|
||||
await svc().parse(file('scan.pdf', '%PDF'), 1);
|
||||
const input = extract.mock.calls[0][0];
|
||||
expect(input.file).toEqual(page('p1'));
|
||||
expect(input.pageImages).toEqual([page('p2')]);
|
||||
expect(input.text).toBeUndefined();
|
||||
});
|
||||
|
||||
it('hands the local router every page', async () => {
|
||||
resolveLlmConfig.mockReturnValue(cfg({ provider: 'local', vision: 'on' }));
|
||||
renderPdfPages.mockResolvedValue([page('p1'), page('p2')]);
|
||||
await svc().parse(file('scan.pdf', '%PDF'), 1);
|
||||
expect(routeImageExtraction).toHaveBeenCalledWith([Buffer.from('p1'), Buffer.from('p2')], expect.anything());
|
||||
expect(routeExtraction).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('keeps the warning, and draws nothing, when the model reads no images', async () => {
|
||||
resolveLlmConfig.mockReturnValue(cfg({ vision: 'off' }));
|
||||
const res = await svc().parse(file('scan.pdf', '%PDF'), 1);
|
||||
expect(res.warnings[0]).toMatch(/no readable text found \(a scanned PDF needs a model that reads images\)/);
|
||||
expect(renderPdfPages).not.toHaveBeenCalled();
|
||||
expect(extract).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('keeps the warning when no page could be drawn', async () => {
|
||||
resolveLlmConfig.mockReturnValue(cfg({ vision: 'on' }));
|
||||
const res = await svc().parse(file('scan.pdf', '%PDF'), 1);
|
||||
expect(res.warnings[0]).toMatch(/no readable text found/);
|
||||
expect(extract).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('does not draw an empty text file', async () => {
|
||||
resolveLlmConfig.mockReturnValue(cfg({ vision: 'on' }));
|
||||
await svc().parse(file('empty.txt', ''), 1);
|
||||
expect(renderPdfPages).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -52,6 +52,15 @@ describe('extractEnforced', () => {
|
||||
expect((init as RequestInit).headers).not.toHaveProperty('authorization');
|
||||
});
|
||||
|
||||
it('attaches images to the user turn only when given', async () => {
|
||||
const fetchFn = mockFetch(() => jsonResponse({ message: { content: '{}' } }));
|
||||
await extractEnforced({ ...INPUT, images: ['aW1n'] });
|
||||
await extractEnforced(INPUT);
|
||||
const userTurn = (i: number) => JSON.parse((fetchFn.mock.calls[i][1] as RequestInit).body as string).messages[1];
|
||||
expect(userTurn(0).images).toEqual(['aW1n']);
|
||||
expect(userTurn(1)).not.toHaveProperty('images');
|
||||
});
|
||||
|
||||
it('sends a bearer header only when an apiKey is given', async () => {
|
||||
const fetchFn = mockFetch(() => jsonResponse({ message: { content: '{}' } }));
|
||||
await extractEnforced({ ...INPUT, apiKey: 'sk-123', numPredict: 900, numCtx: 16000 });
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { buildReceiptPrompt, RECEIPT_LIST_JSON_SCHEMA, RECEIPT_ROOT_KEY, toReceiptRead } from '../../../../src/nest/llm-parse/receipt-read';
|
||||
|
||||
describe('toReceiptRead', () => {
|
||||
it('keeps a clean answer as it came', () => {
|
||||
expect(toReceiptRead({
|
||||
merchant: 'Café de Flore', date: '2026-09-20', total: 23.4, currency: 'EUR',
|
||||
items: [{ name: '2 x Espresso', price: 8 }, { name: 'Croque', price: 15.4 }],
|
||||
})).toEqual({
|
||||
merchant: 'Café de Flore', date: '2026-09-20', total: 23.4, currency: 'EUR',
|
||||
items: [{ name: '2 x Espresso', price: 8 }, { name: 'Croque', price: 15.4 }],
|
||||
});
|
||||
});
|
||||
|
||||
it('reads amounts written as text, in either decimal convention', () => {
|
||||
expect(toReceiptRead({ total: '12,50 €' })?.total).toBe(12.5);
|
||||
expect(toReceiptRead({ total: '1.234,50' })?.total).toBe(1234.5);
|
||||
expect(toReceiptRead({ total: '1,234.50' })?.total).toBe(1234.5);
|
||||
expect(toReceiptRead({ total: 7, items: [{ name: 'Tea', price: '3,20' }] })?.items).toEqual([{ name: 'Tea', price: 3.2 }]);
|
||||
});
|
||||
|
||||
it('turns a currency symbol or name into its code, and drops one nobody can convert', () => {
|
||||
expect(toReceiptRead({ total: 5, currency: '€' })?.currency).toBe('EUR');
|
||||
expect(toReceiptRead({ total: 5, currency: 'euros' })?.currency).toBe('EUR');
|
||||
expect(toReceiptRead({ total: 5, currency: 'Lek' })?.currency).toBeNull();
|
||||
});
|
||||
|
||||
it('keeps only a real calendar date', () => {
|
||||
expect(toReceiptRead({ total: 5, date: '2026-02-28' })?.date).toBe('2026-02-28');
|
||||
for (const date of ['2026-02-30', '28/02/2026', '2026-2-8', '']) expect(toReceiptRead({ total: 5, date })?.date).toBeNull();
|
||||
});
|
||||
|
||||
it('leaves out a total that is not a positive amount, and lines without a name or price', () => {
|
||||
const read = toReceiptRead({ merchant: 'Shop', total: 0, items: [{ name: '', price: 2 }, { name: 'Bread' }, 'x', { name: 'Milk', price: 1.1 }] });
|
||||
expect(read).toEqual({ merchant: 'Shop', date: null, total: null, currency: null, items: [{ name: 'Milk', price: 1.1 }] });
|
||||
});
|
||||
|
||||
it('is null when nothing usable came back', () => {
|
||||
for (const raw of [null, undefined, 'text', [], {}, { total: 'n/a', merchant: ' ' }]) expect(toReceiptRead(raw)).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('the receipt prompt and schema', () => {
|
||||
it('pins today so an ambiguous date is read towards it', () => {
|
||||
expect(buildReceiptPrompt(new Date('2026-09-24T10:00:00Z'))).toContain('Today is 2026-09-24.');
|
||||
});
|
||||
|
||||
it('wraps one receipt under the key the cloud clients read', () => {
|
||||
expect(RECEIPT_LIST_JSON_SCHEMA.required).toEqual([RECEIPT_ROOT_KEY]);
|
||||
expect(RECEIPT_LIST_JSON_SCHEMA.properties[RECEIPT_ROOT_KEY].items.required).toEqual(['merchant', 'date', 'total', 'currency', 'items']);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,55 @@
|
||||
import { describe, it, expect, vi } from 'vitest';
|
||||
import { HttpException } from '@nestjs/common';
|
||||
import { ReceiptScanController } from '../../../src/nest/receipt-scan/receipt-scan.controller';
|
||||
import type { ImportJobsService } from '../../../src/nest/booking-import/import-jobs.service';
|
||||
import type { LlmParseService } from '../../../src/nest/llm-parse/llm-parse.service';
|
||||
import type { DatabaseService } from '../../../src/nest/database/database.service';
|
||||
import type { PermissionsService } from '../../../src/nest/permissions/permissions.service';
|
||||
import type { AddonsService } from '../../../src/nest/addons/addons.service';
|
||||
import type { User } from '../../../src/types';
|
||||
|
||||
const user = { id: 3, role: 'user' } as User;
|
||||
const photo = (name = 'r.jpg') => ({ originalname: name, buffer: Buffer.from('x') } as Express.Multer.File);
|
||||
|
||||
function make(over: { readsImages?: boolean; trip?: unknown; addon?: boolean; allowed?: boolean } = {}) {
|
||||
const startReceipt = vi.fn(() => 'job-1');
|
||||
const checkPermission = vi.fn(() => over.allowed ?? true);
|
||||
const c = new ReceiptScanController(
|
||||
{ startReceipt } as unknown as ImportJobsService,
|
||||
{ readsImages: vi.fn(async () => over.readsImages ?? true) } as unknown as LlmParseService,
|
||||
{ canAccessTrip: vi.fn(() => ('trip' in over ? over.trip : { user_id: 5 })) } as unknown as DatabaseService,
|
||||
{ checkPermission } as unknown as PermissionsService,
|
||||
{ isAddonEnabled: vi.fn(() => over.addon ?? true) } as unknown as AddonsService,
|
||||
);
|
||||
return { c, startReceipt, checkPermission };
|
||||
}
|
||||
|
||||
async function failure(fn: () => Promise<unknown>): Promise<[number, unknown]> {
|
||||
try { await fn(); } catch (e) { expect(e).toBeInstanceOf(HttpException); return [(e as HttpException).getStatus(), (e as HttpException).getResponse()]; }
|
||||
throw new Error('expected throw');
|
||||
}
|
||||
|
||||
describe('ReceiptScanController', () => {
|
||||
it('queues a photo and answers the job id', async () => {
|
||||
const { c, startReceipt, checkPermission } = make();
|
||||
await expect(c.scan(user, '9', photo())).resolves.toEqual({ jobId: 'job-1' });
|
||||
expect(startReceipt).toHaveBeenCalledWith('9', expect.objectContaining({ originalname: 'r.jpg' }), 3);
|
||||
expect(checkPermission).toHaveBeenCalledWith('budget_edit', 'user', 5, 3, true);
|
||||
});
|
||||
|
||||
it('answers what the guards would: 404 for a trip out of reach or Costs off, 403 without budget_edit', async () => {
|
||||
expect(await failure(() => make({ trip: undefined }).c.scan(user, '9', photo()))).toEqual([404, { error: 'Trip not found' }]);
|
||||
expect(await failure(() => make({ addon: false }).c.scan(user, '9', photo()))).toEqual([404, { error: 'Costs addon is not enabled' }]);
|
||||
const { c, startReceipt } = make({ allowed: false });
|
||||
expect(await failure(() => c.scan(user, '9', photo()))).toEqual([403, { error: 'No permission' }]);
|
||||
expect(startReceipt).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('refuses with 400 a missing file, a file that is not a photo, or a model that reads no images', async () => {
|
||||
expect((await failure(() => make().c.scan(user, '9', undefined)))[0]).toBe(400);
|
||||
expect((await failure(() => make().c.scan(user, '9', photo('r.pdf'))))[0]).toBe(400);
|
||||
const { c, startReceipt } = make({ readsImages: false });
|
||||
expect(await failure(() => c.scan(user, '9', photo()))).toEqual([400, { error: 'The configured AI model does not read photos' }]);
|
||||
expect(startReceipt).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user