Console: Polish screens for sources, library, standards and model providers (M2)

Replaces the scaffold's example Record screens. Documents the module in
README/CLAUDE.md, credits compass-ingestion and pypdfium2, and points the
managed-db README at the platform rendering of provision.sql.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-12 19:51:10 +01:00
co-authored by Claude Opus 5.5
parent 5019d29d52
commit 16cebbd875
5 changed files with 508 additions and 106 deletions
+25 -3
View File
@@ -4,7 +4,11 @@ Guidance for Claude Code when working in this repository.
## What this is
**Lexicon** — A self-hosted management console. Built on **dredd-core**, the shared substrate of this app family:
**Lexicon** — the family's **clause library** (Biblioteka klauzul), split out of Compass (work
package M2): library sources (an uploaded file or a pinned Galena document, `library_source`),
the clauses cut from them (`library_clause`, full-text searchable), the catalog's clause types
(typed by a model, corrected by a person) and the **standards** (`clause_standard`) that Arbiter
reads. Built on **dredd-core**, the shared substrate of this app family:
identity, sessions, auth, the access-control resolver, the org tree, audit and the security
primitives are an installed dependency, not source in this repo. Stack: **FastAPI + SQLAlchemy 2
+ Alembic + PostgreSQL 16 / 17**, Argon2id auth + server-side cookie sessions, a
@@ -300,5 +304,23 @@ node --check frontend/app.js # ALWAYS after editing the console
## Status
Scaffolded skeleton on dredd-core v0.22.0. The `example` entity (`Record`) is a worked seam —
model → migration → service → router → console screen — to copy for the real domain, then delete.
M2 port (2026-11-12) on dredd-core v0.22.0. The scaffold's `example` entity is gone. Ported from
Compass: `models/library.py`, `services/library.py`, the typing half of `services/catalog.py`,
`routers/library.py`, `agents/catalog.py` (typing only), and the clause cutter from
`compass_analysis/clauses.py` + `locate.py` (copied into `services/cutting.py`; it should move into
`compass_ingestion`). The model-provider stack is copied from Arbiter.
Rules specific to this module:
- **Lexicon never imports or calls the engine** (`compass_analysis`, the contract runs).
`tests/test_ingestion_boundary.py` enforces it; text extraction comes from `compass_ingestion`,
pinned by an immutable commit SHA in `backend/requirements.txt` (no tag exists yet; repin to a
tag once L1 merges). `pypdfium2` replaces PyMuPDF (AGPL); never reintroduce fitz.
- **Cutting happens in the request**, not a queue: a background thread holds no token with which to
read a Galena document. Typing is a background thread (`catalog.track`), gated by
`TYPING_ENABLED` and the `CATALOG_MODEL` setting.
- **Visibility:** a source is readable by its owner, by moderators, and by everyone once `shared`.
Standards are written by moderators and read by every user; with the library they are Arbiter's
read API (`GET /standards`, `/standards/{id}`, `/library/types`, `/sources/{id}/library`).
- On the platform the model providers are the hub's (`models.SHARED_TABLES`); `0005` drops empty
local copies and refuses if they hold rows.
+3
View File
@@ -18,6 +18,9 @@ gate (`backend/scripts/license_gate.py`) fails the build on GPL, AGPL or SSPL.
| [argon2-cffi](https://github.com/hynek/argon2-cffi) | MIT | Argon2id password hashing |
| [httpx](https://www.python-httpx.org) | BSD-3-Clause | the one outbound HTTP client |
| [OpenTelemetry Python](https://opentelemetry.io) | Apache-2.0 | optional tracing, off by default |
| compass-ingestion / compass-schemas (Alpaq92/compass-contract-hub, private) | Apache-2.0 | text extraction from PDF/DOCX, pinned by commit |
| [pypdfium2](https://github.com/pypdfium2-team/pypdfium2) | Apache-2.0 / BSD-3-Clause (PDFium) | PDF text, replacing the AGPL PyMuPDF |
| [cryptography](https://cryptography.io) | Apache-2.0 / BSD-3-Clause | sealing model-provider keys |
| [PostgreSQL](https://www.postgresql.org) | PostgreSQL License | the database |
## Console
+5 -1
View File
@@ -1,6 +1,10 @@
# Lexicon
A self-hosted management console.
**Biblioteka klauzul**: the clause library of the family. Upload a model contract (PDF, DOCX, TXT,
MD) or pin a document from Galena; Lexicon cuts it into clauses (§ and decimal numbering), indexes
them for full-text search, has a model sort them onto typed shelves (a person can correct any
type), and keeps the **standards** (per clause type: the rule, the model wording and the fallback)
that Arbiter checks contracts against. Lexicon never runs the analysis engine itself.
Self-hosted and single-tenant, built on **dredd-core** — the shared substrate this app family
installs as a dependency rather than copies.
+6 -11
View File
@@ -90,19 +90,14 @@ avoids.
```bash
python -m dredd_core.managed provision --sql-only --schema lexicon --app-role lexicon_app \
--migrator-role lexicon_migrator --output db/managed/provision.sql
--migrator-role lexicon_migrator --identity-schema dredd --identity-owner atrium_migrator \
--output db/managed/provision.sql
```
The committed file is the **standalone** rendering, which is what a generated app needs on day one.
Joining a platform adds two flags to that command, and therefore changes the file — which is exactly
why CI compares it. See section 6.
**Joining Atrium (the platform) means re-rendering with the identity flags**, exactly as Galena,
Sygna and Counsel ship theirs, and adding the same two flags to CI's `--check-file` step:
```bash
python -m dredd_core.managed provision --sql-only --schema lexicon --app-role lexicon_app --migrator-role lexicon_migrator --identity-schema dredd --identity-owner atrium_migrator --output db/managed/provision.sql
```
The committed file is the **platform** rendering: Lexicon is split out of Compass to run as a
module of Atrium, so it ships with the identity flags, exactly as Galena, Sygna and Counsel do, and
CI's `--check-file` step passes the same two flags. A standalone deployment renders without
`--identity-schema` / `--identity-owner` (and must then not use the committed file). See section 6.
(plus every `--extension` this app's `0001` needs). The platform's `deploy/push.sh` checks it: before
it provisions anything, it re-renders each module's `provision.sql` from that module's checkout with
+469 -91
View File
@@ -198,11 +198,31 @@ const I18N = {
'Język: polski': 'Language: Polish',
'Język: angielski': 'Language: English',
'Pulpit': 'Dashboard',
'Rekordy': 'Records',
'Źródła': 'Sources',
'Biblioteka': 'Library',
'Standardy': 'Standards',
'Dostawcy modeli': 'Model providers',
'Klauzule': 'Clauses',
'Nowe źródło': 'New source',
'Nowy standard': 'New standard',
'Tytuł': 'Title',
'Zmień typ': 'Change type',
'Potnij ponownie': 'Re-cut',
'Odśwież z Galeny': 'Refresh from Galena',
'Nowy plik': 'New file',
'Pobierz': 'Download',
'Bez typu': 'Untyped',
'Brak źródeł.': 'No sources yet.',
'Brak standardów.': 'No standards yet.',
'Wybierz plik.': 'Choose a file.',
'Zasada': 'Rule',
'Wzorcowe brzmienie': 'Model wording',
'Stanowisko rezerwowe': 'Fallback position',
'Przykłady': 'Examples',
'Model katalogu': 'Catalog model',
'Administracja': 'Administration',
'Użytkownicy': 'Users',
'Przestrzenie': 'Workspaces',
'Nowy rekord': 'New record',
'Nazwa': 'Name',
'Notatka': 'Note',
'Utworzono': 'Created',
@@ -212,7 +232,6 @@ const I18N = {
'Edytuj': 'Edit',
'Wczytywanie…': 'Loading…',
'Brak wyników': 'Nothing found',
'Brak rekordów.': 'No records yet.',
'Nie znaleziono strony.': 'Page not found.',
'otwarty': 'open',
'zamknięty': 'done',
@@ -372,7 +391,9 @@ const isModerator = () => !!(state.user && state.user.is_moderator);
/* ── navigation ─────────────────────────────────────────────────────────── */
const NAV = [
{ hash: '#/', icon: 'dashboard', label: 'Pulpit' },
{ hash: '#/records', icon: 'file', label: 'Rekordy' },
{ hash: '#/sources', icon: 'file', label: 'Źródła', badge: 'sources' },
{ hash: '#/library', icon: 'search', label: 'Biblioteka' },
{ hash: '#/standards', icon: 'license', label: 'Standardy' },
];
function renderNav(counts) {
@@ -385,7 +406,8 @@ function renderNav(counts) {
return `<a class="nav-item ${on ? 'on' : ''}" href="${n.hash}">${svg(ICN[n.icon])}<span>${esc(n.label)}</span>${badge}</a>`;
}).join('');
$('navAdmin').innerHTML = isModerator()
? `<a class="nav-item ${cur.startsWith('#/admin') ? 'on' : ''}" href="#/admin">${svg(ICN.settings)}<span>Administracja</span></a>`
? `<a class="nav-item ${cur.startsWith('#/providers') ? 'on' : ''}" href="#/providers">${svg(ICN.globe)}<span>Dostawcy modeli</span></a>`
+ `<a class="nav-item ${cur.startsWith('#/admin') ? 'on' : ''}" href="#/admin">${svg(ICN.settings)}<span>Administracja</span></a>`
: '';
localize($('sidebar'));
}
@@ -426,8 +448,12 @@ async function router() {
C.innerHTML = '<div class="faint">Wczytywanie…</div>';
try {
if (!seg.length) await viewDashboard(C);
else if (seg[0] === 'records' && seg[1]) await viewRecord(C, seg[1]);
else if (seg[0] === 'records') await viewRecords(C, q);
else if (seg[0] === 'sources' && seg[1]) await viewSource(C, seg[1]);
else if (seg[0] === 'sources') await viewSources(C, q);
else if (seg[0] === 'library') await viewLibrary(C, q);
else if (seg[0] === 'standards' && seg[1]) await viewStandard(C, seg[1]);
else if (seg[0] === 'standards') await viewStandards(C, q);
else if (seg[0] === 'providers') await viewProviders(C);
else if (seg[0] === 'admin') await viewAdmin(C);
else C.innerHTML = '<div class="empty">Nie znaleziono strony.</div>';
} catch (ex) {
@@ -439,138 +465,256 @@ async function router() {
closeDrawer();
}
/* A multipart write (an uploaded file). `api()` speaks JSON only; this is the same request with a
FormData body, the same credentials and the same error shape. */
async function apiForm(path, form) {
const opt = { method: 'POST', headers: {}, credentials: 'same-origin', body: form };
if (state.token) opt.headers.Authorization = 'Bearer ' + state.token;
const res = await fetch(API + path, opt);
const text = await res.text();
let data = null;
if (text) { try { data = JSON.parse(text); } catch { data = { detail: text }; } }
if (!res.ok) {
const err = new Error((data && (data.detail || data.title)) || ('HTTP ' + res.status));
err.status = res.status;
err.problem = data;
throw err;
}
return data;
}
/* The closed list of clause types, fetched once. */
async function clauseTypes() {
if (!state.types) state.types = await api('GET', '/library/types');
return state.types;
}
function typeLabel(key) {
const t = (state.types || []).find((x) => x.type === key);
return t ? t.label : key;
}
const STATE_LABEL = {
queued: 'w kolejce', running: 'w toku', done: 'gotowe', ready: 'gotowe',
failed: 'błąd', empty: 'brak klauzul',
};
function stateChip(s) {
if (!s) return '<span class="chip">—</span>';
const cls = (s === 'done' || s === 'ready') ? 'ok' : s === 'failed' ? 'err' : '';
return `<span class="chip ${cls}">${esc(STATE_LABEL[s] || s)}</span>`;
}
/* ── dashboard ──────────────────────────────────────────────────────────── */
async function viewDashboard(C) {
const d = await api('GET', '/dashboard');
const c = d.cards || {};
state.counts = { records: c.total };
state.counts = { sources: c.sources };
setCrumb([{ label: 'Pulpit' }]);
const tiles = [
{ k: 'Wszystkich', v: c.total ?? 0, cls: '' },
{ k: 'otwarty', v: c.open ?? 0, cls: '' },
{ k: 'zamknięty', v: c.done ?? 0, cls: '' },
{ k: 'Źródła', v: c.sources ?? 0 },
{ k: 'Klauzule', v: c.clauses ?? 0 },
{ k: 'Dokumenty z Galeny', v: c.documents ?? 0 },
{ k: 'Bez typu', v: c.untyped ?? 0 },
];
C.innerHTML = pageHead('Pulpit', state.user.full_name || state.user.email,
`<button class="btn primary" onclick="openRecordNew()">${svg(ICN.plus)}Nowy rekord</button>`)
+ `<div class="tiles">${tiles.map((t) => `<div class="tile ${t.cls}"><div class="k">${esc(t.k)}</div><div class="v">${esc(String(t.v))}</div></div>`).join('')}</div>`
+ `<div class="card" style="margin-top:14px"><h3>Rekordy<span class="n">${(d.recent || []).length}</span></h3>${recordTable(d.recent || [])}</div>`;
`<button class="btn primary" onclick="openSourceNew()">${svg(ICN.plus)}Nowe źródło</button>`)
+ `<div class="tiles">${tiles.map((t) => `<div class="tile"><div class="k">${esc(t.k)}</div><div class="v">${esc(String(t.v))}</div></div>`).join('')}</div>`
+ `<div class="card" style="margin-top:14px"><h3>Źródła<span class="n">${(d.recent || []).length}</span></h3>${sourceTable(d.recent || [])}</div>`;
}
function statusChip(s) {
const cls = s === 'done' ? 'ok' : '';
const label = s === 'done' ? 'zamknięty' : 'otwarty';
return `<span class="chip ${cls}">${esc(label)}</span>`;
}
function recordTable(rows) {
if (!rows.length) return '<div class="empty">Brak rekordów.</div>';
function sourceTable(rows) {
if (!rows.length) return '<div class="empty">Brak źródeł.</div>';
return `<div class="tablewrap"><table class="rt"><thead><tr>
<th>Nazwa</th><th>Status</th><th>Utworzono</th>
</tr></thead><tbody>${rows.map((r) => `<tr class="click" onclick="location.hash='#/records/${encodeURIComponent(r.id)}'">
<td><div>${esc(r.name)}${r.note ? `<div class="faint tiny">${esc(r.note)}</div>` : ''}</div></td>
<td${lbl('Status')}>${statusChip(r.status)}</td>
<th>Tytuł</th><th>Klauzule</th><th>Typowanie</th><th>Utworzono</th>
</tr></thead><tbody>${rows.map((r) => `<tr class="click" onclick="location.hash='#/sources/${encodeURIComponent(r.id)}'">
<td><div>${esc(r.title)}${r.shared ? ' <span class="chip">udostępnione</span>' : ''}${r.status === 'archived' ? ' <span class="chip">archiwum</span>' : ''}<div class="faint tiny">${esc(r.name || '')}</div></div></td>
<td${lbl('Klauzule')}><div class="row">${esc(String((r.library && r.library.count) || 0))} ${stateChip(r.library && r.library.state)}</div></td>
<td${lbl('Typowanie')}>${stateChip(r.typing_state)}</td>
<td class="faint tiny"${lbl('Utworzono')}>${fmtDate(r.created_at)}</td>
</tr>`).join('')}</tbody></table></div>`;
}
/* ── records ────────────────────────────────────────────────────────────── */
async function viewRecords(C, q) {
/* ── sources ────────────────────────────────────────────────────────────── */
async function viewSources(C, q) {
const params = new URLSearchParams();
if (q.q) params.set('q', q.q);
if (q.status) params.set('status', q.status);
const rows = await api('GET', '/records' + (params.toString() ? '?' + params : ''));
setCrumb([{ label: 'Rekordy' }]);
const rows = await api('GET', '/sources' + (params.toString() ? '?' + params : ''));
setCrumb([{ label: 'Źródła' }]);
C.innerHTML = pageHead('Rekordy', rows.length + '',
`<button class="btn primary" onclick="openRecordNew()">${svg(ICN.plus)}Nowy rekord</button>`)
C.innerHTML = pageHead('Źródła', rows.length + '',
`<button class="btn primary" onclick="openSourceNew()">${svg(ICN.plus)}Nowe źródło</button>`)
+ `<div class="toolbar">
<input type="search" id="rq" placeholder="Szukaj…" value="${esc(q.q || '')}" />
<select id="rstatus">
${['', 'open', 'done'].map((s) => `<option value="${s}" ${q.status === s ? 'selected' : ''}>${s ? (s === 'done' ? 'zamknięty' : 'otwarty') : '—'}</option>`).join('')}
${[['', '—'], ['active', 'aktywne'], ['archived', 'archiwum']].map(([v, l]) => `<option value="${v}" ${(q.status || '') === v ? 'selected' : ''}>${esc(l)}</option>`).join('')}
</select>
</div>`
+ (rows.length ? `<div class="card">${recordTable(rows)}</div>` : '<div class="empty">Brak rekordów.</div>');
+ `<div class="card">${sourceTable(rows)}</div>`;
const go = () => {
const p = new URLSearchParams();
if ($('rq').value.trim()) p.set('q', $('rq').value.trim());
if ($('rstatus').value) p.set('status', $('rstatus').value);
location.hash = '#/records' + (p.toString() ? '?' + p : '');
location.hash = '#/sources' + (p.toString() ? '?' + p : '');
};
$('rq').addEventListener('change', go);
$('rstatus').addEventListener('change', go);
}
async function viewRecord(C, id) {
const r = await api('GET', '/records/' + encodeURIComponent(id));
setCrumb([{ label: 'Rekordy', href: '#/records' }, { label: r.name }]);
async function viewSource(C, id) {
const sid = encodeURIComponent(id);
const [s, lib] = await Promise.all([
api('GET', '/sources/' + sid), api('GET', '/sources/' + sid + '/library'), clauseTypes()]);
state._lib = lib;
setCrumb([{ label: 'Źródła', href: '#/sources' }, { label: s.title }]);
const doc = s.kind === 'document';
const ref = s.ref || {};
const where = doc ? `${ref.path || ''} @ ${ref.version || ''}` : (s.name || '');
const canDelete = TENANCY !== 'nodes' || r.role === 'manager';
C.innerHTML = pageHead(r.name, r.path || '',
`<button class="btn" onclick="openRecordEdit('${esc(r.id)}')">${svg(ICN.check)}Edytuj</button>`
+ (canDelete ? `<button class="btn danger" onclick="deleteRecord('${esc(r.id)}')">${svg(ICN.trash)}Usuń</button>` : ''))
C.innerHTML = pageHead(s.title, where,
`<a class="btn" href="api/v1/sources/${sid}/raw?download=true">Pobierz</a>`
+ `<button class="btn" onclick="openSourceEdit('${esc(s.id)}')">${svg(ICN.check)}Edytuj</button>`
+ `<button class="btn" onclick="recutSource('${esc(s.id)}')">Potnij ponownie</button>`
+ (doc
? `<button class="btn" onclick="openSourceRefresh('${esc(s.id)}')">Odśwież z Galeny</button>`
: `<button class="btn" onclick="openSourceFile('${esc(s.id)}')">Nowy plik</button>`)
+ `<button class="btn danger" onclick="deleteSource('${esc(s.id)}')">${svg(ICN.trash)}Usuń</button>`)
+ `<div class="card"><div class="grid3">
${field('Status', r.status === 'done' ? 'zamknięty' : 'otwarty')}
${field('Utworzono', fmtDateTime(r.created_at))}
${field('Rodzaj', doc ? 'dokument z Galeny' : 'plik')}
${field('Wersja źródła', s.revision)}
${field('Udostępnione', s.shared ? 'tak' : 'nie')}
${field('Status', s.status === 'archived' ? 'archiwum' : 'aktywne')}
${field('Klauzule', lib.count)}
${field('Utworzono', fmtDateTime(s.created_at))}
</div>
${r.note ? `<div style="margin-top:14px"><div class="tiny faint">Notatka</div><div>${esc(r.note)}</div></div>` : ''}
</div>`;
<div class="row" style="margin-top:10px">${stateChip(lib.state)} ${stateChip(lib.typing_state)}</div>
${lib.reason ? `<div class="banner warn" style="margin-top:10px">${esc(lib.reason)}</div>` : ''}
${lib.typing_reason ? `<div class="banner warn" style="margin-top:10px">${esc(lib.typing_reason)}</div>` : ''}
${s.note ? `<div style="margin-top:14px"><div class="tiny faint">Notatka</div><div>${esc(s.note)}</div></div>` : ''}
</div>`
+ `<div class="card"><h3>Klauzule<span class="n">${lib.clauses.length}</span></h3>
${lib.clauses.length ? lib.clauses.map((c) => clauseBlock(c, s.id)).join('') : '<div class="empty">Brak klauzul.</div>'}
</div>`;
}
function containerOptions(selected) {
return state.containers.map((n) =>
`<option value="${esc(n.id)}" ${n.id === selected ? 'selected' : ''}>${esc(n.path)}</option>`).join('');
function typeChips(types, source) {
const chips = (types || []).map((t) => `<span class="chip">${esc(typeLabel(t))}</span>`).join(' ');
const by = source === 'person' ? ' <span class="faint tiny">(ręcznie)</span>' : '';
return (chips || '<span class="faint tiny">bez typu</span>') + by;
}
function openRecordNew() {
const where = TENANCY === 'nodes'
? `<label class="field" style="margin-top:12px">Przestrzenie
<select id="rcParent">${containerOptions()}</select></label>`
: '';
modal('Nowy rekord', '',
`<label class="field">Nazwa<input id="rcName" /></label>
<label class="field" style="margin-top:12px">Notatka<textarea id="rcNote"></textarea></label>
${where}`,
function clauseBlock(c, sourceId) {
return `<div class="clause" style="padding:10px 0;border-top:1px solid var(--line)">
<div class="row"><b>${esc(c.label || '')}</b>${c.page ? ` <span class="faint tiny">s. ${esc(String(c.page))}</span>` : ''}
<span style="flex:1"></span>${typeChips(c.types, c.type_source)}
${sourceId ? `<button class="btn" onclick="openClauseTypes('${esc(sourceId)}', ${Number(c.position)})">Zmień typ</button>` : ''}
</div>
<div class="tiny" style="white-space:pre-wrap;margin-top:6px">${esc(c.text || '')}</div>
</div>`;
}
async function openClauseTypes(sourceId, position) {
const types = await clauseTypes();
const c = ((state._lib && state._lib.clauses) || []).find((x) => x.position === position) || {};
const opts = (sel) => `<option value="">—</option>` + types.map((t) =>
`<option value="${esc(t.type)}" ${t.type === sel ? 'selected' : ''}>${esc(t.label)}</option>`).join('');
const cur = c.types || [];
modal('Zmień typ', c.label || '',
`<label class="field">Typ<select id="ctA">${opts(cur[0])}</select></label>
<label class="field" style="margin-top:12px">Drugi typ (opcjonalnie)<select id="ctB">${opts(cur[1])}</select></label>`,
`<button class="btn" onclick="closeModal()">Anuluj</button>
<button class="btn primary" onclick="saveRecordNew()">Zapisz</button>`);
<button class="btn primary" onclick="saveClauseTypes('${esc(sourceId)}', ${Number(position)}, ${Number(c.revision) || 'null'})">Zapisz</button>`);
}
function saveRecordNew() {
function saveClauseTypes(sourceId, position, revision) {
guard(async () => {
const body = { name: $('rcName').value, note: $('rcNote').value || null };
if (TENANCY === 'nodes') body.parent_id = $('rcParent') ? $('rcParent').value : null;
const r = await api('POST', '/records', body);
const picked = [$('ctA').value, $('ctB').value].filter(Boolean);
await api('PUT', '/sources/' + encodeURIComponent(sourceId) + '/library/clauses/' + position + '/types',
{ types: [...new Set(picked)], revision });
closeModal();
toast('Zapisano.');
location.hash = '#/records/' + encodeURIComponent(r.id);
await router();
});
}
function openRecordEdit(id) {
function openSourceNew() {
modal('Nowe źródło', '',
`<div class="row" style="gap:16px;margin-bottom:12px">
<label><input type="radio" name="snKind" value="file" checked onchange="sourceKind()"> Plik</label>
<label><input type="radio" name="snKind" value="document" onchange="sourceKind()"> Dokument z Galeny</label>
</div>
<label class="field">Tytuł<input id="snTitle" /></label>
<div id="snFile"><label class="field" style="margin-top:12px">Plik (PDF, DOCX, TXT, MD)<input id="snUpload" type="file" accept=".pdf,.docx,.txt,.md" /></label></div>
<div id="snDoc" class="hidden">
<label class="field" style="margin-top:12px">Identyfikator projektu<input id="snProject" /></label>
<label class="field" style="margin-top:12px">Ścieżka<input id="snPath" /></label>
<label class="field" style="margin-top:12px">Wersja<input id="snVersion" value="main" /></label>
</div>
<label class="field" style="margin-top:12px">Notatka<textarea id="snNote"></textarea></label>
<label style="display:block;margin-top:12px"><input id="snShared" type="checkbox" /> Udostępnij wszystkim</label>`,
`<button class="btn" onclick="closeModal()">Anuluj</button>
<button class="btn primary" onclick="saveSourceNew()">Zapisz</button>`);
}
function sourceKind() {
const doc = document.querySelector('input[name=snKind]:checked').value === 'document';
$('snFile').classList.toggle('hidden', doc);
$('snDoc').classList.toggle('hidden', !doc);
}
function saveSourceNew() {
guard(async () => {
const r = await api('GET', '/records/' + encodeURIComponent(id));
modal('Edytuj', r.name,
`<label class="field">Nazwa<input id="reName" value="${esc(r.name)}" /></label>
<label class="field" style="margin-top:12px">Notatka<textarea id="reNote">${esc(r.note || '')}</textarea></label>
<label class="field" style="margin-top:12px">Status
<select id="reStatus">
<option value="open" ${r.status === 'open' ? 'selected' : ''}>otwarty</option>
<option value="done" ${r.status === 'done' ? 'selected' : ''}>zamknięty</option>
</select></label>`,
`<button class="btn" onclick="closeModal()">Anuluj</button>
<button class="btn primary" onclick="saveRecordEdit('${esc(id)}')">Zapisz</button>`);
const doc = document.querySelector('input[name=snKind]:checked').value === 'document';
const title = $('snTitle').value.trim();
const note = $('snNote').value.trim();
const shared = $('snShared').checked;
let r;
if (doc) {
r = await api('POST', '/sources/document', {
document_id: $('snProject').value.trim(), path: $('snPath').value.trim(),
version: $('snVersion').value.trim() || 'main',
title: title || null, note: note || null, shared,
});
} else {
const f = $('snUpload').files[0];
if (!f) throw new Error(_tr('Wybierz plik.'));
const form = new FormData();
form.append('file', f);
if (title) form.append('title', title);
if (note) form.append('note', note);
form.append('shared', shared ? 'true' : 'false');
r = await apiForm('/sources/upload', form);
}
closeModal();
toast('Zapisano.');
location.hash = '#/sources/' + encodeURIComponent(r.id);
});
}
function saveRecordEdit(id) {
function openSourceEdit(id) {
guard(async () => {
await api('PATCH', '/records/' + encodeURIComponent(id), {
name: $('reName').value,
note: $('reNote').value,
status: $('reStatus').value,
const s = await api('GET', '/sources/' + encodeURIComponent(id));
modal('Edytuj', s.title,
`<label class="field">Tytuł<input id="seTitle" value="${esc(s.title)}" /></label>
<label class="field" style="margin-top:12px">Notatka<textarea id="seNote">${esc(s.note || '')}</textarea></label>
<label class="field" style="margin-top:12px">Status
<select id="seStatus">
<option value="active" ${s.status === 'active' ? 'selected' : ''}>aktywne</option>
<option value="archived" ${s.status === 'archived' ? 'selected' : ''}>archiwum</option>
</select></label>
<label style="display:block;margin-top:12px"><input id="seShared" type="checkbox" ${s.shared ? 'checked' : ''} /> Udostępnij wszystkim</label>`,
`<button class="btn" onclick="closeModal()">Anuluj</button>
<button class="btn primary" onclick="saveSourceEdit('${esc(id)}')">Zapisz</button>`);
});
}
function saveSourceEdit(id) {
guard(async () => {
await api('PATCH', '/sources/' + encodeURIComponent(id), {
title: $('seTitle').value, note: $('seNote').value,
status: $('seStatus').value, shared: $('seShared').checked,
});
closeModal();
toast('Zapisano.');
@@ -578,19 +722,252 @@ function saveRecordEdit(id) {
});
}
function deleteRecord(id) {
function openSourceFile(id) {
modal('Nowy plik', '',
`<label class="field">Plik (PDF, DOCX, TXT, MD)<input id="sfUpload" type="file" accept=".pdf,.docx,.txt,.md" /></label>
<div class="faint tiny" style="margin-top:8px">Klauzule zostaną pocięte od nowa; ręcznie nadane typy przechodzą na niezmienione klauzule.</div>`,
`<button class="btn" onclick="closeModal()">Anuluj</button>
<button class="btn primary" onclick="saveSourceFile('${esc(id)}')">Zapisz</button>`);
}
function saveSourceFile(id) {
guard(async () => {
const f = $('sfUpload').files[0];
if (!f) throw new Error(_tr('Wybierz plik.'));
const form = new FormData();
form.append('file', f);
await apiForm('/sources/' + encodeURIComponent(id) + '/file', form);
closeModal();
toast('Zapisano.');
await router();
});
}
function openSourceRefresh(id) {
modal('Odśwież z Galeny', '',
`<label class="field">Wersja<input id="srVersion" value="main" /></label>`,
`<button class="btn" onclick="closeModal()">Anuluj</button>
<button class="btn primary" onclick="saveSourceRefresh('${esc(id)}')">Zapisz</button>`);
}
function saveSourceRefresh(id) {
guard(async () => {
await api('POST', '/sources/' + encodeURIComponent(id) + '/refresh',
{ version: $('srVersion').value.trim() || 'main' });
closeModal();
toast('Zapisano.');
await router();
});
}
function recutSource(id) {
guard(async () => {
await api('POST', '/sources/' + encodeURIComponent(id) + '/recut');
toast('Zapisano.');
await router();
});
}
function deleteSource(id) {
modal('Usuń', '',
'<div class="banner warn">Tej operacji nie da się cofnąć.</div>',
`<button class="btn" onclick="closeModal()">Anuluj</button>
<button class="btn danger" onclick="confirmDeleteRecord('${esc(id)}')">Usuń</button>`);
<button class="btn danger" onclick="confirmDeleteSource('${esc(id)}')">Usuń</button>`);
}
function confirmDeleteRecord(id) {
function confirmDeleteSource(id) {
guard(async () => {
await api('DELETE', '/records/' + encodeURIComponent(id));
await api('DELETE', '/sources/' + encodeURIComponent(id));
closeModal();
toast('Zapisano.');
location.hash = '#/records';
location.hash = '#/sources';
});
}
/* ── library (search + shelves) ─────────────────────────────────────────── */
async function viewLibrary(C, q) {
await clauseTypes();
const params = new URLSearchParams();
if (q.q) params.set('q', q.q);
if (q.clause_type) params.set('clause_type', q.clause_type);
if (q.paragraph_only === '1') params.set('paragraph_only', 'true');
if (q.page) params.set('page', q.page);
const [hits, shelves] = await Promise.all([
api('GET', '/library/clauses?' + params), api('GET', '/library/shelves')]);
setCrumb([{ label: 'Biblioteka' }]);
const page = hits.page || 1;
const pages = Math.max(1, Math.ceil((hits.total || 0) / (hits.page_size || 1)));
C.innerHTML = pageHead('Biblioteka', String(hits.total || 0), '')
+ `<div class="toolbar">
<input type="search" id="lq" placeholder="Szukaj w klauzulach…" value="${esc(q.q || '')}" />
<select id="ltype"><option value="">Wszystkie typy</option>
${shelves.map((s) => { const k = s.type == null ? 'untyped' : s.type; return `<option value="${esc(k)}" ${q.clause_type === k ? 'selected' : ''}>${esc(s.type == null ? 'bez typu' : s.label)} (${esc(String(s.count))})</option>`; }).join('')}
</select>
<label class="tiny"><input id="lpar" type="checkbox" ${q.paragraph_only === '1' ? 'checked' : ''} /> tylko §</label>
</div>`
+ `<div class="card"><h3>Półki</h3><div class="row" style="flex-wrap:wrap;gap:6px">
${shelves.map((s) => { const k = s.type == null ? 'untyped' : s.type; return `<a class="chip" href="#/library?clause_type=${encodeURIComponent(k)}">${esc(s.type == null ? 'bez typu' : s.label)} · ${esc(String(s.count))}</a>`; }).join('')}
</div></div>`
+ `<div class="card"><h3>Klauzule<span class="n">${esc(String(hits.total || 0))}</span></h3>
${(hits.items || []).length ? hits.items.map((h) => `<div style="padding:10px 0;border-top:1px solid var(--line)">
<div class="row"><a href="#/sources/${encodeURIComponent(h.source_id)}">${esc(h.source_title)}</a> · <b>${esc(h.label || '')}</b>
<span style="flex:1"></span>${typeChips(h.types, h.type_source)}</div>
<div class="tiny" style="white-space:pre-wrap;margin-top:6px">${h.snippet_cut_before ? '…' : ''}${esc(h.snippet || h.text || '')}${h.snippet_cut_after ? '…' : ''}</div>
</div>`).join('') : '<div class="empty">Brak wyników</div>'}
${pages > 1 ? `<div class="row" style="margin-top:10px">
${page > 1 ? `<button class="btn" id="lprev">‹</button>` : ''}
<span class="faint tiny">${esc(String(page))} / ${esc(String(pages))}</span>
${page < pages ? `<button class="btn" id="lnext">›</button>` : ''}</div>` : ''}
</div>`;
const go = (p) => {
const n = new URLSearchParams();
if ($('lq').value.trim()) n.set('q', $('lq').value.trim());
if ($('ltype').value) n.set('clause_type', $('ltype').value);
if ($('lpar').checked) n.set('paragraph_only', '1');
if (p && p > 1) n.set('page', String(p));
location.hash = '#/library' + (n.toString() ? '?' + n : '');
};
$('lq').addEventListener('change', () => go(1));
$('ltype').addEventListener('change', () => go(1));
$('lpar').addEventListener('change', () => go(1));
if ($('lprev')) $('lprev').addEventListener('click', () => go(page - 1));
if ($('lnext')) $('lnext').addEventListener('click', () => go(page + 1));
}
/* ── standards ──────────────────────────────────────────────────────────── */
async function viewStandards(C, q) {
const types = await clauseTypes();
const params = new URLSearchParams();
params.set('status', q.status || 'active');
if (q.clause_type) params.set('clause_type', q.clause_type);
const rows = await api('GET', '/standards?' + params);
setCrumb([{ label: 'Standardy' }]);
C.innerHTML = pageHead('Standardy', rows.length + '',
isModerator() ? `<button class="btn primary" onclick="openStandardForm()">${svg(ICN.plus)}Nowy standard</button>` : '')
+ `<div class="toolbar">
<select id="stype"><option value="">Wszystkie typy</option>
${types.map((t) => `<option value="${esc(t.type)}" ${q.clause_type === t.type ? 'selected' : ''}>${esc(t.label)}</option>`).join('')}
</select>
<select id="sstatus">
${[['active', 'aktywne'], ['archived', 'archiwum'], ['all', 'wszystkie']].map(([v, l]) => `<option value="${v}" ${(q.status || 'active') === v ? 'selected' : ''}>${esc(l)}</option>`).join('')}
</select>
</div>`
+ (rows.length ? `<div class="card"><div class="tablewrap"><table class="rt"><thead><tr>
<th>Tytuł</th><th>Typ</th><th>Status</th></tr></thead><tbody>
${rows.map((s) => `<tr class="click" onclick="location.hash='#/standards/${encodeURIComponent(s.id)}'">
<td><div>${esc(s.title)}<div class="faint tiny">${esc(s.rule)}</div></div></td>
<td${lbl('Typ')}><span class="chip">${esc(s.clause_type_label)}</span></td>
<td${lbl('Status')}>${s.status === 'archived' ? '<span class="chip">archiwum</span>' : '<span class="chip ok">aktywny</span>'}</td>
</tr>`).join('')}</tbody></table></div></div>` : '<div class="empty">Brak standardów.</div>');
const go = () => {
const p = new URLSearchParams();
if ($('stype').value) p.set('clause_type', $('stype').value);
if ($('sstatus').value !== 'active') p.set('status', $('sstatus').value);
location.hash = '#/standards' + (p.toString() ? '?' + p : '');
};
$('stype').addEventListener('change', go);
$('sstatus').addEventListener('change', go);
}
async function viewStandard(C, id) {
const sid = encodeURIComponent(id);
const [s, ex] = await Promise.all([
api('GET', '/standards/' + sid), api('GET', '/standards/' + sid + '/examples')]);
setCrumb([{ label: 'Standardy', href: '#/standards' }, { label: s.title }]);
const block = (label, text) => text
? `<div style="margin-top:14px"><div class="tiny faint">${esc(label)}</div><div style="white-space:pre-wrap">${esc(text)}</div></div>` : '';
const example = (e) => e.state === 'ok'
? `<div style="padding:8px 0;border-top:1px solid var(--line)"><a href="#/sources/${encodeURIComponent(e.source_id)}">${esc(e.source_title)}</a> · <b>${esc(e.label || '')}</b><div class="tiny" style="white-space:pre-wrap">${esc(e.text || '')}</div></div>`
: e.state === 'gone'
? `<div class="faint tiny" style="padding:8px 0;border-top:1px solid var(--line)">${esc(e.source_title || '')} · ${esc(e.label || '')} — klauzuli już nie ma</div>`
: '<div class="faint tiny" style="padding:8px 0;border-top:1px solid var(--line)">Przykład niedostępny</div>';
C.innerHTML = pageHead(s.title, s.clause_type_label,
isModerator() ? `<button class="btn" onclick="openStandardForm('${esc(s.id)}')">${svg(ICN.check)}Edytuj</button>` : '')
+ `<div class="card">
<div class="row">${s.status === 'archived' ? '<span class="chip">archiwum</span>' : '<span class="chip ok">aktywny</span>'}</div>
${block('Zasada', s.rule)}${block('Wzorcowe brzmienie', s.wording)}${block('Stanowisko rezerwowe', s.fallback)}
</div>`
+ `<div class="card"><h3>Przykłady<span class="n">${(ex || []).length}</span></h3>
${(ex || []).length ? ex.map(example).join('') : '<div class="empty">—</div>'}</div>`;
}
function openStandardForm(id) {
guard(async () => {
const types = await clauseTypes();
const s = id ? await api('GET', '/standards/' + encodeURIComponent(id)) : {};
modal(id ? 'Edytuj' : 'Nowy standard', s.title || '',
`<label class="field">Typ klauzuli<select id="sfType">${types.map((t) =>
`<option value="${esc(t.type)}" ${t.type === s.clause_type ? 'selected' : ''}>${esc(t.label)}</option>`).join('')}</select></label>
<label class="field" style="margin-top:12px">Tytuł<input id="sfTitle" value="${esc(s.title || '')}" /></label>
<label class="field" style="margin-top:12px">Zasada<textarea id="sfRule">${esc(s.rule || '')}</textarea></label>
<label class="field" style="margin-top:12px">Wzorcowe brzmienie<textarea id="sfWording">${esc(s.wording || '')}</textarea></label>
<label class="field" style="margin-top:12px">Stanowisko rezerwowe<textarea id="sfFallback">${esc(s.fallback || '')}</textarea></label>
${id ? `<label class="field" style="margin-top:12px">Status<select id="sfStatus">
<option value="active" ${s.status === 'active' ? 'selected' : ''}>aktywny</option>
<option value="archived" ${s.status === 'archived' ? 'selected' : ''}>archiwum</option></select></label>` : ''}`,
`<button class="btn" onclick="closeModal()">Anuluj</button>
<button class="btn primary" onclick="saveStandard(${id ? `'${esc(id)}'` : 'null'})">Zapisz</button>`,
{ wide: true });
});
}
function saveStandard(id) {
guard(async () => {
const body = {
clause_type: $('sfType').value, title: $('sfTitle').value.trim(),
rule: $('sfRule').value.trim(), wording: $('sfWording').value.trim(),
fallback: $('sfFallback').value.trim() || null,
};
let r;
if (id) {
body.status = $('sfStatus').value;
r = await api('PATCH', '/standards/' + encodeURIComponent(id), body);
} else {
r = await api('POST', '/standards', body);
}
closeModal();
toast('Zapisano.');
location.hash = '#/standards/' + encodeURIComponent(r.id);
await router();
});
}
/* ── model providers + the catalog model ────────────────────────────────── */
async function viewProviders(C) {
setCrumb([{ label: 'Dostawcy modeli' }]);
const [rows, settings] = await Promise.all([
api('GET', '/providers').catch(() => []),
api('GET', '/admin/settings').catch(() => [])]);
const cm = (settings || []).find((s) => s.key === 'CATALOG_MODEL');
const hub = hubMode();
C.innerHTML = pageHead('Dostawcy modeli', '', '')
+ `<div class="card"><h3>Model katalogu</h3>
<div class="faint tiny">Model, który nadaje klauzulom typy. Puste = typowanie wyłączone. Format: dostawca/model.</div>
<div class="row" style="margin-top:10px"><input id="cmValue" value="${esc((cm && cm.value) || '')}" style="flex:1" />
<button class="btn primary" onclick="saveCatalogModel()">Zapisz</button></div></div>`
+ `<div class="card"><h3>Dostawcy<span class="n">${rows.length}</span></h3>
${rows.length ? `<div class="tablewrap"><table class="rt"><thead><tr>
<th>Nazwa</th><th>Rodzaj</th><th>Modele</th><th>Status</th></tr></thead><tbody>
${rows.map((p) => `<tr>
<td><div>${esc(p.name)}<div class="faint tiny mono">${esc(p.base_url || '')}</div></div></td>
<td${lbl('Rodzaj')}>${esc(p.kind || '')}</td>
<td class="tiny"${lbl('Modele')}>${esc((p.models || []).join(', '))}</td>
<td${lbl('Status')}>${p.is_active === false ? '<span class="chip err">wyłączony</span>' : '<span class="chip ok">aktywny</span>'}</td>
</tr>`).join('')}</tbody></table></div>` : '<div class="empty">Brak dostawców.</div>'}
${hub ? '<div class="faint tiny" style="padding:10px 2px 2px">Dostawcami zarządza się w jednym miejscu dla całej platformy.</div>' : ''}
</div>`;
}
function saveCatalogModel() {
guard(async () => {
await api('PUT', '/admin/settings', { values: { CATALOG_MODEL: $('cmValue').value.trim() } });
toast('Zapisano.');
await router();
});
}
@@ -723,13 +1100,14 @@ function openSearch() {
const q = input.value.trim();
if (!q) { $('sres').innerHTML = ''; return; }
try {
const rows = await api('GET', '/records?q=' + encodeURIComponent(q));
const hits = await api('GET', '/library/clauses?q=' + encodeURIComponent(q));
const rows = hits.items || [];
$('sres').innerHTML = rows.length
? `<div class="sgroup">Rekordy</div>` + rows.slice(0, 12).map((r) =>
`<button class="sitem" onclick="closeModal();location.hash='#/records/${encodeURIComponent(r.id)}'">
? `<div class="sgroup">Klauzule</div>` + rows.slice(0, 12).map((r) =>
`<button class="sitem" onclick="closeModal();location.hash='#/sources/${encodeURIComponent(r.source_id)}'">
<span class="ic">${svg(ICN.file)}</span>
<span class="sb"><span class="st">${esc(r.name)}</span>
<span class="ss">${esc(r.note || '')}</span></span></button>`).join('')
<span class="sb"><span class="st">${esc(r.source_title)} · ${esc(r.label || '')}</span>
<span class="ss">${esc(r.snippet || '')}</span></span></button>`).join('')
: '<div class="search-empty">Brak wyników</div>';
localize($('sres'));
} catch { $('sres').innerHTML = ''; }