Files
indexipro/server/public/app.js
T
juli cbb76dbf19 Simpler AI connection that works with any AI app
- Connect AI: make one address, paste it as a custom connection in any
  MCP-capable app, then copy a short start message into a new chat
- Start message holds no secret; page shows when the AI has connected
- Dashboard gets a Start AI research button
2026-11-12 17:59:27 +01:00

797 lines
55 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'], ['/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 === '/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>
</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]}`);
};
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>
<form id="ans" class="grid"><textarea name="text" placeholder="Your answer (or add photos above)"></textarea><button class="btn primary">Send answer</button></form></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>${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); }
};
document.getElementById('ans')?.addEventListener('submit', async (e) => {
e.preventDefault();
await api(`/items/${id}/answer`, { json: { text: e.target.text.value } });
toast('Thanks! The AI will pick it up again.');
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 ---------------- */
async function renderTodo() {
const r = await api('/todo');
$app.innerHTML = `<h1>Questions from the AI</h1>
<p class="muted">The AI couldn't figure these out from the photos alone. Answer in the phone app (To-do tab), or click an item here to add photos or type an answer.</p>
${r.items.length ? `<div class="grid" style="gap:10px">${r.items.map((it) => `
<a class="card row" href="#/item/${it.id}" style="color:inherit">
<div style="width:72px;height:72px;border-radius:10px;background:var(--bg2) url(${thumb(it.cover_id)}) center/cover"></div>
<div style="flex:1;min-width:200px"><div class="mono muted">#${it.id} ${it.location ? `· 📍 ${esc(it.location)}` : ''}</div>
<div><b>${esc(it.question || '')}</b></div><div class="small muted">${esc(it.title || '')}</div></div></a>`).join('')}</div>`
: '<div class="empty"><div class="big">✅</div>No open questions.</div>'}`;
}
/* ---------------- 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. You can hide the value indications per link and 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>
<button class="btn primary">Create link</button>
</form>
${shares.length ? `<div class="tablewrap"><table><tr><th>For</th><th>Link</th><th>Values</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' : ''}> shown</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 } });
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-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 = [
['ChatGPT', 'On chatgpt.com (on a computer): in the chat box click <b>+</b> → <b>Plugins</b> → <b>Add custom MCP server</b>, paste the address, confirm.'],
['Claude', 'Settings → <b>Connectors</b> → <b>Add custom connector</b>, paste the address, click Add.'],
['Other apps', 'Look for <b>Connectors</b>, <b>Plugins</b>, <b>Integrations</b>, <b>Tools</b> or <b>MCP servers</b> — often under the <b>+</b> button in the chat box or in Settings. Choose "custom" / "add your own", paste the address. No login or API key fields need to be filled in.'],
['Developers', 'It\'s a standard Streamable-HTTP MCP server. The key can also go in an <code>Authorization: Bearer</code> header on <code>/mcp</code>. Claude Code: <code>claude mcp add --transport http indexipro &lt;address&gt;</code>'],
];
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 is connected ✅' : '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 — Make your connection</h2>
<div id="conn"><button class="btn primary" id="make">Make my connection</button>
<p class="small muted" style="margin-top:8px">You get one private address. You only do this once per AI account.</p></div>
</div>
<div class="card section">
<h2>2 — Add it to your AI app</h2>
<p>In your AI app (ChatGPT, Claude, or any other app that supports <b>connectors</b> / <b>MCP</b>), add a new custom connection, name it <b>IndexiPro</b> and paste the address. That's all — no login, no other settings.</p>
<details style="margin-top:10px"><summary class="small" style="cursor:pointer">Where exactly?</summary>
<table style="margin-top:8px">${AI_HINTS.map(([n, h]) => `<tr><th style="width:22%">${n}</th><td class="small">${h}</td></tr>`).join('')}</table>
</details>
</div>
<div class="section"><h2 style="margin-left:4px">3 — Start</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>Last used</th><th>Calls</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.last_used ? ago(k.last_used) : '<span class="muted">not yet</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">"Last used" fills in as soon as the AI really connects. 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('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 = `
<p>Your private address (copied already):</p>
<div class="copy"><input readonly value="${esc(k.url)}" style="font-size:1rem"><button class="btn primary" id="cpaddr">📋 Copy</button></div>
<p class="small muted" style="margin-top:8px">It's shown only now, so paste it into your AI app before leaving this page. Don't share it — anyone with it can change the collection. Lost it? Just make a new one.</p>`;
document.getElementById('cpaddr').onclick = () => copy(k.url);
copy(k.url);
});
$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); });
}
/* ---------------- settings ---------------- */
async function renderSettings() {
const s = await api('/settings');
$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>
<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>`;
document.getElementById('sf').onsubmit = async (e) => {
e.preventDefault();
await api('/settings', { method: 'PUT', json: Object.fromEntries(new FormData(e.target).entries()) });
META = await api('/meta'); toast('Saved');
};
}
boot().catch((e) => { $app.innerHTML = `<div class="empty">Could not load: ${esc(e.message)}</div>`; });