[FEAT] Knowledge Base RAG multi-livello (SYSTEM/FIRM/ORG) + Qdrant + Voyage

- KnowledgeBaseController: ingest, list, firmOrgs, search, delete
- VectorService (Qdrant + buildAuthzFilter), EmbedService (Voyage), RagService (pipeline)
- AIService::askWithRag con fallback graceful
- docker-compose: servizio qdrant + env Voyage (chiave da .env/vault, no hardcoded)
- SQL 012 consulting_firms, 013 firm_assignments + kb_uploaded_documents
- public/kb.html + kb.js (upload, lista, search preview)

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
DevEnv nis2-agile
2026-05-29 15:44:13 +02:00
co-authored by Claude Opus 4.8
parent 9b53ca3ba1
commit a7a21faa82
10 changed files with 1164 additions and 0 deletions
+230
View File
@@ -0,0 +1,230 @@
/**
* NIS2 Agile - Knowledge Base UI (Migration 012-014)
*
* Gestisce upload documento, listing, search semantica con visibilita' multi-livello.
*/
(function () {
'use strict';
function getJwt() {
try {
return localStorage.getItem('access_token') || sessionStorage.getItem('access_token') || '';
} catch (e) { return ''; }
}
function authHeaders() {
return {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + getJwt(),
};
}
function escHtml(s) {
var d = document.createElement('div');
d.textContent = s == null ? '' : String(s);
return d.innerHTML;
}
function fmtScopeBadge(scope) {
return '<span class="kb-scope-badge ' + escHtml(scope) + '">' + escHtml(scope) + '</span>';
}
var btnUpload = document.getElementById('btn-kb-upload');
var btnSubmit = document.getElementById('btn-kb-submit');
var btnCancel = document.getElementById('btn-kb-cancel');
var btnSearch = document.getElementById('btn-kb-search');
var formCard = document.getElementById('kb-form-card');
var statusEl = document.getElementById('kb-status');
var listEl = document.getElementById('kb-doc-list');
var resultsEl = document.getElementById('kb-search-results');
var shareSel = document.getElementById('kb-shared-with');
if (!btnUpload || !formCard) return;
function setupScopeForUser() {
// Decodifica JWT per estrarre role e consulting_firm_id
var jwt = getJwt();
if (!jwt) return;
try {
var payload = JSON.parse(atob(jwt.split('.')[1]));
// Il JWT NIS2 contiene solo user_id; chiamo /api/auth/me per role + firm
fetch('/api/auth/me', { headers: authHeaders() })
.then(function (r) { return r.json(); })
.then(function (res) {
var u = (res && res.data && (res.data.user || res.data)) || {};
var role = u.role || '';
var firmId = u.consulting_firm_id || null;
var optSystem = document.querySelector('[data-scope-opt="SYSTEM"]');
var optFirm = document.querySelector('[data-scope-opt="FIRM"]');
var optOrg = document.querySelector('[data-scope-opt="ORG"]');
if (role === 'super_admin' && optSystem) optSystem.style.display = 'inline-flex';
if (firmId && optFirm) optFirm.style.display = 'inline-flex';
if (optOrg) optOrg.style.display = 'inline-flex';
if (firmId) loadFirmOrgs();
});
} catch (e) { /* ignore */ }
}
function loadFirmOrgs() {
if (!shareSel) return;
fetch('/api/knowledgebase/firmOrgs', { headers: authHeaders() })
.then(function (r) { return r.json(); })
.then(function (res) {
var orgs = (res && res.data && res.data.organizations) || [];
if (!orgs.length) {
shareSel.innerHTML = '<option value="">Nessuna organizzazione nello studio</option>';
return;
}
shareSel.innerHTML = orgs.map(function (o) {
var label = o.name + (o.vat_number ? ' (P.IVA ' + o.vat_number + ')' : '');
return '<option value="' + o.id + '">' + escHtml(label) + '</option>';
}).join('');
}).catch(function () {
shareSel.innerHTML = '<option value="">Errore caricamento organizzazioni</option>';
});
}
function loadDocList() {
if (!listEl) return;
listEl.innerHTML = '<div class="text-muted">Caricamento...</div>';
fetch('/api/knowledgebase/list', { headers: authHeaders() })
.then(function (r) { return r.json(); })
.then(function (res) {
var docs = (res && res.data && res.data.documents) || [];
if (!docs.length) {
listEl.innerHTML = '<div class="text-muted">Nessun documento visibile</div>';
return;
}
listEl.innerHTML = docs.map(function (d) {
return '<div class="kb-doc-row">' +
'<div>' +
'<strong>' + escHtml(d.title) + '</strong> ' + fmtScopeBadge(d.scope) +
'<div style="font-size:.78rem;color:var(--gray-500);">' +
escHtml(d.entity_type || '') + ' &middot; ' + (d.chunk_count || 0) + ' chunk &middot; ' + escHtml(d.created_at) +
'</div>' +
'</div>' +
'<button class="btn btn-sm btn-danger" data-del-id="' + d.id + '">Elimina</button>' +
'</div>';
}).join('');
// Wire delete buttons
listEl.querySelectorAll('[data-del-id]').forEach(function (btn) {
btn.addEventListener('click', function () {
if (!confirm('Eliminare definitivamente questo documento dalla KB?')) return;
var id = this.getAttribute('data-del-id');
fetch('/api/knowledgebase/' + id, {
method: 'DELETE',
headers: authHeaders(),
}).then(function (r) { return r.json(); }).then(function (res) {
if (res && res.success) loadDocList();
else alert('Errore: ' + ((res && res.message) || 'sconosciuto'));
});
});
});
}).catch(function () {
listEl.innerHTML = '<div class="text-danger">Errore caricamento</div>';
});
}
btnUpload.addEventListener('click', function () {
var visible = formCard.style.display !== 'none';
formCard.style.display = visible ? 'none' : 'block';
if (!visible) setupScopeForUser();
});
btnCancel.addEventListener('click', function () { formCard.style.display = 'none'; });
document.querySelectorAll('input[name="kb-scope"]').forEach(function (r) {
r.addEventListener('change', function () {
var block = document.getElementById('kb-share-block');
if (block) block.style.display = (this.value === 'FIRM') ? 'block' : 'none';
});
});
btnSubmit.addEventListener('click', function () {
var title = (document.getElementById('kb-title') || {}).value || '';
var text = (document.getElementById('kb-text') || {}).value || '';
var entityType = (document.getElementById('kb-entity-type') || {}).value || 'custom';
var scopeEl = document.querySelector('input[name="kb-scope"]:checked');
var scope = scopeEl ? scopeEl.value : 'ORG';
if (!title.trim()) { statusEl.textContent = 'Inserisci un titolo'; statusEl.style.color = '#ef4444'; return; }
if (text.length < 50) { statusEl.textContent = 'Testo troppo breve (min 50 caratteri)'; statusEl.style.color = '#ef4444'; return; }
var sharedWith = [];
if (scope === 'FIRM' && shareSel) {
for (var i = 0; i < shareSel.options.length; i++) {
if (shareSel.options[i].selected && shareSel.options[i].value) {
sharedWith.push(parseInt(shareSel.options[i].value, 10));
}
}
}
btnSubmit.disabled = true;
statusEl.style.color = '#0ea5e9';
statusEl.textContent = 'Indicizzazione in corso...';
fetch('/api/knowledgebase/ingest', {
method: 'POST',
headers: authHeaders(),
body: JSON.stringify({
title: title.trim(),
text: text,
entity_type: entityType,
scope: scope,
shared_with_orgs: sharedWith,
}),
}).then(function (r) { return r.json().then(function (j) { return { ok: r.ok, body: j }; }); })
.then(function (res) {
btnSubmit.disabled = false;
if (res.ok && res.body && res.body.success !== false) {
var d = res.body.data || res.body;
statusEl.style.color = '#22C55E';
statusEl.textContent = 'Documento indicizzato (' + (d.scope || scope) + ', ' + (d.chunks || '?') + ' chunk)' +
(sharedWith.length ? ' — condiviso con ' + sharedWith.length + ' org.' : '');
document.getElementById('kb-title').value = '';
document.getElementById('kb-text').value = '';
loadDocList();
} else {
statusEl.style.color = '#ef4444';
statusEl.textContent = 'Errore: ' + ((res.body && res.body.message) || 'sconosciuto');
}
}).catch(function (e) {
btnSubmit.disabled = false;
statusEl.style.color = '#ef4444';
statusEl.textContent = 'Errore di rete: ' + (e.message || '');
});
});
btnSearch.addEventListener('click', function () {
var q = (document.getElementById('kb-search-query') || {}).value || '';
if (!q.trim()) return;
resultsEl.innerHTML = '<div class="text-muted">Ricerca in corso...</div>';
fetch('/api/knowledgebase/search', {
method: 'POST',
headers: authHeaders(),
body: JSON.stringify({ query: q.trim(), top_k: 5 }),
}).then(function (r) { return r.json(); })
.then(function (res) {
var hits = (res && res.data && res.data.results) || [];
if (!hits.length) {
resultsEl.innerHTML = '<div class="text-muted">Nessun risultato</div>';
return;
}
resultsEl.innerHTML = hits.map(function (h, i) {
return '<div style="padding:10px;border:1px solid var(--gray-100);border-radius:6px;margin-bottom:8px;">' +
'<div><strong>[' + (i + 1) + '] ' + escHtml(h.title) + '</strong> ' +
fmtScopeBadge(h.scope) + ' <span style="font-size:.72rem;color:var(--gray-500);">score=' + h.score + '</span></div>' +
'<div style="font-size:.84rem;color:var(--gray-700);margin-top:6px;line-height:1.4;">' +
escHtml(h.content.substring(0, 300)) + (h.content.length > 300 ? '...' : '') +
'</div></div>';
}).join('');
});
});
// Carica lista al boot
loadDocList();
})();
+134
View File
@@ -0,0 +1,134 @@
<!DOCTYPE html>
<html lang="it">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Knowledge Base - NIS2 Agile</title>
<link rel="stylesheet" href="css/style.css">
<style>
.kb-scope-radios { display: flex; gap: 18px; flex-wrap: wrap; font-size: .9rem; }
.kb-scope-radios label { display: inline-flex; align-items: center; gap: 6px; cursor: pointer; }
.kb-share-block { margin-top: 12px; }
.kb-doc-list { margin-top: 24px; }
.kb-doc-row { padding: 10px 12px; border-bottom: 1px solid var(--gray-100); display: flex; justify-content: space-between; align-items: center; }
.kb-scope-badge { font-size: .72rem; padding: 2px 8px; border-radius: 10px; font-weight: 600; }
.kb-scope-badge.SYSTEM { background: #DBEAFE; color: #1E40AF; }
.kb-scope-badge.FIRM { background: #FEF3C7; color: #92400E; }
.kb-scope-badge.ORG { background: #DCFCE7; color: #166534; }
</style>
</head>
<body>
<div class="app-layout">
<aside class="sidebar" id="sidebar"></aside>
<main class="main-content">
<header class="content-header">
<h2>Knowledge Base</h2>
<div class="content-header-actions">
<button class="btn btn-primary" id="btn-kb-upload">
<svg viewBox="0 0 20 20" fill="currentColor" style="width:18px;height:18px;vertical-align:middle;"><path d="M5.5 13a3.5 3.5 0 01-.369-6.98 4 4 0 117.753-1.977A4.5 4.5 0 1113.5 13H11V9.413l1.293 1.293a1 1 0 001.414-1.414l-3-3a1 1 0 00-1.414 0l-3 3a1 1 0 001.414 1.414L9 9.414V13H5.5z"/><path d="M9 13h2v5a1 1 0 11-2 0v-5z"/></svg>
Carica documento
</button>
</div>
</header>
<div class="content-body">
<p class="text-muted" style="margin-top:0;">
Carica documenti (procedure, policy, normative, training material) che l'AI usera' per
rispondere alle domande con citazioni precise. La visibilita' segue il modello a 3 livelli:
<strong>SYSTEM</strong> (vendor), <strong>FIRM</strong> (studio + condivisioni esplicite),
<strong>ORG</strong> (singola organizzazione cliente).
</p>
<!-- Form upload (hidden by default) -->
<div class="card" id="kb-form-card" style="display:none;margin-top:16px;">
<div class="card-body">
<div class="form-grid" style="display:grid;grid-template-columns:1fr 1fr;gap:12px;">
<div class="form-group">
<label for="kb-title">Titolo</label>
<input type="text" id="kb-title" class="form-control" placeholder="Es: Procedura interna gestione incidenti NIS2">
</div>
<div class="form-group">
<label for="kb-entity-type">Tipo</label>
<select id="kb-entity-type" class="form-control">
<option value="custom">Procedura interna</option>
<option value="platform_guide">Linea guida</option>
<option value="csrd">Normativa</option>
<option value="training">Training</option>
</select>
</div>
</div>
<div class="form-group" style="margin-top:12px;">
<label for="kb-text">Contenuto (testo libero, 50&ndash;50.000 caratteri)</label>
<textarea id="kb-text" rows="8" class="form-control"
placeholder="Incolla qui il testo della procedura, della checklist o del template..."></textarea>
</div>
<div style="margin-top:12px;border-top:1px solid var(--gray-100);padding-top:12px;">
<label style="font-weight:600;font-size:.85rem;">Visibilita'</label>
<div class="kb-scope-radios" style="margin-top:6px;">
<label data-scope-opt="SYSTEM" style="display:none;">
<input type="radio" name="kb-scope" value="SYSTEM"> Sistema (super_admin)
</label>
<label data-scope-opt="FIRM" style="display:none;">
<input type="radio" name="kb-scope" value="FIRM"> Studio + condivisioni
</label>
<label data-scope-opt="ORG">
<input type="radio" name="kb-scope" value="ORG" checked> Solo organizzazione corrente
</label>
</div>
</div>
<div id="kb-share-block" class="kb-share-block" style="display:none;">
<label style="font-size:.78rem;color:var(--gray-600);">
Organizzazioni clienti destinatarie (Ctrl/Cmd per selezione multipla, opzionale):
</label>
<select id="kb-shared-with" multiple size="5" class="form-control">
<option value="">Caricamento organizzazioni del firm...</option>
</select>
<div style="font-size:.72rem;color:var(--gray-500);margin-top:4px;">
Lascia vuoto per condividere solo con i collaboratori dello studio.
</div>
</div>
<div style="margin-top:16px;display:flex;gap:8px;align-items:center;">
<button class="btn btn-primary" id="btn-kb-submit">Indicizza documento</button>
<button class="btn btn-secondary" id="btn-kb-cancel">Annulla</button>
<span id="kb-status" style="margin-left:8px;font-size:.85rem;"></span>
</div>
</div>
</div>
<!-- Lista documenti -->
<div class="card kb-doc-list">
<div class="card-header">
<h3>Documenti caricati visibili</h3>
</div>
<div class="card-body">
<div id="kb-doc-list">
<div class="text-muted">Caricamento...</div>
</div>
</div>
</div>
<!-- Search preview -->
<div class="card" style="margin-top:24px;">
<div class="card-header"><h3>Test search semantica</h3></div>
<div class="card-body">
<div style="display:flex;gap:8px;">
<input type="text" id="kb-search-query" class="form-control" placeholder="Es: come gestire un incidente NIS2?">
<button class="btn btn-secondary" id="btn-kb-search">Cerca</button>
</div>
<div id="kb-search-results" style="margin-top:12px;"></div>
</div>
</div>
</div>
</main>
</div>
<script src="js/common.js"></script>
<script src="js/api.js"></script>
<script src="js/kb.js"></script>
</body>
</html>