Files
juli a18f992fc1 Bulk delete selected items (admins), with confirmation
Also fix the demo seed script for event-stream MCP answers.
2026-11-14 21:04:48 +01:00

1080 lines
78 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.
import { esc, api, toast, fmtMoney, fmtRange, ago, copy, shrinkImage } from './common.js';
const $app = document.getElementById('app');
let ME = null;
let META = null;
let INFO = null;
const thumb = (id) => (id ? `/photos/${id}/thumb` : '');
const label = (map, k) => (map && map[k] ? map[k].split(' — ')[0] : k);
const pill = (kind, map) => (kind ? `<span class="pill ${esc(kind)}">${esc(label(map, kind))}</span>` : '');
const cur = () => META?.currency || 'EUR';
const RO = () => ME?.role === 'viewer';
const showValues = () => !META?.hide_values;
const prettyKey = (k) => k.replace(/_/g, ' ').replace(/^./, (c) => c.toUpperCase());
function parseHash() {
const h = location.hash.replace(/^#/, '') || '/';
const [path, qs] = h.split('?');
return { path, params: new URLSearchParams(qs || '') };
}
const go = (h) => { location.hash = h; };
/* ---------------- boot ---------------- */
async function boot() {
INFO = await api('/info');
if (!INFO.me) return renderLogin();
ME = await api('/me');
META = await api('/meta');
document.getElementById('topbar').classList.remove('hidden');
document.title = `${META.name} · IndexiPro`;
renderNav();
route();
}
function renderNav() {
const links = RO() ? [['/', 'Overview'], ['/browse', 'Browse']] : [['/', 'Dashboard'], ['/browse', 'Browse'], ['/todo', 'Questions'], ['/reports', 'AI reports'], ['/export', 'Export'], ['/capture', 'Add items']];
if (!RO()) links.push(['/ai', 'Connect AI']);
if (ME.role === 'admin') links.push(['/team', 'Team & sharing'], ['/settings', 'Settings']);
const { path } = parseHash();
document.getElementById('nav').innerHTML = links.map(([h, t]) =>
h === '/capture' ? `<a href="/capture">${t}</a>`
: `<a href="#${h}" class="${(path === h || (h !== '/' && path.startsWith(h))) ? 'active' : ''}">${t}</a>`).join('');
if (RO()) { document.getElementById('who').innerHTML = `👀 Read-only view for <b>${esc(ME.name)}</b>`; return; }
document.getElementById('who').innerHTML = `<a href="#/account">${esc(ME.name)}</a> · <a href="#" id="logout">sign out</a>`;
document.getElementById('logout').onclick = async (e) => { e.preventDefault(); await api('/logout', { json: {} }); location.href = '/'; };
}
window.addEventListener('hashchange', () => { if (ME) { renderNav(); route(); } });
function route() {
const { path, params } = parseHash();
window.scrollTo(0, 0);
const m = path.match(/^\/item\/(\d+)/);
if (m) return renderItem(Number(m[1]));
if (path.startsWith('/browse')) return renderBrowse(params);
if (RO() && !path.startsWith('/browse')) return renderDashboard();
if (path === '/todo') return renderTodo();
if (path === '/reports') return renderReports();
if (path === '/export') return renderExport();
if (path === '/account') return renderAccount();
if (path === '/team' && ME.role === 'admin') return renderTeam();
if (path === '/settings' && ME.role === 'admin') return renderSettings();
if (path === '/ai') return renderAi();
return renderDashboard();
}
/* ---------------- login ---------------- */
function renderLogin() {
$app.innerHTML = `
<div class="login card">
<img src="/icons/logo.svg" alt="IndexiPro logo">
<div class="hero-word">Indexi<b>Pro</b></div>
<p class="muted">${esc(INFO.name)}</p>
<form id="lf" class="grid" style="margin-top:18px">
<input name="username" placeholder="Username" autofocus autocomplete="username" autocapitalize="none">
<input type="password" name="password" placeholder="Password" autocomplete="current-password">
<button class="btn primary">Sign in</button>
</form>
<p class="small muted" style="margin-top:18px">New here? Ask the organiser to show you the <b>join QR code</b> and scan it with your phone camera — you'll create your account there.</p>
</div>`;
document.getElementById('lf').onsubmit = async (e) => {
e.preventDefault();
try { await api('/login', { json: { username: e.target.username.value, password: e.target.password.value } }); boot(); } catch (err) { toast(err.message, true); }
};
}
/* ---------------- dashboard ---------------- */
async function renderDashboard() {
$app.innerHTML = '<p class="muted">Loading…</p>';
const [s, feed, reports] = await Promise.all([api('/stats'), api('/activity?limit=25'), RO() ? [] : api('/reports?limit=1')]);
const t = s.totals;
const maxStatus = Math.max(1, ...Object.values(s.byStatus));
const tierRows = Object.entries(META.tiers).map(([k, v]) => [k, v, s.byTier[k] || { count: 0, low: 0, high: 0 }]);
const untiered = s.byTier.none?.count || 0;
$app.innerHTML = `
<div class="row" style="margin-bottom:16px"><h1 style="margin:0">${esc(META.name)}</h1><span class="spacer"></span>
${RO() ? '' : '<a class="btn" href="/capture">+ Add items</a>'}
${ME.role === 'admin' ? '<a class="btn primary" href="#/team">Invite & share</a>' : ''}
${RO() ? '' : '<button class="btn primary" id="airun">🤖 Start AI research</button>'}</div>
${RO() ? `<p class="muted" style="margin-top:-6px">This is a read-only view of the inventory, shared with you. Everything is being photographed and researched as we go — check back any time.</p>` : ''}
<div class="grid stats">
<div class="card stat"><div class="k">Items</div><div class="v">${t.items || 0}</div><div class="small muted">${t.units || 0} units · ${t.photos} photos</div></div>
<div class="card stat"><div class="k">Catalogued</div><div class="v green">${t.items ? Math.round(((t.items - (s.byStatus.new || 0) - (s.byStatus.needs_info || 0)) / t.items) * 100) : 0}%</div><div class="small muted">${t.items - (s.byStatus.new || 0) - (s.byStatus.needs_info || 0)} of ${t.items} identified</div></div>
<div class="card stat"><div class="k">Waiting for AI</div><div class="v">${s.byStatus.new || 0}</div><div class="small muted">${s.last24h} added in last 24h</div></div>
${RO() ? '' : `<a class="card stat" href="#/todo" style="color:inherit"><div class="k">Questions from AI</div><div class="v ${s.questions ? 'amber' : ''}">${s.questions}</div><div class="small muted">${s.questions ? 'need a human — tap to answer' : 'all clear'}</div></a>`}
<div class="card stat"><div class="k">Categories</div><div class="v">${s.categories.length}</div><div class="small muted">${s.locations.length} locations</div></div>
</div>
${reports[0] ? `<div class="section card"><div class="row"><h2 style="margin:0">Latest AI report</h2><span class="muted small">${esc(reports[0].actor)} · ${ago(reports[0].created_at)}</span><span class="spacer"></span><a href="#/reports">All reports →</a></div>
${reportBody(reports[0], true)}</div>` : ''}
${s.top.length ? `<div class="section card"><div class="row"><h2 style="margin:0">Highlights</h2><span class="muted small">marked notable by the AI</span><span class="spacer"></span><a href="#/browse?tier=notable">See all →</a></div>
<div class="top-items" style="margin-top:12px">${s.top.map(tile).join('')}</div></div>` : ''}
<div class="grid two section">
<div class="card"><h2>Workflow</h2><div class="bars">
${Object.entries(META.statuses).map(([k, v]) => `
<a class="bar" href="#/browse?status=${k}"><span>${esc(v.split(' — ')[0])}</span>
<span class="track"><span class="fill" style="width:${((s.byStatus[k] || 0) / maxStatus) * 100}%"></span></span>
<span class="n">${s.byStatus[k] || 0}</span></a>`).join('')}
</div></div>
<div class="card"><h2>Triage</h2>
<div class="tablewrap"><table><tr><th>Tier</th><th>Items</th><th>${showValues() ? 'Value' : ''}</th></tr>
${tierRows.map(([k, v, r]) => `<tr><td><a href="#/browse?tier=${k}">${pill(k, META.tiers)}</a> <span class="small muted">${esc(v.split(' — ')[1] || '')}</span></td>
<td class="mono">${r.count}</td><td class="mono value">${r.count ? fmtRange(r.low, r.high, s.currency) : ''}</td></tr>`).join('')}
<tr><td><a href="#/browse?tier=none" class="muted">Not triaged yet</a></td><td class="mono">${untiered}</td><td></td></tr>
</table></div>
${showValues() && (t.value_low || t.value_high || t.sold_total) ? `<p class="small muted" style="margin-top:12px">Rough value indication across everything: ${fmtRange(t.value_low, t.value_high, s.currency)}${t.sold_total ? ` · sold so far: ${fmtMoney(t.sold_total, s.currency)}` : ''}. Estimates by the AI — treat them as a starting point, not a verdict.</p>` : ''}
</div>
</div>
<div class="grid two section">
${RO() ? `<div class="card"><h2>Categories</h2><div class="row">${s.categories.map((c) => `<a class="btn small" href="#/browse?category=${encodeURIComponent(c.category)}">${esc(c.category)} <span class="muted">${c.n}</span></a>`).join('') || '<span class="muted">Not categorised yet.</span>'}</div></div>`
: `<div class="card"><h2>Recent activity</h2>${feedHtml(feed)}</div>`}
<div class="card"><h2>Team leaderboard</h2>
${s.contributors.length ? `<table>${s.contributors.map((c, i) => `<tr><td class="mono">${['🥇', '🥈', '🥉'][i] || i + 1}</td><td>${esc(c.name)}</td><td class="mono" style="text-align:right">${c.n} items</td></tr>`).join('')}</table>`
: '<p class="muted">Nobody has added anything yet. Invite some phones!</p>'}
${s.locations.length ? `<h2 class="section">Locations</h2><div class="row">${s.locations.map((l) => `<a class="btn small" href="#/browse?location=${encodeURIComponent(l.location)}">${esc(l.location)} <span class="muted">${l.n}</span></a>`).join('')}</div>` : ''}
</div>
</div>`;
dashboardAiButton();
}
async function dashboardAiButton() {
const b = document.getElementById('airun');
if (b) b.onclick = () => go('/ai');
}
function feedHtml(feed) {
if (!feed.length) return '<p class="muted">Nothing yet.</p>';
const verb = (a) => {
const d = a.details ? JSON.parse(a.details) : {};
switch (a.action) {
case 'created': return `added an item with ${d.photos} photo(s)`;
case 'update': {
if (d.status === 'needs_info') return 'asked a question';
if (d.title) return `identified it as <b>${esc(d.title)}</b>`;
if (d.attributes && Object.keys(d).length === 1) return 'filled in details';
return `updated ${Object.keys(d).slice(0, 4).map(esc).join(', ')}`;
}
case 'comparables': return `added ${d.added} comparable listing(s)`;
case 'added_photos': return `added ${d.photos} photo(s)`;
case 'merged': return `merged duplicate #${d.merged_item}`;
case 'joined': return `joined the team (${esc(d.kind)})`;
case 'ai_key': return `connected an AI (${esc(d.label)})`;
case 'report': return `finished a run (${d.processed} items) — <a href="#/reports">read the report</a>`;
case 'deleted_item': return `deleted item #${d.id}`;
default: return esc(a.action);
}
};
return `<ul class="feed">${feed.map((a) => `<li><span class="who ${a.actor.startsWith('AI') ? 'ai' : ''}">${a.actor.startsWith('AI') ? `🤖 ${esc(a.actor)}` : esc(a.actor)}</span> ${verb(a)}
${a.item_id ? `<a href="#/item/${a.item_id}">#${a.item_id}${a.title && a.action !== 'update' ? ` ${esc(a.title)}` : ''}</a>` : ''} <span class="muted small">${ago(a.at)}</span></li>`).join('')}</ul>`;
}
function tile(it) {
const cover = it.cover_id ?? it.cover_photo_id;
return `<a class="tile" href="#/item/${it.id}" data-id="${it.id}">
<div class="ph" style="${cover ? `background-image:url(${thumb(cover)})` : ''}">${cover ? '' : '📦'}</div>
<span class="id">#${it.id}</span>${it.quantity > 1 ? `<span class="qty">×${it.quantity}</span>` : ''}<span class="check"></span>
<div class="body">
<div class="t ${it.title ? '' : 'unknown'}">${esc(it.title || (it.human_notes ? `“${it.human_notes.slice(0, 60)}”` : 'Not identified yet'))}</div>
${it.category ? `<div class="small muted">${esc(it.category)}${it.year ? ` · ${esc(it.year)}` : ''}</div>` : ''}
<div class="meta">${RO() ? pill(it.tier, META.tiers) : pill(it.status, META.statuses)}<span class="value">${fmtRange(it.value_low, it.value_high, it.value_currency || cur())}</span></div>
</div></a>`;
}
/* ---------------- browse ---------------- */
async function renderBrowse(params) {
const q = Object.fromEntries(params.entries());
const opt = (map, sel, all) => `<option value="">${all}</option>` + Object.entries(map).map(([k, v]) => `<option value="${k}" ${sel === k ? 'selected' : ''}>${esc(v.split(' — ')[0])}</option>`).join('');
$app.innerHTML = `
<div class="toolbar">
<div class="search"><input type="search" id="q" placeholder="Search everything… e.g. clock, oak, Tolkien, ISBN, 1940" value="${esc(q.q || '')}"></div>
<select id="status">${opt(META.statuses, q.status, 'Any status')}</select>
<select id="tier">${opt({ ...META.tiers, none: 'Not triaged' }, q.tier, 'Any tier')}</select>
<select id="category"><option value="">Any category</option>${META.categories.map((c) => `<option ${q.category === c.category ? 'selected' : ''}>${esc(c.category)}</option>`).join('')}</select>
<select id="location"><option value="">Any location</option>${META.locations.map((c) => `<option ${q.location === c.location ? 'selected' : ''}>${esc(c.location)}</option>`).join('')}</select>
<select id="sort">${[['', 'Newest'], ['oldest', 'Oldest'], ['updated', 'Recently updated'], ['title', 'A–Z'], ...(showValues() ? [['value', 'Value (high–low)'], ['value_asc', 'Value (low–high)']] : [])].map(([k, v]) => `<option value="${k}" ${q.sort === k ? 'selected' : ''}>${v}</option>`).join('')}</select>
<button class="btn ${RO() ? 'hidden' : ''}" id="selmode">Select</button>
<a class="btn" id="csv" title="Download as spreadsheet">⇩ CSV</a>
</div>
<p class="muted small" id="count"></p>
<div class="items" id="grid"></div>
<div style="text-align:center;margin-top:18px"><button class="btn hidden" id="more">Load more</button></div>
<div class="bulkbar hidden row" id="bulk">
<b id="selcount">0 selected</b><span class="spacer"></span>
<select id="bstatus" style="width:auto">${opt(META.statuses, '', 'Set status…')}</select>
<select id="btier" style="width:auto">${opt(META.tiers, '', 'Set tier…')}</select>
<button class="btn small" id="bloc">Set location…</button>
<button class="btn small" id="blabels">Print labels</button>
<button class="btn small" id="bmerge">Merge</button>
${ME.role === 'admin' ? '<button class="btn small danger" id="bdelete">Delete…</button>' : ''}
</div>`;
const update = () => {
const p = new URLSearchParams();
for (const k of ['q', 'status', 'tier', 'category', 'location', 'sort']) { const v = document.getElementById(k).value; if (v) p.set(k, v); }
history.replaceState(null, '', `#/browse${p.toString() ? '?' + p : ''}`);
load(p, true);
};
let timer;
document.getElementById('q').oninput = () => { clearTimeout(timer); timer = setTimeout(update, 250); };
for (const k of ['status', 'tier', 'category', 'location', 'sort']) document.getElementById(k).onchange = update;
const grid = document.getElementById('grid');
const selected = new Set();
let offset = 0;
let current;
async function load(p, reset) {
current = p;
if (reset) { offset = 0; grid.innerHTML = ''; }
p.set('offset', offset); p.set('limit', 60);
document.getElementById('csv').href = `/api/export.csv?${p}`;
const r = await api(`/items?${p}`);
if (current !== p) return;
grid.insertAdjacentHTML('beforeend', r.items.map(tile).join(''));
offset += r.items.length;
document.getElementById('count').textContent = `${r.total} item${r.total === 1 ? '' : 's'}`;
document.getElementById('more').classList.toggle('hidden', offset >= r.total);
if (!r.total) grid.innerHTML = `<div class="empty" style="grid-column:1/-1"><div class="big">🔍</div>Nothing found.</div>`;
grid.querySelectorAll('.tile').forEach((t) => t.classList.toggle('sel', selected.has(Number(t.dataset.id))));
}
document.getElementById('more').onclick = () => load(new URLSearchParams(current), false);
const syncBulk = () => {
document.getElementById('bulk').classList.toggle('hidden', !selected.size);
document.getElementById('selcount').textContent = `${selected.size} selected`;
};
document.getElementById('selmode').onclick = (e) => {
const on = grid.classList.toggle('selecting');
e.target.textContent = on ? 'Done' : 'Select';
if (!on) { selected.clear(); grid.querySelectorAll('.sel').forEach((t) => t.classList.remove('sel')); syncBulk(); }
};
grid.addEventListener('click', (e) => {
if (!grid.classList.contains('selecting')) return;
const t = e.target.closest('.tile'); if (!t) return;
e.preventDefault();
const id = Number(t.dataset.id);
if (selected.has(id)) selected.delete(id); else selected.add(id);
t.classList.toggle('sel', selected.has(id));
syncBulk();
});
const bulk = async (patch) => {
await api('/items/bulk', { json: { ids: [...selected], patch } });
toast(`Updated ${selected.size} item(s)`);
load(new URLSearchParams(current), true);
};
document.getElementById('bstatus').onchange = (e) => e.target.value && bulk({ status: e.target.value });
document.getElementById('btier').onchange = (e) => e.target.value && bulk({ tier: e.target.value });
document.getElementById('bloc').onclick = () => { const l = prompt('Location (e.g. "Shelf B3" or "Box 12")'); if (l != null) bulk({ location: l }); };
document.getElementById('blabels').onclick = () => window.open(`/labels?ids=${[...selected].join(',')}`);
document.getElementById('bmerge').onclick = async () => {
if (selected.size < 2) return toast('Select at least two photos-of-the-same-thing items', true);
const ids = [...selected].sort((a, b) => a - b);
if (!confirm(`Merge ${ids.length} items into #${ids[0]}? Photos and notes are combined; the others are removed.`)) return;
for (const id of ids.slice(1)) await api('/items/merge', { json: { keep: ids[0], merge: id } });
go(`/item/${ids[0]}`);
};
document.getElementById('bdelete')?.addEventListener('click', async () => {
const n = selected.size;
if (!n) return;
if (!confirm(`Permanently delete ${n} item${n > 1 ? 's' : ''} and all their photos? This can't be undone.`)) return;
try {
const r = await api('/items/bulk-delete', { json: { ids: [...selected] } });
toast(`Deleted ${r.deleted} item(s)`);
selected.clear(); syncBulk();
load(new URLSearchParams(current), true);
} catch (err) { toast(err.message, true); }
});
const p = new URLSearchParams(params);
load(p, true);
}
/* ---------------- item ---------------- */
async function renderItem(id) {
$app.innerHTML = '<p class="muted">Loading…</p>';
let it;
try { it = await api(`/items/${id}`); } catch { $app.innerHTML = '<div class="empty"><div class="big">🕳️</div>Item not found.</div>'; return; }
const c = it.value_currency || cur();
const ro = RO();
const sel = (name, opts, v, blank = '—') => `<select name="${name}"><option value="">${blank}</option>${opts.map(([k, t]) => `<option value="${k}" ${v === k ? 'selected' : ''}>${esc(t)}</option>`).join('')}</select>`;
const inp = (name, lab, v, type = 'text', wide = false) => `<label class="f ${wide ? 'wide' : ''}"><span>${lab}</span><input type="${type}" name="${name}" value="${esc(v ?? '')}" ${type === 'number' ? 'step="any"' : ''}></label>`;
const nice = (s) => s.replace(/_/g, ' ');
const attrs = Object.entries(it.attributes || {});
const knownKeys = [...new Set(Object.values(META.attribute_keys || {}).flatMap((o) => Object.keys(o)))].sort();
const details = [
['Category', it.category], ['Maker / brand / author', it.manufacturer], ['Model / edition / ref.', it.model], ['Year / period', it.year],
['Condition', it.condition && nice(it.condition)], ['Works?', it.working && nice(it.working)], ['Quantity', it.quantity > 1 ? it.quantity : null],
['Location', it.location], ...attrs.map(([k, v]) => [prettyKey(k), String(v)]), ['Tags', it.tags],
].filter(([, v]) => v != null && v !== '');
const readOnly = `<div class="card">
<h2>${esc(it.title || 'Not identified yet')}</h2>
${showValues() && (it.value_low != null || it.value_high != null) ? `<p class="value" style="font-size:1.3rem">${fmtRange(it.value_low, it.value_high, c)}</p>` : ''}
<table>${details.map(([k, v]) => `<tr><th style="width:40%">${esc(k)}</th><td>${esc(v)}</td></tr>`).join('')}</table>
${it.description ? `<p style="white-space:pre-wrap">${esc(it.description)}</p>` : ''}
${it.research_notes ? `<h3 class="section">Research notes</h3><p class="small" style="white-space:pre-wrap">${esc(it.research_notes)}</p>` : ''}
${it.human_notes ? `<p class="small muted" style="white-space:pre-wrap">${esc(it.human_notes)}</p>` : ''}
${showValues() && it.value_notes ? `<p class="small muted">${esc(it.value_notes)}</p>` : ''}
</div>`;
const editForm = `<form class="card" id="edit">
<div class="form">
${inp('title', 'Title', it.title, 'text', true)}
<label class="f"><span>Category</span><input name="category" list="cats" value="${esc(it.category ?? '')}"></label>
${inp('year', 'Year / period', it.year)}
${inp('manufacturer', 'Maker / brand / author', it.manufacturer)}
${inp('model', 'Model / edition / ref.', it.model)}
<label class="f"><span>Status</span>${sel('status', Object.entries(META.statuses).map(([k, v]) => [k, v.split(' — ')[0]]), it.status).replace('<option value="">—</option>', '')}</label>
<label class="f"><span>Tier</span>${sel('tier', Object.entries(META.tiers).map(([k, v]) => [k, v.split(' — ')[0]]), it.tier)}</label>
<label class="f"><span>Condition</span>${sel('condition', META.conditions.map((k) => [k, nice(k)]), it.condition)}</label>
<label class="f"><span>Works? (if relevant)</span>${sel('working', META.working.map((k) => [k, nice(k)]), it.working)}</label>
${inp('quantity', 'Quantity', it.quantity, 'number')}
<label class="f"><span>Location</span><input name="location" list="locs" value="${esc(it.location ?? '')}"></label>
${inp('value_low', `Value low (${esc(c)})`, it.value_low, 'number')}
${inp('value_high', `Value high (${esc(c)})`, it.value_high, 'number')}
<div class="wide"><span class="small muted" style="text-transform:uppercase;letter-spacing:.05em">Details (custom fields — the AI fills these in per type of item)</span>
<div id="attrs" class="grid" style="gap:6px;margin-top:6px"></div>
<button type="button" class="btn small" id="addattr" style="margin-top:6px">+ Add field</button></div>
${inp('tags', 'Tags', it.tags, 'text', true)}
<label class="f wide"><span>Description</span><textarea name="description" rows="5">${esc(it.description ?? '')}</textarea></label>
<label class="f wide"><span>Research notes${it.ai_confidence ? ` — identification confidence: ${esc(it.ai_confidence)}` : ''}</span><textarea name="research_notes" rows="4">${esc(it.research_notes ?? '')}</textarea></label>
${it.value_notes ? `<div class="wide small"><span class="muted">Value notes (${esc(it.value_confidence || '?')} confidence):</span> ${esc(it.value_notes)}</div>` : ''}
<label class="f wide"><span>Human notes</span><textarea name="human_notes" rows="4">${esc(it.human_notes ?? '')}</textarea></label>
${it.status === 'sold' || it.sold_price != null ? `${inp('sold_price', `Sold for (${esc(c)})`, it.sold_price, 'number')}${inp('sold_at', 'Sold on', it.sold_at)}` : ''}
</div>
<datalist id="cats">${META.categories.map((x) => `<option>${esc(x.category)}</option>`).join('')}</datalist>
<datalist id="locs">${META.locations.map((x) => `<option>${esc(x.location)}</option>`).join('')}</datalist>
<datalist id="akeys">${knownKeys.map((k) => `<option>${esc(k)}</option>`).join('')}</datalist>
<div class="row" style="margin-top:16px"><span class="muted small">Added by ${esc(it.created_by || '?')} ${ago(it.created_at)}${it.ai_updated_at ? ` · AI ${ago(it.ai_updated_at)}` : ''}</span>
<span class="spacer"></span><button class="btn primary">Save changes</button></div>
</form>`;
$app.innerHTML = `
<div class="row" style="margin-bottom:14px">
<a href="javascript:history.back()" class="btn small">← Back</a>
<h1 style="margin:0" class="mono">#${it.id}</h1>
${ro ? '' : pill(it.status, META.statuses)} ${pill(it.tier, META.tiers)}
<span class="spacer"></span>
${ro ? '' : `<a class="btn small" href="/labels?ids=${it.id}" target="_blank">🏷 Label</a>
${it.status !== 'sold' ? '<button class="btn small" id="sold">Mark sold</button>' : ''}
<button class="btn small" id="merge">Merge…</button>
${ME.role === 'admin' ? '<button class="btn small danger" id="del">Delete</button>' : ''}`}
</div>
<div class="item-layout">
<div>
<div class="gallery card">
<div class="main" id="mainph"></div>
<div class="thumbs" id="thumbs"></div>
</div>
${it.question && !ro ? `<div class="card question section"><h3>🤖 The AI asks</h3><p>${esc(it.question)}</p>${answerBox(it.id)}</div>` : ''}
${it.no_questions && !ro ? `<div class="small muted section">The AI won't ask questions about this item. <a href="#" id="allowq">Allow questions again</a></div>` : ''}
${(it.listing_text || it.listing_title) && !ro ? `<div class="card listing section"><div class="row"><h2 style="margin:0">Listing</h2><span class="muted small">${esc(it.listing_platform || '')}</span><span class="spacer"></span>
${it.listing_price != null ? `<span class="value">${fmtMoney(it.listing_price, c)}</span>` : ''}</div>
<h3 style="margin-top:12px">${esc(it.listing_title || '')}</h3>
<pre>${esc(it.listing_text || '')}</pre>
<div class="row"><button class="btn small" data-copy="title">Copy title</button><button class="btn small" data-copy="text">Copy text</button>
<button class="btn small" id="dlphotos">Download photos</button>
${it.status !== 'listed' && it.status !== 'sold' ? '<button class="btn small primary" id="listed">Mark as listed</button>' : ''}</div></div>` : ''}
${showValues() ? `<div class="card section"><h2>Comparable sales</h2>
${it.comparables.length ? `<div class="tablewrap"><table><tr><th>Listing</th><th>Kind</th><th>Price</th>${ro ? '' : '<th></th>'}</tr>
${it.comparables.map((x) => `<tr><td>${/^https?:\/\//i.test(x.url || '') ? `<a href="${esc(x.url)}" target="_blank" rel="noopener noreferrer">${esc(x.title)}</a>` : esc(x.title)}
<div class="small muted">${esc([x.source, x.condition, x.date, x.notes].filter(Boolean).join(' · '))}</div></td>
<td>${esc(x.kind || '')}</td><td class="value">${fmtMoney(x.price, x.currency || c)}</td>${ro ? '' : `<td><button class="btn small" data-delcomp="${x.id}">✕</button></td>`}</tr>`).join('')}</table></div>`
: '<p class="muted">None yet — the AI adds these when it researches the value.</p>'}
</div>` : ''}
${ro ? '' : `<div class="card section"><h2>History</h2>${feedHtml(it.activity.map((a) => ({ ...a, item_id: null })))}</div>`}
</div>
${ro ? readOnly : editForm}
</div>
<input type="file" id="addph" accept="image/*" multiple class="hidden">`;
// gallery
let currentPhoto = it.cover_photo_id || it.photos[0]?.id;
const drawGallery = () => {
const main = document.getElementById('mainph');
main.style.backgroundImage = currentPhoto ? `url(/photos/${currentPhoto}/medium)` : '';
main.innerHTML = currentPhoto ? '' : '<div class="empty">No photos</div>';
document.getElementById('thumbs').innerHTML = it.photos.map((p) => `<div class="th ${p.id === currentPhoto ? 'on' : ''}" data-ph="${p.id}" style="background-image:url(${thumb(p.id)})">${ro ? '' : `<button type="button" class="x" data-delph="${p.id}" title="Delete photo">✕</button>`}</div>`).join('')
+ (ro ? '' : '<button type="button" class="th add" id="addbtn" title="Add photos">+</button>');
};
drawGallery();
document.getElementById('thumbs').onclick = async (e) => {
const del = e.target.closest('[data-delph]');
if (del) {
if (!confirm('Delete this photo?')) return;
await api(`/photos/${del.dataset.delph}`, { method: 'DELETE' });
return renderItem(id);
}
if (e.target.closest('#addbtn')) return document.getElementById('addph').click();
const th = e.target.closest('[data-ph]');
if (th) { currentPhoto = Number(th.dataset.ph); drawGallery(); }
};
document.getElementById('mainph').onclick = () => {
if (!currentPhoto) return;
const lb = document.createElement('div');
lb.className = 'lightbox';
lb.innerHTML = `<img src="/photos/${currentPhoto}/full" alt="">`;
lb.onclick = () => lb.remove();
document.body.appendChild(lb);
};
if (ro) return;
document.getElementById('addph').onchange = async (e) => {
const fd = new FormData();
for (const f of e.target.files) fd.append('photos', await shrinkImage(f));
toast('Uploading…');
await api(`/items/${id}/photos`, { method: 'POST', body: fd });
renderItem(id);
};
// custom fields
const attrBox = document.getElementById('attrs');
const attrRow = (k = '', v = '') => {
const row = document.createElement('div');
row.className = 'row attr';
row.style.flexWrap = 'nowrap';
row.innerHTML = `<input class="ak" list="akeys" placeholder="field, e.g. isbn" value="${esc(k)}" style="flex:0 0 38%"><input class="av" placeholder="value" value="${esc(v)}"><button type="button" class="btn small" title="Remove">✕</button>`;
row.querySelector('button').onclick = () => row.remove();
attrBox.appendChild(row);
};
attrs.forEach(([k, v]) => attrRow(k, v));
document.getElementById('addattr').onclick = () => { attrRow(); attrBox.lastChild.querySelector('.ak').focus(); };
// edit
document.getElementById('edit').onsubmit = async (e) => {
e.preventDefault();
const body = Object.fromEntries(new FormData(e.target).entries());
body.attributes = {};
attrBox.querySelectorAll('.attr').forEach((r) => {
const k = r.querySelector('.ak').value.trim(); const v = r.querySelector('.av').value.trim();
if (k && v) body.attributes[k] = v;
});
try { await api(`/items/${id}`, { method: 'PATCH', json: body }); toast('Saved'); META = await api('/meta'); renderItem(id); } catch (err) { toast(err.message, true); }
};
bindAnswerBoxes($app, () => renderItem(id));
document.getElementById('allowq')?.addEventListener('click', async (e) => { e.preventDefault(); await api(`/items/${id}/allow-questions`, { method: 'POST' }); renderItem(id); });
$app.querySelectorAll('[data-copy]').forEach((b) => { b.onclick = () => copy(b.dataset.copy === 'title' ? it.listing_title : it.listing_text); });
$app.querySelectorAll('[data-delcomp]').forEach((b) => { b.onclick = async () => { await api(`/comparables/${b.dataset.delcomp}`, { method: 'DELETE' }); renderItem(id); }; });
document.getElementById('dlphotos')?.addEventListener('click', () => it.photos.forEach((p, i) => setTimeout(() => {
const a = document.createElement('a'); a.href = `/photos/${p.id}/full?download=1`; a.download = ''; a.click();
}, i * 400)));
document.getElementById('listed')?.addEventListener('click', async () => { await api(`/items/${id}`, { method: 'PATCH', json: { status: 'listed' } }); renderItem(id); });
document.getElementById('sold')?.addEventListener('click', async () => {
const price = prompt(`Sold for how much (${c})?`, it.listing_price ?? it.value_high ?? '');
if (price == null) return;
await api(`/items/${id}`, { method: 'PATCH', json: { status: 'sold', sold_price: price || null, sold_at: new Date().toISOString().slice(0, 10) } });
toast('🎉 Sold!'); renderItem(id);
});
document.getElementById('merge').onclick = async () => {
const other = prompt('Merge which item number INTO this one? (duplicate photos of the same object)');
if (!other) return;
try { await api('/items/merge', { json: { keep: id, merge: Number(String(other).replace('#', '')) } }); toast('Merged'); renderItem(id); } catch (err) { toast(err.message, true); }
};
document.getElementById('del')?.addEventListener('click', async () => {
if (!confirm(`Delete item #${id} and its photos permanently?`)) return;
await api(`/items/${id}`, { method: 'DELETE' });
go('/browse');
});
}
/* ---------------- AI reports ---------------- */
function linkItems(text) {
return esc(text).replace(/#(\d+)/g, '<a href="#/item/$1">#$1</a>');
}
function reportBody(r, short = false) {
const chips = [['processed', 'processed'], ['confident', 'confident'], ['uncertain', 'uncertain'], ['needs_info', 'need info']]
.filter(([k]) => r[k]?.length).map(([k, l]) => `<a class="btn small" href="#/browse?ids=${r[k].join(',')}">${r[k].length} ${l}</a>`).join('');
const body = short && r.report.length > 700 ? r.report.slice(0, 700) + '…' : r.report;
return `<div class="row" style="margin:10px 0">${chips}</div><div style="white-space:pre-wrap">${linkItems(body)}</div>`;
}
async function renderReports() {
const reports = await api('/reports');
$app.innerHTML = `<h1>AI reports</h1>
<p class="muted">After each run the AI writes an honest report: what it found, what it couldn't determine, and what needs more information.</p>
${reports.length ? reports.map((r) => `<div class="card section"><div class="row"><b>${esc(r.actor)}</b><span class="muted small">${new Date(r.created_at.replace(' ', 'T') + 'Z').toLocaleString()}</span></div>${reportBody(r)}</div>`).join('')
: '<div class="empty"><div class="big">📝</div>No reports yet. They appear here after the AI finishes a run.</div>'}`;
}
/* ---------------- questions ---------------- */
/** Answer an AI question with photos (camera or gallery) and/or text, sent together. */
function answerBox(itemId) {
return `<form class="grid answer" data-item="${itemId}" style="margin-top:10px">
<div class="row">
<button type="button" class="btn" data-pick="camera">📷 Take photo</button>
<button type="button" class="btn" data-pick="gallery">🖼 Choose photo</button>
<input type="file" accept="image/*" capture="environment" class="hidden" data-input="camera">
<input type="file" accept="image/*" multiple class="hidden" data-input="gallery">
</div>
<div class="answer-previews"></div>
<textarea name="text" rows="2" placeholder="Answer in words (optional when you add a photo)"></textarea>
<div class="row"><button class="btn primary" disabled style="flex:1">Send to the AI</button>
<button type="button" class="btn" data-skip title="The AI won't ask about this item again and finishes it with what it has">Skip — don't ask again</button></div>
</form>`;
}
function bindAnswerBoxes(root, onDone) {
root.querySelectorAll('form.answer').forEach((form) => {
const files = [];
const prev = form.querySelector('.answer-previews');
const send = form.querySelector('button.primary');
const sync = () => {
prev.innerHTML = files.map((f, i) => `<div class="p" style="background-image:url(${f.url})"><button type="button" data-rm="${i}" title="Remove">✕</button></div>`).join('');
send.disabled = !files.length && !form.text.value.trim();
send.textContent = files.length ? `Send ${files.length} photo${files.length > 1 ? 's' : ''} to the AI` : 'Send to the AI';
};
form.text.addEventListener('input', sync);
form.querySelectorAll('[data-pick]').forEach((b) => { b.onclick = () => form.querySelector(`[data-input="${b.dataset.pick}"]`).click(); });
form.querySelectorAll('input[type=file]').forEach((inp) => {
inp.onchange = async () => {
for (const f of inp.files) { const small = await shrinkImage(f); files.push({ file: small, url: URL.createObjectURL(small) }); }
inp.value = ''; sync();
};
});
prev.addEventListener('click', (e) => {
const i = e.target.dataset.rm; if (i == null) return;
URL.revokeObjectURL(files[i].url); files.splice(Number(i), 1); sync();
});
form.querySelector('[data-skip]').onclick = async () => {
await api(`/items/${form.dataset.item}/skip-question`, { method: 'POST' });
toast('Skipped — the AI won\'t ask about this item again');
onDone();
};
form.onsubmit = async (e) => {
e.preventDefault();
send.disabled = true; send.textContent = 'Sending…';
try {
const id = form.dataset.item;
if (files.length) {
const fd = new FormData();
files.forEach((f) => fd.append('photos', f.file));
fd.append('note', form.text.value);
await api(`/items/${id}/photos`, { method: 'POST', body: fd });
} else {
await api(`/items/${id}/answer`, { json: { text: form.text.value } });
}
toast('Thanks! The AI will pick it up again.');
onDone();
} catch (err) { toast(err.message, true); sync(); }
};
sync();
});
}
async function renderTodo() {
const r = await api('/todo');
$app.innerHTML = `<h1>Questions from the AI</h1>
<div class="row"><p class="muted" style="flex:1;min-width:240px">The AI couldn't work these out from the photos alone. Find the item, then take a photo or type an answer right here — it goes straight back to the AI. Too many questions? Limit them under <a href="#/settings">Settings</a>${ME.role === 'admin' ? '' : ' (admin)'}.</p>
${r.items.length ? `<button class="btn" id="dismissall">Dismiss all ${r.items.length}</button>` : ''}</div>
${r.items.length ? `<div class="grid" style="gap:12px">${r.items.map((it) => `
<div class="card question">
<a class="row" href="#/item/${it.id}" style="color:inherit;align-items:flex-start">
<div style="width:72px;height:72px;border-radius:10px;flex:0 0 72px;background:var(--bg2) url(${thumb(it.cover_id)}) center/cover"></div>
<div style="flex:1;min-width:180px"><div class="mono muted">#${it.id} ${it.location ? `· 📍 ${esc(it.location)}` : ''}</div>
<div class="small muted">${esc(it.title || '')}</div><div style="margin-top:4px">🤖 <b>${esc(it.question || '')}</b></div></div></a>
${answerBox(it.id)}
</div>`).join('')}</div>`
: '<div class="empty"><div class="big">✅</div>No open questions.</div>'}`;
bindAnswerBoxes($app, renderTodo);
document.getElementById('dismissall')?.addEventListener('click', async () => {
if (!confirm('Dismiss every open question? The AI finishes those items with what it has and won\'t ask about them again.')) return;
const d = await api('/questions/dismiss-all', { method: 'POST' });
toast(`Dismissed ${d.dismissed} question(s)`); renderTodo();
});
}
/* ---------------- shared bits ---------------- */
function showOnce(title, html) {
const lb = document.createElement('div');
lb.className = 'lightbox';
lb.style.cursor = 'default';
lb.innerHTML = `<div class="card" style="max-width:640px;width:calc(100% - 32px);max-height:92vh;overflow:auto">
<h2>${title}</h2>${html}<div class="row" style="margin-top:14px"><span class="spacer"></span><button class="btn primary" data-close>Done</button></div></div>`;
lb.querySelector('[data-close]').onclick = () => lb.remove();
lb.querySelectorAll('[data-copytext]').forEach((b) => { b.onclick = () => copy(b.dataset.copytext); });
document.body.appendChild(lb);
window.addEventListener('hashchange', () => lb.remove(), { once: true });
return lb;
}
function qrLightbox(url) {
const lb = document.createElement('div'); lb.className = 'lightbox';
lb.innerHTML = `<div class="qrbox" style="width:min(420px,90vw)"><img src="/api/qr?data=${encodeURIComponent(url)}" alt="" style="width:100%"></div>`;
lb.onclick = () => lb.remove(); document.body.appendChild(lb);
}
/* ---------------- team (admin) ---------------- */
async function renderTeam(fresh = false) {
const [j, users, devices, shares] = await Promise.all([api(`/join${fresh ? '?fresh=1' : ''}`), api('/users'), api('/devices'), api('/shares')]);
const app = INFO.app;
$app.innerHTML = `<h1>Team & sharing</h1>
<div class="grid two">
<div class="card"><h2>New helpers: scan to join</h2>
<div class="row" style="align-items:flex-start;gap:20px">
<div class="qrbox">${j.svg}</div>
<div style="flex:1;min-width:220px">
<ol class="steps">
<li>Point the phone's <b>camera</b> at this code and tap the link.</li>
<li><b>Android:</b> install the IndexiPro app, then tap <i>Open in the app</i>.<br><b>iPhone / no app:</b> carry on in the browser.</li>
<li>Enter your name and choose a password — that creates your own account.</li>
</ol>
<p class="small muted">Code <span class="mono">${esc(j.code)}</span> · used ${j.uses}× · valid until ${new Date(j.expires_at.replace(' ', 'T') + 'Z').toLocaleString()}. Anyone with this code can create an account, so only show it to the team.</p>
<div class="copy"><input readonly value="${esc(j.url)}"><button class="btn small" id="cp">Copy</button></div>
<div class="row" style="margin-top:10px"><button class="btn small" id="fresh">New code</button><button class="btn small danger" id="expire">Stop join codes</button>
<button class="btn small" onclick="document.querySelector('.qrbox').requestFullscreen?.()">Fullscreen</button></div>
</div>
</div>
</div>
<div class="card"><h2>Android app</h2>
${app.available ? `<p>Version <b>${esc(app.versionName)}</b>. Helpers get it from the join link, or directly:</p>
<p><a class="btn primary" href="/download/indexipro.apk">⇩ Download APK</a></p>
<p class="small muted">Android asks to allow installing from the browser ("unknown sources") — expected for apps outside the Play Store.</p>`
: '<p class="muted">No APK bundled with this server yet. Run <code>android/build-and-publish.sh</code>.</p>'}
<p class="small muted">The app works offline: photos queue up and upload automatically once the phone has a connection. Existing team members add another phone via <a href="#/account">My account → Pair a phone</a>.</p>
</div>
</div>
<div class="card section"><div class="row"><h2 style="margin:0">Team accounts</h2><span class="spacer"></span></div>
<p class="muted small">Admins can manage the team, share links and settings. Editors can add, edit and research items and create their own AI keys.</p>
<form id="newuser" class="row" style="margin:10px 0">
<input name="display_name" placeholder="Name, e.g. Sam" required style="flex:1;min-width:160px">
<input name="username" placeholder="Username (optional)" style="flex:1;min-width:140px">
<select name="role" style="width:auto"><option value="editor">Editor</option><option value="admin">Admin</option></select>
<button class="btn">Add person</button>
</form>
<div class="tablewrap"><table><tr><th>Name</th><th>Username</th><th>Role</th><th>Phones</th><th>AI keys</th><th>Items</th><th>Last seen</th><th></th></tr>
${users.users.map((u) => `<tr class="${u.disabled ? 'muted' : ''}"><td>${esc(u.display_name)}${u.id === ME.id ? ' <span class="small muted">(you)</span>' : ''}</td><td class="mono">${esc(u.username)}</td>
<td>${u.disabled ? 'disabled' : `<select data-role="${u.id}" style="width:auto;padding:4px 8px">${Object.keys(users.roles).map((r) => `<option ${u.role === r ? 'selected' : ''} value="${r}">${r}</option>`).join('')}</select>`}</td>
<td class="mono">${u.devices}</td><td class="mono">${u.ai_keys}</td><td class="mono">${u.items}</td><td>${ago(u.last_seen)}</td>
<td class="row" style="flex-wrap:nowrap">${u.disabled ? `<button class="btn small" data-enable="${u.id}">Enable</button>`
: `<button class="btn small" data-reset="${u.id}" data-name="${esc(u.display_name)}">Reset password</button><button class="btn small danger" data-disable="${u.id}">Disable</button>`}</td></tr>`).join('')}
</table></div>
</div>
<div class="card section" id="share"><h2>Read-only share links</h2>
<p class="muted">Let someone look through everything — no account, no password, nothing to install. They can't change anything and never see the AI's questions or activity. Per link you choose whether value indications (with research notes) and team notes & storage locations are shown, and you can switch a link off at any time.</p>
<form id="newshare" class="row" style="margin:12px 0">
<input name="label" placeholder="Who is it for? e.g. Mia, or the group chat" style="flex:1;min-width:220px" required>
<select name="days" style="width:auto"><option value="0">Never expires</option><option value="7">7 days</option><option value="30">30 days</option><option value="90">90 days</option></select>
<label class="row small" style="gap:6px"><input type="checkbox" name="show_values" checked> show values</label>
<label class="row small" style="gap:6px" title="Team notes, storage locations and who photographed it"><input type="checkbox" name="show_details"> show notes & locations</label>
<button class="btn primary">Create link</button>
</form>
${shares.length ? `<div class="tablewrap"><table><tr><th>For</th><th>Link</th><th>Shows</th><th>Opened</th><th></th></tr>
${shares.map((sh) => `<tr class="${sh.revoked ? 'muted' : ''}"><td>${esc(sh.label)}${sh.expires_at ? `<div class="small muted">until ${esc(sh.expires_at.slice(0, 10))}</div>` : ''}</td>
<td>${sh.revoked ? '<i>switched off</i>' : `<div class="copy"><input readonly value="${esc(sh.url)}"><button class="btn small" data-cps="${esc(sh.url)}">Copy</button><button class="btn small" data-qrs="${esc(sh.url)}">QR</button></div>`}</td>
<td>${sh.revoked ? '' : `<label class="row small" style="gap:6px"><input type="checkbox" data-vals="${sh.id}" ${sh.show_values ? 'checked' : ''}> values</label>
<label class="row small" style="gap:6px"><input type="checkbox" data-dets="${sh.id}" ${sh.show_details ? 'checked' : ''}> notes & locations</label>`}</td>
<td class="small">${sh.views}× ${sh.last_used ? `· ${ago(sh.last_used)}` : ''}</td>
<td>${sh.revoked ? '' : `<button class="btn small danger" data-revs="${sh.id}">Switch off</button>`}</td></tr>`).join('')}</table></div>` : ''}
</div>
<div class="card section"><h2>Signed-in phones</h2>
${devices.length ? `<div class="tablewrap"><table><tr><th>Phone</th><th>Account</th><th>Paired</th><th>Last seen</th><th></th></tr>
${devices.map((d) => `<tr><td>${esc(d.name)}</td><td>${esc(d.owner || '?')}</td><td>${ago(d.created_at)}</td><td>${ago(d.last_seen)}</td>
<td><button class="btn small danger" data-rev="${d.id}">Sign out</button></td></tr>`).join('')}</table></div>` : '<p class="muted">No phones yet.</p>'}
</div>`;
const credentials = (title, username, password) => showOnce(title, `
<p>Give these to the person (e.g. by text message). They can change the password under <b>My account</b>.</p>
<table><tr><th>Address</th><td class="mono">${esc(INFO.base_url)}</td></tr><tr><th>Username</th><td class="mono">${esc(username)}</td></tr><tr><th>Password</th><td class="mono">${esc(password)}</td></tr></table>
<p class="small muted">The password is shown only now.</p>
<button class="btn" data-copytext="${esc(`${INFO.base_url}\nUsername: ${username}\nPassword: ${password}`)}">Copy all</button>`);
document.getElementById('cp').onclick = () => copy(j.url);
document.getElementById('fresh').onclick = () => renderTeam(true);
document.getElementById('expire').onclick = async () => { if (confirm('Invalidate the join QR codes? Existing accounts and phones keep working.')) { await api('/join/expire', { json: {} }); toast('Join codes stopped'); } };
document.getElementById('newuser').onsubmit = async (e) => {
e.preventDefault();
try {
const f = e.target;
const r = await api('/users', { json: { display_name: f.display_name.value, username: f.username.value, role: f.role.value } });
await renderTeam();
credentials('Account created', r.username, r.password);
} catch (err) { toast(err.message, true); }
};
$app.querySelectorAll('[data-role]').forEach((s) => { s.onchange = async () => {
try { await api(`/users/${s.dataset.role}`, { method: 'PATCH', json: { role: s.value } }); toast('Role updated'); } catch (err) { toast(err.message, true); renderTeam(); }
}; });
$app.querySelectorAll('[data-reset]').forEach((b) => { b.onclick = async () => {
if (!confirm(`Give ${b.dataset.name} a new temporary password?`)) return;
const r = await api(`/users/${b.dataset.reset}/reset`, { json: {} });
const u = users.users.find((x) => String(x.id) === b.dataset.reset);
credentials('New password', u.username, r.password);
}; });
$app.querySelectorAll('[data-disable]').forEach((b) => { b.onclick = async () => {
if (!confirm('Disable this account? Their phones and AI keys stop working immediately.')) return;
try { await api(`/users/${b.dataset.disable}`, { method: 'PATCH', json: { disabled: true } }); renderTeam(); } catch (err) { toast(err.message, true); }
}; });
$app.querySelectorAll('[data-enable]').forEach((b) => { b.onclick = async () => { await api(`/users/${b.dataset.enable}`, { method: 'PATCH', json: { disabled: false } }); renderTeam(); }; });
document.getElementById('newshare').onsubmit = async (e) => {
e.preventDefault();
const f = e.target;
const r = await api('/shares', { json: { label: f.label.value, days: f.days.value, show_values: f.show_values.checked, show_details: f.show_details.checked } });
await copy(r.url);
toast('Link created and copied — paste it in a message');
renderTeam();
};
$app.querySelectorAll('[data-cps]').forEach((b) => { b.onclick = () => copy(b.dataset.cps); });
$app.querySelectorAll('[data-qrs]').forEach((b) => { b.onclick = () => qrLightbox(b.dataset.qrs); });
$app.querySelectorAll('[data-vals]').forEach((b) => { b.onchange = () => api(`/shares/${b.dataset.vals}`, { method: 'PATCH', json: { show_values: b.checked } }).then(() => toast('Updated')); });
$app.querySelectorAll('[data-dets]').forEach((b) => { b.onchange = () => api(`/shares/${b.dataset.dets}`, { method: 'PATCH', json: { show_details: b.checked } }).then(() => toast('Updated')); });
$app.querySelectorAll('[data-revs]').forEach((b) => { b.onclick = async () => { if (confirm('Switch this link off? Anyone using it loses access.')) { await api(`/shares/${b.dataset.revs}`, { method: 'DELETE' }); renderTeam(); } }; });
$app.querySelectorAll('[data-rev]').forEach((b) => { b.onclick = async () => { if (confirm('Sign this phone out?')) { await api(`/devices/${b.dataset.rev}`, { method: 'DELETE' }); renderTeam(); } }; });
}
/* ---------------- my account ---------------- */
async function renderAccount() {
const devices = await api('/me/devices');
$app.innerHTML = `<h1>My account</h1>
<div class="grid two">
<form class="card grid" id="acc">
<h2 style="margin:0">Details</h2>
<p class="muted small" style="margin:0">Username: <span class="mono">${esc(ME.username)}</span> · role: ${esc(ME.role)}</p>
<label class="f"><span>Name shown to others</span><input name="display_name" value="${esc(ME.name)}"></label>
<label class="f"><span>Current password</span><input type="password" name="current_password" autocomplete="current-password"></label>
<label class="f"><span>New password (min. 6 characters)</span><input type="password" name="new_password" autocomplete="new-password"></label>
<div class="row"><span class="spacer"></span><button class="btn primary">Save</button></div>
</form>
<div class="card"><h2>Pair a phone</h2>
<p class="muted">Sign the IndexiPro app on another phone into <b>your</b> account: open the app, tap <i>Scan join QR code</i>, and scan this. Works once, for 15 minutes.</p>
<button class="btn primary" id="pair">Show my pairing code</button>
<div id="pairbox" style="margin-top:14px"></div>
<h2 class="section">My phones</h2>
${devices.length ? `<table>${devices.map((d) => `<tr><td>${esc(d.name)}</td><td class="small muted">last seen ${ago(d.last_seen)}</td><td><button class="btn small danger" data-out="${d.id}">Sign out</button></td></tr>`).join('')}</table>` : '<p class="muted">None yet.</p>'}
</div>
</div>`;
document.getElementById('acc').onsubmit = async (e) => {
e.preventDefault();
try {
await api('/me', { method: 'PATCH', json: Object.fromEntries(new FormData(e.target).entries()) });
toast('Saved'); ME = await api('/me'); renderNav(); renderAccount();
} catch (err) { toast(err.message, true); }
};
document.getElementById('pair').onclick = async () => {
const r = await api('/me/pair');
document.getElementById('pairbox').innerHTML = `<div class="qrbox">${r.svg}</div>`;
};
$app.querySelectorAll('[data-out]').forEach((b) => { b.onclick = async () => { await api(`/me/devices/${b.dataset.out}`, { method: 'DELETE' }); renderAccount(); }; });
}
/* ---------------- AI ---------------- */
/** Optional "where exactly?" hints. The main flow is the same for every AI app. */
const AI_HINTS = [
['Claude', 'Add a custom connector using the server URL below. Open its Connect / Authorize action, then sign in to IndexiPro and approve access. Under OAuth client, choose “Register automatically”. Leave optional client ID and secret empty.'],
['ChatGPT', 'Add a custom MCP app using the server URL below and select OAuth authentication when offered. Sign in to IndexiPro and approve access. Enable the app in the chat before starting research. Availability depends on your account and workspace settings.'],
['Codex / other MCP clients', 'Use Streamable HTTP with the server URL below and run the client’s OAuth login / authorization action. If your client only supports manual headers, use the advanced token setup.'],
];
async function renderAi(setupMode = false) {
const r = await api('/aikeys');
const connected = r.connected && !setupMode;
const startCard = `
<div class="card" style="text-align:center;padding:28px">
<div style="font-size:2.4rem">🤖</div>
<h2>${connected ? 'Your AI has discovered IndexiPro ✅' : 'Start a research session'}</h2>
<p class="muted">Copy this message, paste it into a <b>new chat</b> in your AI app, and press send. When it's done it reports back — say <i>"continue"</i> for the next batch.</p>
<div class="card" style="text-align:left;margin:14px auto;max-width:640px;white-space:pre-wrap;font-size:.92rem">${esc(r.session_prompt)}</div>
<button class="btn primary" id="copystart" style="font-size:1.1rem;padding:14px 26px">📋 Copy start message</button>
<p class="small muted" style="margin-top:12px">The message contains nothing secret — it's safe to keep in a note or share with the team.
If the AI says it can't see IndexiPro, switch the IndexiPro connection on in that chat (usually under the <b>+</b> button).</p>
${connected ? '<p class="small" style="margin-top:8px"><a href="#" id="setup">Connect another AI account</a></p>' : ''}
</div>`;
const setup = `
<div class="card">
<h2>1 — Add IndexiPro to your AI app</h2>
<p>Copy this server URL. Choose <b>OAuth</b> authentication if asked, then sign in with your <b>IndexiPro username and password</b> and approve access.</p>
<div class="copy"><input readonly value="${esc(r.endpoint)}"><button class="btn" id="copyendpoint">Copy server URL</button></div>
<label class="f" style="margin-top:16px">Your AI app<select id="aiclient">${AI_HINTS.map(([name], i) => `<option value="${i}">${name}</option>`).join('')}</select></label>
<p id="aihint">${AI_HINTS[0][1]}</p>
<p class="small muted">Use this clean URL for a new connection. If an old token-based connector failed, remove that failed connector from your AI app and add it again using this URL.</p>
</div>
<details class="card section"><summary>Advanced: manual API token</summary>
<p>For clients that support an Authorization header or a secret URL.</p>
<div id="conn"><button class="btn" id="make">Make a manual connection</button></div>
</details>
<div class="section"><h2>2 — Verify the connection</h2><p>Refresh the status after approving access in your AI app. Tool discovery confirms setup; a successful tool call confirms the AI can use the collection.</p><button class="btn" id="refreshconnection">Refresh connection status</button></div>
<div class="section"><h2>3 — Start research</h2></div>`;
const keysCard = r.keys.length ? `
<div class="card section"><h2>${ME.role === 'admin' ? 'All AI connections' : 'My AI connections'}</h2>
<div class="tablewrap"><table><tr><th>Name</th>${ME.role === 'admin' ? '<th>Owner</th>' : ''}<th>Created</th><th>Connection status</th><th>Requests</th><th></th></tr>
${r.keys.map((k) => `<tr><td>${esc(k.label)} <span class="mono small muted">${esc(k.key_hint)}</span></td>${ME.role === 'admin' ? `<td>${esc(k.owner)}</td>` : ''}<td>${ago(k.created_at)}</td>
<td>${k.tool_called_at ? 'Tool call succeeded' : k.tools_listed_at ? 'Tools discovered' : k.initialized_at ? 'Handshake completed' : k.authenticated_at ? 'Authenticated; setup incomplete' : 'Waiting for AI app'}${k.last_used ? `<br><span class="small muted">${ago(k.last_used)}</span>` : ''}${k.last_error ? `<br><span role="status">${esc(k.last_error)}</span>` : ''}</td><td class="mono">${k.calls}</td><td><button class="btn small danger" data-revk="${k.id}">Remove</button></td></tr>`).join('')}</table></div>
<p class="small muted">Status records completed connection steps; it does not mean the app is currently online. Removing a connection makes that AI lose access straight away.</p>
</div>` : '';
const ideas = `
<div class="card section"><h2>Other things you can ask the AI</h2>
${['Continue with the next batch.',
'Go through the items marked "notable" and check the identifications carefully. Which ones deserve an expert opinion?',
'Look at all books: fill in author, publisher, year, edition and ISBN where visible, and flag possible first editions.',
'Find duplicates and items that belong together (sets, pairs) and merge or tag them.',
'Summarise the collection: highlights per category, what stands out, and what still needs better photos.'].map((s) => `
<div class="row" style="margin-bottom:8px"><div class="card" style="flex:1;padding:10px 14px">${esc(s)}</div><button class="btn small" data-say="${esc(s)}">Copy</button></div>`).join('')}
</div>`;
$app.innerHTML = `<h1>Connect your AI</h1>
${r.https ? '' : '<p class="small" style="color:var(--amber)">⚠ This server is not on a public https address, so online AI apps can\'t reach it yet (admin: see "Making it reachable" in the README).</p>'}
${connected ? '' : setup}
${startCard}
${keysCard}
${ideas}`;
document.getElementById('copyendpoint')?.addEventListener('click', () => copy(r.endpoint));
document.getElementById('aiclient')?.addEventListener('change', (e) => { document.getElementById('aihint').textContent = AI_HINTS[Number(e.target.value)][1]; });
document.getElementById('refreshconnection')?.addEventListener('click', () => renderAi(true));
document.getElementById('copystart').onclick = () => copy(r.session_prompt);
document.getElementById('setup')?.addEventListener('click', (e) => { e.preventDefault(); renderAi(true); });
document.getElementById('make')?.addEventListener('click', async () => {
const k = await api('/aikeys', { json: { label: `${ME.name}'s AI` } });
document.getElementById('conn').innerHTML = `
<table>
<tr><th style="width:24%">Server URL</th><td><div class="copy"><input readonly value="${esc(k.endpoint)}"><button class="btn small" data-c="${esc(k.endpoint)}">Copy</button></div></td></tr>
<tr><th>API token</th><td><div class="copy"><input readonly value="${esc(k.key)}"><button class="btn small" data-c="${esc(k.key)}">Copy</button></div>
<div class="small muted">Sent as the header <code>Authorization: Bearer &lt;token&gt;</code>. If the app asks for a "Bearer token", paste the token itself.</div></td></tr>
<tr><th>One address<br><span class="small muted">(apps with only a URL field)</span></th><td><div class="copy"><input readonly value="${esc(k.url)}"><button class="btn small" data-c="${esc(k.url)}">Copy</button></div></td></tr>
</table>
<p class="small muted" style="margin-top:8px">Shown only now, so set it up before leaving this page. Don't share the token — anyone with it can change the collection. Lost it? Just make a new one.</p>`;
document.querySelectorAll('#conn [data-c]').forEach((b) => { b.onclick = () => copy(b.dataset.c); });
});
$app.querySelectorAll('[data-revk]').forEach((b) => { b.onclick = async () => { if (confirm('Remove this connection? That AI loses access immediately.')) { await api(`/aikeys/${b.dataset.revk}`, { method: 'DELETE' }); renderAi(); } }; });
$app.querySelectorAll('[data-say]').forEach((b) => { b.onclick = () => copy(b.dataset.say); });
}
/* ---------------- export packages ---------------- */
async function renderExport(start = null) {
const presets = await api('/export/presets');
const all = presets.builtin.concat(presets.custom);
const blank = { name: 'My export', audience: '', intro: '', contact: '', all: {}, any: {}, pdf: { include: 'all', layout: 'detailed' }, files: { csv: true, json: false, photos: false }, show: { research: true } };
const spec = structuredClone(start || blank);
const tierOpts = Object.entries(META.tiers).map(([k, v]) => [k, v.split(' — ')[0]]);
const statusOpts = Object.entries(META.statuses).map(([k, v]) => [k, v.split(' — ')[0]]);
const g = (o, k, d = '') => (o && o[k] != null ? o[k] : d);
const list = (v) => (Array.isArray(v) ? v.join(', ') : v || '');
const checks = (name, opts, sel = []) => opts.map(([k, l]) => `<label class="row small" style="gap:6px;display:inline-flex;margin:0 12px 6px 0"><input type="checkbox" name="${name}" value="${k}" ${sel.includes(k) ? 'checked' : ''}> ${esc(l)}</label>`).join('');
const cb = (name, on, label) => `<label class="row small" style="gap:6px;display:inline-flex;margin:0 14px 6px 0"><input type="checkbox" name="${name}" ${on ? 'checked' : ''}> ${label}</label>`;
$app.innerHTML = `<h1>Export packages</h1>
<p class="muted">Put together a package for a specific audience — a dealer, a museum, an auction house — as one zip with a spreadsheet, a PDF catalogue with photos, and optionally all photos. Start from an example or build your own.</p>
<div class="grid" style="grid-template-columns:repeat(auto-fill,minmax(220px,1fr));gap:10px">
${all.map((p) => `<button class="card" data-preset="${esc(p.key)}" style="text-align:left;cursor:pointer;color:inherit;font:inherit">
<div style="font-size:1.4rem">${p.icon || '📦'}</div><b>${esc(p.name)}</b><div class="small muted">${esc(p.blurb || '')}</div>
${p.custom ? `<span class="small"><a href="#" data-delpreset="${esc(p.key)}">remove</a></span>` : ''}</button>`).join('')}
</div>
<div class="item-layout section" style="grid-template-columns:minmax(0,1.4fr) minmax(0,1fr)">
<form class="card grid" id="xf" style="gap:14px">
<div class="form">
<label class="f"><span>Package name</span><input name="name" value="${esc(spec.name)}"></label>
<label class="f"><span>Prepared for</span><input name="audience" value="${esc(g(spec, 'audience'))}" placeholder="e.g. Computer museum"></label>
<label class="f wide"><span>Introduction (on the PDF cover and in README)</span><textarea name="intro" rows="3">${esc(g(spec, 'intro'))}</textarea></label>
<label class="f wide"><span>Contact line</span><input name="contact" value="${esc(g(spec, 'contact'))}" placeholder="e.g. Julien — julien@example.com — 06 …"></label>
</div>
<div><h2 style="margin-bottom:4px">Items that match all of these</h2><p class="small muted" style="margin-top:0">Leave a field empty to not filter on it.</p>
<div class="form">
<label class="f wide"><span>Categories (comma-separated)</span><input name="all.categories" value="${esc(list(g(spec.all, 'categories')))}" placeholder="e.g. Books, Vinyl Records"></label>
<div class="wide row" style="gap:6px">${META.categories.slice(0, 24).map((c) => `<button type="button" class="btn small" data-addcat="${esc(c.category)}">${esc(c.category)} <span class="muted">${c.n}</span></button>`).join('')}</div>
<label class="f"><span>Search words</span><input name="all.q" value="${esc(g(spec.all, 'q'))}" placeholder="e.g. Commodore"></label>
<label class="f"><span>Locations (comma-separated)</span><input name="all.locations" value="${esc(list(g(spec.all, 'locations')))}"></label>
<label class="f"><span>Value from</span><input type="number" name="all.value_min" value="${esc(g(spec.all, 'value_min'))}"></label>
<label class="f"><span>Value up to</span><input type="number" name="all.value_max" value="${esc(g(spec.all, 'value_max'))}"></label>
<label class="f"><span>Year from</span><input type="number" name="all.year_from" value="${esc(g(spec.all, 'year_from'))}" placeholder="e.g. 1950"></label>
<label class="f"><span>Year up to</span><input type="number" name="all.year_to" value="${esc(g(spec.all, 'year_to'))}" placeholder="e.g. 1999"></label>
<div class="wide"><span class="small muted">Tier</span><br>${checks('all.tiers', tierOpts, g(spec.all, 'tiers', []))}</div>
<div class="wide"><span class="small muted">Status</span><br>${checks('all.statuses', statusOpts, g(spec.all, 'statuses', []))}</div>
<div class="wide">${cb('all.has_photos', g(spec.all, 'has_photos', false), 'only items with photos')}</div>
</div></div>
<div><h2 style="margin-bottom:4px">…and at least one of these <span class="small muted" style="font-weight:400">(optional)</span></h2>
<p class="small muted" style="margin-top:0">E.g. "notable OR made before 2000". Leave everything empty to skip.</p>
<div class="form">
<div class="wide">${cb('any.notable', g(spec.any, 'notable', false), 'marked notable')} ${cb('any.confidence_high', g(spec.any, 'confidence_high', false), 'AI is confident about it')}</div>
<label class="f"><span>Made before year</span><input type="number" name="any.year_before" value="${esc(g(spec.any, 'year_before'))}"></label>
<label class="f"><span>Made after year</span><input type="number" name="any.year_after" value="${esc(g(spec.any, 'year_after'))}"></label>
<label class="f"><span>Value at least</span><input type="number" name="any.value_min" value="${esc(g(spec.any, 'value_min'))}"></label>
<div class="wide"><span class="small muted">Tier</span><br>${checks('any.tiers', tierOpts, g(spec.any, 'tiers', []))}</div>
</div></div>
<div><h2 style="margin-bottom:4px">What goes in the zip</h2>
<div class="form">
<label class="f"><span>PDF catalogue with photos</span><select name="pdf.include">
${[['all', 'All selected items'], ['notable', 'Only notable items'], ['min_value', 'Items worth at least…'], ['top', 'The top N by value'], ['none', 'No PDF']].map(([k, l]) => `<option value="${k}" ${g(spec.pdf, 'include', 'all') === k ? 'selected' : ''}>${l}</option>`).join('')}</select></label>
<label class="f" id="pdfmin"><span>…worth at least</span><input type="number" name="pdf.min_value" value="${esc(g(spec.pdf, 'min_value'))}"></label>
<label class="f" id="pdftop"><span>…how many</span><input type="number" name="pdf.top" value="${esc(g(spec.pdf, 'top', 25))}"></label>
<label class="f"><span>PDF layout</span><select name="pdf.layout">
${[['detailed', 'Detailed — one item per page, up to 4 photos'], ['compact', 'Compact — three items per page']].map(([k, l]) => `<option value="${k}" ${g(spec.pdf, 'layout', 'detailed') === k ? 'selected' : ''}>${l}</option>`).join('')}</select></label>
<div class="wide">${cb('files.csv', g(spec.files, 'csv', true), 'spreadsheet (CSV) of all items')} ${cb('files.photos', g(spec.files, 'photos', false), 'all photos, full size')} ${cb('files.json', g(spec.files, 'json', false), 'JSON data file')}</div>
<div class="wide"><span class="small muted">Show to the recipient</span><br>
${cb('show.research', g(spec.show, 'research', true), 'research notes')} ${cb('show.values', g(spec.show, 'values', false), 'value indications')} ${cb('show.locations', g(spec.show, 'locations', false), 'storage locations')} ${cb('show.notes', g(spec.show, 'notes', false), 'internal notes from the team')}</div>
</div></div>
<div class="row"><button class="btn primary" id="build">⇩ Build & download zip</button><button type="button" class="btn" id="savepreset">Save as preset</button></div>
</form>
<div class="card" style="position:sticky;top:80px"><h2>Preview</h2><div id="pv"><p class="muted">Counting…</p></div></div>
</div>`;
const form = document.getElementById('xf');
const readSpec = () => {
const out = { all: {}, any: {}, pdf: {}, files: {}, show: {} };
for (const el of form.elements) {
if (!el.name) continue;
const [grp, key] = el.name.includes('.') ? el.name.split('.') : [null, el.name];
const target = grp ? out[grp] : out;
if (el.type === 'checkbox') {
if (['tiers', 'statuses'].includes(key)) { target[key] = target[key] || []; if (el.checked) target[key].push(el.value); } else target[key] = el.checked;
} else target[key] = el.value;
}
return out;
};
const syncPdf = () => {
const v = form['pdf.include'].value;
document.getElementById('pdfmin').classList.toggle('hidden', v !== 'min_value');
document.getElementById('pdftop').classList.toggle('hidden', v !== 'top');
};
let t;
const refresh = () => {
syncPdf();
clearTimeout(t);
t = setTimeout(async () => {
const p = await api('/export/preview', { json: readSpec() });
document.getElementById('pv').innerHTML = `
<div class="grid stats" style="grid-template-columns:1fr 1fr 1fr;gap:8px">
<div class="stat"><div class="k">Items</div><div class="v">${p.items}</div></div>
<div class="stat"><div class="k">In PDF</div><div class="v">${p.pdf_items}</div></div>
<div class="stat"><div class="k">Photos</div><div class="v">${p.photos}</div></div></div>
${p.categories.length ? `<p class="small muted" style="margin-top:12px">${p.categories.map(([c, n]) => `${esc(c)} ${n}`).join(' · ')}</p>` : ''}
${p.sample.length ? `<ul class="feed">${p.sample.map((s) => `<li><a href="#/item/${s.id}" target="_blank">#${s.id}</a> ${esc(s.title)}${s.year ? ` <span class="muted">· ${esc(s.year)}</span>` : ''}${s.tier === 'notable' ? ' ★' : ''}</li>`).join('')}</ul>${p.items > p.sample.length ? `<p class="small muted">…and ${p.items - p.sample.length} more</p>` : ''}`
: '<p class="muted">Nothing matches yet — loosen the filters.</p>'}`;
}, 250);
};
form.addEventListener('input', refresh);
form.addEventListener('change', refresh);
refresh();
$app.querySelectorAll('[data-addcat]').forEach((b) => { b.onclick = () => {
const inp = form['all.categories'];
const cur = inp.value.split(',').map((x) => x.trim()).filter(Boolean);
if (!cur.includes(b.dataset.addcat)) cur.push(b.dataset.addcat);
inp.value = cur.join(', '); refresh();
}; });
$app.querySelectorAll('[data-preset]').forEach((b) => { b.onclick = (e) => {
if (e.target.closest('[data-delpreset]')) return;
const p = all.find((x) => x.key === b.dataset.preset);
renderExport({ ...blank, ...structuredClone(p.spec), name: p.name, audience: p.audience || p.spec.audience || '' });
}; });
$app.querySelectorAll('[data-delpreset]').forEach((a) => { a.onclick = async (e) => {
e.preventDefault(); e.stopPropagation();
if (!confirm('Remove this saved preset?')) return;
await api(`/export/presets/${encodeURIComponent(a.dataset.delpreset)}`, { method: 'DELETE' }); renderExport(readSpec());
}; });
document.getElementById('savepreset').onclick = async () => {
const name = prompt('Name for this preset', form.name.value);
if (!name) return;
await api('/export/presets', { json: { name, spec: readSpec() } });
toast('Preset saved'); renderExport(readSpec());
};
form.onsubmit = async (e) => {
e.preventDefault();
const btn = document.getElementById('build');
btn.disabled = true; btn.textContent = 'Building…';
try {
const { url } = await api('/export', { json: readSpec() });
const a = document.createElement('a'); a.href = url; a.download = ''; document.body.appendChild(a); a.click(); a.remove();
toast('Your download starts in a moment — big exports with photos can take a while');
} catch (err) { toast(err.message, true); }
setTimeout(() => { btn.disabled = false; btn.textContent = '⇩ Build & download zip'; }, 2500);
};
}
/* ---------------- settings ---------------- */
async function renderSettings() {
const s = await api('/settings');
const L = s.question_ladder;
const cur = s.currency || 'EUR';
$app.innerHTML = `<h1>Settings</h1>
<form class="card form" id="sf" style="max-width:760px">
<label class="f wide"><span>Collection name</span><input name="collection_name" value="${esc(s.collection_name)}"></label>
<label class="f"><span>Currency</span><input name="currency" value="${esc(s.currency)}" placeholder="EUR"></label>
<label class="f"><span>Country / region of the collection</span><input name="region" value="${esc(s.region || '')}" placeholder="e.g. Netherlands"></label>
<p class="wide small muted" style="margin:-4px 0 0">The AI researches internationally, but gives local markets extra weight (e.g. in the Netherlands also Marktplaats and eBay.de, not only eBay.nl).</p>
<div class="wide"><h2 style="margin:8px 0 2px">AI questions & research depth</h2>
<p class="small muted" style="margin:0">Keeps things manageable with thousands of items. The server enforces these limits — the AI can't ask more than allowed.</p></div>
<label class="f"><span>Questions to the team</span><select name="questions_mode">
${[['on', 'On — follow the steps below'], ['off', 'Never ask']].map(([k, l]) => `<option value="${k}" ${(s.questions_mode === 'off' ? 'off' : 'on') === k ? 'selected' : ''}>${l}</option>`).join('')}</select></label>
<label class="f"><span>Deep research only from (${esc(cur)}, 0 = always)</span><input type="number" min="0" name="deep_research_min_value" value="${esc(s.deep_research_min_value)}"></label>
<div class="wide">
<span class="small muted" style="text-transform:uppercase;letter-spacing:.05em">Questions per item, by the AI's value estimate</span>
<table style="margin-top:6px"><thead><tr><th>From (${esc(cur)})</th><th>To</th><th>Max questions</th><th></th></tr></thead><tbody id="ladder"></tbody></table>
<button type="button" class="btn small" id="addstep" style="margin-top:6px">+ Add step</button>
<table style="margin-top:14px"><tr><th style="width:50%">When…</th><th>Max questions</th></tr>
${[['unsure', 'the AI is unsure what it is (low confidence)'], ['unknown', 'there is no value estimate yet'], ['notable', 'the item is marked notable']].map(([k, l]) => `
<tr><td>${l}</td><td><input type="number" min="0" data-special="${k}" value="${L[k] ?? ''}" placeholder="unlimited" style="max-width:140px"></td></tr>`).join('')}
</table>
<p class="small muted" style="margin-top:6px">Leave "Max questions" empty for unlimited. An item gets whichever applicable rule allows the most. Single items can be excused with "Skip — don't ask again".</p>
</div>
<label class="f wide"><span>Extra guidance for the AI</span><textarea name="ai_guidance" rows="6" placeholder="e.g. We are in the Netherlands and prefer selling on Marktplaats. Anything Apple or Commodore should be researched carefully. Don't bother pricing cables.">${esc(s.ai_guidance)}</textarea></label>
<div class="wide row"><span class="spacer"></span><button class="btn primary">Save</button></div>
</form>
<div class="card section" style="max-width:760px"><h2>Data</h2>
<p><a class="btn" href="/api/export.csv">⇩ Export everything as CSV</a></p>
<p class="small muted">All data (database + photos) lives in the server's <code>data/</code> folder — back that folder up.</p>
</div>`;
const tbody = document.getElementById('ladder');
const drawLadder = (bands) => {
bands.sort((a, b) => a.from - b.from);
tbody.innerHTML = bands.map((b, i) => `<tr data-i="${i}">
<td><input type="number" min="0" class="lfrom" value="${b.from}" ${i === 0 ? 'readonly title="The first step always starts at 0"' : ''} style="max-width:140px"></td>
<td class="muted">${bands[i + 1] ? `up to ${bands[i + 1].from}` : 'and up'}</td>
<td><input type="number" min="0" class="lmax" value="${b.max ?? ''}" placeholder="unlimited" style="max-width:140px"></td>
<td>${i === 0 ? '' : '<button type="button" class="btn small" data-rmstep>✕</button>'}</td></tr>`).join('');
};
const readLadder = () => [...tbody.querySelectorAll('tr')].map((tr) => ({
from: Number(tr.querySelector('.lfrom').value) || 0,
max: tr.querySelector('.lmax').value === '' ? null : Number(tr.querySelector('.lmax').value),
}));
drawLadder(L.bands.map((b) => ({ ...b })));
tbody.addEventListener('change', (e) => { if (e.target.classList.contains('lfrom')) drawLadder(readLadder()); });
tbody.addEventListener('click', (e) => {
const rm = e.target.closest('[data-rmstep]'); if (!rm) return;
const bands = readLadder(); bands.splice(Number(rm.closest('tr').dataset.i), 1); drawLadder(bands);
});
document.getElementById('addstep').onclick = () => {
const bands = readLadder(); const last = bands[bands.length - 1];
bands.push({ from: (last?.from || 0) * 2 || 100, max: last?.max ?? null }); drawLadder(bands);
};
document.getElementById('sf').onsubmit = async (e) => {
e.preventDefault();
const body = Object.fromEntries(new FormData(e.target).entries());
body.question_ladder = { bands: readLadder() };
document.querySelectorAll('[data-special]').forEach((inp) => { body.question_ladder[inp.dataset.special] = inp.value === '' ? null : Number(inp.value); });
await api('/settings', { method: 'PUT', json: body });
META = await api('/meta'); toast('Saved'); renderSettings();
};
}
boot().catch((e) => { $app.innerHTML = `<div class="empty">Could not load: ${esc(e.message)}</div>`; });