An API key that expires after a day left its provider on the list for good. DELETE /admin/model-providers/{id} binds dredd-core 0.23.2's delete_unused: refused while active (409 provider_still_active) and once any run points at it (409 provider_in_use). The console offers Usuń on a disabled row. No revision: atrium-migrate re-applies the provider grants, which now give the hub DELETE.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_016uwxqKuxvGXDvtwWKrBWYR
6703 lines
449 KiB
JavaScript
6703 lines
449 KiB
JavaScript
/* Atrium console — vanilla JS, no build step.
|
||
Atrium is the Dredd family's front door: a launcher ("Your apps"), a marketplace of modules, and
|
||
the administration that decides who is offered what. The family runs at ONE origin, one module
|
||
per path (/atrium, /galena, /sygna, /counsel), so a module is one link away and shares this
|
||
page's origin — Atrium still only links to modules, it never proxies them.
|
||
|
||
Source strings are in the product's first language; I18N translates to the other. The
|
||
mechanism (_tr / _trAttr / localize, matching on source text, with data-no-i18n opt-outs) is
|
||
the same across the family — only the source language differs. Data from the server (module
|
||
names, descriptions, audit details) is wrapped in data-no-i18n via dat(), so a module that
|
||
happens to be called like a UI label is never "translated".
|
||
|
||
After editing this file, run `node --check frontend/app.js`. A duplicate `const` inside one
|
||
function silently stops the whole file parsing, so every function defined after it disappears,
|
||
and the symptom is a screen that renders nothing with no console error to find. */
|
||
|
||
'use strict';
|
||
|
||
/* The API is under THIS document's base, not the site root. The family serves one module per path on
|
||
one origin, so a root-absolute '/api/v1' would leave this module and land on a sibling's backend.
|
||
document.baseURI is whatever we are served from — '/' standalone, '/atrium/' behind the front
|
||
door's `Mount("/atrium")` — which is the same reason every asset in index.html is relative. Routing
|
||
is hash-based, so the base never moves as you navigate. */
|
||
const API = new URL('api/v1', document.baseURI).pathname;
|
||
|
||
const $ = (id) => document.getElementById(id);
|
||
const esc = (v) => String(v ?? '').replace(/[&<>"']/g, (c) =>
|
||
({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]));
|
||
/* Server data, escaped and exempt from translation. */
|
||
const dat = (v) => `<span data-no-i18n>${esc(v)}</span>`;
|
||
/* Only ever an http(s) address in an href. The server and a database CHECK already refuse anything
|
||
else; this is the third line, because a launcher link is exactly where `javascript:` would hurt. */
|
||
// `../<slug>/` is a module the front door serves without an administrator's address (marketplace
|
||
// `module_url`): a path on this very site, resolved here so every caller sees an absolute address.
|
||
const safeUrl = (u) => (/^https?:\/\//i.test(String(u || '')) ? String(u)
|
||
: /^\.\.\/[a-z][a-z0-9-]*\/$/.test(String(u || '')) ? new URL(String(u), document.baseURI).href : '#');
|
||
/* Does an address land on this very origin? Modules normally do — they are paths on the platform's
|
||
one host — and that is what decides whether a launch needs a new tab and a `rel` at all. */
|
||
const sameOrigin = (u) => {
|
||
try { return new URL(String(u || ''), document.baseURI).origin === location.origin; }
|
||
catch { return false; }
|
||
};
|
||
const enc = encodeURIComponent;
|
||
/* A column label for a data cell. Tables with class "rt" become stacked cards on a phone, and each
|
||
cell shows its label there (CSS `td[data-label]::before`); on a wide screen the header row does. */
|
||
const lbl = (label) => ` data-label="${esc(label)}"`;
|
||
/* A path or hash with a query string. URLSearchParams builds it, so parseHash() reads it back the same
|
||
way; empty values are left out. */
|
||
function withQuery(base, params) {
|
||
const s = new URLSearchParams(Object.entries(params).filter(([, v]) => v).map(([k, v]) => [k, String(v)])).toString();
|
||
return s ? `${base}?${s}` : base;
|
||
}
|
||
|
||
const state = {
|
||
user: null, users: [], modules: null, config: { settings: {} }, launcher: [], pending: 0,
|
||
// Whether the data other screens show from memory (settings, app switcher, pending badge) must be
|
||
// re-read before it is shown again: true until the first read, and after every write (see api()).
|
||
stale: true,
|
||
};
|
||
|
||
/* The console holds NO credential. The HttpOnly session cookie is the only one a sign-in issues, the
|
||
browser attaches it (`credentials: 'same-origin'`), and no script — this one included — can read
|
||
it. The sign-in reply used to repeat the raw token for a bearer header kept in memory; that copy
|
||
was readable by any script on the platform's one origin, so the server stopped sending it and
|
||
there is nothing here to keep. An app token minted on the Connected apps screen is shown once
|
||
for the person to copy into a desktop client, and is never used by this console. */
|
||
async function api(method, path, body) {
|
||
const opt = { method, headers: {}, credentials: 'same-origin' };
|
||
if (body instanceof Blob) {
|
||
// The raw body (the server takes no multipart forms): a pack import is a ZIP, an attached chat file any bytes.
|
||
opt.headers['Content-Type'] = /\/import\b/.test(path) ? 'application/zip' : 'application/octet-stream';
|
||
opt.body = body;
|
||
} else if (body !== undefined) {
|
||
opt.headers['Content-Type'] = 'application/json';
|
||
opt.body = JSON.stringify(body);
|
||
}
|
||
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) {
|
||
let msg = (data && (data.detail || data.title)) || ('HTTP ' + res.status);
|
||
if (data && Array.isArray(data.errors) && data.errors.length) {
|
||
msg = data.errors.map((e) => `${(e.loc || []).slice(-1)[0] || ''}: ${e.msg}`).join('; ');
|
||
}
|
||
msg = admissionRefusal(data) || coreRefusal(data) || msg;
|
||
const err = new Error(msg);
|
||
err.status = res.status;
|
||
err.problem = data;
|
||
throw err;
|
||
}
|
||
// Any write can change the brand, someone's apps or the pending count. Marking them here, rather than
|
||
// refreshing after each action, means a new action cannot forget to; the router re-reads them once.
|
||
if (method !== 'GET') state.stale = true;
|
||
return data;
|
||
}
|
||
|
||
/* The one refusal the console words itself. Only an administrator or a module's own moderator may
|
||
let somebody into a module, so a unit manager adding a person to a unit that has modules assigned
|
||
is refused, and the reply names those modules (`code` + `modules`, services/marketplace.py). The
|
||
names are data inside a sentence that has to be in the reader's language, which a server-side
|
||
English sentence cannot be — so the sentence is built here and the names are only ever placed
|
||
with textContent / esc() by whoever shows the message. Keep the code in step with
|
||
`ADMISSION_REFUSED`. */
|
||
function admissionRefusal(problem) {
|
||
if (!problem || problem.code !== 'module_admission_refused' || !Array.isArray(problem.modules)) return '';
|
||
const names = problem.modules.map((m) => String((m && (m.name || m.slug)) || '')).filter(Boolean);
|
||
const lead = names.length > 1
|
||
? 'Ta zmiana dałaby dostęp do modułów, których nie moderujesz:'
|
||
: 'Ta zmiana dałaby dostęp do modułu, którego nie moderujesz:';
|
||
return `${_tr(lead)} ${names.join(', ')}. `
|
||
+ _tr('Wpuścić kogoś do modułu może tylko administrator albo moderator tego modułu.');
|
||
}
|
||
|
||
/* dredd-core's refusals (model providers, custom fields) carry the Polish sentence as `detail` and the
|
||
English one as `en`, next to a stable `code`. The console's source language is Polish, so `detail`
|
||
already reads right in PL; in EN take core's own sentence rather than a dictionary entry per code. */
|
||
function coreRefusal(problem) {
|
||
if (LANG === SRC_LANG || !problem || !problem.code || typeof problem.en !== 'string') return '';
|
||
return problem.en;
|
||
}
|
||
|
||
function toast(msg) {
|
||
const t = $('toast');
|
||
t.innerHTML = `<div class="toast">${esc(_tr(msg))}</div>`;
|
||
setTimeout(() => { t.innerHTML = ''; }, 3000);
|
||
}
|
||
|
||
const setting = (k) => (state.config.settings || {})[k];
|
||
|
||
/* ── formatting ─────────────────────────────────────────────────────────── */
|
||
function fmtDateTime(iso) {
|
||
if (!iso) return '—';
|
||
const d = new Date(iso);
|
||
return isNaN(d) ? '—' : d.toLocaleString(LANG === 'pl' ? 'pl-PL' : 'en-GB', {
|
||
day: '2-digit', month: '2-digit', year: 'numeric', hour: '2-digit', minute: '2-digit',
|
||
});
|
||
}
|
||
|
||
function initials(s) {
|
||
s = String(s || '?');
|
||
return s.replace(/@.*/, '').split(/[.\s_-]+/).filter(Boolean).slice(0, 2)
|
||
.map((x) => x[0].toUpperCase()).join('') || '?';
|
||
}
|
||
|
||
/* ── icons (Tabler outline, MIT — path data vendored, never a CDN) ──────── */
|
||
const ICN = {
|
||
// tabler: layout-dashboard
|
||
dashboard: '<path d="M5 4h4a1 1 0 0 1 1 1v6a1 1 0 0 1 -1 1h-4a1 1 0 0 1 -1 -1v-6a1 1 0 0 1 1 -1"/><path d="M5 16h4a1 1 0 0 1 1 1v2a1 1 0 0 1 -1 1h-4a1 1 0 0 1 -1 -1v-2a1 1 0 0 1 1 -1"/><path d="M15 12h4a1 1 0 0 1 1 1v6a1 1 0 0 1 -1 1h-4a1 1 0 0 1 -1 -1v-6a1 1 0 0 1 1 -1"/><path d="M15 4h4a1 1 0 0 1 1 1v2a1 1 0 0 1 -1 1h-4a1 1 0 0 1 -1 -1v-2a1 1 0 0 1 1 -1"/>',
|
||
// tabler: grid-dots
|
||
griddots: '<path d="M5 5h2v2h-2z M11 5h2v2h-2z M17 5h2v2h-2z M5 11h2v2h-2z M11 11h2v2h-2z M17 11h2v2h-2z M5 17h2v2h-2z M11 17h2v2h-2z M17 17h2v2h-2z"/>',
|
||
// tabler: layout-grid
|
||
grid: '<path d="M4 4h6v6h-6z"/><path d="M14 4h6v6h-6z"/><path d="M4 14h6v6h-6z"/><path d="M14 14h6v6h-6z"/>',
|
||
// tabler: layout-grid-add
|
||
store: '<path d="M4 4h6v6h-6z"/><path d="M14 4h6v6h-6z"/><path d="M4 14h6v6h-6z"/><path d="M14 17h6m-3 -3v6"/>',
|
||
// tabler: send
|
||
send: '<path d="M10 14l11 -11"/><path d="M21 3l-6.5 18a.55 .55 0 0 1 -1 0l-3.5 -7l-7 -3.5a.55 .55 0 0 1 0 -1z"/>',
|
||
// tabler: building
|
||
workspace: '<path d="M3 21h18"/><path d="M5 21v-14l8 -4v18"/><path d="M19 21v-10l-6 -4"/><path d="M9 9v0"/><path d="M9 12v0"/><path d="M9 15v0"/><path d="M9 18v0"/>',
|
||
// tabler: history
|
||
history: '<path d="M12 8l0 4l2 2"/><path d="M3.05 11a9 9 0 1 1 .5 4m-.5 5v-5h5"/>',
|
||
// tabler: external-link
|
||
arrowupright: '<path d="M17 7l-10 10"/><path d="M8 7h9v9"/>',
|
||
external: '<path d="M12 6h-6a2 2 0 0 0 -2 2v10a2 2 0 0 0 2 2h10a2 2 0 0 0 2 -2v-6"/><path d="M11 13l9 -9"/><path d="M15 4h5v5"/>',
|
||
// tabler: refresh
|
||
refresh: '<path d="M20 11a8.1 8.1 0 0 0 -15.5 -2m-.5 -4v4h4"/><path d="M4 13a8.1 8.1 0 0 0 15.5 2m.5 4v-4h-4"/>',
|
||
// tabler: info-circle
|
||
info: '<path d="M3 12a9 9 0 1 0 18 0a9 9 0 0 0 -18 0"/><path d="M12 9h.01"/><path d="M11 12h1v4h1"/>',
|
||
// tabler: edit
|
||
edit: '<path d="M7 7h-1a2 2 0 0 0 -2 2v9a2 2 0 0 0 2 2h9a2 2 0 0 0 2 -2v-1"/><path d="M20.385 6.585a2.1 2.1 0 0 0 -2.97 -2.97l-8.415 8.385v3h3z"/>',
|
||
// tabler: settings
|
||
settings: '<path d="M10.325 4.317c.426 -1.756 2.924 -1.756 3.35 0a1.724 1.724 0 0 0 2.573 1.066c1.543 -.94 3.31 .826 2.37 2.37a1.724 1.724 0 0 0 1.065 2.572c1.756 .426 1.756 2.924 0 3.35a1.724 1.724 0 0 0 -1.066 2.573c.94 1.543 -.826 3.31 -2.37 2.37a1.724 1.724 0 0 0 -2.572 1.065c-.426 1.756 -2.924 1.756 -3.35 0a1.724 1.724 0 0 0 -2.573 -1.066c-1.543 .94 -3.31 -.826 -2.37 -2.37a1.724 1.724 0 0 0 -1.065 -2.572c-1.756 -.426 -1.756 -2.924 0 -3.35a1.724 1.724 0 0 0 1.066 -2.573c-.94 -1.543 .826 -3.31 2.37 -2.37c1 .608 2.296 .07 2.572 -1.065"/><path d="M9 12a3 3 0 1 0 6 0a3 3 0 0 0 -6 0"/>',
|
||
// tabler: plus
|
||
plus: '<path d="M12 5l0 14"/><path d="M5 12l14 0"/>',
|
||
// tabler: check
|
||
check: '<path d="M5 12l5 5l10 -10"/>',
|
||
// tabler: x
|
||
x: '<path d="M18 6l-12 12"/><path d="M6 6l12 12"/>',
|
||
// tabler: paperclip
|
||
paperclip: '<path d="M15 7l-6.5 6.5a1.5 1.5 0 0 0 3 3l6.5 -6.5a3 3 0 0 0 -6 -6l-6.5 6.5a4.5 4.5 0 0 0 9 9l6.5 -6.5"/>',
|
||
stop: '<path d="M5 7a2 2 0 0 1 2 -2h10a2 2 0 0 1 2 2v10a2 2 0 0 1 -2 2h-10a2 2 0 0 1 -2 -2z"/>',
|
||
// tabler: sun
|
||
sun: '<path d="M8 12a4 4 0 1 0 8 0a4 4 0 1 0 -8 0"/><path d="M3 12h1m8 -9v1m8 8h1m-9 8v1m-6.4 -15.4l.7 .7m12.1 -.7l-.7 .7m0 11.4l.7 .7m-12.1 -.7l-.7 .7"/>',
|
||
// tabler: moon
|
||
moon: '<path d="M12 3c.132 0 .263 0 .393 0a7.5 7.5 0 0 0 7.92 12.446a9 9 0 1 1 -8.313 -12.454l0 .008"/>',
|
||
// tabler: device-desktop
|
||
desktop: '<path d="M3 5a1 1 0 0 1 1 -1h16a1 1 0 0 1 1 1v10a1 1 0 0 1 -1 1h-16a1 1 0 0 1 -1 -1v-10"/><path d="M7 20h10"/><path d="M9 16v4"/><path d="M15 16v4"/>',
|
||
// tabler: eye
|
||
eye: '<path d="M10 12a2 2 0 1 0 4 0a2 2 0 0 0 -4 0"/><path d="M21 12c-2.4 4 -5.4 6 -9 6c-3.6 0 -6.6 -2 -9 -6c2.4 -4 5.4 -6 9 -6c3.6 0 6.6 2 9 6"/>',
|
||
// tabler: eye-off
|
||
eyeoff: '<path d="M10.585 10.587a2 2 0 0 0 2.829 2.828"/><path d="M16.681 16.673a8.717 8.717 0 0 1 -4.681 1.327c-3.6 0 -6.6 -2 -9 -6c1.272 -2.12 2.712 -3.678 4.32 -4.674m2.86 -1.146a9.055 9.055 0 0 1 1.82 -.18c3.6 0 6.6 2 9 6c-.666 1.11 -1.379 2.067 -2.138 2.87"/><path d="M3 3l18 18"/>',
|
||
// tabler: trash
|
||
trash: '<path d="M4 7l16 0"/><path d="M10 11l0 6"/><path d="M14 11l0 6"/><path d="M5 7l1 12a2 2 0 0 0 2 2h8a2 2 0 0 0 2 -2l1 -12"/><path d="M9 7v-3a1 1 0 0 1 1 -1h4a1 1 0 0 1 1 1v3"/>',
|
||
// tabler: menu-2
|
||
menu: '<path d="M4 6h16"/><path d="M4 12h16"/><path d="M4 18h16"/>',
|
||
sidebar: '<path d="M4 6a2 2 0 0 1 2-2h12a2 2 0 0 1 2 2v12a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2z"/><path d="M9 4v16"/>',
|
||
// tabler: search
|
||
search: '<path d="M3 10a7 7 0 1 0 14 0a7 7 0 1 0 -14 0"/><path d="M21 21l-6 -6"/>',
|
||
home: '<path d="M5 12l-2 0l9 -9l9 9l-2 0"/><path d="M5 12v7a2 2 0 0 0 2 2h10a2 2 0 0 0 2 -2v-7"/><path d="M9 21v-6a2 2 0 0 1 2 -2h2a2 2 0 0 1 2 2v6"/>',
|
||
arrowright: '<path d="M5 12l14 0"/><path d="M13 18l6 -6"/><path d="M13 6l6 6"/>',
|
||
// tabler: users
|
||
users: '<path d="M5 7a4 4 0 1 0 8 0a4 4 0 1 0 -8 0"/><path d="M3 21v-2a4 4 0 0 1 4 -4h4a4 4 0 0 1 4 4v2"/><path d="M16 3.13a4 4 0 0 1 0 7.75"/><path d="M21 21v-2a4 4 0 0 0 -3 -3.85"/>',
|
||
// tabler: key — connected apps, i.e. the app tokens this console is now the only source of
|
||
key: '<path d="M16.555 3.843l3.602 3.602a2.877 2.877 0 0 1 0 4.069l-2.643 2.643a2.877 2.877 0 0 1 -4.069 0l-.301 -.301l-6.558 6.558a2 2 0 0 1 -1.239 .578l-.175 .008h-1.575a1 1 0 0 1 -.993 -.883l-.007 -.117v-1.575a2 2 0 0 1 .467 -1.284l.119 -.13l.414 -.414h2v-2h2v-2l2.144 -2.144l-.301 -.301a2.877 2.877 0 0 1 0 -4.069l2.643 -2.643a2.877 2.877 0 0 1 4.069 0z"/><path d="M15 9h.01"/>',
|
||
// tabler: book — skills and agents
|
||
book: '<path d="M3 19a9 9 0 0 1 9 0a9 9 0 0 1 9 0"/><path d="M3 6a9 9 0 0 1 9 0a9 9 0 0 1 9 0"/><path d="M3 6l0 13"/><path d="M12 6l0 13"/><path d="M21 6l0 13"/>',
|
||
// tabler: world
|
||
globe: '<path d="M3 12a9 9 0 1 0 18 0a9 9 0 0 0 -18 0"/><path d="M3.6 9h16.8"/><path d="M3.6 15h16.8"/><path d="M11.5 3a17 17 0 0 0 0 18"/><path d="M12.5 3a17 17 0 0 1 0 18"/>',
|
||
// tabler: sparkles — the model gateway (LM Studio behind Atrium)
|
||
sparkles: '<path d="M16 18a2 2 0 0 1 2 2a2 2 0 0 1 2 -2a2 2 0 0 1 -2 -2a2 2 0 0 1 -2 2zm0 -12a2 2 0 0 1 2 2a2 2 0 0 1 2 -2a2 2 0 0 1 -2 -2a2 2 0 0 1 -2 2zm-7 12a6 6 0 0 1 6 -6a6 6 0 0 1 -6 -6a6 6 0 0 1 -6 6a6 6 0 0 1 6 6z"/>',
|
||
// tabler: logout
|
||
logout: '<path d="M14 8v-2a2 2 0 0 0 -2 -2h-7a2 2 0 0 0 -2 2v12a2 2 0 0 0 2 2h7a2 2 0 0 0 2 -2v-2"/><path d="M9 12h12l-3 -3"/><path d="M18 15l3 -3"/>',
|
||
};
|
||
|
||
function svg(p, w) {
|
||
return `<svg viewBox="0 0 24 24" width="${w || 16}" height="${w || 16}" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">${p}</svg>`;
|
||
}
|
||
|
||
/* ── module marks ───────────────────────────────────────────────────────────
|
||
What a module looks like on its tile: an Open Color hue (CSS `.mi.h-<hue>`) and one of these
|
||
glyphs. Both are allowlisted by the server (services/marketplace.py HUES/GLYPHS), and
|
||
tests/test_marketplace_unit.py fails if the lists drift apart. `galena`, `sygna` and `percent`
|
||
are the siblings' own app marks, so a module is recognisable in Atrium the way it looks at home;
|
||
the rest are Tabler icons scaled into the tile. */
|
||
const _mark = (p, w) => `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="${w}" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">${p}</svg>`;
|
||
const _tab = (p) => _mark(`<g transform="translate(12 12) scale(.55) translate(-12 -12)">${p}</g>`, 3.6);
|
||
const GLYPH = {
|
||
galena: _mark('<path d="M12 7.5v9"/><path d="M8.1 9.75l7.8 4.5"/><path d="M15.9 9.75l-7.8 4.5"/>', 2),
|
||
sygna: _mark('<path d="M8 8.5h8"/><path d="M8 12h8"/><path d="M8 15.5h4.5"/>', 2),
|
||
percent: _mark('<g transform="translate(12 12) scale(.8) translate(-12 -12)"><path d="M16 17a1 1 0 1 0 2 0a1 1 0 1 0 -2 0"/><path d="M6 7a1 1 0 1 0 2 0a1 1 0 1 0 -2 0"/><path d="M6 18l12 -12"/></g>', 2.6),
|
||
compass: _tab('<path d="M8 16l2 -6l6 -2l-2 6l-6 2"/><path d="M3 12a9 9 0 1 0 18 0a9 9 0 0 0 -18 0"/><path d="M12 3v2m0 14v2m-9 -9h2m14 0h2"/>'),
|
||
scale: _tab('<path d="M7 20l10 0"/><path d="M6 6l6 -1l6 1"/><path d="M12 3l0 17"/><path d="M9 12l-3 -6l-3 6a3 3 0 0 0 6 0"/><path d="M21 12l-3 -6l-3 6a3 3 0 0 0 6 0"/>'),
|
||
folder: _tab('<path d="M5 4h4l3 3h7a2 2 0 0 1 2 2v8a2 2 0 0 1 -2 2h-14a2 2 0 0 1 -2 -2v-11a2 2 0 0 1 2 -2"/>'),
|
||
file: _tab('<path d="M14 3v4a1 1 0 0 0 1 1h4"/><path d="M17 21h-10a2 2 0 0 1 -2 -2v-14a2 2 0 0 1 2 -2h7l5 5v11a2 2 0 0 1 -2 2"/><path d="M9 13h6"/><path d="M9 17h6"/>'),
|
||
users: _tab(ICN.users),
|
||
shield: _tab('<path d="M12 3a12 12 0 0 0 8.5 3a12 12 0 0 1 -8.5 15a12 12 0 0 1 -8.5 -15a12 12 0 0 0 8.5 -3"/><path d="M11 12a1 1 0 1 0 2 0a1 1 0 0 0 -2 0"/><path d="M12 13l0 2.5"/>'),
|
||
chart: _tab(ICN.dashboard),
|
||
clock: _tab('<path d="M3 12a9 9 0 1 0 18 0a9 9 0 0 0 -18 0"/><path d="M12 7v5l3 3"/>'),
|
||
lock: _tab('<path d="M5 13a2 2 0 0 1 2 -2h10a2 2 0 0 1 2 2v6a2 2 0 0 1 -2 2h-10a2 2 0 0 1 -2 -2v-6z"/><path d="M11 16a1 1 0 1 0 2 0a1 1 0 0 0 -2 0"/><path d="M8 11v-4a4 4 0 1 1 8 0v4"/>'),
|
||
star: _tab('<path d="M12 17.75l-6.172 3.245l1.179 -6.873l-5 -4.867l6.9 -1l3.086 -6.253l3.086 6.253l6.9 1l-5 4.867l1.179 6.873z"/>'),
|
||
bell: _tab('<path d="M10 5a2 2 0 1 1 4 0a7 7 0 0 1 4 6v3a4 4 0 0 0 2 3h-16a4 4 0 0 0 2 -3v-3a7 7 0 0 1 4 -6"/><path d="M9 17v1a3 3 0 0 0 6 0v-1"/>'),
|
||
plug: _tab('<path d="M9 7v4a2 2 0 0 0 2 2h2a2 2 0 0 0 2 -2v-4"/><path d="M10 3v4"/><path d="M14 3v4"/><path d="M12 15v6"/>'),
|
||
grid: _tab(ICN.grid),
|
||
key: _tab(ICN.key),
|
||
};
|
||
const HUES = ['grape', 'violet', 'indigo', 'blue', 'cyan', 'teal', 'green', 'lime', 'yellow', 'orange', 'red', 'pink', 'gray'];
|
||
|
||
/* No size: the stylesheet sizes it (`.mi`, and per context such as `.app .mi`), so a breakpoint can
|
||
resize it without fighting an inline style. */
|
||
function moduleIcon(m, size) {
|
||
const hue = HUES.includes(m.hue) ? m.hue : 'gray';
|
||
const glyph = GLYPH[m.glyph] || GLYPH.grid;
|
||
const style = size ? ` style="--mi:${Number(size)}px"` : '';
|
||
return `<span class="mi h-${hue}"${style}>${glyph}</span>`;
|
||
}
|
||
|
||
/* ── theme ──────────────────────────────────────────────────────────────── */
|
||
const TH = { system: ICN.desktop, light: ICN.sun, dark: ICN.moon };
|
||
|
||
function themeMode() {
|
||
try { return localStorage.getItem('dredd_theme') || localStorage.getItem('atrium_theme') || 'system'; } catch { return 'system'; }
|
||
}
|
||
function applyTheme(m) {
|
||
const dark = m === 'dark' || (m === 'system' && matchMedia('(prefers-color-scheme:dark)').matches);
|
||
document.documentElement.dataset.theme = dark ? 'dark' : 'light';
|
||
document.querySelectorAll('.js-theme').forEach((b) => { b.innerHTML = svg(TH[m] || TH.system); });
|
||
}
|
||
function cycleTheme() {
|
||
const next = { system: 'light', light: 'dark', dark: 'system' }[themeMode()] || 'system';
|
||
try { localStorage.setItem('dredd_theme', next); } catch { /* private mode */ }
|
||
applyTheme(next);
|
||
if (frame.win) {
|
||
seedModulePrefs(frame.slug);
|
||
try { frame.win.applyTheme(next); } catch { /* a module without the hook picks it up on its next load */ }
|
||
}
|
||
}
|
||
/* "System" has to keep following the OS after load, not just at first paint: switching the OS to
|
||
dark (or an automatic sunset switch) must repaint an open tab without a reload. */
|
||
(function followOsTheme() {
|
||
const mq = window.matchMedia && window.matchMedia('(prefers-color-scheme:dark)');
|
||
const onChange = () => { if (themeMode() === 'system') applyTheme('system'); };
|
||
// Guarded: at top level, a missing API would stop the whole file parsing past this point.
|
||
if (mq && mq.addEventListener) mq.addEventListener('change', onChange);
|
||
else if (mq && mq.addListener) mq.addListener(onChange); // Safari < 14
|
||
})();
|
||
|
||
/* ── i18n ───────────────────────────────────────────────────────────────── */
|
||
const SRC_LANG = 'pl';
|
||
const ALT_LANG = 'en';
|
||
|
||
const I18N = {
|
||
// shell
|
||
'System zarządzania': 'Management console',
|
||
'Zaloguj się': 'Sign in',
|
||
'Wyloguj się': 'Sign out',
|
||
'E-mail': 'Email',
|
||
'Hasło': 'Password',
|
||
'Pokaż hasło': 'Show password',
|
||
'Motyw': 'Theme',
|
||
'Język': 'Language',
|
||
'Konto': 'Account',
|
||
'Motyw: systemowy': 'Theme: system',
|
||
'Motyw: jasny': 'Theme: light',
|
||
'Motyw: ciemny': 'Theme: dark',
|
||
'Język: polski': 'Language: Polish',
|
||
'Język: angielski': 'Language: English',
|
||
'Strona główna': 'Home',
|
||
'Szukaj…': 'Search…',
|
||
'Szukaj modułów…': 'Search modules…',
|
||
'Wczytywanie…': 'Loading…',
|
||
'Brak wyników': 'Nothing found',
|
||
'Nie znaleziono strony.': 'Page not found.',
|
||
'Zapisz': 'Save',
|
||
'Anuluj': 'Cancel',
|
||
'Usuń': 'Delete',
|
||
'Zamknij': 'Close',
|
||
'Zapisano.': 'Saved.',
|
||
'Tej operacji nie da się cofnąć.': 'This cannot be undone.',
|
||
'Moduły': 'Modules',
|
||
'Moduł': 'Module',
|
||
// nav
|
||
'Moduły i dostęp': 'Modules and access',
|
||
'Ludzie i organizacja': 'People and organization',
|
||
'Platforma': 'Platform',
|
||
'Rozpatrz wnioski': 'Review requests',
|
||
'Dostosuj listę': 'Customize the list',
|
||
'Moduły w pasku bocznym': 'Modules in the sidebar',
|
||
'Odznaczone znikną z paska bocznego. W katalogu zostają.': 'Unticked ones leave the sidebar. They stay in the marketplace.',
|
||
'Katalog modułów': 'Marketplace',
|
||
'Katalog': 'Marketplace',
|
||
'Aplikacje': 'Apps',
|
||
'Konta': 'Accounts',
|
||
'Na pewno?': 'Sure?',
|
||
'Szukaj modułów': 'Search modules',
|
||
'Filtruj akcję': 'Filter by action',
|
||
'Filtruj akcję, np. module.…': 'Filter by action, e.g. module.…',
|
||
'Przejdź do treści': 'Skip to content',
|
||
'Wnioski': 'Requests',
|
||
'W skrócie': 'At a glance',
|
||
'Twoje aplikacje': 'Your apps',
|
||
'Aktywne sesje': 'Active sessions',
|
||
'Tokeny aplikacji': 'App tokens',
|
||
'Twoje wnioski w toku': 'Your open requests',
|
||
'Aktywni dziś': 'Active today',
|
||
'Aktywni w tym tygodniu': 'Active this week',
|
||
'Twoja aktywność': 'Your activity',
|
||
'zdarzenia dziennie, ostatnie 14 dni': 'events per day, last 14 days',
|
||
'Logowania na platformie': 'Platform sign-ins',
|
||
'nowe sesje dziennie, ostatnie 14 dni': 'new sessions per day, last 14 days',
|
||
'Zdarzenia na platformie': 'Platform events',
|
||
'wpisy w dzienniku dziennie, ostatnie 14 dni': 'audit entries per day, last 14 days',
|
||
'Najczęstsze zdarzenia': 'Most frequent events',
|
||
'ostatnie 7 dni': 'last 7 days',
|
||
'Z modułów': 'From the modules',
|
||
'Najbliższe terminy': 'Upcoming deadlines',
|
||
'Po terminie': 'Overdue',
|
||
'Moje sprawy': 'My matters',
|
||
'Czas w tym tygodniu': 'Time this week',
|
||
'Korespondencja do rozdzielenia': 'Correspondence to sort',
|
||
'Do zatwierdzenia': 'Awaiting approval',
|
||
'Otwarte szkice': 'Open drafts',
|
||
'Projekty': 'Projects',
|
||
'Czeka na mnie': 'Waiting for me',
|
||
'Do podpisu prawnika': 'Awaiting lawyer sign-off',
|
||
'Wygasa w 60 dni': 'Expiring within 60 days',
|
||
'Obowiązujące umowy': 'Contracts in force',
|
||
'Do zrobienia': 'To do',
|
||
'Oczekujące wnioski o dostęp:': 'Pending access requests:',
|
||
'Sprawdź stan': 'Check status',
|
||
'Moje wnioski': 'My requests',
|
||
'Zarządzanie': 'Manage',
|
||
'Administracja': 'Administration',
|
||
'Wnioski o dostęp': 'Access requests',
|
||
'Prośby o publikację': 'Publish requests',
|
||
'Skille i agenci, które ktoś chce udostępnić całej firmie.': 'Skills and agents somebody wants to share with the whole firm.',
|
||
'(aktualna w firmie)': '(current in the firm)',
|
||
'Pierwsza publikacja w firmie': 'First publication in the firm',
|
||
'Brak próśb o publikację.': 'No publish requests.',
|
||
'Publikacja skilli i agentów w firmie': 'Publishing skills and agents to the firm',
|
||
'Zgoda dotyczy każdej wersji, nie tylko pierwszej.': 'Approval applies to every version, not only the first.',
|
||
'Za zgodą administratora': 'With administrator approval',
|
||
'Od razu, bez zgody': 'Immediately, without approval',
|
||
'Eksport firmowych skilli i agentów': 'Exporting firm skills and agents',
|
||
'Własne osobiste może eksportować każdy.': 'Everyone may export their own personal ones.',
|
||
'Tylko administrator': 'Administrator only',
|
||
'Organizacja': 'Organization',
|
||
'Użytkownicy': 'Users',
|
||
'Ustawienia': 'Settings',
|
||
'Ogólne': 'General',
|
||
'Dziennik zdarzeń': 'Audit log',
|
||
// home + launcher
|
||
'Witaj,': 'Welcome,',
|
||
'Od czego zaczynamy?': 'Where shall we start?',
|
||
'Szukaj spraw, umów, plików i kancelarii…': 'Search matters, contracts, files and law firms…',
|
||
'Szukaj we wszystkich modułach': 'Search every module',
|
||
'Szukaj': 'Search',
|
||
'Wpisz co najmniej dwa znaki.': 'Type at least two characters.',
|
||
'Szukam…': 'Searching…',
|
||
'Nic nie znaleziono.': 'Nothing found.',
|
||
'Nie udało się przeszukać.': 'Search failed.',
|
||
// the model gateway (Home's assistant)
|
||
'Model AI': 'AI model',
|
||
'Serwer modeli wyłączony': 'Model server is off',
|
||
'Tylko szukaj': 'Search only',
|
||
'Zapytaj asystenta albo szukaj w modułach…': 'Ask the assistant or search the modules…',
|
||
'Zapytaj asystenta': 'Ask the assistant',
|
||
'Wyślij': 'Send',
|
||
'Odpowiedź AI': 'AI answer',
|
||
'· sprawdź w źródle': '· check it against the source',
|
||
'Nowa rozmowa': 'New conversation',
|
||
'Dołącz plik': 'Attach a file',
|
||
'Dołącz plik (PDF, DOCX, TXT, MD, CSV)': 'Attach a file (PDF, DOCX, TXT, MD, CSV)',
|
||
'Usuń plik': 'Remove the file',
|
||
'Czytam plik…': 'Reading the file…',
|
||
'Pliki nie przetrwały odświeżenia strony, dołącz je ponownie:': 'The files did not survive the page reload, attach them again:',
|
||
'Wybierz model asystenta, żeby zapytać o plik.': 'Pick an assistant model to ask about a file.',
|
||
'Do rozmowy można dołączyć najwyżej 3 pliki.': 'A conversation takes at most 3 files.',
|
||
'Myślę…': 'Thinking…',
|
||
'Ładuję model do pamięci karty graficznej, to trwa około minuty…': 'Loading the model into the graphics card, this takes about a minute…',
|
||
'Model nie odpowiedział.': 'The model did not answer.',
|
||
'Nie udało się: ': 'Failed: ',
|
||
'Model': 'Model',
|
||
'Terminy': 'Deadlines',
|
||
'Co wymaga działania w najbliższych dniach.': 'What needs doing in the coming days.',
|
||
'Umowy wygasające': 'Expiring contracts',
|
||
'Umowy, które kończą się w ciągu 60 dni.': 'Contracts that end within 60 days.',
|
||
'Ostatnie pliki': 'Recent files',
|
||
'Pliki otwierane ostatnio.': 'Files opened lately.',
|
||
'Wyślij ocenę': 'Submit a review',
|
||
'Oceń kancelarię po zakończonej sprawie.': 'Review a law firm after a closed matter.',
|
||
'Sprawa': 'Matter',
|
||
'Strona': 'Party',
|
||
'Korespondencja': 'Correspondence',
|
||
'Termin': 'Deadline',
|
||
'Faktura': 'Invoice',
|
||
'Zapytanie': 'Lead',
|
||
'Umowa': 'Contract',
|
||
'Kontrahent': 'Counterparty',
|
||
'Plik': 'File',
|
||
'Folder': 'Folder',
|
||
'Kancelaria': 'Law firm',
|
||
'Ocena': 'Review',
|
||
'Pytanie': 'Question',
|
||
'Nie masz jeszcze żadnych aplikacji.': "You don't have any apps yet.",
|
||
'Przeglądaj katalog': 'Browse the marketplace',
|
||
'Otwórz': 'Open',
|
||
'Więcej aplikacji': 'More apps',
|
||
'Wszystkie moduły w katalogu': 'All modules in the marketplace',
|
||
'Moduły otwierają się w nowej karcie. Jesteś już zalogowany — to jedno konto dla całej platformy.': 'Modules open in a new tab. You are already signed in: one account for the whole platform.',
|
||
'Moduły otwierają się w tej karcie. Jesteś już zalogowany — to jedno konto dla całej platformy.': 'Modules open in this tab. You are already signed in: one account for the whole platform.',
|
||
// marketplace
|
||
'Aplikacje dostępne w twojej organizacji': 'Apps available in your organization',
|
||
'Wszystkie': 'All',
|
||
'Dostępny': 'Available',
|
||
'Wkrótce': 'Coming soon',
|
||
'Masz dostęp': 'You have access',
|
||
'Wniosek wysłany': 'Request sent',
|
||
'Nieskonfigurowany': 'Not set up',
|
||
'Wszyscy': 'Everyone',
|
||
'Wybrani': 'Selected',
|
||
'Wyłączony': 'Off',
|
||
'Poproś o dostęp': 'Request access',
|
||
'Zarządzaj': 'Manage',
|
||
'Opis': 'Description',
|
||
'Kategoria': 'Category',
|
||
'Potrzebujesz dostępu? Kontakt:': 'Need access? Contact:',
|
||
'Ten moduł nie ma jeszcze adresu w tej instancji — administrator musi go skonfigurować.': "This module doesn't have an address on this instance yet — an administrator has to set it up.",
|
||
'Moduł będzie dostępny wkrótce.': 'This module is coming soon.',
|
||
'Dostęp do tego modułu przyznaje administrator.': 'An administrator grants access to this module.',
|
||
'Twój wniosek czeka na decyzję administratora.': 'Your request is waiting for an administrator.',
|
||
'Brak modułów.': 'No modules.',
|
||
'Po co ci ten moduł? (opcjonalnie)': 'What do you need it for? (optional)',
|
||
'Wyślij wniosek': 'Send request',
|
||
'Wniosek wysłany.': 'Request sent.',
|
||
'Atrium otwiera moduł — na razie logujesz się do niego osobno, jego własnym kontem.': 'Atrium opens the module — for now you sign in to it separately, with its own account.',
|
||
// requests
|
||
'Nie wysłano jeszcze żadnych wniosków.': "You haven't sent any requests yet.",
|
||
'Oczekuje': 'Pending',
|
||
'Zatwierdzony': 'Approved',
|
||
'Odrzucony': 'Declined',
|
||
'Wysłano': 'Sent',
|
||
'Decyzja': 'Decision',
|
||
'Notatka': 'Note',
|
||
'Użytkownik': 'User',
|
||
'Zatwierdź': 'Approve',
|
||
'Odrzuć': 'Decline',
|
||
'Notatka do decyzji (opcjonalnie)': 'Note on the decision (optional)',
|
||
'Brak wniosków.': 'No requests.',
|
||
// connected apps (app tokens) — minting lives only in the hub, so this screen is the family's
|
||
// only one. Every string that tells someone what a token reaches is here, in both languages.
|
||
'Połączone aplikacje': 'Connected apps',
|
||
// skills and agents
|
||
'Skille i agenci': 'Skills and agents',
|
||
'Instrukcje i asystenci, z których korzystasz ty i twoja firma.': 'Instructions and assistants that you and your firm use.',
|
||
'Moje': 'Mine',
|
||
'Firmowe': "The firm's",
|
||
'Skille': 'Skills',
|
||
'Agenci': 'Agents',
|
||
'Zasięg': 'Scope',
|
||
'Osobisty': 'Personal',
|
||
'Firmowy': 'Firm',
|
||
'Zarchiwizowany': 'Archived',
|
||
'Czeka na zgodę': 'Awaiting approval',
|
||
'Zaimportowany': 'Imported',
|
||
'Nie masz jeszcze żadnego skilla.': "You don't have any skills yet.",
|
||
'Nie masz jeszcze żadnego agenta.': "You don't have any agents yet.",
|
||
'Firma nie ma jeszcze żadnego skilla.': 'The firm has no skills yet.',
|
||
'Firma nie ma jeszcze żadnego agenta.': 'The firm has no agents yet.',
|
||
'Nowy skill': 'New skill',
|
||
'Nowa wersja': 'New version',
|
||
'Opublikuj w firmie': 'Publish to the firm',
|
||
'Eksportuj': 'Export',
|
||
'Archiwizuj': 'Archive',
|
||
'Aktualna': 'Current',
|
||
'Utworzona': 'Created',
|
||
'Różnice względem': 'Changes since',
|
||
'Pierwsza wersja': 'First version',
|
||
'Bez zmian w treści.': 'No change in the content.',
|
||
'Wersja': 'Version',
|
||
'Wersje': 'Versions',
|
||
'Pliki': 'Files',
|
||
'Treść': 'Content',
|
||
'np. umowa-najmu': 'e.g. lease-agreement',
|
||
'Małe litery, cyfry i myślniki. Nie da się go później zmienić.': "Lower-case letters, digits and hyphens. It can't be changed later.",
|
||
'Opis mówi modelowi, kiedy sięgnąć po ten skill.': 'The description tells the model when to reach for this skill.',
|
||
'Wybrane pliki zastąpią obecne. Bez wyboru obecne pliki przechodzą do nowej wersji.': 'The files you pick replace the current ones. Pick none and the current files carry over to the new version.',
|
||
'Pliki pomocnicze, łącznie do 10 MB.': 'Supporting files, up to 10 MB in total.',
|
||
'Usuń obecne pliki': 'Remove the current files',
|
||
'plik do pobrania, model go jeszcze nie czyta': "a file to download, the model doesn't read it yet",
|
||
'Plik do pobrania, model go jeszcze nie czyta:': "Files to download, the model doesn't read them yet:",
|
||
'Ta wersja czeka na zgodę administratora.': 'This version is waiting for an administrator to approve it.',
|
||
'Zapisano nową wersję.': 'New version saved.',
|
||
'Skill utworzony.': 'Skill created.',
|
||
'Wysłano do zatwierdzenia przez administratora.': 'Sent to an administrator for approval.',
|
||
'Opublikowano w firmie.': 'Published to the firm.',
|
||
'Zarchiwizowano.': 'Archived.',
|
||
'Importuj ZIP': 'Import ZIP',
|
||
'Importuj': 'Import',
|
||
'Paczka ZIP': 'ZIP pack',
|
||
'Skill albo agent w formacie SKILL.md, do 10 MB. Import tworzy twoją osobistą kopię; nic nie aktualizuje się samo.': 'A skill or an agent in the SKILL.md format, up to 10 MB. Importing makes your own personal copy; nothing updates by itself.',
|
||
'Wybierz plik ZIP.': 'Choose a ZIP file.',
|
||
'Paczka odrzucona': 'Pack refused',
|
||
'Pliki, których to dotyczy:': 'The files concerned:',
|
||
'Wybierz inny plik': 'Choose another file',
|
||
'Zapisane tylko jako informacja:': 'Kept as information only:',
|
||
'zostanie dodany jako nowy skill': 'will be added as a new skill',
|
||
'Pominięte pliki (nie należą do żadnego skilla):': 'Skipped files (they belong to no skill):',
|
||
'Masz już ten skill': 'You already have this skill',
|
||
'Ta sama treść jest już w twoich skillach. Dodać ją jako nową wersję?': 'The same content is already among your skills. Add it as a new version?',
|
||
'Dodaj jako nową wersję': 'Add as a new version',
|
||
'Agent zaimportowany': 'Agent imported',
|
||
'Zaimportowano': 'Imported',
|
||
'Nowy agent': 'New agent',
|
||
'Agent utworzony.': 'Agent created.',
|
||
'Instrukcja': 'Instructions',
|
||
'Podpowiedź modelu': 'Model hint',
|
||
'Podpowiedź modelu:': 'Model hint:',
|
||
'np. claude-sonnet-4-5': 'e.g. claude-sonnet-4-5',
|
||
'Tylko podpowiedź — model wybiera platforma.': 'A hint only — the platform picks the model.',
|
||
'Prosi o narzędzia (zapisane tylko jako informacja):': 'Asks for tools (kept as information only):',
|
||
'Przypięte skille': 'Pinned skills',
|
||
'Brak przypiętych skilli.': 'No skills pinned.',
|
||
'Skill zarchiwizowany': 'Skill archived',
|
||
'aktualna wersja': 'current version',
|
||
'Agent firmowy przypina tylko opublikowane wersje firmowych skilli.': "A firm agent pins only the firm's published skill versions.",
|
||
'Nie masz skilli do przypięcia.': 'You have no skills to pin.',
|
||
'Aplikacje i skrypty, które logują się twoim kontem bez hasła.': 'Apps and scripts that sign in as you, without a password.',
|
||
'Twoje tokeny': 'Your tokens',
|
||
'Nowy token': 'New token',
|
||
'Utwórz token': 'Create token',
|
||
'Tokeny są wyłączone na tej instancji.': 'App tokens are switched off on this instance.',
|
||
'Token działa w każdym module platformy — przedrostek mówi, gdzie powstał, a nie gdzie działa.': 'A token works in every module on the platform — the prefix says where it was minted, not where it works.',
|
||
'Token działa w tej instancji i jest równoważny twojemu hasłu, więc traktuj go jak hasło.': 'A token works in this instance and is as good as your password, so treat it like one.',
|
||
'Żadna aplikacja nie jest połączona.': 'No apps are connected.',
|
||
'Odwołanie działa natychmiast i tylko na ten jeden token. Zmiana twojego hasła odwołuje wszystkie.': 'Revoking is immediate and reaches that one token only. Changing your password revokes all of them.',
|
||
'Utworzony w': 'Minted in',
|
||
'utworzony': 'created',
|
||
'Zakres': 'Scope',
|
||
'Ostatnio użyty': 'Last used',
|
||
'Wygasa': 'Expires',
|
||
'Wygasa po (dni bez użycia)': 'Expires after (days unused)',
|
||
'nigdy': 'never',
|
||
'Bez nazwy': 'Unnamed',
|
||
'Aktywny': 'Active',
|
||
'Wygasł': 'Expired',
|
||
'Odwołany': 'Revoked',
|
||
'Odwołaj': 'Revoke',
|
||
'Token odwołany.': 'Token revoked.',
|
||
'Token utworzony.': 'Token created.',
|
||
'odczyt i zapis': 'read and write',
|
||
'tylko odczyt': 'read-only',
|
||
'Token działa w każdym module, nie tylko w wybranym tutaj: przedrostek mówi, gdzie powstał. Uprawnienia ma takie jak jego twórca.': 'The token works in every module, not just the one picked here: the prefix says where it was minted. It has the permissions of its creator.',
|
||
'GalenaConnect na laptopie': 'GalenaConnect on the laptop',
|
||
'Nazwa jest po to, żeby dało się odwołać jeden token, a nie wszystkie.': 'The name is what makes it possible to revoke one token instead of all of them.',
|
||
'Wybór nadaje tokenowi przedrostek, po którym go rozpoznasz na liście i w dzienniku zdarzeń.': 'Your choice gives the token the prefix you will recognise it by, here and in the audit log.',
|
||
'Każde użycie przesuwa termin, więc token używany nie wygasa, a zapomniany umiera sam. Maksimum:': 'Every use pushes the date forward, so a token in use never expires and a forgotten one dies on its own. Maximum:',
|
||
'Liczba dni musi być liczbą całkowitą od 1 do maksimum podanego niżej.': 'The number of days must be a whole number, from 1 up to the maximum given below.',
|
||
'Skopiuj token teraz. Nie da się go odczytać później — serwer przechowuje tylko jego skrót.': 'Copy the token now. It cannot be read back later: the server keeps only its hash.',
|
||
'Kopiuj': 'Copy',
|
||
'Skopiowano.': 'Copied.',
|
||
'Nie udało się skopiować — zaznacz i skopiuj ręcznie.': 'Couldn’t copy — select it and copy it by hand.',
|
||
'Wklej go w aplikacji, która ma się nim logować. Działa w każdym module; jeśli wycieknie, odwołaj go tutaj.': 'Paste it into the app that will sign in with it. It works in every module; if it leaks, revoke it here.',
|
||
'Wklej go w aplikacji, która ma się nim logować. Jeśli wycieknie, odwołaj go tutaj.': 'Paste it into the app that will sign in with it. If it leaks, revoke it here.',
|
||
'Odwołać token? Aplikacja, która go używa, straci dostęp natychmiast — we wszystkich modułach.': 'Revoke the token? Whatever is using it loses access immediately, in every module.',
|
||
'Odwołać token? Aplikacja, która go używa, straci dostęp natychmiast.': 'Revoke the token? Whatever is using it loses access immediately.',
|
||
// admin overview
|
||
'Oczekujące wnioski': 'Pending requests',
|
||
'Stan': 'Health',
|
||
'Sprawdź': 'Check',
|
||
'Adres': 'Address',
|
||
'Adres stanu': 'Health address',
|
||
'Wynik': 'Result',
|
||
'brak': 'none',
|
||
'Niektóre moduły nie mają adresu, więc nikt ich nie zobaczy wśród swoich aplikacji.': "Some modules have no address, so nobody will see them among their apps.",
|
||
'przekroczono czas': 'timed out',
|
||
'brak połączenia': 'unreachable',
|
||
'przekierowanie (nie śledzone)': 'redirect (not followed)',
|
||
'błąd HTTP': 'HTTP error',
|
||
'brak adresu stanu': 'no health address',
|
||
'nieobsługiwany adres': 'unsupported address',
|
||
'zajęte — spróbuj ponownie': 'busy — try again',
|
||
// admin modules
|
||
'Nowy moduł': 'New module',
|
||
'Dostępność': 'Availability',
|
||
'Przypisania': 'Assignments',
|
||
'Kolejność': 'Order',
|
||
'Kolejność musi być liczbą całkowitą od 0 do 10000.': 'Order must be a whole number from 0 to 10000.',
|
||
'Identyfikator': 'Slug',
|
||
'Nazwa': 'Name',
|
||
'Hasło reklamowe': 'Tagline',
|
||
'Kolor': 'Colour',
|
||
'Znak': 'Mark',
|
||
'Szczegóły': 'Details',
|
||
'Adres modułu (np. https://twoj-host/galena)': 'Module address (e.g. https://your-host/galena)',
|
||
'Adres stanu (np. https://twoj-host/galena/api/v1/health)': 'Health address (e.g. https://your-host/galena/api/v1/health)',
|
||
'Otwórz w katalogu': 'View in marketplace',
|
||
'Usunąć moduł? Znikną też jego przypisania i wnioski.': 'Delete the module? Its assignments and requests go with it.',
|
||
'Wszyscy użytkownicy': 'All users',
|
||
'Wybrane jednostki i osoby': 'Selected units and people',
|
||
'Nikt (ukryty w katalogu)': 'Nobody (hidden from the marketplace)',
|
||
'Przypisania działają tylko przy dostępności „Wybrani”.': 'Assignments only apply when availability is “Selected”.',
|
||
'Moduł przypisany do jednostki trafia do jej członków i do członków jednostek podrzędnych.': 'A module assigned to a unit reaches its members and the members of every unit below it.',
|
||
'Jednostka': 'Unit',
|
||
'Przypisz jednostkę': 'Assign unit',
|
||
'Przypisz osobę': 'Assign person',
|
||
'Brak przypisań.': 'No assignments.',
|
||
'Identyfikator nie zmienia się po utworzeniu.': "The slug can't be changed after creation.",
|
||
// admin org
|
||
'Nowa jednostka': 'New unit',
|
||
'Jednostka nadrzędna': 'Parent unit',
|
||
'Rodzaj': 'Kind',
|
||
'Przestrzeń': 'Workspace',
|
||
'Dział': 'Department',
|
||
'Zespół': 'Team',
|
||
'Członkowie': 'Members',
|
||
'Członek': 'Member',
|
||
'Edytor': 'Editor',
|
||
'Zatwierdzający': 'Approver',
|
||
'Zarządca jednostki': 'Unit manager',
|
||
'Dodaj': 'Add',
|
||
'Bezpośrednio': 'Direct',
|
||
'Dostęp z jednostki nadrzędnej': 'Access from a parent unit',
|
||
'Mogą przeglądać lub zarządzać tą jednostką, ale nie są jej członkami — nie otrzymują przypisanych do niej modułów.': "They can view or manage this unit but are not its members, so they don't receive the modules assigned to it.",
|
||
'podgląd': 'view',
|
||
'edycja': 'edit',
|
||
'zatwierdzanie': 'approve',
|
||
'zarządzanie': 'manage',
|
||
'Szukaj… (Ctrl+K)': 'Search… (Ctrl+K)',
|
||
'Brak członków.': 'No members.',
|
||
'Członkowie jednostki otrzymują moduły przypisane do niej i do jednostek nadrzędnych.': 'Members of a unit receive the modules assigned to it and to the units above it.',
|
||
// the admission refusal — built in admissionRefusal() around the module names the server sends
|
||
'Ta zmiana dałaby dostęp do modułu, którego nie moderujesz:': 'This change would give access to a module you do not moderate:',
|
||
'Ta zmiana dałaby dostęp do modułów, których nie moderujesz:': 'This change would give access to modules you do not moderate:',
|
||
'Wpuścić kogoś do modułu może tylko administrator albo moderator tego modułu.': 'Only an administrator or that module’s moderator can let someone into a module.',
|
||
'Usunąć jednostkę?': 'Delete the unit?',
|
||
// admin users
|
||
'Nowy użytkownik': 'New user',
|
||
'Imię i nazwisko': 'Full name',
|
||
'aktywny': 'active',
|
||
'nieaktywny': 'inactive',
|
||
'Dezaktywuj': 'Deactivate',
|
||
'Dezaktywować użytkownika? Jego sesje we wszystkich modułach zostaną zakończone.': 'Deactivate the user? Their sessions in every module end immediately.',
|
||
'Przywróć': 'Reactivate',
|
||
'Konto przywrócone.': 'Account reactivated.',
|
||
'Nie znaleziono użytkownika.': 'User not found.',
|
||
// correcting an account, and the password reset — the hub is the only place either can happen
|
||
'Edytuj': 'Edit',
|
||
'Edytuj konto': 'Edit account',
|
||
'Dla osoby, która zapomniała hasła: tylko administrator może je ustawić, bo konta zapisuje wyłącznie Atrium.': 'For someone who has forgotten theirs: only an administrator can set it, because Atrium is the only writer of accounts.',
|
||
'E-mail jest nazwą, którą wpisuje się przy logowaniu — jedną dla całej platformy. Zmiana nie kończy sesji tej osoby.': 'The email is the name people sign in with — one for the whole platform. Changing it does not end their sessions.',
|
||
// 'Hasło' itself is already above, with the login form.
|
||
'Ustaw hasło': 'Set password',
|
||
'Nowe hasło': 'New password',
|
||
'Nowe hasło kończy wszystkie sesje i tokeny tej osoby. Przekaż je bezpiecznie i poproś o zmianę po zalogowaniu.': 'A new password ends every session and token this person holds. Hand it over safely and ask them to change it after signing in.',
|
||
'Co najmniej 10 znaków. Zdarzenie trafia do dziennika wraz z tym, kto je wykonał.': 'At least 10 characters. The audit log records the reset and who made it.',
|
||
'Hasło ustawione. Sesje tej osoby zostały zakończone.': 'Password set. That person’s sessions have ended.',
|
||
'Jedno konto na osobę, wspólne dla wszystkich modułów. Logowanie odbywa się tutaj; moduły tylko odczytują tę samą sesję.': 'One account per person, shared by every module. Signing in happens here; the modules only read the same session.',
|
||
// the three tiers. Administrator = platform-wide, Moderator = exactly one module, User = may
|
||
// open exactly one module. The owner chose those words, so they are used verbatim in both
|
||
// languages, in the API and in the table. The fourth answer is no row at all: no access.
|
||
'Rola': 'Role',
|
||
'Uprawnienia': 'Permissions',
|
||
'Dostęp': 'Access',
|
||
'Dostęp do modułów': 'Module access',
|
||
'Nadaj dostęp': 'Grant access',
|
||
'Nikt nie ma jeszcze dostępu.': 'Nobody has access yet.',
|
||
'Nie ma dostępu do żadnego modułu.': 'Has access to no module.',
|
||
'Odbierz': 'Revoke',
|
||
'Bez wpisu nie da się wejść do modułu. Użytkownik z niego korzysta, moderator także nim zarządza (tylko tym modułem).': 'Without an entry nobody can enter the module. A user works in it; a moderator also administers it (this module only).',
|
||
'Kto naprawdę ma ten moduł. Administrator wchodzi wszędzie bez wpisu.': 'Who really has this module. An administrator gets in everywhere without an entry.',
|
||
'Moduł przypisany do jednostki dostają jej członkowie i członkowie jednostek podrzędnych.': 'A module assigned to an organizational unit goes to its members and to the members of every unit below it.',
|
||
'To nie jest jednorazowe nadanie: kto dołączy do jednostki, dostanie moduł, a kto odejdzie, straci go.': 'This is not a one-time bulk grant: whoever joins the unit gets the module, whoever leaves loses it.',
|
||
'Dostęp cofnięty. Osoba nadal należy do jednostki, która ma ten moduł, więc zachowuje zwykły dostęp.': 'Access revoked. They are still in an organizational unit that has this module, so they keep ordinary access.',
|
||
'Bez wpisu na tej liście osoba nie wejdzie do modułu. Moderator dodatkowo zarządza jednym modułem i nie ma uprawnień w pozostałych.': 'Without an entry on this list they cannot enter the module. A moderator also administers one module and has no permissions in the others.',
|
||
'Administrator wchodzi do każdego modułu i zarządza nim niezależnie od tej listy.': 'An administrator enters and administers every module, whatever this list says.',
|
||
'Pełne uprawnienia na całej platformie: wszystkie moduły i sam Atrium. Ostatniego administratora nie da się odebrać ani dezaktywować.': 'Full permissions across the whole platform: every module, and Atrium itself. The last administrator can be neither demoted nor deactivated.',
|
||
'To twoje własne konto. Po odebraniu sobie roli nie przywrócisz jej samodzielnie.': 'This is your own account. Once you take the role off yourself you cannot put it back.',
|
||
'Konto samo w sobie nie otwiera żadnego modułu — dostęp nadaje się poniżej albo później. Rola administratora jest domyślnie wyłączona.': 'An account on its own opens no module: access is granted below, or later. The administrator role is off by default.',
|
||
'Jako użytkownik. Moderatora nadaje się na stronie danego modułu.': 'As a user. A moderator is appointed on that module’s own page.',
|
||
'Rola jest domyślnie wyłączona — nadaje się ją świadomie.': 'The role is off by default: granting it is a deliberate act.',
|
||
// admin settings
|
||
'Nazwa instancji': 'Instance name',
|
||
'Powitanie na stronie głównej': 'Welcome message on Home',
|
||
'Kontakt w sprawie dostępu': 'Contact for access questions',
|
||
'Otwieranie modułów': 'Opening modules',
|
||
'Nowa karta': 'New tab',
|
||
'Ta sama karta': 'Same tab',
|
||
'Wnioski o dostęp dozwolone': 'Allow access requests',
|
||
'Domyślna dostępność nowego modułu': 'Default availability for a new module',
|
||
'Pokazywana w pasku bocznym i tytule strony.': 'Shown in the sidebar and the page title.',
|
||
'Zwykły tekst nad listą aplikacji.': 'Plain text above the list of apps.',
|
||
'Pokazywany w katalogu jako tekst, nie link.': 'Shown in the marketplace as text, never a link.',
|
||
'Użytkownicy mogą prosić o moduły dostępne dla wybranych.': 'Users may ask for modules offered to selected people.',
|
||
// audit
|
||
'Czas': 'Time',
|
||
'Kto': 'Who',
|
||
'Akcja': 'Action',
|
||
'Obiekt': 'Entity',
|
||
'Zmiany': 'Changes',
|
||
'Wcześniejsze': 'Older',
|
||
'Najnowsze': 'Newest',
|
||
// model providers
|
||
'Dostawcy modeli': 'Model providers',
|
||
'Edytuj dostawcę': 'Edit provider',
|
||
'Dostawca': 'Provider',
|
||
'Modele': 'Models',
|
||
'Klucz API': 'API key',
|
||
'Region': 'Region',
|
||
'Podmiot przetwarzający': 'Processor',
|
||
'Adres umowy powierzenia (DPA)': 'DPA address',
|
||
'Trenuje na danych': 'Trains on data',
|
||
'Dostawca trenuje modele na przesłanych danych': 'The provider trains models on the data it is sent',
|
||
'Dla kogo': 'Allowed for',
|
||
'Zgodnie z polityką': 'As the policy says',
|
||
'wyłączony': 'disabled',
|
||
'ustawiony': 'set',
|
||
'Wyłącz': 'Disable',
|
||
'Włącz': 'Enable',
|
||
'Usuń klucz': 'Remove key',
|
||
'lokalny': 'local',
|
||
'API (zewnętrzny)': 'API (hosted)',
|
||
'Nikt': 'Nobody',
|
||
'Tylko administratorzy': 'Administrators only',
|
||
'Każdy': 'Everyone',
|
||
'Polityka użycia': 'Usage policy',
|
||
'Kto może używać modeli': 'Who may use the models',
|
||
'Tylko dostawcy z UE/EOG (lub lokalni)': 'EU/EEA providers only (or local ones)',
|
||
'Zapisz politykę': 'Save policy',
|
||
'Brak dostawców modeli.': 'No model providers yet.',
|
||
'UE/EOG': 'EU/EEA',
|
||
'poza UE': 'outside the EU',
|
||
'Pozostaw puste, aby zachować obecny klucz': 'Leave empty to keep the current key',
|
||
'Klucz jest tylko do zapisu: nikt, także administrator, nie zobaczy go ponownie.': 'The key is write-only: nobody, the administrator included, sees it again.',
|
||
'Ten serwer nie ma ustawionego MODEL_PROVIDER_SECRET, więc nie może zapisać klucza API.': 'This server has no MODEL_PROVIDER_SECRET, so it cannot store an API key.',
|
||
'Obowiązuje we wszystkich modułach. Wyłączonego dostawcę można usunąć, dopóki nie policzył żadnego przebiegu; potem zostaje na liście, bo przebiegi pamiętają, kto je policzył.': 'Applies in every module. A disabled provider can be deleted as long as it has computed no run; after that it stays on the list, because runs remember which one computed them.',
|
||
'Usunąć tego dostawcę razem z jego kluczami? Tego nie da się cofnąć.': 'Delete this provider together with its keys? This cannot be undone.',
|
||
'Usunięto.': 'Deleted.',
|
||
'Wyłączyć tego dostawcę? Moduły przestaną go oferować.': 'Disable this provider? Modules stop offering it.',
|
||
'Usunąć zapisany klucz API tego dostawcy?': 'Remove the stored API key of this provider?',
|
||
'Czyj klucz': 'Whose key',
|
||
'Klucz firmy': 'The firm’s key',
|
||
'Własny klucz użytkownika': 'Each user’s own key',
|
||
'Bez klucza': 'No key',
|
||
'Zmiana adresu albo odejście od własnych kluczy użytkowników usuwa wszystkie zapisane klucze użytkowników tego dostawcy.': 'Changing the address, or moving away from users’ own keys, deletes every user key stored for this provider.',
|
||
'Moje klucze modeli': 'My model keys',
|
||
'Dostawcy modeli, którzy używają twojego własnego klucza API zamiast klucza firmy.': 'Model providers that use your own API key instead of the firm’s.',
|
||
'Żaden dostawca nie potrzebuje twojego klucza.': 'No provider needs your key.',
|
||
'Dodaj klucz': 'Add key',
|
||
'Twój własny klucz API jest potrzebny dla:': 'Your own API key is needed for:',
|
||
'Zmień klucz': 'Change key',
|
||
'Usunąć twój zapisany klucz API tego dostawcy?': 'Remove your stored API key for this provider?',
|
||
'Dodaj dostawcę': 'Add provider',
|
||
'Wklej klucz API albo adres serwera': 'Paste an API key or a server’s address',
|
||
'Klucz (jeśli serwer go wymaga)': 'Key (if the server needs one)',
|
||
'Znaleziono modele.': 'Models found.',
|
||
'Odśwież modele': 'Refresh models',
|
||
'Odświeżono modele.': 'Models refreshed.',
|
||
// discover/refresh refusals (provider_key_refused, provider_unreachable, provider_no_models,
|
||
// provider_unknown_key) carry their own `en` and are worded by coreRefusal(), not here
|
||
};
|
||
|
||
let LANG = (function () {
|
||
try {
|
||
const s = localStorage.getItem('atrium_lang');
|
||
if (s === SRC_LANG || s === ALT_LANG) return s;
|
||
} catch { /* private mode */ }
|
||
return (navigator.language || SRC_LANG).toLowerCase().startsWith(SRC_LANG) ? SRC_LANG : ALT_LANG;
|
||
})();
|
||
|
||
const _origAttr = new WeakMap();
|
||
|
||
function _tr(s) {
|
||
if (LANG === SRC_LANG || s == null) return s;
|
||
const k = String(s).trim();
|
||
if (!k) return s;
|
||
const v = I18N[k];
|
||
return v ? String(s).replace(k, v) : s;
|
||
}
|
||
function _trAttr(el, attr) {
|
||
const cur = el.getAttribute && el.getAttribute(attr);
|
||
if (cur == null) return;
|
||
let orig = _origAttr.get(el);
|
||
if (!orig) { orig = {}; _origAttr.set(el, orig); }
|
||
if (orig[attr] === undefined) orig[attr] = cur;
|
||
el.setAttribute(attr, _tr(orig[attr]));
|
||
}
|
||
/* Translations set nodeValue / setAttribute, never innerHTML — so esc() still holds and a
|
||
dictionary entry can never inject markup. */
|
||
function localize(root) {
|
||
if (root) nameIconButtons(root);
|
||
if (LANG === SRC_LANG || !root) return;
|
||
const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT);
|
||
const nodes = [];
|
||
while (walker.nextNode()) nodes.push(walker.currentNode);
|
||
nodes.forEach((n) => {
|
||
if (n.parentElement && n.parentElement.closest('[data-no-i18n]')) return;
|
||
const t = _tr(n.nodeValue);
|
||
if (t !== n.nodeValue) n.nodeValue = t;
|
||
});
|
||
root.querySelectorAll('[title],[placeholder],[data-label],[aria-label]').forEach((el) => {
|
||
if (el.closest('[data-no-i18n]')) return;
|
||
_trAttr(el, 'title');
|
||
_trAttr(el, 'placeholder');
|
||
_trAttr(el, 'data-label');
|
||
_trAttr(el, 'aria-label');
|
||
});
|
||
}
|
||
/* An icon-only button is named by its tooltip, which touch users never see and some screen readers
|
||
skip: give every titled button without an accessible name the same words as aria-label, which
|
||
_trAttr then translates like any other attribute. */
|
||
function nameIconButtons(root) {
|
||
root.querySelectorAll('button[title]:not([aria-label])').forEach((b) => {
|
||
if (!b.textContent.trim()) b.setAttribute('aria-label', b.getAttribute('title'));
|
||
});
|
||
}
|
||
|
||
/* A one-click removal asks once, in place: the first click turns the button into "Na pewno?", the
|
||
second within four seconds does it. Works inside an open dialog, where a confirm dialog of its own
|
||
would replace the one the person is working in. */
|
||
function confirmTwice(btn, fn) {
|
||
if (btn.dataset.armed) { fn(); return; }
|
||
btn.dataset.armed = '1';
|
||
const was = btn.innerHTML;
|
||
btn.innerHTML = esc(_tr('Na pewno?'));
|
||
btn.classList.add('armed');
|
||
setTimeout(() => { if (document.contains(btn)) { delete btn.dataset.armed; btn.innerHTML = was; btn.classList.remove('armed'); } }, 4000);
|
||
}
|
||
|
||
function cycleLang() {
|
||
LANG = LANG === SRC_LANG ? ALT_LANG : SRC_LANG;
|
||
try { localStorage.setItem('atrium_lang', LANG); } catch { /* private mode */ }
|
||
if (frame.slug) seedModulePrefs(frame.slug);
|
||
location.reload();
|
||
}
|
||
|
||
/* ── vocabularies ───────────────────────────────────────────────────────── */
|
||
const STATUS_LABEL = { live: 'Dostępny', beta: 'Beta', coming_soon: 'Wkrótce' };
|
||
const AVAIL_LABEL = { everyone: 'Wszyscy', selected: 'Wybrani', off: 'Wyłączony' };
|
||
const AVAIL_LONG = { everyone: 'Wszyscy użytkownicy', selected: 'Wybrane jednostki i osoby', off: 'Nikt (ukryty w katalogu)' };
|
||
const REQ_LABEL = { pending: 'Oczekuje', approved: 'Zatwierdzony', declined: 'Odrzucony' };
|
||
const KIND_LABEL = { workspace: 'Przestrzeń', group: 'Dział', folder: 'Zespół' };
|
||
const ACCESS_LABEL = { viewer: 'podgląd', editor: 'edycja', approver: 'zatwierdzanie', manager: 'zarządzanie' };
|
||
const ROLE_LABEL = { viewer: 'Członek', editor: 'Edytor', approver: 'Zatwierdzający', manager: 'Zarządca jednostki' };
|
||
/* What somebody may do in ONE module — the `role` on their `module_permission` row. The third
|
||
answer is the absence of a row, which is no entry at all, so it has no label here. Keep in step
|
||
with dredd-core's MODULE_ROLES; the server validates against that tuple and so does a CHECK. */
|
||
const MODULE_ROLE_LABEL = { user: 'Użytkownik', moderator: 'Moderator' };
|
||
const PROBE_ERR = {
|
||
timeout: 'przekroczono czas', unreachable: 'brak połączenia', redirect: 'przekierowanie (nie śledzone)',
|
||
'http error': 'błąd HTTP', 'no health address': 'brak adresu stanu', 'unsupported address': 'nieobsługiwany adres',
|
||
busy: 'zajęte — spróbuj ponownie',
|
||
};
|
||
|
||
function statusChip(s) {
|
||
if (s === 'live') return '';
|
||
return `<span class="chip ${s === 'beta' ? 'warn' : ''}">${esc(STATUS_LABEL[s] || s)}</span>`;
|
||
}
|
||
function availChip(a) {
|
||
const cls = { everyone: 'ok', selected: '', off: 'err' }[a] || '';
|
||
return `<span class="chip ${cls}">${esc(AVAIL_LABEL[a] || a)}</span>`;
|
||
}
|
||
function reqChip(s) {
|
||
const cls = { pending: 'warn', approved: 'ok', declined: 'err' }[s] || '';
|
||
return `<span class="chip ${cls}">${esc(REQ_LABEL[s] || s)}</span>`;
|
||
}
|
||
|
||
/* ── auth ───────────────────────────────────────────────────────────────── */
|
||
/* Signing out, or a lapsed session, drops what was read as that user, so whoever signs in next on this
|
||
browser never sees their apps, badge or user list — not even when a first read fails. */
|
||
function showLogin() {
|
||
Object.assign(state, { launcher: [], pending: 0, users: [], modules: null, stale: true,
|
||
// Someone's own credentials and the catalogue as THEY were allowed to see
|
||
// it: both are per-person, so neither may outlive the session.
|
||
_tokens: null, _catalogue: null });
|
||
chatForget(); // the Home conversation is the same: per person, read with their session
|
||
$('login').classList.remove('hidden');
|
||
$('app').classList.add('hidden');
|
||
}
|
||
function showApp() { $('login').classList.add('hidden'); $('app').classList.remove('hidden'); }
|
||
|
||
async function doLogin(e) {
|
||
if (e) e.preventDefault();
|
||
const err = $('loginErr');
|
||
err.classList.add('hidden');
|
||
try {
|
||
// The reply is the user only: the credential is the HttpOnly cookie the same reply set.
|
||
const r = await api('POST', '/auth/login', {
|
||
email: $('email').value, password: $('password').value,
|
||
});
|
||
state.user = r.user;
|
||
await afterLogin();
|
||
} catch (ex) {
|
||
err.textContent = ex.message;
|
||
err.classList.remove('hidden');
|
||
}
|
||
}
|
||
|
||
async function doLogout() {
|
||
try { await api('POST', '/auth/logout'); } catch { /* already gone */ }
|
||
state.user = null;
|
||
showLogin();
|
||
}
|
||
|
||
async function restore() {
|
||
try {
|
||
state.user = await api('GET', '/auth/me');
|
||
await afterLogin();
|
||
} catch {
|
||
showLogin();
|
||
}
|
||
}
|
||
|
||
const isAdmin = () => !!(state.user && state.user.is_admin);
|
||
/* Deployment shape, from /config — not a setting anyone can change here. `sharesIdentity()` is false
|
||
on a standalone Atrium, where there are no modules sharing its accounts and therefore nothing to
|
||
be admitted to: the whole per-module list is hidden rather than offered and then refused.
|
||
`hubSlug()` is this instance's own slug, which never appears in the table at all — every account
|
||
may open the launcher, and the hub has administrators rather than moderators — so it comes out
|
||
of every module picker. */
|
||
const sharesIdentity = () => !!state.config.shares_identity;
|
||
const hubSlug = () => state.config.hub_slug || '';
|
||
/* Modules somebody can actually be given access to: the catalogue minus the hub itself. */
|
||
const grantable = () => (state.modules || []).filter((m) => m.slug !== hubSlug());
|
||
|
||
async function afterLogin() {
|
||
showApp();
|
||
applyTheme(themeMode());
|
||
document.querySelectorAll('#aLang,#btnLangLogin').forEach((b) => {
|
||
b.textContent = LANG.toUpperCase();
|
||
});
|
||
$('aUser').textContent = initials(state.user.full_name || state.user.email);
|
||
// replaceState, not `location.hash =`: that fires hashchange too, and the page would render twice.
|
||
if (!location.hash || location.hash === '#') history.replaceState(null, '', '#/');
|
||
await router();
|
||
}
|
||
|
||
async function refreshShared() {
|
||
state.stale = false; // before the reads: a write that lands meanwhile marks it again
|
||
// The catalogue is cached for the people pickers and the access chips; any write may have
|
||
// renamed or removed a module, so it is dropped here and read again on the next screen needing it.
|
||
// `_catalogue` is the same list as an ordinary user may see it (see ensureCatalogue), and goes for
|
||
// the same reason.
|
||
state.modules = null;
|
||
state._catalogue = null;
|
||
await Promise.all([refreshConfig(), refreshLauncher(), refreshPending()]);
|
||
}
|
||
/* A failed read keeps what was shown and stays stale, so the next navigation retries it: a blip must
|
||
not blank the brand or someone's apps. Per-user data is dropped at sign-out instead (showLogin). */
|
||
async function refreshConfig() {
|
||
try { state.config = await api('GET', '/config'); } catch { state.stale = true; }
|
||
const name = setting('instance_name') || 'Atrium';
|
||
$('brandName').textContent = name;
|
||
document.title = name;
|
||
}
|
||
async function refreshLauncher() {
|
||
try {
|
||
state.launcher = await api('GET', '/launcher');
|
||
// A module the front door serves may come without an administrator's address: its own path on
|
||
// this site, sent relative (`../<slug>/`). Made absolute once here, so every reader of `m.url`
|
||
// (safeUrl, embeddable, the stats fetch) sees one shape.
|
||
for (const m of state.launcher || []) if (m.url && !/^https?:\/\//i.test(m.url)) m.url = new URL(m.url, document.baseURI).href;
|
||
} catch { state.stale = true; }
|
||
}
|
||
async function refreshPending() {
|
||
if (!isAdmin()) { state.pending = 0; return; }
|
||
try { state.pending = (await api('GET', '/admin/overview')).pending_requests || 0; } catch { state.stale = true; }
|
||
}
|
||
|
||
/* ── navigation ─────────────────────────────────────────────────────────── */
|
||
/* One entry per destination. The launcher is the dashboard's first section, so it is not a nav item
|
||
of its own; "Moje wnioski" is a tab of the catalogue (`also`), where a request is made. Every old
|
||
hash still routes — `#/requests` and `#/admin` are only off the menu, not gone. */
|
||
const NAV = [
|
||
{ hash: '#/', icon: 'home', label: 'Strona główna', exact: true },
|
||
/* "Moje wnioski" is a tab of the catalogue, where a request is made, not an entry of its own. */
|
||
/* One place for modules: the catalogue for everybody, and for an administrator a "Zarządzanie" tab
|
||
with the admin table — not a second "Moduły" entry under Administracja. */
|
||
{ hash: '#/marketplace', icon: 'store', label: 'Moduły', also: ['#/requests', '#/admin/modules'] },
|
||
// Everybody keeps their own skills and agents, and only some of them are the firm's.
|
||
{ hash: '#/skills', icon: 'book', label: 'Skille i agenci' },
|
||
];
|
||
/* Ustawienia, at the foot of the sidebar: everybody's, with an administrator's screens added, and a
|
||
module's own settings screen for whoever administers that module (settingsModules).
|
||
"Połączone aplikacje" is not an administrator's screen: everybody holds their own credentials, and
|
||
after the cutover this console is the ONLY place in the family a token can be made — no module
|
||
holds INSERT on `session` — so a desktop client's user who cannot find it has no way left but curl. */
|
||
const SETTINGS_NAV = [
|
||
{ hash: '#/tokens', icon: 'key', label: 'Połączone aplikacje' },
|
||
{ hash: '#/my-keys', icon: 'key', label: 'Moje klucze modeli' },
|
||
{ hash: '#/admin/settings', icon: 'settings', label: 'Ogólne', admin: true },
|
||
{ hash: '#/admin/providers', icon: 'globe', label: 'Dostawcy modeli', admin: true },
|
||
];
|
||
// Administracja, at the foot under Ustawienia: grouped by what an administrator is doing. The
|
||
// overview moved onto the dashboard.
|
||
const ADMIN_NAV = [
|
||
{ sep: 'Dostęp', items: [
|
||
{ hash: '#/admin/requests', icon: 'send', label: 'Wnioski', badge: 'pending' },
|
||
{ hash: '#/admin/publish-requests', icon: 'book', label: 'Prośby o publikację' },
|
||
] },
|
||
{ sep: 'Ludzie i organizacja', items: [
|
||
{ hash: '#/admin/users', icon: 'users', label: 'Użytkownicy' },
|
||
{ hash: '#/admin/org', icon: 'workspace', label: 'Organizacja' },
|
||
] },
|
||
{ sep: 'Platforma', items: [
|
||
{ hash: '#/admin/audit', icon: 'history', label: 'Dziennik zdarzeń' },
|
||
] },
|
||
];
|
||
/* A module's own settings screen, shown framed under Ustawienia: slug → its route inside the module.
|
||
Only for a module that is on (it is in the launcher) and only to whoever administers it. */
|
||
const MODULE_SETTINGS = { sygna: 'admin', counsel: 'settings' };
|
||
const administers = (slug) => isAdmin() || ((state.user && state.user.modules) || {})[slug] === 'moderator';
|
||
const settingsModules = () => state.launcher.filter((m) => MODULE_SETTINGS[m.slug] && embeddable(m) && administers(m.slug));
|
||
// The two sections at the foot. Each opens on its first screen; its screens stand in the column.
|
||
const SECTIONS = [
|
||
{ key: 'settings', icon: 'settings', label: 'Ustawienia', groups: () => [{ items: SETTINGS_NAV
|
||
.concat(settingsModules().map((m) => ({ hash: '#/settings/' + enc(m.slug), label: m.name, mod: m }))) }] },
|
||
{ key: 'admin', icon: 'users', label: 'Administracja', admin: true, groups: () => ADMIN_NAV },
|
||
];
|
||
const curHash = () => (location.hash || '#/').split('?')[0];
|
||
const navOn = (n, cur) => (n.exact ? cur === n.hash : (cur === n.hash || cur.startsWith(n.hash + '/')))
|
||
|| (n.also || []).some((h) => cur === h || cur.startsWith(h + '/'));
|
||
const sectionItems = (s) => s.groups().flatMap((g) => g.items).filter((n) => !n.admin || isAdmin());
|
||
const sectionOf = (cur) => SECTIONS.find((s) => (!s.admin || isAdmin()) && sectionItems(s).some((n) => navOn(n, cur)));
|
||
const pendingBadge = (on) => (on && state.pending ? `<span class="cnt hot">${esc(String(state.pending))}</span>` : '');
|
||
function navItem(n, cur) {
|
||
const icon = n.mod ? moduleIcon(n.mod, 18) : svg(ICN[n.icon]);
|
||
return `<a class="nav-item ${navOn(n, cur) ? 'on' : ''}" href="${esc(n.hash)}"${n.mod ? ' data-no-i18n' : ''}>`
|
||
+ `${icon}<span>${esc(n.label)}</span>${pendingBadge(n.badge === 'pending')}</a>`;
|
||
}
|
||
// A section's screens, under their group heads: in the column beside the rail, or under the
|
||
// section's entry in the drawer.
|
||
const sectionList = (s, cur) => s.groups().map((g) => {
|
||
const items = g.items.filter((n) => !n.admin || isAdmin()).map((n) => navItem(n, cur)).join('');
|
||
return items && (g.sep ? `<div class="nav-sep">${esc(g.sep)}</div>` : '') + items;
|
||
}).join('');
|
||
|
||
/* legalwork's layout: an open module, Ustawienia and Administracja each get a column of their own
|
||
beside the icon rail, their whole menu in it. Galena keeps its menu nested under its
|
||
entry for now. Only on a wide screen: under 881px the sidebar is a drawer, one column. */
|
||
const NESTED_NAV = new Set(['galena']);
|
||
const NARROW = window.matchMedia('(max-width: 880px)');
|
||
NARROW.addEventListener('change', () => { if (state.user) renderNav(); });
|
||
const ownColumn = () => frame.slug && !NESTED_NAV.has(frame.slug) && !NARROW.matches;
|
||
const colHead = (icon, label, raw) => `<div class="modcol-head"${raw ? ' data-no-i18n' : ''}>${icon}<span>${esc(label)}</span></div>`;
|
||
|
||
// Sidebar sections fold (Aplikacje, Administracja); the choice is remembered per browser, and a
|
||
// section is always open while you are inside it, so the page you are on never loses its place.
|
||
function navGroup(key, label, items, inside) {
|
||
let folded = false;
|
||
try { folded = localStorage.getItem('atrium_fold_' + key) === '1'; } catch { /* private window */ }
|
||
const open = inside || !folded;
|
||
return `<button type="button" class="nav-sep fold" aria-expanded="${open}" aria-controls="navGroup_${key}" data-fold="${key}" onclick="toggleNavGroup(this)">`
|
||
+ `<span>${esc(label)}</span>${svg('<path d="M6 9l6 6l6 -6"/>')}</button>`
|
||
+ `<div id="navGroup_${key}"${open ? '' : ' hidden'}>${items}</div>`;
|
||
}
|
||
function toggleNavGroup(btn) {
|
||
const open = btn.getAttribute('aria-expanded') !== 'true';
|
||
btn.setAttribute('aria-expanded', String(open));
|
||
$('navGroup_' + btn.dataset.fold).hidden = !open;
|
||
try { localStorage.setItem('atrium_fold_' + btn.dataset.fold, open ? '0' : '1'); } catch { /* private window */ }
|
||
}
|
||
|
||
function renderNav() {
|
||
const cur = curHash();
|
||
const sec = sectionOf(cur);
|
||
const modCol = ownColumn() && state.launcher.find((m) => m.slug === frame.slug);
|
||
const secCol = !modCol && !NARROW.matches && sec;
|
||
$('app').classList.toggle('mod-col', !!(modCol || secCol));
|
||
$('modCol').innerHTML = modCol
|
||
? colHead(moduleIcon(modCol, 22), modCol.name, true) + '<nav class="nav modnav" id="modNav" data-no-i18n></nav>'
|
||
: (secCol ? colHead(svg(ICN[secCol.icon], 20), secCol.label) + `<nav class="nav modnav">${sectionList(secCol, cur)}</nav>` : '');
|
||
const mods = navModules();
|
||
const modItem = (m) => `<a class="nav-item ${frame.slug === m.slug ? 'on' : ''}" href="${esc(frameHash(m.slug))}" data-no-i18n>`
|
||
+ `${moduleIcon(m, 18)}<span>${esc(m.name)}</span></a>`
|
||
+ (frame.slug === m.slug && !modCol ? '<div class="modnav" id="modNav" data-no-i18n></div>' : '');
|
||
$('nav').innerHTML = NAV.map((n) => navItem(n, cur)).join('')
|
||
+ (mods.length || state.launcher.some(embeddable)
|
||
? navGroup('apps', 'Aplikacje', mods.map(modItem).join('')
|
||
+ `<button type="button" class="nav-item nav-tune" onclick="openNavPrefs()">${svg(ICN.settings)}<span>Dostosuj listę</span></button>`, !!frame.slug)
|
||
: '');
|
||
$('navFoot').innerHTML = SECTIONS.filter((s) => !s.admin || isAdmin()).map((s) =>
|
||
`<a class="nav-item ${sec === s ? 'on' : ''}" href="${esc(sectionItems(s)[0].hash)}">${svg(ICN[s.icon])}<span>${esc(s.label)}</span>`
|
||
+ `${pendingBadge(s.key === 'admin')}</a>`
|
||
+ (sec === s && !secCol ? `<div class="modnav">${sectionList(s, cur)}</div>` : '')).join('');
|
||
localize($('sidebar'));
|
||
localize($('modCol'));
|
||
if (frame.win) mirror();
|
||
}
|
||
|
||
function setCrumb(parts) {
|
||
$('crumb').innerHTML = parts.map((p, i) => {
|
||
const sep = i ? '<span class="sep">/</span>' : '';
|
||
const last = i === parts.length - 1;
|
||
const label = p.data ? dat(p.label) : esc(p.label);
|
||
return sep + (p.href && !last ? `<a href="${esc(p.href)}">${label}</a>` : `<b>${label}</b>`);
|
||
}).join(' ');
|
||
localize($('crumb'));
|
||
}
|
||
|
||
/* A filter applies as you type (debounced) and on Enter — `change` alone waits for the field to lose
|
||
focus, which on a phone keyboard looks like a filter that does nothing. Re-rendering moves focus,
|
||
so it is put back, caret at the end. */
|
||
function onFilter(input, apply) {
|
||
let t;
|
||
const go = () => { clearTimeout(t); const v = input.value.trim(); if (v !== (input.dataset.was || '')) { sessionStorage.setItem('atrium_refocus', input.id); apply(v); } };
|
||
input.dataset.was = input.value.trim();
|
||
input.addEventListener('input', () => { clearTimeout(t); t = setTimeout(go, 400); });
|
||
input.addEventListener('keydown', (e) => { if (e.key === 'Enter') go(); });
|
||
let again = null;
|
||
try { again = sessionStorage.getItem('atrium_refocus'); sessionStorage.removeItem('atrium_refocus'); } catch { /* private mode */ }
|
||
if (again === input.id) { input.focus(); input.setSelectionRange(input.value.length, input.value.length); }
|
||
}
|
||
|
||
// `userText`: the title and subtitle are something a person typed (a skill's name), so localize() keeps out.
|
||
function pageHead(title, sub, actions, userText = false) {
|
||
const keep = userText ? ' data-no-i18n' : '';
|
||
return `<div class="page-head"><div${keep}><h1>${esc(title)}</h1>${sub ? `<div class="sub">${esc(sub)}</div>` : ''}</div>${actions ? `<div class="acts">${actions}</div>` : ''}</div>`;
|
||
}
|
||
|
||
/* URLSearchParams builds these links (a space becomes '+'), so URLSearchParams reads them back:
|
||
it decodes '+' and never throws. A bare decodeURIComponent did neither, so "Ocena i ankiety"
|
||
matched nothing and a stray '%' in a shared link threw before the router could run. */
|
||
function parseHash() {
|
||
const h = (location.hash || '#/').replace(/^#\/?/, '');
|
||
const i = h.indexOf('?');
|
||
const path = i < 0 ? h : h.slice(0, i);
|
||
const q = Object.fromEntries(new URLSearchParams(i < 0 ? '' : h.slice(i + 1)));
|
||
const dec = (s) => { try { return decodeURIComponent(s); } catch { return s; } };
|
||
return { seg: path.split('/').filter(Boolean).map(dec), q };
|
||
}
|
||
|
||
async function router() {
|
||
if (!state.user) return;
|
||
const fm = /^#\/m\/([^/?]+)\/?(.*)$/.exec(location.hash || '');
|
||
if (fm) {
|
||
if (state.stale) await refreshShared();
|
||
// A malformed escape (`#/m/%zz`) names no module: "not found", not an uncaught URIError.
|
||
let slug = '';
|
||
try { slug = decodeURIComponent(fm[1]); } catch { /* stays '' */ }
|
||
showFrame(slug, fm[2]);
|
||
return;
|
||
}
|
||
leaveFrame();
|
||
const C = $('content');
|
||
const { seg, q } = parseHash();
|
||
C.innerHTML = '<div class="faint">Wczytywanie…</div>';
|
||
localize(C);
|
||
if (state.stale) await refreshShared();
|
||
else if (!seg.length) await refreshLauncher(); // Home is the launcher: always show it current
|
||
try {
|
||
if (!seg.length) await viewHome(C);
|
||
else if (seg[0] === 'marketplace' && seg[1]) await viewModule(C, seg[1]);
|
||
else if (seg[0] === 'marketplace') await viewMarketplace(C, q);
|
||
else if (seg[0] === 'requests') await viewMyRequests(C);
|
||
else if (seg[0] === 'tokens') await viewTokens(C);
|
||
else if (seg[0] === 'my-keys') await viewMyKeys(C);
|
||
else if (seg[0] === 'skills' && seg[1] === 'skill' && seg[2]) await viewSkill(C, seg[2]);
|
||
else if (seg[0] === 'skills' && seg[1] === 'agent' && seg[2]) await viewAgent(C, seg[2]);
|
||
else if (seg[0] === 'skills') await viewSkills(C, seg[1] === 'firm' ? 'firm' : 'mine');
|
||
else if (seg[0] === 'settings' && seg[1]) viewModuleSettings(C, seg[1]);
|
||
else if (seg[0] === 'admin' && isAdmin()) await adminRoute(C, seg.slice(1), q);
|
||
else { setCrumb([]); C.innerHTML = '<div class="empty">Nie znaleziono strony.</div>'; }
|
||
} catch (ex) {
|
||
if (ex.status === 401) { showLogin(); return; }
|
||
C.innerHTML = ex.status === 404
|
||
? '<div class="empty">Nie znaleziono strony.</div>'
|
||
: `<div class="banner err">${esc(ex.message)}</div>`;
|
||
}
|
||
localize(C);
|
||
renderNav();
|
||
closeDrawer();
|
||
}
|
||
|
||
async function adminRoute(C, seg, q) {
|
||
const [page, id] = seg;
|
||
// The overview is the dashboard's admin section now; an old bookmark lands there.
|
||
if (!page) { location.replace('#/'); return null; }
|
||
if (page === 'modules' && id) return viewAdminModule(C, id);
|
||
if (page === 'modules') return viewAdminModules(C);
|
||
if (page === 'requests') return viewAdminRequests(C, q);
|
||
if (page === 'publish-requests') return viewAdminPublishRequests(C);
|
||
if (page === 'org') return viewAdminOrg(C);
|
||
if (page === 'users') return viewAdminUsers(C);
|
||
if (page === 'settings') return viewAdminSettings(C);
|
||
if (page === 'providers') return viewAdminProviders(C);
|
||
if (page === 'audit') return viewAdminAudit(C, q);
|
||
setCrumb([]);
|
||
C.innerHTML = '<div class="empty">Nie znaleziono strony.</div>';
|
||
return null;
|
||
}
|
||
|
||
/* ── launching ──────────────────────────────────────────────────────────── */
|
||
/* A real <a href>, not window.open: middle-click, "copy link" and screen readers all keep working.
|
||
The same tab is the default now (`launcher_open_mode`), because a module is a path on this same
|
||
origin: the launcher is a front door, not a bookmark list, and a tab per module is how you end up
|
||
with four of them. `noopener noreferrer` is kept only where it does something — a new tab, or an
|
||
address on another origin, where the opened page would otherwise hold a handle on this window and
|
||
be told our URL. Same-origin in this tab it protects against nothing. */
|
||
function launchAttrs(m) {
|
||
const href = embeddable(m) ? frameHash(m.slug) : safeUrl(m.url);
|
||
const newTab = setting('launcher_open_mode') === 'new_tab';
|
||
const rel = (newTab || !sameOrigin(href)) ? ' rel="noopener noreferrer"' : '';
|
||
return `href="${esc(href)}"${newTab ? ' target="_blank"' : ''}${rel}`;
|
||
}
|
||
|
||
/* legalwork's "a place to start" card: mark, name, one line, an arrow in the corner. */
|
||
/* ── home: one search box over the modules, places to start, your apps ──── */
|
||
/* legalwork's Home is a prompt to an agent; the family has no agent, so the same box searches. Each
|
||
module answers with its own search (same origin, same session cookie), so what a person finds is
|
||
decided by the module that holds it, exactly as in that module's own Ctrl+K — the hub filters
|
||
nothing and learns nothing it would not see by opening the module. `inner` is the module's own
|
||
hash route, the one its palette navigates to, opened inside the frame. */
|
||
const HOME_SEARCH = {
|
||
sygna: async (base, q) => {
|
||
const KIND = { matter: 'Sprawa', party: 'Strona', correspondence: 'Korespondencja', deadline: 'Termin', invoice: 'Faktura', lead: 'Zapytanie' };
|
||
const inner = (k, i) => ({
|
||
matter: 'matters/' + i.id, party: 'parties/' + i.id, lead: 'intake/' + i.id,
|
||
correspondence: i.matter_id ? `matters/${i.matter_id}?tab=correspondence` : 'inbox',
|
||
// a deadline or invoice without a matter has nowhere to open, so it drops out of the results
|
||
deadline: i.matter_id && `matters/${i.matter_id}?tab=deadlines`, invoice: i.matter_id && `matters/${i.matter_id}?tab=billing`,
|
||
}[k]);
|
||
const r = await moduleGet(base, 'search?limit=5&q=' + encodeURIComponent(q));
|
||
return (r.groups || []).flatMap((g) => g.items.filter((i) => inner(g.kind, i))
|
||
.map((i) => ({ kind: KIND[g.kind] || g.kind, title: i.title, sub: i.subtitle, inner: inner(g.kind, i) })));
|
||
},
|
||
galena: async (base, q) => {
|
||
const [r, c] = await Promise.all([moduleGet(base, 'search?q=' + encodeURIComponent(q)),
|
||
moduleGet(base, 'cards?limit=5&q=' + encodeURIComponent(q)).catch(() => ({}))]);
|
||
return (c.items || []).map((i) => ({ kind: 'Umowa', title: i.name, sub: i.number, inner: 'card/' + i.project_id })).concat((r.hits || []).slice(0, 8).map((h) => (h.type === 'file'
|
||
? { kind: 'Plik', title: h.name, sub: `${h.project} / ${h.path}`, inner: 'n/' + h.project_id + (h.folder ? '?path=' + encodeURIComponent(h.folder) : '') }
|
||
: { kind: 'Folder', title: h.name, sub: h.path, inner: 'n/' + h.id })));
|
||
},
|
||
counsel: async (base, q) => {
|
||
const KIND = { firm: 'Kancelaria', matter: 'Sprawa', response: 'Ocena', question: 'Pytanie' };
|
||
const inner = { firm: (h) => 'firms/' + h.id, matter: (h) => 'matters/' + h.id, response: () => 'evaluations', question: () => 'questions' };
|
||
const r = await moduleGet(base, 'search?q=' + encodeURIComponent(q));
|
||
return (r.hits || []).filter((h) => inner[h.type]).slice(0, 8)
|
||
.map((h) => ({ kind: KIND[h.type], title: h.title || h.id, inner: inner[h.type](h) }));
|
||
},
|
||
};
|
||
/* One card per module, pointing at a screen that exists — a card that promised "new contract" and
|
||
landed on a list would be the dead prompt legalwork's cards are not. */
|
||
// The modules you can open in the frame, in launcher order: the only ones searched or suggested.
|
||
const homeModules = () => state.launcher.filter((m) => m.has_access && embeddable(m) && HOME_SEARCH[m.slug]);
|
||
|
||
async function moduleGet(base, path) {
|
||
const r = await fetch(base + path, { credentials: 'same-origin', headers: { Accept: 'application/json' }, signal: homeSearch.ctl.signal });
|
||
if (!r.ok) throw new Error(String(r.status));
|
||
return r.json();
|
||
}
|
||
const homeSearch = { timer: 0, ctl: new AbortController() };
|
||
|
||
function homeResults(groups) {
|
||
const box = $('homeResults');
|
||
if (!box) return;
|
||
box.innerHTML = groups.map(({ m, hits, failed }) => `<div class="hr-group">
|
||
<div class="hr-head" data-no-i18n>${moduleIcon(m, 18)}<span>${esc(m.name)}</span></div>`
|
||
+ (failed ? '<div class="hr-note">Nie udało się przeszukać.</div>'
|
||
: hits.map((h) => `<a class="hr-item" href="${esc(frameHash(m.slug, h.inner))}">
|
||
<span class="hr-kind">${esc(h.kind)}</span>
|
||
<span class="hr-main" data-no-i18n><span class="hr-title">${esc(h.title)}</span>${h.sub ? `<span class="hr-sub">${esc(h.sub)}</span>` : ''}</span>
|
||
<span class="hr-go">${svg(ICN.arrowright, 15)}</span></a>`).join(''))
|
||
+ '</div>').join('') || '<div class="hr-note">Nic nie znaleziono.</div>';
|
||
localize(box);
|
||
}
|
||
|
||
function homeQuery(input) {
|
||
clearTimeout(homeSearch.timer);
|
||
homeSearch.ctl.abort();
|
||
homeSearch.ctl = new AbortController();
|
||
const q = input.value.trim();
|
||
const box = $('homeResults');
|
||
// A follow-up being typed is not a search: hits would open under the composer docked at the bottom.
|
||
const asking = chat.turns.length && $('homeModel') && $('homeModel').value;
|
||
box.classList.toggle('hidden', !q || !!asking);
|
||
if (!q || asking) return;
|
||
if (q.length < 2) { box.innerHTML = '<div class="hr-note">Wpisz co najmniej dwa znaki.</div>'; localize(box); return; }
|
||
box.innerHTML = '<div class="hr-note">Szukam…</div>';
|
||
localize(box);
|
||
homeSearch.timer = setTimeout(async () => {
|
||
const ctl = homeSearch.ctl;
|
||
const groups = await Promise.all(homeModules().map(async (m) => {
|
||
const base = new URL('api/v1/', m.url.replace(/\/?$/, '/')).pathname;
|
||
try { return { m, hits: await HOME_SEARCH[m.slug](base, q) }; } catch { return { m, hits: [], failed: !ctl.signal.aborted }; }
|
||
}));
|
||
if (ctl.signal.aborted) return;
|
||
homeResults(groups.filter((g) => g.failed || g.hits.length));
|
||
}, 250);
|
||
}
|
||
// Enter sends, Shift+Enter starts a new line; not while an input method is composing a word.
|
||
function homeKey(ev) {
|
||
if (ev.key !== 'Enter' || ev.shiftKey || ev.isComposing) return;
|
||
ev.preventDefault();
|
||
ev.target.form.requestSubmit();
|
||
}
|
||
// While an answer streams the send button is a stop button; Enter still sends the next question.
|
||
function homeSendClick(ev) {
|
||
if (!chat.busy) return;
|
||
ev.preventDefault();
|
||
Object.assign(chat.busy, { aborted: true, status: '', content: chat.busy.content || _tr('Zatrzymane.') });
|
||
chat.busy = null;
|
||
if (chat.ctl) chat.ctl.abort();
|
||
chatSave();
|
||
chatRender();
|
||
}
|
||
// Enter opens the first hit, as legalwork's composer sends: the box is one gesture, not a form to fill.
|
||
function homeSubmit(ev) {
|
||
ev.preventDefault();
|
||
const model = $('homeModel') && $('homeModel').value;
|
||
if (model) { homeAsk(model, $('homeQ').value.trim()); return; }
|
||
const first = document.querySelector('#homeResults .hr-item');
|
||
if (first) location.hash = first.getAttribute('href');
|
||
}
|
||
|
||
/* ── the model gateway: the platform's model providers behind Atrium ──────────
|
||
Home's assistant. The server holds the address and the key (a provider row); this console only
|
||
ever names a model from the list the server offers this person. The pick is remembered in this
|
||
browser, per account (modelPickKey); the server keeps no choice. The answer is
|
||
written with textContent and nothing else, so a model cannot put markup, a link or an image on
|
||
the platform's one origin. The conversation lives in this tab (sessionStorage, see chatSave). */
|
||
const chat = { model: '', turns: [], ctl: null, files: [], filesLost: [] };
|
||
|
||
/* A model id as a person reads it: `claude-opus-5-5` → "Claude Opus 5.5", `qwen/qwen3.5-9b` →
|
||
"Qwen3.5 9B". Only short all-digit parts join with a dot, so a date suffix stays a word.
|
||
ponytail: a heuristic over the id; a display name from the provider when one is offered. */
|
||
function prettyModel(id) {
|
||
const parts = String(id).split('/').pop().split('-').filter(Boolean);
|
||
const words = [];
|
||
for (const p of parts) {
|
||
const prev = words[words.length - 1];
|
||
if (/^\d{1,2}$/.test(p) && /^\d{1,2}(\.\d{1,2})*$/.test(prev || '')) words[words.length - 1] = prev + '.' + p;
|
||
else words.push(p);
|
||
}
|
||
return words.map((w) => w.replace(/[a-z]/, (c) => c.toUpperCase())).join(' ');
|
||
}
|
||
|
||
/* Which family a model belongs to, by its id: a family key (`anthropic`, `openai`, …), or for any
|
||
other model the first letter of its name as a one-character monogram. */
|
||
function modelFamily(id) {
|
||
const name = String(id).split('/').pop().toLowerCase();
|
||
if (/claude/.test(name)) return 'anthropic';
|
||
if (/^(gpt|o\d)/.test(name)) return 'openai';
|
||
if (/gemini|gemma/.test(name)) return 'google';
|
||
if (/qwen/.test(name)) return 'qwen';
|
||
if (/bielik/.test(name)) return 'bielik';
|
||
if (/llama/.test(name)) return 'meta';
|
||
if (/mistral|mixtral/.test(name)) return 'mistral';
|
||
return ((name.match(/[a-z0-9]/) || ['?'])[0]).toUpperCase();
|
||
}
|
||
|
||
async function loadModels() {
|
||
/* 502 = configured, but the model server does not answer (the pod is stopped). */
|
||
try { state._models = await api('GET', '/models'); }
|
||
catch (ex) { state._models = ex.status === 502 ? { configured: true, off: true, models: [] } : null; }
|
||
return state._models;
|
||
}
|
||
|
||
/* The picker groups by provider; /models already lists them in provider order. */
|
||
function modelOptions(models, selected, none) {
|
||
const groups = [];
|
||
// The ask names a model id and the server takes the FIRST provider offering it (core `offering`),
|
||
// so an id a later provider repeats is shown once, under the provider that will answer.
|
||
// ponytail: pass a provider id with the ask if two providers of one model must both be choosable.
|
||
const seen = new Set();
|
||
for (const m of models) {
|
||
if (seen.has(m.id)) continue;
|
||
seen.add(m.id);
|
||
if (!groups.length || groups[groups.length - 1].provider !== m.provider) groups.push({ provider: m.provider, models: [] });
|
||
groups[groups.length - 1].models.push(m);
|
||
}
|
||
return `<option value="">${esc(none)}</option>` + groups.map((g) =>
|
||
`<optgroup label="${esc(g.provider)}" data-no-i18n>` + g.models.map((m) =>
|
||
`<option value="${esc(m.id)}" title="${esc(m.id)}"${m.id === selected ? ' selected' : ''} data-no-i18n>${esc(prettyModel(m.id))}</option>`).join('')
|
||
+ '</optgroup>').join('');
|
||
}
|
||
|
||
/* Brand logotypes for model families and providers: Simple Icons (CC0-1.0, no per-icon licence
|
||
in its data), path data vendored at commit e451c581, never from a CDN. Decided per brand
|
||
(plan 5.2): anthropic, google (Gemini), qwen, meta, mistral, openrouter → logotype; openai →
|
||
monogram (not in Simple Icons), bielik and the rest → monogram (not in the set). */
|
||
const BRAND = {
|
||
// simple-icons: anthropic
|
||
anthropic: 'M17.3041 3.541h-3.6718l6.696 16.918H24Zm-10.6082 0L0 20.459h3.7442l1.3693-3.5527h7.0052l1.3693 3.5528h3.7442L10.5363 3.5409Zm-.3712 10.2232 2.2914-5.9456 2.2914 5.9456Z',
|
||
// simple-icons: googlegemini
|
||
google: 'M11.04 19.32Q12 21.51 12 24q0-2.49.93-4.68.96-2.19 2.58-3.81t3.81-2.55Q21.51 12 24 12q-2.49 0-4.68-.93a12.3 12.3 0 0 1-3.81-2.58 12.3 12.3 0 0 1-2.58-3.81Q12 2.49 12 0q0 2.49-.96 4.68-.93 2.19-2.55 3.81a12.3 12.3 0 0 1-3.81 2.58Q2.49 12 0 12q2.49 0 4.68.96 2.19.93 3.81 2.55t2.55 3.81',
|
||
// simple-icons: qwen
|
||
qwen: 'M23.919 14.545 20.817 9.17l1.47-2.544a.56.56 0 0 0 0-.566l-1.633-2.83a.57.57 0 0 0-.49-.283h-6.207L12.487.402a.57.57 0 0 0-.49-.284H8.732a.56.56 0 0 0-.49.284L5.139 5.775h-2.94a.56.56 0 0 0-.49.284L.077 8.887a.56.56 0 0 0 0 .567L3.18 14.83l-1.47 2.545a.56.56 0 0 0 0 .566l1.634 2.83a.57.57 0 0 0 .49.283h6.205l1.47 2.545a.57.57 0 0 0 .49.284h3.266a.57.57 0 0 0 .49-.284l3.104-5.375h2.94a.57.57 0 0 0 .49-.283l1.634-2.828a.55.55 0 0 0-.004-.568M8.733.686l1.634 2.828-1.634 2.828H21.8L20.164 9.17H7.425L5.63 6.06Zm1.306 19.801-6.205-.002 1.634-2.83h3.265L2.201 6.344h3.267q3.182 5.517 6.367 11.032zm10.124-5.66L18.53 12l-6.532 11.315-1.634-2.83c2.129-3.673 4.25-7.351 6.373-11.028h3.592l3.102 5.374z',
|
||
// simple-icons: meta
|
||
meta: 'M6.915 4.03c-1.968 0-3.683 1.28-4.871 3.113C.704 9.208 0 11.883 0 14.449c0 .706.07 1.369.21 1.973a6.624 6.624 0 0 0 .265.86 5.297 5.297 0 0 0 .371.761c.696 1.159 1.818 1.927 3.593 1.927 1.497 0 2.633-.671 3.965-2.444.76-1.012 1.144-1.626 2.663-4.32l.756-1.339.186-.325c.061.1.121.196.183.3l2.152 3.595c.724 1.21 1.665 2.556 2.47 3.314 1.046.987 1.992 1.22 3.06 1.22 1.075 0 1.876-.355 2.455-.843a3.743 3.743 0 0 0 .81-.973c.542-.939.861-2.127.861-3.745 0-2.72-.681-5.357-2.084-7.45-1.282-1.912-2.957-2.93-4.716-2.93-1.047 0-2.088.467-3.053 1.308-.652.57-1.257 1.29-1.82 2.05-.69-.875-1.335-1.547-1.958-2.056-1.182-.966-2.315-1.303-3.454-1.303zm10.16 2.053c1.147 0 2.188.758 2.992 1.999 1.132 1.748 1.647 4.195 1.647 6.4 0 1.548-.368 2.9-1.839 2.9-.58 0-1.027-.23-1.664-1.004-.496-.601-1.343-1.878-2.832-4.358l-.617-1.028a44.908 44.908 0 0 0-1.255-1.98c.07-.109.141-.224.211-.327 1.12-1.667 2.118-2.602 3.358-2.602zm-10.201.553c1.265 0 2.058.791 2.675 1.446.307.327.737.871 1.234 1.579l-1.02 1.566c-.757 1.163-1.882 3.017-2.837 4.338-1.191 1.649-1.81 1.817-2.486 1.817-.524 0-1.038-.237-1.383-.794-.263-.426-.464-1.13-.464-2.046 0-2.221.63-4.535 1.66-6.088.454-.687.964-1.226 1.533-1.533a2.264 2.264 0 0 1 1.088-.285z',
|
||
// simple-icons: mistralai
|
||
mistral: 'M17.143 3.429v3.428h-3.429v3.429h-3.428V6.857H6.857V3.43H3.43v13.714H0v3.428h10.286v-3.428H6.857v-3.429h3.429v3.429h3.429v-3.429h3.428v3.429h-3.428v3.428H24v-3.428h-3.43V3.429z',
|
||
// simple-icons: openrouter
|
||
openrouter: 'M16.778 1.844v1.919q-.569-.026-1.138-.032-.708-.008-1.415.037c-1.93.126-4.023.728-6.149 2.237-2.911 2.066-2.731 1.95-4.14 2.75-.396.223-1.342.574-2.185.798-.841.225-1.753.333-1.751.333v4.229s.768.108 1.61.333c.842.224 1.789.575 2.185.799 1.41.798 1.228.683 4.14 2.75 2.126 1.509 4.22 2.11 6.148 2.236.88.058 1.716.041 2.555.005v1.918l7.222-4.168-7.222-4.17v2.176c-.86.038-1.611.065-2.278.021-1.364-.09-2.417-.357-3.979-1.465-2.244-1.593-2.866-2.027-3.68-2.508.889-.518 1.449-.906 3.822-2.59 1.56-1.109 2.614-1.377 3.978-1.466.667-.044 1.418-.017 2.278.02v2.176L24 6.014Z',
|
||
};
|
||
// A brand's logotype scaled into the tile, else a one-letter monogram.
|
||
function markSvg(brand, letter) {
|
||
const glyph = BRAND[brand]
|
||
? `<g transform="translate(5 5) scale(.5833)"><path d="${BRAND[brand]}" fill="currentColor"/></g>`
|
||
: `<text x="12" y="16.5" text-anchor="middle" font-size="13" font-weight="600" fill="currentColor">${esc(letter)}</text>`;
|
||
return `<svg viewBox="0 0 24 24" aria-hidden="true">${glyph}</svg>`;
|
||
}
|
||
|
||
/* A family's mark beside the picker, in the family's colour (a one-letter family is "other", in
|
||
gray): its logotype where BRAND has one, else a monogram. */
|
||
const FAMILY_MARK = { anthropic: ['A', 'orange'], openai: ['O', 'teal'], google: ['G', 'blue'], qwen: ['Q', 'violet'],
|
||
bielik: ['B', 'red'], meta: ['M', 'indigo'], mistral: ['M', 'pink'] };
|
||
function familyIcon(id) {
|
||
if (!id) return '';
|
||
const fam = modelFamily(id);
|
||
const [letter, hue] = FAMILY_MARK[fam] || [fam, 'gray'];
|
||
return `<span class="mi h-${hue}" style="--mi:22px">${markSvg(fam, letter)}</span>`;
|
||
}
|
||
|
||
// ponytail: per browser; a server-side preference when a pick has to follow a person across devices.
|
||
const modelPickKey = () => 'atrium_home_model:' + state.user.id;
|
||
function savedModelPick() {
|
||
try { return localStorage.getItem(modelPickKey()) || ''; } catch { return ''; }
|
||
}
|
||
function saveModelPick(model) {
|
||
try { model ? localStorage.setItem(modelPickKey(), model) : localStorage.removeItem(modelPickKey()); } catch { /* private mode */ }
|
||
}
|
||
|
||
function homeModelChange(sel) {
|
||
const ask = !!sel.value;
|
||
$('homeQ').placeholder = _tr(ask ? 'Zapytaj asystenta albo szukaj w modułach…' : 'Szukaj spraw, umów, plików i kancelarii…');
|
||
$('homeQ').setAttribute('aria-label', _tr(ask ? 'Zapytaj asystenta' : 'Szukaj we wszystkich modułach'));
|
||
document.querySelector('.home-send').setAttribute('aria-label', _tr(ask ? 'Wyślij' : 'Szukaj'));
|
||
$('homeModelIcon').innerHTML = familyIcon(sel.value);
|
||
saveModelPick(sel.value);
|
||
chatFilesRender(); // how much of a file fits depends on the model
|
||
}
|
||
|
||
/* Files attached to the conversation: the server returns their text and keeps nothing (routers/attachments.py);
|
||
each becomes a numbered source of every following question, so the answer cites it as [n] and its quotations
|
||
are checked like a contract's. The text lives in this page only: not in sessionStorage (a 40-page contract
|
||
would fill it), so after a reload the chips say the files have to be attached again. */
|
||
const CHAT_MAX_FILES = 3;
|
||
// ponytail: the whole text while it fits, else its beginning, said out loud; choosing the passages that answer is
|
||
// the next step. About 2.5 characters a token (Polish legal text, cautious), less room for the rest and the answer.
|
||
function chatFileBudget(model) {
|
||
const m = ((state._models || {}).models || []).find((x) => x.id === model);
|
||
const tokens = (m && Number(m.context_window)) || 32768;
|
||
return Math.max(6000, Math.min(100000, Math.round(tokens * 2.5) - 25000));
|
||
}
|
||
function chatFileSources(files, model) {
|
||
let left = chatFileBudget(model);
|
||
const fit = new Map();
|
||
// The shortest first, each its share of what is left: a short file is read whole beside a long one.
|
||
[...files].sort((a, b) => a.text.length - b.text.length).forEach((f, i, all) => {
|
||
const n = Math.min(f.text.length, Math.floor(left / (all.length - i)));
|
||
fit.set(f, n);
|
||
left -= n;
|
||
});
|
||
return files.map((f, i) => {
|
||
const n = fit.get(f);
|
||
const text = f.text.slice(0, n);
|
||
const read = n >= f.text.length ? '' : f.pages ? `do strony ${(text.match(/\[strona \d+\]/g) || []).length} z ${f.pages}`
|
||
: `${Math.round((100 * n) / f.text.length)}% tekstu`;
|
||
const note = read ? `\n(Plik przycięty: przeczytano tylko ${read}. Jeśli odpowiedzi tu nie ma, napisz, że nie przeczytałem dalszej części pliku.)` : '';
|
||
return { slug: 'załącznik', kind: 'plik', key: `plik:${i}:${f.name}`, title: f.name, read, note, text: text + note };
|
||
});
|
||
}
|
||
function chatFilesRender() {
|
||
const box = $('homeFiles');
|
||
if (!box) return;
|
||
const srcs = chatFileSources(chat.files, ($('homeModel') && $('homeModel').value) || chat.model);
|
||
box.innerHTML = srcs.map((s, i) => `<span class="chip home-file">${svg(ICN.paperclip, 13)}<span data-no-i18n>${esc(s.title)}</span>`
|
||
+ (s.read ? `<span class="faint" data-no-i18n>· model przeczyta ${esc(s.read)}</span>` : '')
|
||
+ `<button type="button" class="home-file-x" aria-label="Usuń plik" onclick="chatDropFile(${i})">${svg(ICN.x, 12)}</button></span>`).join('')
|
||
+ (chat.reading ? '<span class="chip home-file faint">Czytam plik…</span>' : '')
|
||
+ (chat.filesLost.length ? `<span class="faint tiny">Pliki nie przetrwały odświeżenia strony, dołącz je ponownie: <span data-no-i18n>${esc(chat.filesLost.join(', '))}</span></span>` : '');
|
||
localize(box);
|
||
box.classList.toggle('hidden', !box.innerHTML);
|
||
}
|
||
function chatDropFile(i) {
|
||
chat.files.splice(i, 1);
|
||
chatFilesRender();
|
||
}
|
||
async function homeAttach(list) {
|
||
const files = [...list];
|
||
if (!files.length) return;
|
||
if (!($('homeModel') && $('homeModel').value)) { toast('Wybierz model asystenta, żeby zapytać o plik.'); return; }
|
||
if (chat.files.length + files.length > CHAT_MAX_FILES) { toast('Do rozmowy można dołączyć najwyżej 3 pliki.'); return; }
|
||
chat.filesLost = [];
|
||
for (const f of files) {
|
||
if (f.size > 10 * 1024 * 1024) { toast(`${f.name}: plik jest większy niż 10 MB.`); continue; }
|
||
chat.reading = true;
|
||
chatFilesRender();
|
||
try { chat.files.push(await api('POST', '/chat/attachments?name=' + encodeURIComponent(f.name), f)); }
|
||
catch (ex) { toast(`${f.name}: ${ex.message}`); }
|
||
}
|
||
chat.reading = false;
|
||
chatFilesRender();
|
||
}
|
||
// A file dropped anywhere on Home is attached; anywhere else the browser would leave the page to open it.
|
||
const homeBox = () => document.querySelector('.home-box');
|
||
addEventListener('dragover', (e) => {
|
||
if (!e.dataTransfer || !e.dataTransfer.types.includes('Files')) return;
|
||
e.preventDefault();
|
||
if (homeBox()) homeBox().classList.add('drop');
|
||
});
|
||
addEventListener('dragleave', (e) => { if (!e.relatedTarget && homeBox()) homeBox().classList.remove('drop'); });
|
||
addEventListener('drop', (e) => {
|
||
if (!e.dataTransfer || !e.dataTransfer.files.length) return;
|
||
e.preventDefault();
|
||
if (homeBox()) homeBox().classList.remove('drop');
|
||
if ($('homeQ')) homeAttach(e.dataTransfer.files);
|
||
});
|
||
|
||
// Rebuilt on every streamed chunk inside its own scrolling box, so the reader's place is kept as it was.
|
||
// `toEnd`: the asker just sent, so their question goes to the top and the answer is read from its first line
|
||
// while it is written below; nothing pulls the reader down after it.
|
||
function chatRender(toEnd) {
|
||
const box = $('homeAnswer');
|
||
if (!box) return;
|
||
const keep = box.scrollTop;
|
||
box.closest('.home').classList.toggle('chatting', chat.turns.length > 0);
|
||
const busy = !!chat.busy && chat.turns.includes(chat.busy);
|
||
const send = document.querySelector('.home-send');
|
||
if (send) {
|
||
send.classList.toggle('stop', busy);
|
||
send.setAttribute('aria-label', _tr(busy ? 'Zatrzymaj odpowiedź' : $('homeModel') && $('homeModel').value ? 'Wyślij' : 'Szukaj'));
|
||
send.innerHTML = svg(busy ? ICN.stop : ICN.arrowright, 18);
|
||
}
|
||
box.classList.toggle('hidden', !chat.turns.length);
|
||
box.setAttribute('aria-busy', String(!!chat.busy && chat.turns.includes(chat.busy)));
|
||
box.innerHTML = `<div class="ha-head"><span>${svg(ICN.sparkles, 15)}<span>Odpowiedź AI</span>
|
||
<span class="ha-model" data-no-i18n></span><span>· sprawdź w źródle</span></span></div>
|
||
<div class="ha-turns"></div>`;
|
||
localize(box);
|
||
box.querySelector('.ha-model').textContent = '(' + chat.model + ')';
|
||
const list = box.querySelector('.ha-turns');
|
||
for (const t of chat.turns) {
|
||
const el = document.createElement('div');
|
||
el.className = 'ha-turn ' + t.role;
|
||
el.setAttribute('data-no-i18n', '');
|
||
// A code-built table (chatPick) is in the text for the history; here it is drawn, cell by cell as text.
|
||
const shown = t.table && !t.status ? { ...t, content: t.content.split('\n\n| ')[0] } : t;
|
||
if (shown.refs && shown.refs.length && !shown.status) renderCited(el, shown);
|
||
else el.textContent = shown.content;
|
||
if (shown !== t) el.appendChild(chatTableEl(t.table));
|
||
if (t.review && !t.status) renderReview(el, t.review);
|
||
if (t.trace && t.trace.length && !t.status) { // what the model actually looked at, in order
|
||
const det = document.createElement('details');
|
||
det.className = 'ha-trace faint tiny';
|
||
det.open = !!t.traceOpen; // survives the re-render of the next chunk
|
||
det.ontoggle = () => { t.traceOpen = det.open; };
|
||
const sum = document.createElement('summary');
|
||
sum.textContent = _tr('Co sprawdził model') + ' (' + t.trace.length + ')';
|
||
det.appendChild(sum);
|
||
for (const line of t.trace) { const d = document.createElement('div'); d.textContent = line; det.appendChild(d); }
|
||
el.appendChild(det);
|
||
}
|
||
if (t.status) {
|
||
const st = document.createElement('div');
|
||
st.className = 'ha-status faint tiny';
|
||
st.textContent = _tr(t.status);
|
||
el.appendChild(st);
|
||
}
|
||
list.appendChild(el);
|
||
}
|
||
const last = list.lastElementChild;
|
||
const asked = last && last.previousElementSibling;
|
||
// Room under the newest answer, so its question can reach the top however short the answer is.
|
||
if (last && asked && asked.classList.contains('user')) last.style.minHeight = Math.max(0, box.clientHeight - asked.offsetHeight - 40) + 'px';
|
||
box.scrollTop = toEnd && asked ? box.scrollTop + asked.getBoundingClientRect().top - box.getBoundingClientRect().top - 16 : keep;
|
||
}
|
||
|
||
/* The rows stay whole (the history the model reads next turn is built from them); `view` only says how to draw
|
||
them, as plain data so it survives the conversation's storage: `sub` puts one column as a small second line
|
||
under another ("procesowy" under the item, the state under the date), `head` renames a column, `dropSame`
|
||
leaves out a column whose every row says the same (one owner for all), `nowrap` keeps a column on one line.
|
||
On a phone each row is a card. */
|
||
function chatTableEl({ head, rows, links = [], linkCol = -1, view = {} }) {
|
||
const sub = view.sub || {};
|
||
const under = new Set(Object.values(sub).map(Number));
|
||
const same = (c) => rows.every((r) => r[c] === rows[0][c]);
|
||
const cols = head.map((_, i) => i).filter((i) => !under.has(i) && !((view.dropSame || []).includes(i) && rows.length > 1 && same(i)));
|
||
const label = (i) => (view.head || {})[i] || head[i];
|
||
const el = (tag, cls, text) => { const x = document.createElement(tag); if (cls) x.className = cls; if (text != null) x.textContent = text; return x; };
|
||
const wrap = el('div', 'ha-table');
|
||
const table = el('table');
|
||
const hr = el('tr');
|
||
for (const i of cols) hr.appendChild(el('th', null, label(i)));
|
||
const th = el('thead'); th.appendChild(hr);
|
||
const tb = el('tbody');
|
||
rows.forEach((r, n) => {
|
||
const row = el('tr');
|
||
for (const i of cols) {
|
||
const td = el('td');
|
||
td.dataset.label = label(i);
|
||
if ((view.nowrap || []).includes(i)) td.className = 'nw'; // a date is not broken after its year
|
||
const href = links[n];
|
||
if (i === linkCol && href && (href.startsWith('#') || sameOrigin(href))) {
|
||
const a = el('a', null, r[i]);
|
||
a.href = href;
|
||
td.appendChild(a);
|
||
} else td.textContent = r[i];
|
||
if (sub[i] != null && r[sub[i]]) td.appendChild(el('span', 'ha-sub', r[sub[i]]));
|
||
row.appendChild(td);
|
||
}
|
||
tb.appendChild(row);
|
||
});
|
||
table.append(th, tb);
|
||
wrap.appendChild(table);
|
||
return wrap;
|
||
}
|
||
|
||
function chatReset() {
|
||
if (chat.ctl) chat.ctl.abort();
|
||
chat.busy = null; // or the send button stays a stop button for an answer that is gone
|
||
chat.turns = [];
|
||
chat.index = null; // the next question reads the modules again
|
||
Object.assign(chat, { files: [], filesLost: [] });
|
||
chatSave();
|
||
chatRender();
|
||
chatFilesRender();
|
||
}
|
||
|
||
// The conversation outlives leaving Home: Back from a source's link brings it back, also after a module's
|
||
// own page reloaded Atrium. sessionStorage: this tab only, gone with it; tied to the account that asked.
|
||
// A source's text is kept only where the answer cites it: twelve full records a turn filled the quota within
|
||
// a few turns. Not cut to a prefix: the passage shown under a cited law text can sit past it. The quotation
|
||
// verdicts are stored with the answer (chatQuotes), so they need no text. The next question takes the
|
||
// records again from the index, by key.
|
||
function chatSave() {
|
||
const slim = (t) => {
|
||
if (!t.refs) return t;
|
||
const cited = new Set((t.content.match(/\[\d+(?:\s*,\s*\d+)*\]/g) || []).flatMap((m) => m.match(/\d+/g).map(Number)));
|
||
return { ...t, refs: t.refs.map((r) => ({ ...r, text: cited.has(r.n) ? String(r.text || '').slice(0, 8000) : '' })) };
|
||
};
|
||
try { sessionStorage.setItem('atrium.chat', JSON.stringify({ user: state.user.id, model: chat.model, turns: chat.turns.map(slim), files: chat.files.map((f) => f.name) })); }
|
||
catch { /* storage off (private window): the conversation lives as long as the page */ }
|
||
}
|
||
function chatForget() {
|
||
if (chat.ctl) chat.ctl.abort();
|
||
Object.assign(chat, { user: null, model: '', turns: [], index: null, files: [], filesLost: [] });
|
||
try { sessionStorage.removeItem('atrium.chat'); } catch { /* storage off */ }
|
||
}
|
||
// Checked on every Home render, not only on a reload: a sign-in after another in this tab keeps the page.
|
||
function chatRestore() {
|
||
if (chat.user && chat.user !== state.user.id) chatForget();
|
||
chat.user = state.user.id;
|
||
if (chat.turns.length) return;
|
||
try {
|
||
const saved = JSON.parse(sessionStorage.getItem('atrium.chat') || 'null');
|
||
if (saved && saved.user === state.user.id) Object.assign(chat, { model: saved.model, turns: saved.turns, filesLost: chat.files.length ? [] : saved.files || [] });
|
||
} catch { /* nothing saved, or storage off */ }
|
||
}
|
||
|
||
// Code finds, the model reads. Measured on the demo data (2026-10-28): 9-10 of 10 answers right, against 2
|
||
// of 10 when the model called the modules' APIs itself (it searched the wrong module, guessed paths and
|
||
// summed wrong). The browser reads every module the asker may read, with the asker's own session, turns
|
||
// each record into one sentence and computes the totals here; a question gets the 12 best-matching records
|
||
// and the article it cites, and the model gets them as numbered sources, with no tools.
|
||
// ponytail: the index is built once per conversation ("Nowa rozmowa" rebuilds it) from whole lists, fine for
|
||
// hundreds of records; thousands want the totals from the modules' own queries.
|
||
// ponytail: word search only; the prototype also ranked by bge-m3 vectors, which caught English questions.
|
||
const CHAT_TOP = 12;
|
||
const chatModules = () => (state._chatModules || []);
|
||
async function loadChatModules() {
|
||
state._chatModules = (await api('GET', '/marketplace')).modules
|
||
.filter((m) => m.slug !== hubSlug() && m.status !== 'coming_soon');
|
||
}
|
||
|
||
// One module's GET as the asker: null when they may not read it, a wrapped list (`items`) unwrapped.
|
||
async function askerGet(slug, path) {
|
||
const r = await fetch(new URL('../' + slug + '/api/v1/' + path, document.baseURI), { credentials: 'same-origin', signal: chat.ctl.signal });
|
||
if ([401, 403, 404].includes(r.status)) return null;
|
||
if (!r.ok) throw new Error(slug + ': HTTP ' + r.status);
|
||
const d = await r.json();
|
||
return d && Array.isArray(d.items) ? d.items : d;
|
||
}
|
||
|
||
const chatDays = (d, today) => Math.round((Date.parse(d) - Date.parse(today)) / 864e5);
|
||
const CHAT_MONTHS = ['stycznia', 'lutego', 'marca', 'kwietnia', 'maja', 'czerwca', 'lipca', 'sierpnia', 'września', 'października', 'listopada', 'grudnia'];
|
||
// "21 października": how an answer names a deadline's date, so the date still says which deadline it was.
|
||
const chatPlDate = (d) => d ? `${Number(d.slice(8, 10))} ${CHAT_MONTHS[Number(d.slice(5, 7)) - 1]}` : '';
|
||
// "1 umowa", "3 umowy", "5 umów", "22 umowy": the plural a count takes in Polish.
|
||
const chatPlural = (n, one, few, many) => `${n} ${n === 1 ? one : [2, 3, 4].includes(n % 10) && ![12, 13, 14].includes(n % 100) ? few : many}`;
|
||
const chatUmowy = (n) => chatPlural(n, 'umowa', 'umowy', 'umów');
|
||
const chatAddDays = (today, n) => new Date(Date.parse(today) + n * 864e5).toISOString().slice(0, 10);
|
||
// Statuses and empty fields in words, one dictionary for every record, table and card: Qwen read "kontrahent brak"
|
||
// as a firm called Brak (5 of 6) and "zawarta brak daty" as concluded, and answers copied the codes "obowiazuje",
|
||
// "open", "closed" (9.11). The codes are the modules' enums (the contract status on Galena's register card, Sygna MatterStatus, Counsel
|
||
// FirmStatus, MatterStatus and ReviewCycleStatus, Galena DraftStatus); an unknown code is shown as it is.
|
||
const CHAT_STATUS_PL = {
|
||
umowa: { szkic: 'szkic (umowa niezawarta)', negocjacje: 'w negocjacjach', podpisana: 'podpisana', obowiazuje: 'obowiązuje', rozwiazana: 'rozwiązana' },
|
||
sprawa: { prospect: 'potencjalna, jeszcze nieotwarta', open: 'otwarta', suspended: 'zawieszona', closed: 'zamknięta', archived: 'w archiwum' },
|
||
kancelaria: { active: 'aktywna', inactive: 'nieaktywna', blacklisted: 'wykluczona' },
|
||
zlecenie: { open: 'otwarte', in_progress: 'w toku', cancelled: 'anulowane', closed: 'zamknięte, zakończone' },
|
||
cykl: { open: 'otwarty', closed: 'zamknięty' },
|
||
wersja: { open: 'czeka na akceptację', approved: 'zaakceptowana', rejected: 'odrzucona', withdrawn: 'wycofana', published: 'opublikowana' },
|
||
};
|
||
// English only where the table already follows the question's language (the contract list).
|
||
const CHAT_STATUS_EN = { umowa: { szkic: 'draft (not concluded)', negocjacje: 'in negotiation', podpisana: 'signed', obowiazuje: 'in force', rozwiazana: 'terminated' } };
|
||
const chatStatus = (kind, code, en = false) => ((en ? CHAT_STATUS_EN : CHAT_STATUS_PL)[kind] || {})[code] || code;
|
||
// A person by id: "prowadzi Anna Nowak", else the field said to be empty ("osoba prowadząca nie wpisana"), never
|
||
// "prowadzi nieznany"; an id the user list lacks is said as such.
|
||
// An empty `names` is a list this account could not read (a real one holds at least the asker): then the person
|
||
// is entered but unnamed here, not "spoza listy".
|
||
const chatWho = (names, id, verb, missing) => (names[id] ? `${verb} ${names[id]}` : !id ? missing
|
||
: Object.keys(names).length ? `${verb} osoba spoza listy użytkowników` : `${verb} osoba, której nazwiska to konto nie widzi`);
|
||
// The calendar week of a day, Monday to Sunday: an answer's "w tym tygodniu (9-15 listopada)" had no source for its
|
||
// dates, so the check refused it (user-ii-thread#3, 9.11).
|
||
const chatWeekOf = (today) => { const d = (new Date(today + 'T00:00:00Z').getUTCDay() + 6) % 7; return [chatAddDays(today, -d), chatAddDays(today, 6 - d)]; };
|
||
const chatMoney = (x) => Number(x).toLocaleString('pl-PL', { minimumFractionDigits: 2, maximumFractionDigits: 2, useGrouping: 'always' }).replace(/\s/g, ' ');
|
||
|
||
// Galena's contract register (WP-R3; since Compass 0030 the contracts live there, not in Workflow). A card
|
||
// is a project typed `umowa`: `status` is the one shown today, `card/<project_id>` its console page.
|
||
async function chatRegister(today) {
|
||
const rows = [];
|
||
for (let off = 0; ; off += 200) {
|
||
const page = await askerGet('galena', 'cards?limit=200&offset=' + off);
|
||
if (page === null) return null;
|
||
rows.push(...page);
|
||
if (page.length < 200) break;
|
||
}
|
||
const rec = (kind, title, inner, text, key, members) => ({ slug: 'galena', kind, title, inner, text, key, members });
|
||
const ck = (c) => 'galena:umowa:' + c.id;
|
||
const out = rows.map((c) => {
|
||
const left = c.ends_on ? chatDays(c.ends_on, today) : 0;
|
||
const when = c.ends_on ? `kończy się ${c.ends_on} (${left >= 0 ? 'za ' + left + ' dni' : -left + ' dni temu'})` : 'data końca nie wpisana';
|
||
const value = c.value_amount ? `wartość ${chatMoney(c.value_amount)} ${c.value_currency}` : 'wartość nie wpisana';
|
||
return { ...rec('umowa', c.number + ' ' + c.name, 'card/' + c.project_id,
|
||
`Umowa ${c.number} „${c.name}”, kontrahent ${c.counterparty || 'nie wpisany'}, status ${chatStatus('umowa', c.status)}, ${value}, ` +
|
||
`${c.concluded_on ? 'zawarta ' + c.concluded_on : 'data zawarcia nie wpisana'}, ${when}.`, ck(c)),
|
||
labels: [c.number, c.name, c.counterparty], at: c.created_at, did: 'dodana do rejestru umów', contract: c };
|
||
});
|
||
// The totals are computed here: a model that summed itself got it wrong every time. One sentence per status,
|
||
// its total first: split over a line per currency, "obowiązuje" was read as 5 contracts where there were 7
|
||
// (Bielik, 9.11).
|
||
const nums = (cs) => cs.map((c) => c.number).join(', ');
|
||
const statuses = [...new Set(rows.map((c) => c.status))].sort();
|
||
const totals = statuses.map((st) => {
|
||
const cs = rows.filter((c) => c.status === st);
|
||
const none = cs.filter((c) => !c.value_amount);
|
||
// "waluta -: 3 umów, łączna wartość 0,00 -" read as a currency called "-"; models then found no such contracts.
|
||
const parts = none.length ? [`wartość nie wpisana: ${chatUmowy(none.length)} (${nums(none)})`] : [];
|
||
for (const cur of [...new Set(cs.filter((c) => c.value_amount).map((c) => c.value_currency || '-'))].sort()) {
|
||
const g = cs.filter((c) => c.value_amount && (c.value_currency || '-') === cur);
|
||
const sum = g.reduce((a, c) => a + Number(c.value_amount), 0);
|
||
parts.push(cur === '-' ? `z wartością bez waluty ${chatUmowy(g.length)} (${nums(g)})`
|
||
: `w ${cur} ${chatUmowy(g.length)}, łączna wartość ${chatMoney(sum)} ${cur} (${nums(g)})`);
|
||
}
|
||
// The earliest end in the record a list question cites, so the model reads it instead of comparing dates.
|
||
const ending = cs.filter((c) => c.ends_on >= today).sort((a, b) => a.ends_on.localeCompare(b.ends_on));
|
||
const past = cs.filter((c) => c.ends_on && c.ends_on < today);
|
||
const undated = cs.filter((c) => !c.ends_on).length;
|
||
return `Status ${chatStatus('umowa', st)}: ${chatUmowy(cs.length)}; w tym ${parts.join('; ')}; ` + [
|
||
ending.length ? `najbliższa data końca: ${ending[0].number} (${ending[0].ends_on})` : '',
|
||
past.length ? `data końca już minęła: ${past.map((c) => `${c.number} (${c.ends_on})`).join(', ')}` : '',
|
||
undated ? (undated === cs.length ? 'żadna nie ma wpisanej daty końca' : `${undated} z ${cs.length} bez wpisanej daty końca`) : ''].filter(Boolean).join(', ');
|
||
});
|
||
out.push({ ...rec('zestawienie', 'Zestawienie umów wg statusu i waluty (wartości łączne, liczba umów)', 'cards',
|
||
`Rejestr umów, stan na ${today}, razem ${chatUmowy(rows.length)}. ${totals.join('. ')}.`, 'galena:zestawienie', rows.map(ck)),
|
||
// `list`: the groups a list question can ask for, each picked only by its own words ("w statusie szkic"):
|
||
// "wygasające" alone is the expiry windows, not the status "wygasla".
|
||
list: statuses.map((st) => ({ re: new RegExp(`status\\p{L}*\\s+(?:\\p{L}+\\s+)?${chatEsc(st.slice(0, 5))}`, 'iu'), keys: rows.filter((c) => c.status === st).map(ck) })) });
|
||
// One record per window: in a single list up to 90 days both models lost the 60-day line.
|
||
for (const w of [30, 60, 90]) {
|
||
const soon = rows.filter((c) => c.ends_on && chatDays(c.ends_on, today) >= 0 && chatDays(c.ends_on, today) <= w)
|
||
.sort((a, b) => a.ends_on.localeCompare(b.ends_on));
|
||
out.push({ ...rec('zestawienie', `Umowy wygasające (kończące się) w ciągu ${w} dni`, 'cards',
|
||
// The window's last day is written out: the check holds an answer's "do 28 listopada" to the sources.
|
||
`Stan na ${today}, okno ${w} dni do ${chatAddDays(today, w)}. W ciągu ${w} dni kończy się ${chatUmowy(soon.length)}` + (soon.length ? ': ' : '') + soon.map((c) =>
|
||
`${c.number} ${c.name} (kontrahent ${c.counterparty || 'nie wpisany'}) kończy się ${c.ends_on}, za ${chatDays(c.ends_on, today)} dni, status ${chatStatus('umowa', c.status)}, ` +
|
||
(c.value_amount ? `wartość ${chatMoney(c.value_amount)} ${c.value_currency}` : 'wartość nie wpisana')).join('; ') + '.',
|
||
'galena:wygasajace:' + w, soon.map(ck)), list: [{ re: chatAsksWindow(w), keys: soon.map(ck) }] });
|
||
}
|
||
const top = rows.filter((c) => c.value_amount).sort((a, b) => b.value_amount - a.value_amount).slice(0, 5);
|
||
out.push(rec('zestawienie', 'Umowy o najwyższej wartości (ranking)', 'cards', 'Bez przeliczania walut. ' + top.map((c, i) =>
|
||
`${i + 1}. ${c.number} ${c.name} (kontrahent ${c.counterparty || 'nie wpisany'}): ${chatMoney(c.value_amount)} ${c.value_currency}, status ${chatStatus('umowa', c.status)}`).join('; ') + '.',
|
||
'galena:ranking', top.map(ck)));
|
||
return out;
|
||
}
|
||
|
||
// A question names a deadline group only in that group's own words. Bare substrings picked wrong groups:
|
||
// "late" in "later", "tygodni" in "w ciągu dwóch tygodni" and "w zeszłym tygodniu", "this week" in "after
|
||
// this week", "późn" in "najpóźniej".
|
||
const CHAT_DEADLINE_KINDS = { procedural: 'termin procesowy', internal: 'termin wewnętrzny', contractual: 'termin umowny', limitation: 'termin przedawnienia', hearing: 'termin rozprawy' };
|
||
const CHAT_DEADLINE_SHORT = { procedural: 'procesowy', internal: 'wewnętrzny', contractual: 'umowny', limitation: 'przedawnienie', hearing: 'rozprawa', umowa: 'koniec umowy' };
|
||
const CHAT_ASKS_LATE = /po\s+termin|przekroczon|zaległ|spóźn|piln|overdue|past\s+due|\blate\b|urgent/iu;
|
||
const CHAT_ASKS_WEEK = /(?<!(?:po|niż|after|than|beyond)\s+(?:w\s+)?)(?<![\p{L}])(?:(?:tym|ten|bieżąc\p{L}*|najbliższ\p{L}*)\s+(?:tydz|tygod)|this\s+week)/iu;
|
||
const CHAT_ASKS_LATER = /(?<!naj)późn|\blater\b/iu;
|
||
// An expiry window's list only for a question about expiry: "dodane w ostatnich 30 dniach" is no window.
|
||
const chatAsksWindow = (w) => new RegExp(`^(?![\\s\\S]*(?:ostatni|ubiegł|minion|\\bpast\\b|\\blast\\b))(?=[\\s\\S]*(?:wygas|wygaś|końc|kończ|upływ|expir|\\bend))[\\s\\S]*(?<!\\d)${w}\\s*(?:dni|days)`, 'iu');
|
||
|
||
async function chatSygna(today, names, contracts = []) {
|
||
const matters = await askerGet('sygna', 'matters');
|
||
if (matters === null) return null;
|
||
const rec = (kind, title, inner, text, key, labels, members) => ({ slug: 'sygna', kind, title, inner, text, key, labels, members });
|
||
const out = matters.map((m) => ({ ...rec('sprawa', `Sprawa ${m.reference} ${m.name}`, 'matters/' + m.id,
|
||
`Sprawa ${m.reference} „${m.name}” dla klienta ${m.client_name}, ${m.practice_area ? 'dziedzina ' + m.practice_area : 'dziedzina nie wpisana'}, ` +
|
||
`status ${chatStatus('sprawa', m.status)}, ${chatWho(names, m.responsible_lawyer_id, 'prowadzi', 'osoba prowadząca nie wpisana')}, otwarta ${m.opened_at}. ${m.description || ''}`,
|
||
'sygna:sprawa:' + m.id, [m.reference, m.name]),
|
||
at: m.closed_at || m.opened_at, did: m.closed_at ? 'zamknięta' : 'otwarta', matter: m }));
|
||
// days=365: Sygna's default window is 14 days, and a deadline 20 days out did not exist for the chat
|
||
// ("nie znalazłem", czat-v3 termin-07-data, 2026-11-03). Overdue ones come back whatever the window.
|
||
const deadlines = (await askerGet('sygna', 'deadlines?days=365')) || [];
|
||
// The urgency facts in words: given "rodzaj internal" and a bare date, a model listed overdue titles with no
|
||
// reason, and once called dates a week past "later than today".
|
||
// "(sąd)" only where a court is the forum: a breach notice to UODO is procedural, not before a court (step 0, 13.11).
|
||
const kindPl = (d) => d.kind === 'procedural' && chatCivil(d) ? 'termin procesowy (sąd)' : CHAT_DEADLINE_KINDS[d.kind] || 'termin (rodzaj ' + d.kind + ')';
|
||
const late = (d) => `po terminie od ${chatPlural(-d.days_left, 'dnia', 'dni', 'dni')}`;
|
||
for (const d of deadlines) {
|
||
const state = d.completed_at ? 'wykonany' : d.days_left < 0 ? `PO TERMINIE, niewykonany, ${late(d)}` : `za ${d.days_left} dni`;
|
||
out.push({ ...rec('termin', `Termin: ${d.title} (${d.due_date})`, `matters/${d.matter_id}?tab=deadlines`,
|
||
`Termin „${d.title}” w sprawie ${d.matter_reference} „${d.matter_name || ''}”: ${kindPl(d)}, data ${d.due_date}, ${state}, ` +
|
||
`${d.basis ? 'podstawa ' + d.basis : 'podstawa nie wpisana'}, ${chatWho(names, d.owner_id, 'odpowiada', 'osoba odpowiedzialna nie wpisana')}.`,
|
||
'sygna:termin:' + d.id, [d.title, d.due_date, chatPlDate(d.due_date)]), at: d.completed_at, did: 'wykonany', deadline: d });
|
||
}
|
||
// The default order is the date alone, earliest first, whatever the kind: which kind matters more is the
|
||
// asker's to say ("najpierw sądowe"), not ours (Tobiasz, 2026-11-04; it used to put court deadlines first).
|
||
// Expiring contracts are urgent too (Tobiasz, 2026-11-04): one in force that ends within 30 days, or has
|
||
// ended while still marked in force, joins the same date order as a deadline.
|
||
// ponytail: a fixed 30 days; a firm setting if anyone asks for another window.
|
||
const ends = contracts.filter((c) => c.status === 'obowiazuje' && c.ends_on && chatDays(c.ends_on, today) <= 30)
|
||
.map((c) => ({ title: `Koniec umowy ${c.number} „${c.name}”`, kind: 'umowa', due_date: c.ends_on, days_left: chatDays(c.ends_on, today),
|
||
who: `umowa ${c.number}, kontrahent ${c.counterparty || 'nie wpisany'}`, ref: `umowa ${c.number}, ${c.counterparty || 'kontrahent nie wpisany'}`, owner: '-',
|
||
key: 'galena:umowa:' + c.id, contract: c }));
|
||
const open = [...deadlines.filter((d) => !d.completed_at).map((d) => ({ ...d, key: 'sygna:termin:' + d.id, ref: `sprawa ${d.matter_reference} „${d.matter_name || ''}”`,
|
||
owner: names[d.owner_id] || '-', who: `sprawa ${d.matter_reference} „${d.matter_name || ''}”, ${chatWho(names, d.owner_id, 'odpowiada', 'osoba odpowiedzialna nie wpisana')}` })), ...ends]
|
||
.sort((a, b) => a.due_date.localeCompare(b.due_date));
|
||
const urgent = (d) => d.days_left < 0;
|
||
const week = (d) => d.days_left >= 0 && d.days_left <= 7;
|
||
const later = (d) => d.days_left > 7;
|
||
// One line per group, its count and its name in capitals: in one running sentence models moved deadlines
|
||
// between the groups (an overdue one listed "this week").
|
||
const groups = [['PO TERMINIE, NIEWYKONANE (najpilniejsze)', urgent, CHAT_ASKS_LATE],
|
||
['W TYM TYGODNIU (najbliższe 7 dni, do ' + chatAddDays(today, 7) + ')', week, CHAT_ASKS_WEEK], ['PÓŹNIEJ', later, CHAT_ASKS_LATER]];
|
||
const line = ([name, keep]) => { const ds = open.filter(keep);
|
||
return `${name} (${ds.length}): ${ds.map((d, i) => `${i + 1}. ${d.title} (${CHAT_DEADLINE_SHORT[d.kind] || d.kind}, ${d.due_date}, ${d.days_left < 0 ? late(d) : 'za ' + d.days_left + ' dni'}, ` +
|
||
`${d.who})`).join('; ') || 'brak'}.`; };
|
||
const owed = new Map();
|
||
const ownerOf = (d) => chatWho(names, d.owner_id, '', 'osoba odpowiedzialna nie wpisana').trim();
|
||
for (const d of open.filter((d) => urgent(d) && d.kind !== 'umowa')) owed.set(ownerOf(d), (owed.get(ownerOf(d)) || 0) + 1);
|
||
// "Visible to the asker", not "there are": an account that sees no matter must not read as a firm without deadlines.
|
||
// Named in the words people ask with ("co pilne na ten tydzień", "zadania do zrobienia"): word search found
|
||
// nothing for them, and an overdue deadline is the urgent task.
|
||
// Contracts are named only when one is listed: for an account without the contract register, "wygasające umowy" in this
|
||
// title won the search for "które umowy wygasają" and hid the no-access answer (jan-60-dni, 2026-11-04).
|
||
const note = '\nKolejność pilności w tym zestawieniu: według faktycznej daty terminu, najwcześniejszy pierwszy, bez względu na rodzaj (procesowy, umowny, wewnętrzny, koniec umowy). Jeśli pytający wskaże inny akcent, na przykład najpierw terminy sądowe, ułóż według niego.' +
|
||
// Past a court deadline the act itself is no longer the step: told only the order, the model said "złóż
|
||
// odpowiedź" five days late. Whether a still-meetable court deadline goes first is the lawyer's call (open).
|
||
' Tylko przy terminie w postępowaniu cywilnym (wyznaczonym przez sąd albo z k.p.c.) po terminie następny krok to sprawdzić, czy czynność została złożona, a jeśli nie, rozważyć wniosek o przywrócenie terminu (art. 168 i art. 169 KPC); przy terminie z innego postępowania (np. przed UODO) skutki uchybienia ustala się według jego przepisów; przy zadaniu wewnętrznym, terminie umownym i końcu umowy ten wniosek nie ma zastosowania. Termin procesowy z tego tygodnia, który jeszcze można dotrzymać, wymień obok, żeby nie minął.';
|
||
out.push({ ...rec('zestawienie', `Terminy procesowe, zadania do zrobienia${ends.length ? ' i wygasające umowy' : ''}: pilne (po terminie, zaległe), w tym tygodniu i później, kto odpowiada`, 'deadlines',
|
||
`Stan na ${today} (tydzień kalendarzowy od ${chatWeekOf(today).join(' do ')}), terminy widoczne na koncie pytającego${ends.length ? ' oraz umowy w mocy kończące się w ciągu 30 dni (koniec umowy liczy się jak termin)' : ''}.\n` + groups.map(line).join('\n') +
|
||
note +
|
||
(owed.size ? `\nZaległe (po terminie) według osoby odpowiedzialnej: ${[...owed].sort((a, b) => b[1] - a[1]).map(([n, k]) => `${n} ${k}`).join(', ')}.` : ''),
|
||
'sygna:terminy', null, groups.flatMap(([, keep]) => open.filter(keep).map((d) => d.key))),
|
||
// `note`: said to the model inside the source, cut out where code shows the source to the asker (the fallback).
|
||
note,
|
||
// `dates`: chatVerify holds "w tym tygodniu"/"po terminie" in an answer to the group the date is in.
|
||
items: open,
|
||
list: groups.map(([label, keep, re], i) => ({ label: ['po terminie', 'w tym tygodniu', 'później'][i], re, keys: open.filter(keep).map((d) => d.key),
|
||
dates: open.filter(keep).map((d) => d.due_date) })) });
|
||
for (const p of (await askerGet('sygna', 'parties')) || []) {
|
||
const linked = matters.filter((m) => m.client_party_id === p.id);
|
||
out.push({ ...rec('strona', p.name, 'parties/' + p.id,
|
||
`Strona (klient/kontrahent) ${p.name}, NIP ${p.nip || 'nie wpisany'}, adres ${p.address || 'nie wpisany'}. ` +
|
||
`Sprawy widoczne na koncie pytającego, w których jest klientem: ${linked.map((m) => m.reference + ' ' + m.name).join('; ') || 'brak'}.`,
|
||
'sygna:strona:' + p.id, [p.name], linked.map((m) => 'sygna:sprawa:' + m.id)), party: p });
|
||
}
|
||
return out;
|
||
}
|
||
|
||
async function chatCounsel() {
|
||
const firms = await askerGet('counsel', 'firms');
|
||
if (firms === null) return null;
|
||
const firm = Object.fromEntries(firms.map((f) => [f.id, f.name]));
|
||
const rec = (kind, title, inner, text, key, labels, members) => ({ slug: 'counsel', kind, title, inner, text, key, labels, members });
|
||
const out = firms.map((f) => ({ ...rec('kancelaria', f.name, 'firms/' + f.id,
|
||
`Kancelaria zewnętrzna ${f.name} (${f.legal_name}), współpraca ${chatStatus('kancelaria', f.status)}, ${f.contact_person ? 'kontakt ' + f.contact_person : 'osoba kontaktowa nie wpisana'}. ${f.notes || ''}`,
|
||
'counsel:kancelaria:' + f.id, [f.name, f.legal_name]), firm: f }));
|
||
for (const m of (await askerGet('counsel', 'matters')) || []) {
|
||
out.push({ ...rec('zlecenie', `Zlecenie ${m.reference} ${m.title}`, 'matters/' + m.id,
|
||
`Zlecenie dla kancelarii zewnętrznej ${firm[m.firm_id]}: ${m.reference} „${m.title}”, status ${chatOrderStatus(m.status)}, ` +
|
||
`${m.budget_estimate != null ? `budżet ${m.budget_estimate} ${m.budget_currency}` : 'budżet nie wpisany'}.`,
|
||
'counsel:zlecenie:' + m.id, [m.reference, m.title]), at: m.created_at, did: 'zlecone', order: m });
|
||
}
|
||
for (const cy of (await askerGet('counsel', 'review-cycles')) || []) {
|
||
const snaps = ((await askerGet('counsel', `review-cycles/${cy.id}/snapshots`)) || []).sort((a, b) => b.composite_score - a.composite_score);
|
||
if (snaps.length) out.push(rec('ranking', `Ranking (oceny) kancelarii zewnętrznych: ${cy.name}`, null,
|
||
`Cykl ocen ${cy.name} (cykl ${chatStatus('cykl', cy.status)}), od najwyższej do najniższej oceny: ` +
|
||
snaps.map((s, i) => `${i + 1}. ${firm[s.firm_id]}: ${s.composite_score} pkt, ocen ${s.evaluation_count}`).join('; ') + '.' +
|
||
// Who is last, said outright: from the order alone Bielik called the last of five "5. miejsce od końca".
|
||
(snaps.length > 1 ? ` Najwyższa ocena: ${firm[snaps[0].firm_id]} (1. miejsce z ${snaps.length}). Najniższa ocena: ` +
|
||
`${firm[snaps.at(-1).firm_id]} (ostatnie, ${snaps.length}. miejsce z ${snaps.length}).` : ''),
|
||
'counsel:ranking:' + cy.id, null, snaps.map((s) => 'counsel:kancelaria:' + s.firm_id)));
|
||
}
|
||
return out;
|
||
}
|
||
|
||
async function chatGalena(names) {
|
||
const home = await askerGet('galena', 'drive/home');
|
||
if (home === null) return null;
|
||
const out = [];
|
||
// A project shared with someone outside its workspace shows only under "shared".
|
||
const todo = [...home.workspaces, ...((await askerGet('galena', 'drive/shared')) || [])];
|
||
while (todo.length) {
|
||
const c = todo.pop();
|
||
if (c.kind !== 'project') { todo.push(...(((await askerGet('galena', 'nodes/' + c.id)) || {}).children || [])); continue; }
|
||
const tree = (await askerGet('galena', `projects/${c.id}/tree?recursive=true`)) || [];
|
||
const files = (Array.isArray(tree) ? tree : tree.entries || []).filter((x) => ['file', 'blob'].includes(x.type || x.kind)).map((x) => x.path);
|
||
out.push({ slug: 'galena', kind: 'projekt', title: `Projekt dokumentów ${c.name}`, inner: 'n/' + c.id, key: 'galena:projekt:' + c.id, labels: [c.name],
|
||
text: `Projekt dokumentów „${c.name}” w Galenie (${c.path}), wymaga akceptacji: ${c.review_policy !== 'open' ? 'tak' : 'nie'}. Pliki: ${files.join('; ') || 'brak'}.`, project: c });
|
||
for (const d of (await askerGet('galena', `projects/${c.id}/drafts`)) || []) {
|
||
out.push({ slug: 'galena', kind: 'wersja', title: `Wersja do akceptacji: ${d.title}`, inner: 'n/' + c.id, key: 'galena:wersja:' + d.id, labels: [d.title],
|
||
text: `Wersja robocza (opinia/dokument) „${d.title}” w projekcie ${c.name}, status ${chatStatus('wersja', d.status)}, ` +
|
||
`${chatWho(names, d.author_id, 'autor', 'autor nie wpisany')}, utworzona ${d.created_at.slice(0, 10)}.`, at: d.created_at, did: 'utworzona',
|
||
draft: d, projectKey: 'galena:projekt:' + c.id });
|
||
}
|
||
}
|
||
return out;
|
||
}
|
||
|
||
// What Insider's resolve takes: an article of a code or a named EU act, a Dz.U. reference, a case number, a CELEX.
|
||
// A topic question without a citation ("kara umowna") goes to chatTopic, and only once Insider's own index
|
||
// of the acts' texts is built: its live mode matches titles and finds junk.
|
||
// Contracts write a code's full name ("art. 481 § 1 Kodeksu cywilnego"), which resolve takes as it is; it
|
||
// comes first, or "k" plus three letters reads "Kodeksu" as an abbreviation. A longer name goes before its
|
||
// prefix: "Kodeksu karnego skarbowego" cut to "Kodeksu karnego" resolves to another act.
|
||
const CHAT_CODE = 'Kodeks[a-ząćęłńóśźż]*\\s+(?:postępowania\\s+(?:cywiln|karn|administracyjn)|postępowania\\s+w\\s+sprawach\\s+o\\s+wykroczeni|karn[a-ząćęłńóśźż]*\\s+(?:skarbow|wykonawcz)|cywiln|karn|pracy|spółek\\s+handlowych|wykroczeń|rodzinn[a-ząćęłńóśźż]*\\s+i\\s+opiekuńcz|morsk|wyborcz)[a-ząćęłńóśźż]*';
|
||
const CHAT_ART = '\\bart(?:ykuł|\\.)?\\s*\\d+[a-z]?(?:\\s*(?:§|ust\\.|pkt|lit\\.)\\s*\\w+\\)?)*\\s+';
|
||
const CHAT_CITES = [
|
||
new RegExp(CHAT_ART + '(?:' + CHAT_CODE + '|k(?!odeks)\\.?\\s?[a-z]{1,3}\\.?(?:\\s?[a-z]\\.?){0,3}(?![a-ząćęłńóśźż])|p\\.p\\.s\\.a\\.|o\\.p\\.|RODO|GDPR|DSA|DMA|NIS2|eIDAS|MiCA|AI Act)', 'gi'),
|
||
// "art. 28 rozporządzenia Parlamentu Europejskiego i Rady (UE) 2016/679": resolve knows it only as RODO.
|
||
// Not across another regulation's number: "art. 28 rozporządzenia (UE) 2022/2065 oraz ... 2016/679" is DSA's.
|
||
new RegExp(CHAT_ART + 'rozporządzenia\\b(?:(?!\\((?:UE|WE)\\)\\s*(?:nr\\s*)?\\d{4}\\/\\d+)[^;]){0,160}?\\(UE\\)\\s*(?:nr\\s*)?2016\\/679', 'gi'),
|
||
/\barticle\s+\d+[a-z]?\s+(?:GDPR|DSA|DMA|NIS2|eIDAS|MiCA|AI Act)/gi,
|
||
/\bDz\.\s?U\.\s*(?:z\s*)?\d{4}(?:\s*r\.)?\s*(?:nr\s*\d+\s*)?poz\.\s*\d+/gi,
|
||
/\b[IVX]{1,4}\s+[A-Z][A-Za-z]{0,3}(?:\/[A-Z][a-z]{0,2})?\s+\d{1,5}\/\d{2}\b/g,
|
||
/\bC-\d{1,3}\/\d{2}\b/g, /\b[0-9]{5}[A-Z]{1,2}[0-9]{4}\b/g,
|
||
];
|
||
// The Insider screen a document opens on: the console's own #/doc route, at the article when given one.
|
||
// `art` is resolve's article ({part, label}; its url is a graph link for codes) or chatArticle's text url.
|
||
function insiderInner(d, art) {
|
||
const [src, ...rest] = d.id.split(':');
|
||
const id = rest.join(':');
|
||
const route = ['eli', 'dzu_md'].includes(src) ? ['act', ...id.split('/')]
|
||
: ['eurlex', 'cellar'].includes(src) ? (d.kind === 'judgment' ? ['judgment', 'eurlex', id] : ['eu', id]) : ['judgment', src, id];
|
||
const m = typeof art === 'string' && art.match(/part=(\d+)#art-(.+)$/);
|
||
const at = art && art.part && art.label ? [art.part, art.label] : m ? [m[1], m[2]] : null;
|
||
return 'doc/' + route.map(encodeURIComponent).join('/') + (at ? `?part=${at[0]}&art=${encodeURIComponent(at[1])}` : '');
|
||
}
|
||
// "art. 471 k.c. i art. 6 RODO": the abbreviation's optional letters run on into the "i"; cut it off.
|
||
const chatCites = (text) => [...new Set(CHAT_CITES.flatMap((re) => String(text).match(re) || [])
|
||
.map((c) => c.replace(/\s+/g, ' ').replace(/\s+rozporządzenia\b.*$/i, ' RODO').replace(/\.\s[a-ząćęłńóśźż]$/i, '.')))];
|
||
// Insider's text: "\r\n" lines, \x02 where a word was hyphenated across lines, footnote marks on lines of
|
||
// their own or as "[^5]" after a word, markdown headings.
|
||
const chatClean = (s) => String(s || '').replace(/\r\n?/g, '\n').replace(/\x02\n?/g, '').replace(/^\s*\[\d+\]\s*$/gm, '').replace(/\[\^\d+\]/g, '')
|
||
.replace(/^#+\s*/gm, '').replace(/[ \t]+/g, ' ').replace(/\n{3,}/g, '\n\n').trim();
|
||
async function chatLaw(question, index) {
|
||
if (!index.law) return []; // no access to Insider
|
||
const out = [];
|
||
for (const c of chatCites(question).slice(0, 3)) {
|
||
let r;
|
||
try { r = await askerGet('insider', 'resolve?citation=' + encodeURIComponent(c)); } catch { continue; } // 422: not a citation after all
|
||
if (!r) continue; // a 404 is this citation's, not Insider's: the next one may resolve
|
||
const docs = r.documents || [];
|
||
const a = r.article && r.article.located ? r.article : null;
|
||
if (a && docs[0]) {
|
||
out.push({ slug: 'insider', kind: 'przepis', title: `${c}: ${docs[0].title}`, inner: insiderInner(docs[0], a), url: docs[0].official_url, key: 'insider:' + c,
|
||
seed: { act: docs[0], num: a.label },
|
||
text: `${docs[0].title} (${docs[0].signature}), status aktu: ${docs[0].status}. Tekst ${c}: ${chatClean(a.text).slice(0, 6000)}` });
|
||
continue;
|
||
}
|
||
// A case number's ruling: the operative part opens its text, the snippet is the first line of the file.
|
||
const ruling = docs.find((d) => d.kind === 'judgment' && d.status === 'SENTENCE') || docs.find((d) => d.kind === 'judgment');
|
||
if (ruling) {
|
||
const [src, ...id] = ruling.id.split(':');
|
||
const t = await askerGet('insider', `judgments/${src}/${encodeURIComponent(id.join(':'))}/text?max_chars=4000`).catch(() => null);
|
||
if (t && t.text) ruling.snippet = t.text.slice(0, 4000);
|
||
}
|
||
for (const d of docs.slice(0, 3)) {
|
||
out.push({ slug: 'insider', kind: d.kind === 'judgment' ? 'orzeczenie' : 'akt', title: `${d.title} (${d.court_or_publisher}, ${d.date})`,
|
||
inner: insiderInner(d), url: d.official_url, key: 'insider:' + d.id,
|
||
text: `${d.kind === 'judgment' ? 'Orzeczenie' : 'Akt prawny'} ${d.title}, ${d.court_or_publisher}, ${d.date}, sygnatura ${d.signature}, status ${d.status}. ${d.snippet || ''}` });
|
||
}
|
||
(r.notices || []).forEach((n, i) => out.push({ slug: 'insider', kind: 'uwaga', title: `Insider o „${c}”`, inner: null, key: 'insider:uwaga:' + c + ':' + i, text: String(n.text || n.message || n) }));
|
||
}
|
||
return out;
|
||
}
|
||
|
||
// A question about the law itself, not the firm's data: legal words, and nothing of ours named or implied.
|
||
// "Termin" alone is a Sygna deadline, "kto" a person here, "w umowie z X" one of our contracts.
|
||
const CHAT_TOPICWORD = /przepis|\bustaw|kodeks|\bprawo\b|prawn|przedawn|kar[aęy]\s+umown|wypowiedz|odstąpi|rękojm|odszkodowan|zadat|pracodawc|urlop|spadk|zachowek|orzecznictw|\blaws?\b|statut|case law/i;
|
||
const CHAT_FIRMWORD = /(?:^|[^\p{L}])(?:mamy|mam|nasz\p{L}*|moj\p{L}*|mój|kontrahent\p{L}*|klien\p{L}*|kancelari\p{L}*|kto|sygn[aiy]e?|rejestr\p{L}*|w umowie|our|we)(?![\p{L}])/iu;
|
||
// "Które umowy przewidują kary umowne?", "Który prawnik prowadzi najwięcej spraw?": our records as the subject.
|
||
const CHAT_FIRMLIST = /(?:^|[^\p{L}])(?:któr|jaki|ile|pokaż|wymień)\p{L}*\s+(?:z\s+|wszystkie\s+)?(?:umowy|umów|sprawy|spraw|prawni\p{L}*)(?![\p{L}])/iu;
|
||
function chatRoute(question, named = 0) {
|
||
if (chatCites(question).length) return 'law_cite';
|
||
return !named && CHAT_TOPICWORD.test(question) && !CHAT_FIRMWORD.test(question) && !CHAT_FIRMLIST.test(question) ? 'law_topic' : 'data';
|
||
}
|
||
const chatActName = (d) => (!d ? '' : /^Dz\.\s?U/.test(d.signature || '') ? d.signature : String(d.title || '').replace(/\s+z dnia[\s\S]*$/, ''));
|
||
const chatOff = (d) => !!d && ((d.extra || {}).in_force === 'NOT_IN_FORCE' || /uchylon|nieobowiązuj|wygaśnięcie/i.test(d.status || ''));
|
||
const chatBare = (d) => (d ? d.id.replace(/^[a-z_]+:/, '') : '');
|
||
/* A question about the law with no citation ("czy pracodawca może wypowiedzieć…"): one short call to the
|
||
chosen model names the act and rewords the question in the statute's words, code reads that act's whole
|
||
text from Insider and ranks its articles by word prefixes, then fetches the best three articles' text; the
|
||
model answering reads them. Insider's own full-text index is the fallback when no act is named: it ANDs
|
||
whole words, so "przedawnienie" never meets "przedawniają się" and "zwolnienie lekarskie" never meets
|
||
"usprawiedliwiona nieobecność". A found article may still not answer, and the model is told to say so.
|
||
Rulings only when asked for, as examples: SAOS returns them newest first, not by relevance. */
|
||
// Question words Insider's stopword list keeps, and words every legal question shares: AND over them
|
||
// finds only the longest articles.
|
||
const CHAT_QWORDS = /^(jak\p{L}*|kto|kogo|komu|kiedy|ile|gdzie|dlaczego|czemu|może|można|mogę|moż\p{L}*|musi|muszę|trzeba|wolno|należy|ma|mają|wynosi|są|był\p{L}*|być|przepis\p{L}*|prawo|prawa|ustaw\p{L}*|zgodnie|polsk\p{L}*|orzecz\p{L}*|wyrok\p{L}*|sąd\p{L}*|what|which|when|who|how|can|may|is|are|the|law|under)$/u;
|
||
const CHAT_CASELAW = /orzecznictw|orzeczeni[ae]|orzeczeń|wyrok(?:i|ów|ach)|uchwał[ay] sn|case law|rulings|judgments/i;
|
||
const CHAT_EU = /\b(?:UE|EU|RODO|GDPR|DSA|DMA|NIS2|AI Act)\b|unijn|europejsk|dyrektyw|rozporządzeni\p{L}* (?:UE|Parlamentu)/iu;
|
||
const CHAT_COURTS = [[/Najwyższy|Trybunał/, 0], [/Naczelny Sąd Administracyjny/, 1], [/Apelacyjn/, 2], [/Okręgow|Wojewódzki Sąd Administracyjny/, 3], [/Rejonow/, 4]];
|
||
const chatTopicWords = (q) => (q.match(/[\p{L}\d]+/gu) || []).filter((w) => w.length > 1 && !CHAT_QWORDS.test(w.toLowerCase()));
|
||
// Ready = the dataset's index is built AND its first import finished: Cellar's index reports ready while
|
||
// the import still runs, and search then skips it ("index_updating:cellar").
|
||
async function chatTopicState(eu) {
|
||
const d = ((await askerGet('insider', 'sources/datasets')) || {}).datasets || [];
|
||
const s = d.find((x) => x.name === (eu ? 'cellar' : 'dzu_md')) || {};
|
||
const p = s.progress || {};
|
||
// A run's own progress counts that run (Cellar's "fetched" restarts per pass); documents is the total kept.
|
||
return { ready: !!(s.index && s.index.ready && s.completed_at), done: p.total ? p.done : s.documents || 0, total: p.total || null };
|
||
}
|
||
// One article's whole text from the act's text: the outline gives where "Art. N" starts, the 20000-char
|
||
// part holding it is cut from there to the next article. The outline drops superscripts ("Art. 41[1]" is
|
||
// "Art. 41") and lists the promulgating notice's own articles, hence the check on the text itself. A t.j.
|
||
// can hold one number twice (two "Art. 94[3]." in the Labour Code): nth picks which.
|
||
async function chatArticle(act, num, nth = 0) {
|
||
const path = chatTextPath(act);
|
||
const M = 20000;
|
||
const head = await askerGet('insider', path + '?part=1&max_chars=1000');
|
||
const [base, sup] = String(num).split('^');
|
||
const at = new RegExp(`^Art(?:ykuł|\\.)\\s*${base}${sup ? `(?:\\[${sup}\\]|${chatSup('^' + sup)})` : ''}\\.?(?![\\d\\[⁰¹²³⁴⁵⁶⁷⁸⁹ᵃᵇᶜᵈᵉ])`);
|
||
// Some outlines keep the superscript ("Art. 505¹ᵃ"), others drop it: only those two labels are candidates.
|
||
// Any label with base 505 cost k.p.c. 45 part fetches and 3 s for art. 505³⁶ (2026-10-29).
|
||
const want = [base, sup ? base + chatSup('^' + sup) : base];
|
||
for (const o of ((head && head.outline) || []).filter((x) => want.includes(x.label.replace(/^Art(?:ykuł|\.)\s*/, '')))) {
|
||
let part = Math.floor(o.offset / M) + 1;
|
||
let t = await askerGet('insider', `${path}?part=${part}&max_chars=${M}`);
|
||
// Parts end at a line break, so they drift from multiples of 20000: the article may sit in a neighbour.
|
||
if (t && t.text && o.offset >= t.offset + t.text.length && part < t.parts) t = await askerGet('insider', `${path}?part=${++part}&max_chars=${M}`);
|
||
else if (t && t.text && o.offset < t.offset && part > 1) t = await askerGet('insider', `${path}?part=${--part}&max_chars=${M}`);
|
||
if (!t || !t.text) continue;
|
||
let text = t.text.slice(o.offset - t.offset);
|
||
if (!at.test(text) || nth-- > 0) continue;
|
||
if (text.length < 6000 && part < t.parts) text += ((await askerGet('insider', `${path}?part=${part + 1}&max_chars=${M}`)) || {}).text || '';
|
||
const end = text.slice(4).search(/\n[\s#]*Art(?:ykuł|\.)\s*\d/); // "\n\n##### Art. 28." in many dzu_md texts
|
||
text = (end >= 0 ? text.slice(0, end + 4) : text).replace(/^Dziennik Ustaw\s*[–-]\s*\d+\s*[–-]\s*Poz\.\s*\d+\s*$/gm, '');
|
||
return { text: chatClean(text).replace(/\n(?:TYTUŁ|DZIAŁ|Rozdział|Oddział|KSIĘGA)\b[\s\S]*$/, '').slice(0, 4000), url: `${path}?part=${part}#art-${num}` };
|
||
}
|
||
return null;
|
||
}
|
||
// Rulings for an explicit case-law question: the slow SAOS search answers through its pending ticket.
|
||
async function chatRulings(words) {
|
||
const s = await askerGet('insider', 'search?kind=judgment&jurisdiction=pl&progressive=true&limit=20&q=' + encodeURIComponent(words.join(' ')));
|
||
let js = (s && s.judgments) || [];
|
||
for (const p of (s && s.pending) || []) {
|
||
const r = await askerGet('insider', 'search/pending?ticket=' + encodeURIComponent(p.ticket)).catch((ex) => { if (ex.name === 'AbortError') throw ex; return null; });
|
||
js = js.concat((r && r.judgments) || []);
|
||
}
|
||
const q = chatStems(words.join(' '));
|
||
const tier = (j) => (CHAT_COURTS.find(([re]) => re.test(j.court_or_publisher || '')) || [null, 5])[1];
|
||
const overlap = (j) => [...chatStems(j.snippet || '')].filter((w) => q.has(w)).length;
|
||
return js.filter((j) => overlap(j) >= Math.min(2, q.size)).sort((a, b) => tier(a) - tier(b) || overlap(b) - overlap(a)).slice(0, 2)
|
||
.map((j) => ({ slug: 'insider', kind: 'orzeczenie', title: `Przykład z orzecznictwa: ${j.court_or_publisher}, ${j.date}, ${j.signature}`, inner: insiderInner(j),
|
||
url: j.official_url, key: 'insider:' + j.id,
|
||
text: `Przykład z orzecznictwa (fragment uzasadnienia, nie przesądza sprawy): ${j.court_or_publisher}, ${j.date}, sygnatura ${j.signature}. ${String(j.snippet || '').replace(/\s+/g, ' ')}` }));
|
||
}
|
||
// Everyday words for what a statute says otherwise, added beside them: Insider's index has no synonyms.
|
||
// "dług" is matched as its own inflections: as a prefix it caught "długo" and cost "how long" questions a hit.
|
||
const CHAT_VOCAB = [[/zwolnieni\p{L}* lekarski\p{L}*|\bL4\b|chorobow\p{L}*/giu, 'niezdolności do pracy usprawiedliwionej nieobecności'],
|
||
[/dyscyplinarn\p{L}*/giu, 'bez wypowiedzenia z winy pracownika'], [/wyciek\p{L}* danych/giu, 'naruszenie ochrony danych'], [/\bUODO\b/g, 'organowi nadzorczemu'],
|
||
[/(?<!\p{L})dług(?:u|i|ów|iem|owi|ami|ach|om)?(?!\p{L})/giu, 'zobowiązania'], [/spóźni\p{L}*/giu, 'opóźnienie'], [/\bz o\.\s?o\./giu, 'z ograniczoną odpowiedzialnością'], [/alimen\p{L}*/giu, 'świadczenia alimentacyjne'],
|
||
[/zwrot\p{L}* towar\p{L}*/giu, 'odstąpić od umowy'], [/przez internet|online/giu, 'na odległość']];
|
||
const chatVocab = (q) => CHAT_VOCAB.reduce((s, [re, w]) => s.replace(re, (m) => `${m} ${w}`), q);
|
||
// The model names the act and rewords the question the way statutes word it; it gives no article
|
||
// numbers, the article is chosen by code from the act's text in Insider, so the model cannot invent law.
|
||
// The example is deliberately outside testy/czat-v2/topic-set.json.
|
||
const CHAT_REWRITE = 'Zamieniasz pytanie o polskie prawo na słowa do wyszukania przepisu w tekście ustawy. Podaj ustawę, w której najpewniej jest odpowiedź, i 3 krótkie zapytania słowami, którymi mówi sama ustawa, a nie potocznymi (np. „rażącej niewdzięczności”, a nie „niewdzięczny”). Odpowiedz tylko JSON: {"akt": "nazwa ustawy", "q": ["zapytanie 1", "zapytanie 2", "zapytanie 3"]}, bez numerów artykułów.\n\n' +
|
||
'Przykład. Pytanie: Czy mogę odebrać darowiznę, jeśli obdarowany okazał się niewdzięczny?\n{"akt": "Kodeks cywilny", "q": ["darczyńca może odwołać darowiznę", "rażącej niewdzięczności", "obdarowany dopuścił się"]}\n\nPytanie: ';
|
||
// The 9B answers in about 1 s (2026-10-29); a model still loading would take a minute, so past this the
|
||
// question's own words search alone.
|
||
const CHAT_REWRITE_MS = 3000;
|
||
// Codes resolve by abbreviation to their current consolidated text; any other act is found by its title.
|
||
// Anchored on "kodeks": a bare /rodzinny/ sent "o świadczeniach rodzinnych" to k.r.o.
|
||
const CHAT_CODE_ABBR = [[/kodeks\p{L}* postępowania cywilnego/iu, 'k.p.c.'], [/kodeks\p{L}* postępowania karnego/iu, 'k.p.k.'],
|
||
[/kodeks\p{L}* postępowania administracyjnego/iu, 'k.p.a.'], [/kodeks\p{L}* spółek handlowych/iu, 'k.s.h.'], [/kodeks rodzinny/i, 'k.r.o.'],
|
||
[/kodeks pracy/i, 'k.p.'], [/kodeks cywilny/i, 'k.c.'], [/kodeks wykroczeń/i, 'k.w.'], [/kodeks karny(?! (?:skarbowy|wykonawczy))/i, 'k.k.'],
|
||
[/\bRODO\b|2016\/679|ogólne rozporządzenie o ochronie danych/i, 'RODO']];
|
||
const chatTextPath = (d) => (/^(?:eurlex|cellar):/.test(d.id) ? 'acts/eu/' : 'acts/') + chatBare(d) + '/text';
|
||
const chatSup = (n) => String(n).replace(/\^(\d+)/, (_, d) => [...d].map((c) => '⁰¹²³⁴⁵⁶⁷⁸⁹'[c]).join(''));
|
||
|
||
async function chatRewrite(model, question, onStatus) {
|
||
// The clock stops while LM Studio loads the model: aborting then cancelled the load, so a cold model never
|
||
// got loaded by this call and every topic question fell back (2026-10-29). The answer needs it loaded anyway.
|
||
const ctl = new AbortController();
|
||
let timer = null;
|
||
let last = null;
|
||
const arm = (on) => { clearTimeout(timer); timer = on ? setTimeout(() => ctl.abort(), CHAT_REWRITE_MS) : null; };
|
||
const onUpdate = (x) => {
|
||
if (x.status === last) return;
|
||
last = x.status;
|
||
if (x.status) onStatus(x.status);
|
||
arm(!/^Ładuję model/.test(x.status || '')); // chatRound's status while the model loads
|
||
};
|
||
arm(true);
|
||
try {
|
||
const got = await chatRound(model, [{ role: 'user', content: CHAT_REWRITE + question }], { content: '' }, onUpdate,
|
||
{ temperature: 0, max_tokens: 120, signal: AbortSignal.any([chat.ctl.signal, ctl.signal]) });
|
||
const j = JSON.parse(got.text.slice(got.text.indexOf('{'), got.text.lastIndexOf('}') + 1));
|
||
return { act: String(j.akt || ''), queries: (Array.isArray(j.q) ? j.q : []).map(String).slice(0, 4) };
|
||
} catch (ex) {
|
||
if (chat.ctl.signal.aborted || ex.refusal) throw ex;
|
||
return { act: '', queries: [] }; // timed out, unparsable or the model failed: the question's words still search
|
||
} finally {
|
||
clearTimeout(timer);
|
||
}
|
||
}
|
||
async function chatActDoc(name) {
|
||
const code = (CHAT_CODE_ABBR.find(([re]) => re.test(name)) || [])[1];
|
||
if (code) return ((await askerGet('insider', 'resolve?citation=' + encodeURIComponent('art. 1 ' + code)) || {}).documents || [])[0] || null;
|
||
// "Ustawa z dnia 30 maja 2014 r. o prawach konsumenta" is the t.j. "Ustawa o prawach konsumenta (tekst jednolity)";
|
||
// the same words are no match for "o zmianie ustawy o prawach konsumenta".
|
||
const bare = (t) => t.toLowerCase().replace(/\s*\(.*$/, '').replace(/^ustawa\s*(?:z dnia .*? r\.)?\s*[-–]?\s*/, '').trim();
|
||
const want = bare(name);
|
||
if (want.length < 6) return null;
|
||
const s = await askerGet('insider', 'search?kind=act&jurisdiction=pl&limit=6&q=' + encodeURIComponent(want.slice(0, 300)));
|
||
return ((s && s.acts) || []).filter((a) => !chatOff(a) && bare(a.title) === want)
|
||
.sort((a, b) => /tekst jednolity/.test(b.title) - /tekst jednolity/.test(a.title))[0] || null;
|
||
}
|
||
// The act's articles from its whole text, once per conversation (the Civil Code is five 100000-char parts).
|
||
async function chatActArticles(doc, index) {
|
||
const cache = (index.acts ||= new Map());
|
||
if (!cache.has(doc.id)) {
|
||
cache.set(doc.id, (async () => {
|
||
const path = chatTextPath(doc);
|
||
const first = await askerGet('insider', path + '?part=1&max_chars=100000');
|
||
const parts = [first];
|
||
// Two at a time: wider fan-outs exhausted Insider's connection pool (HTTP 500, 2026-10-29).
|
||
for (let n = 2; n <= ((first && first.parts) || 1); n += 2) {
|
||
parts.push(...await Promise.all([n, n + 1].filter((k) => k <= first.parts).map((k) => askerGet('insider', `${path}?part=${k}&max_chars=100000`))));
|
||
}
|
||
// A missing part would be cached as an act without those articles for the whole conversation.
|
||
if (parts.some((x) => !x || !x.text)) throw new Error('insider: act text incomplete');
|
||
const text = parts.map((x) => x.text).join('\n').replace(/\x02\r?\n?/g, '').replace(/\r\n?/g, '\n');
|
||
// A superscript is "Art. 41[1]." in some texts and "Art. 505¹ᵃ." in others; both become "41^1".
|
||
const marks = [...text.matchAll(/^[\s#]*(?:Art\.|Artykuł)\s*(\d+[a-z]*(?:\[\d+\]|[⁰¹²³⁴⁵⁶⁷⁸⁹]+)?[a-zᵃᵇᶜᵈᵉ]*)\.?/gm)];
|
||
const seen = new Map();
|
||
return marks.map((m, i) => {
|
||
const num = m[1].replace(/\[(\d+)\]|[⁰¹²³⁴⁵⁶⁷⁸⁹]+/, (x, d) => '^' + (d || [...x].map((c) => '⁰¹²³⁴⁵⁶⁷⁸⁹'.indexOf(c)).join('')));
|
||
seen.set(num, (seen.get(num) || 0) + 1);
|
||
return { num, nth: seen.get(num) - 1, text: text.slice(m.index, Math.min(i + 1 < marks.length ? marks[i + 1].index : text.length, m.index + 6000)) };
|
||
});
|
||
})().catch((ex) => { cache.delete(doc.id); throw ex; }));
|
||
}
|
||
return cache.get(doc.id);
|
||
}
|
||
// Word prefixes, so "przedawnienie" meets the statute's "przedawniają się": 5 letters for inflection, 7 more
|
||
// for long words, where 5 ("przed") is shared by unrelated ones.
|
||
const chatPrefixes = (s) => (String(s).toLowerCase().match(/\p{L}{3,}/gu) || []).flatMap((w) => (w.length > 7 ? [w.slice(0, 5), w.slice(0, 7) + '+'] : [w.slice(0, 5)]));
|
||
const CHAT_RANK_STOP = new Set(['czy', 'jaki', 'jaka', 'jakie', 'jest', 'się', 'gdy', 'jeśli', 'jeżeli', 'który', 'która', 'które', 'przez', 'oraz', 'albo', 'jego', 'tego', 'według'].map((w) => w.slice(0, 5)));
|
||
// The act's articles ranked by the rare words they share with the query, shorter ones slightly favoured
|
||
// (the fourth root of the length: 16 of 24 on topic-set.json against 13 for the square root and 14 for none).
|
||
function chatRankArticles(arts, query) {
|
||
if (!arts.df) {
|
||
for (const a of arts) a.stems = new Set(chatPrefixes(a.text));
|
||
arts.df = new Map();
|
||
for (const a of arts) for (const w of a.stems) arts.df.set(w, (arts.df.get(w) || 0) + 1);
|
||
arts.avg = arts.reduce((n, a) => n + a.text.length, 0) / (arts.length || 1);
|
||
}
|
||
const q = [...new Set(chatPrefixes(query))].filter((w) => !CHAT_RANK_STOP.has(w));
|
||
return arts.map((a) => ({ a, s: q.reduce((s, w) => s + (a.stems.has(w) ? Math.log(1 + arts.length / (arts.df.get(w) + 1)) : 0), 0) / (0.5 + 0.5 * a.text.length / arts.avg) ** 0.25 }))
|
||
.filter((x) => x.s > 0).sort((x, y) => y.s - x.s);
|
||
}
|
||
// {records} for the answer, or {coded}: what code says itself (no access, index not built, nothing found).
|
||
// Measured on testy/czat-v2/topic-set.json (24 questions, 2026-10-29), expected article in the top 3: Insider's
|
||
// search with the question's words 4 (5 with CHAT_VOCAB); the model's act ranked by code 16, in about 1.2 s on qwen 9B.
|
||
async function chatTopic(question, index, onStatus, model) {
|
||
if (!index.law) return { coded: 'Nie masz dostępu do Insidera, więc nie wyszukam przepisów. O dostęp poproś administratora.' };
|
||
const words = chatTopicWords(chatVocab(question));
|
||
const rw = model ? await chatRewrite(model, question, onStatus) : { act: '', queries: [] };
|
||
onStatus('Szukam przepisów w Insiderze…');
|
||
const doc = rw.act ? await chatActDoc(rw.act).catch((ex) => { if (ex.name === 'AbortError') throw ex; return null; }) : null;
|
||
const eu = CHAT_EU.test(question) || !!(doc && /^(?:eurlex|cellar):/.test(doc.id));
|
||
const soft = (ex) => { if (ex.name === 'AbortError') throw ex; return []; };
|
||
// The named act's articles ranked by code; an Insider error there leaves the full-text search below.
|
||
const named = doc && !chatOff(doc) ? chatActArticles(doc, index).then((arts) => chatRankArticles(arts, [...words, ...rw.queries].join(' ')).slice(0, 3)
|
||
.map(({ a }) => ({ act: doc, num: a.num, nth: a.nth, shown: chatSup(a.num), key: `insider:${doc.id}#art-${a.num}:${a.nth}`, part: chatClean(a.text).slice(0, 4000), whole: true }))).catch(soft) : Promise.resolve([]);
|
||
// Insider's full-text index over every act, the question's words ANDed. Run even beside a named act: the
|
||
// model can name the wrong one ("zasiłek rodzinny" → the sickness-benefit act), and this search still finds it.
|
||
const full = chatTopicState(eu).then(async (s) => {
|
||
if (!s.ready) return { st: s, found: [] };
|
||
const r = await askerGet('insider', `search?kind=act&jurisdiction=${eu ? 'eu' : 'pl'}&limit=6&q=` + encodeURIComponent(words.join(' ').slice(0, 300)));
|
||
return { st: s, found: ((r && r.acts) || []).filter((a) => !chatOff(a)).flatMap((a) => ((a.extra || {}).articles || []).filter((x) => x.num).map((x) => ({ a, x })))
|
||
.sort((p, q) => q.x.score - p.x.score).slice(0, 3)
|
||
// label is "94^3" where num is "94³"; one label twice in an act is two articles, in ord order.
|
||
.map(({ a, x }) => ({ act: a, num: x.label || x.num, nth: a.extra.articles.filter((y) => y.label === x.label && y.ord < x.ord).length, shown: x.num,
|
||
key: 'insider:' + a.id + '#' + x.ord, part: chatClean(x.snippet) })) };
|
||
}).catch((ex) => ({ st: { ready: true }, found: soft(ex) }));
|
||
const [mine, { st: st0, found }] = await Promise.all([named, full]);
|
||
// Its best article goes fourth, after the named act's three: in third place it cost topic-set.json one hit
|
||
// (16 → 15, art. 481 k.c.), and no score separated the right act from noise (2026-10-29).
|
||
const extra = found.filter((f) => !mine.some((m) => m.act.id === f.act.id && m.num === f.num && m.nth === f.nth));
|
||
const picked = mine.length ? [...mine, ...extra.slice(0, 1)] : found;
|
||
// An index still building matters only when it was the whole answer.
|
||
const st = mine.length ? { ready: true } : st0;
|
||
const out = [];
|
||
for (const p of picked) {
|
||
const art = await chatArticle(p.act, p.num, p.nth);
|
||
const a = p.act;
|
||
out.push({ slug: 'insider', kind: 'przepis', title: `art. ${p.shown} ${a.title.replace(/\s*\(tekst jednolity\)\s*$/, '')}`, inner: insiderInner(a, art && art.url), url: a.official_url, key: p.key,
|
||
seed: p.whole ? { act: a, num: p.num, nth: p.nth } : null,
|
||
text: `${a.title} (${a.signature}), status aktu: ${a.status}. ` + (art ? `Tekst art. ${p.shown}: ${art.text}`
|
||
: p.whole ? `Tekst art. ${p.shown}: ${p.part}` : `Fragment art. ${p.shown} (urywek z wyszukiwarki, nie cały przepis): ${p.part}`) });
|
||
}
|
||
if (CHAT_CASELAW.test(question)) {
|
||
onStatus('Szukam orzeczeń w SAOS, to może potrwać do pół minuty…');
|
||
out.push(...await chatRulings(chatTopicWords(question)));
|
||
}
|
||
const where = doc ? `tekście aktu ${doc.title}` : eu ? 'tekstach prawa UE (EUR-Lex)' : 'tekstach polskich ustaw (Dziennik Ustaw)';
|
||
if (!st.ready) {
|
||
const got = st.total ? `${st.done} z ${st.total}` : `${st.done}`;
|
||
const note = `Wyszukiwanie przepisów po temacie pytania jest jeszcze budowane w Insiderze: indeks ${eu ? 'prawa UE (EUR-Lex)' : 'polskich ustaw (Dziennik Ustaw)'} nie jest gotowy (pobrano ${got} aktów).`;
|
||
if (!out.length) return { coded: note + ' Podaj konkretny przepis, np. „art. 646 k.c.”, a pobiorę jego tekst.' };
|
||
out.push({ slug: 'insider', kind: 'uwaga', title: 'Insider: indeks przepisów w budowie', inner: null, key: 'insider:uwaga:indeks', text: note });
|
||
}
|
||
if (!out.some((r) => r.kind !== 'uwaga')) return { coded: `W ${where} w Insiderze nie znalazłem przepisu pasującego do pytania. Spróbuj słowami ustawy albo podaj konkretny przepis, np. „art. 646 k.c.”.` };
|
||
return { records: out };
|
||
}
|
||
|
||
/* GraphRAG prawa (testy/czat-prawo/PROJEKT.md, ramię G, domyślnie wyłączone): obok przepisu, który czat już
|
||
pobrał, jego sąsiedztwo w grafie. Krawędzie:
|
||
odesłania z grafu Insidera (graph/references, ze zdaniem cytującym), struktura aktu (sąsiednie artykuły tej
|
||
samej jednostki: Kodeks cywilny odsyła numerami rzadko, 111 krawędzi na 1297 artykułów, więc o obniżeniu kary
|
||
z art. 483 mówi art. 484 obok, nie odesłanie). Kod łączy, model czyta. Klauzule umów (biblioteka Compassu)
|
||
odpadły wraz z umowami w Compassie: rejestr Galeny trzyma metadane umowy, nie jej podział na klauzule. */
|
||
const CHAT_UNIT_HEAD = /\n[\s#]*(?:KSIĘGA|TYTUŁ|DZIAŁ|Rozdział|Oddział)\b/;
|
||
const CHAT_REF_KIND = { ODSYLA_DO: 'odesłanie', STOSUJE_ODPOWIEDNIO: 'stosuje się odpowiednio', Z_ZASTRZEZENIEM: 'z zastrzeżeniem' };
|
||
const chatCaret = (n) => String(n).replace(/[⁰¹²³⁴⁵⁶⁷⁸⁹]+/, (x) => '^' + [...x].map((c) => '⁰¹²³⁴⁵⁶⁷⁸⁹'.indexOf(c)).join(''));
|
||
// The last article with that number: a t.j. opens with the promulgating notice's own Art. 1-4.
|
||
const chatArtAt = (arts, num, nth) => { const same = arts.filter((a) => a.num === num); return nth == null ? same.at(-1) : same.find((a) => a.nth === nth); };
|
||
const chatArtText = (a, n) => `Tekst art. ${chatSup(a.num)}: ${chatClean(a.text).replace(/\n\s*(?:KSIĘGA|TYTUŁ|DZIAŁ|Rozdział|Oddział)\b[\s\S]*$/, '').replace(/\s+/g, ' ').slice(0, n)}`;
|
||
async function chatLawAround(seed, index, shown) {
|
||
const doc = seed.act;
|
||
const arts = await chatActArticles(doc, index);
|
||
const num = chatCaret(seed.num);
|
||
const at = arts.indexOf(chatArtAt(arts, num, seed.nth));
|
||
if (at < 0) return null;
|
||
// Two each way inside the unit: a unit heading ends the text of the article before it.
|
||
const near = [];
|
||
for (let j = at - 1; j >= Math.max(0, at - 2) && !CHAT_UNIT_HEAD.test(arts[j].text); j--) near.unshift(arts[j]);
|
||
for (let j = at + 1; j <= Math.min(arts.length - 1, at + 2) && !CHAT_UNIT_HEAD.test(arts[j - 1].text); j++) near.push(arts[j]);
|
||
const g = await askerGet('insider', `graph/references?act=${encodeURIComponent(chatBare(doc))}&article=${encodeURIComponent(chatSup(num))}&direction=out&depth=1`)
|
||
.catch((ex) => { if (ex.name === 'AbortError') throw ex; return null; });
|
||
const refs = ((g && g.out) || []).filter((e) => e.resolved && e.to && e.to.eli === chatBare(doc)).slice(0, 3);
|
||
const title = doc.title.replace(/\s*\(tekst jednolity\)\s*$/, '');
|
||
const own = chatSup(num);
|
||
const refLines = refs.map((e) => {
|
||
const t = chatArtAt(arts, chatCaret(e.to.num));
|
||
const text = t && !shown.has(t.num) ? ' ' + chatArtText(t, 1500) : '';
|
||
if (t) shown.add(t.num);
|
||
return `Art. ${own} odsyła do art. ${e.to.num} (${CHAT_REF_KIND[e.kind] || e.kind}; zdanie z art. ${own}: „${String(e.context || '').replace(/\s+/g, ' ').trim()}”).` + text;
|
||
});
|
||
const rest = near.filter((a) => !shown.has(a.num));
|
||
rest.forEach((a) => shown.add(a.num));
|
||
return { slug: 'insider', kind: 'przepis', key: `insider:graf:${doc.id}#${num}`, title: `Przepisy powiązane z art. ${own} ${title} (graf przepisów)`,
|
||
inner: insiderInner(doc), url: doc.official_url,
|
||
text: `Przepisy powiązane z art. ${own} ${title} według grafu przepisów w Insiderze (tekst samego art. ${own} jest w osobnym źródle). ` +
|
||
(refLines.length ? refLines.join(' ') : `Art. ${own} nie odsyła numerem do innych przepisów.`) +
|
||
(rest.length ? ` Sąsiednie przepisy z tej samej części aktu: ${rest.map((a) => chatArtText(a, 1500)).join(' ')}` : '') };
|
||
}
|
||
async function chatLawGraph({ law, topic }, index) {
|
||
if (!index.law) return { near: [] };
|
||
const seeds = [...law.filter((r) => r.seed).slice(0, 2), ...topic.filter((r) => r.seed).slice(0, 1)];
|
||
// Articles the model already reads in full are not repeated.
|
||
const shown = new Set(seeds.map((r) => chatCaret(r.seed.num)));
|
||
const near = [];
|
||
for (const r of seeds) near.push(await chatLawAround(r.seed, index, shown));
|
||
return { near: near.filter(Boolean) };
|
||
}
|
||
|
||
// One change of the activity summary in words, by its record's kind and what was done ("umowa" + "dodana do
|
||
// rejestru umów"), as one, few and many.
|
||
const CHAT_DID = { 'umowa dodana do rejestru umów': ['umowa dodana do rejestru', 'umowy dodane do rejestru', 'umów dodanych do rejestru'],
|
||
'sprawa otwarta': ['sprawa otwarta', 'sprawy otwarte', 'spraw otwartych'], 'sprawa zamknięta': ['sprawa zamknięta', 'sprawy zamknięte', 'spraw zamkniętych'],
|
||
'termin wykonany': ['termin wykonany', 'terminy wykonane', 'terminów wykonanych'],
|
||
'zlecenie zlecone': ['zlecenie dla kancelarii zewnętrznej', 'zlecenia dla kancelarii zewnętrznych', 'zleceń dla kancelarii zewnętrznych'],
|
||
'wersja utworzona': ['wersja dokumentu utworzona', 'wersje dokumentów utworzone', 'wersji dokumentów utworzonych'] };
|
||
async function chatIndex() {
|
||
const today = new Date().toLocaleDateString('sv');
|
||
const names = Object.fromEntries(((await askerGet('sygna', 'users')) || []).map((u) => [u.id, u.full_name]));
|
||
// Sygna's urgency summary takes the register's contracts in, so both readers share one fetch.
|
||
const register = chatRegister(today);
|
||
const parts = [['Rejestr umów (Galena)', () => register], ['Sygna (sprawy, terminy, klienci)',
|
||
async () => chatSygna(today, names, ((await register) || []).filter((r) => r.contract).map((r) => r.contract))],
|
||
['Counsel Scorecard (kancelarie zewnętrzne, oceny)', chatCounsel], ['Galena (dokumenty, opinie)', () => chatGalena(names)]];
|
||
const [got, law] = await Promise.all([Promise.all(parts.map(([, read]) => read())), askerGet('insider', 'sources')]);
|
||
const blind = parts.filter((_, i) => got[i] === null).map(([name]) => name);
|
||
// "Do you have access to Insider?" is a question about the chat itself: answered from this record.
|
||
const seen = parts.filter((_, i) => got[i] !== null).map(([name]) => name);
|
||
const access = { slug: 'atrium', kind: 'dostęp', key: 'atrium:dostep', title: 'Dostęp czatu: moduły i dane widoczne na Twoim koncie (Insider, Sygna, Counsel, Galena z rejestrem umów)', inner: null,
|
||
text: `Czat czyta dane na koncie pytającego. Ma dostęp do: ${seen.join(', ') || 'żadnego modułu'}. Nie ma dostępu do: ${blind.join(', ') || 'brak takich modułów'}. ` +
|
||
(law === null ? 'Insider (przepisy i orzeczenia): brak dostępu na tym koncie.'
|
||
: 'Insider (przepisy i orzeczenia): dostęp jest. Czat pobiera tekst przepisu, akt albo orzeczenie, gdy pytanie podaje konkretne odwołanie, np. art. 471 k.c., art. 6 RODO, Dz.U. 2018 poz. 1000, sygnaturę II C 2145/25. Szuka też przepisów po samym temacie pytania.') };
|
||
const records = got.filter(Boolean).flat();
|
||
// "What happened lately" read as "what ends soon" until the dates of what was done were one record.
|
||
|
||
const recent = records.filter((r) => r.at && chatDays(r.at.slice(0, 10), today) >= -7).sort((a, b) => b.at.localeCompare(a.at));
|
||
// Counted per day span and per kind of change: asked about "ostatnie 3 dni", a model answered "nie znalazłem"
|
||
// from the 7-day list; given a bare "zmian 5" beside a sentence naming every kind the summary could hold, Qwen
|
||
// reported closed matters and done deadlines that never happened (9.11).
|
||
const span = (d) => {
|
||
const rs = recent.filter((r) => chatDays(r.at.slice(0, 10), today) >= -d);
|
||
const n = new Map(rs.map((r) => [r.kind + ' ' + r.did, 0]));
|
||
for (const r of rs) n.set(r.kind + ' ' + r.did, n.get(r.kind + ' ' + r.did) + 1);
|
||
const order = [...Object.keys(CHAT_DID).filter((k) => n.has(k)), ...[...n.keys()].filter((k) => !CHAT_DID[k])];
|
||
const what = order.map((k) => (CHAT_DID[k] ? chatPlural(n.get(k), ...CHAT_DID[k]) : `${k}: ${n.get(k)}`)).join(', ');
|
||
return `${d === 1 ? 'W ostatnim dniu' : `W ostatnich ${d} dniach`}: ${rs.length ? `${chatPlural(rs.length, 'zmiana', 'zmiany', 'zmian')}: ${what}` : 'brak zmian, żadnej aktywności'}.`;
|
||
};
|
||
const activity = { slug: 'atrium', kind: 'zestawienie', title: 'Aktywność i zmiany z ostatnich 7 dni (co się działo, ostatnio dodane, wykonane, otwarte)', inner: null,
|
||
key: 'atrium:aktywnosc', members: recent.map((r) => r.key),
|
||
text: `Stan na ${today}, z modułów widocznych na koncie pytającego. ${[1, 3, 7].map(span).join(' ')} ` +
|
||
`Wpisy z ostatnich 7 dni, od najnowszych: ${recent.map((r) => `${r.at.slice(0, 10)}: ${r.title}, ${r.did}`).join('; ') || 'brak'}. ` +
|
||
// The one thing the summary cannot see, kept so "nic się nie zmieniło" is not read off it.
|
||
'Zmian w istniejących wpisach to zestawienie nie pokazuje.' };
|
||
const all = [...records, access, activity];
|
||
// A broken map must not take the chat down: without it every turn answers as before.
|
||
let graph = null;
|
||
try { graph = chatGraph(records, names, today); } catch (ex) { console.warn('chat map off:', ex); }
|
||
return { user: state.user.id, records: all, blind, law: law !== null, byKey: new Map(all.map((r) => [r.key, r])), graph };
|
||
}
|
||
|
||
/* The map of links between the modules' records (testy/czat-graf/PROJEKT.md, B). When a question names a client,
|
||
a counterparty, a matter or a person of the team, code joins their records from Sygna, Galena and
|
||
Counsel, counts them and hands the model one ready "card" to read. Records are joined only by fields with one
|
||
right answer (ids, NIP, a matter's or contract's number, the full name with its legal form); anything less sure
|
||
stays unjoined or is asked about, and the model never sees "possible links". Built once per index, no requests. */
|
||
|
||
// Compass's match_key (the retired Workflow module's services/counterparties.py), ported 1:1: one key for every comparison of names, so the
|
||
// chat links what Compass itself would call the same counterparty, and nothing looser. Parity: test T1.
|
||
const CHAT_FORMS = {
|
||
'sp z o o': ['spolka z ograniczona odpowiedzialnoscia', 'sp z o o', 'sp z oo', 'spzoo', 'spolka z o o'],
|
||
's a': ['spolka akcyjna', 's a'], 'p s a': ['prosta spolka akcyjna', 'p s a'], 's k a': ['spolka komandytowo akcyjna', 's k a'],
|
||
'sp k': ['spolka komandytowa', 'sp k'], 'sp j': ['spolka jawna', 'sp j'], 'sp p': ['spolka partnerska', 'sp p'], 's c': ['spolka cywilna', 's c'] };
|
||
const CHAT_FORM_OF = new Map(Object.entries(CHAT_FORMS).flatMap(([f, vs]) => vs.map((v) => [v, f])));
|
||
const chatWholeWords = (ps) => new RegExp(`(?<!\\S)(?:${ps.map((p) => p.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')).join('|')})(?!\\S)`, 'g');
|
||
const CHAT_FORM_VARIANT = chatWholeWords([...CHAT_FORM_OF.keys()]);
|
||
const CHAT_FORM_ONLY = chatWholeWords([...Object.keys(CHAT_FORMS), 'spolka']);
|
||
const chatFold = (s) => [...String(s || '').toLowerCase().replace(/ß/g, 'ss')]
|
||
.map((ch) => 'ąćęłńóśźż'.includes(ch) ? 'acelnoszz'['ąćęłńóśźż'.indexOf(ch)]
|
||
: ch < '\u0080' || !/\p{Script=Latin}/u.test(ch) ? ch : ch.normalize('NFKD').replace(/\p{M}/gu, '')).join('');
|
||
function chatMatchKey(name) {
|
||
const s = chatFold(name).replace(/[^\p{L}\p{N}]+/gu, ' ').trim().replace(CHAT_FORM_VARIANT, (m) => CHAT_FORM_OF.get(m));
|
||
return s.replace(CHAT_FORM_ONLY, '').trim() ? s : '';
|
||
}
|
||
const CHAT_FORM_KEYS = chatWholeWords(Object.keys(CHAT_FORMS));
|
||
// The name without its legal form: for recognising a name in a question only, never for linking records.
|
||
const chatCoreKey = (key) => key.replace(CHAT_FORM_KEYS, ' ').replace(/\s+/g, ' ').trim();
|
||
const chatHasForm = (key) => key !== chatCoreKey(key);
|
||
const chatFormPart = (key) => (key.match(CHAT_FORM_KEYS) || []).join(' ');
|
||
|
||
// Every linking rule can be switched off on its own: a rule that makes even one false link in the pair test
|
||
// is dropped, not patched for that case (T14). Tests only; the page keeps them all on.
|
||
const CHAT_GRAPH_RULES = new Set(['id', 'nip', 'nazwa', 'nazwa_organizacji', 'nazwa_bez_formy', 'przedstawiciel',
|
||
'k1', 'k2', 'k3', 'numer', 'osoba', 'czesciowe']);
|
||
// How sure a link is: 0 for a field with one right answer, more for a name. A record reached two ways keeps the
|
||
// surer one, and a link derived through two steps is as sure as its weaker step.
|
||
const CHAT_VIA_RANK = { strona: 0, sprawa: 0, klient: 0, termin: 0, k1: 0, k2: 0, numer: 0, osoba: 0, id: 0, nip: 0,
|
||
nazwa: 1, nazwa_organizacji: 1, k3: 1, nazwa_bez_formy: 2, przedstawiciel: 3 };
|
||
const chatWeaker = (a, b) => (CHAT_VIA_RANK[b] > CHAT_VIA_RANK[a] ? b : a);
|
||
const CHAT_VIA_PL = { id: 'ten sam kontrahent z listy kontrahentów', nazwa: 'ta sama nazwa', nazwa_organizacji: 'ta sama nazwa',
|
||
nazwa_bez_formy: 'nazwa bez formy prawnej', przedstawiciel: 'strona umowy wg przedstawicieli' };
|
||
const CHAT_ID_PL = { nip: 'zgodny NIP', krs: 'zgodny KRS', regon: 'zgodny REGON', pesel: 'zgodny PESEL' };
|
||
const CHAT_KIND_MOD = { umowa: 'galena', sprawa: 'sygna', termin: 'sygna', strona: 'sygna', kancelaria: 'counsel', zlecenie: 'counsel',
|
||
projekt: 'galena', wersja: 'galena' };
|
||
|
||
// Another case of the same word: a closed list of Polish endings, never a prefix. A prefix rule made "Kodax"
|
||
// (a firm we do not have) the existing Kodar; an ending list misses an odd form, which only means today's answer.
|
||
const CHAT_ENDINGS = ['a', 'e', 'i', 'o', 'u', 'y', 'em', 'om', 'ie', 'owi', 'ach', 'ami', 'ow', 'iej', 'ej', 'ego', 'emu', 'ym', 'im', 'mi'];
|
||
function chatSameWord(q, n) {
|
||
if (q === n) return true;
|
||
if (q.length < 4 || n.length < 4 || /\d/.test(n)) return false;
|
||
const stems = [n];
|
||
if (/[aeiouy]$/.test(n)) stems.push(n.slice(0, -1)); // zielona → zielon|ej, energia → energi|i
|
||
if (/e[kc]$/.test(n)) stems.push(n.slice(0, -2) + n.slice(-1)); // kaczmarek → kaczmark|a (movable e)
|
||
return stems.some((s) => q.startsWith(s) && CHAT_ENDINGS.includes(q.slice(s.length)));
|
||
}
|
||
// A three-letter first name inflects too ("Ewy Sadowskiej", "Jana Nowaka"), which chatSameWord refuses for a lone
|
||
// short word. Used only for the first word of a person's full name, so the surname still has to match beside it.
|
||
const chatSameFirst = (q, n) => n.length === 3 && [n, /[aeiouy]$/.test(n) ? n.slice(0, -1) : n]
|
||
.some((s) => q.startsWith(s) && CHAT_ENDINGS.includes(q.slice(s.length)));
|
||
|
||
function chatUnion() {
|
||
const up = new Map();
|
||
const find = (x) => { while (up.has(x)) { const y = up.get(x); if (up.has(y)) up.set(x, up.get(y)); x = y; } return x; };
|
||
// The smaller key is the root, so a group's root is its smallest key: the entity's id does not depend on order.
|
||
const join = (a, b) => { const [x, y] = [find(a), find(b)]; if (x !== y) up.set(x < y ? y : x, x < y ? x : y); return x !== y; };
|
||
return { find, join, copy: () => { const u = chatUnion(); for (const [k, v] of up) u.join(k, v); return u; } };
|
||
}
|
||
|
||
// The map over the index's records: carriers of a name (a Sygna party, a contract's listed counterparty, a firm named among
|
||
// a contract's representatives) merged into entities by the rules of B4, then every record tied to its entities.
|
||
function chatGraph(records, names, today) {
|
||
const on = (rule) => CHAT_GRAPH_RULES.has(rule);
|
||
const generic = new RegExp(chatFold(CHAT_PARTY_GENERIC.source), 'u');
|
||
const words = (s) => s.split(' ').filter(Boolean);
|
||
const kinds = (kind, field) => records.filter((r) => r.kind === kind && r[field]);
|
||
const parties = kinds('strona', 'party');
|
||
const matters = kinds('sprawa', 'matter');
|
||
const deadlines = kinds('termin', 'deadline');
|
||
const contracts = kinds('umowa', 'contract');
|
||
const orders = kinds('zlecenie', 'order');
|
||
const projects = kinds('projekt', 'project');
|
||
const drafts = kinds('wersja', 'draft');
|
||
const first = new Set([...Object.values(names), ...parties.filter((r) => r.party.kind === 'person').map((r) => r.party.name)]
|
||
.map((n) => words(chatMatchKey(n))).filter((w) => w.length >= 2).map((w) => w[0]));
|
||
|
||
// ---- carriers ----
|
||
const ID_KINDS = ['nip', 'krs', 'regon', 'pesel'];
|
||
const digits = (x) => String(x ?? '').replace(/\D/g, '');
|
||
const carriers = new Map();
|
||
const carrier = (key, name, type) => {
|
||
let c = carriers.get(key);
|
||
if (!c) carriers.set(key, c = { key, mk: key.startsWith('n:') ? key.slice(2) : chatMatchKey(name), names: [], type, ids: {}, att: [], party: null, list: false });
|
||
if (name && !c.names.includes(name)) c.names.push(name);
|
||
return c;
|
||
};
|
||
const setIds = (c, o) => { for (const t of ID_KINDS) { const v = digits(o[t]); if (v) c.ids[t] = v; } };
|
||
for (const r of parties) {
|
||
const c = carrier('s:' + r.party.id, r.party.name, r.party.kind === 'person' ? 'person' : 'org');
|
||
Object.assign(c, { party: r, organisation: r.party.kind === 'organisation' });
|
||
setIds(c, r.party);
|
||
}
|
||
const typeOf = (k) => (chatHasForm(k) ? 'org' : '?');
|
||
for (const r of contracts) {
|
||
const c = r.contract;
|
||
for (const cp of c.counterparties || []) {
|
||
// With R1 off every listing of a counterparty is its own carrier, so only another rule can join them.
|
||
const x = carrier(on('id') ? 'c:' + cp.id : `c:${cp.id}@${c.id}`, cp.name || '', typeOf(chatMatchKey(cp.name)));
|
||
x.list = true;
|
||
setIds(x, cp);
|
||
x.att.push({ rec: r.key, how: 'lista' });
|
||
}
|
||
// The text names the same counterparty as the contract's own list: the list is the surer carrier. A text
|
||
// carrier beside it was shared by every contract of that name, so two firms of one name and two NIPs met in it.
|
||
const listed = new Set((c.counterparties || []).map((cp) => chatMatchKey(cp.name)).filter(Boolean));
|
||
for (const piece of String(c.counterparty || '').split('; ')) {
|
||
const k = chatMatchKey(piece);
|
||
if (k && !listed.has(k)) carrier('n:' + k, piece.trim(), typeOf(k)).att.push({ rec: r.key, how: 'tekst' });
|
||
}
|
||
if (!on('przedstawiciel')) continue;
|
||
// "Jan Nowicki (Członek Zarządu, Ortolan Logistyka S.A.)": the firm is the last part in the closing brackets,
|
||
// and only a name with a legal form is a firm; the people themselves are never carriers.
|
||
for (const p of c.representatives || []) {
|
||
const m = /\(([^()]*)\)\s*$/.exec(String(p));
|
||
const firm = m ? m[1].split(',').pop().trim() : '';
|
||
const k = firm ? chatMatchKey(firm) : '';
|
||
if (k && chatHasForm(k)) carrier('n:' + k, firm, 'org').att.push({ rec: r.key, how: 'przedstawiciel' });
|
||
}
|
||
}
|
||
// "Anna Zawilska" in a contract is a person when its first word is somebody's first name: names of people
|
||
// repeat far more often than firms', so a person joins only by an identifier.
|
||
for (const c of carriers.values()) {
|
||
const w = words(c.mk);
|
||
if (c.type === '?' && w.length >= 2 && w.length <= 3 && first.has(w[0])) c.type = 'person';
|
||
}
|
||
|
||
// ---- phase 1: exact keys ----
|
||
const keys = [...carriers.keys()].sort();
|
||
const uf = chatUnion();
|
||
const idsOf = new Map(keys.map((k) => [k, Object.fromEntries(ID_KINDS.map((t) => [t, new Set(carriers.get(k).ids[t] ? [carriers.get(k).ids[t]] : [])]))]));
|
||
const clash = (a, b) => ID_KINDS.some((t) => a[t].size && b[t].size && ([...a[t]].some((v) => !b[t].has(v)) || [...b[t]].some((v) => !a[t].has(v))));
|
||
const merges = [];
|
||
const join = (a, b, via, label) => {
|
||
const [ra, rb] = [uf.find(a), uf.find(b)];
|
||
if (ra === rb || clash(idsOf.get(ra), idsOf.get(rb))) return false; // R0: a contrary identifier never joins
|
||
const [A, B] = [idsOf.get(ra), idsOf.get(rb)];
|
||
uf.join(ra, rb);
|
||
idsOf.set(uf.find(ra), Object.fromEntries(ID_KINDS.map((t) => [t, new Set([...A[t], ...B[t]])])));
|
||
merges.push({ a, b, via, label });
|
||
return true;
|
||
};
|
||
if (on('nip')) {
|
||
for (const t of ID_KINDS) {
|
||
const by = new Map();
|
||
for (const k of keys) { const v = carriers.get(k).ids[t]; if (v) by.set(v, [...(by.get(v) || []), k]); }
|
||
for (const ks of by.values()) for (const k of ks.slice(1)) join(ks[0], k, 'nip', CHAT_ID_PL[t]);
|
||
}
|
||
}
|
||
const p1 = new Map(keys.map((k) => [k, uf.find(k)]));
|
||
const p1Ids = new Map([...new Set(p1.values())].map((r) => [r, idsOf.get(r)]));
|
||
const idsAt = (k) => p1Ids.get(p1.get(k));
|
||
|
||
// ---- phase 2: names, candidate edges first ----
|
||
const byMk = new Map();
|
||
for (const k of keys) { const c = carriers.get(k); if (c.mk) byMk.set(c.mk, [...(byMk.get(c.mk) || []), c]); }
|
||
// A name two Sygna parties share links nobody (as chatNamed drops a label two records share).
|
||
const shared = new Set([...byMk].filter(([, cs]) => new Set(cs.filter((c) => c.party).map((c) => p1.get(c.key))).size > 1).map(([mk]) => mk));
|
||
const cand = [];
|
||
for (const [mk, cs] of byMk) {
|
||
if (shared.has(mk)) continue;
|
||
if (on('nazwa') && chatHasForm(mk)) {
|
||
const orgs = cs.filter((c) => c.type === 'org');
|
||
for (const c of orgs.slice(1)) cand.push({ a: orgs[0].key, b: c.key, via: 'nazwa' });
|
||
}
|
||
if (on('nazwa_organizacji') && !chatHasForm(mk) && words(mk).length >= 2) {
|
||
const org = cs.filter((c) => c.party && c.organisation);
|
||
if (org.length === 1) for (const c of cs.filter((x) => x.type === '?')) cand.push({ a: org[0].key, b: c.key, via: 'nazwa_organizacji' });
|
||
}
|
||
}
|
||
const sure = (e) => !clash(idsAt(e.a), idsAt(e.b));
|
||
if (on('nazwa_bez_formy')) {
|
||
// R4 counts the firms a bare name could be after the full names have joined: two carriers of one firm are
|
||
// one candidate, two firms with that core are none.
|
||
const uf2 = uf.copy();
|
||
for (const e of cand.filter(sure)) uf2.join(e.a, e.b);
|
||
const size = new Map();
|
||
for (const k of keys) size.set(uf2.find(k), (size.get(uf2.find(k)) || 0) + 1);
|
||
const formed = new Map();
|
||
for (const c of carriers.values()) {
|
||
if (c.type !== 'org' || !chatHasForm(c.mk)) continue;
|
||
// R5: a firm known only from a contract's representatives joins by R2/R3 alone, so it is no target for a
|
||
// bare name. A group it shares with a real carrier is still found through that one.
|
||
if (!c.party && !c.list && c.att.length && c.att.every((a) => a.how === 'przedstawiciel')) continue;
|
||
const core = chatCoreKey(c.mk);
|
||
if (!formed.has(core)) formed.set(core, new Map());
|
||
if (!formed.get(core).has(uf2.find(c.key))) formed.get(core).set(uf2.find(c.key), c.key);
|
||
}
|
||
for (const c of carriers.values()) {
|
||
// A bare name already joined by name (Fundacja Ostoja, R3b) is not offered to a second firm.
|
||
if (c.type !== '?' || shared.has(c.mk) || size.get(uf2.find(c.key)) > 1) continue;
|
||
const w = words(c.mk);
|
||
if (!(w.length >= 2 || (w[0].length >= 5 && !generic.test(w[0])))) continue;
|
||
const hit = formed.get(c.mk);
|
||
if (hit && hit.size === 1) cand.push({ a: [...hit.values()][0], b: c.key, via: 'nazwa_bez_formy' });
|
||
}
|
||
}
|
||
// A chain A (NIP 1) = B = C (NIP 2) by names: the whole group loses its name edges. It costs missed links, never
|
||
// false ones. The groups are drawn over every candidate, the contrary A = C too, or B would still join A.
|
||
const named = cand.filter(sure);
|
||
const comp = chatUnion();
|
||
for (const e of cand) comp.join(p1.get(e.a), p1.get(e.b));
|
||
const compIds = new Map();
|
||
for (const r of p1Ids.keys()) {
|
||
const c = comp.find(r);
|
||
if (!compIds.has(c)) compIds.set(c, Object.fromEntries(ID_KINDS.map((t) => [t, new Set()])));
|
||
for (const t of ID_KINDS) for (const v of p1Ids.get(r)[t]) compIds.get(c)[t].add(v);
|
||
}
|
||
const broken = (k) => ID_KINDS.some((t) => compIds.get(comp.find(p1.get(k)))[t].size > 1);
|
||
for (const e of named) if (!broken(e.a)) join(e.a, e.b, e.via, CHAT_VIA_PL[e.via]);
|
||
// A text name in a group split by two NIPs may be either firm: each contract keeps a carrier of its own, so the
|
||
// name does not gather both firms' contracts under one entity with no NIP. Such a carrier joined nothing above.
|
||
for (const k of keys.filter((x) => x.startsWith('n:') && broken(x))) {
|
||
const c = carriers.get(k);
|
||
const recs = [...new Set(c.att.map((a) => a.rec))];
|
||
if (recs.length < 2) continue;
|
||
carriers.delete(k);
|
||
keys.splice(keys.indexOf(k), 1);
|
||
for (const rec of recs) {
|
||
const x = { ...c, key: `${k}@${rec}`, att: c.att.filter((a) => a.rec === rec) };
|
||
carriers.set(x.key, x);
|
||
keys.push(x.key);
|
||
}
|
||
}
|
||
|
||
// ---- entities ----
|
||
const ent = new Map();
|
||
const of = new Map();
|
||
const add = (id, key, rule, labels = []) => {
|
||
const e = ent.get(id);
|
||
if (!e) return;
|
||
const had = e.recs.get(key);
|
||
e.recs.set(key, had && CHAT_VIA_RANK[had] <= CHAT_VIA_RANK[rule] ? had : rule);
|
||
const w = e.why.get(key) || [];
|
||
for (const l of labels) if (l && !w.includes(l)) w.push(l);
|
||
e.why.set(key, w);
|
||
e.mods.add(key.split(':')[0]);
|
||
if (!(of.get(key) || []).includes(id)) of.set(key, [...(of.get(key) || []), id]);
|
||
};
|
||
const adj = new Map();
|
||
for (const m of merges) {
|
||
adj.set(m.a, [...(adj.get(m.a) || []), { to: m.b, via: m.via, label: m.label }]);
|
||
adj.set(m.b, [...(adj.get(m.b) || []), { to: m.a, via: m.via, label: m.label }]);
|
||
}
|
||
const groups = new Map();
|
||
for (const k of keys) groups.set(uf.find(k), [...(groups.get(uf.find(k)) || []), carriers.get(k)]);
|
||
const entOfCarrier = new Map();
|
||
for (const [root, cs] of groups) {
|
||
const id = 'podmiot:' + root;
|
||
// Shown by the Sygna party's name, else the contract's counterparty list's, else the longest one written.
|
||
const anchor = cs.find((c) => c.party) || cs.find((c) => c.list) || [...cs].sort((a, b) => b.names[0].length - a.names[0].length)[0];
|
||
const nips = new Set(cs.map((c) => c.ids.nip).filter(Boolean));
|
||
ent.set(id, { id, type: 'podmiot', name: anchor.party ? anchor.party.party.name : anchor.names[0], nip: nips.size === 1 ? [...nips][0] : null,
|
||
rec: anchor.party ? anchor.party.key : null, recs: new Map(), why: new Map(), mods: new Set(), lex: [],
|
||
person: cs.some((c) => c.type === 'person'), forms: new Set(), carriers: cs.map((c) => c.key) });
|
||
for (const c of cs) entOfCarrier.set(c.key, id);
|
||
// How each carrier reached the anchor, the surest way first: an identifier, then a full name, then a bare one.
|
||
const via = new Map([[anchor.key, null]]);
|
||
for (const lim of [0, 1, 2]) {
|
||
const queue = [...via.keys()];
|
||
while (queue.length) {
|
||
const k = queue.shift();
|
||
for (const x of adj.get(k) || []) {
|
||
if (via.has(x.to) || CHAT_VIA_RANK[x.via] > lim) continue;
|
||
const up = via.get(k);
|
||
via.set(x.to, up && CHAT_VIA_RANK[up.via] >= CHAT_VIA_RANK[x.via] ? up : { via: x.via, label: x.label });
|
||
queue.push(x.to);
|
||
}
|
||
}
|
||
}
|
||
const best = new Map();
|
||
for (const c of cs) {
|
||
if (c.party) add(id, c.party.key, 'strona');
|
||
const v = via.get(c.key) || { via: c.list ? 'id' : 'nazwa', label: CHAT_VIA_PL[c.list ? 'id' : 'nazwa'] };
|
||
for (const a of c.att) {
|
||
const w = a.how === 'przedstawiciel' ? { via: 'przedstawiciel', label: CHAT_VIA_PL.przedstawiciel } : v;
|
||
if (!best.has(a.rec) || CHAT_VIA_RANK[w.via] < CHAT_VIA_RANK[best.get(a.rec).via]) best.set(a.rec, w);
|
||
}
|
||
}
|
||
for (const [rec, w] of best) add(id, rec, w.via, [w.label]);
|
||
}
|
||
|
||
// ---- matters, their deadlines, contracts, folders and orders ----
|
||
const partyEnt = new Map(parties.map((r) => [r.party.id, entOfCarrier.get('s:' + r.party.id)]));
|
||
const matterOf = new Map(matters.map((r) => [r.matter.id, r]));
|
||
const projectOf = new Map(projects.map((r) => [r.project.id, r]));
|
||
const sprawa = (r) => 'sprawa:' + r.matter.id;
|
||
const client = (r) => partyEnt.get(r.matter.client_party_id) || null;
|
||
for (const r of matters) {
|
||
ent.set(sprawa(r), { id: sprawa(r), type: 'sprawa', name: `${r.matter.reference} ${r.matter.name}`, nip: null, rec: r.key,
|
||
recs: new Map(), why: new Map(), mods: new Set(), lex: [], person: false, forms: new Set(), client: client(r) });
|
||
add(sprawa(r), r.key, 'sprawa');
|
||
if (client(r)) add(client(r), r.key, 'klient');
|
||
}
|
||
// Both the matter and its client: what belongs to a matter belongs to whoever the matter is for.
|
||
const toMatter = (m, key, rule, labels = []) => { add(sprawa(m), key, rule, labels); if (client(m)) add(client(m), key, rule, labels); };
|
||
for (const r of deadlines) { const m = matterOf.get(r.deadline.matter_id); if (m) toMatter(m, r.key, 'termin'); }
|
||
// K1/K2 to a record the asker cannot see make no link and leave no trace: even "assigned to some matter" tells
|
||
// that the matter exists.
|
||
const contractMatter = new Map();
|
||
if (on('k1')) {
|
||
for (const r of contracts) {
|
||
const m = r.contract.matter_ref && matterOf.get(r.contract.matter_ref);
|
||
if (m) { contractMatter.set(r.key, m.key); toMatter(m, r.key, 'k1', [`umowa przypisana do sprawy ${m.matter.reference}`]); }
|
||
}
|
||
}
|
||
const draftsOf = new Map();
|
||
for (const r of drafts) draftsOf.set(r.projectKey, [...(draftsOf.get(r.projectKey) || []), r]);
|
||
const projMatter = new Map();
|
||
const folder = (m, p, rule, label) => {
|
||
projMatter.set(p.key, { matter: m.key, rule, label });
|
||
for (const x of [p, ...(draftsOf.get(p.key) || [])]) toMatter(m, x.key, rule, [label]);
|
||
};
|
||
const pointed = new Set(matters.map((r) => r.matter.document_node_id).filter(Boolean));
|
||
if (on('k2')) for (const m of matters) { const p = m.matter.document_node_id && projectOf.get(m.matter.document_node_id); if (p) folder(m, p, 'k2', 'teczka wskazana w sprawie'); }
|
||
if (on('k3')) {
|
||
// A folder of the matter's own name, only where the name is the only one of its kind on both sides and
|
||
// neither side has a folder pointed at it: two matters of one name and one folder link nothing.
|
||
const count = (rs, name) => { const n = new Map(); for (const r of rs) { const k = chatMatchKey(name(r)); if (k) n.set(k, [...(n.get(k) || []), r]); } return n; };
|
||
const ms = count(matters, (r) => r.matter.name);
|
||
const ps = count(projects, (r) => r.project.name);
|
||
for (const [k, [m, ...more]] of ms) {
|
||
const [p, ...others] = ps.get(k) || [];
|
||
if (!p || more.length || others.length || m.matter.document_node_id || pointed.has(p.project.id)) continue;
|
||
folder(m, p, 'k3', 'ta sama nazwa');
|
||
}
|
||
}
|
||
const orderTarget = new Map();
|
||
if (on('numer')) {
|
||
const nums = new Map();
|
||
const put = (n, r, label) => { if (n) nums.set(n, [...(nums.get(n) || []), { r, label }]); };
|
||
for (const m of matters) put(m.matter.reference, m, `numer sprawy ${m.matter.reference} w zleceniu`);
|
||
for (const c of contracts) put(c.contract.number, c, `numer umowy ${c.contract.number} w zleceniu`);
|
||
const sigs = matters.filter((m) => String(m.matter.case_signature || '').length >= 6);
|
||
for (const r of orders) {
|
||
const text = `${r.order.title || ''} ${r.order.billing_notes || ''}`;
|
||
const hits = new Map();
|
||
for (const t of text.match(/[\p{L}\p{N}/-]+/gu) || []) for (const h of nums.get(t) || []) hits.set(h.r.key, h);
|
||
for (const m of sigs) {
|
||
if (new RegExp(`(?<![\\p{L}\\p{N}/-])${chatEsc(m.matter.case_signature)}(?![\\p{L}\\p{N}/-])`, 'u').test(text)) hits.set(m.key, { r: m, label: `sygnatura ${m.matter.case_signature} w zleceniu` });
|
||
}
|
||
if (hits.size !== 1) continue;
|
||
const [{ r: to, label }] = hits.values();
|
||
orderTarget.set(r.key, { to: to.key, label });
|
||
if (to.matter) toMatter(to, r.key, 'numer', [label]);
|
||
else for (const id of of.get(to.key) || []) add(id, r.key, chatWeaker('numer', ent.get(id).recs.get(to.key)), [label]);
|
||
}
|
||
}
|
||
if (on('osoba')) {
|
||
const person = (uid, key) => {
|
||
if (!uid || !names[uid]) return;
|
||
const id = 'osoba:' + uid;
|
||
if (!ent.has(id)) ent.set(id, { id, type: 'osoba', name: names[uid], nip: null, rec: null, recs: new Map(), why: new Map(), mods: new Set(), lex: [], person: true, forms: new Set() });
|
||
add(id, key, 'osoba');
|
||
};
|
||
for (const r of matters) person(r.matter.responsible_lawyer_id, r.key);
|
||
for (const r of deadlines) person(r.deadline.owner_id, r.key);
|
||
for (const r of drafts) person(r.draft.author_id, r.key);
|
||
for (const r of orders) person(r.order.matter_owner_id, r.key);
|
||
}
|
||
|
||
// ---- the recognition dictionary ----
|
||
const lex = [];
|
||
const seen = new Set();
|
||
const put = (x) => {
|
||
const k = [x.ent, x.ref || '', x.toks.join(' '), x.form || '', x.full, !!x.exact].join('|');
|
||
if (seen.has(k)) return;
|
||
seen.add(k);
|
||
lex.push(x);
|
||
if (x.full) ent.get(x.ent).lex.push(x);
|
||
};
|
||
for (const e of ent.values()) {
|
||
if (e.type !== 'podmiot') continue;
|
||
const cores = new Set();
|
||
for (const k of e.carriers) {
|
||
for (const n of carriers.get(k).names) {
|
||
const mk = chatMatchKey(n);
|
||
const core = chatCoreKey(mk);
|
||
if (!core) continue;
|
||
cores.add(core);
|
||
if (chatFormPart(mk)) e.forms.add(chatFormPart(mk));
|
||
put({ toks: words(core), ent: e.id, form: chatFormPart(mk) || null, full: true, person: e.person });
|
||
}
|
||
}
|
||
if (e.person || !on('czesciowe')) continue;
|
||
const own = [...cores].flatMap(words);
|
||
for (const core of cores) {
|
||
// Only the first word, the one that tells the firm apart (Velmora, Ortolan). A later one is mostly a common
|
||
// word as well ("Development", "Systems", "Pompy", "Energii"): it gave a law question a firm's card.
|
||
const [w, ...more] = words(core);
|
||
if (w.length >= 5 && !/\d/.test(w) && !generic.test(w) && !first.has(w)) put({ toks: [w], ent: e.id, full: false, own });
|
||
// "Velmorze Pompy": the whole name with its first word in a case the ending list does not know.
|
||
if (more.length && w.length >= 6 && !/\d/.test(w)) put({ toks: [w, ...more], ent: e.id, full: false, loose: true, own });
|
||
}
|
||
}
|
||
for (const [uid, full] of Object.entries(names)) {
|
||
const toks = words(chatMatchKey(full));
|
||
if (ent.has('osoba:' + uid) && toks.length >= 2) put({ toks, ent: 'osoba:' + uid, full: true, person: true });
|
||
}
|
||
const plain = (s) => words(chatFold(s).replace(/[^\p{L}\p{N}]+/gu, ' ').trim());
|
||
for (const r of matters) {
|
||
put({ ref: r.matter.reference, toks: [], ent: sprawa(r), full: true });
|
||
const own = [r.matter.name, ...[...projMatter].filter(([, x]) => x.matter === r.key).map(([p]) => records.find((x) => x.key === p).project.name)];
|
||
for (const n of own) if (plain(n).length >= 2) put({ toks: plain(n), ent: sprawa(r), full: true, exact: true });
|
||
}
|
||
lex.sort((a, b) => b.toks.length - a.toks.length || b.full - a.full);
|
||
|
||
const pairs = [];
|
||
for (const e of ent.values()) if (e.type === 'podmiot') for (const [rec, via] of e.recs) pairs.push({ rec, ent: e.id, via });
|
||
return { ent, of, lex, pairs, merges, first, names, today, carriers, contractMatter, projMatter, orderTarget };
|
||
}
|
||
|
||
// Where the dictionary's entries stand in a text: [{a, b, ents, hit}] over its words. Longest entry first and no
|
||
// overlaps, as chatNamed; entries of the same words at the same place all count (a core two firms share).
|
||
function chatLexSpans(text, entries, graph, { partial = true } = {}) {
|
||
const src = String(text);
|
||
const toks = [...src.matchAll(/[\p{L}\p{N}]+/gu)].map((m, i) => ({ t: chatFold(m[0]), s: m.index, e: m.index + m[0].length,
|
||
cap: /^\p{Lu}/u.test(m[0]), lead: i === 0 || /[.!?]\s*$/.test(src.slice(0, m.index)) }));
|
||
const spans = [];
|
||
const claim = (a, b, ent, hit) => {
|
||
const s = spans.find((x) => x.a === a && x.b === b && x.hit === hit);
|
||
if (s) s.ents.add(ent);
|
||
else if (!spans.some((x) => a < x.b && b > x.a)) spans.push({ a, b, ents: new Set([ent]), hit });
|
||
};
|
||
for (const x of entries) {
|
||
if (!x.ref || !src.includes(x.ref)) continue;
|
||
for (const m of src.matchAll(new RegExp(`(?<![\\p{L}\\p{N}/-])${chatEsc(x.ref)}(?![\\p{L}\\p{N}/-])`, 'gu'))) {
|
||
const a = toks.findIndex((t) => t.e > m.index);
|
||
const b = toks.findIndex((t) => t.s >= m.index + m[0].length);
|
||
claim(a, b < 0 ? toks.length : b, x.ent, 'numer');
|
||
}
|
||
}
|
||
const formAt = (i) => {
|
||
for (let n = 5; n >= 1; n--) {
|
||
const f = i + n <= toks.length && CHAT_FORM_OF.get(toks.slice(i, i + n).map((t) => t.t).join(' '));
|
||
if (f) return { f, n };
|
||
}
|
||
return null;
|
||
};
|
||
// The first word in a case chatSameWord does not know ("velmorze"): all but the last letter, and only with the
|
||
// rest of the name beside it.
|
||
const near = (q, w) => w.length >= 6 && q.startsWith(w.slice(0, -1));
|
||
const fits = (x, i) => x.toks.every((w, k) => {
|
||
const q = toks[i + k];
|
||
if (!q) return false;
|
||
if (x.exact) return q.t === w;
|
||
// A single word of a firm's name counts only written as a name: capitalised and not opening a sentence.
|
||
return (chatSameWord(q.t, w) || (x.person && k === 0 && x.toks.length > 1 && chatSameFirst(q.t, w)) || (x.loose && k === 0 && near(q.t, w)))
|
||
&& (x.full || (q.cap && !q.lead));
|
||
});
|
||
// A capitalised word right beside a partial hit that is not of this firm's name makes another name of it:
|
||
// "Ortolan Cargo", "Kalinowe Wzgórze", "Fundacja Przystań", "w Zielonej Górze" are not our firms.
|
||
const foreign = (x, j) => { const q = toks[j]; return !!q && q.cap && !q.lead && !x.own.some((w) => chatSameWord(q.t, w) || near(q.t, w)); };
|
||
const fullEnts = new Set();
|
||
for (const full of [true, false]) {
|
||
if (!full && !partial) break;
|
||
if (!full) for (const s of spans) for (const id of s.ents) fullEnts.add(id);
|
||
for (const x of entries) {
|
||
if (x.ref || x.full !== full) continue;
|
||
for (let i = 0; i + x.toks.length <= toks.length; i++) {
|
||
if (!fits(x, i)) continue;
|
||
// A full hit wins over partial ones of the same firm; a partial hit of another firm elsewhere still
|
||
// counts, so "Velmora Pompy i Sowiniec" names two firms, not one.
|
||
if (!full && (fullEnts.has(x.ent) || foreign(x, i - 1) || foreign(x, i + x.toks.length))) continue;
|
||
let b = i + x.toks.length;
|
||
// "Miedziak Energia S.A." picks the S.A.; without a form written both firms of that core stay in play.
|
||
const f = full && !x.exact ? formAt(b) : null;
|
||
if (f) {
|
||
if (x.form ? x.form !== f.f : graph.ent.get(x.ent).forms.size) continue;
|
||
b += f.n;
|
||
}
|
||
claim(i, b, x.ent, full ? 'pelne' : 'czesciowe');
|
||
}
|
||
}
|
||
}
|
||
return spans;
|
||
}
|
||
|
||
// The entity a question names, read by the names in the data, never by words for kinds of questions.
|
||
// {root, hit} | {ambiguous: [entId]} | {root: null, why: 'dwie encje'} | null.
|
||
function chatGraphFind(question, index) {
|
||
const g = index.graph;
|
||
if (!g) return null;
|
||
const spans = chatLexSpans(question, g.lex, g);
|
||
if (!spans.length) return null;
|
||
// A matter and its own client named together: the matter, the narrower one.
|
||
const all = new Set(spans.flatMap((s) => [...s.ents]));
|
||
for (const id of all) { const e = g.ent.get(id); if (e.type === 'sprawa' && e.client && all.has(e.client)) for (const s of spans) s.ents.delete(e.client); }
|
||
const live = spans.filter((s) => s.ents.size);
|
||
const sets = [...new Set(live.map((s) => [...s.ents].sort().join('|')))];
|
||
if (sets.length > 1) return { root: null, why: 'dwie encje' };
|
||
const ids = sets[0].split('|');
|
||
// The hit travels with an ambiguous name too: one word alone ("Energii") must not take a question off Insider.
|
||
const hit = live.some((s) => s.hit !== 'czesciowe') ? live.find((s) => s.hit !== 'czesciowe').hit : 'czesciowe';
|
||
return ids.length > 1 ? { ambiguous: ids, hit } : { root: ids[0], hit };
|
||
}
|
||
// Whether a text (a record's title) names the entity in full: the found records that stay beside a card.
|
||
const chatGraphNames = (text, ent, graph) => chatLexSpans(text, ent.lex, graph, { partial: false }).length > 0;
|
||
|
||
// Whether one named record has a link into another module: then it gets a short card of its links.
|
||
function chatLinkable(key, g) {
|
||
const kind = key.split(':')[1];
|
||
if (kind === 'umowa') return g.contractMatter.has(key) || (g.of.get(key) || []).some((id) => [...g.ent.get(id).mods].some((m) => m !== 'galena'));
|
||
if (kind === 'zlecenie') return g.orderTarget.has(key);
|
||
if (kind === 'projekt') return g.projMatter.has(key);
|
||
if (kind === 'wersja') return (g.of.get(key) || []).some((id) => id.startsWith('sprawa:'));
|
||
return false;
|
||
}
|
||
|
||
function chatGraphAsk(ids, index) {
|
||
const g = index.graph;
|
||
const cands = ids.map((id) => g.ent.get(id)).sort((a, b) => a.name.localeCompare(b.name, 'pl')).slice(0, 6);
|
||
const n = (e, prefix) => [...e.recs.keys()].filter((k) => k.startsWith(prefix)).length;
|
||
// One fact per candidate, counted by code: the module where it has the most records.
|
||
const fact = (e) => {
|
||
if (e.type === 'sprawa') { const c = e.client && g.ent.get(e.client); return `Sygna: sprawa${c ? ', klient ' + c.name : ''}`; }
|
||
const opts = [['Sygna', n(e, 'sygna:sprawa:'), (k) => `klient w ${chatPlural(k, 'sprawie', 'sprawach', 'sprawach')}`], ['Galena', n(e, 'galena:umowa:'), chatUmowy],
|
||
['Galena', n(e, 'galena:projekt:'), (k) => chatPlural(k, 'projekt dokumentów', 'projekty dokumentów', 'projektów dokumentów')],
|
||
['Counsel', n(e, 'counsel:zlecenie:'), (k) => chatPlural(k, 'zlecenie', 'zlecenia', 'zleceń')]];
|
||
const best = opts.reduce((a, b) => (b[1] > a[1] ? b : a));
|
||
return best[1] ? `${best[0]}: ${best[2](best[1])}` : e.rec ? 'Sygna: klient bez spraw' : e.type === 'osoba' ? 'osoba z zespołu' : 'bez rekordów';
|
||
};
|
||
// The anchor record of each candidate, so "ta pierwsza" next turn resolves through chatResolveRefs.
|
||
const anchor = (e) => e.rec || [...e.recs.keys()].find((k) => k.startsWith('galena:umowa:')) || null;
|
||
const noun = cands.every((e) => e.type === 'sprawa') ? 'którą sprawę' : cands.every((e) => e.person) ? 'którą osobę' : 'którą firmę';
|
||
// Two candidates of one name: writing the full name again would only bring the same question back.
|
||
const ORD = ['pierwsza', 'druga', 'trzecia', 'czwarta', 'piąta', 'szósta'];
|
||
const tail = new Set(cands.map((e) => e.name)).size < cands.length ? `Napisz, która: ${ORD.slice(0, cands.length).join(', ').replace(/, (?=[^,]*$)/, ' czy ')}.` : 'Napisz pełną nazwę.';
|
||
// `order`: the candidates as shown, so "ta druga" next turn means the second of them (chatTurn).
|
||
return { ask: `O ${noun} chodzi: ${cands.map((e) => `${e.name} (${fact(e)})`).join('; ')}? ${tail}`,
|
||
mentioned: cands.map(anchor).filter(Boolean), why: 'niejednoznaczna nazwa', ambiguous: ids, order: cands.map((e) => e.id) };
|
||
}
|
||
|
||
// The asker speaking of themselves: "co mam na głowie", "moje terminy". Singular only: "mamy" is the firm.
|
||
const CHAT_SELF = /(?<!\p{L})(?:m[oó]j|moj(?:a|e|ą|ego|ej|emu|ich|im|imi)|mnie|mną|mam|prowadz[eę]|odpowiadam)(?!\p{L})/iu;
|
||
|
||
// The plan of a turn: a card of which entity, a card of one record's links, a question back, or nothing (`why`).
|
||
// `ja`: a question in the first person that names nobody gets the asker's own card (testy/czat-graf/RUNDA3.md).
|
||
function chatGraphTurn({ question, index, named = [], resolved = [], back = [], pin = null, ja = false }) {
|
||
const g = index.graph;
|
||
if (!g) return null;
|
||
// `pin`: the candidate the asker picked by its place in the code's own question back ("ta druga").
|
||
if (pin && g.ent.has(pin)) return { root: pin, kind: g.ent.get(pin).type, hit: 'pelne' };
|
||
if (back.length) return { why: 'odwołanie do listy' };
|
||
const entOf = (r) => (r.kind === 'sprawa' ? 'sprawa:' + r.key.split(':').pop()
|
||
: r.kind === 'strona' ? (g.of.get(r.key) || []).find((id) => id.startsWith('podmiot:')) : null);
|
||
const picked = [...named, ...resolved];
|
||
const found = chatGraphFind(question, index);
|
||
if (found && found.ambiguous && !picked.length) return { ...chatGraphAsk(found.ambiguous, index), hit: found.hit };
|
||
if (found && found.why === 'dwie encje') return { why: 'dwie encje' };
|
||
const text = found && found.root ? [found.root] : [];
|
||
let ents = [...new Set([...picked.map(entOf).filter(Boolean), ...text])].filter((id) => g.ent.has(id));
|
||
const narrow = ents.find((id) => g.ent.get(id).type === 'sprawa' && ents.includes(g.ent.get(id).client));
|
||
if (narrow) ents = ents.filter((id) => id !== g.ent.get(narrow).client);
|
||
if (ents.length > 1) return { why: 'dwie encje' };
|
||
const root = ents[0] || null;
|
||
// One-hop gate: a question about one deadline or one contract keeps that record first and gets no entity card.
|
||
// A contract chatByParty found by the entity's own name is no such question.
|
||
const other = picked.filter((r) => r.kind !== 'strona' && r.kind !== 'sprawa');
|
||
const direct = new Set(chatNamed(question, index.records).map(([k]) => k));
|
||
const blocking = other.filter((r) => !(root && !direct.has(r.key) && g.ent.get(root).recs.has(r.key)));
|
||
if (blocking.length) {
|
||
return blocking.length === 1 && other.length === 1 && !ents.length && chatLinkable(blocking[0].key, g) ? { link: blocking[0].key } : { why: 'jednoskokowe' };
|
||
}
|
||
if (!root) {
|
||
// A small firm's owner or manager is often the administrator and does the work too; they ask about themselves.
|
||
const me = ja && !picked.length && CHAT_SELF.test(question) && g.ent.get('osoba:' + index.user);
|
||
if (me && me.recs.size) return { root: me.id, kind: 'osoba', hit: 'pelne', ja: true };
|
||
return { why: found ? 'brak encji' : 'nic w pytaniu' };
|
||
}
|
||
const e = g.ent.get(root);
|
||
// A root from a named record is a full hit; from the text, as sure as the words that found it.
|
||
const hit = picked.map(entOf).includes(root) ? 'pelne' : found.hit;
|
||
if (e.type === 'osoba') return e.recs.size ? { root, kind: 'osoba', hit } : { why: 'jeden moduł' };
|
||
if (e.mods.size >= 2) return { root, kind: e.type, hit };
|
||
// One module only: a card adds something when the question asks for a kind of record the entity has none of
|
||
// ("czy mamy umowę z Fundacją Ostoja") or that the asker cannot see. Only ever a reason for a card, never to refuse.
|
||
const blind = index.blind.map((b) => b.split(' ')[0].toLowerCase());
|
||
const asked = (question.match(/\p{L}+/gu) || []).map((w) => CHAT_KIND_MOD[chatKindOf(chatFold(w))]).filter(Boolean);
|
||
return asked.some((m) => !e.mods.has(m) || blind.includes(m)) ? { root, kind: e.type, hit } : { why: 'jeden moduł' };
|
||
}
|
||
|
||
// ---- the card ----
|
||
const chatCardBlind = (index, slug) => index.blind.some((b) => b.toLowerCase().startsWith(slug));
|
||
// Brackets would read as source marks in the model's prompt.
|
||
const chatNoBrackets = (s) => String(s).replace(/\[/g, '(').replace(/\]/g, ')');
|
||
// Counsel's order status in plain Polish on the full map: Qwen read a raw 'cancelled' order as current (testy/czat-graf/RUNDA7.md).
|
||
const chatOrderStatus = (s) => chatStatus('zlecenie', s);
|
||
// At most 8 items on a line, the rest by their numbers: about 2000 characters in a typical card.
|
||
const chatCap = (items, rest) => items.slice(0, 8).join('; ') + (items.length > 8 ? `; i jeszcze ${items.length - 8}: ${rest.slice(8).join(', ')}` : '');
|
||
function chatCardLines(e, index, today, kind) {
|
||
const g = index.graph;
|
||
const names = g.names;
|
||
const get = (prefix) => [...e.recs.keys()].filter((k) => k.startsWith(prefix)).map((k) => index.byKey.get(k)).filter(Boolean);
|
||
const visible = (kind) => index.records.filter((r) => r.kind === kind).length;
|
||
const why = (r) => (e.why.get(r.key) || []).filter(Boolean);
|
||
// String(): a register row may lack a field (a draft contract without a number); sorting must not throw on it.
|
||
const S = (x) => String(x || '');
|
||
const matters = get('sygna:sprawa:').sort((a, b) => S(a.matter.reference).localeCompare(S(b.matter.reference)));
|
||
const items = new Map(((index.byKey.get('sygna:terminy') || {}).items || []).map((d) => [d.key, d]));
|
||
// The days and groups of the urgency summary itself, so the card and "sygna:terminy" never disagree.
|
||
const dls = get('sygna:termin:').map((r) => items.get(r.key)).filter(Boolean).sort((a, b) => S(a.due_date).localeCompare(S(b.due_date)));
|
||
const contracts = get('galena:umowa:').sort((a, b) => (a.contract.ends_on || '9999').localeCompare(b.contract.ends_on || '9999') || S(a.contract.number).localeCompare(S(b.contract.number)));
|
||
const projects = get('galena:projekt:').sort((a, b) => S(a.project.name).localeCompare(S(b.project.name), 'pl'));
|
||
const versions = get('galena:wersja:').sort((a, b) => S(a.draft.created_at).localeCompare(S(b.draft.created_at)));
|
||
const orders = get('counsel:zlecenie:').sort((a, b) => S(a.order.reference).localeCompare(S(b.order.reference)));
|
||
const late = (d) => `po terminie od ${chatPlural(-d.days_left, 'dnia', 'dni', 'dni')}`;
|
||
const groups = [['PO TERMINIE', 'po terminie', (d) => d.days_left < 0], ['W TYM TYGODNIU', 'w tym tygodniu', (d) => d.days_left >= 0 && d.days_left <= 7],
|
||
['PÓŹNIEJ', 'później', (d) => d.days_left > 7]];
|
||
const out = { lines: [], total: [], lead: [...dls.map((d) => index.byKey.get(d.key)), ...contracts, ...matters, ...projects, ...versions, ...orders].filter(Boolean),
|
||
list: groups.map(([, label, keep]) => ({ label, dates: dls.filter(keep).map((d) => d.due_date) })) };
|
||
const L = (s) => out.lines.push(chatNoBrackets(s));
|
||
// Plural, as the count reads: "2 sprawy w Sygnie (otwarte: 2)".
|
||
const STATUS_PL = { open: 'otwarte', closed: 'zamknięte', suspended: 'zawieszone' };
|
||
const counts = (rs, of) => { const n = new Map(); for (const r of rs) n.set(of(r), (n.get(of(r)) || 0) + 1); return [...n].sort(([a], [b]) => a.localeCompare(b)).map(([k, v]) => `${k}: ${v}`).join(', '); };
|
||
|
||
// Sygna: matters
|
||
const mHead = { podmiot: 'Sygna, sprawy, w których jest klientem', osoba: 'Sygna, sprawy, które prowadzi' }[kind];
|
||
if (mHead) {
|
||
if (chatCardBlind(index, 'sygna')) L('Sygna: brak dostępu na tym koncie, spraw nie widzę.');
|
||
else {
|
||
L(`${mHead} (${matters.length}): ` + (matters.length ? chatCap(matters.map((r) => { const m = r.matter;
|
||
return `${m.reference} „${m.name}”, ${kind === 'osoba' ? `klient ${m.client_name}, ` : ''}status ${chatStatus('sprawa', m.status)}${kind === 'osoba' ? '' : `, ${chatWho(names, m.responsible_lawyer_id, 'prowadzi', 'osoba prowadząca nie wpisana')}`}`; }), matters.map((r) => r.matter.reference))
|
||
: kind === 'osoba' ? `brak, ta osoba nie prowadzi żadnej sprawy widocznej na tym koncie (spraw na koncie: ${visible('sprawa')}).`
|
||
: `brak, ten podmiot nie jest klientem w żadnej sprawie widocznej na tym koncie (sprawę łączy się po stronie Sygny o tym NIP albo pełnej nazwie; spraw na koncie: ${visible('sprawa')}).`) + (matters.length ? '.' : ''));
|
||
out.total.push(`${chatPlural(matters.length, 'sprawa', 'sprawy', 'spraw')} w Sygnie${matters.length ? ` (${counts(matters, (r) => STATUS_PL[r.matter.status] || chatStatus('sprawa', r.matter.status))})` : ''}`);
|
||
}
|
||
}
|
||
// Sygna: deadlines
|
||
if (!chatCardBlind(index, 'sygna')) {
|
||
const head = { podmiot: 'Sygna, terminy niewykonane w tych sprawach', sprawa: 'Sygna, terminy niewykonane w tej sprawie', osoba: 'Sygna, terminy niewykonane, za które odpowiada' }[kind];
|
||
let left = 8;
|
||
const item = (d) => `„${d.title}” ${d.due_date}, ${d.days_left < 0 ? late(d) : 'za ' + d.days_left + ' dni'}, ${CHAT_DEADLINE_SHORT[d.kind] || d.kind}, sprawa ${d.matter_reference}, ${chatWho(names, d.owner_id, 'odpowiada', 'osoba odpowiedzialna nie wpisana')}`;
|
||
L(`${head} (${dls.length})` + (dls.length ? ', od najwcześniejszego: ' + groups.map(([name, , keep]) => {
|
||
const ds = dls.filter(keep);
|
||
const shown = ds.slice(0, Math.max(left, 0));
|
||
left -= shown.length;
|
||
const rest = ds.slice(shown.length);
|
||
return `${name} (${ds.length}): ${shown.map(item).join('; ') || (rest.length ? '' : 'brak')}${rest.length ? `${shown.length ? '; ' : ''}i jeszcze ${rest.length}: ${rest.map((d) => `„${d.title}” ${d.due_date}`).join(', ')}` : ''}`;
|
||
}).join('; ') + '.' : `: ${kind === 'osoba' ? 'brak, ta osoba nie odpowiada za żaden niewykonany termin' : 'brak niewykonanych terminów w ' + (kind === 'sprawa' ? 'tej sprawie' : 'sprawach tego podmiotu')}.`));
|
||
out.total.push(`${chatPlural(dls.length, 'termin niewykonany', 'terminy niewykonane', 'terminów niewykonanych')}${dls.length ? ` (po terminie: ${dls.filter((d) => d.days_left < 0).length})` : ''}`);
|
||
}
|
||
// Galena's contract register
|
||
if (kind === 'osoba') L('Rejestr umów (Galena): umowy nie mają w danych osoby odpowiedzialnej, więc ich tu nie ma.');
|
||
else if (chatCardBlind(index, 'rejestr')) L('Rejestr umów (Galena): brak dostępu na tym koncie, umów nie widzę.');
|
||
else {
|
||
const sums = new Map();
|
||
for (const r of contracts) if (r.contract.value_amount) sums.set(r.contract.value_currency, (sums.get(r.contract.value_currency) || 0) + Number(r.contract.value_amount));
|
||
const item = (r) => {
|
||
const c = r.contract;
|
||
const d = c.ends_on ? chatDays(c.ends_on, today) : 0;
|
||
return `${c.number} „${c.name}”, kontrahent ${c.counterparty || 'nie wpisany'}${why(r).length ? ` (powiązanie: ${why(r).join('; ')})` : ''}, status ${chatStatus('umowa', c.status)}, ` +
|
||
`${c.value_amount ? `wartość ${chatMoney(c.value_amount)} ${c.value_currency}` : 'wartość nie wpisana'}, ${c.ends_on ? `kończy się ${c.ends_on}, ${d >= 0 ? 'za ' + d + ' dni' : -d + ' dni temu'}` : 'data końca nie wpisana'}`;
|
||
};
|
||
const head = kind === 'sprawa' ? 'Rejestr umów (Galena), umowy przypisane do tej sprawy' : 'Rejestr umów (Galena), umowy';
|
||
L(contracts.length ? `${head} (${contracts.length}), łączna wartość ${[...sums].map(([cur, s]) => `${chatMoney(s)} ${cur}`).join(' i ') || 'nieokreślona'}, od najwcześniej kończącej się: ` +
|
||
chatCap(contracts.map(item), contracts.map((r) => r.contract.number)) + '.'
|
||
: `${head} (0): ${kind === 'sprawa' ? 'brak, w rejestrze umów żadna widoczna umowa nie jest przypisana do tej sprawy' : 'brak, żadna widoczna umowa nie jest połączona z tym podmiotem po NIP, numerze sprawy ani pełnej nazwie'} (w rejestrze na tym koncie: ${chatUmowy(visible('umowa'))}).`);
|
||
out.total.push(`${chatUmowy(contracts.length)} w rejestrze umów Galeny${contracts.length ? ` (${counts(contracts, (r) => chatStatus('umowa', r.contract.status))})` : ''}`);
|
||
}
|
||
// Galena
|
||
if (chatCardBlind(index, 'galena')) L('Galena: brak dostępu na tym koncie, dokumentów nie widzę.');
|
||
else {
|
||
const vItem = (r, status) => `„${r.draft.title}”, ${kind === 'osoba' ? `projekt „${(index.byKey.get(r.projectKey) || { project: { name: '?' } }).project.name}”, ` : ''}${status ? `status ${chatStatus('wersja', r.draft.status)}, ` : ''}` +
|
||
`${kind === 'osoba' ? '' : `${chatWho(names, r.draft.author_id, 'autor', 'autor nie wpisany')}, `}utworzona ${r.draft.created_at.slice(0, 10)}`;
|
||
if (kind === 'osoba') {
|
||
L(`Galena, wersje dokumentów, których autorem jest ta osoba (${versions.length}): ` + (versions.length ? chatCap(versions.map((r) => vItem(r, true)), versions.map((r) => `„${r.draft.title}”`)) + '.'
|
||
: `brak, ta osoba nie jest autorem żadnej wersji widocznej na tym koncie (projektów na koncie: ${visible('projekt')}).`));
|
||
out.total.push(chatPlural(versions.length, 'wersja dokumentu w Galenie', 'wersje dokumentów w Galenie', 'wersji dokumentów w Galenie'));
|
||
} else {
|
||
const files = (r) => { const m = /Pliki: (.*)\.$/.exec(r.text); return !m || m[1] === 'brak' ? 0 : m[1].split('; ').length; };
|
||
const pItem = (r) => { const pm = g.projMatter.get(r.key); const m = pm && index.byKey.get(pm.matter);
|
||
return `„${r.project.name}”${m ? `, teczka sprawy ${m.matter.reference} (powiązanie: ${pm.label})` : ''}, plików ${files(r)}`; };
|
||
const open = versions.filter((r) => r.draft.status === 'open');
|
||
const rest = versions.filter((r) => r.draft.status !== 'open');
|
||
const head = kind === 'sprawa' ? 'Galena, teczka sprawy' : 'Galena, projekty dokumentów';
|
||
L(`${head} (${projects.length}): ` + (projects.length ? chatCap(projects.map(pItem), projects.map((r) => `„${r.project.name}”`)) +
|
||
(open.length ? `; wersje czekające na akceptację (${open.length}): ${chatCap(open.map((r) => vItem(r, false)), open.map((r) => `„${r.draft.title}”`))}` : '') +
|
||
(rest.length ? `; pozostałe wersje (${rest.length}): ${chatCap(rest.map((r) => vItem(r, true)), rest.map((r) => `„${r.draft.title}”`))}` : '') + '.'
|
||
: `brak, żadna teczka nie jest wskazana w ${kind === 'sprawa' ? 'tej sprawie' : 'sprawie tego podmiotu'} ani nie nosi nazwy ${kind === 'sprawa' ? 'tej sprawy' : 'jego sprawy'} (projektów na koncie: ${visible('projekt')}).`));
|
||
out.total.push(chatPlural(projects.length, 'projekt dokumentów', 'projekty dokumentów', 'projektów dokumentów') + ' w Galenie');
|
||
}
|
||
}
|
||
// Counsel
|
||
const METHOD = 'Counsel nie zapisuje klienta zlecenia: policzone są tylko zlecenia, których tytuł albo notatka podaje numer sprawy lub umowy tego podmiotu.';
|
||
if (chatCardBlind(index, 'counsel')) L('Counsel: brak dostępu na tym koncie, zleceń nie widzę.');
|
||
else {
|
||
const firm = (o) => ((index.byKey.get('counsel:kancelaria:' + o.firm_id) || {}).firm || {}).name || 'nieznana';
|
||
const item = (r) => { const o = r.order;
|
||
return `${o.reference} „${o.title}”, kancelaria ${firm(o)}, status ${chatOrderStatus(o.status)}, budżet ${o.budget_estimate != null ? `${chatMoney(o.budget_estimate)} ${o.budget_currency}` : 'nie wpisany'}` +
|
||
`${kind === 'osoba' ? '' : `, ${chatWho(names, o.matter_owner_id, 'właściciel zlecenia', 'właściciel zlecenia nie wpisany')}`}${kind !== 'osoba' && why(r).length ? ` (powiązanie: ${why(r).join('; ')})` : ''}`; };
|
||
const head = { podmiot: 'Counsel, zlecenia dla kancelarii zewnętrznych', sprawa: 'Counsel, zlecenia z numerem tej sprawy albo jej umowy', osoba: 'Counsel, zlecenia, których właścicielem jest ta osoba' }[kind];
|
||
let line = `${head} (${orders.length}): ` + (orders.length ? chatCap(orders.map(item), orders.map((r) => r.order.reference)) + '.'
|
||
: kind === 'osoba' ? `brak, ta osoba nie jest właścicielem żadnego zlecenia widocznego na tym koncie (zleceń na koncie: ${visible('zlecenie')}).`
|
||
: `brak, żadne widoczne zlecenie nie podaje numeru ${kind === 'sprawa' ? 'tej sprawy ani jej umowy' : 'sprawy ani umowy tego podmiotu'} (zleceń na koncie: ${visible('zlecenie')}).`);
|
||
if (kind === 'osoba' && orders.length) {
|
||
const sums = new Map();
|
||
for (const r of orders) if (r.order.budget_estimate != null) { const k = `${r.order.budget_currency} ${r.order.status}`; sums.set(k, (sums.get(k) || 0) + Number(r.order.budget_estimate)); }
|
||
line += ` Budżety razem według waluty i statusu: ${[...sums].sort(([a], [b]) => a.localeCompare(b)).map(([k, s]) => { const [cur, st] = k.split(' '); return `${chatMoney(s)} ${cur} (${st})`; }).join(', ')}.`;
|
||
}
|
||
// Name what no order is about, so an order of one matter is not read as an order of the client's other matter.
|
||
if (kind === 'podmiot' && orders.length) {
|
||
const said = orders.map((r) => [r.order.title, ...why(r)].join(' ')).join(' ');
|
||
const bare = [...matters.map((r) => [r.matter.reference, `sprawa ${r.matter.reference} „${r.matter.name}”`]),
|
||
...contracts.map((r) => [r.contract.number, `umowa ${r.contract.number} „${r.contract.name}”`])].filter(([ref]) => ref && !said.includes(ref)).map(([, t]) => t);
|
||
if (bare.length) line += ` Bez żadnego zlecenia: ${bare.join('; ')}.`;
|
||
}
|
||
L(kind === 'osoba' ? line : line + ' ' + (kind === 'sprawa' ? METHOD.replace('tego podmiotu', 'tej sprawy') : METHOD));
|
||
out.total.push(chatPlural(orders.length, 'zlecenie dla kancelarii zewnętrznej', 'zlecenia dla kancelarii zewnętrznych', 'zleceń dla kancelarii zewnętrznych') + ' w Counsel');
|
||
}
|
||
return out;
|
||
}
|
||
|
||
// The card of an entity as one source: {rec, lead, members, names, table}. `rec` is built per turn and stays out
|
||
// of index.records, so search weights, the no-access refusal and chatNamed never see it; it has no `labels`.
|
||
function chatCard(entId, index, today, { table = false, ja = false } = {}) {
|
||
const g = index.graph;
|
||
const e = g.ent.get(entId);
|
||
const names = g.names;
|
||
const parts = chatCardLines(e, index, today, e.type);
|
||
let head;
|
||
let title;
|
||
const made = `Złożona przez system z modułów widocznych na koncie pytającego, stan na ${today}.`;
|
||
if (e.type === 'podmiot') {
|
||
title = 'Karta podmiotu: ' + e.name;
|
||
head = `Karta podmiotu: ${e.name} (NIP ${e.nip || 'nie wpisany'}). ${made} Rekordy połączył kod po identyfikatorach (NIP, numer sprawy, id) i po pełnej nazwie z formą prawną, nie po podobieństwie słów.`;
|
||
} else if (e.type === 'sprawa') {
|
||
const m = index.byKey.get(e.rec).matter;
|
||
title = `Karta sprawy ${m.reference} ${m.name}`;
|
||
head = `Karta sprawy ${m.reference} „${m.name}”: klient ${m.client_name}, status ${chatStatus('sprawa', m.status)}, ${chatWho(names, m.responsible_lawyer_id, 'prowadzi', 'osoba prowadząca nie wpisana')}. ${made} Rekordy połączył kod po numerze sprawy, polach przypisania i pełnej nazwie, nie po podobieństwie słów.`;
|
||
} else {
|
||
title = 'Karta osoby z zespołu: ' + e.name;
|
||
head = `Karta osoby z zespołu: ${e.name}${ja ? ' (to osoba, która pyta)' : ''}. ${made} Rekordy połączył kod po polach przypisania (prowadzi sprawę, odpowiada za termin, autor wersji, właściciel zlecenia), nie po nazwisku.`;
|
||
}
|
||
const lines = [chatNoBrackets(head), chatNoBrackets(`Razem: ${parts.total.join(', ')}.`), ...parts.lines];
|
||
if (e.type === 'sprawa') {
|
||
// The second hop: what else the matter's client has, as numbers only.
|
||
const c = e.client && g.ent.get(e.client);
|
||
if (c) {
|
||
// By number, as in B7c's example: the order the map met them in says nothing to the reader.
|
||
const others = (prefix, num) => [...c.recs.keys()].filter((k) => k.startsWith(prefix) && !e.recs.has(k)).map((k) => index.byKey.get(k)).filter(Boolean)
|
||
.sort((a, b) => String(num(a) || '').localeCompare(String(num(b) || '')));
|
||
const ms = others('sygna:sprawa:', (r) => r.matter.reference);
|
||
const cs = others('galena:umowa:', (r) => r.contract.number);
|
||
const os = others('counsel:zlecenie:', (r) => r.order.reference);
|
||
const list = (rs, num) => (rs.length ? ` (${rs.map(num).join(', ')})` : '');
|
||
lines.push(chatNoBrackets(`Klient tej sprawy, ${c.name}, ma także: ${chatPlural(ms.length, 'inną sprawę', 'inne sprawy', 'innych spraw')}${list(ms, (r) => r.matter.reference)}, ` +
|
||
`${chatPlural(cs.length, 'umowę', 'umowy', 'umów')}${list(cs, (r) => r.contract.number)}, ${chatPlural(os.length, 'inne zlecenie', 'inne zlecenia', 'innych zleceń')}${list(os, (r) => r.order.reference)}.`));
|
||
}
|
||
}
|
||
const members = new Set([...e.recs.keys()].filter((k) => index.byKey.has(k)));
|
||
const rec = { slug: 'atrium', kind: 'karta', key: 'atrium:karta:' + entId, title, inner: null, text: lines.join('\n'), members: [...members], list: parts.list };
|
||
const lead = parts.lead.filter((r) => r.key !== e.rec);
|
||
const out = { rec, lead, members, names: (r) => chatGraphNames(r.title || '', e, g), table: { head: [], rows: [] } };
|
||
if (table) {
|
||
const MOD = { sygna: 'Sygna', galena: 'Galena', counsel: 'Counsel' };
|
||
const items = new Map(((index.byKey.get('sygna:terminy') || {}).items || []).map((d) => [d.key, d]));
|
||
const row = (r) => {
|
||
const why = (e.why.get(r.key) || []).join('; ') || '-';
|
||
if (r.deadline) { const d = items.get(r.key) || r.deadline; return [r.deadline.title, d.due_date, d.days_left < 0 ? `po terminie od ${-d.days_left} dni` : `za ${d.days_left} dni`, why, names[r.deadline.owner_id] || '-']; }
|
||
if (r.contract) return [`${r.contract.number} ${r.contract.name}`, r.contract.ends_on || '-', chatStatus('umowa', r.contract.status), why, '-'];
|
||
if (r.matter) return [`${r.matter.reference} ${r.matter.name}`, r.matter.opened_at || '-', chatStatus('sprawa', r.matter.status), why, names[r.matter.responsible_lawyer_id] || '-'];
|
||
if (r.project) return [r.project.name, '-', '-', why, '-'];
|
||
if (r.draft) return [r.draft.title, r.draft.created_at.slice(0, 10), chatStatus('wersja', r.draft.status), why, names[r.draft.author_id] || '-'];
|
||
return [`${r.order.reference} ${r.order.title}`, '-', chatOrderStatus(r.order.status), why, names[r.order.matter_owner_id] || '-'];
|
||
};
|
||
out.table = { head: ['Lp.', 'Moduł', 'Pozycja', 'Data', 'Stan', 'Powiązanie', 'Odpowiada'],
|
||
rows: lead.map((r, i) => [String(i + 1), MOD[r.slug] || r.slug, ...row(r)]), links: lead.map((r) => (r.inner ? moduleHref(r.slug, r.inner) : '')), linkCol: 2, view: { nowrap: [3] } };
|
||
}
|
||
return out;
|
||
}
|
||
|
||
// The links of one named record (a contract, an order, a folder, a version) as a short source after it: the
|
||
// one-hop question keeps its record first and gets only what code joined to it.
|
||
function chatLinkCard(recKey, index, today) {
|
||
const g = index.graph;
|
||
const r = index.byKey.get(recKey);
|
||
const names = g.names;
|
||
const members = new Set();
|
||
const seen = (x) => { if (x) members.add(x.key); return x; };
|
||
const ents = (key, type) => (g.of.get(key) || []).map((id) => g.ent.get(id)).filter((e) => e.type === type);
|
||
const recsOf = (e, prefix) => [...e.recs.keys()].filter((k) => k.startsWith(prefix)).map((k) => index.byKey.get(k)).filter(Boolean);
|
||
const matter = (m) => `${m.matter.reference} „${m.matter.name}”, status ${chatStatus('sprawa', m.matter.status)}, ${chatWho(names, m.matter.responsible_lawyer_id, 'prowadzi', 'osoba prowadząca nie wpisana')}`;
|
||
const firm = (o) => ((index.byKey.get('counsel:kancelaria:' + o.firm_id) || {}).firm || {}).name || 'nieznana';
|
||
// What a podmiot has besides `except`: its matters, other contracts and orders.
|
||
const about = (e, except) => {
|
||
const ms = recsOf(e, 'sygna:sprawa:').filter((x) => !except.includes(x.key)).map(seen);
|
||
const cs = recsOf(e, 'galena:umowa:').filter((x) => !except.includes(x.key)).map(seen);
|
||
const os = recsOf(e, 'counsel:zlecenie:').filter((x) => !except.includes(x.key)).map(seen);
|
||
const parts = [ms.length ? `jest klientem w ${chatPlural(ms.length, 'sprawie', 'sprawach', 'sprawach')} w Sygnie: ${ms.map(matter).join('; ')}` : 'nie jest klientem w żadnej sprawie widocznej w Sygnie'];
|
||
const more = [];
|
||
if (cs.length) more.push(`${chatPlural(cs.length, 'inną umowę', 'inne umowy', 'innych umów')} (${cs.map((x) => [x.contract.number, ...(e.why.get(x.key) || [])].join(', ')).join('; ')})`);
|
||
if (os.length) more.push(`${chatPlural(os.length, 'zlecenie dla kancelarii zewnętrznej', 'zlecenia dla kancelarii zewnętrznych', 'zleceń dla kancelarii zewnętrznych')} (${os.map((x) => [x.order.reference, firm(x.order), chatOrderStatus(x.order.status), ...(e.why.get(x.key) || []).map((w) => `powiązanie: ${w}`)].join(', ')).join('; ')})`);
|
||
return parts.concat(more.length ? [`ma też ${more.join(' i ')}`] : []).join('; ');
|
||
};
|
||
const contractLinks = (c, except) => {
|
||
const ps = ents(c.key, 'podmiot').sort((a, b) => a.name.localeCompare(b.name, 'pl'));
|
||
const out = ps.map((e) => `kontrahent ${e.name} (powiązanie: ${(e.why.get(c.key) || []).join('; ')}) ${about(e, [c.key, ...except])}`);
|
||
const mk = g.contractMatter.get(c.key);
|
||
// Not assigned is said only when the field is empty: assigned to a matter the asker cannot see leaves no trace.
|
||
if (mk) out.push(`umowa jest przypisana w rejestrze umów do sprawy ${matter(seen(index.byKey.get(mk)))}`);
|
||
else if (!c.contract.matter_ref) out.push('umowa nie jest przypisana do sprawy w rejestrze umów');
|
||
return out;
|
||
};
|
||
const matterLinks = (m, except) => {
|
||
const c = ents(m.key, 'podmiot').find((e) => e.recs.get(m.key) === 'klient');
|
||
return `sprawę ${matter(seen(m))}${c ? `, klient ${c.name}; klient ${about(c, [m.key, ...except])}` : ''}`;
|
||
};
|
||
let title;
|
||
let text;
|
||
if (r.contract) {
|
||
title = 'Powiązania umowy ' + r.contract.number;
|
||
text = `Powiązania umowy ${r.contract.number} ustalone przez system: ${contractLinks(r, []).join('. ')}.`;
|
||
} else if (r.order) {
|
||
const t = g.orderTarget.get(r.key);
|
||
const to = index.byKey.get(t.to);
|
||
title = 'Powiązania zlecenia ' + r.order.reference;
|
||
text = `Powiązania zlecenia ${r.order.reference} ustalone przez system: ${t.label} wskazuje ` + (to.matter ? matterLinks(to, [r.key])
|
||
: `umowę ${seen(to).contract.number} „${to.contract.name}”; ${contractLinks(to, [r.key]).join('; ')}`) + '.';
|
||
} else {
|
||
const p = r.project ? r : index.byKey.get(r.projectKey);
|
||
const pm = g.projMatter.get(p.key);
|
||
title = r.project ? 'Powiązania projektu ' + p.project.name : 'Powiązania wersji ' + r.draft.title;
|
||
text = `Powiązania ${r.project ? 'projektu' : `wersji „${r.draft.title}” w projekcie`} „${p.project.name}” ustalone przez system: projekt jest teczką (powiązanie: ${pm.label}) dla ${matterLinks(index.byKey.get(pm.matter), [p.key])}.`;
|
||
}
|
||
members.delete(r.key);
|
||
const rec = { slug: 'atrium', kind: 'powiązania', key: 'atrium:powiazania:' + recKey, title, inner: null, text: chatNoBrackets(text), members: [...members] };
|
||
return { rec, lead: [], members, names: () => false, table: { head: [], rows: [] } };
|
||
}
|
||
|
||
// What the model is told about the card, appended after the other hints so it switches none of them off.
|
||
function chatCardHint(card, sources, graf) {
|
||
const n = card ? sources.indexOf(card.rec) + 1 : 0;
|
||
if (!n) return '';
|
||
if (card.rec.kind !== 'karta') return `\n(Źródło [${n}] to powiązania tego rekordu ustalone przez system; nie dopisuj innych.)`;
|
||
const lead = graf === 'tabela'
|
||
? `(Źródło [${n}] to karta złożona przez system z kilku modułów. Pod Twoją odpowiedzią pokaże się jako tabela z datami, stanami i powiązaniami, więc jej nie przepisuj. Napisz 1-3 zdania z [${n}]: co jest najważniejsze i co z tego wynika.`
|
||
: `(Źródło [${n}] to karta złożona przez system z kilku modułów: połączenia między rekordami są już ustalone i policzone. Odpowiadaj z karty i podawaj [${n}]; liczby, daty i kwoty przepisuj z niej dosłownie.`;
|
||
return `\n${lead} Nie łącz rekordów sam i nie dopisuj powiązań, których karta nie wymienia. Karta jest odpowiedzią: nie pisz, że nie znalazłeś odpowiedzi. ` +
|
||
// Round 2: at a zero Qwen answered "nie znalazłem odpowiedzi" or a bare "nie", dropping what the card did list.
|
||
'Jeśli pytanie dotyczy czegoś, przy czym karta pisze (0), odpowiedz wprost, że tego nie ma, i dodaj, co karta podaje w pozostałych modułach. Przy „brak dostępu” napisz, że tego modułu nie widać na tym koncie.)';
|
||
}
|
||
|
||
|
||
const chatStems = (s) => new Set((s.toLowerCase().match(/[a-ząćęłńóśźż0-9]+/g) || []).filter((w) => w.length > 2).map((w) => w.slice(0, 5)));
|
||
|
||
// The records are Polish: an English question finds them through the modules' own words.
|
||
// ponytail: a word list, not translation; vectors (bge-m3 in the prototype) once the server builds the index.
|
||
const CHAT_EN = { contr: 'umowa', agree: 'umowa', negot: 'negoc', deadl: 'termi', due: 'termi', firm: 'kance', matte: 'spraw', case: 'spraw',
|
||
expir: 'wygas', value: 'warto', draft: 'szkic', signe: 'podpi', activ: 'obowi', clien: 'klien', ratin: 'ocen', score: 'ocen', opini: 'opini', file: 'plik',
|
||
urgen: 'pilne', task: 'zadan', tasks: 'zadan', week: 'tygod', overd: 'termi' };
|
||
|
||
// Words a question is made of, not about: "jest" is rare in the records (only "w których jest klientem"), so
|
||
// "co jest pilne w tym tygodniu" filled eleven slots with client records.
|
||
const CHAT_SEARCH_STOP = new Set(['jest', 'które', 'która', 'który', 'nich', 'tych', 'trzeb', 'zrobi', 'muszę', 'należ', 'możes', 'dlacz', 'czemu']);
|
||
// Word stems weighted by rarity (idf), doubled in a record's title.
|
||
function chatSearch(records, question) {
|
||
const q = chatStems(question);
|
||
for (const w of q) if (CHAT_SEARCH_STOP.has(w)) q.delete(w);
|
||
for (const w of [...q]) if (CHAT_EN[w]) q.add(CHAT_EN[w]);
|
||
const docs = records.map((r) => chatStems(r.title + ' ' + r.text + ' ' + r.kind));
|
||
const df = new Map();
|
||
for (const d of docs) for (const w of d) df.set(w, (df.get(w) || 0) + 1);
|
||
const scored = records.map((r, i) => {
|
||
const head = chatStems(r.title + ' ' + r.kind);
|
||
let s = 0;
|
||
for (const w of q) if (docs[i].has(w)) s += Math.log(1 + records.length / df.get(w)) * (head.has(w) ? 2 : 1);
|
||
return [r, s];
|
||
});
|
||
const best = scored.filter(([, s]) => s > 0).sort((a, b) => b[1] - a[1]).slice(0, CHAT_TOP);
|
||
// `top`: how well the best record matched, for telling an off-topic request from an uncited answer.
|
||
return Object.assign(best.map(([r]) => r), { top: best.length ? best[0][1] : 0 });
|
||
}
|
||
|
||
// ponytail: a module's keywords, enough for four modules; more modules want a question classifier.
|
||
const CHAT_BLIND_WORDS = {
|
||
'Rejestr umów (Galena)': ['umowa', 'umowy', 'umów', 'umowę', 'umowi', 'kontr', 'contr', 'wygas'],
|
||
'Counsel Scorecard (kancelarie zewnętrzne, oceny)': ['zewnę', 'ocena', 'ocenę', 'oceny', 'ocen', 'ranki', 'score'],
|
||
};
|
||
// What the code answers itself: told the asker had no access, the model still said "there is none".
|
||
function chatRefusal({ records, blind }, question) {
|
||
const q = chatStems(question);
|
||
// Sygna open but no matter visible: "no deadlines this week" was the one false claim Qwen still made.
|
||
if (!blind.some((b) => b.startsWith('Sygna')) && !records.some((r) => r.kind === 'sprawa') && ['termi', 'spraw', 'apela'].some((w) => q.has(w))) {
|
||
return 'Na Twoim koncie nie jest widoczna żadna sprawa w Sygnie, więc nie widzę też ich terminów. O dostęp do spraw poproś osobę, która je prowadzi.';
|
||
}
|
||
const hit = blind.filter((b) => (CHAT_BLIND_WORDS[b] || []).some((w) => q.has(w)));
|
||
// A question naming a visible record (the "Wzory umów" project) stays with the model.
|
||
if (!hit.length || records.some((r) => [...chatStems(r.title)].filter((w) => q.has(w)).length >= 2)) return null;
|
||
return `Nie masz dostępu do modułu ${hit.join(', ')}, więc nie widzę tych danych. O dostęp poproś administratora.`;
|
||
}
|
||
|
||
// Made-up data marked PRZYKŁAD: with realistic names Bielik copied the example contract into a real answer.
|
||
const CHAT_EXAMPLES = [
|
||
['Źródła:\n[1] (PRZYKŁAD, umowa) Umowa PRZYKŁAD-1 „Przykładowy najem”, kontrahent Firma Przykładowa, status obowiązuje, wartość 1,00 PLN.\n' +
|
||
'[2] (PRZYKŁAD, sprawa) Sprawa PRZYKŁAD/0 „Przykładowy spór” dla klienta Klient Przykładowy.\n\nPytanie: Jaką umowę mamy z Firmą Przykładową?',
|
||
'Z Firmą Przykładową mamy umowę „Przykładowy najem” (PRZYKŁAD-1) o wartości 1 PLN [1].'],
|
||
['Źródła:\n[1] (PRZYKŁAD, umowa) Umowa PRZYKŁAD-1 „Przykładowy najem”, kontrahent Firma Przykładowa, status obowiązuje.\n\n' +
|
||
'Pytanie: Ile wynosi kara umowna w umowie z Firmą Przykładową?',
|
||
'W danych, do których masz dostęp, nie znalazłem odpowiedzi.'],
|
||
];
|
||
// `about`: what code resolved a follow-up to ("a ta druga?" → [1]). Without it the bare question gave the
|
||
// model nothing to answer, and it said it found nothing although [1] was the contract.
|
||
function chatMessages(blind, question, sources, history = [], about = [], hint = '') {
|
||
const ctx = sources.map((r, i) => `[${i + 1}] (${r.slug}, ${r.kind}) ${r.text}`).join('\n') || '(brak źródeł)';
|
||
const denied = blind.length ? `Ta osoba nie ma dostępu do: ${blind.join(', ')}. Jeśli pytanie dotyczy tych modułów, powiedz, że nie masz do nich dostępu w jej imieniu.\n\n` : '';
|
||
return [...CHAT_EXAMPLES.flatMap(([u, a]) => [{ role: 'user', content: u }, { role: 'assistant', content: a }]),
|
||
...history, { role: 'user', content: `${denied}Źródła:\n${ctx}\n\nPytanie: ${question}` +
|
||
(about.length ? `\n(W tym pytaniu chodzi o: ${about.join('; ')}.)` : '') + hint }];
|
||
}
|
||
|
||
/* The conversation: what a follow-up refers to is decided in code. A 9B model asked to rewrite "a ta druga?"
|
||
into a full question invents entities and drops negations, and nothing can check it afterwards. So code
|
||
resolves the reference from what the previous answer named (its cited records, and the members of a cited
|
||
list it names by number, title or date), asks back when that is ambiguous, and the model only reads. */
|
||
const CHAT_KINDS = [[/^umow/, 'umowa'], [/^spraw/, 'sprawa'], [/^termin/, 'termin'], [/^kancel/, 'kancelaria'], [/^zleceni/, 'zlecenie'],
|
||
[/^(projekt|dokument)/, 'projekt'], [/^(opini|wersj)/, 'wersja'], [/^(klient|stron|firm)/, 'strona']];
|
||
// Whole inflected forms: a stem also caught "ostatnio" (lately), "piątek" and "czwartek" (weekdays).
|
||
const CHAT_ORDINALS = [[/^pierwsz(y|a|e|ego|ej|emu|ym|ą|ych|ymi)$/, 1], [/^drug(i|a|ie|iego|iej|iemu|im|ą|ich|imi)$/, 2],
|
||
[/^trzeci(a|e|ego|ej|emu|m|ą|ch|mi)?$/, 3], [/^czwart(y|a|e|ego|ej|emu|ym|ą|ych|ymi)$/, 4],
|
||
[/^piąt(y|a|e|ego|ej|emu|ym|ą|ych|ymi)$/, 5], [/^ostatni(a|e|ego|ej|emu|m|ą|ch|mi)?$/, -1]];
|
||
// Accusative, for "O którą umowę chodzi".
|
||
const CHAT_WHICH = { umowa: 'którą umowę', sprawa: 'którą sprawę', termin: 'który termin', kancelaria: 'którą kancelarię',
|
||
zlecenie: 'które zlecenie', projekt: 'który projekt', wersja: 'którą wersję', strona: 'którą firmę' };
|
||
const chatKindOf = (w) => (CHAT_KINDS.find(([re]) => re.test(w)) || [])[1] || null;
|
||
const chatOrdinalOf = (w) => (CHAT_ORDINALS.find(([re]) => re.test(w)) || [])[1] || null;
|
||
|
||
// "w tej umowie", "ten pierwszy termin", "a ta druga?". "to" alone ("co to jest") is no reference: a
|
||
// demonstrative counts only with a kind noun or an ordinal right after it ("w tym tygodniu terminy" is a
|
||
// time, not "this deadline"). "Druga strona" is the counterparty, not the second of anything.
|
||
function chatAnaphora(question) {
|
||
const w = question.toLowerCase().match(/[\p{L}\d]+/gu) || [];
|
||
const ordAt = (i) => (/^drug/.test(w[i] || '') && /^stron/.test(w[i + 1] || '') ? null : chatOrdinalOf(w[i] || ''));
|
||
// `strong`: a pronoun that can only point back ("ta umowa", "w tej sprawie"), unlike a plural "te umowy".
|
||
const out = { kind: null, ordinal: null, demonstrative: false, strong: false };
|
||
w.forEach((x, i) => {
|
||
const ord = ordAt(i);
|
||
// "jakie to umowy", "co to za umowa", "jaka to sprawa": a question word before "to" asks, it does not point.
|
||
if (x === 'to' && /^(jak\p{L}*|co|czym|któr\p{L}*|czyj\p{L}*)$/u.test(w[i - 1] || '')) return;
|
||
if (/^(ten|ta|to|tej|tego|tym|tę|tą|te|tych|tamt\p{L}*|powyższ\p{L}*)$/u.test(x)) {
|
||
const n = ordAt(i + 1);
|
||
const kind = chatKindOf(w[i + (n ? 2 : 1)] || '');
|
||
if (kind || n) Object.assign(out, { demonstrative: true, kind: kind || out.kind, ordinal: n || out.ordinal, strong: out.strong || !/^(to|te|tych)$/.test(x) });
|
||
} else if (ord && !out.ordinal && (chatKindOf(w[i + 1] || '') || w.length <= 3)) {
|
||
Object.assign(out, { ordinal: ord, kind: out.kind || chatKindOf(w[i + 1] || '') });
|
||
}
|
||
});
|
||
return out;
|
||
}
|
||
|
||
// The records a text names, as [key, position] in the order it names them. Longest label first and no
|
||
// overlaps, so "Odpowiedź na sprzeciw" inside "Odpowiedź na sprzeciw od nakazu zapłaty" is not a second
|
||
// deadline; a label two records share (a date, a counterparty) names neither.
|
||
function chatNamed(text, recs) {
|
||
const low = String(text).toLowerCase();
|
||
const owner = new Map();
|
||
for (const r of recs) for (const l of r.labels || []) {
|
||
if (!l || l.length < 4) continue;
|
||
const k = l.toLowerCase();
|
||
owner.set(k, owner.has(k) && owner.get(k) !== r.key ? null : r.key);
|
||
}
|
||
const taken = [];
|
||
const first = new Map();
|
||
for (const [l, key] of [...owner].sort((a, b) => b[0].length - a[0].length)) {
|
||
if (!key) continue;
|
||
for (let i = low.indexOf(l); i >= 0; i = low.indexOf(l, i + 1)) {
|
||
const end = i + l.length;
|
||
// "1 listopada" inside "11 listopada" names nothing.
|
||
if (/[\p{L}\d]/u.test(low[i - 1] || '') || /[\p{L}\d]/u.test(low[end] || '')) continue;
|
||
if (taken.some(([s, e]) => i < e && end > s)) continue;
|
||
taken.push([i, end]);
|
||
if (!first.has(key) || first.get(key) > i) first.set(key, i);
|
||
}
|
||
}
|
||
return [...first].sort((a, b) => a[1] - b[1]);
|
||
}
|
||
|
||
// {keys}: resolved. {ambiguous, kind}: code asks which. {none}: nothing in the conversation to point at.
|
||
function chatResolveRefs(prev, ana, index) {
|
||
const recs = ((prev && prev.mentioned) || []).map((k) => index.byKey.get(k)).filter((r) => r && CHAT_WHICH[r.kind]);
|
||
let kind = ana.kind;
|
||
if (!kind) { // "a ta druga?": the kind the previous answer listed most of
|
||
const n = {};
|
||
for (const r of recs) n[r.kind] = (n[r.kind] || 0) + 1;
|
||
kind = Object.keys(n).sort((a, b) => n[b] - n[a])[0] || null;
|
||
}
|
||
const cands = recs.filter((r) => r.kind === kind);
|
||
if (!cands.length) return { keys: [], none: ana.demonstrative && ['umowa', 'sprawa'].includes(kind), kind };
|
||
if (ana.ordinal) {
|
||
const r = ana.ordinal < 0 ? cands[cands.length - 1] : cands[ana.ordinal - 1];
|
||
// "ta druga" after one record: pinning it would be wrong, and searching the question as new found another
|
||
// record and answered about it (q-ta-druga, 9.11): code says there was only one and asks.
|
||
// Only when the answer named every member of the lists it cited: past them there is a next item to look up.
|
||
const byN = new Map((prev.refs || []).map((x) => [x.n, x.key]));
|
||
const more = chatCitedNs(prev.content || '').map((n) => index.byKey.get(byN.get(n)))
|
||
.some((l) => l && l.members && l.members.some((k) => !(prev.mentioned || []).includes(k)));
|
||
return r ? { keys: [r.key] } : cands.length === 1 ? (more ? { keys: [] } : { keys: [], only: cands[0], kind }) : { keys: [], ambiguous: cands, kind };
|
||
}
|
||
return cands.length === 1 ? { keys: [cands[0].key] } : { keys: [], ambiguous: cands, kind };
|
||
}
|
||
|
||
// Every quotation checked against the fetched text: the n of the source it is in, or null. Stored on the
|
||
// answer, because a restored conversation keeps only the cited sources' text.
|
||
const norm = (s) => String(s).toLowerCase().replace(/[„”"«»]/g, '').replace(/\s+/g, ' ').trim();
|
||
// A quotation is found when its words occur in that order with only their endings changed: "Umowę powierzenia"
|
||
// quotes the source's "Umowa powierzenia" in another case, and an exact match turned a right answer into an
|
||
// error. Each word is whole words only: a word of up to three letters ("nie", "za") and a number exactly, a
|
||
// longer one as its stem (all but its last two letters, at least three) plus at most four letters. A five-letter
|
||
// prefix let "Pracownik" quote "Pracodawca", and an unanchored "n" let an invented "nie" in.
|
||
const chatQuoteRe = (q) => new RegExp('(?<![\\p{L}\\d])' + (norm(q).match(/[\p{L}\d]+/gu) || ['(?!)'])
|
||
.map((w) => (/\d/.test(w) || w === '(?!)' || w.length <= 3 ? chatEsc(w) : chatEsc(w.slice(0, Math.max(3, w.length - 2))) + '\\p{L}{0,4}'))
|
||
.join('[^\\p{L}\\d]+') + '(?![\\p{L}\\d])', 'u');
|
||
// A quotation is what stands between typographic quotes („…”, “…”) only: a straight " opens and closes alike, so
|
||
// the text between two quoted words became a "quotation" and a right English answer was refused (q-negocjacje-en,
|
||
// 0 of 16, 9.11). A verbatim quote in straight quotes goes unchecked; that is the price.
|
||
const CHAT_QUOTE = /[„“]([^„“”"]{12,})”/g;
|
||
const chatQuoteIn = (q) => { const re = chatQuoteRe(q); return (text) => re.test(norm(text)); };
|
||
// Only what the model wrote: the table the system appends repeats every record's name, and those are not quotes.
|
||
// Each quotation once, however often the answer repeats it.
|
||
const chatQuotes = (t) => [...new Set([...(t.table ? t.content.split('\n\n| ')[0] : t.content).matchAll(CHAT_QUOTE)].map((m) => m[1]))]
|
||
.map((q) => {
|
||
const has = chatQuoteIn(q);
|
||
const r = (t.refs || []).find((x) => has(x.text || ''));
|
||
// "Dosłownie" only for the exact words: a match with endings changed says so, not more.
|
||
return { q, n: (r || {}).n || null, exact: !!r && norm(r.text || '').includes(norm(q)) };
|
||
});
|
||
|
||
const chatCitedNs = (text) => [...new Set((String(text).match(/\[\d+(?:\s*,\s*\d+)*\]/g) || []).flatMap((m) => m.match(/\d+/g).map(Number)))];
|
||
|
||
// An answer that cites but says only that it found nothing ("nie znalazłem odpowiedzi [1]"): no value, no record
|
||
// named, and the not-found words chatVerify already reads. Its [n] is no reference: made one, the next "ta umowa"
|
||
// pointed at it (P7, 9.11). Judged on the whole answer: split into sentences, "S.A. [1]" left an empty piece.
|
||
const chatSaysNothing = (text, records) => CHAT_SAYS_NOTHING.test(text)
|
||
&& !chatClaims(String(text).replace(/\[\d+(?:\s*,\s*\d+)*\]/g, ' ')).length && !chatNamed(text, records).length;
|
||
|
||
// The records the previous answer cited come first again: most follow-ups ("ale przecież…") are about them.
|
||
// A law text is not in the index; the ref's kept text stands in for it.
|
||
function chatCarry(prev, index) {
|
||
if (!prev || !prev.refs) return [];
|
||
const byN = new Map(prev.refs.map((r) => [r.n, r]));
|
||
if (chatSaysNothing(prev.content, index.records)) return [];
|
||
return chatCitedNs(prev.content).map((n) => byN.get(n)).filter((r) => r && r.key)
|
||
.map((r) => index.byKey.get(r.key) || (r.text ? { slug: r.slug, kind: r.kind, title: r.title, inner: r.inner, url: r.url, text: r.text, key: r.key } : null))
|
||
.filter(Boolean).slice(0, 4);
|
||
}
|
||
|
||
// The last two exchanges as messages, their [n] renumbered onto this turn's sources (dropped where the record
|
||
// is not among them), so history and sources share one numbering. Failures and code refusals stay out.
|
||
function chatHistory(turns, refs) {
|
||
const at = new Map(refs.map((r) => [r.key, r.n]));
|
||
const pairs = [];
|
||
for (let i = 0; i + 1 < turns.length; i++) {
|
||
const [u, a] = [turns[i], turns[i + 1]];
|
||
if (u.role === 'user' && a.role === 'assistant' && !a.failed && !a.aborted && a.coded !== 'refusal' && !a.status && a.content) pairs.push([u, a]);
|
||
}
|
||
return pairs.slice(-2).flatMap(([u, a]) => {
|
||
const old = new Map((a.refs || []).map((r) => [r.n, r.key]));
|
||
let text = a.content.replace(/\[(\d+(?:\s*,\s*\d+)*)\]/g, (_, ns) => {
|
||
const m = [...new Set(ns.split(',').map((n) => at.get(old.get(Number(n)))).filter(Boolean))];
|
||
return m.length ? '[' + m.join(', ') + ']' : '';
|
||
});
|
||
// Same for provisions: "(art. 168 i art. 169 KPC)" from a deadlines answer was copied into the next turn's
|
||
// contract answer, and the check then failed it. Kept only where this turn's sources hold the article.
|
||
const known = (n) => refs.some((r) => new RegExp(`\\bart\\.\\s*${n}\\b`, 'i').test(r.text || ''));
|
||
text = text.replace(/\s*\([^()]*\bart\.\s*\d+[^()]*\)/gi, (m) => [...m.matchAll(/art\.\s*(\d+)/gi)].every(([, n]) => known(n)) ? m : '');
|
||
if (text.length > 700) { const cut = text.slice(0, 700); text = cut.slice(0, Math.max(cut.lastIndexOf('. '), 400) + 1) + ' …'; }
|
||
return [{ role: 'user', content: u.content }, { role: 'assistant', content: text }];
|
||
});
|
||
}
|
||
|
||
/* The answer checked against its sources in code. The text up to a [n] mark is held to the sources that mark
|
||
cites (text after the last mark, a list under "[1]:", to every source the answer cites). What can be found
|
||
by matching must be there: money and decimals, dates (ISO, "21 października", "30.10.2026", English),
|
||
counts of two digits or more, numbers of five digits or more, record numbers (UM-2026-0017, 2026/0003),
|
||
citations and quotations. Found only in another source of this turn it is weak (⚠: read, cited sloppily),
|
||
in none unsupported (✗). A value from the question counts only as a date bound ("do 2026-11-05") or
|
||
where the answer says it found nothing, so a false premise repeated is still caught. Text after a mark up
|
||
to its sentence's end also has that mark's sources. A provision the review's code verdict does not call
|
||
current, called current (or the other way round), is a wrong verdict. Not checked: negations, comparisons,
|
||
judgements in other words, names; an article number is matched without its act. */
|
||
const CHAT_MONTHS_EN = ['january', 'february', 'march', 'april', 'may', 'june', 'july', 'august', 'september', 'october', 'november', 'december'];
|
||
const CHAT_MON = `(${CHAT_MONTHS.join('|')}|${CHAT_MONTHS_EN.join('|')})`;
|
||
const chatMonth = (w) => (CHAT_MONTHS.indexOf(w.toLowerCase()) + 1) || (CHAT_MONTHS_EN.indexOf(w.toLowerCase()) + 1);
|
||
const chatIso = (y, m, d) => `${y || 'xxxx'}-${String(m).padStart(2, '0')}-${String(d).padStart(2, '0')}`;
|
||
// Each way of writing a date with its ISO form; "xxxx" where the year is left out.
|
||
const CHAT_DATES = [
|
||
[new RegExp(`(?<![\\d.,])(\\d{1,2})(?:st|nd|rd|th)?\\s+${CHAT_MON}(?:,?\\s+(\\d{4}))?(?![\\p{L}\\d])`, 'giu'), (m) => chatIso(m[3], chatMonth(m[2]), m[1])],
|
||
[new RegExp(`(?<![\\p{L}])${CHAT_MON}\\s+(\\d{1,2})(?:st|nd|rd|th)?(?:,?\\s+(\\d{4}))?(?![\\p{L}\\d])`, 'giu'), (m) => chatIso(m[3], chatMonth(m[1]), m[2])],
|
||
[/(?<![\d.])(\d{1,2})\.(\d{1,2})\.(\d{4})(?!\d)/g, (m) => chatIso(m[3], m[2], m[1])],
|
||
[/(?<![\d-])\d{4}-\d{2}-\d{2}(?![\d-])/g, (m) => m[0]],
|
||
];
|
||
// "240 000,00", "240.000,00" and "240000" are one amount; "87.98" (the record) and "87,98" (the answer) one score.
|
||
const chatCanon = (x) => {
|
||
const m = String(x).replace(/\s/g, '').match(/^(.*?)(?:[.,](\d{1,2}))?$/);
|
||
const int = m[1].replace(/[.,]/g, '').replace(/^0+(?=\d)/, '');
|
||
return m[2] && Number(m[2]) ? int + '.' + m[2].padEnd(2, '0') : int;
|
||
};
|
||
const CHAT_NUM = /(?<![\d.,])(?:\d{1,3}(?:[ \u00a0.]\d{3})+(?:,\d{1,2})?|\d+(?:[.,]\d{1,2})?)(?![\d])/g;
|
||
// A source as the checks read it: lower case, one space, dates in ISO form, every number in canonical form.
|
||
function chatFacts(text) {
|
||
let low = String(text || '').toLowerCase().replace(/\s+/g, ' ');
|
||
for (const [re, iso] of CHAT_DATES) low = low.replace(re, (...m) => iso(m));
|
||
return { low, flat: low.replace(/\s/g, ''), quote: norm(text || ''), nums: new Set((String(text || '').match(CHAT_NUM) || []).map(chatCanon)) };
|
||
}
|
||
const chatArtRe = (n) => new RegExp(`(?:^|[^\\p{L}])(?:art(?:ykuł|icle)?\\.?)\\s*${n}(?![\\da-z])`, 'iu');
|
||
// How a source must contain a citation: its article number, a Dz.U. year and item, else the citation itself.
|
||
function chatCiteIn(c) {
|
||
const a = c.match(/(?:^|[^\p{L}])(?:art(?:ykuł|icle)?\.?)\s*(\d+[a-z]?)/iu);
|
||
if (a) { const re = chatArtRe(a[1]); return (f) => re.test(f.low); }
|
||
const dz = c.match(/(\d{4})\D{0,12}?poz\.\s*(\d+)/i);
|
||
if (dz) { const re = new RegExp(`${dz[1]}\\D{0,15}poz\\.?\\s*${dz[2]}(?!\\d)`); return (f) => re.test(f.low); }
|
||
const k = c.toLowerCase().replace(/\s+/g, '');
|
||
return (f) => f.flat.includes(k);
|
||
}
|
||
// The checkable claims of one piece of the answer. Each kind is cut out before the next is looked for, so the
|
||
// "10" of a date is no count and the "2026" of "UM-2026-0017" no year.
|
||
function chatClaims(piece) {
|
||
let s = String(piece);
|
||
const out = [];
|
||
const take = (re, claim) => { s = s.replace(re, (...m) => { const c = claim(m); if (c) out.push({ raw: m[0].trim(), ...c }); return ' '.repeat(m[0].length); }); };
|
||
take(CHAT_QUOTE, (m) => { const re = chatQuoteRe(m[1]); return { kind: 'cytat', in: (f) => re.test(f.quote) }; });
|
||
for (const re of CHAT_CITES) take(re, (m) => ({ kind: 'przepis', in: chatCiteIn(m[0]) }));
|
||
take(/(?:^|[^\p{L}])(?:art(?:ykuł|icle)?\.?)\s*\d+[a-z]?(?![\da-z])/giu, (m) => ({ kind: 'przepis', in: chatCiteIn(m[0]) }));
|
||
// A contract's "§ 7 pkt 2" must stand in a source: the model made one up for a deadline (verify: []).
|
||
// "§ 1 pkt 1" stands in a statute as "§ 1." and below it "1)": the point counts as "pkt 1" or "1)" after its
|
||
// paragraph and before the next one (law-kp-zwolnienie-lekarskie: a right answer refused).
|
||
take(/§\s*(\d+[a-z]?)(?:\s*(ust\.|pkt)\s*(\d+))?(?![\da-z])/giu, (m) => {
|
||
const re = /pkt/i.test(m[2] || '') ? new RegExp(`§${chatEsc(m[1].toLowerCase())}(?![\\da-z])[^§]*?(?:pkt${m[3]}(?!\\d)|(?<![\\d.])${m[3]}\\))`)
|
||
: new RegExp(chatEsc(m[0].toLowerCase().replace(/\s+/g, '')) + '(?!\\d)');
|
||
return { kind: 'paragraf', in: (f) => re.test(f.flat) };
|
||
});
|
||
take(/(?<![\p{L}\d-])\p{Lu}{1,6}-\d{2,4}-\d{2,6}(?![\d-])/gu, (m) => ({ kind: 'numer', in: (f) => f.low.includes(m[0].toLowerCase()) }));
|
||
// Not "(UE) 2016/679": a regulation's number is a citation's business, and checked with it. Not "2025/2026",
|
||
// a span of years.
|
||
take(/(?<!\((?:UE|WE|EU|EC)\)\s?|nr\s|rozporządzeni\p{L}*\s|regulation\s|[\d/])\d{4}\/(?!(?:19|20)\d\d(?![\d/]))\d{2,5}(?![\d/])/giu, (m) => ({ kind: 'numer', in: (f) => f.low.includes(m[0]) }));
|
||
for (const [re, iso] of CHAT_DATES) {
|
||
take(re, (m) => {
|
||
// "clause 7 may apply": a lower-case "may" with no year is the verb.
|
||
if (/may/.test(m[0]) && !/\d{4}$/.test(m[0])) return null;
|
||
const k = iso(m);
|
||
return { kind: 'data', in: k.startsWith('xxxx') ? (f) => f.low.includes(k.slice(4)) : (f) => f.low.includes(k) || f.low.includes('xxxx' + k.slice(4)) };
|
||
});
|
||
}
|
||
// replace() passes the offset where a group would be: the count's number is its group, the others the match.
|
||
const num = (g) => (m) => { const k = chatCanon(m[g]); return { kind: 'liczba', in: (f) => f.nums.has(k) }; };
|
||
take(/(?<![\d.,])(?:\d{1,3}(?:[ \u00a0.]\d{3})+(?:,\d{1,2})?|\d+[.,]\d{1,2}|\d+(?=\s*(?:PLN|EUR|USD|GBP|CHF|zł|złotych|euro)(?![\p{L}])))(?![\d])/giu, num(0));
|
||
take(/(?<![\d.,])(\d{2,})\s+(?:dni|dnia|umów|umowy|spraw|sprawy|pkt|punktów|terminów|terminy|kancelarii|plików|days|contracts|agreements|matters|cases|deadlines|points|firms|files)(?![\p{L}])/giu, num(1));
|
||
take(/(?<![\d.,/-])\d{5,}(?![\d.,/-])/g, num(0));
|
||
return out;
|
||
}
|
||
// "Nothing found" in an answer's words; with CHAT_SAYS_UNSURE, what chatVerify reads as a refusal's piece.
|
||
const CHAT_SAYS_NOTHING = /nie\s+znalaz|nie\s+ma\b|brak\b|nie\s+(?:istnieje|występuje)|did\s+not\s+find|no\s+such|not\s+found/iu;
|
||
const CHAT_SAYS_UNSURE = /nie\s+sprawdz|niesprawdz|nie\s+(?:udało|można|da\s+się)|nie\s+rozpozna|nie\s+wiadomo|not\s+checked|could\s+not|unknown/iu;
|
||
const CHAT_SAYS_KEPT = /nie\s+(?:jest\s+|został\s+)?(?:uchylon|skreślon)|not\s+(?:been\s+)?repealed/iu;
|
||
const CHAT_SAYS_OFF = /nieaktualn|nieobowiązuj|nie\s+(?:jest\s+)?(?:już\s+)?(?:aktualn|obowiązuj)|uchylon|utracił|skreślon|nie\s+(?:występuje|istnieje)|nie\s+ma\s+(?:\S+\s+){0,3}w\s+(?:obecnym|obowiązującym|aktualnym)|no\s+longer|not\s+(?:current|in\s+force|valid)|repealed|outdated/iu;
|
||
const CHAT_SAYS_ON = /aktualn|obowiązuj|\bcurrent\b|in\s+force|\bvalid\b/iu;
|
||
// "Wszystkie poza art. 442 są aktualne" says the opposite of what stands next to the article.
|
||
const CHAT_SAYS_EXCEPT = /(?:^|[^\p{L}])(?:poza|oprócz|z\s+wyjątkiem|except|apart\s+from|other\s+than)(?![\p{L}])/iu;
|
||
const chatSays = (s) => (CHAT_SAYS_KEPT.test(s) ? true : CHAT_SAYS_OFF.test(s) ? false : CHAT_SAYS_ON.test(s) ? true : null);
|
||
const chatEsc = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
||
// The review's verdicts against what the answer says of each provision: the words from its mention to the
|
||
// next provision's, else those before it, so "118 jest aktualny, a 442 uchylony" gives each its own.
|
||
function chatVerdicts(text, review) {
|
||
const out = [];
|
||
const rows = review.rows.filter((r) => !/, cały akt$/.test(r.label)).map((r) => {
|
||
const a = r.label.match(/(?:^|[^\p{L}])art(?:ykuł|\.)?\s*(\d+[a-z]?)/iu);
|
||
const p = r.label.match(/poz\.\s*(\d+)/i);
|
||
return { r, flat: r.label.toLowerCase().replace(/\s+/g, ''), re: a ? chatArtRe(a[1]) : p ? new RegExp(`poz\\.?\\s*${p[1]}(?!\\d)`, 'i') : null };
|
||
});
|
||
for (const clause of String(text).split(/\n|;|(?<=[.!?])\s+(?=[*•\-\p{Lu}])/u)) {
|
||
if (CHAT_SAYS_UNSURE.test(clause) || CHAT_SAYS_EXCEPT.test(clause)) continue;
|
||
// An article number two cited acts share ("art. 28" of RODO and of DSA) names neither without its act.
|
||
const at = rows.map((x) => {
|
||
const m = clause.match(new RegExp(chatEsc(x.r.label).replace(/\s+/g, '\\s*'), 'iu'))
|
||
|| (x.re && rows.filter((y) => y.re && String(y.re) === String(x.re)).length === 1 && clause.match(x.re));
|
||
return m ? { x, i: m.index, end: m.index + m[0].length } : null;
|
||
}).filter(Boolean).sort((a, b) => a.i - b.i);
|
||
at.forEach(({ x, end }, k) => {
|
||
const says = chatSays(clause.slice(end, k + 1 < at.length ? at[k + 1].i : undefined)) ?? chatSays(clause.slice(k ? at[k - 1].end : 0, at[k].i));
|
||
if (says !== null && says !== (x.r.ok === true)) out.push({ kind: 'ocena', raw: x.r.label, level: 'bad', verdict: x.r.verdict });
|
||
});
|
||
}
|
||
return out;
|
||
}
|
||
const CHAT_ASKS_TOTAL = /(?:^|[^\p{L}])(?:ile|łączn\p{L}*|sum\p{L}*|razem|ogółem|how\s+many|total|count)(?![\p{L}])/iu;
|
||
const CHAT_SAYS_WEEK = /w\s+tym\s+tygodniu|na\s+ten\s+tydzień|w\s+bieżącym\s+tygodniu|this\s+week/iu;
|
||
const CHAT_SAYS_LATE = /po\s+terminie|przekroczon|zaległ|minął|minęł|upłynął|upłynęł|overdue|past\s+due|missed/iu;
|
||
const CHAT_GROUP_DENIED = /(?<![\p{L}])(?:nie|not|no|none|brak\p{L}*|żadn\p{L}*|dopiero)(?![\p{L}])/iu;
|
||
// A deadline's date said to be "w tym tygodniu" (or "po terminie") must be in that group of the grouped list it
|
||
// came from: models moved overdue deadlines into this week. A list item under a "W tym tygodniu:" line says what
|
||
// the line says, unless it says otherwise itself; a line saying both groups, or "najpilniejsze", decides nothing.
|
||
function chatGroupIssues(text, sources, pieces) {
|
||
const groups = sources.flatMap((r) => r.list || []).filter((g) => g.dates && g.label);
|
||
if (!groups.length) return [];
|
||
// A group named with a negation or "dopiero" a few words either side is denied, not claimed: "W tym tygodniu
|
||
// nie masz terminów, najbliższy dopiero 12 listopada" and "12 listopada, czyli nie w tym tygodniu" are right.
|
||
const denied = (s, re) => { const m = s.match(re); return !!m && CHAT_GROUP_DENIED.test(s.slice(Math.max(0, m.index - 30), m.index + m[0].length + 30)); };
|
||
const label = (s) => {
|
||
const w = CHAT_SAYS_WEEK.test(s) && !denied(s, CHAT_SAYS_WEEK);
|
||
const l = CHAT_SAYS_LATE.test(s) && !denied(s, CHAT_SAYS_LATE);
|
||
return w === l ? null : w ? 'w tym tygodniu' : 'po terminie';
|
||
};
|
||
const pieceAt = (pos) => { for (let i = 0, o = 0; i < pieces.length; o += pieces[i].length, i++) if (pos < o + pieces[i].length) return i - (i % 2); return 0; };
|
||
const out = [];
|
||
let ctx = null;
|
||
let cur = 0;
|
||
for (const line of String(text).split('\n')) {
|
||
const item = /^\s*(?:[*•-]|\d+[.)])\s/.test(line);
|
||
if (!item && line.trim()) ctx = /:\s*$/.test(line) && !/piln|urgent/i.test(line) ? label(line) : null;
|
||
for (const seg of line.split(/;|(?<=[.!?])\s+/)) {
|
||
const at = text.indexOf(seg, cur);
|
||
cur = at + seg.length;
|
||
const both = CHAT_SAYS_WEEK.test(seg) && CHAT_SAYS_LATE.test(seg);
|
||
const says = both ? null : label(seg) || (item ? ctx : null);
|
||
if (!says) continue;
|
||
for (const [re, iso] of CHAT_DATES) {
|
||
for (const m of seg.matchAll(re)) {
|
||
const k = iso(m);
|
||
const has = (g) => g.dates.some((d) => d === k || 'xxxx' + d.slice(4) === k);
|
||
if (groups.some(has) && !groups.some((g) => g.label === says && has(g))) {
|
||
out.push({ kind: 'grupa', raw: m[0], level: 'bad', at: pieceAt(at + m.index), says });
|
||
}
|
||
}
|
||
}
|
||
}
|
||
}
|
||
return out;
|
||
}
|
||
// {hard, issues, retry}: hard = a [n] it was not given, an unsupported record number, citation or quotation, a
|
||
// wrong verdict, a date put in the wrong group, a wrong headline total, or two unsupported numbers or dates.
|
||
// One unsupported number elsewhere is shown marked, not refused.
|
||
function chatVerify(text, sources, { question = '', review = null, today = new Date().toLocaleDateString('sv') } = {}) {
|
||
const facts = sources.map((r) => chatFacts(r.text));
|
||
const asked = chatFacts(question);
|
||
// Today's date is the answer's frame, not a fact from a source: "Na dziś, 9 listopada" was refused (followup-urgent-owner).
|
||
const now = chatFacts(today);
|
||
const known = (n) => n >= 1 && n <= sources.length;
|
||
const issues = [...new Set(chatCitedNs(text).filter((n) => !known(n)))].map((n) => ({ kind: 'źródło', raw: `[${n}]`, level: 'bad' }));
|
||
const cited = chatCitedNs(text).filter(known);
|
||
const pieces = String(text).split(/(\[\d+(?:\s*,\s*\d+)*\])/); // as renderCited splits, so `at` is its piece
|
||
for (let i = 0; i < pieces.length; i += 2) {
|
||
const marks = pieces[i + 1] ? pieces[i + 1].match(/\d+/g).map(Number).filter(known) : [];
|
||
const own = (marks.length ? marks : cited.length ? cited : sources.map((_, j) => j + 1)).map((n) => facts[n - 1]);
|
||
// "Umowa X [1] kończy się 2 listopada": up to its sentence's end the piece is still [1]'s sentence.
|
||
const head = i ? pieces[i].split(/[.!?](?=\s|$)|\n/)[0] : '';
|
||
const prev = i ? pieces[i - 1].match(/\d+/g).map(Number).filter(known).map((n) => facts[n - 1]) : [];
|
||
const nothing = CHAT_SAYS_UNSURE.test(pieces[i]) || CHAT_SAYS_NOTHING.test(pieces[i]);
|
||
for (const c of chatClaims(pieces[i])) {
|
||
const before = pieces[i].slice(0, pieces[i].indexOf(c.raw));
|
||
// ponytail: frame words listed; a frame in other words is checked as any date
|
||
const frame = c.kind === 'data' && c.in(now) && /(?:na\s+dzi[śs]|na\s+dzie[ńn]|stan\s+na|dzisiaj|today|as\s+of)(?![\p{L}])[^.\n]{0,40}$/iu.test(before);
|
||
const echo = frame || (c.in(asked) && (nothing || (c.kind === 'data' && /(?:^|[^\p{L}])(?:do|przed|po|od|until|before|after|since|by)\s+(?:dnia\s+)?$/iu.test(before))));
|
||
const level = echo || own.some(c.in) || (head.includes(c.raw) && prev.some(c.in)) ? null : facts.some(c.in) ? 'weak' : 'bad';
|
||
if (level && !issues.some((x) => x.raw === c.raw && x.at === i)) issues.push({ kind: c.kind, raw: c.raw, level, at: i });
|
||
}
|
||
}
|
||
if (review) issues.push(...chatVerdicts(text, review));
|
||
issues.push(...chatGroupIssues(text, sources, pieces));
|
||
const bad = issues.filter((x) => x.level === 'bad');
|
||
// The total a question asks for, stated in the answer's first sentence, is the answer: wrong, it is retried.
|
||
const first = String(text).split(/(?<=[.!?])\s|\n/)[0];
|
||
// A one-digit count ("4 umowy") is no claim chatClaims checks (a digit is in every date and record number),
|
||
// so a wrong small total went through unmarked. In the first sentence of an answer to "ile", it must stand
|
||
// alone in a used source ("3 umowy", "(3)"), not inside "UM-2026-0004".
|
||
if (CHAT_ASKS_TOTAL.test(question)) {
|
||
const scope = (cited.length ? cited : sources.map((_, j) => j + 1)).map((n) => facts[n - 1]);
|
||
for (const m of first.matchAll(/(?<![\d.,/-])(\d)\s+(?:umów|umow\p{L}*|spraw\p{L}*|termin\p{L}*|kancelari\p{L}*|plik\p{L}*|dokument\p{L}*|pozycj\p{L}*|contracts?|agreements?|matters?|cases?|deadlines?|firms?|files?|documents?|items?)(?![\p{L}])/giu)) {
|
||
const re = new RegExp(`(?<![\\d.,/-])${m[1]}(?![\\d.,/-])`);
|
||
if (!scope.some((f) => re.test(f.low)) && !issues.some((x) => x.raw === m[0])) {
|
||
const x = { kind: 'liczba', raw: m[0], level: 'bad', at: 0 };
|
||
issues.push(x);
|
||
bad.push(x);
|
||
}
|
||
}
|
||
}
|
||
// By place, not substring: "500" said in sentence two is not the "241 500,00" of sentence one.
|
||
const inFirst = (raw) => new RegExp(`(?<![\\d.,]|\\d[ \\u00a0])${chatEsc(raw)}(?![\\d]|[.,]\\d|[ \\u00a0]\\d{3}(?!\\d))`).test(first);
|
||
const headline = CHAT_ASKS_TOTAL.test(question) && bad.some((x) => x.kind === 'liczba' && inFirst(x.raw));
|
||
const hard = headline || bad.some((x) => !['data', 'liczba'].includes(x.kind)) || new Set(bad.map((x) => x.raw)).size >= 2;
|
||
const said = [...new Set(bad.map((x) => (x.kind === 'ocena' ? `ocena ${x.raw} (w przeglądzie: ${x.verdict})` : x.kind === 'grupa' ? `${x.raw} opisany jako „${x.says}” (w źródle jest w innej grupie)` : x.raw)))];
|
||
return { hard, issues, retry: hard ? `W odpowiedzi są: ${said.join(', ')}, których nie ma w źródłach albo które się z nimi nie zgadzają. Odpowiedz ponownie tylko ze źródeł.` : '' };
|
||
}
|
||
|
||
// A refusal that is itself the sentence to show (`model_busy`: the running model and who may switch it;
|
||
// a missing or unreadable personal key: where to add it). Not named chatRefusal: that is the coded no-access
|
||
// answer above, and a second declaration silently replaced it (every question answered "Error", 2026-11-06).
|
||
const CHAT_REFUSALS = new Set(['model_busy', 'model_provider_user_key_missing', 'model_provider_user_key_unreadable']);
|
||
function chatBusy(problem) {
|
||
const err = new Error(coreRefusal(problem) || problem.detail || problem.error);
|
||
err.refusal = true;
|
||
return err;
|
||
}
|
||
const chatFailure = (ex) => (ex.refusal ? ex.message : _tr('Nie udało się: ') + ex.message);
|
||
|
||
// One model call, streamed: `onUpdate` sees the text so far. No thinking and a low temperature: the answer is
|
||
// read off the sources, and thinking took ~29 s where the answer itself took 1 (Qwen 3.5 9B, 2026-10-29).
|
||
// A connection broken before the first word ("TypeError: terminated") is no answer of the model: asked once
|
||
// more, as a person did by hand (9.11). Not after words came (they would be shown twice), not on a stop.
|
||
async function chatRound(model, messages, answer, onUpdate, opts = {}) {
|
||
const before = answer.content;
|
||
try { return await chatStream(model, messages, answer, onUpdate, opts); } catch (ex) {
|
||
if (!(ex instanceof TypeError) || answer.content !== before || (opts.signal || chat.ctl.signal).aborted) throw ex;
|
||
return chatStream(model, messages, answer, onUpdate, opts);
|
||
}
|
||
}
|
||
async function chatStream(model, messages, answer, onUpdate, { signal = chat.ctl.signal, ...knobs } = {}) {
|
||
const res = await fetch(new URL('api/v1/models/ask', document.baseURI), {
|
||
method: 'POST', credentials: 'same-origin', signal,
|
||
headers: { 'Content-Type': 'application/json', Accept: 'text/event-stream' },
|
||
body: JSON.stringify({ model, messages, thinking: false, temperature: 0.2, ...knobs }),
|
||
});
|
||
if (!res.ok) {
|
||
let detail = 'HTTP ' + res.status;
|
||
let p = null;
|
||
try { p = await res.json(); detail = p.detail || p.title || detail; } catch { /* the status is the message */ }
|
||
if (p && CHAT_REFUSALS.has(p.code)) throw chatBusy(p);
|
||
throw new Error(detail);
|
||
}
|
||
const reader = res.body.getReader();
|
||
const dec = new TextDecoder();
|
||
let text = '';
|
||
let finish = null;
|
||
let buf = '';
|
||
let ours = false;
|
||
for (;;) {
|
||
const { value, done } = await reader.read();
|
||
if (done) break;
|
||
buf += dec.decode(value, { stream: true });
|
||
let cut;
|
||
while ((cut = buf.indexOf('\n')) >= 0) {
|
||
const line = buf.slice(0, cut).trim();
|
||
buf = buf.slice(cut + 1);
|
||
if (line === 'event: atrium') { ours = true; continue; }
|
||
if (!line.startsWith('data: ') || line === 'data: [DONE]') { if (!line) ours = false; continue; }
|
||
let d;
|
||
try { d = JSON.parse(line.slice(6)); } catch { continue; }
|
||
if (ours) {
|
||
if (d.loading) answer.status = 'Ładuję model do pamięci karty graficznej, to trwa około minuty…';
|
||
if (d.loaded) answer.status = 'Myślę…';
|
||
if (d.error) throw CHAT_REFUSALS.has(d.code) ? chatBusy(d) : new Error(d.error);
|
||
continue;
|
||
}
|
||
const c = (d.choices && d.choices[0]) || {};
|
||
if (c.finish_reason) finish = c.finish_reason;
|
||
if (c.delta && c.delta.content) { text += c.delta.content; answer.content = text; answer.status = ''; }
|
||
}
|
||
onUpdate(answer);
|
||
}
|
||
return { text: text.replace(/<think>[\s\S]*?<\/think>/g, '').trim(), finish };
|
||
}
|
||
|
||
// A name the question asks about that no visible record carries, in any inflection: said by code, with the closest
|
||
// names, so the model need not decide alone that a firm does not exist. "Nie znalazłem", never "nie ma": the account
|
||
// may not see every module. A name is a capitalised word not opening a sentence and not an acronym; a lower-case
|
||
// name slips past (P11).
|
||
function chatExistence(question, index) {
|
||
if (chatIsEn(question)) return []; // ponytail: "Friday", "Monday" read as names; English questions wait for P11
|
||
// The modules' own names are no unknown firm ("w Compassie", "z Insidera"), and a person named in any record
|
||
// ("prowadzi Anna Nowak") is no unknown name either: the record's text counts, not only its labels.
|
||
const words = [...new Set(['atrium', 'insider', ...index.records.flatMap((r) => [r.slug, r.title, r.text, ...(r.labels || [])])].filter(Boolean)
|
||
.flatMap((l) => chatFold(l).match(/\p{L}{3,}/gu) || []))];
|
||
const lost = [...question.matchAll(/\p{L}+/gu)].filter((m) => /^\p{Lu}\p{Ll}{2,}$/u.test(m[0]) && m.index && !/[.!?]\s*$/.test(question.slice(0, m.index)))
|
||
.map((m) => m[0]).filter((w) => !words.some((n) => chatSameWord(chatFold(w), n)));
|
||
if (!lost.length) return [];
|
||
const edits = (a, b) => { let row = [...Array(b.length + 1).keys()];
|
||
for (let i = 1; i <= a.length; i++) { const next = [i]; for (let j = 1; j <= b.length; j++) next[j] = Math.min(row[j] + 1, next[j - 1] + 1, row[j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1)); row = next; }
|
||
return row[b.length]; };
|
||
const near = (w) => { const f = chatFold(w); return [...new Set(index.records.flatMap((r) => (r.labels || []).filter((l) => l && /\p{L}{3}/u.test(l))
|
||
.filter((l) => (chatFold(l).match(/\p{L}{3,}/gu) || []).some((n) => n.length >= 4 && edits(n, f) <= Math.max(1, Math.floor(f.length / 4))))))].slice(0, 3); };
|
||
const seen = [...new Set(index.records.map((r) => r.slug))].filter((x) => x !== 'atrium')
|
||
.map((x) => (chatModules().find((m) => m.slug === x) || { name: x[0].toUpperCase() + x.slice(1) }).name);
|
||
return [{ slug: 'atrium', kind: 'sprawdzenie', key: 'atrium:istnienie', title: 'Sprawdzenie nazw z pytania', inner: '',
|
||
text: lost.map((w) => `Nazwy „${w}” nie znalazłem w rejestrach widocznych na tym koncie (${seen.join(', ')}).` +
|
||
(near(w).length ? ` Najbliższe nazwy: ${near(w).join(', ')}.` : ' Podobnych nazw w nich nie znalazłem.')).join(' ') +
|
||
(index.blind.length ? ` Moduły niewidoczne na tym koncie, więc nieprzeszukane: ${index.blind.join(', ')}.` : '') }];
|
||
}
|
||
|
||
// What the next "ta druga" can point at: the cited records and the members of a cited list the answer names,
|
||
// in the answer's order (a record cited but not named sits where its first [n] is).
|
||
function chatMentioned(text, sources, index) {
|
||
if (chatSaysNothing(text, index.records)) return [];
|
||
const citedRecs = chatCitedNs(text).map((n) => sources[n - 1]).filter(Boolean);
|
||
const pos = new Map(chatNamed(text, [...citedRecs, ...citedRecs.flatMap((r) => (r.members || []).map((k) => index.byKey.get(k)).filter(Boolean))]));
|
||
for (const r of citedRecs) if (!pos.has(r.key)) pos.set(r.key, text.search(new RegExp(`\\[(\\d+\\s*,\\s*)*${sources.indexOf(r) + 1}\\b`)));
|
||
return [...pos].sort((a, b) => a[1] - b[1]).map(([k]) => k);
|
||
}
|
||
// Items past `count` of a numbered list, each with its sub-lines, up to the next paragraph ("Następny krok:").
|
||
// Bullets are not counted: flat "- odpowiada: …" sub-bullets used up the budget and cut a right answer to one.
|
||
function chatTrimList(text, count) {
|
||
let k = 0;
|
||
let cutting = false;
|
||
return text.split('\n').filter((l) => {
|
||
if (/^\d+[.)]\s/.test(l)) cutting = ++k > count;
|
||
else if (!l.trim() || !/^(?:\s|[*•-]\s)/.test(l)) cutting = false;
|
||
return !cutting;
|
||
}).join('\n').trim();
|
||
}
|
||
// "* Odpowiedź na sprzeciw (sprawa 2026/0003) [2]." twice in one list: the repeat is dropped.
|
||
function chatDedupe(text) {
|
||
const seen = new Set();
|
||
return text.split('\n').filter((line) => {
|
||
const m = line.match(/^\s*(?:[*•-]|\d+[.)])\s+(.*)$/);
|
||
if (!m) return true;
|
||
const k = m[1].replace(/\[\d+(?:\s*,\s*\d+)*\]/g, '').replace(/[\s.;,*]+/g, ' ').trim().toLowerCase();
|
||
return !k || (!seen.has(k) && seen.add(k));
|
||
}).join('\n');
|
||
}
|
||
// A list question ("które", "jakie", "what") and the source group it names by that group's own words.
|
||
const CHAT_LISTQ = /(?:^|[^\p{L}])(?:któr\p{L}*|jaki\p{L}*|wymień|wypisz|pokaż|co\s+mam\p{L}*|which|what|list)(?![\p{L}])/iu;
|
||
// Only when the group is the question's whole filter: a second source's group ("obowiązuje" and "30 dni"), a
|
||
// matter or a record number narrow it, and the whole group, appended as "Pełna lista", would not answer.
|
||
// "Co pilne", "3 najpilniejsze zadania", "czy któraś umowa wymaga pilnej uwagi": code picks the items and their
|
||
// order, the model only says what comes first and why. Told to apply an order and a next step per kind, models
|
||
// put internal tasks under art. 168 KPC and answered a contracts question with matter deadlines (2026-11-04).
|
||
const CHAT_URGENT = /(?<![\p{L}])(?:(?:naj)?piln\p{L}*|najpierw|zaległ\p{L}*|priorytet\p{L}*|urgent\p{L}*|overdue|most\s+important)(?![\p{L}])/iu;
|
||
// The asker's emphasis narrows the list; the default is every kind, by date (Tobiasz, 2026-11-04).
|
||
const CHAT_STRESS = [[/sąd|sądow|procesow|court|procedural|hearing|rozpraw/iu, ['procedural', 'hearing'], 'tylko terminy sądowe'],
|
||
[/umow|umów|contract|agreement/iu, ['umowa'], 'tylko umowy'], [/wewnętrzn|internal/iu, ['internal'], 'tylko zadania wewnętrzne']];
|
||
// English questions get an English table: a Polish one under an English answer read as the model switching language.
|
||
const CHAT_STEPS_EN = { procLate: 'check whether it was filed; if not, consider a motion to restore the deadline (art. 168-169 KPC)',
|
||
procLateOther: 'check whether it was filed; if not, establish the effect of the missed date and whether the rules of that procedure allow restoring it',
|
||
proc: 'prepare and file by DATE', hearing: 'prepare for the hearing on DATE', hearingLate: 'check whether the hearing took place and what the court decided', limitation: 'by DATE take a step that interrupts the limitation period (art. 123 k.c.)',
|
||
umowa: 'decide by DATE: renew, renegotiate or end it; check the renewal and notice clauses', contrLate: 'check the contract for the effect of the missed date',
|
||
contr: 'prepare by DATE', intLate: 'ask the owner whether it was done and set a new date', int: 'complete by DATE' };
|
||
const CHAT_KINDS_EN = { procedural: 'court', hearing: 'hearing', internal: 'internal', contractual: 'contractual', limitation: 'limitation', umowa: 'contract end' };
|
||
// Art. 168-169 KPC restores a deadline in CIVIL procedure only: a court-set date or one whose basis is the k.p.c.
|
||
// It was offered for a late RODO breach notification to UODO, which is not civil procedure (Tobiasz, 2026-11-06).
|
||
const chatCivil = (d) => d.source === 'court' || /k\.?\s?p\.?\s?c/i.test(d.basis || '');
|
||
function chatStep(d, en) {
|
||
if (en) {
|
||
const late = d.days_left < 0;
|
||
const k = d.kind === 'hearing' ? (late ? 'hearingLate' : 'hearing') : d.kind === 'procedural' ? (late ? (chatCivil(d) ? 'procLate' : 'procLateOther') : 'proc') : d.kind === 'limitation' ? 'limitation'
|
||
: d.kind === 'umowa' ? 'umowa' : d.kind === 'contractual' ? (late ? 'contrLate' : 'contr') : late ? 'intLate' : 'int';
|
||
return CHAT_STEPS_EN[k].replace('DATE', d.due_date);
|
||
}
|
||
// "do" with the date, "dziś" for today: "przed 2026-11-12" on the day itself read as already too late (9.11).
|
||
const by = d.days_left === 0 ? 'dziś' : `do ${d.due_date}`;
|
||
if (d.kind === 'hearing') return d.days_left < 0 ? 'sprawdzić, czy rozprawa się odbyła i co postanowił sąd' : `przygotować się do rozprawy w dniu ${d.due_date}`;
|
||
if (d.kind === 'procedural') return d.days_left >= 0 ? `przygotować i złożyć ${by}` : chatCivil(d)
|
||
? 'sprawdzić, czy czynność złożono; jeśli nie, rozważyć wniosek o przywrócenie terminu (art. 168 i 169 KPC)'
|
||
: 'sprawdzić, czy czynność złożono; jeśli nie, ustalić skutki uchybienia i czy przepisy tego postępowania pozwalają przywrócić termin';
|
||
if (d.kind === 'limitation') return `${by} podjąć czynność przerywającą bieg przedawnienia (art. 123 k.c.)`;
|
||
if (d.kind === 'umowa') return `${by} zdecydować: przedłużyć, renegocjować czy zakończyć; sprawdzić w umowie przedłużenie i wypowiedzenie`;
|
||
if (d.kind === 'contractual') return d.days_left < 0 ? 'sprawdzić w umowie skutek upływu terminu' : `przygotować i wykonać ${by}`;
|
||
return d.days_left < 0 ? 'ustalić z odpowiedzialnym, czy zadanie wykonano, i wyznaczyć nowy termin' : `wykonać ${by}`;
|
||
}
|
||
const CHAT_DUE = /(?<![\p{L}])(?:termin\p{L}*|zada\p{L}*|deadline\p{L}*|task\p{L}*|rozpraw\p{L}*|hearing\p{L}*)(?![\p{L}])/iu;
|
||
function chatPick(question, index) {
|
||
if (!(CHAT_URGENT.test(question) || (CHAT_ASKS_WEEK.test(question) && CHAT_DUE.test(question))) || CHAT_BACK.test(question) || /\d{4}\/\d{2,5}|\p{Lu}{1,6}-\d{2,4}-\d{2,6}|w\s+sprawie|in\s+(?:the\s+)?matter/iu.test(question)) return null;
|
||
const all = (index.byKey.get('sygna:terminy') || {}).items;
|
||
if (!all) return null;
|
||
const stress = CHAT_STRESS.find(([re]) => re.test(question));
|
||
const week = CHAT_ASKS_WEEK.test(question);
|
||
// What is overdue stays on the list, also for "na ten tydzień", and the date order puts it first, oldest first:
|
||
// left out of the week's table and named in one closing sentence, the overdue items were lost by 15 of 16
|
||
// answers (user-ii-thread, 9.11).
|
||
let items = all.filter((d) => (!stress || stress[1].includes(d.kind)) && (!week || d.days_left <= 7));
|
||
// A number said wins over "najpierw": "3 zadania? najpierw sądowe" asks for three, the second word is the emphasis.
|
||
const said = question.match(CHAT_COUNT);
|
||
const count = said ? CHAT_NUMWORDS[said[1].toLowerCase()] || Number(said[1]) : chatCount(question);
|
||
if (count) items = items.slice(0, count);
|
||
// No number asked: what is overdue or due within a week; contracts all (they are only the next 30 days).
|
||
else if (!stress || stress[1][0] !== 'umowa') { const near = items.filter((d) => d.days_left <= 7); items = near.length ? near : items.slice(0, 3); }
|
||
const en = chatIsEn(question);
|
||
const days = (n) => `${n} day${n === 1 ? '' : 's'}`;
|
||
const state = (d) => en ? (d.days_left < 0 ? `overdue by ${days(-d.days_left)}` : d.days_left === 0 ? 'today' : `in ${days(d.days_left)}`) : (d.days_left < 0 ? `po terminie od ${chatPlural(-d.days_left, 'dnia', 'dni', 'dni')}` : d.days_left === 0 ? 'dziś' : `za ${chatPlural(d.days_left, 'dzień', 'dni', 'dni')}`);
|
||
// Under an English answer the words code writes are English; deadline titles are data and stay as entered.
|
||
const title = (d) => en && d.contract ? `End of contract ${d.contract.number} „${d.contract.name}”` : d.title;
|
||
const ref = (d) => !en ? d.ref : d.contract ? `contract ${d.contract.number}, ${d.contract.counterparty || 'counterparty not entered'}`
|
||
: `matter ${d.matter_reference} „${d.matter_name || ''}”`;
|
||
const kind = (d) => en ? (d.kind === 'procedural' && !chatCivil(d) ? 'procedural' : CHAT_KINDS_EN[d.kind]) : CHAT_DEADLINE_SHORT[d.kind];
|
||
const rows = items.map((d, i) => [String(i + 1), title(d), kind(d) || d.kind, d.due_date, state(d), ref(d), d.owner, chatStep(d, en)]);
|
||
const head = en ? ['No.', 'Item', 'Kind', 'Date', 'Status', 'Matter / contract', 'Owner', 'Next step']
|
||
: ['Lp.', 'Pozycja', 'Rodzaj', 'Data', 'Stan', 'Sprawa / umowa', 'Odpowiada', 'Następny krok'];
|
||
const how = `według faktycznej daty, najwcześniejsza pierwsza${stress ? ', ' + stress[2] + ' (tak prosi pytający)' : ', bez względu na rodzaj'}${week ? ', pozycje po terminie i najbliższe 7 dni' : ''}`;
|
||
const text = `Pozycje wybrane do odpowiedzi (${rows.length}), ${how}; stan na ${new Date().toLocaleDateString('sv')} ` +
|
||
`(tydzień kalendarzowy od ${chatWeekOf(new Date().toLocaleDateString('sv')).join(' do ')}):\n` +
|
||
(rows.map((r) => `${r[0]}. ${r[1]} (${r[2]}, ${r[3]}, ${r[4]}, ${r[5]}, odpowiada ${r[6]}). Następny krok: ${r[7]}.`).join('\n') || 'brak takich pozycji.');
|
||
// Nothing picked: said by code. Given an empty list beside the deadline summary, Qwen took an internal task
|
||
// from the summary and called it the week's court deadline (q-tydzien-procesowe, 2026-11-05).
|
||
const none = { procedural: ['terminów sądowych', 'court deadlines'], umowa: ['umów kończących się', 'contracts ending'], internal: ['zadań wewnętrznych', 'internal tasks'] }[stress ? stress[1][0] : ''] || ['terminów', 'deadlines'];
|
||
const empty = en ? `There are no ${none[1]}${week ? ' overdue or in the next 7 days' : ''}.`
|
||
: `${week ? 'Po terminie ani w najbliższych 7 dniach nie' : 'Nie'} ma ${none[0]}.`;
|
||
// Each row opens its own record (a matter's deadlines, a contract): an answer with no way to the item was
|
||
// read as "no links to the sources" (Tobiasz, 2026-11-06). The list itself opens Sygna's deadlines.
|
||
const links = items.map((d) => { const r = index.byKey.get(d.key); return r && r.inner ? moduleHref(r.slug, r.inner) : ''; });
|
||
return { empty, rec: { slug: 'sygna', kind: 'zestawienie', key: 'atrium:pilne', title: 'Pilne: pozycje wybrane do odpowiedzi', inner: 'deadlines', text,
|
||
members: items.map((d) => d.key) }, table: { head, rows, links, linkCol: 5, view: { sub: { 1: 2, 3: 4 }, head: { 3: en ? 'Due' : 'Termin' }, dropSame: [6], nowrap: [3] } } };
|
||
}
|
||
const chatIsEn = (question) => !/[ąćęłńóśźż]/i.test(question) && /(?:^|\W)(?:the|what|which|is|are|how|english)(?!\w)/i.test(question);
|
||
function chatContractTable(cs, today, en) {
|
||
const head = en ? ['No.', 'Contract', 'Counterparty', 'Ends', 'Days left', 'Status', 'Value'] : ['Lp.', 'Umowa', 'Kontrahent', 'Koniec', 'Zostało dni', 'Status', 'Wartość'];
|
||
return { head, rows: cs.map((c, i) => [String(i + 1), `${c.number} ${c.name}`, c.counterparty || '-', c.ends_on || '-',
|
||
c.ends_on ? String(chatDays(c.ends_on, today)) : '-', chatStatus('umowa', c.status, en), c.value_amount ? `${chatMoney(c.value_amount)} ${c.value_currency}` : '-']),
|
||
view: { nowrap: [3] } };
|
||
}
|
||
const chatTableText = (t) => [t.head, ...t.rows].map((r) => '| ' + r.join(' | ') + ' |').join('\n');
|
||
function chatListFor(sources, question) {
|
||
if (!CHAT_LISTQ.test(question) || /\d{4}\/\d{2,5}|\p{Lu}{1,6}-\d{2,4}-\d{2,6}|w\s+sprawie|in\s+(?:the\s+)?matter/iu.test(question)) return null;
|
||
const hits = sources.map((r, i) => ({ i, gs: (r.list || []).filter((g) => g.re && g.re.test(question) && g.keys.length) })).filter((h) => h.gs.length);
|
||
if (hits.length !== 1) return null;
|
||
const { i, gs } = hits[0];
|
||
return { n: i + 1, keys: [...new Set(gs.flatMap((g) => g.keys))], labels: gs.map((g) => g.label).filter(Boolean) };
|
||
}
|
||
// Below this best-match score (chatSearch) no record is about the question. Measured on the admin index
|
||
// (2026-10-29): a poem 4.4, small talk 1.8-3.2, an e-mail to write 2.8; data questions mostly 6-29, the
|
||
// lower ones law citations (they have Insider sources) or "nie znalazłem" answers, which this gate never sees.
|
||
const CHAT_OFFTOPIC = 6;
|
||
// Also says "nie znalazłem": a low score is as often a firm we have no record of ("Zygzak") as a poem.
|
||
const CHAT_SCOPE = 'W danych, do których masz dostęp, nie znalazłem nic na ten temat. Pomagam tylko w sprawach z danych Twojej firmy (umowy, sprawy i terminy, kancelarie zewnętrzne, dokumenty) i w przepisach z Insidera.';
|
||
const CHAT_SCOPE_EN = "I found nothing on this in the data you have access to. I help only with your firm's data (contracts, matters and deadlines, external law firms, documents) and with the law in Insider.";
|
||
|
||
// How many items the question asks for: "3 zadania", "top 3", "trzy", "two most urgent"; 1 for "najważniejsza",
|
||
// "która z nich", "najpierw". Then the whole group is not appended (asked for 3, the user got 3 plus all 6).
|
||
// Only a number before a countable noun: "do 15 listopada", "art. 52", "50 tys. zł", "o 10 rano" are no count.
|
||
const CHAT_NUMWORDS = { jeden: 1, jedno: 1, jedna: 1, dwa: 2, dwie: 2, dwóch: 2, trzy: 3, trzech: 3, cztery: 4, czterech: 4, pięć: 5, pięciu: 5,
|
||
one: 1, two: 2, three: 3, four: 4, five: 5 };
|
||
const CHAT_COUNT = new RegExp(`(?<!(?:art\\.?|§|ust\\.?|pkt|poz\\.?)\\s*)(?<![\\p{L}\\d.,/-])(\\d{1,2}|${Object.keys(CHAT_NUMWORDS).join('|')})(?![\\p{L}\\d.,/-])` +
|
||
'\\s+(?:naj\\p{L}+\\s+|most\\s+\\p{L}+\\s+)?(?:zada|termin|umow|umów|spraw|pozycj|rzecz|punkt|czynnoś|task|deadline|contract|agreement|matter|case|item|thing)\\p{L}*', 'iu');
|
||
const CHAT_ONE = /(?<![\p{L}])(?:naj\p{L}*(?:szy|sza|szą|szego|szej|ższy|ższa)|najpierw|któr[ya]\s+(?:z\s+nich|z\s+tych|z\s+wygas\p{L}*)|which\s+one)(?![\p{L}])/iu;
|
||
// "Mam 3 umowy z Ostrewą, która jest najcenniejsza?" asks for one: the single-item word wins over the number.
|
||
function chatCount(question) {
|
||
if (CHAT_ONE.test(question)) return 1;
|
||
const m = question.match(CHAT_COUNT);
|
||
return m ? CHAT_NUMWORDS[m[1].toLowerCase()] || Number(m[1]) : null;
|
||
}
|
||
// "z nich", "spośród tych", "of them": the records the previous answer listed, all of them, as sources. Without
|
||
// it "która z nich jest najważniejsza" searched its own words and got eight client records.
|
||
const CHAT_BACK = /(?<![\p{L}])(?:z|spośród|wśród|of|among)\s+(?:nich|tych|them|these|those)(?![\p{L}])/iu;
|
||
// "z Zawadą", "w umowie z Kodar Cloud", "with Nivelia": a contract named by one word of its counterparty in any
|
||
// case ending. The full label never matched "Zawadą", so the question went to search or to the law.
|
||
// Only a capitalised name, not after "w związku z"/"zgodnie z", and never a generic word of a firm's name:
|
||
// "w związku z transportem" pinned the transport contract and took a law question off Insider.
|
||
const CHAT_PARTY_GENERIC = /^(?:sp|spółk|trans|agenc|dystr|logis|księg|labor|insta|hurto|rekla|firm|consu|grup|group|serwi|usług|budow|medyc|polsk|przem|handl)/u;
|
||
function chatByParty(question, recs) {
|
||
const hits = new Set();
|
||
for (const [, w] of question.matchAll(/(?<![\p{L}])(?<!(?:związku|zgodnie|razem|wraz|porównaniu)\s+)(?:[zZ]|[zZ]e|[wW]ith)\s+(\p{Lu}[\p{L}-]{3,})/gu)) {
|
||
const st = w.toLowerCase().slice(0, w.length > 5 ? 5 : 4);
|
||
if (CHAT_PARTY_GENERIC.test(st)) continue;
|
||
const m = recs.filter((r) => r.kind === 'umowa' && (r.contract.counterparty || '').toLowerCase().split(/[^\p{L}]+/u)
|
||
.some((x) => x.length >= 4 && !CHAT_PARTY_GENERIC.test(x) && x.startsWith(st)));
|
||
if (m.length === 1) hits.add(m[0]);
|
||
}
|
||
return [...hits];
|
||
}
|
||
// "Co zrobić przed końcem", "przedłużenie": a question about acting on an expiring contract.
|
||
const CHAT_ACT = /co\s+(?:\p{L}+\s+){0,3}?(?:zrobi|zrób|przygotow)|przed\s+(?:jej\s+|jego\s+)?(?:końc|upływ|wygaś)|przedłuż|wypowi|rozwiąz|odstąp|jak\s+(?:ją|go)\b|krok|what\s+(?:should|to\s+do)|before\s+(?:it\s+)?end|renew|terminat|next\s+step/iu;
|
||
// A recommendation question gets told the shape of a useful answer; a lookup question keeps its plain one.
|
||
// "Najcenniejsza" is a lookup: told to add a next step, the model borrowed the example's § 4 ust. 2.
|
||
// Not a risk question: squeezed into "Najpierw X, bo …", "na co uważać" got payment terms called a risk.
|
||
const CHAT_ADVICE = /naj(?:ważn|piln|pierw)|priorytet|co\s+(?:\p{L}+\s+){0,3}?(?:zrobi|zrób|przygotow)|dlaczego|czemu|first|most\s+(?:urgent|important|valuable)|why|what\s+should/iu;
|
||
|
||
// One turn of the conversation without the page: sources, messages, the model round and the gates. It fills
|
||
// and returns `answer`; `turns` are the turns before this question; the page renders through `onUpdate`.
|
||
// The evaluation harness (testy/czat-v2/run.mjs) runs this very function from Node, so no DOM in here.
|
||
async function chatTurn({ model, question, turns, index, answer = { role: 'assistant', content: '', status: '', refs: [], trace: [] }, onUpdate = () => {},
|
||
// Default 'osoba' after round 2 (testy/czat-graf/RUNDA2.md): the team member's card helped both Qwen and Bielik;
|
||
// the full map (true) cost Qwen its "nie ma" answers twice. false switches the map off entirely.
|
||
// ja: the asker's own card for "co mam na głowie" (testy/czat-graf/RUNDA4.md: passed on Qwen and Bielik); false switches it off.
|
||
graf = chat.graf ?? 'osoba', ja = chat.ja ?? true,
|
||
// prawo: the law graph beside the cited article (testy/czat-prawo/PROJEKT.md: passed on
|
||
// Qwen and Bielik, 12.11); false switches it off.
|
||
prawo = chat.prawo ?? true,
|
||
// istnienie: a code source saying a capitalised name of the question matches no visible record (audit P9, 13.11);
|
||
// the condition for a milder rule 3, not yet measured on the models, so off by default.
|
||
istnienie = chat.istnienie ?? false, files = chat.files }) {
|
||
const done = (content, extra = {}) => Object.assign(answer, { content, status: '', ...extra });
|
||
try {
|
||
// "Umowa o dzieło" in a question about the law is not a question about the register's contracts.
|
||
// An attached file is what the question is about: "w tej umowie" means it, not the register.
|
||
const att = chatFileSources(files, model);
|
||
const coded = att.length || chatRoute(question) === 'law_topic' ? null : chatRefusal(index, question);
|
||
if (coded) return done(coded, { coded: 'refusal' });
|
||
// A turn that failed its check still named its records (kept in `mentioned`): "ta umowa" after it means them.
|
||
const at = turns.map((t) => t.role === 'assistant' && !t.aborted && (!t.failed || !!(t.mentioned && t.mentioned.length))).lastIndexOf(true);
|
||
const prev = at >= 0 ? turns[at] : null;
|
||
const prevQ = at > 0 ? turns[at - 1].content : '';
|
||
// A question that names its record ("w umowie UM-2026-0017") needs no resolving.
|
||
const named = chatNamed(question, index.records).map(([k]) => index.byKey.get(k));
|
||
// A party hit never takes a law question off Insider unless the question is about a contract.
|
||
if (!named.length && (!CHAT_TOPICWORD.test(question) || /umow|kontrakt|contract|agreement/iu.test(question))) named.push(...chatByParty(question, index.records));
|
||
const ana = chatAnaphora(question);
|
||
// "ta druga" right after the map asked which firm: the second candidate as the question listed them. Resolved
|
||
// through the anchors' records instead, it missed when the two anchors were of different kinds.
|
||
const asked = graf && !named.length && ana.ordinal && prev && prev.coded === 'ask' && prev.graf && prev.graf.order;
|
||
const pin = asked ? asked.at(ana.ordinal < 0 ? -1 : ana.ordinal - 1) || null : null;
|
||
let resolved = [];
|
||
if (!att.length && !named.length && !pin && (ana.demonstrative || ana.ordinal)) {
|
||
const res = chatResolveRefs(prev, ana, index);
|
||
const which = CHAT_WHICH[res.kind] || 'który z nich';
|
||
if (res.ambiguous) {
|
||
return done(`O ${which} chodzi: ${res.ambiguous.slice(0, 6).map((r) => r.title).join('; ')}? Napisz numer albo nazwę.`,
|
||
{ coded: 'ask', mentioned: res.ambiguous.map((r) => r.key) });
|
||
}
|
||
if (res.only) {
|
||
return done(`W poprzedniej odpowiedzi była tylko jedna pozycja: ${res.only.title}. O ${which} chodzi? Podaj numer albo nazwę.`,
|
||
{ coded: 'ask', mentioned: [res.only.key] });
|
||
}
|
||
// A first question with nothing before it ("Ile umów w statusie szkic i jakie to umowy?") is asked of the
|
||
// data; only a pronoun that can only point back ("w tej umowie") is asked about.
|
||
if (res.none && (prev || ana.strong)) return done(`Nie wiem, o ${which} chodzi: w tej rozmowie nie padła jeszcze żadna ${res.kind}. Podaj jej numer albo nazwę.`, { coded: 'ask' });
|
||
resolved = res.keys.map((k) => index.byKey.get(k));
|
||
}
|
||
let back = [];
|
||
if (!named.length && !resolved.length && prev && CHAT_BACK.test(question)) {
|
||
const recs = (prev.mentioned || []).map((k) => index.byKey.get(k)).filter((r) => r && CHAT_WHICH[r.kind]);
|
||
const n = {};
|
||
for (const r of recs) n[r.kind] = (n[r.kind] || 0) + 1;
|
||
const kind = Object.keys(n).sort((a, b) => n[b] - n[a])[0];
|
||
// "co z umowami najmu? która z nich…": "z nich" points inside this question when it names another kind.
|
||
const own = question.split(/[^\p{L}]+/u).map((w) => chatKindOf(w.toLowerCase())).filter(Boolean);
|
||
if (!own.length || own.includes(kind)) back = recs.filter((r) => r.kind === kind).slice(0, 8);
|
||
} else if (!named.length && !resolved.length && /wygas|kończ\p{L}*\s+się|expir|ending/iu.test(question) && CHAT_ACT.test(question)
|
||
&& (chatCount(question) === 1 || /(?<![\p{L}])first(?![\p{L}])/iu.test(question))) {
|
||
// "Which expiring contract first, and what does its renewal clause say?": the expiring ones are "z nich",
|
||
// so code ranks them instead of the model guessing at a register row.
|
||
const win = index.byKey.get('galena:wygasajace:90');
|
||
back = ((win && win.members) || []).map((k) => index.byKey.get(k)).filter(Boolean).slice(0, 8);
|
||
}
|
||
// "Która z nich najważniejsza": the contracts ranked by value in code. Left to compare, the model called a
|
||
// 240 000 PLN contract "the most valuable" beside one of 1 200 000 PLN.
|
||
const cs = back.map((r) => r.contract).filter(Boolean);
|
||
const today = new Date().toLocaleDateString('sv');
|
||
const byVal = [...cs].sort((a, b) => Number(b.value_amount || 0) - Number(a.value_amount || 0));
|
||
const byEnd = cs.filter((c) => c.ends_on).sort((a, b) => a.ends_on.localeCompare(b.ends_on)).concat(cs.filter((c) => !c.ends_on));
|
||
const backSum = cs.length > 1 ? [{ slug: 'galena', kind: 'zestawienie', key: 'galena:z-nich', title: 'Umowy z poprzedniej odpowiedzi według wartości', inner: 'cards', members: back.map((r) => r.key),
|
||
text: `Najwyższą wartość ma ${byVal[0].number} (${byVal[0].value_amount ? chatMoney(byVal[0].value_amount) + ' ' + byVal[0].value_currency : 'wartość nie wpisana'}), najwcześniej kończy się ${byEnd[0].number} (${byEnd[0].ends_on || 'data końca nie wpisana'}). ` +
|
||
'Umowy wymienione w poprzedniej odpowiedzi, od najwyższej wartości (bez przeliczania walut): ' + byVal
|
||
.map((c, i) => `${i + 1}. ${c.number} ${c.name} (kontrahent ${c.counterparty || 'nie wpisany'}): ${c.value_amount ? chatMoney(c.value_amount) + ' ' + c.value_currency : 'wartość nie wpisana'}, ` +
|
||
(c.ends_on ? `kończy się ${c.ends_on}, za ${chatDays(c.ends_on, today)} dni` : 'data końca nie wpisana')).join('; ') + '.' }] : [];
|
||
let topic = [];
|
||
// Computed on both arms: on A it only records whether B would have had a card (coverage without extra turns).
|
||
let gt = null;
|
||
try { gt = index.graph && chatGraphTurn({ question, index, named, resolved, back, pin, ja: ja && !!graf }); } catch (ex) { console.warn('chat map off:', ex); }
|
||
// 'osoba': only a team member's card (testy/czat-graf/RUNDA2.md); firms, matters, one record and the question back stay as A.
|
||
if (graf === 'osoba' && gt && gt.kind !== 'osoba') gt = { why: 'tylko osoba' };
|
||
// "Wypowiedzenie umowy z Velmora Pompy" names a client, so it is a data question, not one for Insider. A name
|
||
// read from one word ("Energii", "Zielonej Górze") never takes a question off Insider, and a question that
|
||
// stays with the law gets no card, so it gets no question back either.
|
||
const route0 = chatRoute(question, named.length + resolved.length);
|
||
const route1 = chatRoute(question, named.length + resolved.length + 1);
|
||
const usable = !!(graf && gt && route1 === 'data' && (route0 === 'data' || gt.hit !== 'czesciowe'));
|
||
if (usable && gt.ask && !att.length) return done(gt.ask, { coded: 'ask', mentioned: gt.mentioned, graf: gt });
|
||
const route = usable && (gt.root || gt.link) ? route1 : route0;
|
||
// A card only for a data question: a cited article stays Insider's. A fault in building it leaves the turn as A.
|
||
let card = null;
|
||
try {
|
||
card = !usable || route !== 'data' ? null : gt.root ? chatCard(gt.root, index, today, { table: graf === 'tabela', ja: !!gt.ja })
|
||
: gt.link ? chatLinkCard(gt.link, index, today) : null;
|
||
} catch (ex) { console.warn('chat map off:', ex); card = null; }
|
||
// Set here, so turns that end early (done) carry it too; the harness reads it from every answer.
|
||
if (graf) answer.graf = gt && { root: gt.root || null, link: gt.link || null, why: gt.why || null, card: card && card.rec.key, members: card ? [...card.members] : [] };
|
||
else answer.grafDry = gt && { root: gt.root || null, link: gt.link || null, why: gt.why || null, ask: !!gt.ask };
|
||
// A cited provision with no Insider access: given no text, Bielik answered from memory and cited a [2] it had not.
|
||
if (route === 'law_cite' && !index.law) {
|
||
return done('Nie masz dostępu do Insidera, więc nie pobiorę tekstu tego przepisu i nie sprawdzę, czy obowiązuje. O dostęp poproś administratora.', { coded: 'refusal' });
|
||
}
|
||
if (route === 'law_topic') {
|
||
const status = (t) => { answer.status = t; onUpdate(answer); };
|
||
status('Szukam przepisów w Insiderze…');
|
||
const t = await chatTopic(question, index, status, model);
|
||
if (t.coded) return done(t.coded, { coded: 'topic' });
|
||
topic = t.records;
|
||
}
|
||
const law = await chatLaw(question, index);
|
||
// A fault in the law graph leaves the turn as without it.
|
||
let lawGraph = { near: [] };
|
||
if (prawo) {
|
||
try { lawGraph = await chatLawGraph({ law, topic }, index); } catch (ex) { if (ex.name === 'AbortError') throw ex; console.warn('law graph off:', ex); }
|
||
answer.prawo = lawGraph.near.map((r) => r.key);
|
||
}
|
||
// A question about the law gets no firm records: a dozen contracts beside three articles are noise.
|
||
let found = topic.length ? [] : chatSearch(index.records, question + (ana.demonstrative && prevQ ? ' ' + prevQ : ''));
|
||
// "z nich": the rest of the slots stay with that kind and the totals, not with whatever shares a word.
|
||
if (back.length) found = found.filter((r) => r.kind === back[0].kind || r.kind === 'zestawienie');
|
||
// The card replaces what search found around the name: the activity list, the firm's whole deadline summary
|
||
// and the 30/60/90-day windows were what misled both models on 2026-11-10. Records naming the subject stay.
|
||
// filter() drops `top`, which the CHAT_SCOPE gate reads.
|
||
// The asker's own card cuts only what it covers: contracts belong to nobody on the team, so "ile mam umów w
|
||
// szkicu" still needs the register (testy/czat-graf/RUNDA4.md; cutting them all failed in RUNDA3.md).
|
||
if (card && card.rec.kind === 'karta') {
|
||
const top = found.top;
|
||
found = Object.assign(found.filter((r) => card.members.has(r.key) || card.names(r) || (gt.ja && /^galena:(?:umowa|zestawienie|wygasajace|ranking)/.test(r.key))), { top });
|
||
}
|
||
const seen = new Set();
|
||
const pick = att.length || law.length || topic.length || named.length || resolved.length || back.length || card ? null : chatPick(question, index);
|
||
if (pick && !pick.table.rows.length) return done(pick.empty, { coded: 'pick', refs: [], verify: [] });
|
||
// The entity's card right after law and topic; a one-record link card behind its record, so [1] stays the record.
|
||
const pool = [...att, ...(istnienie && !pick && !named.length && !resolved.length && !card && !law.length ? chatExistence(question, index) : []),
|
||
...(pick ? [pick.rec] : []), ...law, ...topic, ...lawGraph.near,
|
||
...(card && card.rec.kind === 'karta' ? [card.rec] : []), ...named, ...resolved,
|
||
...(card && card.rec.kind !== 'karta' ? [card.rec] : []), ...backSum, ...back, ...chatCarry(prev, index),
|
||
...(card ? card.lead : []), ...found]
|
||
.filter((r) => !seen.has(r.key) && seen.add(r.key));
|
||
// The group the question names, without its siblings: given the 30-, 60- and 90-day windows at once for "w
|
||
// ciągu 60 dni", both models answered from the wrong one (q-60-dni, 14 of 16, 9.11). A record whose `list`
|
||
// group the question names drops the records of its family (its key up to the last ":") that have groups the
|
||
// question does not name; which family it is, code does not need to know.
|
||
const fam = (r) => r.key.slice(0, r.key.lastIndexOf(':'));
|
||
const listHit = (r) => (r.list || []).some((g) => g.re && g.re.test(question));
|
||
const hitFams = new Set(pool.filter(listHit).map(fam));
|
||
const sources = pool.filter((r) => !(r.list && hitFams.has(fam(r))) || listHit(r))
|
||
.slice(0, att.length + CHAT_TOP + law.length + topic.length + lawGraph.near.length);
|
||
const name = (slug) => (chatModules().find((m) => m.slug === slug) || { name: slug }).name;
|
||
const toRef = (r, i) => ({ n: i + 1, key: r.key, kind: r.kind, slug: r.slug, module: name(r.slug), title: r.title, text: r.text,
|
||
data: !['przepis', 'akt', 'orzeczenie', 'plik'].includes(r.kind), inner: r.inner, url: r.url });
|
||
answer.refs = sources.map(toRef);
|
||
answer.trace = sources.map((r, i) => `[${i + 1}] ${name(r.slug)}: ${r.title}${r.read ? ` (${r.read})` : ''}`);
|
||
answer.status = 'Myślę…';
|
||
onUpdate(answer);
|
||
const about = [...resolved, ...(card && card.rec.kind === 'karta' ? [card.rec] : [])].map((r) => `[${sources.indexOf(r) + 1}] ${r.title}`);
|
||
const count = pick ? null : chatCount(question);
|
||
const want = count || pick || card ? null : chatListFor(sources, question);
|
||
// Which listed contract ends first is computed here, or that none has an end date: told to name the earliest
|
||
// of two drafts with no end date, 10 of 16 answers made one up (q-szkic, 9.11).
|
||
const wantCs = want && want.keys.every((k) => k.startsWith('galena:umowa:')) ? want.keys.map((k) => (index.byKey.get(k) || {}).contract).filter(Boolean) : [];
|
||
const dated = wantCs.filter((c) => c.ends_on >= today).sort((a, b) => a.ends_on.localeCompare(b.ends_on));
|
||
const gone = wantCs.filter((c) => c.ends_on && c.ends_on < today);
|
||
const undated = wantCs.filter((c) => !c.ends_on).length;
|
||
const endsSaid = [dated.length ? `że najwcześniej kończy się ${dated[0].number} (${dated[0].ends_on})` : '',
|
||
gone.length ? `że data końca już minęła: ${gone.map((c) => `${c.number} (${c.ends_on})`).join(', ')}` : '',
|
||
undated ? (undated === wantCs.length ? 'że żadna z nich nie ma wpisanej daty końca' : `że ${undated} z ${wantCs.length} nie ma wpisanej daty końca`) : '']
|
||
.filter(Boolean).join(' i ');
|
||
// The search matches words, so a found article may not answer; the model says which one does, or none.
|
||
const hint = topic.length ? '\n(Przepisy w źródłach znalazła wyszukiwarka Insidera po słowach pytania i nie każdy musi pasować. Odpowiedz tylko z tych, które odpowiadają na pytanie, podając numer artykułu i ustawę; jeśli żaden nie odpowiada, napisz, że nie znalazłem przepisu, który odpowiada na pytanie.' +
|
||
(topic.some((r) => r.kind === 'orzeczenie') ? ' Orzeczenia to tylko przykłady z orzecznictwa, nie przesądzają sprawy.' : '') + ')'
|
||
// Models dropped items of a listed group (2 of 6 overdue deadlines): told the count, they mostly list all.
|
||
: pick ? `\n(Źródło [1] to lista wybrana przez system (${chatPlural(pick.table.rows.length, 'pozycja', 'pozycje', 'pozycji')}). Pod Twoją odpowiedzią pokaże się jako tabela z datami, osobami i następnymi krokami, więc jej nie przepisuj. Napisz krótko: co jest na pierwszym miejscu i dlaczego, z [1]; wymień każdą pozycję po terminie i nazwij ją po terminie; nie dodawaj pozycji spoza listy i nie zmieniaj kroków. Jeśli lista jest pusta, napisz, że takich pozycji nie ma.)`
|
||
: want && want.keys.length > 1 && want.keys.every((k) => k.startsWith('galena:umowa:')) ? `\n(Źródło [${want.n}] wymienia ${chatPlural(want.keys.length, 'umowę', 'umowy', 'umów')}. Pod Twoją odpowiedzią pokażą się jako tabela z datami i wartościami, więc ich nie przepisuj. Napisz 1-2 zdania z [${want.n}]: ile ich jest i ${endsSaid}.)`
|
||
: want ? `\n(Źródło [${want.n}] wymienia ${chatPlural(want.keys.length, 'pozycję', 'pozycje', 'pozycji')}${want.labels.length ? ' (' + want.labels.join(', ') + ')' : ''}: wymień wszystkie${want.labels.length > 1 ? ', w każdej grupie osobno, z nazwą grupy' : ''}.)` : '';
|
||
// The hints are Polish, and with them an English question got a Polish answer.
|
||
const en = chatIsEn(question);
|
||
// "Whole answer": the model copied the Polish source sentence into an English answer's second paragraph.
|
||
const shape = (en ? '\n(The question is in English: write the whole answer in English, translating what you take from the sources.)' : '') +
|
||
(count ? `\n(Pytanie prosi o ${count === 1 ? 'jedną pozycję: wskaż jedną' : `${count} pozycje: podaj dokładnie ${count}`}, według kolejności albo kryterium ze źródeł, i nazwij to kryterium.` +
|
||
// tob#0: three right deadlines with no date, days or owner, all of them in the source. Only for deadlines:
|
||
// asked for contracts, the model wrote that the sources give no days overdue.
|
||
(/zada|termin|task|deadline/iu.test(question) ? ' Przy każdej pozycji podaj datę albo liczbę dni po terminie, sprawę i osobę odpowiedzialną.' : '') + ')' : '') +
|
||
// Placeholders, not values: with "do 30 dni" in it the model once moved a 90-day notice to 30.
|
||
// The example lives in this hint, not among the few-shot exchanges: there, every later lookup ("a co z
|
||
// umowami, które wygasają?") came back in its shape and twice named a contract that was in no source.
|
||
// Not on a list question: told to lead with one recommendation, "co jest do zrobienia pilnego" got one of six.
|
||
(!want && !pick && (count || !sources.some((r) => (r.list || []).some((g) => g.re && g.re.test(question)))) && CHAT_ADVICE.test(question) ? '\n(Najpierw odpowiedz wprost, potem jednym zdaniem powód z numerem źródła, potem konkretny następny krok wynikający ze źródła, np. z klauzuli umowy z jej oznaczeniem §. ' +
|
||
// The § slot only for a clause: for a deadline the model wrote "(§ nie podany w źródłach)" or made one up.
|
||
'Wzór formy, nie treści: „Najpierw <umowa albo termin>, bo <fakt ze źródła> [n]. Następny krok: <czynność z klauzuli albo źródła> [n].” ' +
|
||
'Oznaczenie § dopisz tylko wtedy, gdy krok wynika z klauzuli umowy w źródłach; przy terminie podaj jego podstawę prawną ze źródła, jeśli ją ma. ' +
|
||
'Jeśli źródła nie pozwalają ocenić, co ważniejsze albo co zrobić, napisz to wprost zamiast zgadywać. Krótko.)' : '');
|
||
const messages = chatMessages(index.blind, question, sources, chatHistory(turns, answer.refs), about, hint + shape + chatCardHint(card, sources, graf));
|
||
const round = async (msgs) => {
|
||
const got = await chatRound(model, msgs, answer, onUpdate);
|
||
const { finish } = got;
|
||
// Asked for 3, a longer list loses its tail here, before the check, so the flags match the text shown.
|
||
const text = count > 1 ? chatTrimList(chatDedupe(got.text), count) : chatDedupe(got.text);
|
||
answer.content = text;
|
||
// A thinking model can spend the whole answer limit thinking (Qwen, 2 of 78 questions).
|
||
if (!text) throw new Error(finish === 'length' ? _tr('model zużył cały limit na rozważania i nie podał odpowiedzi. Zapytaj jeszcze raz.') : _tr('model nie podał odpowiedzi.'));
|
||
return text;
|
||
};
|
||
// An answer that says nothing about the data: no checkable value and no record named, whatever its words. A list
|
||
// of refusal phrases missed every new wording ("Nie posiadam informacji", "I can only assist with…") and the turn
|
||
// ended as a failure (q-wiersz, q-kranowiec, q-nowicka, 9.11).
|
||
const bare = (t) => !chatClaims(t.replace(/\[\d+(?:\s*,\s*\d+)*\]/g, ' ')).length && !chatNamed(t, index.records).length;
|
||
// Refused twice, or a refusal after an answer that cited the data: shown is what code assembled (the table, else the
|
||
// cited sources), not a failure and not a canned "nie znalazłem" (q-wartosc-pln: the total sat in [1]).
|
||
const fallback = (said) => {
|
||
const table = pick ? pick.table : wantCs.length > 1 ? chatContractTable(wantCs, today, en) : null;
|
||
const ns = table ? [] : (chatCitedNs(said).length ? chatCitedNs(said) : named.map((r) => sources.indexOf(r) + 1))
|
||
.filter((n) => n >= 1 && n <= sources.length).slice(0, 2);
|
||
if (!table && !ns.length) return null;
|
||
const lead = en ? "I could not confirm the model's answer in the sources; below is the data from the system."
|
||
: 'Nie potwierdziłem odpowiedzi modelu w źródłach; poniżej dane z systemu.';
|
||
// A source's `note` is said to the model, not to the asker: left out here.
|
||
const shown = (r) => (r.note ? r.text.replace(r.note, '') : r.text).trim();
|
||
return done(table ? `${lead} [${pick ? 1 : want.n}]\n\n${chatTableText(table)}` : `${lead}\n\n${ns.map((n) => `[${n}] ${shown(sources[n - 1])}`).join('\n\n')}`,
|
||
{ coded: 'fallback', table, tableFrom: table ? (pick ? 'pick' : 'lista') : undefined, verify: [], mentioned: table ? (pick ? pick.rec.members : want.keys) : ns.map((n) => sources[n - 1].key) });
|
||
};
|
||
let text = await round(messages);
|
||
const firstText = text;
|
||
let v = chatVerify(text, sources, { question, review: answer.review });
|
||
// One second chance, told what was wrong: the model mostly copies the right value when pointed at it.
|
||
if (v.hard) {
|
||
answer.status = 'Sprawdzam odpowiedź w źródłach i poprawiam…';
|
||
onUpdate(answer);
|
||
text = await round([...messages, { role: 'assistant', content: text }, { role: 'user', content: v.retry }]);
|
||
answer.retried = v.issues.filter((x) => x.level === 'bad').map((x) => x.raw);
|
||
v = chatVerify(text, sources, { question, review: answer.review });
|
||
// Not over a retry that passed with its [n]: that one is the answer.
|
||
if (v.hard || (!chatCitedNs(text).length && chatCitedNs(firstText).length)) { const kept = fallback(firstText); if (kept) return kept; }
|
||
// It still named its records: a follow-up's "ta umowa" points at them (Kodar: one inflected quote away).
|
||
if (v.hard) answer.mentioned = chatMentioned(text, sources, index);
|
||
if (v.hard) throw new Error(_tr('odpowiedź modelu nie zgadza się ze źródłami także po poprawce. ') + v.retry.replace(/ Odpowiedz ponownie.*$/, ''));
|
||
}
|
||
answer.verify = v.issues;
|
||
// Uncited, yet two or more checkable values and every one of them in one source: the model copied that
|
||
// source and dropped its [n] (Bielik, the grouped deadline list verbatim), so code puts the mark back.
|
||
const claims = chatCitedNs(text).length ? [] : chatClaims(text);
|
||
const from = claims.length >= 2 ? sources.findIndex((r) => { const f = chatFacts(r.text); return claims.every((c) => c.in(f)); }) : -1;
|
||
if (from >= 0) answer.content = text = text.replace(/\s*$/, ` [${from + 1}]`);
|
||
const cited = chatCitedNs(text);
|
||
// Without a [n] an answer comes from the model's memory, unless it says it found nothing or declines.
|
||
if (!cited.length &&!/nie znalazłem|nie masz dostępu|nie mam dostępu|pomagam|did not find|could not find|couldn't find|no access|don't have access/i.test(text)) {
|
||
// Uncited and nothing in the data matched the question well (a poem, small talk): out of scope, said by
|
||
// code. Uncited although records matched stays an error: that answer came from the model's memory.
|
||
// Uncited and saying nothing about the data, where only the search matched (q-wiersz: "kancelarii" pulled in
|
||
// Counsel), is a refusal in other words: said by code too. Where code itself picked records (the urgent list, a
|
||
// list, a named record) "nie znalazłem nic" would be false: shown is what code assembled. A card stays an error (T13).
|
||
const matched = att.length || named.length || resolved.length || law.length || topic.length || card || pick || want;
|
||
if ((!matched && found.top < CHAT_OFFTOPIC) || (!matched && bare(text))) {
|
||
return done(en ? CHAT_SCOPE_EN : CHAT_SCOPE, { coded: 'refusal', refs: [], verify: [] });
|
||
}
|
||
if (!card) { const kept = fallback(text); if (kept) return kept; }
|
||
throw new Error(_tr('model odpowiedział bez wskazania źródła, czyli z pamięci. Zapytaj jeszcze raz albo inaczej.'));
|
||
}
|
||
// The rest of a list the model shortened, built by code from the source's own members, each with its [n].
|
||
if (want && cited.length) {
|
||
const recs = want.keys.map((k) => index.byKey.get(k)).filter(Boolean);
|
||
if (recs.length > 1 && recs.every((r) => r.contract)) Object.assign(answer, { table: chatContractTable(recs.map((r) => r.contract), today, en), tableFrom: 'lista' });
|
||
else if (chatNamed(text, recs).length < recs.length) {
|
||
const nOf = (r) => { if (!sources.includes(r)) { sources.push(r); answer.refs.push(toRef(r, sources.length - 1)); } return sources.indexOf(r) + 1; };
|
||
const EN = { 'po terminie': 'overdue', 'w tym tygodniu': 'this week', później: 'later' };
|
||
const head = [...(en ? want.labels.map((l) => EN[l] || l) : want.labels), recs.length].join(', ');
|
||
text += `\n\n${en ? 'Full list' : 'Pełna lista'} (${head}): ` + recs.map((r) => `${r.title.replace(/^Termin: /, '')} [${nOf(r)}]`).join('; ') + '.';
|
||
answer.content = text;
|
||
}
|
||
}
|
||
// Which table code appended, in a field of its own: `coded` says who wrote the words, and a run that read the
|
||
// table's mark there counted a model's answer as code's (P8, 9.11).
|
||
if (pick && pick.table.rows.length) Object.assign(answer, { table: pick.table, tableFrom: 'pick' });
|
||
if (card && graf === 'tabela' && card.table.rows.length) Object.assign(answer, { table: card.table, tableFrom: 'karta' });
|
||
if (answer.table) answer.content = text = text + '\n\n' + chatTableText(answer.table);
|
||
answer.mentioned = chatMentioned(text, sources, index);
|
||
answer.quotes = chatQuotes(answer);
|
||
answer.status = '';
|
||
} catch (ex) {
|
||
if (ex.name === 'AbortError') throw ex;
|
||
Object.assign(answer, { failed: true, status: '', content: chatFailure(ex) });
|
||
}
|
||
return answer;
|
||
}
|
||
|
||
// A module's screen: inside Atrium's frame where the launcher has it, else the module's own page
|
||
// (Insider has no address in the catalogue, so no frame, yet its screens are on this origin).
|
||
const moduleHref = (slug, inner) => (state.launcher.some((m) => m.slug === slug && embeddable(m))
|
||
? frameHash(slug, inner) : new URL('../' + enc(slug) + '/#/' + inner, document.baseURI).href);
|
||
|
||
// The answer's [n] marks become links; under it the cited sources with their links and the passage the
|
||
// claim rests on, and every quotation checked against the fetched text: ✓ found there, ✗ not found.
|
||
const wordsOf = (s) => [...new Set(norm(s).match(/[\p{L}\d]{5,}/gu) || [])];
|
||
const rowScores = (rows, near) => { const ws = wordsOf(near); return rows.map((x) => ws.filter((w) => x.line.toLowerCase().includes(w)).length); };
|
||
// The rows (one record each) the answer talks about, in the source's order.
|
||
function citedRows(rows, near) {
|
||
const s = rowScores(rows, near);
|
||
const top = [...s].sort((a, b) => b - a)[Math.min(4, rows.length - 1)] || 1;
|
||
return rows.filter((_, i) => s[i] >= Math.max(top, 1)).slice(0, 8);
|
||
}
|
||
// The one row a sentence is about, or none: a tie ("Umowa" is in every contract) points nowhere.
|
||
function bestRow(rows, sentence) {
|
||
const s = rowScores(rows, sentence);
|
||
const max = Math.max(0, ...s);
|
||
return max && s.filter((x) => x === max).length === 1 ? rows[s.indexOf(max)] : null;
|
||
}
|
||
function passage(text, near, data) {
|
||
const ws = wordsOf(near);
|
||
if (data) return citedRows(String(text).split('\n').map((line) => ({ line })), near).map((x) => x.line.slice(0, 300)).join('\n');
|
||
const flat = String(text).replace(/\s+/g, ' ');
|
||
const low = flat.toLowerCase(); // same length as `flat`, so positions carry over to the original
|
||
let best = 0;
|
||
let score = -1;
|
||
for (const w of ws) {
|
||
for (let i = low.indexOf(w); i >= 0; i = low.indexOf(w, i + 1)) {
|
||
const win = low.slice(Math.max(0, i - 150), i + 250);
|
||
const s = ws.filter((x) => win.includes(x)).length;
|
||
if (s > score) { score = s; best = Math.max(0, i - 150); }
|
||
}
|
||
}
|
||
return (best ? '…' : '') + flat.slice(best, best + 600).trim() + '…';
|
||
}
|
||
function refLinks(r) {
|
||
const out = [];
|
||
if (r.inner) out.push(['otwórz w module', moduleHref(r.slug, r.inner)]);
|
||
/* doc/files/api come from other modules' results and are paths on this origin; anything else
|
||
(javascript:, data:, a foreign host) would run or leak in the platform's one origin. */
|
||
if (r.doc && sameOrigin(r.doc)) out.push(['plik', r.doc]);
|
||
if (r.files && sameOrigin(r.files)) out.push(['dokumenty sprawy', r.files]);
|
||
if (r.url && safeUrl(r.url) !== '#') out.push(['źródło oficjalne', r.url]);
|
||
if (r.api && r.api !== r.doc && sameOrigin(r.api)) out.push(['dane', r.api]);
|
||
return out;
|
||
}
|
||
const linkEl = (label, href) => {
|
||
const a = document.createElement('a');
|
||
a.href = href;
|
||
if (!href.startsWith('#')) { a.target = '_blank'; a.rel = 'noopener noreferrer'; }
|
||
a.textContent = _tr(label);
|
||
return a;
|
||
};
|
||
// The answer's tokens chatVerify did not find where the sentence points: ✗ in no source, ⚠ in another one.
|
||
function appendFlagged(el, piece, issues) {
|
||
const marks = issues.filter((x) => x.raw && piece.includes(x.raw));
|
||
if (!marks.length) { el.appendChild(document.createTextNode(piece)); return; }
|
||
const re = new RegExp('(' + marks.map((x) => x.raw.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')).join('|') + ')');
|
||
for (const bit of piece.split(re)) {
|
||
const x = marks.find((m) => m.raw === bit);
|
||
if (!x) { if (bit) el.appendChild(document.createTextNode(bit)); continue; }
|
||
const s = document.createElement('span');
|
||
s.className = 'ha-flag ' + x.level;
|
||
s.title = _tr(x.level === 'bad' ? 'Nie ma tego w pobranych źródłach' : 'Jest w pobranych źródłach, ale nie w tym, które wskazuje zdanie');
|
||
s.textContent = bit + (x.level === 'bad' ? ' ✗' : ' ⚠');
|
||
el.appendChild(s);
|
||
}
|
||
}
|
||
function renderCited(el, t) {
|
||
const byN = new Map(t.refs.map((r) => [r.n, r]));
|
||
const cited = [];
|
||
const near = new Map(); // n → the sentence that cites it, to cut the matching passage
|
||
// Shown as 1, 2, 3 in the order first cited: the model's own numbers ([1], [7]..[12]) read as sources missing.
|
||
const shown = new Map();
|
||
const disp = (n) => shown.get(n) || shown.set(n, shown.size + 1).get(n);
|
||
const pieces = t.content.split(/(\[\d+(?:\s*,\s*\d+)*\])/);
|
||
pieces.forEach((piece, i) => {
|
||
const nums = /^\[[\d,\s]+\]$/.test(piece) ? piece.match(/\d+/g).map(Number).filter((n) => byN.has(n)) : [];
|
||
if (!nums.length) { appendFlagged(el, piece, (t.verify || []).filter((x) => x.at === i)); return; }
|
||
for (const n of nums) {
|
||
if (!cited.includes(n)) cited.push(n);
|
||
const sentence = (pieces[i - 1] || '').split(/[.!?\n]/).slice(-2).join(' ');
|
||
near.set(n, (near.get(n) || '') + ' ' + sentence);
|
||
// [n] after a sentence about one record of a list opens that record, not the whole list.
|
||
const r = byN.get(n);
|
||
const opens = (x) => x && (x.inner || x.doc);
|
||
const row = r.rows && [bestRow(r.rows, sentence), ...citedRows(r.rows, t.content)].find(opens);
|
||
// A total (the ranking of firms) has no screen of its own: its [n] stays plain text.
|
||
const links = refLinks(row ? { ...row, slug: r.slug } : r);
|
||
const a = links.length ? linkEl('', links[0][1]) : document.createElement('span');
|
||
a.className = 'ha-ref';
|
||
a.textContent = '[' + disp(n) + ']';
|
||
el.appendChild(a);
|
||
}
|
||
});
|
||
const verdicts = t.quotes || chatQuotes(t); // while streaming, and for a turn saved before they were stored
|
||
if (!cited.length && !verdicts.length) return;
|
||
const box = document.createElement('div');
|
||
box.className = 'ha-sources';
|
||
const add = (cls, text) => { const d = document.createElement('div'); d.className = cls; d.textContent = text; box.appendChild(d); return d; };
|
||
if (verdicts.length) {
|
||
add('ha-sources-h', _tr('Cytaty'));
|
||
for (const { q, n, exact } of verdicts) {
|
||
add('ha-quote ' + (n ? 'ok' : 'bad'), (n ? '✓ ' : '✗ ') + '„' + q + '” ' +
|
||
(n ? _tr(exact === false ? '- w źródle, w innej odmianie' : '- dosłownie w źródle') + ' [' + disp(n) + ']' : _tr('- nie ma tego w pobranych źródłach')));
|
||
}
|
||
}
|
||
if (cited.length) add('ha-sources-h', _tr('Źródła'));
|
||
for (const n of cited) {
|
||
const r = byN.get(n);
|
||
const row = add('ha-source', '');
|
||
const head = document.createElement('div');
|
||
head.textContent = `[${disp(n)}] ${r.module}: ${r.title}` + (r.partial ? ' ' + _tr('(część listy, nie całość)') : '');
|
||
for (const [label, href] of refLinks(r)) head.append(' · ', linkEl(label, href));
|
||
const q = document.createElement('blockquote');
|
||
const own = verdicts.find((x) => x.n === n);
|
||
if (own) q.textContent = '„' + own.q + '”';
|
||
else if (r.rows && r.rows.length) {
|
||
// Each cited record on its own line, with the links to that record and its file.
|
||
for (const x of citedRows(r.rows, t.content)) {
|
||
const line = document.createElement('div');
|
||
line.textContent = x.line.slice(0, 300);
|
||
for (const [label, href] of refLinks({ ...x, slug: r.slug })) line.append(' · ', linkEl(label, href));
|
||
q.appendChild(line);
|
||
}
|
||
} else q.textContent = passage(r.text, r.data ? t.content : near.get(n), r.data);
|
||
row.append(head, q);
|
||
}
|
||
el.appendChild(box);
|
||
}
|
||
|
||
// The verdicts code computed for a contract's provisions, one line each, whatever the model made of them.
|
||
function renderReview(el, rv) {
|
||
const box = document.createElement('div');
|
||
box.className = 'ha-sources';
|
||
const h = document.createElement('div');
|
||
h.className = 'ha-sources-h';
|
||
h.textContent = rv.title;
|
||
box.appendChild(h);
|
||
for (const x of rv.rows) {
|
||
const d = document.createElement('div');
|
||
d.className = 'ha-quote' + (x.ok === true ? ' ok' : x.ok === false ? ' bad' : '');
|
||
d.textContent = (x.ok === true ? '✓ ' : x.ok === false ? '✗ ' : '? ') + x.label + (x.clauses.length ? ' (' + x.clauses.join(', ') + ')' : '') + ': ' + x.line;
|
||
for (const [label, href] of refLinks({ ...x, slug: 'insider' })) d.append(' · ', linkEl(label, href));
|
||
box.appendChild(d);
|
||
}
|
||
el.appendChild(box);
|
||
}
|
||
|
||
// The page around chatTurn: the turns on screen, streamed, kept in this tab.
|
||
async function homeAsk(model, question) {
|
||
if (!question) return;
|
||
// Marked before `turns` is taken below: the aborted call's own catch runs only after that.
|
||
if (chat.busy) Object.assign(chat.busy, { aborted: true, status: '', content: chat.busy.content || _tr('Przerwane: zadano następne pytanie.') });
|
||
if (chat.ctl) chat.ctl.abort();
|
||
if (model !== chat.model) chat.turns = []; // another model starts another conversation
|
||
chat.model = model;
|
||
const turns = chat.turns.slice();
|
||
chat.turns.push({ role: 'user', content: question });
|
||
const answer = { role: 'assistant', content: '', status: 'Zbieram dane z modułów…', refs: [], trace: [] };
|
||
chat.turns.push(answer);
|
||
chat.busy = answer; // aria-busy until this answer is whole, streaming included
|
||
$('homeQ').value = '';
|
||
homeQuery($('homeQ'));
|
||
chatRender(true);
|
||
chat.ctl = new AbortController();
|
||
try {
|
||
await loadChatModules();
|
||
// Built with the asker's session, so never reused for somebody who signed in after them.
|
||
if (!chat.index || chat.index.user !== state.user.id) chat.index = await chatIndex();
|
||
await chatTurn({ model, question, turns, index: chat.index, answer, onUpdate: () => chatRender() });
|
||
} catch (ex) {
|
||
if (ex.name === 'AbortError') return;
|
||
Object.assign(answer, { failed: true, status: '', content: chatFailure(ex) });
|
||
}
|
||
chat.busy = null;
|
||
chatSave();
|
||
chatRender();
|
||
// The history is rebuilt per chunk, so a screen reader hears only the finished answer, once.
|
||
const say = $('homeSay');
|
||
if (say) say.textContent = answer.content;
|
||
}
|
||
|
||
/* The home page: search across the modules, then the numbers — Atrium's own and the modules' —
|
||
then, for an administrator, what needs doing. Each thing is shown once on the platform: your apps
|
||
are the sidebar, your requests the catalogue's tab, module health Administracja › Moduły. A failed
|
||
secondary read leaves its section out; it never takes the page down with it. */
|
||
async function viewHome(C) {
|
||
setCrumb([{ label: 'Strona główna' }]);
|
||
const admin = isAdmin() ? await adminOverviewHtml().catch(() => '') : '';
|
||
const name = state.user.full_name || state.user.email;
|
||
const welcome = setting('welcome_message');
|
||
/* One account, so a module never asks again. Saying so here is not decoration: the old copy
|
||
promised a second sign-in, and a line that tells people to expect a password prompt is exactly
|
||
how a working single sign-on gets reported as broken. */
|
||
const hint = setting('launcher_open_mode') === 'same_tab'
|
||
? 'Moduły otwierają się w tej karcie. Jesteś już zalogowany — to jedno konto dla całej platformy.'
|
||
: 'Moduły otwierają się w nowej karcie. Jesteś już zalogowany — to jedno konto dla całej platformy.';
|
||
|
||
const searchable = homeModules();
|
||
const gw = await loadModels();
|
||
const models = gw && gw.configured ? gw.models : [];
|
||
const saved = savedModelPick();
|
||
const picked = models.some((m) => m.id === saved) ? saved : '';
|
||
/* Model server off: say so instead of dropping the picker, or the feature looks gone. */
|
||
const picker = models.length ? `<label class="home-model"><span>Model AI</span>
|
||
<span id="homeModelIcon">${familyIcon(picked)}</span>
|
||
<select id="homeModel" onchange="homeModelChange(this)">${modelOptions(models, picked, 'Tylko szukaj')}</select></label>`
|
||
: gw && gw.configured ? `<label class="home-model"><span>Model AI</span>
|
||
<select id="homeModel" disabled><option value="">Serwer modeli wyłączony</option></select></label>` : '';
|
||
/* legalwork's welcome: the mark, a two-tone line, one sentence, then the places to start. */
|
||
C.innerHTML = `<div class="home">
|
||
<div class="home-mark">${document.querySelector('.brand .logo').outerHTML}</div>
|
||
<h1 class="home-title"><span><span>Witaj,</span> ${dat(name)}.</span> <span class="home-q">Od czego zaczynamy?</span></h1>
|
||
<div class="home-sub">${esc(hint)}</div>`
|
||
+ (welcome ? `<div class="banner welcome" data-no-i18n>${esc(welcome)}</div>` : '')
|
||
// The conversation reads downwards, as a chat does: history first, the composer under it.
|
||
+ (searchable.length || picker ? `<div id="homeAnswer" class="home-answer hidden"></div>
|
||
<div id="homeSay" class="sr-only" aria-live="polite" data-no-i18n></div>
|
||
<form class="home-box" role="search" onsubmit="homeSubmit(event)">
|
||
<div class="home-input">
|
||
<div id="homeFiles" class="home-files hidden"></div>
|
||
<div class="home-line">${svg(ICN.search, 20)}
|
||
<textarea id="homeQ" rows="1" autocomplete="off" placeholder="${picked ? 'Zapytaj asystenta albo szukaj w modułach…' : 'Szukaj spraw, umów, plików i kancelarii…'}"
|
||
aria-label="${picked ? 'Zapytaj asystenta' : 'Szukaj we wszystkich modułach'}" oninput="homeQuery(this)" onkeydown="homeKey(event)"></textarea></div>
|
||
<div class="home-scope"><span class="home-tools">${picker}<button class="btn sm ghost home-attach" type="button" onclick="$('homeFile').click()" aria-label="Dołącz plik" title="Dołącz plik (PDF, DOCX, TXT, MD, CSV)">${svg(ICN.paperclip, 16)}</button>
|
||
<input id="homeFile" class="hidden" type="file" multiple accept=".pdf,.docx,.txt,.md,.csv" onchange="homeAttach(this.files); this.value = ''"><button class="btn sm ghost home-new" type="button" onclick="chatReset()">Nowa rozmowa</button>
|
||
<button class="home-send" type="submit" aria-label="${picked ? 'Wyślij' : 'Szukaj'}" onclick="homeSendClick(event)">${svg(ICN.arrowright, 18)}</button></span></div></div>
|
||
</form>
|
||
<div id="homeResults" class="home-results hidden" aria-live="polite"></div>` : '')
|
||
+ '<div id="homeKeys"></div>'
|
||
+ '<div id="homeStats" class="home-stats" aria-live="polite"></div>'
|
||
+ '<div id="homeModStats" class="home-stats" aria-live="polite"></div>'
|
||
/* Your apps are the sidebar; the home page mentions them only when there are none. */
|
||
+ (state.launcher.length ? ''
|
||
: `<div class="empty"><div>Nie masz jeszcze żadnych aplikacji.</div>
|
||
<div style="margin-top:12px"><a class="btn" href="#/marketplace">Przeglądaj katalog</a></div></div>`)
|
||
+ (admin ? `<div class="home-admin">${admin}</div>` : '')
|
||
+ '</div>';
|
||
chatRestore();
|
||
chatRender(true);
|
||
chatFilesRender();
|
||
loadHomeKeys();
|
||
loadHomeStats();
|
||
loadModuleStats();
|
||
}
|
||
|
||
/* A provider that calls with the asker's OWN key (key_mode = "user") is useless until they store one,
|
||
and the only place to do that is Settings → My model keys. Say so on Home, where the picker is,
|
||
instead of letting the first question fail. Quiet when nothing is missing or the call fails. */
|
||
async function loadHomeKeys() {
|
||
let r;
|
||
try { r = await api('GET', '/me/model-keys'); } catch { return; }
|
||
const box = $('homeKeys');
|
||
if (!box) return; // navigated away meanwhile
|
||
const missing = (r.providers || []).filter((p) => !p.key_prefix);
|
||
if (!missing.length || !r.keys_writable) return;
|
||
box.innerHTML = `<div class="banner"><span>Twój własny klucz API jest potrzebny dla:</span>
|
||
<span data-no-i18n>${missing.map((p) => esc(p.name)).join(', ')}</span>.
|
||
<a href="#/my-keys">Dodaj klucz</a></div>`;
|
||
localize(box);
|
||
}
|
||
|
||
/* The home page's numbers: yours for everybody, the platform's for an administrator. Loaded after
|
||
the page is drawn, so a slow query never holds up the search box; a failure just leaves it out. */
|
||
async function loadHomeStats() {
|
||
const box = $('homeStats');
|
||
if (!box) return;
|
||
let st;
|
||
try { st = await api('GET', '/home/stats'); } catch { return; }
|
||
if (!$('homeStats')) return; // navigated away meanwhile
|
||
const m = st.mine, p = st.platform;
|
||
const tile = (label, value, href, warn) => `<a class="stat${warn ? ' warn' : ''}" href="${href}">`
|
||
+ `<span class="stat-v">${esc(String(value))}</span><span class="stat-l">${esc(label)}</span></a>`;
|
||
const tiles = [
|
||
tile('Aktywne sesje', m.sessions, '#/tokens'),
|
||
tile('Tokeny aplikacji', m.tokens, '#/tokens'),
|
||
tile('Twoje wnioski w toku', m.pending_requests, '#/requests', m.pending_requests > 0),
|
||
];
|
||
if (p) tiles.push(
|
||
tile('Aktywni dziś', `${p.active_today} / ${p.users}`, '#/admin/users'),
|
||
tile('Aktywni w tym tygodniu', p.active_week, '#/admin/users'));
|
||
const charts = [chartCard('Twoja aktywność', 'zdarzenia dziennie, ostatnie 14 dni', m.activity)];
|
||
if (p) {
|
||
charts.push(chartCard('Logowania na platformie', 'nowe sesje dziennie, ostatnie 14 dni', p.signins),
|
||
chartCard('Zdarzenia na platformie', 'wpisy w dzienniku dziennie, ostatnie 14 dni', p.events));
|
||
if (p.top_actions.length) {
|
||
const max = Math.max(...p.top_actions.map((a) => a.n));
|
||
charts.push(`<div class="card chart"><div class="chart-h"><b>Najczęstsze zdarzenia</b><span>ostatnie 7 dni</span></div>
|
||
<div class="hbars">${p.top_actions.map((a) => `<div class="hbar"><code data-no-i18n>${esc(a.action)}</code>
|
||
<span class="hbar-t"><i style="width:${Math.max(4, Math.round(a.n / max * 100))}%"></i></span><b>${a.n}</b></div>`).join('')}</div>
|
||
<a class="chart-more" href="#/admin/audit">Dziennik zdarzeń</a></div>`);
|
||
}
|
||
}
|
||
box.innerHTML = `<div class="home-label"><span>W skrócie</span></div><div class="stats">${tiles.join('')}</div>`
|
||
+ `<div class="charts">${charts.join('')}</div>`;
|
||
localize(box);
|
||
}
|
||
|
||
/* Numbers from the modules themselves, read from the dashboards they already serve: one origin
|
||
and one account, so the browser asks each module directly with the same session cookie and
|
||
Atrium's backend is not involved. Each figure is the module's own permission-filtered count —
|
||
what the reader may open, never more. A module that is slow (4 s), down or refuses simply
|
||
contributes nothing. `inner` is the module's own route, opened in the frame. */
|
||
const MODULE_STATS = {
|
||
sygna: (d) => {
|
||
const c = d.cards || {};
|
||
const h = Math.floor((c.minutes_this_week || 0) / 60), mm = String((c.minutes_this_week || 0) % 60).padStart(2, '0');
|
||
return [
|
||
{ label: 'Najbliższe terminy', value: c.deadlines_due, inner: 'deadlines' },
|
||
{ label: 'Po terminie', value: c.deadlines_overdue, inner: 'deadlines', warn: c.deadlines_overdue > 0 },
|
||
{ label: 'Moje sprawy', value: c.my_matters, inner: 'matters' },
|
||
{ label: 'Czas w tym tygodniu', value: `${h}:${mm}`, inner: 'time' },
|
||
{ label: 'Korespondencja do rozdzielenia', value: c.inbox, inner: 'inbox', warn: c.undated_service > 0 },
|
||
];
|
||
},
|
||
galena: (d) => [
|
||
{ label: 'Do zatwierdzenia', value: (d.approvals_waiting || []).length, inner: 'drafts', warn: (d.approvals_waiting || []).length > 0 },
|
||
{ label: 'Otwarte szkice', value: (d.cards || {}).open_drafts, inner: 'drafts' },
|
||
{ label: 'Projekty', value: (d.cards || {}).projects, inner: '' },
|
||
],
|
||
};
|
||
|
||
async function loadModuleStats() {
|
||
const mods = state.launcher.filter((m) => m.has_access && embeddable(m));
|
||
if (!mods.length) return;
|
||
const got = await Promise.all(mods.map(async (m) => {
|
||
const ctl = new AbortController();
|
||
const t = setTimeout(() => ctl.abort(), 4000);
|
||
try {
|
||
const base = new URL('api/v1/', m.url.replace(/\/?$/, '/')).pathname;
|
||
const opts = { credentials: 'same-origin', headers: { Accept: 'application/json' }, signal: ctl.signal };
|
||
// dredd-core's stats contract first (every module since the Compass split): tiles counted for
|
||
// the caller, each equal to the list its link opens. A module without it falls back to the
|
||
// dashboard mapping above, if it has one.
|
||
let tiles = null;
|
||
const st = await fetch(base + 'stats', opts);
|
||
if (st.ok) {
|
||
const d = await st.json();
|
||
if (d && Array.isArray(d.tiles)) tiles = d.tiles.map((x) => ({ label: x.label, value: x.count, inner: x.link }));
|
||
}
|
||
if (!tiles && MODULE_STATS[m.slug]) {
|
||
const r = await fetch(base + 'dashboard', opts);
|
||
if (!r.ok) return null;
|
||
tiles = MODULE_STATS[m.slug](await r.json());
|
||
}
|
||
if (!tiles) return null;
|
||
tiles = tiles.filter((x) => x.value !== undefined && x.value !== null);
|
||
return tiles.length ? { m, tiles } : null;
|
||
} catch { return null; } finally { clearTimeout(t); }
|
||
}));
|
||
const box = $('homeModStats');
|
||
const ok = got.filter(Boolean);
|
||
if (!box || !ok.length) return;
|
||
box.innerHTML = '<div class="home-label"><span>Z modułów</span></div>' + ok.map(({ m, tiles }) =>
|
||
`<div class="modstats"><div class="modstats-h" data-no-i18n>${moduleIcon(m, 18)}<span>${esc(m.name)}</span></div>
|
||
<div class="stats">${tiles.map((x) => `<a class="stat${x.warn ? ' warn' : ''}" href="${esc(frameHash(m.slug, x.inner))}">`
|
||
+ `<span class="stat-v">${esc(String(x.value))}</span><span class="stat-l">${esc(x.label)}</span></a>`).join('')}</div></div>`).join('');
|
||
localize(box);
|
||
}
|
||
|
||
/* A 14-day column chart as inline SVG: no library, the theme's own colours, a title per bar. */
|
||
function chartCard(title, sub, series) {
|
||
const total = series.reduce((a, d) => a + d.n, 0);
|
||
const max = Math.max(1, ...series.map((d) => d.n));
|
||
const W = 280, H = 72, gap = 4, bw = (W - gap * (series.length - 1)) / series.length;
|
||
const bars = series.map((d, i) => {
|
||
const h = d.n ? Math.max(3, Math.round(d.n / max * H)) : 2;
|
||
return `<rect x="${(i * (bw + gap)).toFixed(1)}" y="${H - h}" width="${bw.toFixed(1)}" height="${h}" rx="2"`
|
||
+ ` class="${d.n ? 'bar' : 'bar zero'}"><title>${esc(d.day)}: ${d.n}</title></rect>`;
|
||
}).join('');
|
||
return `<div class="card chart"><div class="chart-h"><b>${esc(title)}</b><span>${esc(sub)}</span></div>
|
||
<div class="chart-v">${total}</div>
|
||
<svg class="spark" viewBox="0 0 ${W} ${H}" preserveAspectRatio="none" role="img" aria-label="${esc(title)}: ${total}">${bars}</svg>
|
||
<div class="chart-x"><span>${esc(series[0].day.slice(5))}</span><span>${esc(series[series.length - 1].day.slice(5))}</span></div></div>`;
|
||
}
|
||
|
||
/* ── marketplace ────────────────────────────────────────────────────────── */
|
||
function accessChip(m) {
|
||
if (m.request_pending) return '<span class="chip warn">Wniosek wysłany</span>';
|
||
if (m.has_access && m.status !== 'coming_soon' && !m.configured) return '<span class="chip">Nieskonfigurowany</span>';
|
||
if (m.launchable) return '<span class="chip ok">Masz dostęp</span>';
|
||
return '';
|
||
}
|
||
|
||
function marketCard(m) {
|
||
return `<a class="mcard" href="#/marketplace/${enc(m.slug)}">
|
||
<div class="mtop">${moduleIcon(m, 44)}<div class="mtxt">
|
||
<div class="mname">${dat(m.name)}</div>
|
||
${m.category ? `<div class="tiny faint">${dat(m.category)}</div>` : ''}</div></div>
|
||
${m.tagline ? `<div class="mtag">${dat(m.tagline)}</div>` : ''}
|
||
<div class="row mchips">${statusChip(m.status)}${accessChip(m)}${isAdmin() && m.availability ? availChip(m.availability) : ''}</div>
|
||
</a>`;
|
||
}
|
||
|
||
async function viewMarketplace(C, q) {
|
||
const d = await api('GET', withQuery('/marketplace', { q: q.q, category: q.category }));
|
||
setCrumb([{ label: 'Moduły' }]);
|
||
|
||
const catHref = (c) => withQuery('#/marketplace', { q: q.q, category: c });
|
||
const contact = setting('support_contact');
|
||
C.innerHTML = pageHead('Moduły', 'Aplikacje dostępne w twojej organizacji') + catalogTabs('market')
|
||
+ `<div class="toolbar">
|
||
<input type="search" id="mq" placeholder="Szukaj modułów…" aria-label="Szukaj modułów" value="${esc(q.q || '')}" />
|
||
<div class="row cats">
|
||
<a class="chip ${!q.category ? 'on' : ''}" href="${esc(catHref(''))}">Wszystkie</a>
|
||
${d.categories.map((c) => `<a class="chip ${q.category === c ? 'on' : ''}" href="${esc(catHref(c))}">${dat(c)}</a>`).join('')}
|
||
</div></div>`
|
||
+ (d.modules.length
|
||
? `<div class="mcards">${d.modules.map(marketCard).join('')}</div>`
|
||
: '<div class="empty">Brak modułów.</div>')
|
||
+ (contact ? `<div class="faint tiny" style="margin-top:16px"><span>Potrzebujesz dostępu? Kontakt:</span> ${dat(contact)}</div>` : '');
|
||
|
||
onFilter($('mq'), (v) => { location.hash = withQuery('#/marketplace', { q: v, category: q.category }); });
|
||
}
|
||
|
||
async function viewModule(C, slug) {
|
||
const m = await api('GET', '/marketplace/' + enc(slug));
|
||
setCrumb([{ label: 'Moduły', href: '#/marketplace' }, { label: m.name, data: true }]);
|
||
|
||
const acts = [];
|
||
if (m.launchable) acts.push(`<a class="btn primary" ${launchAttrs(m)}>${svg(ICN.external)}<span>Otwórz</span></a>`);
|
||
if (m.can_request) acts.push(`<button class="btn primary" onclick="openRequest('${esc(m.slug)}')">${svg(ICN.send)}<span>Poproś o dostęp</span></button>`);
|
||
if (isAdmin()) acts.push(`<a class="btn" href="#/admin/modules/${enc(m.slug)}">${svg(ICN.settings)}<span>Zarządzaj</span></a>`);
|
||
|
||
let note = '';
|
||
if (m.status === 'coming_soon') note = '<div class="banner">Moduł będzie dostępny wkrótce.</div>';
|
||
else if (m.request_pending) note = '<div class="banner warn">Twój wniosek czeka na decyzję administratora.</div>';
|
||
else if (m.has_access && !m.configured) note = '<div class="banner warn">Ten moduł nie ma jeszcze adresu w tej instancji — administrator musi go skonfigurować.</div>';
|
||
else if (!m.has_access && !m.can_request) note = '<div class="banner">Dostęp do tego modułu przyznaje administrator.</div>';
|
||
else if (m.launchable) note = '<div class="banner">Atrium otwiera moduł — na razie logujesz się do niego osobno, jego własnym kontem.</div>';
|
||
|
||
const contact = setting('support_contact');
|
||
C.innerHTML = `<div class="card mhead">
|
||
${moduleIcon(m, 72)}
|
||
<div class="mhtxt"><h2>${dat(m.name)}</h2>
|
||
${m.tagline ? `<div class="faint">${dat(m.tagline)}</div>` : ''}
|
||
<div class="row" style="margin-top:8px">${m.category ? `<span class="chip">${dat(m.category)}</span>` : ''}${statusChip(m.status)}${accessChip(m)}${isAdmin() && m.availability ? availChip(m.availability) : ''}</div>
|
||
</div>
|
||
<div class="acts">${acts.join('')}</div>
|
||
</div>`
|
||
+ (note ? `<div style="margin-top:14px">${note}</div>` : '')
|
||
+ (m.description ? `<div class="card" style="margin-top:14px"><h3>Opis</h3><div class="prose" data-no-i18n>${esc(m.description)}</div></div>` : '')
|
||
+ (!m.has_access && contact ? `<div class="faint tiny" style="margin-top:14px"><span>Potrzebujesz dostępu? Kontakt:</span> ${dat(contact)}</div>` : '');
|
||
}
|
||
|
||
function openRequest(slug) {
|
||
modal('Poproś o dostęp', '',
|
||
`<label class="field">Notatka<textarea id="rqNote" maxlength="1000" placeholder="Po co ci ten moduł? (opcjonalnie)"></textarea></label>`,
|
||
`<button class="btn" onclick="closeModal()">Anuluj</button>
|
||
<button class="btn primary" onclick="sendRequest('${esc(slug)}')">Wyślij wniosek</button>`);
|
||
}
|
||
|
||
function sendRequest(slug) {
|
||
mutate('POST', `/marketplace/${enc(slug)}/requests`, { note: $('rqNote').value || null }, { done: 'Wniosek wysłany.' });
|
||
}
|
||
|
||
function catalogTabs(on) {
|
||
const tab = (k, href, label) => `<a class="${on === k ? 'on' : ''}" href="${href}"${on === k ? ' aria-current="page"' : ''}>${esc(label)}</a>`;
|
||
return `<nav class="tabs">${tab('market', '#/marketplace', 'Katalog')}${tab('requests', '#/requests', 'Moje wnioski')}`
|
||
+ `${isAdmin() ? tab('admin', '#/admin/modules', 'Zarządzanie') : ''}</nav>`;
|
||
}
|
||
|
||
async function viewMyRequests(C) {
|
||
const rows = await api('GET', '/me/access-requests');
|
||
setCrumb([{ label: 'Moduły', href: '#/marketplace' }, { label: 'Moje wnioski' }]);
|
||
C.innerHTML = pageHead('Moduły', 'Aplikacje dostępne w twojej organizacji') + catalogTabs('requests')
|
||
+ (rows.length ? `<div class="card"><div class="tablewrap"><table class="rt"><thead><tr>
|
||
<th>Moduł</th><th>Status</th><th>Wysłano</th><th>Decyzja</th>
|
||
</tr></thead><tbody>${rows.map((r) => `<tr class="click" onclick="location.hash='#/marketplace/${enc(r.module.slug)}'">
|
||
<td><div><div class="cell">${moduleIcon(r.module, 28)}<a href="#/marketplace/${enc(r.module.slug)}" onclick="event.stopPropagation()">${dat(r.module.name)}</a></div>${r.note ? `<div class="faint tiny">${dat(r.note)}</div>` : ''}</div></td>
|
||
<td${lbl('Status')}>${reqChip(r.status)}</td>
|
||
<td class="faint tiny"${lbl('Wysłano')}>${fmtDateTime(r.created_at)}</td>
|
||
<td class="tiny"${lbl('Decyzja')}><div>${r.decided_at ? fmtDateTime(r.decided_at) : '—'}${r.decision_note ? `<div class="faint">${dat(r.decision_note)}</div>` : ''}</div></td>
|
||
</tr>`).join('')}</tbody></table></div></div>`
|
||
: '<div class="empty">Nie wysłano jeszcze żadnych wniosków.</div>');
|
||
}
|
||
|
||
/* ── connected apps (app tokens) ─────────────────────────────────────────────
|
||
A desktop or CLI client — GalenaConnect and its siblings — signs in once and then holds a named
|
||
token instead of a password. This screen is where those come from, and it is HERE rather than in
|
||
each module's own console because it cannot be anywhere else: a `session` row carries a user id
|
||
and a token hash, so a role that can insert one can mint a credential for the administrator. No
|
||
module holds that INSERT, which is exactly why the three module consoles kept *list* and *revoke*
|
||
and lost *Create token* at the cutover. Until this screen existed, the replacement for the button
|
||
they lost was a curl command, which is not a replacement.
|
||
|
||
The thing this UI has to say out loud, and says on both screens where it matters: a token
|
||
authenticates in EVERY module. `galena_pat_…` records where it was minted, not where it works —
|
||
one `session` row, one platform, one credential — and what limits it is each module's own
|
||
permission grants, exactly as they limit the person holding it. */
|
||
const SCOPE_LABEL = { read_write: 'odczyt i zapis', read: 'tylko odczyt' };
|
||
|
||
/* The catalogue as an ORDINARY user may see it — deliberately not `state.modules`, which is the
|
||
administrator's `/admin/modules` list. Everyone reaches this screen, and the server mints for
|
||
whatever `marketplace.visible_module` accepts, which is precisely what `/marketplace` returns: so
|
||
the picker offers exactly what the mint will take, for an administrator and for everybody else.
|
||
Being *offered* a module is deliberately not required — an offer is not a lock anywhere else on
|
||
this platform, and making it one here would be the only place it was. */
|
||
async function ensureCatalogue() {
|
||
if (!state._catalogue) {
|
||
try { state._catalogue = (await api('GET', '/marketplace')).modules; }
|
||
catch { state._catalogue = []; }
|
||
}
|
||
return state._catalogue;
|
||
}
|
||
|
||
/* Where a token was minted, read back out of its own prefix: `session` has no module column, and
|
||
the prefix is the only record there is. An unknown slug still renders as itself — the credential
|
||
is real, and a module that has since left the catalogue must not make one invisible. */
|
||
function tokenOrigin(t) {
|
||
const m = /^(.+?)_pat_/.exec(t.token_prefix || '');
|
||
const slug = m ? m[1] : '';
|
||
if (!slug) return '';
|
||
if (slug === hubSlug()) return setting('instance_name') || 'Atrium';
|
||
const known = (state._catalogue || []).find((x) => x.slug === slug);
|
||
return known ? known.name : slug;
|
||
}
|
||
|
||
/* Has anything actually signed in with this token? `last_seen_at` is stamped when the row is
|
||
created, so a token minted a minute ago and never used would otherwise report a "last used" a
|
||
minute ago — the opposite of what this column is for. The two stamps are not identical either
|
||
(`created_at` is the database's transaction clock, `last_seen_at` is Python's, moments apart and
|
||
in either order), so the test is a gap rather than an inequality: under a minute is the mint
|
||
itself. Nothing is lost by the slack — core only rewrites `last_seen_at` when it is minutes
|
||
stale, so a real use appears as soon as it can appear at all. */
|
||
const tokenUsed = (t) => !!(t.last_used_at && t.created_at
|
||
&& new Date(t.last_used_at) - new Date(t.created_at) > 60000);
|
||
|
||
/* Revoked rows stay in the list on purpose (core lists them last): someone who revokes a token
|
||
needs to see that it really is gone, which an empty row silently disappearing does not show. */
|
||
function tokenState(t) {
|
||
if (t.revoked_at) return '<span class="chip err">Odwołany</span>';
|
||
if (t.expires_at && new Date(t.expires_at) <= new Date()) return '<span class="chip warn">Wygasł</span>';
|
||
return '<span class="chip ok">Aktywny</span>';
|
||
}
|
||
|
||
/* A server that predates this key sends no `app_tokens` at all; absent must mean "on", or the
|
||
console would hide the only way to mint a token on an instance that mints them happily. */
|
||
const tokenPolicy = () => state.config.app_tokens || {};
|
||
const tokensEnabled = () => tokenPolicy().enabled !== false;
|
||
|
||
async function viewTokens(C) {
|
||
const [tokens] = await Promise.all([api('GET', '/me/tokens'), ensureCatalogue()]);
|
||
// Kept so the revoke dialog can name a token from state instead of interpolating its name into
|
||
// markup — the same reason the module pages look a row up rather than passing it around.
|
||
state._tokens = tokens;
|
||
setCrumb([{ label: 'Ustawienia' }, { label: 'Połączone aplikacje' }]);
|
||
const live = tokens.filter((t) => !t.revoked_at);
|
||
const reach = sharesIdentity()
|
||
? 'Token działa w każdym module platformy — przedrostek mówi, gdzie powstał, a nie gdzie działa.'
|
||
: 'Token działa w tej instancji i jest równoważny twojemu hasłu, więc traktuj go jak hasło.';
|
||
|
||
const rows = tokens.map((t) => `<tr>
|
||
<td><div>${t.name ? dat(t.name) : 'Bez nazwy'}
|
||
<div class="mono tiny faint wrap">${dat((t.token_prefix || '') + '…')} · <span>utworzony</span> ${esc(fmtDateTime(t.created_at))}</div></div></td>
|
||
<td${lbl('Utworzony w')}>${tokenOrigin(t) ? `<span class="chip">${dat(tokenOrigin(t))}</span>` : '<span class="faint">—</span>'}</td>
|
||
<td${lbl('Zakres')}><span class="chip">${esc(SCOPE_LABEL[t.scope] || t.scope)}</span></td>
|
||
<td class="faint tiny"${lbl('Ostatnio użyty')}>${tokenUsed(t) ? esc(fmtDateTime(t.last_used_at)) : '<span>nigdy</span>'}</td>
|
||
<td class="faint tiny col-opt"${lbl('Wygasa')}>${esc(fmtDateTime(t.expires_at))}</td>
|
||
<td${lbl('Status')}>${tokenState(t)}</td>
|
||
<td class="acts-cell shrink">${t.revoked_at ? ''
|
||
: `<button class="btn sm danger" onclick="revokeToken('${esc(t.id)}')">Odwołaj</button>`}</td>
|
||
</tr>`).join('');
|
||
|
||
C.innerHTML = pageHead('Połączone aplikacje', 'Aplikacje i skrypty, które logują się twoim kontem bez hasła.',
|
||
tokensEnabled() ? `<button class="btn primary" onclick="openTokenNew()">${svg(ICN.plus)}<span>Nowy token</span></button>` : '')
|
||
+ (tokensEnabled() ? '' : '<div class="banner warn">Tokeny są wyłączone na tej instancji.</div>')
|
||
+ `<div class="card"><h3>Twoje tokeny<span class="n">${live.length}</span></h3>
|
||
<div class="faint tiny" style="margin-bottom:10px">${esc(reach)}</div>`
|
||
+ (tokens.length ? `<div class="tablewrap"><table class="rt"><thead><tr>
|
||
<th>Nazwa</th><th>Utworzony w</th><th>Zakres</th><th>Ostatnio użyty</th>
|
||
<th class="col-opt">Wygasa</th><th>Status</th><th></th>
|
||
</tr></thead><tbody>${rows}</tbody></table></div>`
|
||
: '<div class="empty">Żadna aplikacja nie jest połączona.</div>')
|
||
+ `<div class="faint tiny" style="margin-top:10px">Odwołanie działa natychmiast i tylko na ten jeden token. Zmiana twojego hasła odwołuje wszystkie.</div>
|
||
</div>`;
|
||
}
|
||
|
||
/* ── skills and agents ──
|
||
"Moje" is what you own (personal or published), "Firmowe" is everything published to the firm, so
|
||
a firm skill you wrote is in both. A firm entry with no current version is one whose first
|
||
publication still waits for an administrator: others get it only after that. */
|
||
function skillTabs(on) {
|
||
const tab = (k, href, label) => `<a class="${on === k ? 'on' : ''}" href="${href}"${on === k ? ' aria-current="page"' : ''}>${esc(label)}</a>`;
|
||
return `<nav class="tabs">${tab('mine', '#/skills', 'Moje')}${tab('firm', '#/skills/firm', 'Firmowe')}</nav>`;
|
||
}
|
||
|
||
function skillChips(x) {
|
||
return `<span class="chip">${esc(x.scope === 'firm' ? 'Firmowy' : 'Osobisty')}</span>`
|
||
+ (x.scope === 'firm' && !x.current_version_id ? ' <span class="chip warn">Czeka na zgodę</span>' : '')
|
||
+ (x.status === 'archived' ? ' <span class="chip">Zarchiwizowany</span>' : '')
|
||
+ (x.origin === 'imported' ? ' <span class="chip">Zaimportowany</span>' : '');
|
||
}
|
||
|
||
async function viewSkills(C, tab) {
|
||
const [skills, agents] = await Promise.all([api('GET', '/skills'), api('GET', '/agents')]);
|
||
const pick = (xs) => xs.filter((x) => (tab === 'firm' ? x.scope === 'firm' : x.mine));
|
||
setCrumb([{ label: 'Skille i agenci', href: '#/skills' }, { label: tab === 'firm' ? 'Firmowe' : 'Moje' }]);
|
||
const table = (xs, sub, empty, href) => (xs.length
|
||
? `<div class="tablewrap"><table class="rt"><thead><tr><th>Nazwa</th><th>Zasięg</th></tr></thead><tbody>${
|
||
xs.map((x) => `<tr><td><div>${href ? `<a href="${esc(href(x))}">${dat(x.name)}</a>` : dat(x.name)}${sub(x)}</div></td><td${lbl('Zasięg')}>${skillChips(x)}</td></tr>`).join('')
|
||
}</tbody></table></div>`
|
||
: `<div class="empty">${esc(empty)}</div>`);
|
||
const mine = tab !== 'firm';
|
||
const s = pick(skills);
|
||
const a = pick(agents);
|
||
C.innerHTML = pageHead('Skille i agenci', 'Instrukcje i asystenci, z których korzystasz ty i twoja firma.',
|
||
`<button class="btn" onclick="openImport()"><span>Importuj ZIP</span></button>
|
||
<button class="btn" onclick="openAgentEditor()">${svg(ICN.plus)}<span>Nowy agent</span></button>
|
||
<button class="btn primary" onclick="openSkillEditor()">${svg(ICN.plus)}<span>Nowy skill</span></button>`)
|
||
+ skillTabs(tab)
|
||
+ `<div class="card"><h3>Skille<span class="n">${s.length}</span></h3>${
|
||
table(s, (x) => `<div class="mono tiny faint wrap">${dat(x.slug)}</div>`,
|
||
mine ? 'Nie masz jeszcze żadnego skilla.' : 'Firma nie ma jeszcze żadnego skilla.',
|
||
(x) => '#/skills/skill/' + enc(x.id))}</div>`
|
||
+ `<div class="card"><h3>Agenci<span class="n">${a.length}</span></h3>${
|
||
table(a, () => '', mine ? 'Nie masz jeszcze żadnego agenta.' : 'Firma nie ma jeszcze żadnego agenta.',
|
||
(x) => '#/skills/agent/' + enc(x.id))}</div>`;
|
||
}
|
||
|
||
/* Line diff by longest common subsequence, after trimming the common head and tail so the table only
|
||
covers what changed. ponytail: O(n·m) table — fine for one skill (≤ 30 000 characters); Myers'
|
||
algorithm if bodies ever reach many thousands of changed lines. */
|
||
function lineDiff(a, b) {
|
||
const x = a.split('\n');
|
||
const y = b.split('\n');
|
||
let h = 0;
|
||
while (h < x.length && h < y.length && x[h] === y[h]) h++;
|
||
let t = 0;
|
||
while (t < x.length - h && t < y.length - h && x[x.length - 1 - t] === y[y.length - 1 - t]) t++;
|
||
const xs = x.slice(h, x.length - t);
|
||
const ys = y.slice(h, y.length - t);
|
||
const n = xs.length;
|
||
const m = ys.length;
|
||
const L = Array.from({ length: n + 1 }, () => new Uint32Array(m + 1));
|
||
for (let i = n - 1; i >= 0; i--) {
|
||
for (let j = m - 1; j >= 0; j--) L[i][j] = xs[i] === ys[j] ? L[i + 1][j + 1] + 1 : Math.max(L[i + 1][j], L[i][j + 1]);
|
||
}
|
||
const out = x.slice(0, h).map((l) => [' ', l]);
|
||
let i = 0;
|
||
let j = 0;
|
||
while (i < n && j < m) {
|
||
if (xs[i] === ys[j]) { out.push([' ', xs[i]]); i++; j++; }
|
||
else if (L[i + 1][j] >= L[i][j + 1]) out.push(['-', xs[i++]]);
|
||
else out.push(['+', ys[j++]]);
|
||
}
|
||
while (i < n) out.push(['-', xs[i++]]);
|
||
while (j < m) out.push(['+', ys[j++]]);
|
||
return out.concat(x.slice(x.length - t).map((l) => [' ', l]));
|
||
}
|
||
|
||
/* Changed lines with two lines of context each side; the rest folds into "…". */
|
||
function diffHtml(a, b) {
|
||
const d = lineDiff(a, b);
|
||
const near = (i) => d.slice(Math.max(0, i - 2), i + 3).some((r) => r[0] !== ' ');
|
||
let out = '';
|
||
let gap = false;
|
||
d.forEach((r, i) => {
|
||
if (!near(i)) { gap = true; return; }
|
||
if (gap && out) out += '<span class="faint">…</span>\n';
|
||
gap = false;
|
||
out += `<span class="${r[0] === '+' ? 'add' : r[0] === '-' ? 'del' : ''}">${esc(r[0] + ' ' + r[1])}</span>\n`;
|
||
});
|
||
return out ? `<pre class="diff lines" data-no-i18n>${out}</pre>` : '<div class="faint tiny">Bez zmian w treści.</div>';
|
||
}
|
||
|
||
/* What a version is, as lines to compare: the description, the body, then each file by its checksum —
|
||
a replaced .docx shows up as one changed line, not as bytes. */
|
||
// Every field a version can change is a line here: the administrator's approval (T1) is only as
|
||
// good as the difference it is shown, so license and frontmatter count as much as the body.
|
||
const versionText = (v) => [v.description, '', v.body, '', '---', `license: ${v.license || ''}`,
|
||
`metadata: ${JSON.stringify(v.metadata || {})}`, ...(v.files.length ? ['---'] : []),
|
||
...v.files.map((f) => `${f.path} ${f.sha256.slice(0, 12)}`)].join('\n');
|
||
|
||
// Word, Excel and PDF are kept for download only in this release; nothing reads their text yet.
|
||
const unreadFile = (path) => /\.(docx|xlsx|pdf)$/i.test(path);
|
||
const fileNote = (path) => (unreadFile(path) ? ' <span class="faint tiny">plik do pobrania, model go jeszcze nie czyta</span>' : '');
|
||
|
||
async function viewSkill(C, id) {
|
||
const s = await api('GET', '/skills/' + enc(id));
|
||
// ponytail: one request per readable version; a versions-with-bodies endpoint if skills reach dozens.
|
||
const vs = await Promise.all(s.versions.map((v) => api('GET', `/skills/${enc(id)}/versions/${v.n}`)));
|
||
state._skill = s;
|
||
state._skillLatest = vs[0] || null;
|
||
setCrumb([{ label: 'Skille i agenci', href: '#/skills' }, { label: s.name, data: true }]);
|
||
const shown = s.current || vs[0];
|
||
const active = s.status !== 'archived';
|
||
const latest = vs[0];
|
||
const publishable = s.editable && active && latest && !(s.scope === 'firm' && latest.id === s.current_version_id);
|
||
const acts = (s.editable && active ? `<button class="btn" onclick="openSkillEditor('${esc(s.id)}')">${svg(ICN.plus)}<span>Nowa wersja</span></button>` : '')
|
||
+ (publishable ? `<button class="btn" onclick="publishSkill('${esc(s.id)}')"><span>Opublikuj w firmie</span></button>` : '')
|
||
+ (vs.length ? `<a class="btn" href="${esc(API + '/skills/' + enc(s.id) + '/export')}" download><span>Eksportuj</span></a>` : '')
|
||
+ (s.editable && active ? `<button class="btn danger" onclick="confirmTwice(this, () => archiveSkill('${esc(s.id)}'))"><span>Archiwizuj</span></button>` : '');
|
||
const rows = vs.map((v, k) => `<tr>
|
||
<td class="nowrap">v${esc(String(v.n))}${v.id === s.current_version_id ? ' <span class="chip ok">Aktualna</span>' : ''}</td>
|
||
<td class="faint tiny nowrap"${lbl('Utworzona')}>${esc(fmtDateTime(v.created_at))}</td>
|
||
<td class="wrap"${lbl('Zmiany')}>${vs[k + 1]
|
||
? `<details><summary class="faint"><span>Różnice względem</span> v${esc(String(vs[k + 1].n))}</summary>${diffHtml(versionText(vs[k + 1]), versionText(v))}</details>`
|
||
: '<span class="faint tiny">Pierwsza wersja</span>'}</td>
|
||
</tr>`).join('');
|
||
C.innerHTML = pageHead(s.name, s.slug, acts, true)
|
||
+ `<div class="row" style="margin-bottom:12px">${skillChips(s)}</div>`
|
||
+ (shown ? `<div class="card"><h3><span>Wersja</span> v${esc(String(shown.n))}</h3>
|
||
<div class="prose" data-no-i18n>${esc(shown.description)}</div>
|
||
<pre class="diff lines" data-no-i18n>${esc(shown.body)}</pre>
|
||
${shown.files.length ? `<h4 class="minor">Pliki</h4><ul>${shown.files.map((f) => `<li>${dat(f.path)}${fileNote(f.path)}</li>`).join('')}</ul>` : ''}
|
||
</div>` : '<div class="empty">Ta wersja czeka na zgodę administratora.</div>')
|
||
+ (vs.length ? `<div class="card"><h3>Wersje<span class="n">${vs.length}</span></h3>
|
||
<div class="tablewrap"><table class="rt"><thead><tr><th>Wersja</th><th>Utworzona</th><th>Zmiany</th></tr></thead>
|
||
<tbody>${rows}</tbody></table></div></div>` : '');
|
||
}
|
||
|
||
/* Files travel as base64 inside the version's JSON (the one route the spec allows). Picked files
|
||
REPLACE the version's set; picking none carries the current ones over, because the console never
|
||
holds their bytes to send them back. */
|
||
async function filesBase64(input) {
|
||
const out = {};
|
||
for (const f of input.files) {
|
||
const bytes = new Uint8Array(await f.arrayBuffer());
|
||
let bin = '';
|
||
for (let i = 0; i < bytes.length; i += 0x8000) bin += String.fromCharCode(...bytes.subarray(i, i + 0x8000));
|
||
out[f.name] = btoa(bin);
|
||
}
|
||
return out;
|
||
}
|
||
|
||
function skillFilesNote() {
|
||
const unread = [...$('skFiles').files].map((f) => f.name).filter(unreadFile);
|
||
$('skFilesNote').innerHTML = unread.length
|
||
? `<span>${esc(_tr('Plik do pobrania, model go jeszcze nie czyta:'))}</span> ${dat(unread.join(', '))}`
|
||
: '';
|
||
}
|
||
|
||
function openSkillEditor(id) {
|
||
const s = id ? state._skill : null;
|
||
const v = id ? state._skillLatest : null;
|
||
modal(id ? 'Nowa wersja' : 'Nowy skill', s ? s.name : '',
|
||
(id ? '' : `<label class="field">Identyfikator<input id="skSlug" maxlength="64" placeholder="np. umowa-najmu" /></label>
|
||
<div class="faint tiny">Małe litery, cyfry i myślniki. Nie da się go później zmienić.</div>`)
|
||
+ `<label class="field">Nazwa<input id="skName" maxlength="200" value="${esc(s ? s.name : '')}" /></label>
|
||
<label class="field">Opis<textarea id="skDesc" maxlength="1024" data-no-i18n>${esc(v ? v.description : '')}</textarea></label>
|
||
<div class="faint tiny">Opis mówi modelowi, kiedy sięgnąć po ten skill.</div>
|
||
<label class="field">Treść<textarea id="skBody" rows="14" maxlength="30000" data-no-i18n>${esc(v ? v.body : '')}</textarea></label>
|
||
<label class="field">Pliki<input id="skFiles" type="file" multiple accept=".md,.txt,.docx,.pdf,.xlsx,.csv,.json,.yaml,.yml" onchange="skillFilesNote()" /></label>
|
||
<div class="faint tiny">${id ? 'Wybrane pliki zastąpią obecne. Bez wyboru obecne pliki przechodzą do nowej wersji.' : 'Pliki pomocnicze, łącznie do 10 MB.'}</div>
|
||
<div id="skFilesNote" class="faint tiny"></div>
|
||
${v && v.files.length ? '<label class="check"><input type="checkbox" id="skDrop" /> <span>Usuń obecne pliki</span></label>' : ''}`,
|
||
`<button class="btn" onclick="closeModal()">Anuluj</button>
|
||
<button class="btn primary" onclick="saveSkill(${id ? `'${esc(id)}'` : ''})">Zapisz</button>`, { wide: true });
|
||
}
|
||
|
||
function saveSkill(id) {
|
||
return guard(async () => {
|
||
const body = { name: $('skName').value.trim(), description: $('skDesc').value.trim(), body: $('skBody').value };
|
||
if ($('skFiles').files.length) body.files = await filesBase64($('skFiles'));
|
||
else if ($('skDrop') && $('skDrop').checked) body.files = {};
|
||
if (id) {
|
||
await mutate('POST', `/skills/${enc(id)}/versions`, body, { done: 'Zapisano nową wersję.' });
|
||
} else {
|
||
body.slug = $('skSlug').value.trim();
|
||
await mutate('POST', '/skills', body, { done: 'Skill utworzony.', go: (r) => '#/skills/skill/' + enc(r.id) });
|
||
}
|
||
});
|
||
}
|
||
|
||
function publishSkill(id) {
|
||
mutate('POST', `/skills/${enc(id)}/publish`, undefined, {
|
||
done: (r) => (r.status === 'pending' ? 'Wysłano do zatwierdzenia przez administratora.' : 'Opublikowano w firmie.'),
|
||
});
|
||
}
|
||
|
||
function archiveSkill(id) {
|
||
mutate('POST', `/skills/${enc(id)}/archive`, undefined, { done: 'Zarchiwizowano.' });
|
||
}
|
||
|
||
/* ── import ──
|
||
One button for both kinds of pack: the skills route refuses an agent pack with `pack_is_agent`,
|
||
and only then does it go to the agents route. Not through mutate(): a refusal here is the result
|
||
the person asked for (reason + the files behind it), not an error to toast. api() still marks the
|
||
shared state stale, and closing the result re-renders through router(). */
|
||
function openImport() {
|
||
state._importFile = null;
|
||
modal('Importuj ZIP', '', `<label class="field">Paczka ZIP<input id="impFile" type="file" accept=".zip,application/zip" /></label>
|
||
<div class="faint tiny">Skill albo agent w formacie SKILL.md, do 10 MB. Import tworzy twoją osobistą kopię; nic nie aktualizuje się samo.</div>`,
|
||
`<button class="btn" onclick="closeModal()">Anuluj</button>
|
||
<button class="btn primary" onclick="runImport()">Importuj</button>`);
|
||
}
|
||
|
||
function runImport(addVersion) {
|
||
return guard(async () => {
|
||
const f = addVersion ? state._importFile : $('impFile').files[0];
|
||
if (!f) throw new Error(_tr('Wybierz plik ZIP.'));
|
||
state._importFile = f;
|
||
const q = '?filename=' + enc(f.name);
|
||
let kind = 'skill';
|
||
let r;
|
||
try {
|
||
try {
|
||
r = await api('POST', '/skills/import' + q + (addVersion ? '&add_version=true' : ''), f);
|
||
} catch (ex) {
|
||
if (!ex.problem || ex.problem.code !== 'pack_is_agent') throw ex;
|
||
kind = 'agent';
|
||
r = await api('POST', '/agents/import' + q, f);
|
||
}
|
||
} catch (ex) {
|
||
if (!ex.problem || !ex.problem.code) throw ex;
|
||
showImportRefusal(ex);
|
||
return;
|
||
}
|
||
showImportResult(kind, r);
|
||
});
|
||
}
|
||
|
||
const closeAndRender = 'closeModal();router()';
|
||
|
||
// The message is the server's, already in the reader's language (`coreRefusal`); the files are data.
|
||
function showImportRefusal(ex) {
|
||
const files = Array.isArray(ex.problem.files) ? ex.problem.files : [];
|
||
modal('Paczka odrzucona', '', `<div class="banner err" data-no-i18n>${esc(ex.message)}</div>`
|
||
+ (files.length ? `<div class="faint tiny">Pliki, których to dotyczy:</div><ul>${files.map((p) => `<li>${dat(p)}</li>`).join('')}</ul>` : ''),
|
||
`<button class="btn" onclick="openImport()">Wybierz inny plik</button>
|
||
<button class="btn primary" onclick="closeModal()">Zamknij</button>`);
|
||
}
|
||
|
||
// D3: what a pack asked for and was not given — kept as information, shown once, here.
|
||
const infoLines = (info) => Object.entries(info || {}).map(([k, v]) => `${k}: ${Array.isArray(v) ? v.join(', ')
|
||
: v && typeof v === 'object' ? JSON.stringify(v) : String(v)}`);
|
||
const infoNote = (info) => {
|
||
const lines = infoLines(info);
|
||
return lines.length ? `<div class="faint tiny"><span>Zapisane tylko jako informacja:</span> ${dat(lines.join('; '))}</div>` : '';
|
||
};
|
||
|
||
function importedSkill(x) {
|
||
const s = x.skill || x.match;
|
||
return `<li>${s
|
||
? `<a href="#/skills/skill/${esc(enc(s.id))}" onclick="closeModal()">${dat(s.name)}</a> ${dat('v' + (x.skill ? x.n : s.n))}`
|
||
: `${dat(x.path)} <span class="faint tiny">zostanie dodany jako nowy skill</span>`}${infoNote(x.info_only)}</li>`;
|
||
}
|
||
|
||
function showImportResult(kind, r) {
|
||
const list = `<ul>${r.skills.map(importedSkill).join('')}</ul>`;
|
||
const ignored = r.ignored && r.ignored.length
|
||
? `<div class="faint tiny"><span>Pominięte pliki (nie należą do żadnego skilla):</span> ${dat(r.ignored.join(', '))}</div>` : '';
|
||
if (r.status === 'duplicate') {
|
||
modal('Masz już ten skill', '', `<div>Ta sama treść jest już w twoich skillach. Dodać ją jako nową wersję?</div>${list}${ignored}`,
|
||
`<button class="btn" onclick="closeModal()">Anuluj</button>
|
||
<button class="btn primary" onclick="runImport(true)">Dodaj jako nową wersję</button>`);
|
||
return;
|
||
}
|
||
if (kind === 'agent') {
|
||
modal('Agent zaimportowany', '', `<div><a href="#/skills/agent/${esc(enc(r.agent.id))}" onclick="closeModal()">${dat(r.agent.name)}</a></div>
|
||
${infoNote(r.info_only)}<h4 class="minor">Przypięte skille</h4>${list}`,
|
||
`<button class="btn primary" onclick="${closeAndRender}">Zamknij</button>`);
|
||
return;
|
||
}
|
||
modal('Zaimportowano', '', list + ignored, `<button class="btn primary" onclick="${closeAndRender}">Zamknij</button>`);
|
||
}
|
||
|
||
/* ── agents ──
|
||
An agent is an instruction plus pinned skill VERSIONS: a pin never moves when the skill gets a new
|
||
version, so the editor offers each skill's current version next to whatever is pinned now. */
|
||
async function viewAgent(C, id) {
|
||
const a = await api('GET', '/agents/' + enc(id));
|
||
state._agent = a;
|
||
setCrumb([{ label: 'Skille i agenci', href: '#/skills' }, { label: a.name, data: true }]);
|
||
const v = a.current;
|
||
const active = a.status !== 'archived';
|
||
const newest = a.versions[0];
|
||
const publishable = a.editable && active && newest && !(a.scope === 'firm' && newest.id === a.current_version_id);
|
||
const acts = (a.editable && active ? `<button class="btn" onclick="openAgentEditor('${esc(a.id)}')">${svg(ICN.plus)}<span>Nowa wersja</span></button>` : '')
|
||
+ (publishable ? `<button class="btn" onclick="publishAgent('${esc(a.id)}')"><span>Opublikuj w firmie</span></button>` : '')
|
||
+ (v ? `<a class="btn" href="${esc(API + '/agents/' + enc(a.id) + '/export')}" download><span>Eksportuj</span></a>` : '')
|
||
+ (a.editable && active ? `<button class="btn danger" onclick="confirmTwice(this, () => archiveAgent('${esc(a.id)}'))"><span>Archiwizuj</span></button>` : '');
|
||
const model = v && v.model_policy && v.model_policy.model;
|
||
const pins = v ? v.skills.map((s) => `<li><a href="#/skills/skill/${esc(enc(s.skill_id))}">${dat(s.name)}</a> ${dat('v' + s.n)}${
|
||
s.status === 'archived' ? ' <span class="chip">Skill zarchiwizowany</span>' : ''}</li>`).join('') : '';
|
||
const rows = a.versions.map((x) => `<tr><td class="nowrap">v${esc(String(x.n))}${x.id === a.current_version_id ? ' <span class="chip ok">Aktualna</span>' : ''}</td>
|
||
<td class="faint tiny nowrap"${lbl('Utworzona')}>${esc(fmtDateTime(x.created_at))}</td></tr>`).join('');
|
||
C.innerHTML = pageHead(a.name, '', acts, true)
|
||
+ `<div class="row" style="margin-bottom:12px">${skillChips(a)}</div>`
|
||
+ (v ? `<div class="card"><h3><span>Wersja</span> v${esc(String(v.n))}</h3>
|
||
<h4 class="minor">Instrukcja</h4><pre class="diff lines" data-no-i18n>${esc(v.instructions)}</pre>
|
||
${model ? `<div><span>Podpowiedź modelu:</span> ${dat(model)}</div>` : ''}
|
||
${v.tools_requested.length ? `<div class="faint tiny"><span>Prosi o narzędzia (zapisane tylko jako informacja):</span> ${dat(v.tools_requested.join(', '))}</div>` : ''}
|
||
<h4 class="minor">Przypięte skille</h4>${pins ? `<ul>${pins}</ul>` : '<div class="faint tiny">Brak przypiętych skilli.</div>'}
|
||
</div>` : '<div class="empty">Ta wersja czeka na zgodę administratora.</div>')
|
||
+ (rows ? `<div class="card"><h3>Wersje<span class="n">${a.versions.length}</span></h3>
|
||
<div class="tablewrap"><table class="rt"><thead><tr><th>Wersja</th><th>Utworzona</th></tr></thead>
|
||
<tbody>${rows}</tbody></table></div></div>` : '');
|
||
}
|
||
|
||
function openAgentEditor(id) {
|
||
return guard(async () => {
|
||
const a = id ? state._agent : null;
|
||
// ponytail: prefilled from the CURRENT version — a firm agent's unapproved newer one has no read
|
||
// route yet (GET /agents/{id}/versions/{n}); add it if editing on top of a pending one matters.
|
||
const v = a && a.current;
|
||
const firm = a && a.scope === 'firm';
|
||
const skills = (await api('GET', '/skills')).filter((s) => s.status !== 'archived' && s.current_version_id
|
||
&& (!firm || s.scope === 'firm')); // the server's `may_pin`, so the list offers nothing it refuses
|
||
const pinned = v ? v.skills : [];
|
||
const pinnedIds = new Set(pinned.map((p) => p.skill_version_id));
|
||
const opt = (vid, label, on) => `<label class="check"><input type="checkbox" name="agPin" value="${esc(vid)}"${on ? ' checked' : ''} /> ${label}</label>`;
|
||
const opts = pinned.map((p) => opt(p.skill_version_id, `${dat(p.name)} ${dat('v' + p.n)}`, true))
|
||
.concat(skills.filter((s) => !pinnedIds.has(s.current_version_id))
|
||
.map((s) => opt(s.current_version_id, `${dat(s.name)} <span class="faint tiny">aktualna wersja</span>`, false)));
|
||
modal(id ? 'Nowa wersja' : 'Nowy agent', a ? a.name : '',
|
||
`<label class="field">Nazwa<input id="agName" maxlength="200" value="${esc(a ? a.name : '')}" /></label>
|
||
<label class="field">Instrukcja<textarea id="agInstr" rows="12" maxlength="60000" data-no-i18n>${esc(v ? v.instructions : '')}</textarea></label>
|
||
<label class="field">Podpowiedź modelu<input id="agModel" maxlength="200" placeholder="np. claude-sonnet-4-5" value="${esc((v && v.model_policy && v.model_policy.model) || '')}" /></label>
|
||
<div class="faint tiny">Tylko podpowiedź — model wybiera platforma.</div>
|
||
<h4 class="minor">Przypięte skille</h4>
|
||
${firm ? '<div class="faint tiny">Agent firmowy przypina tylko opublikowane wersje firmowych skilli.</div>' : ''}
|
||
${opts.length ? `<div class="stack">${opts.join('')}</div>` : '<div class="faint tiny">Nie masz skilli do przypięcia.</div>'}`,
|
||
`<button class="btn" onclick="closeModal()">Anuluj</button>
|
||
<button class="btn primary" onclick="saveAgent(${id ? `'${esc(id)}'` : ''})">Zapisz</button>`, { wide: true });
|
||
});
|
||
}
|
||
|
||
function saveAgent(id) {
|
||
const model = $('agModel').value.trim();
|
||
const policy = { ...((state._agent && id && state._agent.current && state._agent.current.model_policy) || {}) };
|
||
if (model) policy.model = model; else delete policy.model;
|
||
const body = {
|
||
name: $('agName').value.trim(),
|
||
instructions: $('agInstr').value,
|
||
model_policy: policy, // {} clears the hint; null would carry the old one over
|
||
skill_version_ids: [...document.querySelectorAll('input[name=agPin]:checked')].map((x) => x.value),
|
||
};
|
||
if (id) mutate('POST', `/agents/${enc(id)}/versions`, body, { done: 'Zapisano nową wersję.' });
|
||
else mutate('POST', '/agents', body, { done: 'Agent utworzony.', go: (r) => '#/skills/agent/' + enc(r.id) });
|
||
}
|
||
|
||
function publishAgent(id) {
|
||
mutate('POST', `/agents/${enc(id)}/publish`, undefined, {
|
||
done: (r) => (r.status === 'pending' ? 'Wysłano do zatwierdzenia przez administratora.' : 'Opublikowano w firmie.'),
|
||
});
|
||
}
|
||
|
||
function archiveAgent(id) {
|
||
mutate('POST', `/agents/${enc(id)}/archive`, undefined, { done: 'Zarchiwizowano.' });
|
||
}
|
||
|
||
function openTokenNew() {
|
||
const policy = tokenPolicy();
|
||
const max = policy.max_idle_days || 365;
|
||
const days = policy.idle_days || 30;
|
||
/* The module picker exists only on a platform. Standalone there are no modules sharing this
|
||
account, so "mint for Galena" would name a prefix and promise nothing — the same reason the
|
||
MODERATOR tier is absent rather than offered and refused on a standalone install. The hub is
|
||
the first entry because a token for this console's own API is an ordinary thing to want, and it
|
||
is the one entry that goes to `POST /me/tokens` rather than the module route. */
|
||
const modules = state._catalogue || [];
|
||
const picker = !sharesIdentity() ? '' : `<label class="field">Moduł<select id="tkModule">
|
||
<option value="${esc(hubSlug())}" data-no-i18n>${esc(setting('instance_name') || 'Atrium')}</option>
|
||
${modules.map((m) => `<option value="${esc(m.slug)}" data-no-i18n>${esc(m.name)}</option>`).join('')}
|
||
</select></label>
|
||
<div class="faint tiny">Wybór nadaje tokenowi przedrostek, po którym go rozpoznasz na liście i w dzienniku zdarzeń.</div>`;
|
||
|
||
modal('Nowy token', '',
|
||
(sharesIdentity() ? '<div class="banner">Token działa w każdym module, nie tylko w wybranym tutaj: przedrostek mówi, gdzie powstał. Uprawnienia ma takie jak jego twórca.</div>' : '')
|
||
+ `<label class="field">Nazwa<input id="tkName" maxlength="120" placeholder="GalenaConnect na laptopie" /></label>
|
||
<div class="faint tiny">Nazwa jest po to, żeby dało się odwołać jeden token, a nie wszystkie.</div>
|
||
${picker}
|
||
<div class="grid2">
|
||
<label class="field">Zakres${choice('tkScope', SCOPE_LABEL, 'read_write')}</label>
|
||
<label class="field">Wygasa po (dni bez użycia)<input id="tkDays" type="number" min="1" max="${esc(String(max))}" value="${esc(String(days))}" /></label>
|
||
</div>
|
||
<div class="faint tiny"><span>Każde użycie przesuwa termin, więc token używany nie wygasa, a zapomniany umiera sam. Maksimum:</span> ${esc(String(max))}.</div>`,
|
||
`<button class="btn" onclick="closeModal()">Anuluj</button>
|
||
<button class="btn primary" onclick="saveTokenNew()">Utwórz token</button>`, { wide: true });
|
||
}
|
||
|
||
/* Blank means "the server's default", the way orderValue() does it. Anything else must be a whole
|
||
number of days — say so here rather than letting the server answer a typo with a 422. */
|
||
function readTokenForm() {
|
||
const raw = $('tkDays').value.trim();
|
||
const max = tokenPolicy().max_idle_days || 365;
|
||
if (raw !== '' && (!/^\d+$/.test(raw) || +raw < 1 || +raw > max)) {
|
||
throw new Error(_tr('Liczba dni musi być liczbą całkowitą od 1 do maksimum podanego niżej.'));
|
||
}
|
||
return { name: $('tkName').value.trim(), scope: $('tkScope').value,
|
||
idle_days: raw === '' ? undefined : parseInt(raw, 10) };
|
||
}
|
||
|
||
function saveTokenNew() {
|
||
const slug = $('tkModule') ? $('tkModule').value : '';
|
||
// The hub has no catalogue row of its own, and `/me/tokens` is the route that stamps this app's
|
||
// own prefix — so it, not `/me/modules/atrium/tokens`, is what "a token for Atrium" means.
|
||
const path = (!slug || slug === hubSlug()) ? '/me/tokens' : `/me/modules/${enc(slug)}/tokens`;
|
||
// `reopen` rather than the default close-and-re-render: the secret exists exactly once, in this
|
||
// reply, and closing the dialog on it would be the one bug this screen cannot recover from.
|
||
mutate('POST', path, readTokenForm, { done: 'Token utworzony.', reopen: (r) => showToken(r) });
|
||
}
|
||
|
||
function showToken(t) {
|
||
modal('Nowy token', t.name || '',
|
||
`<div class="banner warn">Skopiuj token teraz. Nie da się go odczytać później — serwer przechowuje tylko jego skrót.</div>
|
||
<label class="field">Token<input id="tkSecret" class="secret" readonly value="${esc(t.token)}" /></label>
|
||
<div class="row"><button class="btn" onclick="copyToken()">Kopiuj</button></div>
|
||
<div class="faint tiny" style="margin-top:10px">${sharesIdentity()
|
||
? 'Wklej go w aplikacji, która ma się nim logować. Działa w każdym module; jeśli wycieknie, odwołaj go tutaj.'
|
||
: 'Wklej go w aplikacji, która ma się nim logować. Jeśli wycieknie, odwołaj go tutaj.'}</div>`,
|
||
// Closing re-renders the list, which `mutate`'s reopen path deliberately does not do.
|
||
`<button class="btn primary" onclick="closeModal();router()">Zamknij</button>`, { wide: true });
|
||
const el = $('tkSecret');
|
||
if (el) el.select();
|
||
}
|
||
|
||
function copyToken() {
|
||
const el = $('tkSecret');
|
||
if (!el) return;
|
||
/* Selected first, and that is the fallback doing the work rather than a nicety: navigator.clipboard
|
||
is undefined outside a secure context, and this platform's first deployment is plain HTTP on a
|
||
bare-IP address. So the field is left selected and the toast says to copy it by hand. */
|
||
el.select();
|
||
if (!navigator.clipboard) { toast('Nie udało się skopiować — zaznacz i skopiuj ręcznie.'); return; }
|
||
navigator.clipboard.writeText(el.value).then(
|
||
() => toast('Skopiowano.'),
|
||
() => toast('Nie udało się skopiować — zaznacz i skopiuj ręcznie.'));
|
||
}
|
||
|
||
function revokeToken(id) {
|
||
const t = (state._tokens || []).find((x) => x.id === id) || {};
|
||
modal('Odwołaj', t.name || '',
|
||
`<div class="banner warn">${sharesIdentity()
|
||
? 'Odwołać token? Aplikacja, która go używa, straci dostęp natychmiast — we wszystkich modułach.'
|
||
: 'Odwołać token? Aplikacja, która go używa, straci dostęp natychmiast.'}</div>
|
||
<div class="faint tiny" style="margin-top:8px">Tej operacji nie da się cofnąć.</div>`,
|
||
`<button class="btn" onclick="closeModal()">Anuluj</button>
|
||
<button class="btn danger" onclick="confirmRevokeToken('${esc(id)}')">Odwołaj</button>`);
|
||
}
|
||
|
||
function confirmRevokeToken(id) {
|
||
mutate('DELETE', '/me/tokens/' + enc(id), undefined, { done: 'Token odwołany.' });
|
||
}
|
||
|
||
/* ── my model keys (dredd-core 0.18.0, key_mode = "user") ─────────────────────
|
||
A provider whose `key_mode` is `user` calls with the asker's OWN key. This is where a person stores
|
||
it: `PUT /me/model-keys/{id}` (core's `set_user_key`), `DELETE` (core's `clear_user_key`, never
|
||
refused — a person can always take their key back). Write-only like the firm's key: the API
|
||
returns only `key_prefix`, the field is always empty, and nothing here keeps or calls anything. */
|
||
async function viewMyKeys(C) {
|
||
const r = await api('GET', '/me/model-keys');
|
||
state._myKeys = r.providers;
|
||
setCrumb([{ label: 'Ustawienia' }, { label: 'Moje klucze modeli' }]);
|
||
const writable = !!r.keys_writable;
|
||
const rows = r.providers.map((p) => `<tr>
|
||
<td><div>${dat(p.name)}</div><div class="mono tiny faint wrap" data-no-i18n>${esc((p.models || []).join(', '))}</div></td>
|
||
<td${lbl('Klucz API')}>${p.key_prefix
|
||
? `<span class="chip ok">ustawiony</span> <span class="mono tiny faint" data-no-i18n>${esc(p.key_prefix)}…</span>`
|
||
: '<span class="faint">brak</span>'}</td>
|
||
<td class="acts-cell shrink"><div class="row">
|
||
<button class="btn sm" data-pid="${esc(p.id)}" ${writable ? '' : 'disabled'} onclick="openMyKeyForm(this.dataset.pid)">${p.key_prefix ? 'Zmień klucz' : 'Dodaj klucz'}</button>
|
||
${p.key_prefix ? `<button class="btn sm danger" data-pid="${esc(p.id)}" onclick="removeMyKey(this.dataset.pid)">Usuń klucz</button>` : ''}
|
||
</div></td>
|
||
</tr>`).join('');
|
||
C.innerHTML = pageHead('Moje klucze modeli', 'Dostawcy modeli, którzy używają twojego własnego klucza API zamiast klucza firmy.', '')
|
||
+ (writable ? '' : '<div class="banner warn">Ten serwer nie ma ustawionego MODEL_PROVIDER_SECRET, więc nie może zapisać klucza API.</div>')
|
||
+ '<div class="card">'
|
||
+ (rows ? `<div class="tablewrap"><table class="rt"><thead><tr>
|
||
<th>Dostawca</th><th>Klucz API</th><th></th>
|
||
</tr></thead><tbody>${rows}</tbody></table></div>`
|
||
: '<div class="empty">Żaden dostawca nie potrzebuje twojego klucza.</div>')
|
||
+ '<div class="faint tiny" style="margin-top:10px">Klucz jest tylko do zapisu: nikt, także administrator, nie zobaczy go ponownie.</div></div>';
|
||
}
|
||
|
||
function openMyKeyForm(id) {
|
||
const p = (state._myKeys || []).find((x) => x.id === id);
|
||
if (!p) { toast('Nie znaleziono strony.'); return; }
|
||
modal(p.key_prefix ? 'Zmień klucz' : 'Dodaj klucz', p.name,
|
||
`<label class="field">Klucz API<input id="mkKey" type="password" autocomplete="new-password" maxlength="4096" /></label>`,
|
||
`<button class="btn" onclick="closeModal()">Anuluj</button>
|
||
<button class="btn primary" data-pid="${esc(p.id)}" onclick="saveMyKey(this.dataset.pid)">Zapisz</button>`);
|
||
}
|
||
|
||
function saveMyKey(id) {
|
||
mutate('PUT', '/me/model-keys/' + enc(id), () => ({ api_key: $('mkKey').value }));
|
||
}
|
||
|
||
function removeMyKey(id) {
|
||
modal('Usuń klucz', '', '<div class="banner warn">Usunąć twój zapisany klucz API tego dostawcy?</div>',
|
||
`<button class="btn" onclick="closeModal()">Anuluj</button>
|
||
<button class="btn danger" data-pid="${esc(id)}" onclick="confirmRemoveMyKey(this.dataset.pid)">Usuń klucz</button>`);
|
||
}
|
||
|
||
function confirmRemoveMyKey(id) {
|
||
mutate('DELETE', '/me/model-keys/' + enc(id));
|
||
}
|
||
|
||
/* ── administration: overview (the dashboard's admin section) ───────────── */
|
||
/* An administrator's part of the home page: only what needs doing. The module counts and their
|
||
health checks live on Administracja › Moduły — one place, not two. */
|
||
async function adminOverviewHtml() {
|
||
const o = await api('GET', '/admin/overview');
|
||
state.pending = o.pending_requests || 0;
|
||
const notes = [];
|
||
if (o.pending_requests) notes.push(`<div class="banner warn row" style="justify-content:space-between">`
|
||
+ `<span><span>Oczekujące wnioski o dostęp:</span> <b>${esc(String(o.pending_requests))}</b></span>`
|
||
+ '<a class="btn sm primary" href="#/admin/requests">Rozpatrz wnioski</a></div>');
|
||
if (o.unconfigured) notes.push('<div class="banner warn row" style="justify-content:space-between">'
|
||
+ '<span>Niektóre moduły nie mają adresu, więc nikt ich nie zobaczy wśród swoich aplikacji.</span>'
|
||
+ '<a class="btn sm" href="#/admin/modules">Moduły</a></div>');
|
||
return notes.length ? '<div class="home-label"><span>Do zrobienia</span></div>' + notes.join('') : '';
|
||
}
|
||
|
||
function probeCell(r) {
|
||
if (r.ok) {
|
||
return `<div><span class="chip ok">${esc(String(r.status_code))}</span> ${r.version ? `<span class="mono" data-no-i18n>v${esc(r.version)}</span>` : ''} <span class="faint">${esc(String(r.latency_ms))} ms</span></div>`;
|
||
}
|
||
return `<div><span class="chip err">${esc(PROBE_ERR[r.error] || r.error || 'błąd HTTP')}</span>${r.status_code ? ` <span class="faint">${esc(String(r.status_code))}</span>` : ''}</div>`;
|
||
}
|
||
|
||
async function probeOne(slug) {
|
||
const cell = $('probe-' + slug);
|
||
if (!cell) return;
|
||
cell.innerHTML = '<span class="faint">…</span>';
|
||
try {
|
||
cell.innerHTML = probeCell(await api('POST', `/admin/modules/${enc(slug)}/probe`));
|
||
} catch (ex) {
|
||
cell.innerHTML = `<div><span class="chip err">${esc(ex.message)}</span></div>`;
|
||
}
|
||
localize(cell);
|
||
}
|
||
|
||
/* Four at a time, matching the server's concurrent-probe limit — firing every module at once would
|
||
just come back "busy" for the rest. */
|
||
async function probeAll() {
|
||
const queue = Array.from(document.querySelectorAll('[data-probe]')).map((c) => c.id.slice(6));
|
||
const worker = async () => { while (queue.length) await probeOne(queue.shift()); };
|
||
await Promise.all([worker(), worker(), worker(), worker()]);
|
||
}
|
||
|
||
/* ── administration: modules ────────────────────────────────────────────── */
|
||
async function viewAdminModules(C) {
|
||
const rows = await api('GET', '/admin/modules');
|
||
setCrumb([{ label: 'Moduły', href: '#/marketplace' }, { label: 'Zarządzanie' }]);
|
||
C.innerHTML = pageHead('Moduły', 'Aplikacje dostępne w twojej organizacji',
|
||
`<button class="btn" onclick="probeAll()">${svg(ICN.refresh)}<span>Sprawdź stan</span></button>`
|
||
+ `<button class="btn primary" onclick="openModuleNew()">${svg(ICN.plus)}<span>Nowy moduł</span></button>`)
|
||
+ catalogTabs('admin')
|
||
+ (rows.length ? `<div class="card"><div class="tablewrap"><table class="rt"><thead><tr>
|
||
<th>Moduł</th><th>Status</th><th>Dostępność</th><th>Adres</th><th class="num col-opt">Przypisania</th><th class="num">Wnioski o dostęp</th><th class="num col-opt">Kolejność</th><th>Stan</th>
|
||
</tr></thead><tbody>${rows.map((m) => `<tr class="click" onclick="location.hash='#/admin/modules/${enc(m.slug)}'">
|
||
<td><div class="cell">${moduleIcon(m, 28)}<div><a href="#/admin/modules/${enc(m.slug)}" onclick="event.stopPropagation()">${dat(m.name)}</a><div class="mono tiny faint">${esc(m.slug)}</div></div></div></td>
|
||
<td${lbl('Status')}>${statusChip(m.status) || `<span class="chip">${esc(STATUS_LABEL.live)}</span>`}</td>
|
||
<td${lbl('Dostępność')}>${availChip(m.availability)}</td>
|
||
<td${lbl('Adres')}>${m.url ? `<span class="chip ok">${svg(ICN.check, 12)}</span>` : '<span class="chip warn">brak</span>'}</td>
|
||
<td class="num col-opt"${lbl('Przypisania')}>${esc(String(m.assignments))}</td>
|
||
<td class="num"${lbl('Wnioski o dostęp')}>${m.pending_requests ? `<span class="chip err">${esc(String(m.pending_requests))}</span>` : '0'}</td>
|
||
<td class="num faint col-opt"${lbl('Kolejność')}>${esc(String(m.sort_order))}</td>
|
||
<td id="probe-${esc(m.slug)}" class="tiny"${m.health_url ? ' data-probe' : ''}${lbl('Stan')} onclick="event.stopPropagation()">${m.health_url ? '<span class="faint">—</span>' : '<span class="faint">brak adresu stanu</span>'}</td>
|
||
</tr>`).join('')}</tbody></table></div></div>` : '<div class="empty">Brak modułów.</div>');
|
||
if (rows.some((m) => m.health_url)) probeAll();
|
||
}
|
||
|
||
function choice(id, map, selected) {
|
||
return `<select id="${id}">${Object.keys(map).map((k) => `<option value="${esc(k)}" ${k === selected ? 'selected' : ''}>${esc(map[k])}</option>`).join('')}</select>`;
|
||
}
|
||
const unitOptions = (units, selected) => units.map((u) =>
|
||
`<option value="${esc(u.id)}" ${u.id === selected ? 'selected' : ''}>${esc(u.path)}</option>`).join('');
|
||
const userOptions = () => state.users.filter((u) => u.is_active).map((u) =>
|
||
`<option value="${esc(u.id)}">${esc(u.full_name)} — ${esc(u.email)}</option>`).join('');
|
||
|
||
/* The people pickers read the user list once; the Users page always re-reads it, so someone created
|
||
there is offered next time. */
|
||
async function ensureUsers() {
|
||
if (!state.users.length) { try { state.users = await api('GET', '/users'); } catch { state.users = []; } }
|
||
}
|
||
|
||
/* The identity picker: every hue × the chosen glyph, and every glyph in the chosen hue. Buttons, so
|
||
it is keyboard-reachable; the choice lives in data attributes on the form, not in globals. */
|
||
function identityPicker(hue, glyph) {
|
||
return `<div class="field">Kolor<div class="swatches" id="hues">${HUES.map((h) =>
|
||
`<button type="button" class="sw ${h === hue ? 'on' : ''}" aria-pressed="${h === hue}" data-hue="${h}" title="${h}" onclick="pickIdentity(this)">${moduleIcon({ hue: h, glyph }, 30)}</button>`).join('')}</div></div>
|
||
<div class="field">Znak<div class="swatches" id="glyphs">${Object.keys(GLYPH).map((g) =>
|
||
`<button type="button" class="sw ${g === glyph ? 'on' : ''}" aria-pressed="${g === glyph}" data-glyph="${g}" title="${g}" onclick="pickIdentity(this)">${moduleIcon({ hue, glyph: g }, 30)}</button>`).join('')}</div></div>
|
||
<input type="hidden" id="mfHue" value="${esc(hue)}" /><input type="hidden" id="mfGlyph" value="${esc(glyph)}" />`;
|
||
}
|
||
|
||
function pickIdentity(btn) {
|
||
if (btn.dataset.hue) $('mfHue').value = btn.dataset.hue;
|
||
if (btn.dataset.glyph) $('mfGlyph').value = btn.dataset.glyph;
|
||
const wrap = btn.closest('.identity');
|
||
const key = btn.dataset.hue ? `[data-hue="${btn.dataset.hue}"]` : `[data-glyph="${btn.dataset.glyph}"]`;
|
||
wrap.innerHTML = identityPicker($('mfHue').value, $('mfGlyph').value);
|
||
localize(wrap);
|
||
const again = wrap.querySelector(key); // the rebuild replaced the button that had focus
|
||
if (again) again.focus();
|
||
}
|
||
|
||
function moduleForm(m, creating) {
|
||
return `${creating ? `<label class="field">Identyfikator<input id="mfSlug" autocomplete="off" spellcheck="false" maxlength="40" placeholder="galena" /></label>` : ''}
|
||
<div class="grid2">
|
||
<label class="field">Nazwa<input id="mfName" maxlength="80" value="${esc(m.name || '')}" /></label>
|
||
<label class="field">Kategoria<input id="mfCategory" maxlength="40" value="${esc(m.category || '')}" /></label>
|
||
</div>
|
||
<label class="field">Hasło reklamowe<input id="mfTagline" maxlength="140" value="${esc(m.tagline || '')}" /></label>
|
||
<label class="field">Opis<textarea id="mfDescription" maxlength="4000">${esc(m.description || '')}</textarea></label>
|
||
<label class="field">Adres<input id="mfUrl" type="url" inputmode="url" autocomplete="off" spellcheck="false" maxlength="2000" placeholder="Adres modułu (np. https://twoj-host/galena)" value="${esc(m.url || '')}" /></label>
|
||
<label class="field">Adres stanu<input id="mfHealth" type="url" inputmode="url" autocomplete="off" spellcheck="false" maxlength="2000" placeholder="Adres stanu (np. https://twoj-host/galena/api/v1/health)" value="${esc(m.health_url || '')}" /></label>
|
||
<div class="grid3">
|
||
<label class="field">Status${choice('mfStatus', STATUS_LABEL, m.status || 'live')}</label>
|
||
${creating ? `<label class="field">Dostępność${choice('mfAvail', AVAIL_LABEL, setting('default_availability') || 'everyone')}</label>` : ''}
|
||
<label class="field">Kolejność<input id="mfOrder" type="number" min="0" max="10000" value="${esc(String(m.sort_order ?? 100))}" /></label>
|
||
</div>
|
||
<div class="identity">${identityPicker(m.hue || 'grape', m.glyph || 'grid')}</div>`;
|
||
}
|
||
|
||
/* Blank means "leave it" (undefined is dropped by JSON.stringify: the order is kept on edit and the
|
||
server default applies on create). Anything else must be a whole number — say so, don't drop it. */
|
||
function orderValue() {
|
||
const raw = $('mfOrder').value.trim();
|
||
if (raw === '') return undefined;
|
||
if (!/^\d+$/.test(raw)) throw new Error(_tr('Kolejność musi być liczbą całkowitą od 0 do 10000.'));
|
||
return parseInt(raw, 10);
|
||
}
|
||
|
||
function readModuleForm() {
|
||
return {
|
||
name: $('mfName').value, category: $('mfCategory').value, tagline: $('mfTagline').value,
|
||
description: $('mfDescription').value, url: $('mfUrl').value, health_url: $('mfHealth').value,
|
||
status: $('mfStatus').value,
|
||
sort_order: orderValue(),
|
||
hue: $('mfHue').value, glyph: $('mfGlyph').value,
|
||
};
|
||
}
|
||
|
||
function openModuleNew() {
|
||
modal('Nowy moduł', 'Identyfikator nie zmienia się po utworzeniu.', moduleForm({}, true),
|
||
`<button class="btn" onclick="closeModal()">Anuluj</button>
|
||
<button class="btn primary" onclick="saveModuleNew()">Zapisz</button>`, { wide: true });
|
||
}
|
||
|
||
function saveModuleNew() {
|
||
mutate('POST', '/admin/modules',
|
||
() => ({ slug: $('mfSlug').value.trim(), availability: $('mfAvail').value, ...readModuleForm() }),
|
||
{ go: (m) => '#/admin/modules/' + enc(m.slug) });
|
||
}
|
||
|
||
async function viewAdminModule(C, slug) {
|
||
const [m, units, people] = await Promise.all([
|
||
api('GET', '/admin/modules/' + enc(slug)), api('GET', '/tree/containers'),
|
||
sharesIdentity() ? api('GET', `/admin/modules/${enc(slug)}/moderators`) : [], ensureUsers()]);
|
||
setCrumb([{ label: 'Moduły', href: '#/marketplace' }, { label: 'Zarządzanie', href: '#/admin/modules' }, { label: m.name, data: true }]);
|
||
|
||
const assigned = m.assignments.length ? `<div class="tablewrap"><table><tbody>${m.assignments.map((a) => `<tr>
|
||
<td class="shrink"><span class="chip">${a.kind === 'unit' ? 'Jednostka' : 'Użytkownik'}</span></td>
|
||
<td>${dat(a.name)}<div class="mono tiny faint">${dat(a.kind === 'unit' ? a.path : a.email)}</div></td>
|
||
<td class="shrink"><button class="btn sm danger" onclick="confirmTwice(this, () => removeAssignment('${esc(m.slug)}','${esc(a.id)}'))" title="Usuń">${svg(ICN.x, 14)}</button></td>
|
||
</tr>`).join('')}</tbody></table></div>` : '<div class="empty">Brak przypisań.</div>';
|
||
|
||
/* Who may actually open this module, and at what role — the `module_permission` rows the module
|
||
itself reads at its own door. Directly under Przypisania because that is where an administrator
|
||
is already thinking about who the module is for, and the copy says how the two relate: an
|
||
assignment is the reason, this list is the effect. */
|
||
const roster = people.length ? `<div class="tablewrap"><table><tbody>${people.map((x) => `<tr>
|
||
<td>${dat(x.full_name)}<div class="mono tiny faint">${dat(x.email)}</div>
|
||
${x.is_admin ? '<span class="chip">Administrator</span>' : ''}${x.is_active ? '' : '<span class="chip err">nieaktywny</span>'}</td>
|
||
<td class="shrink">${roleSelect(`pr-${esc(x.user_id)}`, x.role, `setPermission('${esc(m.slug)}','${esc(x.user_id)}', this.value)`)}</td>
|
||
<td class="faint tiny">${esc(fmtDateTime(x.created_at))}</td>
|
||
<td class="shrink"><button class="btn sm danger" onclick="confirmTwice(this, () => revokePermission('${esc(m.slug)}','${esc(x.user_id)}'))" title="Odbierz">${svg(ICN.x, 14)}</button></td>
|
||
</tr>`).join('')}</tbody></table></div>` : '<div class="empty">Nikt nie ma jeszcze dostępu.</div>';
|
||
|
||
C.innerHTML = `<div class="card mhead">${moduleIcon(m, 64)}
|
||
<div class="mhtxt"><h2>${dat(m.name)}</h2><div class="mono tiny faint">${esc(m.slug)}</div>
|
||
<div class="row" style="margin-top:8px">${statusChip(m.status)}${availChip(m.availability)}</div></div>
|
||
<div class="acts">
|
||
<a class="btn" href="#/marketplace/${enc(m.slug)}">${svg(ICN.store)}<span>Otwórz w katalogu</span></a>
|
||
<button class="btn danger" onclick="deleteModule('${esc(m.slug)}')">${svg(ICN.trash)}<span>Usuń</span></button>
|
||
</div></div>
|
||
<div class="grid-admin" style="margin-top:14px">
|
||
<div class="card"><h3>Szczegóły</h3>
|
||
<div class="stack">${moduleForm(m, false)}</div>
|
||
<div class="acts-row"><button class="btn primary" onclick="saveModule('${esc(m.slug)}')">${svg(ICN.check)}<span>Zapisz</span></button></div>
|
||
</div>
|
||
<div>
|
||
<div class="card"><h3>Dostępność</h3>
|
||
${Object.keys(AVAIL_LONG).map((k) => `<label class="radio"><input type="radio" name="avail" value="${k}" ${m.availability === k ? 'checked' : ''} onchange="saveAvailability('${esc(m.slug)}', this.value)" /> <span>${esc(AVAIL_LONG[k])}</span></label>`).join('')}
|
||
</div>
|
||
<div class="card"><h3>Przypisania<span class="n">${m.assignments.length}</span></h3>
|
||
${m.availability !== 'selected' ? '<div class="banner warn">Przypisania działają tylko przy dostępności „Wybrani”.</div>' : ''}
|
||
<div class="faint tiny" style="margin-bottom:10px">Moduł przypisany do jednostki dostają jej członkowie i członkowie jednostek podrzędnych.</div>
|
||
<div class="faint tiny" style="margin-bottom:10px">To nie jest jednorazowe nadanie: kto dołączy do jednostki, dostanie moduł, a kto odejdzie, straci go.</div>
|
||
${assigned}
|
||
<div class="assign">
|
||
<div class="row"><select id="asUnit" aria-label="Jednostka">${unitOptions(units)}</select>
|
||
<button class="btn sm" onclick="addAssignment('${esc(m.slug)}','unit')">Przypisz jednostkę</button></div>
|
||
<div class="row"><select id="asUser" aria-label="Użytkownik">${userOptions()}</select>
|
||
<button class="btn sm" onclick="addAssignment('${esc(m.slug)}','user')">Przypisz osobę</button></div>
|
||
</div>
|
||
</div>
|
||
${!sharesIdentity() || m.slug === hubSlug() ? '' : `<div class="card"><h3>Dostęp<span class="n">${people.length}</span></h3>
|
||
<div class="faint tiny" style="margin-bottom:10px">Bez wpisu nie da się wejść do modułu. Użytkownik z niego korzysta, moderator także nim zarządza (tylko tym modułem).</div>
|
||
<div class="faint tiny" style="margin-bottom:10px">Kto naprawdę ma ten moduł. Administrator wchodzi wszędzie bez wpisu.</div>
|
||
${roster}
|
||
<div class="assign">
|
||
<div class="row"><select id="mdUser" aria-label="Użytkownik">${userOptions()}</select>
|
||
${roleSelect('mdRole', 'user')}
|
||
<button class="btn sm" onclick="grantPermission('${esc(m.slug)}')">${svg(ICN.plus, 14)}<span>Nadaj dostęp</span></button></div>
|
||
</div>
|
||
</div>`}
|
||
<div class="card"><h3>Stan</h3>
|
||
<div class="row"><span id="probe-${esc(m.slug)}" class="tiny">—</span><span class="spacer"></span>
|
||
<button class="btn sm" onclick="probeOne('${esc(m.slug)}')" ${m.health_url ? '' : 'disabled'}>${svg(ICN.refresh)}<span>Sprawdź</span></button></div>
|
||
</div>
|
||
</div>
|
||
</div>`;
|
||
}
|
||
|
||
function saveModule(slug) {
|
||
mutate('PATCH', '/admin/modules/' + enc(slug), readModuleForm);
|
||
}
|
||
|
||
function saveAvailability(slug, availability) {
|
||
mutate('PATCH', '/admin/modules/' + enc(slug), { availability });
|
||
}
|
||
|
||
function addAssignment(slug, kind) {
|
||
mutate('POST', `/admin/modules/${enc(slug)}/assignments`,
|
||
kind === 'unit' ? { node_id: $('asUnit').value } : { user_id: $('asUser').value });
|
||
}
|
||
|
||
function removeAssignment(slug, id) {
|
||
mutate('DELETE', `/admin/modules/${enc(slug)}/assignments/${enc(id)}`);
|
||
}
|
||
|
||
/* Who may open one module, and at what role. Every write goes through mutate(), so they get the
|
||
toast, the re-render and the one error path for free. */
|
||
const roleSelect = (id, role, onchange) => `<select id="${esc(id)}"${onchange ? ` onchange="${onchange}"` : ''}>${
|
||
Object.keys(MODULE_ROLE_LABEL).map((k) =>
|
||
`<option value="${esc(k)}" ${k === role ? 'selected' : ''}>${esc(MODULE_ROLE_LABEL[k])}</option>`).join('')}</select>`;
|
||
|
||
function grantPermission(slug) {
|
||
mutate('POST', `/admin/modules/${enc(slug)}/moderators`,
|
||
() => ({ user_id: $('mdUser').value, role: $('mdRole').value }));
|
||
}
|
||
|
||
/* Promotion and demotion are the SAME call: the server's grant is an upsert, so the row stays and
|
||
with it the record of who admitted this person and when. */
|
||
function setPermission(slug, userId, role) {
|
||
mutate('POST', `/admin/modules/${enc(slug)}/moderators`, { user_id: userId, role });
|
||
}
|
||
|
||
/* Revoking may not empty the row: if a unit assignment still reaches this person they keep
|
||
ordinary access and merely stop being a moderator. Only the server knows which happened, so the
|
||
toast says what it did rather than claiming a revocation the re-render appears to undo. */
|
||
function revokePermission(slug, userId) {
|
||
guard(async () => {
|
||
const out = await api('DELETE', `/admin/modules/${enc(slug)}/moderators/${enc(userId)}`);
|
||
toast(out.still_a_member
|
||
? 'Dostęp cofnięty. Osoba nadal należy do jednostki, która ma ten moduł, więc zachowuje zwykły dostęp.'
|
||
: 'Zapisano.');
|
||
await router();
|
||
});
|
||
}
|
||
|
||
function deleteModule(slug) {
|
||
modal('Usuń', '',
|
||
'<div class="banner warn">Usunąć moduł? Znikną też jego przypisania i wnioski.</div><div class="faint tiny" style="margin-top:8px">Tej operacji nie da się cofnąć.</div>',
|
||
`<button class="btn" onclick="closeModal()">Anuluj</button>
|
||
<button class="btn danger" onclick="confirmDeleteModule('${esc(slug)}')">Usuń</button>`);
|
||
}
|
||
|
||
function confirmDeleteModule(slug) {
|
||
mutate('DELETE', '/admin/modules/' + enc(slug), undefined, { go: () => '#/admin/modules' });
|
||
}
|
||
|
||
/* ── administration: access requests ────────────────────────────────────── */
|
||
async function viewAdminRequests(C, q) {
|
||
const status = q.status === undefined ? 'pending' : q.status;
|
||
const rows = await api('GET', withQuery('/admin/access-requests', { status }));
|
||
// This list is the badge's count, unless it hit list_requests' 500-row cap: then ask for the total.
|
||
if (status === 'pending') { if (rows.length < 500) state.pending = rows.length; else await refreshPending(); }
|
||
setCrumb([{ label: 'Administracja' }, { label: 'Wnioski o dostęp' }]);
|
||
const tab = (s, label) => `<a class="chip ${status === s ? 'on' : ''}" href="#/admin/requests?status=${enc(s)}">${esc(label)}</a>`;
|
||
C.innerHTML = pageHead('Wnioski o dostęp', '')
|
||
+ `<div class="toolbar"><div class="row cats">${tab('pending', 'Oczekuje')}${tab('approved', 'Zatwierdzony')}${tab('declined', 'Odrzucony')}${tab('', 'Wszystkie')}</div></div>`
|
||
+ (rows.length ? `<div class="card"><div class="tablewrap"><table class="rt"><thead><tr>
|
||
<th>Użytkownik</th><th>Moduł</th><th>Notatka</th><th>Wysłano</th><th>Status</th><th></th>
|
||
</tr></thead><tbody>${rows.map((r) => `<tr>
|
||
<td><div>${dat(r.user.full_name)}<div class="mono tiny faint">${dat(r.user.email)}</div></div></td>
|
||
<td${lbl('Moduł')}><div class="cell">${moduleIcon(r.module, 24)}<a href="#/admin/modules/${enc(r.module.slug)}">${dat(r.module.name)}</a></div></td>
|
||
<td class="tiny"${lbl('Notatka')}>${r.note ? dat(r.note) : '—'}</td>
|
||
<td class="faint tiny"${lbl('Wysłano')}>${fmtDateTime(r.created_at)}</td>
|
||
<td${lbl('Status')}><div>${reqChip(r.status)}${r.decision_note ? `<div class="faint tiny">${dat(r.decision_note)}</div>` : ''}</div></td>
|
||
<td class="acts-cell"><div class="btncol">${r.status === 'pending' ? `<button class="btn sm" onclick="openDecision('${esc(r.id)}', true)">${svg(ICN.check, 14)}<span>Zatwierdź</span></button>
|
||
<button class="btn sm danger" onclick="openDecision('${esc(r.id)}', false)">${svg(ICN.x, 14)}<span>Odrzuć</span></button>` : ''}</div></td>
|
||
</tr>`).join('')}</tbody></table></div></div>` : '<div class="empty">Brak wniosków.</div>');
|
||
}
|
||
|
||
/* ── administration: publish requests ───────────────────────────────────── */
|
||
/* An agent version as lines to compare, like versionText for a skill: the pins by name and version. */
|
||
const agentVersionText = (v) => [v.instructions, '', `model_policy: ${JSON.stringify(v.model_policy || {})}`,
|
||
`tools: ${(v.tools_requested || []).join(', ')}`,
|
||
...v.skills.map((s) => `skill: ${s.slug} v${s.n}`)].join('\n');
|
||
|
||
async function viewAdminPublishRequests(C) {
|
||
const rows = await api('GET', '/admin/publish-requests');
|
||
setCrumb([{ label: 'Administracja' }, { label: 'Prośby o publikację' }]);
|
||
const text = (r, v) => (r.kind === 'agent' ? agentVersionText(v) : versionText(v));
|
||
// No base = the first publication: the whole version shows as added, which is what is being asked.
|
||
const card = (r) => `<div class="card">
|
||
<h3>${dat(r.item.name)} ${dat('v' + r.version.n)} <span class="chip">${r.kind === 'agent' ? 'Agent' : 'Skill'}</span></h3>
|
||
<div class="faint tiny">${dat(r.requested_by.full_name)} · ${dat(r.requested_by.email)} · ${esc(fmtDateTime(r.created_at))}</div>
|
||
<div class="tiny">${r.base ? `<span>Różnice względem</span> ${dat('v' + r.base.n)} <span>(aktualna w firmie)</span>` : '<span>Pierwsza publikacja w firmie</span>'}</div>
|
||
${diffHtml(r.base ? text(r, r.base) : '', text(r, r.version))}
|
||
<div class="acts-row"><button class="btn sm" onclick="openDecision('${esc(r.id)}', true, 'publish-requests')">${svg(ICN.check, 14)}<span>Zatwierdź</span></button>
|
||
<button class="btn sm danger" onclick="openDecision('${esc(r.id)}', false, 'publish-requests')">${svg(ICN.x, 14)}<span>Odrzuć</span></button></div>
|
||
</div>`;
|
||
C.innerHTML = pageHead('Prośby o publikację', 'Skille i agenci, które ktoś chce udostępnić całej firmie.')
|
||
+ (rows.length ? rows.map(card).join('') : '<div class="empty">Brak próśb o publikację.</div>');
|
||
}
|
||
|
||
function openDecision(id, approve, queue = 'access-requests') {
|
||
modal(approve ? 'Zatwierdź' : 'Odrzuć', '',
|
||
'<label class="field">Notatka<textarea id="dcNote" maxlength="1000" placeholder="Notatka do decyzji (opcjonalnie)"></textarea></label>',
|
||
`<button class="btn" onclick="closeModal()">Anuluj</button>
|
||
<button class="btn ${approve ? 'primary' : 'danger'}" onclick="sendDecision('${esc(id)}', ${approve ? 'true' : 'false'}, '${esc(queue)}')">${approve ? 'Zatwierdź' : 'Odrzuć'}</button>`);
|
||
}
|
||
|
||
function sendDecision(id, approve, queue = 'access-requests') {
|
||
mutate('POST', `/admin/${queue}/${enc(id)}/${approve ? 'approve' : 'decline'}`, { note: $('dcNote').value || null });
|
||
}
|
||
|
||
/* ── administration: organization ───────────────────────────────────────── */
|
||
async function viewAdminOrg(C) {
|
||
const units = await api('GET', '/tree/containers');
|
||
setCrumb([{ label: 'Administracja' }, { label: 'Organizacja' }]);
|
||
const depth = (p) => Math.max(0, p.split('/').length - 2);
|
||
C.innerHTML = pageHead('Organizacja', '',
|
||
`<button class="btn primary" onclick="openUnitNew()">${svg(ICN.plus)}<span>Nowa jednostka</span></button>`)
|
||
+ '<div class="banner" style="margin-bottom:14px">Członkowie jednostki otrzymują moduły przypisane do niej i do jednostek nadrzędnych.</div>'
|
||
+ (units.length ? `<div class="card units">${units.map((u) => `<div class="unit" style="--depth:${depth(u.path)}">
|
||
<div class="unit-main">
|
||
<div class="cell">${svg(ICN.workspace)}<b>${dat(u.name)}</b><span class="chip">${esc(KIND_LABEL[u.kind] || u.kind)}</span></div>
|
||
<div class="mono tiny faint wrap">${dat(u.path)}</div>
|
||
</div>
|
||
<div class="unit-acts">
|
||
<button class="btn sm" onclick="openMembers('${esc(u.id)}')">${svg(ICN.users, 14)}<span>Członkowie</span></button>
|
||
<button class="btn sm" onclick="openUnitNew('${esc(u.id)}')" title="Nowa jednostka">${svg(ICN.plus, 14)}</button>
|
||
${u.parent_id ? `<button class="btn sm danger" onclick="deleteUnit('${esc(u.id)}')" title="Usuń">${svg(ICN.trash, 14)}</button>` : ''}
|
||
</div></div>`).join('')}</div>` : '<div class="empty">—</div>');
|
||
state._units = units;
|
||
}
|
||
|
||
function openUnitNew(parentId) {
|
||
const units = state._units || [];
|
||
const parent = parentId || (units[0] && units[0].id) || '';
|
||
modal('Nowa jednostka', '',
|
||
`<label class="field">Jednostka nadrzędna<select id="unParent">${unitOptions(units, parent)}</select></label>
|
||
<div class="grid2">
|
||
<label class="field">Rodzaj${choice('unKind', { group: KIND_LABEL.group, folder: KIND_LABEL.folder }, 'group')}</label>
|
||
<label class="field">Nazwa<input id="unName" maxlength="200" /></label>
|
||
</div>`,
|
||
`<button class="btn" onclick="closeModal()">Anuluj</button>
|
||
<button class="btn primary" onclick="saveUnitNew()">Zapisz</button>`);
|
||
}
|
||
|
||
function saveUnitNew() {
|
||
mutate('POST', '/nodes', { kind: $('unKind').value, name: $('unName').value, parent_id: $('unParent').value });
|
||
}
|
||
|
||
function deleteUnit(id) {
|
||
modal('Usuń', '', '<div class="banner warn">Usunąć jednostkę?</div>',
|
||
`<button class="btn" onclick="closeModal()">Anuluj</button>
|
||
<button class="btn danger" onclick="confirmDeleteUnit('${esc(id)}')">Usuń</button>`);
|
||
}
|
||
|
||
function confirmDeleteUnit(id) {
|
||
mutate('DELETE', '/nodes/' + enc(id));
|
||
}
|
||
|
||
async function openMembers(id) {
|
||
const unit = (state._units || []).find((u) => u.id === id) || { name: '', path: '' };
|
||
const [g] = await Promise.all([api('GET', `/nodes/${enc(id)}/grants`), ensureUsers()]);
|
||
const roleName = (r) => esc(ROLE_LABEL[r] || r);
|
||
const direct = new Set(g.direct.map((x) => x.user_id));
|
||
const inherited = g.inherited.filter((x) => !direct.has(x.user_id));
|
||
const body = `<h4 class="minor">Bezpośrednio</h4>`
|
||
+ (g.direct.length ? `<div class="tablewrap"><table><tbody>${g.direct.map((x) => `<tr>
|
||
<td>${dat(x.name)}<div class="mono tiny faint">${dat(x.email)}</div></td><td><span class="chip">${roleName(x.role)}</span></td>
|
||
<td class="shrink"><button class="btn sm danger" onclick="confirmTwice(this, () => removeMember('${esc(id)}','${esc(x.user_id)}'))" title="Usuń">${svg(ICN.x, 14)}</button></td>
|
||
</tr>`).join('')}</tbody></table></div>` : '<div class="faint tiny">Brak członków.</div>')
|
||
+ (inherited.length ? `<h4 class="minor">Dostęp z jednostki nadrzędnej</h4>
|
||
<div class="faint tiny" style="margin-bottom:6px">Mogą przeglądać lub zarządzać tą jednostką, ale nie są jej członkami — nie otrzymują przypisanych do niej modułów.</div>
|
||
<div class="tablewrap"><table><tbody>${inherited.map((x) => `<tr>
|
||
<td>${dat(x.name)}<div class="mono tiny faint">${dat(x.email)}</div></td><td><span class="chip">${esc(ACCESS_LABEL[x.role] || x.role)}</span></td>
|
||
<td class="faint tiny">${dat(x.from || '')}</td></tr>`).join('')}</tbody></table></div>` : '')
|
||
+ `<div class="row" style="margin-top:14px">
|
||
<select id="mbUser" aria-label="Użytkownik">${userOptions()}</select>
|
||
${choice('mbRole', { viewer: ROLE_LABEL.viewer, manager: ROLE_LABEL.manager }, 'viewer')}
|
||
<button class="btn sm primary" onclick="addMember('${esc(id)}')">${svg(ICN.plus, 14)}<span>Dodaj</span></button></div>`;
|
||
modal('Członkowie', unit.path, body, '<button class="btn" onclick="closeModal()">Zamknij</button>', { wide: true });
|
||
}
|
||
|
||
function addMember(id) {
|
||
mutate('PUT', `/nodes/${enc(id)}/grants`, { user_id: $('mbUser').value, role: $('mbRole').value },
|
||
{ reopen: () => openMembers(id) });
|
||
}
|
||
|
||
function removeMember(id, userId) {
|
||
mutate('DELETE', `/nodes/${enc(id)}/grants/${enc(userId)}`, undefined, { reopen: () => openMembers(id) });
|
||
}
|
||
|
||
/* ── administration: users ──────────────────────────────────────────────── */
|
||
/* ONE admin pane. Every account on the platform is made, elevated and switched off here, because
|
||
the hub is the only writer of identity — a module's database role cannot create or change an
|
||
account at all. Three words, used exactly: ADMINISTRATOR is platform-wide, MODERATOR administers
|
||
one module, USER may open one. An administrator reaches everything, so the row shows that rather
|
||
than a list; for everyone else it shows the modules they may open, and names the moderated ones.
|
||
No chips at all means an account that can sign in and open nothing, which is a real state and
|
||
the default for a new person. */
|
||
const tierChips = (u) => (u.is_admin
|
||
? '<span class="chip">Administrator</span>'
|
||
: Object.entries(u.modules || {}).map(([s, role]) => `<span class="chip">${
|
||
role === 'moderator' ? 'Moderator: ' : ''}${dat(moduleName(s))}</span>`).join(''))
|
||
|| '<span class="faint tiny">—</span>';
|
||
|
||
/* The catalogue, read once for the pickers and the chip labels. A slug always renders, even for a
|
||
module that has since left the catalogue: the grant is real and the pane must not hide it. */
|
||
const moduleName = (slug) => ((state.modules || []).find((m) => m.slug === slug) || {}).name || slug;
|
||
async function ensureModules() {
|
||
if (!state.modules) {
|
||
try { state.modules = await api('GET', '/admin/modules'); } catch { state.modules = []; }
|
||
}
|
||
}
|
||
|
||
async function viewAdminUsers(C) {
|
||
[state.users] = await Promise.all([api('GET', '/users'), ensureModules()]);
|
||
setCrumb([{ label: 'Administracja' }, { label: 'Użytkownicy' }]);
|
||
C.innerHTML = pageHead('Użytkownicy', '',
|
||
`<button class="btn primary" onclick="openUserNew()">${svg(ICN.plus)}<span>Nowy użytkownik</span></button>`)
|
||
+ `<div class="card"><h3>Konta<span class="n">${state.users.length}</span></h3>
|
||
<div class="faint tiny" style="margin-bottom:10px">Jedno konto na osobę, wspólne dla wszystkich modułów. Logowanie odbywa się tutaj; moduły tylko odczytują tę samą sesję.</div>
|
||
<div class="tablewrap"><table class="rt"><thead><tr>
|
||
<th>Nazwa</th><th>E-mail</th><th>Rola</th><th>Status</th><th></th>
|
||
</tr></thead><tbody>${state.users.map((u) => `<tr>
|
||
<td>${dat(u.full_name)}</td>
|
||
<td class="mono wrap"${lbl('E-mail')}>${dat(u.email)}</td>
|
||
<td${lbl('Rola')}><div class="row">${tierChips(u)}</div></td>
|
||
<td${lbl('Status')}>${u.is_active ? '<span class="chip ok">aktywny</span>' : '<span class="chip err">nieaktywny</span>'}</td>
|
||
<td class="acts-cell shrink"><div class="row">
|
||
<button class="btn sm" onclick="openUserEdit('${esc(u.id)}')">Edytuj</button>
|
||
<button class="btn sm" onclick="openUserAccess('${esc(u.id)}')">Uprawnienia</button>
|
||
${u.is_active
|
||
? (u.id === state.user.id ? '' : `<button class="btn sm danger" onclick="deactivateUser('${esc(u.id)}')">Dezaktywuj</button>`)
|
||
: `<button class="btn sm" onclick="reactivateUser('${esc(u.id)}')">Przywróć</button>`}
|
||
</div></td>
|
||
</tr>`).join('')}</tbody></table></div></div>`;
|
||
}
|
||
|
||
/* One person, both tiers, one dialog — which is what "one admin pane" has to mean in practice, or
|
||
an administrator ends up visiting four module pages to answer "what can this person do?".
|
||
Everything writes through mutate(..., { reopen }), so the dialog stays open and redraws itself. */
|
||
async function openUserAccess(id) {
|
||
await ensureModules();
|
||
const u = (state.users || []).find((x) => x.id === id);
|
||
if (!u) { toast('Nie znaleziono użytkownika.'); return; }
|
||
const held = u.modules || {};
|
||
const free = grantable().filter((m) => !(m.slug in held));
|
||
const self = u.id === state.user.id;
|
||
|
||
/* The platform-wide tier. The checkbox writes on change rather than on a Save button, because
|
||
there is nothing else in this dialog to save together with it — and every write is audited. */
|
||
const administrator = `<label class="check"><input type="checkbox" id="uaAdmin" ${u.is_admin ? 'checked' : ''}
|
||
onchange="setAdministrator('${esc(id)}', this.checked)" /> <span>Administrator</span></label>
|
||
<div class="faint tiny">Pełne uprawnienia na całej platformie: wszystkie moduły i sam Atrium. Ostatniego administratora nie da się odebrać ani dezaktywować.</div>
|
||
${self && u.is_admin ? '<div class="banner warn">To twoje własne konto. Po odebraniu sobie roli nie przywrócisz jej samodzielnie.</div>' : ''}`;
|
||
|
||
/* Which modules this person may open, and at what role — the same `module_permission` rows a
|
||
module's own page lists, seen from the other side. Only exists when this Atrium is the hub of
|
||
a platform; on a standalone install the whole section is absent rather than present and
|
||
refused. */
|
||
const roster = Object.keys(held).length
|
||
? `<div class="tablewrap"><table><tbody>${Object.entries(held).map(([s, role]) => `<tr>
|
||
<td>${dat(moduleName(s))}<div class="mono tiny faint">${dat(s)}</div></td>
|
||
<td class="shrink">${roleSelect(`ua-${esc(s)}`, role, `setModuleFor('${esc(s)}','${esc(id)}', this.value)`)}</td>
|
||
<td class="shrink"><button class="btn sm danger" onclick="confirmTwice(this, () => removeModuleFor('${esc(s)}','${esc(id)}'))" title="Odbierz">${svg(ICN.x, 14)}</button></td>
|
||
</tr>`).join('')}</tbody></table></div>`
|
||
: '<div class="faint tiny">Nie ma dostępu do żadnego modułu.</div>';
|
||
const picker = free.length
|
||
? `<div class="row" style="margin-top:12px">
|
||
<select id="uaModule">${free.map((m) => `<option value="${esc(m.slug)}">${esc(m.name)}</option>`).join('')}</select>
|
||
${roleSelect('uaRole', 'user')}
|
||
<button class="btn sm primary" onclick="addModuleFor('${esc(id)}')">${svg(ICN.plus, 14)}<span>Dodaj</span></button></div>`
|
||
: '';
|
||
const moderator = !sharesIdentity() ? '' : `<h4 class="minor">Dostęp do modułów</h4>
|
||
<div class="faint tiny" style="margin-bottom:6px">Bez wpisu na tej liście osoba nie wejdzie do modułu. Moderator dodatkowo zarządza jednym modułem i nie ma uprawnień w pozostałych.</div>
|
||
${u.is_admin ? '<div class="faint tiny">Administrator wchodzi do każdego modułu i zarządza nim niezależnie od tej listy.</div>' : ''}
|
||
${roster}${picker}`;
|
||
|
||
modal('Uprawnienia', u.email, administrator + moderator,
|
||
'<button class="btn" onclick="closeModal()">Zamknij</button>', { wide: true });
|
||
}
|
||
|
||
/* After any tier change the dialog is rebuilt from a FRESH /users read, not from the row it was
|
||
opened with — otherwise a second change in the same dialog would send stale state. */
|
||
async function _reopenUserAccess(id) {
|
||
state.users = await api('GET', '/users');
|
||
await openUserAccess(id);
|
||
}
|
||
|
||
function setAdministrator(id, isAdmin) {
|
||
mutate('POST', `/users/${enc(id)}/administrator`, { is_admin: !!isAdmin },
|
||
{ reopen: () => _reopenUserAccess(id) });
|
||
}
|
||
|
||
function addModuleFor(id) {
|
||
mutate('POST', `/admin/modules/${enc($('uaModule').value)}/moderators`,
|
||
() => ({ user_id: id, role: $('uaRole').value }),
|
||
{ reopen: () => _reopenUserAccess(id) });
|
||
}
|
||
|
||
function setModuleFor(slug, id, role) {
|
||
mutate('POST', `/admin/modules/${enc(slug)}/moderators`, { user_id: id, role },
|
||
{ reopen: () => _reopenUserAccess(id) });
|
||
}
|
||
|
||
function removeModuleFor(slug, id) {
|
||
mutate('DELETE', `/admin/modules/${enc(slug)}/moderators/${enc(id)}`, undefined,
|
||
{ reopen: () => _reopenUserAccess(id) });
|
||
}
|
||
|
||
/* Correcting a name or an email, and resetting a forgotten password. Both live HERE and nowhere
|
||
else, for the same reason the tiers do: the hub is the only writer of identity, so a correction
|
||
this pane cannot make cannot be made anywhere on the platform. Before these two dialogs existed,
|
||
a person who forgot their password was locked out of all four modules until somebody ran an
|
||
UPDATE by hand as the identity owner — `POST /me/password` needs the password they have lost,
|
||
a module's own reset answers 409, and there is no e-mail reset to fall back on. */
|
||
function _person(id) {
|
||
const u = (state.users || []).find((x) => x.id === id);
|
||
if (!u) toast('Nie znaleziono użytkownika.');
|
||
return u;
|
||
}
|
||
|
||
function openUserEdit(id) {
|
||
const u = _person(id);
|
||
if (!u) return;
|
||
/* Two different acts, so two buttons and two audit rows — but one dialog, because "fix this
|
||
person's account" is one errand and the row already carries as many buttons as it can hold. */
|
||
modal('Edytuj konto', u.email,
|
||
`<label class="field">Imię i nazwisko<input id="ueFull" maxlength="200" value="${esc(u.full_name)}" /></label>
|
||
<label class="field">E-mail<input id="ueEmail" type="email" autocomplete="off" spellcheck="false" value="${esc(u.email)}" /></label>
|
||
<div class="faint tiny">E-mail jest nazwą, którą wpisuje się przy logowaniu — jedną dla całej platformy. Zmiana nie kończy sesji tej osoby.</div>
|
||
<h4 class="minor">Hasło</h4>
|
||
<div class="faint tiny" style="margin-bottom:8px">Dla osoby, która zapomniała hasła: tylko administrator może je ustawić, bo konta zapisuje wyłącznie Atrium.</div>
|
||
<div class="row"><button class="btn" onclick="openUserPassword('${esc(id)}')">Ustaw hasło</button></div>`,
|
||
`<button class="btn" onclick="closeModal()">Anuluj</button>
|
||
<button class="btn primary" onclick="saveUserEdit('${esc(id)}')">Zapisz</button>`);
|
||
}
|
||
|
||
function saveUserEdit(id) {
|
||
mutate('POST', `/users/${enc(id)}/profile`,
|
||
() => ({ full_name: $('ueFull').value, email: $('ueEmail').value }));
|
||
}
|
||
|
||
function openUserPassword(id) {
|
||
const u = _person(id);
|
||
if (!u) return;
|
||
/* The warning is not a formality: the reset revokes every session and app token the person holds,
|
||
in every module, because whoever opened them knew the old password. */
|
||
modal('Ustaw hasło', u.email,
|
||
`<div class="banner warn">Nowe hasło kończy wszystkie sesje i tokeny tej osoby. Przekaż je bezpiecznie i poproś o zmianę po zalogowaniu.</div>
|
||
<label class="field">Nowe hasło<input id="upPass" type="password" minlength="10" autocomplete="new-password" /></label>
|
||
<div class="faint tiny">Co najmniej 10 znaków. Zdarzenie trafia do dziennika wraz z tym, kto je wykonał.</div>`,
|
||
`<button class="btn" onclick="closeModal()">Anuluj</button>
|
||
<button class="btn primary" onclick="saveUserPassword('${esc(id)}')">Ustaw hasło</button>`);
|
||
}
|
||
|
||
function saveUserPassword(id) {
|
||
mutate('POST', `/users/${enc(id)}/password`, () => ({ new_password: $('upPass').value }),
|
||
{ done: 'Hasło ustawione. Sesje tej osoby zostały zakończone.' });
|
||
}
|
||
|
||
async function openUserNew() {
|
||
await ensureModules();
|
||
const choices = grantable();
|
||
/* Both tiers on the creation form, so an administrator can finish the job in one dialog instead
|
||
of creating the person and then visiting a module page. Both default to off. */
|
||
/* Access is off by default and granted as USER here — promoting somebody is a deliberate act on
|
||
that module's own page, one person at a time. Modules with availability „Wszyscy” arrive
|
||
anyway, without being named: the server materialises those rows as the account is created. */
|
||
const tiers = `<label class="check"><input type="checkbox" id="unAdmin" /> <span>Administrator</span></label>
|
||
<div class="faint tiny">${sharesIdentity()
|
||
? 'Konto samo w sobie nie otwiera żadnego modułu — dostęp nadaje się poniżej albo później. Rola administratora jest domyślnie wyłączona.'
|
||
: 'Rola jest domyślnie wyłączona — nadaje się ją świadomie.'}</div>`
|
||
+ (sharesIdentity() && choices.length ? `<label class="field">Dostęp do modułów
|
||
<select id="unMods" multiple size="${Math.min(5, Math.max(2, choices.length))}">${
|
||
choices.map((m) => `<option value="${esc(m.slug)}">${esc(m.name)}</option>`).join('')}</select></label>
|
||
<div class="faint tiny">Jako użytkownik. Moderatora nadaje się na stronie danego modułu.</div>` : '');
|
||
modal('Nowy użytkownik', '',
|
||
`<label class="field">Imię i nazwisko<input id="unFull" maxlength="200" /></label>
|
||
<label class="field">E-mail<input id="unEmail" type="email" autocomplete="off" spellcheck="false" /></label>
|
||
<label class="field">Hasło<input id="unPass" type="password" minlength="10" autocomplete="new-password" /></label>
|
||
${tiers}`,
|
||
`<button class="btn" onclick="closeModal()">Anuluj</button>
|
||
<button class="btn primary" onclick="saveUserNew()">Zapisz</button>`);
|
||
}
|
||
|
||
function saveUserNew() {
|
||
mutate('POST', '/users', () => ({
|
||
full_name: $('unFull').value, email: $('unEmail').value,
|
||
password: $('unPass').value, is_admin: $('unAdmin').checked,
|
||
// slug -> role. Absent on a standalone install, where the field is not rendered at all.
|
||
modules: $('unMods')
|
||
? Object.fromEntries(Array.from($('unMods').selectedOptions).map((o) => [o.value, 'user']))
|
||
: {},
|
||
}));
|
||
}
|
||
|
||
function deactivateUser(id) {
|
||
modal('Dezaktywuj', '', '<div class="banner warn">Dezaktywować użytkownika? Jego sesje we wszystkich modułach zostaną zakończone.</div>',
|
||
`<button class="btn" onclick="closeModal()">Anuluj</button>
|
||
<button class="btn danger" onclick="confirmDeactivate('${esc(id)}')">Dezaktywuj</button>`);
|
||
}
|
||
|
||
function confirmDeactivate(id) {
|
||
mutate('POST', `/users/${enc(id)}/deactivate`);
|
||
}
|
||
|
||
function reactivateUser(id) {
|
||
mutate('POST', `/users/${enc(id)}/reactivate`, undefined, { done: 'Konto przywrócone.' });
|
||
}
|
||
|
||
/* ── administration: settings ───────────────────────────────────────────── */
|
||
const SETTING_UI = {
|
||
instance_name: { label: 'Nazwa instancji', help: 'Pokazywana w pasku bocznym i tytule strony.' },
|
||
welcome_message: { label: 'Powitanie na stronie głównej', help: 'Zwykły tekst nad listą aplikacji.', area: true },
|
||
support_contact: { label: 'Kontakt w sprawie dostępu', help: 'Pokazywany w katalogu jako tekst, nie link.' },
|
||
launcher_open_mode: { label: 'Otwieranie modułów', choices: { new_tab: 'Nowa karta', same_tab: 'Ta sama karta' } },
|
||
allow_access_requests: { label: 'Wnioski o dostęp dozwolone', help: 'Użytkownicy mogą prosić o moduły dostępne dla wybranych.' },
|
||
default_availability: { label: 'Domyślna dostępność nowego modułu', choices: AVAIL_LONG },
|
||
skills_firm_publish: { label: 'Publikacja skilli i agentów w firmie', help: 'Zgoda dotyczy każdej wersji, nie tylko pierwszej.',
|
||
choices: { approval: 'Za zgodą administratora', direct: 'Od razu, bez zgody' } },
|
||
skills_firm_export: { label: 'Eksport firmowych skilli i agentów', help: 'Własne osobiste może eksportować każdy.',
|
||
choices: { administrator: 'Tylko administrator', everyone: 'Każdy' } },
|
||
};
|
||
|
||
async function viewAdminSettings(C) {
|
||
const specs = await api('GET', '/admin/settings');
|
||
setCrumb([{ label: 'Ustawienia' }, { label: 'Ogólne' }]);
|
||
const input = (s) => {
|
||
const ui = SETTING_UI[s.key] || { label: s.key };
|
||
const id = 'st_' + s.key;
|
||
const help = ui.help ? `<div class="faint tiny">${esc(ui.help)}</div>` : '';
|
||
if (s.kind === 'bool') {
|
||
return `<label class="check"><input type="checkbox" id="${id}" ${s.value ? 'checked' : ''} /> <span>${esc(ui.label)}</span></label>${help}`;
|
||
}
|
||
if (s.kind === 'choice') {
|
||
const labels = {};
|
||
s.choices.forEach((c) => { labels[c] = (ui.choices && ui.choices[c]) || c; });
|
||
return `<label class="field">${esc(ui.label)}${choice(id, labels, s.value)}</label>${help}`;
|
||
}
|
||
const max = s.max_length ? `maxlength="${s.max_length}"` : '';
|
||
return ui.area
|
||
? `<label class="field">${esc(ui.label)}<textarea id="${id}" ${max}>${esc(s.value)}</textarea></label>${help}`
|
||
: `<label class="field">${esc(ui.label)}<input id="${id}" ${max} value="${esc(s.value)}" /></label>${help}`;
|
||
};
|
||
C.innerHTML = pageHead('Ogólne', '')
|
||
+ `<div class="card settings"><div class="stack">${specs.map((s) => `<div>${input(s)}</div>`).join('')}</div>
|
||
<div class="acts-row"><button class="btn primary" onclick="saveSettings()">${svg(ICN.check)}<span>Zapisz</span></button></div></div>`;
|
||
state._settings = specs;
|
||
}
|
||
|
||
function saveSettings() {
|
||
const values = {};
|
||
(state._settings || []).forEach((s) => {
|
||
const el = $('st_' + s.key);
|
||
if (!el) return;
|
||
const v = s.kind === 'bool' ? el.checked : el.value;
|
||
if (v !== s.value) values[s.key] = v;
|
||
});
|
||
if (!Object.keys(values).length) { toast('Zapisano.'); return; }
|
||
mutate('PUT', '/admin/settings', { values });
|
||
}
|
||
|
||
/* ── administration: model providers ────────────────────────────────────── */
|
||
/* The platform's model providers and their usage policy (dredd-core 0.15.0; the hub is the only
|
||
writer, every module reads them). Deliberately plain: functional and minimal, built from the same
|
||
pieces as the other admin screens — the look is Tobiasz's to replace.
|
||
The key is WRITE-ONLY: the API never returns it (only has_key / key_prefix), so the field is
|
||
always empty, "leave empty to keep", and removing it is its own action. The console never calls
|
||
a provider itself: "Odśwież modele" asks the hub (`/refresh`), which reads the provider's list
|
||
under the outbound limits of integrations/model_server.py. */
|
||
const PROVIDER_KIND = { api: 'API (zewnętrzny)', local: 'lokalny' };
|
||
/* A provider's mark in its colour, recognised by the host it answers on (the console holds no
|
||
key-prefix catalogue — that is services/providers.py's): its logotype where BRAND has one
|
||
(PROVIDER_BRAND), else a monogram. */
|
||
const PROVIDER_HUE = { 'api.anthropic.com': 'orange', 'api.openai.com': 'teal', 'openrouter.ai': 'indigo' };
|
||
const PROVIDER_BRAND = { 'api.anthropic.com': 'anthropic', 'openrouter.ai': 'openrouter' };
|
||
function providerIcon(p) {
|
||
let host = '';
|
||
try { host = new URL(p.base_url).hostname; } catch { /* the row is shown anyway, in gray */ }
|
||
const hue = PROVIDER_HUE[host] || (p.kind === 'local' ? 'gray' : 'blue');
|
||
const letter = ((p.name || host || '?').trim()[0] || '?').toUpperCase();
|
||
return `<span class="mi h-${hue}" style="--mi:28px">${markSvg(PROVIDER_BRAND[host], letter)}</span>`;
|
||
}
|
||
const PROVIDER_LEVEL = { nobody: 'Nikt', admins_only: 'Tylko administratorzy', everyone: 'Każdy' };
|
||
/* dredd-core 0.18.0: whose key a call carries — one source per provider, never a fallback. */
|
||
const KEY_MODE = { firm: 'Klucz firmy', user: 'Własny klucz użytkownika', none: 'Bez klucza' };
|
||
|
||
async function viewAdminProviders(C) {
|
||
const [rows, policy] = await Promise.all([api('GET', '/admin/model-providers'),
|
||
api('GET', '/admin/model-providers/policy')]);
|
||
state._providers = rows;
|
||
state._providerPolicy = policy;
|
||
setCrumb([{ label: 'Ustawienia' }, { label: 'Dostawcy modeli' }]);
|
||
C.innerHTML = pageHead('Dostawcy modeli', '',
|
||
`<button class="btn primary" onclick="openAddProvider()">${svg(ICN.plus)}<span>Dodaj dostawcę</span></button>`)
|
||
+ `<div class="faint tiny" style="margin-bottom:10px">Obowiązuje we wszystkich modułach. Wyłączonego dostawcę można usunąć, dopóki nie policzył żadnego przebiegu; potem zostaje na liście, bo przebiegi pamiętają, kto je policzył.</div>`
|
||
+ `<div class="card"><h3>Polityka użycia</h3><div class="stack">
|
||
<label class="field">Kto może używać modeli${choice('ppLevel', PROVIDER_LEVEL, policy.level)}</label>
|
||
<label class="check"><input type="checkbox" id="ppEu" ${policy.eu_only ? 'checked' : ''} /> <span>Tylko dostawcy z UE/EOG (lub lokalni)</span></label>
|
||
</div><div class="acts-row"><button class="btn primary" onclick="saveProviderPolicy()">${svg(ICN.check)}<span>Zapisz politykę</span></button></div></div>`
|
||
+ (rows.length ? `<div class="card"><div class="tablewrap"><table class="rt"><thead><tr>
|
||
<th>Dostawca</th><th>Modele</th><th>Czyj klucz</th><th>Status</th><th></th>
|
||
</tr></thead><tbody>${rows.map((p) => `<tr>
|
||
<td><div class="row">${providerIcon(p)}<div><div>${dat(p.name)}</div><div class="mono tiny faint wrap" data-no-i18n>${esc(p.base_url)}</div></div></div></td>
|
||
<td class="mono"${lbl('Modele')} data-no-i18n>${esc(String((p.models || []).length))}</td>
|
||
<td${lbl('Czyj klucz')}><span class="chip">${esc(KEY_MODE[p.key_mode] || p.key_mode)}</span></td>
|
||
<td${lbl('Status')}>${p.is_active === false ? '<span class="chip err">wyłączony</span>'
|
||
: policy.eu_only && !p.stays_in_the_eu
|
||
? '<span class="chip warn" title="Polityka „Tylko dostawcy z UE/EOG” ukrywa jego modele. Odznacz ją albo podaj region w Szczegółach.">ukryty: tylko UE</span>'
|
||
: '<span class="chip ok">aktywny</span>'}</td>
|
||
<td class="acts-cell shrink"><div class="row">
|
||
<button class="btn sm" data-pid="${esc(p.id)}" onclick="refreshProvider(this.dataset.pid)">${svg(ICN.refresh)}<span>Odśwież modele</span></button>
|
||
<button class="btn sm" data-pid="${esc(p.id)}" onclick="openProviderForm(this.dataset.pid)">Szczegóły</button>
|
||
${p.is_active
|
||
? `<button class="btn sm danger" data-pid="${esc(p.id)}" onclick="disableProvider(this.dataset.pid)">Wyłącz</button>`
|
||
: `<button class="btn sm" data-pid="${esc(p.id)}" onclick="enableProvider(this.dataset.pid)">Włącz</button>
|
||
<button class="btn sm danger" data-pid="${esc(p.id)}" onclick="deleteProvider(this.dataset.pid)">Usuń</button>`}
|
||
</div></td>
|
||
</tr>`).join('')}</tbody></table></div></div>` : '<div class="empty">Brak dostawców modeli.</div>');
|
||
}
|
||
|
||
/* "Dodaj dostawcę": one field. The hub recognises what was pasted and lists its models (`discover`,
|
||
which holds the key-prefix catalogue — the console does not copy it); the preview is read-only
|
||
but the name. The key is never rendered or kept: it stays in its input until "Dodaj" sends it once,
|
||
and any edit drops the preview, so what is added is always what was checked. */
|
||
const isAddress = (text) => /^https?:\/\//i.test(text.trim());
|
||
|
||
function openAddProvider() {
|
||
state._discovered = null;
|
||
modal('Dodaj dostawcę', '', `<label class="field">Wklej klucz API albo adres serwera<input id="apInput"
|
||
autocomplete="off" spellcheck="false" maxlength="4096" oninput="addProviderInput()" /></label>
|
||
<label class="field hidden" id="apKeyRow">Klucz (jeśli serwer go wymaga)<input id="apKey" type="password"
|
||
autocomplete="new-password" maxlength="4096" oninput="addProviderInput()" /></label>
|
||
<div id="apPreview" class="stack"></div>`,
|
||
`<button class="btn" onclick="closeModal()">Anuluj</button>
|
||
<button class="btn" onclick="discoverProvider()">Sprawdź</button>
|
||
<button class="btn primary hidden" id="apAdd" onclick="addProvider()">Dodaj</button>`,
|
||
{ wide: true });
|
||
}
|
||
|
||
function addProviderInput() {
|
||
$('apKeyRow').classList.toggle('hidden', !isAddress($('apInput').value));
|
||
state._discovered = null;
|
||
$('apPreview').innerHTML = '';
|
||
$('apAdd').classList.add('hidden');
|
||
}
|
||
|
||
function discoverProvider() {
|
||
const input = $('apInput').value.trim();
|
||
const key = isAddress(input) ? $('apKey').value.trim() : '';
|
||
mutate('POST', '/admin/model-providers/discover', key ? { input, key } : { input },
|
||
{ reopen: showDiscovered, done: 'Znaleziono modele.' });
|
||
}
|
||
|
||
function showDiscovered(r) {
|
||
state._discovered = r;
|
||
const stale = $('modalBody').querySelector('.banner.err');
|
||
if (stale) stale.remove();
|
||
$('apPreview').innerHTML = `<div class="row">${providerIcon(r)}
|
||
<label class="field">Nazwa<input id="apName" maxlength="120" value="${esc(r.name)}" /></label></div>
|
||
<div class="faint tiny">${esc(PROVIDER_KIND[r.kind] || r.kind)} · <span class="mono" data-no-i18n>${esc(r.base_url)}</span></div>
|
||
<ul class="mono tiny" data-no-i18n>${r.models.map((m) => `<li>${esc(m.id)}</li>`).join('')}</ul>`;
|
||
localize($('apPreview'));
|
||
$('apAdd').classList.remove('hidden');
|
||
}
|
||
|
||
/* A recognised vendor (a key) also suggests the processor's name; region and DPA are the
|
||
administrator's to fill in under "Szczegóły" — nothing about a vendor is asserted here. */
|
||
function addProvider() {
|
||
const r = state._discovered;
|
||
if (!r) return;
|
||
const input = $('apInput').value.trim();
|
||
const key = isAddress(input) ? $('apKey').value.trim() : input;
|
||
const body = { name: $('apName').value.trim(), kind: r.kind, base_url: r.base_url, models: r.models,
|
||
trains_on_data: false };
|
||
if (r.vendor) body.processor_name = r.name;
|
||
if (key) body.api_key = key;
|
||
mutate('POST', '/admin/model-providers', body);
|
||
}
|
||
|
||
function openProviderForm(id) {
|
||
const p = (state._providers || []).find((x) => x.id === id);
|
||
if (!p) { toast('Nie znaleziono strony.'); return; }
|
||
const writable = !!(state._providerPolicy && state._providerPolicy.keys_writable);
|
||
const allowed = { '': 'Zgodnie z polityką', ...PROVIDER_LEVEL };
|
||
const body = `<div class="grid2">
|
||
<label class="field">Nazwa<input id="pfName" maxlength="120" value="${esc(p.name || '')}" /></label>
|
||
<label class="field">Rodzaj<input value="${esc(PROVIDER_KIND[p.kind] || p.kind)}" disabled /></label>
|
||
</div>
|
||
<label class="field">Adres<input id="pfUrl" type="url" inputmode="url" autocomplete="off" spellcheck="false" maxlength="2000" placeholder="https://api.example.eu/v1" value="${esc(p.base_url || '')}" /></label>
|
||
<div class="grid3">
|
||
<label class="field">Region<input id="pfRegion" autocomplete="off" spellcheck="false" maxlength="8" placeholder="DE" value="${esc(p.region || '')}" /></label>
|
||
<label class="field">Podmiot przetwarzający<input id="pfProcessor" maxlength="200" value="${esc(p.processor_name || '')}" /></label>
|
||
<label class="field">Dla kogo${choice('pfAllowed', allowed, p.allowed_for || '')}</label>
|
||
</div>
|
||
<label class="field">Adres umowy powierzenia (DPA)<input id="pfDpa" maxlength="2000" value="${esc(p.dpa_url || '')}" /></label>
|
||
<label class="check"><input type="checkbox" id="pfTrains" ${p.trains_on_data ? 'checked' : ''} /> <span>Dostawca trenuje modele na przesłanych danych</span></label>
|
||
<label class="check"><input type="checkbox" id="pfActive" ${p.is_active ? 'checked' : ''} /> <span>Aktywny</span></label>
|
||
<label class="field">Czyj klucz${choice('pfKeyMode', KEY_MODE, p.key_mode || 'firm')}</label>
|
||
<div class="faint tiny">Zmiana adresu albo odejście od własnych kluczy użytkowników usuwa wszystkie zapisane klucze użytkowników tego dostawcy.</div>
|
||
<label class="field">Klucz API<input id="pfKey" type="password" autocomplete="new-password" maxlength="4096"
|
||
placeholder="Pozostaw puste, aby zachować obecny klucz" ${writable ? '' : 'disabled'} /></label>
|
||
<div class="faint tiny">${writable ? 'Klucz jest tylko do zapisu: nikt, także administrator, nie zobaczy go ponownie.'
|
||
: 'Ten serwer nie ma ustawionego MODEL_PROVIDER_SECRET, więc nie może zapisać klucza API.'}</div>
|
||
${p.has_key ? `<div class="row"><span class="chip ok">ustawiony</span> <span class="mono tiny faint" data-no-i18n>${esc(p.key_prefix || '')}…</span>
|
||
<button type="button" class="btn sm danger" data-pid="${esc(p.id)}" onclick="removeProviderKey(this.dataset.pid)">Usuń klucz</button></div>` : ''}`;
|
||
modal('Szczegóły', '', body,
|
||
`<button class="btn" onclick="closeModal()">Anuluj</button>
|
||
<button class="btn primary" data-pid="${esc(p.id)}" onclick="saveProvider(this.dataset.pid)">Zapisz</button>`,
|
||
{ wide: true });
|
||
}
|
||
|
||
/* Sends the whole card, with emptied optional fields asked for by name in `clear` (absent means
|
||
"leave it" on the server) — and never a key unless one was typed. The models are the provider's
|
||
own list (`/refresh`), never typed. */
|
||
function readProviderForm() {
|
||
const text = (id) => $(id).value.trim();
|
||
const body = {
|
||
name: text('pfName'), base_url: text('pfUrl'), trains_on_data: $('pfTrains').checked,
|
||
is_active: $('pfActive').checked, key_mode: $('pfKeyMode').value,
|
||
};
|
||
const clear = [];
|
||
[['region', 'pfRegion'], ['processor_name', 'pfProcessor'], ['dpa_url', 'pfDpa'], ['allowed_for', 'pfAllowed']]
|
||
.forEach(([field, id]) => {
|
||
const value = text(id);
|
||
if (value) body[field] = value;
|
||
else clear.push(field);
|
||
});
|
||
body.clear = clear;
|
||
const key = $('pfKey').value;
|
||
if (key) body.api_key = key;
|
||
return body;
|
||
}
|
||
|
||
function saveProvider(id) {
|
||
mutate('PATCH', '/admin/model-providers/' + enc(id), readProviderForm);
|
||
}
|
||
|
||
function removeProviderKey(id) {
|
||
modal('Usuń klucz', '', '<div class="banner warn">Usunąć zapisany klucz API tego dostawcy?</div>',
|
||
`<button class="btn" onclick="closeModal()">Anuluj</button>
|
||
<button class="btn danger" data-pid="${esc(id)}" onclick="confirmRemoveProviderKey(this.dataset.pid)">Usuń klucz</button>`);
|
||
}
|
||
|
||
function confirmRemoveProviderKey(id) {
|
||
mutate('PATCH', '/admin/model-providers/' + enc(id), { clear: ['api_key'] });
|
||
}
|
||
|
||
function disableProvider(id) {
|
||
modal('Wyłącz', '', '<div class="banner warn">Wyłączyć tego dostawcę? Moduły przestaną go oferować.</div>',
|
||
`<button class="btn" onclick="closeModal()">Anuluj</button>
|
||
<button class="btn danger" data-pid="${esc(id)}" onclick="confirmDisableProvider(this.dataset.pid)">Wyłącz</button>`);
|
||
}
|
||
|
||
function confirmDisableProvider(id) {
|
||
mutate('POST', `/admin/model-providers/${enc(id)}/disable`);
|
||
}
|
||
|
||
// Only a disabled provider offers this; one that has computed a run is refused by core (409, its sentence).
|
||
function deleteProvider(id) {
|
||
modal('Usuń', '', '<div class="banner warn">Usunąć tego dostawcę razem z jego kluczami? Tego nie da się cofnąć.</div>',
|
||
`<button class="btn" onclick="closeModal()">Anuluj</button>
|
||
<button class="btn danger" data-pid="${esc(id)}" onclick="confirmDeleteProvider(this.dataset.pid)">Usuń</button>`);
|
||
}
|
||
|
||
function confirmDeleteProvider(id) {
|
||
mutate('DELETE', '/admin/model-providers/' + enc(id), undefined, { done: 'Usunięto.' });
|
||
}
|
||
|
||
function refreshProvider(id) {
|
||
mutate('POST', `/admin/model-providers/${enc(id)}/refresh`, undefined, { done: 'Odświeżono modele.' });
|
||
}
|
||
|
||
function enableProvider(id) {
|
||
mutate('PATCH', '/admin/model-providers/' + enc(id), { is_active: true });
|
||
}
|
||
|
||
function saveProviderPolicy() {
|
||
mutate('PUT', '/admin/model-providers/policy', { level: $('ppLevel').value, eu_only: $('ppEu').checked });
|
||
}
|
||
|
||
/* ── administration: audit log ──────────────────────────────────────────── */
|
||
async function viewAdminAudit(C, q) {
|
||
const offset = Math.max(0, parseInt(q.offset || '0', 10) || 0);
|
||
const rows = await api('GET', withQuery('/admin/audit', { limit: 100, offset, action: q.action }));
|
||
setCrumb([{ label: 'Administracja' }, { label: 'Dziennik zdarzeń' }]);
|
||
const page = (o) => withQuery('#/admin/audit', { action: q.action, offset: o });
|
||
C.innerHTML = pageHead('Dziennik zdarzeń', '')
|
||
+ `<div class="toolbar"><input type="search" id="auq" placeholder="Filtruj akcję, np. module.…" aria-label="Filtruj akcję" value="${esc(q.action || '')}" /></div>`
|
||
+ (rows.length ? `<div class="card"><div class="tablewrap"><table class="rt"><thead><tr>
|
||
<th>Czas</th><th>Kto</th><th>Akcja</th><th>Obiekt</th><th>Wynik</th>
|
||
</tr></thead><tbody>${rows.map((a) => `<tr>
|
||
<td class="faint tiny nowrap">${fmtDateTime(a.created_at)}</td>
|
||
<td class="tiny wrap"${lbl('Kto')}>${a.actor_email ? dat(a.actor_email) : '<span class="faint">system</span>'}</td>
|
||
<td class="mono wrap"${lbl('Akcja')}>${dat(a.action)}</td>
|
||
<td class="tiny wrap"${lbl('Obiekt')}><div>${dat(a.entity_type)}${a.detail ? `<div class="faint">${dat(a.detail)}</div>` : ''}
|
||
${a.diff && Object.keys(a.diff).length ? `<details><summary class="faint">Zmiany</summary><pre class="diff" data-no-i18n>${esc(JSON.stringify(a.diff, null, 2))}</pre></details>` : ''}</div></td>
|
||
<td${lbl('Wynik')}>${a.result === 'ok' ? '<span class="chip ok">ok</span>' : `<span class="chip err">${dat(a.result || '')}</span>`}</td>
|
||
</tr>`).join('')}</tbody></table></div></div>` : '<div class="empty">—</div>')
|
||
+ `<div class="row" style="margin-top:12px">
|
||
${offset ? `<a class="btn sm" href="${esc(page(Math.max(0, offset - 100)))}">Najnowsze</a>` : ''}
|
||
${rows.length === 100 ? `<a class="btn sm" href="${esc(page(offset + 100))}">Wcześniejsze</a>` : ''}</div>`;
|
||
onFilter($('auq'), (v) => { location.hash = withQuery('#/admin/audit', { action: v }); });
|
||
}
|
||
|
||
/* ── modal ──────────────────────────────────────────────────────────────── */
|
||
let _modalOpener = null;
|
||
function closeModal() {
|
||
const wasOpen = !!$('modalRoot').innerHTML;
|
||
$('modalRoot').innerHTML = '';
|
||
$('app').inert = false;
|
||
// Give focus back to whatever opened the dialog, rather than dropping it onto <body>.
|
||
if (wasOpen && _modalOpener && document.contains(_modalOpener)) _modalOpener.focus();
|
||
_modalOpener = null;
|
||
}
|
||
|
||
function modal(title, sub, bodyHtml, actionsHtml, opts) {
|
||
$('modalRoot').innerHTML = `<div class="scrim" onclick="if(event.target===this)closeModal()">
|
||
<div class="modal ${opts && opts.wide ? 'wide' : ''}" role="dialog" aria-modal="true" aria-labelledby="modalTitle">
|
||
<h3 id="modalTitle">${esc(title)}</h3>${sub ? `<div class="msub">${esc(sub)}</div>` : ''}
|
||
<div id="modalBody" class="stack">${bodyHtml}</div>
|
||
<div class="acts">${actionsHtml}</div>
|
||
</div></div>`;
|
||
localize($('modalRoot'));
|
||
$('app').inert = true;
|
||
if (!_modalOpener && document.activeElement && document.activeElement !== document.body
|
||
&& !$('modalRoot').contains(document.activeElement)) _modalOpener = document.activeElement;
|
||
// A field if there is one; otherwise the dialog's first control, so a keyboard user starts inside.
|
||
const first = $('modalRoot').querySelector('input:not([type=hidden]),select,textarea')
|
||
|| $('modalRoot').querySelector('.modal button, .modal a[href]');
|
||
if (first) first.focus();
|
||
}
|
||
|
||
function modalError(msg) {
|
||
const b = $('modalBody');
|
||
if (!b) { toast(msg); return; }
|
||
let el = b.querySelector('.banner.err');
|
||
if (!el) {
|
||
el = document.createElement('div');
|
||
el.className = 'banner err';
|
||
b.prepend(el);
|
||
}
|
||
el.textContent = msg;
|
||
}
|
||
|
||
/* Run an async handler and put its error where the user is looking: inside the open dialog, or as a
|
||
toast when there is none (modalError decides). */
|
||
function guard(fn) {
|
||
return Promise.resolve().then(fn).catch((ex) => {
|
||
if (ex && ex.status === 401) { showLogin(); return; }
|
||
modalError(ex.message || String(ex));
|
||
});
|
||
}
|
||
|
||
/* Every write behind a button: send it, confirm it, then show the outcome. By default any dialog
|
||
closes and the page re-renders, and the router re-reads what api() marked stale. `go(result)` returns
|
||
a hash to navigate to instead; `reopen(result)` redraws a dialog that stays open; `done` replaces the
|
||
confirmation (or is a function of the result, when the outcome decides the wording). `body` may be a function, so a form reader that refuses input (orderValue) reports
|
||
through the same error path. */
|
||
function mutate(method, path, body, { go, reopen, done = 'Zapisano.' } = {}) {
|
||
return guard(async () => {
|
||
const result = await api(method, path, typeof body === 'function' ? body() : body);
|
||
toast(typeof done === 'function' ? done(result) : done);
|
||
// A dialog that stays open means no navigation to re-read the shared state, so read it here.
|
||
if (reopen) { await Promise.all([reopen(result), refreshShared()]); return; }
|
||
closeModal();
|
||
if (go) location.hash = go(result);
|
||
else await router();
|
||
});
|
||
}
|
||
|
||
/* ── modules inside the frame ───────────────────────────────────────────── */
|
||
/* Atrium is the one frame: a module on this origin opens at #/m/<slug>/<its own hash> inside an
|
||
iframe, and its own chrome (sidebar, top bar) is hidden. Its nav, breadcrumb and top-bar tools
|
||
are MIRRORED into this frame — copies whose clicks are forwarded to the original element — so
|
||
the module's code stays untouched. That makes the module's DOM a contract this file reads:
|
||
`#sidebar` holds `.nav-item` / `.nav-sep` / `.gh`, `.topbar` holds the tools, `#crumb` the path.
|
||
Same origin is what makes reading it possible at all; a module elsewhere opens as before. */
|
||
const SHELL_IDS = new Set(['navToggle', 'navCollapse', 'aApps', 'aTheme', 'btnTheme', 'aLang', 'aUser',
|
||
'userAvatar', 'aSearch', 'btnPalette', 'btnLang']);
|
||
const LS_PREFIX = { counsel: 'cs' }; // a module's own localStorage prefix, where it is not its slug
|
||
/* ponytail: per-browser preference; a server-side setting when it has to follow a person across devices */
|
||
const NAV_HIDDEN_KEY = 'dredd_nav_hidden';
|
||
const frame = { slug: null, el: null, win: null, srcs: [], search: null, obs: null, raf: 0 };
|
||
|
||
const embeddable = (m) => sameOrigin(safeUrl(m.url));
|
||
const frameHash = (slug, inner) => '#/m/' + enc(slug) + (inner ? '/' + inner : '');
|
||
const innerOf = (win) => (win.location.hash || '').replace(/^#\/?/, '');
|
||
function navHidden() {
|
||
try { return JSON.parse(localStorage.getItem(NAV_HIDDEN_KEY) || '[]'); } catch { return []; }
|
||
}
|
||
// The open module stays listed even when hidden: its nav lives only under its own entry.
|
||
const navModules = () => state.launcher.filter((m) => embeddable(m)
|
||
&& (m.slug === frame.slug || !navHidden().includes(m.slug)));
|
||
const basePath = (m) => new URL(safeUrl(m.url), document.baseURI).pathname;
|
||
/* mirror-prefix:begin — a path is under a module only at a segment boundary: `/galena` must not
|
||
claim `/galena-x`. Both sides get a trailing slash, so `/galena` itself still matches `/galena/`. */
|
||
const slashed = (p) => (p.endsWith('/') ? p : p + '/');
|
||
const underPath = (path, base) => slashed(path).startsWith(slashed(base));
|
||
/* mirror-prefix:end */
|
||
const isUnder = (path, m) => underPath(path, basePath(m));
|
||
const moduleAt = (path) => state.launcher.find((x) => embeddable(x) && isUnder(path, x));
|
||
|
||
/* The module reads its theme and language once, at boot, from its own keys: write ours there first. */
|
||
function seedModulePrefs(slug) {
|
||
const p = LS_PREFIX[slug] || slug;
|
||
try {
|
||
localStorage.setItem(p + '_theme', themeMode());
|
||
localStorage.setItem(p + '_lang', LANG);
|
||
} catch { /* private mode */ }
|
||
}
|
||
|
||
/* The other way round: a module's own language button writes only its own key. The frame shares
|
||
this origin, so that write reaches us as a `storage` event — take it as the platform's choice, and
|
||
the next module opened gets it from seedModulePrefs. The event also arrives from every OTHER tab
|
||
of this origin, and a reload there would throw away whatever is unsaved in its frame: only the
|
||
tab the click happened in has focus, so only it reloads. The rest pick `atrium_lang` up on their
|
||
next load. */
|
||
window.addEventListener('storage', (e) => {
|
||
if (!document.hasFocus()) return;
|
||
if (!frame.slug || e.key !== (LS_PREFIX[frame.slug] || frame.slug) + '_lang') return;
|
||
if ((e.newValue !== SRC_LANG && e.newValue !== ALT_LANG) || e.newValue === LANG) return;
|
||
try { localStorage.setItem('atrium_lang', e.newValue); } catch { /* private mode */ }
|
||
location.reload();
|
||
});
|
||
|
||
function leaveFrame() {
|
||
if (!frame.slug) return;
|
||
if (frame.obs) frame.obs.disconnect();
|
||
Object.assign(frame, { slug: null, el: null, win: null, srcs: [], search: null, obs: null });
|
||
$('app').classList.remove('framed');
|
||
$('modTools').innerHTML = '';
|
||
}
|
||
|
||
function showFrame(slug, inner) {
|
||
const m = state.launcher.find((x) => x.slug === slug && embeddable(x));
|
||
if (!m) { leaveFrame(); setCrumb([]); $('content').innerHTML = '<div class="empty">Nie znaleziono modułu.</div>'; localize($('content')); renderNav(); return; }
|
||
if (frame.slug === slug && frame.win) {
|
||
// Back/forward inside the same module: move its hash, never reload it.
|
||
if (innerOf(frame.win) !== inner) frame.win.location.hash = '#/' + inner;
|
||
renderNav();
|
||
return;
|
||
}
|
||
leaveFrame();
|
||
seedModulePrefs(slug);
|
||
frame.slug = slug;
|
||
$('app').classList.add('framed');
|
||
const C = $('content');
|
||
const u = new URL(safeUrl(m.url), document.baseURI);
|
||
u.hash = inner ? '#/' + inner : '';
|
||
// src in the markup: an iframe inserted without one loads about:blank first, which reads as a refusal.
|
||
C.innerHTML = `<iframe class="modframe" title="${esc(m.name)}" src="${esc(u.href)}"></iframe>`;
|
||
frame.el = C.firstChild;
|
||
frame.el.addEventListener('load', () => attachFrame(m));
|
||
setCrumb([{ label: m.name, data: true }]);
|
||
renderNav();
|
||
closeDrawer();
|
||
}
|
||
|
||
// The frame draws the workspace's edge and corner; the module's own copy of them would show inside
|
||
// it as a second line.
|
||
const FRAME_CHROME_CSS = '#sidebar,.sidebar,#navScrim,.nav-scrim,.topbar{display:none!important}'
|
||
+ '#app{background:var(--at-canvas,inherit)!important}'
|
||
+ '.content{border:0!important;border-radius:0!important}';
|
||
|
||
/* A module's settings screen inside Ustawienia: the module page without its own chrome. Not the
|
||
module frame (showFrame): no mirrored nav, the sidebar stays on Ustawienia. */
|
||
function viewModuleSettings(C, slug) {
|
||
const m = settingsModules().find((x) => x.slug === slug);
|
||
if (!m) { setCrumb([]); C.innerHTML = '<div class="empty">Nie znaleziono strony.</div>'; return; }
|
||
setCrumb([{ label: 'Ustawienia' }, { label: m.name, data: true }]);
|
||
seedModulePrefs(slug);
|
||
const u = new URL(safeUrl(m.url), document.baseURI);
|
||
u.hash = '#/' + MODULE_SETTINGS[slug];
|
||
C.innerHTML = `<iframe class="modframe setframe" title="${esc(m.name)}" src="${esc(u.href)}"></iframe>`;
|
||
C.firstChild.addEventListener('load', (e) => {
|
||
try {
|
||
const st = e.target.contentDocument.createElement('style');
|
||
st.textContent = FRAME_CHROME_CSS;
|
||
e.target.contentDocument.head.appendChild(st);
|
||
} catch { /* another origin: shown as it is */ }
|
||
});
|
||
}
|
||
|
||
function attachFrame(m) {
|
||
if (!frame.el || frame.slug !== m.slug) return;
|
||
let win, doc;
|
||
try { win = frame.el.contentWindow; doc = win.document; } catch { doc = null; }
|
||
if (!doc || doc.URL === 'about:blank') {
|
||
// A page that refused the frame (Atrium itself, after the module sent an expired session here)
|
||
// is unreadable: offer the module on its own instead of an empty box.
|
||
$('content').innerHTML = `<div class="empty">Nie udało się otworzyć modułu w ramie. <a href="${esc(safeUrl(m.url))}">Otwórz ${esc(m.name)} osobno</a></div>`;
|
||
leaveFrame();
|
||
setCrumb([{ label: m.name, data: true }]);
|
||
return renderNav();
|
||
}
|
||
if (!isUnder(win.location.pathname, m)) {
|
||
// The module navigated to a sibling (a matter link from Compass to Sygna): follow it in the frame,
|
||
// or, if it left the modules altogether, let the whole tab go there.
|
||
const other = moduleAt(win.location.pathname);
|
||
if (other) location.hash = frameHash(other.slug, innerOf(win));
|
||
else location.href = win.location.href;
|
||
return;
|
||
}
|
||
if (frame.obs) frame.obs.disconnect();
|
||
frame.win = win;
|
||
const st = doc.createElement('style');
|
||
st.textContent = FRAME_CHROME_CSS;
|
||
doc.head.appendChild(st);
|
||
win.addEventListener('hashchange', () => {
|
||
history.replaceState(null, '', frameHash(m.slug, innerOf(win)));
|
||
queueMirror();
|
||
});
|
||
// A module opens its siblings and Atrium in a new tab (target=_blank); inside the frame they are a
|
||
// route here instead, or the whole tab for Atrium's own pages.
|
||
doc.addEventListener('click', (e) => {
|
||
const a = e.target.closest('a[href]');
|
||
if (!a || e.defaultPrevented || e.button !== 0 || e.ctrlKey || e.metaKey || e.shiftKey) return;
|
||
const u = new URL(a.href, doc.baseURI);
|
||
if (u.origin !== location.origin || isUnder(u.pathname, m)) return;
|
||
const other = moduleAt(u.pathname);
|
||
e.preventDefault();
|
||
if (other) location.hash = frameHash(other.slug, u.hash.replace(/^#\/?/, ''));
|
||
else location.href = u.href;
|
||
});
|
||
frame.obs = new MutationObserver(queueMirror);
|
||
doc.querySelectorAll('#sidebar, .topbar').forEach((el) =>
|
||
frame.obs.observe(el, { childList: true, subtree: true, attributes: true, characterData: true }));
|
||
history.replaceState(null, '', frameHash(m.slug, innerOf(win)));
|
||
mirror();
|
||
}
|
||
|
||
function queueMirror() {
|
||
cancelAnimationFrame(frame.raf);
|
||
frame.raf = requestAnimationFrame(mirror);
|
||
}
|
||
|
||
/* mirror-copy:begin
|
||
A copy of a module element that cannot run anything here. It is an ALLOWLIST, not a blocklist:
|
||
the module's markup lands in Atrium's document, where `script-src 'unsafe-inline'` holds, so
|
||
anything not named below is gone — an SVG <a href="javascript:…">, <meta http-equiv=refresh>,
|
||
<area>, `formaction`, `style`, `xlink:href`, and a `data-mi` the module wrote itself (which would
|
||
point a mirrored click at another control). Elements are matched by namespace + localName, so the
|
||
SVG `a` is not the HTML one. Anything outside the list is dropped with its subtree. The only href
|
||
that survives is an HTML <a>'s own `#…` hash, rewritten into this frame's route.
|
||
Every clickable original gets a `data-mi` index on its copy — set after sanitising, so it is
|
||
always ours — found by walking both trees in step, so a nested control (a tree's expand chevron)
|
||
forwards to the right element. */
|
||
const MIRROR_HTML = new Set(['div', 'span', 'a', 'button', 'kbd', 'i', 'b', 'strong', 'small']);
|
||
const MIRROR_SVG = new Set(['svg', 'path', 'circle', 'rect', 'line', 'polyline', 'polygon', 'g']);
|
||
const MIRROR_ATTR = /^(class|title|role|aria-[a-z-]+|viewbox|d|cx|cy|r|rx|ry|x\d*|y\d*|width|height|points|fill|stroke(-[a-z]+)?|xmlns)$/;
|
||
const NS_HTML = 'http://www.w3.org/1999/xhtml';
|
||
const NS_SVG = 'http://www.w3.org/2000/svg';
|
||
function mirrorAllowed(el) {
|
||
const n = String(el.localName || '').toLowerCase();
|
||
if (el.namespaceURI === NS_HTML) return MIRROR_HTML.has(n);
|
||
if (el.namespaceURI === NS_SVG) return MIRROR_SVG.has(n);
|
||
return false;
|
||
}
|
||
function mirrorCopy(src) {
|
||
if (!mirrorAllowed(src)) return document.createElement('span');
|
||
const copy = src.cloneNode(true);
|
||
const a = [src, ...src.querySelectorAll('*')];
|
||
const b = [copy, ...copy.querySelectorAll('*')];
|
||
b.forEach((el, i) => {
|
||
if (el !== copy && !copy.contains(el)) return; // inside a subtree already dropped
|
||
const o = a[i];
|
||
if (!mirrorAllowed(el)) { el.remove(); return; }
|
||
[...el.attributes].forEach((at) => {
|
||
if (!MIRROR_ATTR.test(at.name.toLowerCase())) el.removeAttribute(at.name);
|
||
});
|
||
const htmlA = el.namespaceURI === NS_HTML && el.localName.toLowerCase() === 'a';
|
||
if (htmlA) {
|
||
const h = o.getAttribute('href') || '';
|
||
if (h.startsWith('#')) el.setAttribute('href', frameHash(frame.slug, h.replace(/^#\/?/, '')));
|
||
}
|
||
// A handler set as a property (`el.onclick = …`) leaves no attribute; a nav item is clickable regardless.
|
||
if (o.onclick || o.hasAttribute('onclick') || htmlA
|
||
|| (o.namespaceURI === NS_HTML && o.localName.toLowerCase() === 'button')
|
||
|| o.classList.contains('nav-item')) {
|
||
el.setAttribute('data-mi', String(frame.srcs.push(o) - 1));
|
||
}
|
||
});
|
||
return copy;
|
||
}
|
||
/* mirror-copy:end */
|
||
|
||
function mirror() {
|
||
const doc = frame.win && frame.win.document;
|
||
const nav = $('modNav');
|
||
if (!doc || !nav) return;
|
||
frame.srcs = [];
|
||
const visible = (el) => !el.classList.contains('hidden') && !el.hidden && el.style.display !== 'none';
|
||
nav.replaceChildren(...[...doc.querySelectorAll('#sidebar .nav-item, #sidebar .nav-sep, #sidebar .nav-head, #sidebar .gh')]
|
||
.filter((el) => visible(el) && el.textContent.trim()
|
||
&& !(el.parentElement && el.parentElement.closest('#sidebar .nav-item')))
|
||
.map((el) => {
|
||
if (!el.matches('.gh, .nav-head')) return mirrorCopy(el);
|
||
const sep = document.createElement('div'); // a group head (Counsel's collapsible, Galena's): a plain label here
|
||
sep.className = 'nav-sep';
|
||
sep.textContent = el.textContent.trim();
|
||
return sep;
|
||
}));
|
||
frame.search = doc.querySelector('.topbar #aSearch, .topbar #btnPalette');
|
||
const tools = [...doc.querySelectorAll('.topbar .iconbtn, .topbar .vdiv')]
|
||
.filter((el) => visible(el) && !SHELL_IDS.has(el.id) && !el.classList.contains('js-theme'));
|
||
const isDiv = (el) => el && el.classList.contains('vdiv'); // no divider at either end
|
||
while (isDiv(tools[0])) tools.shift();
|
||
while (isDiv(tools[tools.length - 1])) tools.pop();
|
||
$('modTools').replaceChildren(...tools.map(mirrorCopy));
|
||
const crumb = doc.getElementById('crumb');
|
||
const m = state.launcher.find((x) => x.slug === frame.slug);
|
||
$('crumb').innerHTML = `<a href="${esc(frameHash(frame.slug))}" data-no-i18n>${esc(m ? m.name : frame.slug)}</a>`;
|
||
if (crumb && crumb.textContent.trim()) {
|
||
const sep = document.createElement('span');
|
||
sep.className = 'sep';
|
||
sep.textContent = '/';
|
||
const c = mirrorCopy(crumb);
|
||
c.className = 'modcrumb';
|
||
$('crumb').append(' ', sep, ' ', c);
|
||
}
|
||
}
|
||
|
||
/* One listener for every mirrored control. */
|
||
function forwardMirrored(e) {
|
||
const t = e.target.closest('[data-mi]');
|
||
if (!t || !frame.srcs[t.dataset.mi]) return;
|
||
if (e.button !== 0 || e.ctrlKey || e.metaKey || e.shiftKey) return; // a new tab follows the href
|
||
e.preventDefault();
|
||
frame.el.focus();
|
||
frame.srcs[t.dataset.mi].click();
|
||
closeDrawer();
|
||
}
|
||
|
||
/* In the frame, the top bar's search is the module's own palette: it knows the module's records. */
|
||
function openFrameSearch() {
|
||
if (frame.search) { frame.el.focus(); frame.search.click(); } else openSearch();
|
||
}
|
||
|
||
function openNavPrefs() {
|
||
const hidden = navHidden();
|
||
const rows = state.launcher.filter(embeddable).map((m) => `<label class="navpref" data-no-i18n>
|
||
<input type="checkbox" value="${esc(m.slug)}" ${hidden.includes(m.slug) ? '' : 'checked'} />
|
||
${moduleIcon(m, 22)}<span>${esc(m.name)}</span></label>`).join('');
|
||
modal('Moduły w pasku bocznym', 'Odznaczone znikną z paska bocznego. W katalogu zostają.',
|
||
rows ? `<div class="navprefs" id="navPrefs">${rows}</div>` : '<div class="empty">Nie masz jeszcze żadnych aplikacji.</div>',
|
||
'<button class="btn" onclick="closeModal()">Anuluj</button><button class="btn primary" onclick="saveNavPrefs()">Zapisz</button>');
|
||
}
|
||
function saveNavPrefs() {
|
||
const off = [...document.querySelectorAll('#navPrefs input:not(:checked)')].map((i) => i.value);
|
||
try { localStorage.setItem(NAV_HIDDEN_KEY, JSON.stringify(off)); } catch { /* private mode */ }
|
||
closeModal();
|
||
renderNav();
|
||
}
|
||
|
||
/* ── command palette ────────────────────────────────────────────────────── */
|
||
function openSearch() {
|
||
// On the home page the big box IS the search; a second one on top of it would be a duplicate.
|
||
if ($('homeQ')) { $('homeQ').focus(); return; }
|
||
$('modalRoot').innerHTML = `<div class="scrim search-scrim" onclick="if(event.target===this)closeModal()">
|
||
<div class="search-modal" role="dialog" aria-modal="true" aria-label="Szukaj">
|
||
<div class="sin">${svg(ICN.search, 18)}<input id="sq" type="search" placeholder="Szukaj modułów…" aria-label="Szukaj modułów" autocomplete="off" /></div>
|
||
<div class="search-results" id="sres"></div>
|
||
<div class="shint">Esc</div>
|
||
</div></div>`;
|
||
localize($('modalRoot'));
|
||
$('app').inert = true;
|
||
const input = $('sq');
|
||
input.focus();
|
||
let timer = null;
|
||
const run = async () => {
|
||
const q = input.value.trim();
|
||
if (!q) { $('sres').innerHTML = ''; return; }
|
||
try {
|
||
const d = await api('GET', '/marketplace?q=' + enc(q));
|
||
$('sres').innerHTML = d.modules.length
|
||
? '<div class="sgroup">Moduły</div>' + d.modules.slice(0, 12).map((m) =>
|
||
`<button class="sitem" onclick="closeModal();location.hash='#/marketplace/${enc(m.slug)}'">
|
||
<span class="ic">${moduleIcon(m, 26)}</span>
|
||
<span class="sb"><span class="st">${dat(m.name)}</span>
|
||
<span class="ss">${dat(m.tagline || m.category || '')}</span></span></button>`).join('')
|
||
: '<div class="search-empty">Brak wyników</div>';
|
||
localize($('sres'));
|
||
} catch { $('sres').innerHTML = ''; }
|
||
};
|
||
input.addEventListener('input', () => { clearTimeout(timer); timer = setTimeout(run, 180); });
|
||
}
|
||
|
||
/* ── account sheet ──────────────────────────────────────────────────────── */
|
||
/* On a phone the top bar drops search, theme and language (`.js-tool`) to leave room for the
|
||
breadcrumb — so they live here too (`.m-only`), or a phone user could never reach them. */
|
||
const THEME_LABEL = { system: 'Motyw: systemowy', light: 'Motyw: jasny', dark: 'Motyw: ciemny' };
|
||
|
||
function openAccount() {
|
||
const mode = themeMode();
|
||
const row = (icon, label, action, cls) =>
|
||
`<button class="appcard ${cls || ''}" onclick="${action}"><span class="ai">${svg(icon)}</span><span class="an">${esc(label)}</span></button>`;
|
||
modal(state.user ? (state.user.full_name || state.user.email) : '', state.user ? state.user.email : '',
|
||
'<div class="applist">'
|
||
+ `<a class="appcard" href="#/requests" onclick="closeModal()"><span class="ai">${svg(ICN.send)}</span><span class="an">Moje wnioski</span></a>`
|
||
// Your credentials belong in the sheet that carries your account, not only in the nav.
|
||
+ `<a class="appcard" href="#/tokens" onclick="closeModal()"><span class="ai">${svg(ICN.key)}</span><span class="an">Połączone aplikacje</span></a>`
|
||
+ row(ICN.search, 'Szukaj…', 'closeModal();openSearch()', 'm-only')
|
||
+ row(TH[mode] || TH.system, THEME_LABEL[mode] || THEME_LABEL.system, "cycleTheme();openAccount();document.querySelector('#modalRoot .js-theme-row').focus()", 'm-only js-theme-row')
|
||
+ row(ICN.globe, LANG === 'pl' ? 'Język: polski' : 'Język: angielski', 'cycleLang()', 'm-only')
|
||
+ row(ICN.logout, 'Wyloguj się', 'closeModal();doLogout()')
|
||
+ '</div>',
|
||
`<button class="btn" onclick="closeModal()">Zamknij</button>`);
|
||
}
|
||
|
||
/* ── mobile drawer ──────────────────────────────────────────────────────── */
|
||
function openDrawer() {
|
||
$('sidebar').classList.add('open');
|
||
$('navScrim').classList.add('on');
|
||
}
|
||
function closeDrawer() {
|
||
$('sidebar').classList.remove('open');
|
||
$('navScrim').classList.remove('on');
|
||
}
|
||
|
||
/* ── boot ───────────────────────────────────────────────────────────────── */
|
||
function togglePassword(inputId, btn) {
|
||
const el = $(inputId);
|
||
if (!el) return;
|
||
const show = el.type === 'password';
|
||
el.type = show ? 'text' : 'password';
|
||
btn.innerHTML = svg(show ? ICN.eyeoff : ICN.eye);
|
||
}
|
||
|
||
window.addEventListener('DOMContentLoaded', () => {
|
||
applyTheme(themeMode());
|
||
document.querySelectorAll('#aLang,#btnLangLogin').forEach((b) => {
|
||
b.textContent = LANG.toUpperCase();
|
||
b.addEventListener('click', cycleLang);
|
||
});
|
||
document.querySelectorAll('.js-theme').forEach((b) => b.addEventListener('click', cycleTheme));
|
||
|
||
$('loginForm').addEventListener('submit', doLogin);
|
||
const pwBtn = $('pwToggleLogin');
|
||
if (pwBtn) {
|
||
pwBtn.innerHTML = svg(ICN.eye);
|
||
pwBtn.addEventListener('click', () => togglePassword('password', pwBtn));
|
||
}
|
||
|
||
$('navToggle').innerHTML = svg(ICN.menu, 18);
|
||
$('navCollapse').innerHTML = svg(ICN.sidebar, 16);
|
||
$('navToggle').addEventListener('click', openDrawer);
|
||
$('navScrim').addEventListener('click', closeDrawer);
|
||
const searchBtn = $('aSearch');
|
||
searchBtn.querySelector('.si').innerHTML = svg(ICN.search, 14);
|
||
searchBtn.addEventListener('click', openFrameSearch);
|
||
$('sidebar').addEventListener('click', forwardMirrored);
|
||
$('modCol').addEventListener('click', forwardMirrored);
|
||
document.querySelector('.topbar').addEventListener('click', forwardMirrored);
|
||
$('aUser').addEventListener('click', openAccount);
|
||
|
||
window.addEventListener('hashchange', router);
|
||
document.addEventListener('keydown', (e) => {
|
||
if ((e.ctrlKey || e.metaKey) && e.key.toLowerCase() === 'k') { e.preventDefault(); openFrameSearch(); }
|
||
if (e.key === 'Escape') closeModal();
|
||
});
|
||
|
||
document.title = 'Atrium — ' + _tr('System zarządzania');
|
||
localize(document.body);
|
||
restore();
|
||
});
|