Files
indexipro/server/test/e2e.js
T
juli 5ad4fac46a Export packages and condition/works when adding items
- Export page: audience-specific zip with CSV, PDF catalogue (cover,
  contents, photos, details), optional full-size photos and JSON
- All-of + any-of selection (e.g. notable OR before 2000), PDF subset
  (all / notable / min value / top N), per-package privacy switches
- Presets: book dealer, computer museum, record dealer, auction house,
  insurance, charity, recycler, keepsakes; save your own
- Optional condition and works/untested dropdowns on web and Android
  capture; the AI keeps the team's answer unless photos contradict it
- App 1.4.0
2026-11-12 19:51:52 +01:00

215 lines
19 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// End-to-end smoke test: node test/e2e.js (starts its own server on a temp data dir)
import { spawn } from 'node:child_process';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import sharp from 'sharp';
import assert from 'node:assert/strict';
const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'ipx-'));
const port = 18000 + Math.floor(Math.random() * 1000);
const base = `http://localhost:${port}`;
const srv = spawn('node', ['src/index.js'], { env: { ...process.env, DATA_DIR: dataDir, PORT: port, ADMIN_PASSWORD: 'adminpw1' }, stdio: ['ignore', 'pipe', 'inherit'] });
await new Promise((r) => srv.stdout.on('data', (d) => d.toString().includes('listening') && r()));
let ok = 0;
const step = (name) => { ok++; console.log('✓', name); };
const cookieOf = (r) => r.headers.get('set-cookie').split(';')[0];
try {
let r = await fetch(`${base}/api/login`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ username: 'admin', password: 'wrong' }) });
assert.equal(r.status, 401); step('wrong password rejected');
r = await fetch(`${base}/api/login`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ username: 'admin', password: 'adminpw1' }) });
assert.equal(r.status, 200); const admin = cookieOf(r); step('admin login (username + password)');
const A = (p, o = {}) => fetch(base + p, { ...o, headers: { cookie: admin, 'content-type': 'application/json', ...(o.headers || {}) } });
const info = await (await fetch(`${base}/api/info`)).json();
if (info.app.available) {
assert.match(info.app.url, /\/download\/IndexiPro-[\d.]+\.apk$/);
const apk = await fetch(info.app.url.replace(/^https?:\/\/[^/]+/, base));
assert.equal(apk.status, 200);
const bytes = Buffer.from(await apk.arrayBuffer());
if (info.app.sha256) assert.equal((await import('node:crypto')).createHash('sha256').update(bytes).digest('hex'), info.app.sha256);
assert.equal((await fetch(`${base}/download/IndexiPro-0.0.1.apk`)).status, 404);
step('APK offered under its versioned name, checksum matches');
}
const join = await (await A('/api/join')).json();
assert.match(join.url, /\/join\/[A-Z0-9]{8}$/); assert.match(join.svg, /<svg/); step('join QR');
r = await fetch(`${base}/api/pair`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ code: join.code, name: 'Sam', kind: 'android' }) });
assert.equal(r.status, 400); step('joining requires a password');
r = await fetch(`${base}/api/pair`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ code: join.code, name: 'Sam', password: 'secret1', kind: 'android' }) });
const pair = await r.json(); assert.ok(pair.token); assert.equal(pair.username, 'sam'); assert.ok(pair.created); step('phone join creates editor account "sam"');
r = await fetch(`${base}/api/login`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ username: 'sam', password: 'secret1' }) });
const samWeb = cookieOf(r); assert.equal(r.status, 200); step('helper can log in on the web');
const S = (p, o = {}) => fetch(base + p, { ...o, headers: { cookie: samWeb, 'content-type': 'application/json', ...(o.headers || {}) } });
assert.equal((await S('/api/users')).status, 403); assert.equal((await S('/api/shares')).status, 403); step('editor cannot manage team or share links');
r = await fetch(`${base}/api/pair`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ code: join.code, username: 'sam', password: 'secret1', kind: 'android' }) });
assert.ok((await r.json()).token); step('existing account can sign in a second phone with the join code');
const personal = await (await S('/api/me/pair')).json();
const pcode = personal.url.split('/').pop();
assert.equal((await (await fetch(`${base}/api/invite/${pcode}`)).json()).person, 'Sam');
r = await fetch(`${base}/api/pair`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ code: pcode, kind: 'android' }) });
assert.ok((await r.json()).token);
r = await fetch(`${base}/api/pair`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ code: pcode, kind: 'android' }) });
assert.equal(r.status, 404); step('personal "pair my phone" code works once');
const P = (p, o = {}) => fetch(base + p, { ...o, headers: { authorization: `Bearer ${pair.token}`, ...(o.headers || {}) } });
const img = await sharp({ create: { width: 1600, height: 1200, channels: 3, background: '#a0522d' } }).jpeg().toBuffer();
const fd = new FormData();
fd.append('photos', new Blob([img], { type: 'image/jpeg' }), 'a.jpg');
fd.append('photos', new Blob([img], { type: 'image/jpeg' }), 'b.jpg');
fd.append('note', 'old book from the attic, looks like a first edition');
fd.append('location', 'Attic box 3'); fd.append('client_id', 'abc-1'); fd.append('condition', 'fair'); fd.append('working', 'untested');
r = await P('/api/items', { method: 'POST', body: fd });
const item = await r.json(); assert.equal(r.status, 201); assert.equal(item.photos.length, 2);
assert.equal(item.condition, 'fair'); assert.equal(item.working, 'untested'); step('upload item with photos, condition and works-status');
r = await P('/api/items', { method: 'POST', body: fd }); assert.equal((await r.json()).id, item.id); step('upload retry is idempotent');
r = await P(`/photos/${item.photos[0].id}/thumb`); assert.equal(r.status, 200); step('photo thumb');
const keyRes = await (await S('/api/aikeys', { method: 'POST', body: JSON.stringify({ label: "Sam's Claude" }) })).json();
const mcpUrl = keyRes.url;
assert.ok(mcpUrl.includes(keyRes.key)); step('editor creates a personal AI connection');
assert.equal((await (await S('/api/aikeys')).json()).connected, false);
let rpcId = 0;
const mcp = async (method, params) => {
const res = await fetch(mcpUrl, { method: 'POST', headers: { 'content-type': 'application/json', accept: 'application/json, text/event-stream' }, body: JSON.stringify({ jsonrpc: '2.0', id: ++rpcId, method, params }) });
const j = await res.json(); if (j.error) throw new Error(JSON.stringify(j.error)); return j.result;
};
for (const probe of ['/.well-known/oauth-protected-resource', '/.well-known/oauth-authorization-server', '/.well-known/openid-configuration']) {
for (const url of [`${base}${probe}`, `${mcpUrl}${probe}`]) {
const pr = await fetch(url);
assert.equal(pr.status, 404, url); assert.match(pr.headers.get('content-type'), /json/, url);
}
}
step('OAuth discovery probes get a clean JSON 404 (no HTML)');
const init = await mcp('initialize', { protocolVersion: '2025-06-18', capabilities: {}, clientInfo: { name: 'test', version: '1' } });
assert.match(init.instructions, /cataloguer/); step('MCP initialize');
const res = await mcp('resources/list', {});
assert.ok(res.resources.some((r) => r.uri === 'indexipro://instructions'));
assert.equal((await mcp('resources/templates/list', {})).resourceTemplates.length, 0); step('MCP resources/list and templates/list answer normally');
const tools = (await mcp('tools/list', {})).tools.map((t) => t.name);
for (const t of ['next_items_to_identify', 'update_item', 'field_conventions', 'add_comparables', 'ask_humans', 'save_listing', 'research_links']) assert.ok(tools.includes(t), t);
step(`MCP tools/list (${tools.length} tools)`);
const call = (name, args) => mcp('tools/call', { name, arguments: args });
const next = await call('next_items_to_identify', { limit: 2 });
assert.ok(next.content.some((c) => c.type === 'image')); step('MCP next items includes images');
let u = await call('update_item', { id: item.id, title: 'J.R.R. Tolkien – The Hobbit (1937)', category: 'Books', tier: 'notable', value_low: 2000, value_high: 6000, attributes: { author: 'J.R.R. Tolkien', isbn: 'n/a', publisher: 'George Allen & Unwin' } });
assert.ok(!u.isError, JSON.stringify(u));
u = await call('update_item', { id: item.id, attributes: { isbn: null, edition: 'First edition, first impression' } });
const full = await (await A(`/api/items/${item.id}`)).json();
assert.equal(full.status, 'identified'); assert.equal(full.attributes.author, 'J.R.R. Tolkien'); assert.equal(full.attributes.isbn, undefined); assert.ok(full.attributes.edition);
step('MCP update_item with custom attributes (merge + delete)');
const conv = await call('field_conventions', {});
assert.match(conv.content[0].text, /publisher/); step('MCP field_conventions');
await call('add_comparables', { item_id: item.id, comparables: [{ source: 'Test', kind: 'sold', title: 'Hobbit 1937', price: 4000, currency: 'EUR' }] });
await call('ask_humans', { item_id: item.id, question: 'Please photograph the title page' });
const links = JSON.parse((await call('research_links', { query: 'Delft plate' })).content[0].text);
assert.ok(links.ebay_sold_by_country.de.includes('ebay.de') && links.marketplaces.marktplaats_nl && links.identify.google_images); step('research_links spans many sites and countries');
const rep = await call('submit_run_report', { report: 'Identified #1 as The Hobbit. Could not verify the printing.', processed: [item.id], uncertain: [item.id] });
assert.ok(!rep.isError);
const reports = await (await A('/api/reports')).json();
assert.equal(reports[0].uncertain[0], item.id); step('AI run report saved and visible to the team');
const todo = await (await P('/api/todo')).json(); assert.equal(todo.total, 1); step('AI question reaches the phone to-do list');
const ans = new FormData(); ans.append('photos', new Blob([img], { type: 'image/jpeg' }), 'c.jpg'); ans.append('note', 'here it is');
r = await P(`/api/items/${item.id}/photos`, { method: 'POST', body: ans });
const answered = await r.json();
assert.equal(answered.status, 'new'); assert.match(answered.human_notes, /Q: Please photograph the title page\nA \(Sam\): here it is \(added 1 photo\)/);
step('answering puts item back in the AI queue, question + answer kept in notes');
const setS = (body) => A('/api/settings', { method: 'PUT', body: JSON.stringify(body) });
const second = await call('ask_humans', { item_id: item.id, question: 'Photograph the spine' });
assert.ok(!second.isError); step('ladder: items estimated 1500+ get unlimited questions');
const onlyPhoto = new FormData(); onlyPhoto.append('photos', new Blob([img], { type: 'image/jpeg' }), 'd.jpg');
const op = await (await P(`/api/items/${item.id}/photos`, { method: 'POST', body: onlyPhoto })).json();
assert.equal(op.status, 'new'); assert.match(op.human_notes, /Q: Photograph the spine\nA \(Sam\): added 1 photo/); step('photo-only answer also records the question');
// a fresh, cheap item to walk up the ladder
const fd2 = new FormData(); fd2.append('photos', new Blob([img], { type: 'image/jpeg' }), 'x.jpg'); fd2.append('note', 'some cables');
const cheap = await (await P('/api/items', { method: 'POST', body: fd2 })).json();
let q = await call('ask_humans', { item_id: cheap.id, question: 'What is it?' });
assert.ok(!q.isError); step('ladder: no value estimate yet → 1 question');
await P(`/api/items/${cheap.id}/answer`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ text: 'cables' }) });
await call('update_item', { id: cheap.id, title: 'Box of USB cables', value_low: 2, value_high: 5 });
q = await call('ask_humans', { item_id: cheap.id, question: 'How many?' });
assert.ok(q.isError && /under|0–50|get no questions/.test(q.content[0].text), q.content[0].text); step('ladder: under 50 → no questions');
await call('update_item', { id: cheap.id, value_high: 300 });
for (let i = 0; i < 3; i++) assert.ok(!(await call('ask_humans', { item_id: cheap.id, question: `Q${i}` })).isError);
q = await call('ask_humans', { item_id: cheap.id, question: 'Q4' });
assert.ok(q.isError && /100–500 EUR get 4 question/.test(q.content[0].text), q.content[0].text); step('ladder: 100–500 → 4 questions, then stop');
await call('update_item', { id: cheap.id, ai_confidence: 'low' });
assert.ok(!(await call('ask_humans', { item_id: cheap.id, question: 'Unsure one' })).isError); step('ladder: AI unsure → up to 5');
await setS({ question_ladder: { bands: [{ from: 200, max: 3 }, { from: 0, max: 0 }, { from: 200, max: 9 }], unsure: null, unknown: 2, notable: '' } });
const stg = await (await A("/api/settings")).json();
assert.deepEqual(stg.question_ladder.bands, [{ from: 0, max: 0 }, { from: 200, max: 3 }]); assert.equal(stg.question_ladder.unsure, null);
step('custom ladder saved, sorted and de-duplicated; empty = unlimited');
await setS({ question_ladder: { bands: [{ from: 0, max: 0 }, { from: 50, max: 1 }, { from: 100, max: 4 }, { from: 500, max: 8 }, { from: 1500, max: null }], unsure: 5, unknown: 1, notable: 10 } });
const sk = await (await P(`/api/items/${cheap.id}/skip-question`, { method: 'POST' })).json();
assert.equal(sk.status, 'identified'); assert.equal(sk.question, null);
q = await call('ask_humans', { item_id: cheap.id, question: 'Again?' });
assert.ok(q.isError && /switched off questions for this item/.test(q.content[0].text)); step('skip: "don\'t ask again" sticks for that item');
await setS({ questions_mode: 'off' });
q = await call('ask_humans', { item_id: item.id, question: 'x' });
assert.ok(q.isError && /switched off in Settings/.test(q.content[0].text)); step('policy: questions can be switched off entirely');
await setS({ questions_mode: 'on' });
await call('ask_humans', { item_id: item.id, question: 'One more look please' });
const dis = await (await P('/api/questions/dismiss-all', { method: 'POST' })).json();
assert.ok(dis.dismissed >= 1); assert.equal((await (await P('/api/todo')).json()).total, 0); step('dismiss all open questions');
const instr = (await mcp('initialize', { protocolVersion: '2025-06-18', capabilities: {}, clientInfo: { name: 't', version: '1' } })).instructions;
assert.match(instr, /QUESTIONS TO THE TEAM/); step('AI instructions include the question policy');
const ak = await (await S('/api/aikeys')).json();
assert.ok(ak.connected && !ak.session_prompt.includes(keyRes.key)); step('connection shows as connected; session message holds no secret');
const act = await (await A(`/api/items/${item.id}`)).json();
assert.ok(act.activity.some((a) => a.actor === "AI (Sam's Claude)")); step('AI edits are attributed to the key');
const bearer = await fetch(`${base}/mcp`, { method: 'POST', headers: { authorization: `Bearer ${keyRes.key}`, 'content-type': 'application/json', accept: 'application/json, text/event-stream' }, body: JSON.stringify({ jsonrpc: '2.0', id: 99, method: 'tools/list' }) });
assert.equal(bearer.status, 200); step('MCP also accepts the key as a Bearer header');
const s = await (await A('/api/items?q=tolkien')).json(); assert.equal(s.total, 1);
const s2 = await (await A('/api/items?q=unwin')).json(); assert.equal(s2.total, 1); step('full-text search incl. custom fields');
// share links
const sh = await (await A('/api/shares', { method: 'POST', body: JSON.stringify({ label: 'Aunt Mia', show_values: false }) })).json();
r = await fetch(sh.url, { redirect: 'manual' }); assert.equal(r.status, 302); const viewer = cookieOf(r);
const V = (p, o = {}) => fetch(base + p, { ...o, headers: { cookie: viewer, 'content-type': 'application/json', ...(o.headers || {}) } });
const vi = await (await V(`/api/items/${item.id}`)).json();
assert.equal(vi.title, full.title); assert.equal(vi.value_high, null); assert.equal(vi.comparables.length, 0); step('share link: read-only view, values hidden');
r = await V(`/api/items/${item.id}`, { method: 'PATCH', body: JSON.stringify({ title: 'x' }) }); assert.equal(r.status, 403); step('share link cannot edit');
r = await V('/api/devices'); assert.equal(r.status, 403); step('share link cannot see admin pages');
r = await V(`/photos/${item.photos[0].id}/medium`); assert.equal(r.status, 200); step('share link sees photos');
const st = await (await V('/api/stats')).json(); assert.equal(st.totals.value_high, null); step('share-link stats redacted');
const shares = await (await A('/api/shares')).json();
await A(`/api/shares/${shares[0].id}`, { method: 'DELETE' });
r = await V(`/api/items/${item.id}`); assert.equal(r.status, 401); step('switched-off link stops working');
await S(`/api/aikeys/${keyRes.id}`, { method: 'DELETE' });
r = await fetch(mcpUrl, { method: 'POST', headers: { 'content-type': 'application/json', accept: 'application/json, text/event-stream' }, body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'tools/list' }) });
assert.equal(r.status, 401); step('revoked AI key stops working');
const users = (await (await A('/api/users')).json()).users;
const sam = users.find((u) => u.username === 'sam');
await A(`/api/users/${sam.id}`, { method: 'PATCH', body: JSON.stringify({ disabled: true }) });
assert.equal((await P('/api/me')).status, 401); assert.equal((await S('/api/me')).status, 401); step('disabling an account signs out its phones and browsers');
const adminRow = users.find((u) => u.username === 'admin');
r = await A(`/api/users/${adminRow.id}`, { method: 'PATCH', body: JSON.stringify({ role: 'editor' }) });
assert.equal(r.status, 400); step('cannot remove the last admin');
const presets = await (await A('/api/export/presets')).json();
const books = presets.builtin.find((p) => p.key === 'books');
const pv = await (await A('/api/export/preview', { method: 'POST', body: JSON.stringify(books.spec) })).json();
assert.ok(pv.items >= 1 && pv.pdf_items >= 1); step(`export preview: book dealer preset finds ${pv.items} book(s), ${pv.pdf_items} in PDF`);
const museumish = { name: 'Old or notable', all: { categories: ['Books', 'Furniture'] }, any: { notable: true, year_before: 1900 }, pdf: { include: 'none' } };
assert.equal((await (await A('/api/export/preview', { method: 'POST', body: JSON.stringify(museumish) })).json()).items, 1); step('export: all-of + any-of selection');
const job = await (await A('/api/export', { method: 'POST', body: JSON.stringify({ ...books.spec, name: 'Book dealer', files: { csv: true, json: true, photos: true } }) })).json();
const zr = await A(job.url);
const zbuf = Buffer.from(await zr.arrayBuffer());
assert.equal(zr.headers.get('content-type'), 'application/zip');
for (const f of ['README.txt', 'items.csv', 'items.json', 'catalogue.pdf', 'photos/0001-1-']) assert.ok(zbuf.includes(Buffer.from(f)), f);
step('export zip: README, CSV, JSON, PDF catalogue and photos');
const other = await (await A('/api/users', { method: 'POST', body: JSON.stringify({ display_name: 'Mia' }) })).json();
const lo = await fetch(`${base}/api/login`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ username: other.username, password: other.password }) });
assert.equal((await fetch(base + job.url, { headers: { cookie: cookieOf(lo) } })).status, 404); step('export download link only works for the person who built it');
await A('/api/export/presets', { method: 'POST', body: JSON.stringify({ name: 'My dealer', spec: museumish }) });
assert.ok((await (await A('/api/export/presets')).json()).custom.some((p) => p.name === 'My dealer')); step('custom export preset saved');
r = await A('/api/export.csv'); const csv = await r.text(); assert.match(csv, /publisher/); step('CSV export includes custom fields');
console.log(`\nAll ${ok} checks passed.`);
} catch (e) {
console.error('✗ FAILED:', e); process.exitCode = 1;
} finally {
srv.kill(); fs.rmSync(dataDir, { recursive: true, force: true });
}