feat(czat): mapa powiązań między modułami (B3-B7)

Nowa sekcja bloku czatu za chatIndex: chatMatchKey (1:1 z match_key Compassu),
chatSameWord (zamknięta lista końcówek), chatGraph (nośniki nazw scalane w
podmioty po id, NIP/KRS/REGON/PESEL, pełnej nazwie z formą, R0 i rozbiciu
łańcuchów; krawędzie spraw, terminów, umów, teczek, zleceń i osób),
chatGraphFind/chatGraphTurn (rozpoznanie w pytaniu i plan tury) oraz
chatCard/chatLinkCard/chatCardHint. chatIndex buduje mapę w strażniku: błąd
w mapie daje graph = null i czat działa jak dotąd. Wpięcie w chatTurn osobno.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_016uwxqFLC3q51VqQzdfk12g
(cherry picked from commit ff3b18ea98)
This commit is contained in:
tobayah
2026-11-12 20:39:43 +01:00
parent c9b1e70c74
commit cf006e7a53
+783 -1
View File
@@ -2068,9 +2068,791 @@ async function chatIndex() {
return `W ostatnich ${d === 1 ? 'dniu' : d + ' dniach'}: ${n ? 'zmian ' + n : 'brak zmian, żadnej aktywności'}. `; }).join('') +
'Zestawienie obejmuje dodanie umowy do rejestru, otwarcie i zamknięcie sprawy, wykonanie terminu, zlecenie dla kancelarii i wersję dokumentu w Galenie; zmian w istniejących wpisach nie widać.' };
const all = [...records, access, activity];
return { user: state.user.id, records: all, blind, law: law !== null, byKey: new Map(all.map((r) => [r.key, r])) };
// 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, Compass, 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, ported 1:1 (services/counterparties.py): 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 Compassu', 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: 'compass', 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 Compass 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' });
}
for (const piece of String(c.counterparty || '').split('; ')) {
const k = chatMatchKey(piece);
if (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;
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]);
// ---- 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 Compass'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;
for (const core of cores) {
for (const w of words(core)) if (w.length >= 5 && !/\d/.test(w) && !generic.test(w) && !first.has(w)) put({ toks: [w], ent: e.id, full: false });
}
}
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;
};
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.full || (q.cap && !q.lead));
});
for (const full of [true, false]) {
if (!full && (!partial || spans.length)) break; // one full hit wins over partial ones
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;
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('|');
return ids.length > 1 ? { ambiguous: ids } : { root: ids[0], hit: live[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 !== 'compass'));
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')}`], ['Compass', n(e, 'compass: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('compass:umowa:')) || null;
const noun = cands.every((e) => e.type === 'sprawa') ? 'którą sprawę' : cands.every((e) => e.person) ? 'którą osobę' : 'którą firmę';
return { ask: `O ${noun} chodzi: ${cands.map((e) => `${e.name} (${fact(e)})`).join('; ')}? Napisz pełną nazwę.`,
mentioned: cands.map(anchor).filter(Boolean), why: 'niejednoznaczna nazwa', ambiguous: ids };
}
// The plan of a turn: a card of which entity, a card of one record's links, a question back, or nothing (`why`).
function chatGraphTurn({ question, index, named = [], resolved = [], back = [] }) {
const g = index.graph;
if (!g) return null;
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);
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) return { why: found ? 'brak encji' : 'nic w pytaniu' };
const e = g.ent.get(root);
if (e.type === 'osoba') return e.recs.size ? { root, kind: 'osoba' } : { why: 'jeden moduł' };
if (e.mods.size >= 2) return { root, kind: e.type };
// 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 } : { 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, ')');
// 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);
const matters = get('sygna:sprawa:').sort((a, b) => a.matter.reference.localeCompare(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) => a.due_date.localeCompare(b.due_date));
const contracts = get('compass:umowa:').sort((a, b) => (a.contract.ends_on || '9999').localeCompare(b.contract.ends_on || '9999') || a.contract.number.localeCompare(b.contract.number));
const projects = get('galena:projekt:').sort((a, b) => a.project.name.localeCompare(b.project.name, 'pl'));
const versions = get('galena:wersja:').sort((a, b) => a.draft.created_at.localeCompare(b.draft.created_at));
const orders = get('counsel:zlecenie:').sort((a, b) => a.order.reference.localeCompare(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));
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(', '); };
const STATUS_PL = { open: 'otwarte', closed: 'zamknięte' };
// 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 ${m.status}${kind === 'osoba' ? '' : `, prowadzi ${names[m.responsible_lawyer_id] || 'nieznany'}`}`; }), matters.map((r) => r.matter.reference))
: kind === 'osoba' ? `kod nie znalazł sprawy, którą prowadzi ta osoba (sprawy widoczne na koncie pytającego: ${visible('sprawa')}).`
: `kod nie znalazł sprawy, w której ten podmiot jest klientem; sprawę łączy się po stronie Sygny o tym NIP albo pełnej nazwie (sprawy widoczne na koncie pytającego: ${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] || 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}, odpowiada ${names[d.owner_id] || 'nieznany'}`;
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 niewykonanych terminów przypisanych tej osobie' : '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})` : ''}`);
}
// Compass
if (kind === 'osoba') L('Compass: umowy nie mają w danych osoby odpowiedzialnej, więc ich tu nie ma.');
else if (chatCardBlind(index, 'compass')) L('Compass: 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 || 'brak'}${why(r).length ? ` (powiązanie: ${why(r).join('; ')})` : ''}, status ${c.status}, ` +
`${c.value_amount ? `wartość ${chatMoney(c.value_amount)} ${c.value_currency}` : 'bez wartości'}, ${c.ends_on ? `kończy się ${c.ends_on}, ${d >= 0 ? 'za ' + d + ' dni' : -d + ' dni temu'}` : 'bez daty końca'}`;
};
const head = kind === 'sprawa' ? 'Compass, umowy przypisane do tej sprawy' : 'Compass, 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' ? 'w Compassie żadna widoczna umowa nie jest przypisana do tej sprawy' : 'kod nie znalazł umowy połączonej z tym podmiotem po NIP, numerze sprawy ani pełnej nazwie'} (rejestr widoczny na koncie pytającego: ${chatUmowy(visible('umowa'))}).`);
out.total.push(`${chatUmowy(contracts.length)} w Compassie${contracts.length ? ` (${counts(contracts, (r) => 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 ${r.draft.status === 'open' ? 'czeka na akceptację' : r.draft.status}, ` : ''}` +
`${kind === 'osoba' ? '' : `autor ${names[r.draft.author_id] || 'nieznany'}, `}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}”`)) + '.'
: `kod nie znalazł wersji tej osoby (projekty widoczne na koncie pytającego: ${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}”`))}` : '') + '.'
: `kod nie znalazł teczki wskazanej w ${kind === 'sprawa' ? 'tej sprawie' : 'sprawie tego podmiotu'} ani teczki o nazwie ${kind === 'sprawa' ? 'tej sprawy' : 'jego sprawy'} (projekty widoczne na koncie pytającego: ${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 ${o.status}, budżet ${o.budget_estimate != null ? `${chatMoney(o.budget_estimate)} ${o.budget_currency}` : 'brak'}` +
`${kind === 'osoba' ? '' : `, właściciel zlecenia ${names[o.matter_owner_id] || 'nieznany'}`}${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' ? `kod nie znalazł zlecenia tej osoby (zlecenia widoczne na koncie pytającego: ${visible('zlecenie')}).`
: `kod nie znalazł zlecenia z numerem ${kind === 'sprawa' ? 'tej sprawy ani jej umowy' : 'sprawy ani umowy tego podmiotu'} (zlecenia widoczne na koncie pytającego: ${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(', ')}.`;
}
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 } = {}) {
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 || 'brak'}). ${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 ${m.status}, prowadzi ${names[m.responsible_lawyer_id] || 'nieznany'}. ${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}. ${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) {
const others = (prefix) => [...c.recs.keys()].filter((k) => k.startsWith(prefix) && !e.recs.has(k)).map((k) => index.byKey.get(k)).filter(Boolean);
const ms = others('sygna:sprawa:');
const cs = others('compass:umowa:');
const os = others('counsel:zlecenie:');
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', compass: 'Compass', 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 || '-', r.contract.status, why, '-'];
if (r.matter) return [`${r.matter.reference} ${r.matter.name}`, r.matter.opened_at || '-', 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), r.draft.status, why, names[r.draft.author_id] || '-'];
return [`${r.order.reference} ${r.order.title}`, '-', 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 ${m.matter.status}, prowadzi ${names[m.matter.responsible_lawyer_id] || 'nieznany'}`;
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, 'compass: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)}`).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 Compassie do sprawy ${matter(seen(index.byKey.get(mk)))}`);
else if (!c.contract.matter_ref) out.push('umowa nie jest przypisana do sprawy w Compassie');
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. Jeśli karta przy module pisze (0) albo brak dostępu, powiedz to wprost.)`;
}
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.