Platform bundle: marketing publish, IT ops, packaging, agents mesh.
Volledige Foodlinkk Command Center uitbreiding met social automatisering, reclamefolder filters, Proxmox monitoring en documentatie.
This commit is contained in:
@@ -0,0 +1,109 @@
|
||||
(function () {
|
||||
const NS = 'http://www.w3.org/2000/svg';
|
||||
|
||||
function make(tag, attrs = {}) {
|
||||
const el = document.createElementNS(NS, tag);
|
||||
Object.entries(attrs).forEach(([k, v]) => el.setAttribute(k, String(v)));
|
||||
return el;
|
||||
}
|
||||
|
||||
function clear(el) {
|
||||
while (el.firstChild) el.removeChild(el.firstChild);
|
||||
}
|
||||
|
||||
function curvePath(x1, y1, x2, y2) {
|
||||
const cx1 = x1 + (x2 - x1) * 0.35;
|
||||
const cy1 = y1;
|
||||
const cx2 = x1 + (x2 - x1) * 0.72;
|
||||
const cy2 = y2;
|
||||
return `M ${x1} ${y1} C ${cx1} ${cy1}, ${cx2} ${cy2}, ${x2} ${y2}`;
|
||||
}
|
||||
|
||||
async function loadMeshData() {
|
||||
const r = await fetch('/api/agents/mesh');
|
||||
if (!r.ok) throw new Error('Mesh API unavailable');
|
||||
return r.json();
|
||||
}
|
||||
|
||||
function drawMesh(svg, data) {
|
||||
clear(svg);
|
||||
const vb = svg.viewBox.baseVal;
|
||||
const width = vb && vb.width ? vb.width : 1000;
|
||||
const height = vb && vb.height ? vb.height : 620;
|
||||
const cx = width / 2;
|
||||
const cy = height / 2;
|
||||
const radius = Math.min(width, height) * 0.35;
|
||||
|
||||
const souls = (data.nodes || []).filter((n) => (n.agent_key || '').toLowerCase() !== 'herman');
|
||||
const edgesBySource = {};
|
||||
(data.edges || []).forEach((e) => { edgesBySource[e.source] = e; });
|
||||
|
||||
souls.forEach((node, i) => {
|
||||
const a = (Math.PI * 2 * i) / Math.max(1, souls.length) - Math.PI / 2;
|
||||
node._x = cx + Math.cos(a) * radius;
|
||||
node._y = cy + Math.sin(a) * radius;
|
||||
});
|
||||
|
||||
const edgesLayer = make('g');
|
||||
const nodesLayer = make('g');
|
||||
svg.appendChild(edgesLayer);
|
||||
svg.appendChild(nodesLayer);
|
||||
|
||||
souls.forEach((node) => {
|
||||
const pathDef = curvePath(node._x, node._y, cx, cy);
|
||||
const edge = make('path', { d: pathDef, class: 'mesh-edge' });
|
||||
edgesLayer.appendChild(edge);
|
||||
|
||||
if (edgesBySource[node.agent_key]) {
|
||||
const pulse = make('path', { d: pathDef, class: 'mesh-pulse' });
|
||||
pulse.style.animationDuration = `${Math.max(1.2, 3.5 - Math.min(2.2, edgesBySource[node.agent_key].weight / 8))}s`;
|
||||
edgesLayer.appendChild(pulse);
|
||||
}
|
||||
});
|
||||
|
||||
const herman = make('g', { class: 'mesh-node mesh-herman' });
|
||||
herman.appendChild(make('circle', { class: 'ring', cx, cy, r: 62 }));
|
||||
herman.appendChild(make('circle', { class: 'main', cx, cy, r: 46 }));
|
||||
const crown = make('text', { x: cx, y: cy - 2, 'font-size': 24, 'text-anchor': 'middle' });
|
||||
crown.textContent = '👑';
|
||||
herman.appendChild(crown);
|
||||
const label = make('text', { x: cx, y: cy + 22 });
|
||||
label.textContent = 'Herman · Co-CEO';
|
||||
herman.appendChild(label);
|
||||
nodesLayer.appendChild(herman);
|
||||
|
||||
souls.forEach((node) => {
|
||||
const group = make('g', { class: `mesh-node ${node.health || 'idle'}` });
|
||||
group.appendChild(make('circle', { cx: node._x, cy: node._y, r: 24 }));
|
||||
const shortName = (node.display_name || node.agent_key || '?').split(' ')[0];
|
||||
const t = make('text', { x: node._x, y: node._y + 4 });
|
||||
t.textContent = shortName;
|
||||
group.appendChild(t);
|
||||
const role = make('text', { x: node._x, y: node._y + 42, 'font-size': 10, opacity: 0.82 });
|
||||
role.textContent = node.role_title || node.agent_key;
|
||||
group.appendChild(role);
|
||||
group.addEventListener('click', () => {
|
||||
if (window.Cockpit && Cockpit.toast) {
|
||||
Cockpit.toast(`${node.display_name || node.agent_key}: ${node.health || 'idle'}`, 'success');
|
||||
}
|
||||
});
|
||||
nodesLayer.appendChild(group);
|
||||
});
|
||||
}
|
||||
|
||||
async function mount(targetId) {
|
||||
const svg = document.getElementById(targetId);
|
||||
if (!svg) return;
|
||||
try {
|
||||
const data = await loadMeshData();
|
||||
drawMesh(svg, data);
|
||||
} catch (e) {
|
||||
clear(svg);
|
||||
const msg = make('text', { x: 32, y: 40, fill: '#ef4444', 'font-size': 14 });
|
||||
msg.textContent = 'Mesh kon niet geladen worden';
|
||||
svg.appendChild(msg);
|
||||
}
|
||||
}
|
||||
|
||||
window.AgentsMesh = { mount };
|
||||
})();
|
||||
@@ -0,0 +1,181 @@
|
||||
window.AnalyticsCharts = (function () {
|
||||
var charts = {};
|
||||
var colors = {
|
||||
gold: 'rgba(252, 211, 77, 0.85)', cyan: 'rgba(56, 189, 248, 0.85)',
|
||||
green: 'rgba(74, 222, 128, 0.85)', red: 'rgba(251, 113, 133, 0.85)',
|
||||
purple: 'rgba(168, 85, 247, 0.85)', orange: 'rgba(255, 159, 67, 0.85)',
|
||||
gray: 'rgba(159, 176, 196, 0.85)', grid: 'rgba(159, 176, 196, 0.12)', text: '#c8d4e0',
|
||||
};
|
||||
var palette = [colors.gold, colors.cyan, colors.green, colors.purple, colors.orange, colors.red, colors.gray];
|
||||
|
||||
function destroyAll() {
|
||||
Object.keys(charts).forEach(function (k) {
|
||||
if (charts[k]) { charts[k].destroy(); charts[k] = null; }
|
||||
});
|
||||
}
|
||||
|
||||
function barChart(id, labels, values, label, horizontal) {
|
||||
var canvas = document.getElementById(id);
|
||||
if (!canvas || typeof Chart === 'undefined') return;
|
||||
if (charts[id]) charts[id].destroy();
|
||||
charts[id] = new Chart(canvas, {
|
||||
type: 'bar',
|
||||
data: {
|
||||
labels: labels,
|
||||
datasets: [{ label: label, data: values, backgroundColor: palette.slice(0, labels.length), borderRadius: 6 }],
|
||||
},
|
||||
options: {
|
||||
indexAxis: horizontal ? 'y' : 'x',
|
||||
responsive: true,
|
||||
plugins: { legend: { display: false } },
|
||||
scales: {
|
||||
x: { ticks: { color: colors.text, maxRotation: 45 }, grid: { color: colors.grid } },
|
||||
y: { ticks: { color: colors.text }, grid: { color: colors.grid } },
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
function doughnut(id, labels, values) {
|
||||
var canvas = document.getElementById(id);
|
||||
if (!canvas || typeof Chart === 'undefined') return;
|
||||
if (charts[id]) charts[id].destroy();
|
||||
charts[id] = new Chart(canvas, {
|
||||
type: 'doughnut',
|
||||
data: { labels: labels, datasets: [{ data: values, backgroundColor: palette, borderWidth: 0 }] },
|
||||
options: { responsive: true, plugins: { legend: { position: 'bottom', labels: { color: colors.text, boxWidth: 12 } } } },
|
||||
});
|
||||
}
|
||||
|
||||
function lineChart(id, labels, values) {
|
||||
var canvas = document.getElementById(id);
|
||||
if (!canvas || typeof Chart === 'undefined') return;
|
||||
if (charts[id]) charts[id].destroy();
|
||||
charts[id] = new Chart(canvas, {
|
||||
type: 'line',
|
||||
data: {
|
||||
labels: labels,
|
||||
datasets: [{ data: values, borderColor: colors.cyan, backgroundColor: 'rgba(56,189,248,0.15)', fill: true, tension: 0.3 }],
|
||||
},
|
||||
options: {
|
||||
responsive: true,
|
||||
plugins: { legend: { display: false } },
|
||||
scales: {
|
||||
x: { ticks: { color: colors.text }, grid: { color: colors.grid } },
|
||||
y: { ticks: { color: colors.text }, grid: { color: colors.grid } },
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
function renderKpis(container, kpis) {
|
||||
if (!container || !kpis) return;
|
||||
var items = [
|
||||
['Klanten totaal', kpis.clients_total], ['Actieve klanten', kpis.clients_active],
|
||||
['Pipeline €', '€' + Math.round(kpis.pipeline_eur || 0).toLocaleString('nl-NL')],
|
||||
['Supermarkten', kpis.supermarkets], ['Groothandels', kpis.wholesalers],
|
||||
['CRM actief', kpis.crm_partnerships], ['RSS items', kpis.rss_items],
|
||||
['Bookmarks', kpis.rss_bookmarks], ['Promo's', kpis.promo_campaigns],
|
||||
['Agent events', kpis.agent_events], ['Goedkeuringen', kpis.pending_approvals],
|
||||
['Contacten SM', kpis.contacts_supermarket], ['NAS docs', kpis.nas_docs],
|
||||
];
|
||||
container.innerHTML = items.map(function (it) {
|
||||
return '<div class="kpi-card"><span>' + it[0] + '</span><strong>' + it[1] + '</strong></div>';
|
||||
}).join('');
|
||||
}
|
||||
|
||||
function renderTables(data) {
|
||||
var dealsEl = document.getElementById('analytics-deals-table');
|
||||
var eventsEl = document.getElementById('analytics-events-table');
|
||||
if (dealsEl) {
|
||||
dealsEl.innerHTML = (data.recent_deals || []).map(function (d) {
|
||||
return '<tr><td>' + (d.title || '—') + '</td><td>' + (d.stage || '') + '</td><td>€' + Math.round(Number(d.value || 0)).toLocaleString('nl-NL') + '</td></tr>';
|
||||
}).join('') || '<tr><td colspan="3">Geen deals</td></tr>';
|
||||
}
|
||||
if (eventsEl) {
|
||||
eventsEl.innerHTML = (data.recent_events || []).map(function (e) {
|
||||
var t = (e.created_at || '').substring(0, 16).replace('T', ' ');
|
||||
return '<tr><td>' + (e.agent_name || '') + '</td><td>' + (e.title || e.event_type || '') + '</td><td>' + t + '</td></tr>';
|
||||
}).join('') || '<tr><td colspan="3">Geen events</td></tr>';
|
||||
}
|
||||
}
|
||||
|
||||
function render(data) {
|
||||
if (!data) return;
|
||||
renderKpis(document.getElementById('analytics-kpis'), data.kpis);
|
||||
barChart('chart-deals', (data.deals_by_stage || []).map(function (r) { return r.stage; }),
|
||||
(data.deals_by_stage || []).map(function (r) { return Number(r.total || r.cnt || 0); }), 'EUR');
|
||||
barChart('chart-clients', (data.clients_by_stage || []).map(function (r) { return r.stage; }),
|
||||
(data.clients_by_stage || []).map(function (r) { return Number(r.cnt || 0); }), 'Klanten');
|
||||
barChart('chart-chains', (data.supermarkets_by_chain || []).map(function (r) { return r.chain; }),
|
||||
(data.supermarkets_by_chain || []).map(function (r) { return Number(r.cnt || 0); }), 'Filialen');
|
||||
doughnut('chart-provinces', (data.supermarkets_by_province || []).map(function (r) { return r.province; }),
|
||||
(data.supermarkets_by_province || []).map(function (r) { return Number(r.cnt || 0); }));
|
||||
doughnut('chart-partnerships', (data.partnership_breakdown || []).map(function (r) { return r.status; }),
|
||||
(data.partnership_breakdown || []).map(function (r) { return Number(r.cnt || 0); }));
|
||||
barChart('chart-agents', (data.events_by_agent || []).map(function (r) { return r.agent_name; }),
|
||||
(data.events_by_agent || []).map(function (r) { return Number(r.cnt || 0); }), 'Events', true);
|
||||
lineChart('chart-timeline', (data.events_timeline || []).map(function (r) { return String(r.day || '').substring(5); }),
|
||||
(data.events_timeline || []).map(function (r) { return Number(r.cnt || 0); }));
|
||||
doughnut('chart-rss', (data.rss_by_category || []).map(function (r) { return r.category || 'other'; }),
|
||||
(data.rss_by_category || []).map(function (r) { return Number(r.cnt || 0); }));
|
||||
barChart('chart-wholesale', (data.wholesalers_by_province || []).map(function (r) { return r.province; }),
|
||||
(data.wholesalers_by_province || []).map(function (r) { return Number(r.cnt || 0); }), 'GH');
|
||||
doughnut('chart-sentiment', (data.sentiment_distribution || []).map(function (r) { return r.sentiment_label || 'neutral'; }),
|
||||
(data.sentiment_distribution || []).map(function (r) { return Number(r.cnt || 0); }));
|
||||
barChart('chart-words', (data.top_words || []).slice(0, 10).map(function (r) { return r.lemma; }),
|
||||
(data.top_words || []).slice(0, 10).map(function (r) { return Number(r.total || 0); }), 'Count', true);
|
||||
barChart('chart-opportunities', (data.top_opportunities || []).map(function (r) { return (r.chain || '') + ' ' + (r.city || ''); }),
|
||||
(data.top_opportunities || []).map(function (r) { return Math.round(Number(r.halal_opportunity_score || 0)); }), 'Score', true);
|
||||
barChart('chart-promo', (data.promo_by_chain || []).map(function (r) { return r.chain || '?'; }),
|
||||
(data.promo_by_chain || []).map(function (r) { return Number(r.cnt || 0); }), 'Promo');
|
||||
doughnut('chart-milestones', (data.milestones_by_status || []).map(function (r) { return r.status; }),
|
||||
(data.milestones_by_status || []).map(function (r) { return Number(r.cnt || 0); }));
|
||||
renderTables(data);
|
||||
}
|
||||
|
||||
return { render: render, destroyAll: destroyAll };
|
||||
})();
|
||||
|
||||
function analyticsHub() {
|
||||
return {
|
||||
loading: false,
|
||||
updatedAt: '—',
|
||||
liveLabel: 'Live',
|
||||
f: { chain: '', province: '', stage: '', agent: '', days: 90 },
|
||||
meta: {},
|
||||
_pollStop: null,
|
||||
init() {
|
||||
var initial = window.ANALYTICS_INITIAL || {};
|
||||
this.meta = initial.filter_meta || {};
|
||||
AnalyticsCharts.render(initial);
|
||||
this.updatedAt = (initial.generated_at || '').substring(0, 19).replace('T', ' ');
|
||||
this._pollStop = CockpitLive.startPolling(function () { return this.refresh(false); }.bind(this), 30000);
|
||||
},
|
||||
params() {
|
||||
var p = new URLSearchParams();
|
||||
Object.entries(this.f).forEach(function (e) {
|
||||
if (e[1] !== null && e[1] !== '' && e[1] !== undefined) p.set(e[0], e[1]);
|
||||
});
|
||||
return p.toString();
|
||||
},
|
||||
async refresh(toast) {
|
||||
this.loading = true;
|
||||
try {
|
||||
var data = await fetch('/analytics/api/data?' + this.params()).then(function (r) { return r.json(); });
|
||||
this.meta = data.filter_meta || this.meta;
|
||||
AnalyticsCharts.render(data);
|
||||
this.updatedAt = (data.generated_at || '').substring(0, 19).replace('T', ' ');
|
||||
if (toast !== false) Cockpit.toast('Analytics bijgewerkt', 'success');
|
||||
} catch (e) {
|
||||
if (toast !== false) Cockpit.toast(e.message, 'error');
|
||||
} finally {
|
||||
this.loading = false;
|
||||
}
|
||||
},
|
||||
resetFilters() {
|
||||
this.f = { chain: '', province: '', stage: '', agent: '', days: 90 };
|
||||
this.refresh();
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
window.beursHub = function () {
|
||||
return {
|
||||
tab: new URLSearchParams(location.search).get('tab') || 'beurs',
|
||||
busy: false,
|
||||
lastRefresh: '',
|
||||
listed: [],
|
||||
unlisted: [],
|
||||
summary: {},
|
||||
trends: { halal_meat_trends: [], top_dishes: [], market_trends: [] },
|
||||
concepts: [],
|
||||
events: [],
|
||||
platformStats: {},
|
||||
eventFilter: '',
|
||||
pollTimer: null,
|
||||
indicatorStyle: { left: '0%', width: '25%' },
|
||||
|
||||
init() {
|
||||
this.updateIndicator();
|
||||
this.refreshAll();
|
||||
this.pollTimer = setInterval(() => {
|
||||
if (this.tab === 'events') this.loadEvents(false);
|
||||
}, 5000);
|
||||
},
|
||||
|
||||
setTab(t) {
|
||||
this.tab = t;
|
||||
const url = new URL(location.href);
|
||||
url.searchParams.set('tab', t);
|
||||
history.replaceState({}, '', url);
|
||||
this.updateIndicator();
|
||||
if (t === 'trends' && !this.trends.halal_meat_trends?.length) this.loadTrends();
|
||||
if (t === 'concepten' && !this.concepts.length) this.loadConcepts();
|
||||
if (t === 'events') this.loadEvents();
|
||||
},
|
||||
|
||||
updateIndicator() {
|
||||
const tabs = ['beurs', 'trends', 'concepten', 'events'];
|
||||
const i = tabs.indexOf(this.tab);
|
||||
const w = 100 / tabs.length;
|
||||
this.indicatorStyle = { left: (i * w) + '%', width: w + '%' };
|
||||
},
|
||||
|
||||
sparkPoints(arr) {
|
||||
if (!arr || !arr.length) return '';
|
||||
const min = Math.min.apply(null, arr);
|
||||
const max = Math.max.apply(null, arr);
|
||||
const range = max - min || 1;
|
||||
return arr.map(function (v, idx) {
|
||||
var x = (idx / (arr.length - 1 || 1)) * 100;
|
||||
var y = 28 - ((v - min) / range) * 24;
|
||||
return x.toFixed(1) + ',' + y.toFixed(1);
|
||||
}).join(' ');
|
||||
},
|
||||
|
||||
async refreshAll() {
|
||||
this.busy = true;
|
||||
try {
|
||||
await Promise.all([
|
||||
this.loadMarket(),
|
||||
this.loadTrends(),
|
||||
this.loadConcepts(),
|
||||
this.loadEvents(false),
|
||||
]);
|
||||
this.lastRefresh = new Date().toLocaleString('nl-NL');
|
||||
if (typeof Cockpit !== 'undefined') Cockpit.toast('Beurs data bijgewerkt', 'success');
|
||||
} catch (e) {
|
||||
if (typeof Cockpit !== 'undefined') Cockpit.toast(e.message, 'error');
|
||||
}
|
||||
this.busy = false;
|
||||
},
|
||||
|
||||
async loadMarket() {
|
||||
const d = await fetch('/api/retail/market/supermarkets').then(function (r) { return r.json(); });
|
||||
this.listed = d.listed || [];
|
||||
this.unlisted = d.unlisted_nl || [];
|
||||
this.summary = d.summary || {};
|
||||
},
|
||||
|
||||
async loadTrends() {
|
||||
const d = await fetch('/api/retail/market/food-trends').then(function (r) { return r.json(); });
|
||||
this.trends = d;
|
||||
},
|
||||
|
||||
async loadConcepts() {
|
||||
const d = await fetch('/api/retail/market/concepts?limit=6').then(function (r) { return r.json(); });
|
||||
this.concepts = d.concepts || [];
|
||||
},
|
||||
|
||||
async loadEvents(toast) {
|
||||
var q = this.eventFilter ? '?limit=80&agent=' + encodeURIComponent(this.eventFilter) : '?limit=80';
|
||||
try {
|
||||
var r = await fetch('/api/live/platform' + q).then(function (x) { return x.json(); });
|
||||
this.events = r.events || [];
|
||||
this.platformStats = r.stats || {};
|
||||
} catch (e) {
|
||||
if (toast !== false && typeof Cockpit !== 'undefined') Cockpit.toast(e.message, 'error');
|
||||
}
|
||||
},
|
||||
};
|
||||
};
|
||||
@@ -0,0 +1,347 @@
|
||||
window.BriefingCharts = (function () {
|
||||
var charts = {};
|
||||
var typewriterTimer = null;
|
||||
|
||||
function destroyAll() {
|
||||
Object.keys(charts).forEach(function (k) {
|
||||
if (charts[k]) { charts[k].destroy(); charts[k] = null; }
|
||||
});
|
||||
}
|
||||
|
||||
function parseContent(content) {
|
||||
var parts = (content || '').split(/\n---\n/);
|
||||
var ai = parts[0] || '';
|
||||
var summary = '', actions = [], longTerm = [];
|
||||
var sm = ai.match(/##\s*Samenvatting\s*\n([\s\S]*?)(?=##\s*Actiepunten|##\s*Lange termijn|$)/i);
|
||||
if (sm) summary = sm[1].trim().replace(/\*\*/g, '');
|
||||
var am = ai.match(/##\s*Actiepunten[^\n]*\n([\s\S]*?)(?=##\s*Lange termijn|$)/i);
|
||||
if (am) actions = am[1].split('\n').map(function (l) { return l.replace(/^[-*]\s*/, '').trim(); }).filter(Boolean);
|
||||
var lm = ai.match(/##\s*Lange termijn[^\n]*\n([\s\S]*)/i);
|
||||
if (lm) longTerm = lm[1].split('\n').map(function (l) { return l.replace(/^[-*]\s*/, '').trim(); }).filter(Boolean);
|
||||
if (!summary && ai.trim()) summary = ai.trim().slice(0, 800).replace(/\*\*/g, '');
|
||||
return { summary: summary, actions: actions, longTerm: longTerm };
|
||||
}
|
||||
|
||||
function typewriter(el, text, speed) {
|
||||
if (!el) return;
|
||||
if (typewriterTimer) clearInterval(typewriterTimer);
|
||||
el.textContent = '';
|
||||
if (!text) { el.textContent = 'Klik «Genereer dagrapport» voor je persoonlijke Herman briefing.'; return; }
|
||||
var i = 0;
|
||||
typewriterTimer = setInterval(function () {
|
||||
if (i < text.length) { el.textContent += text.charAt(i); i++; }
|
||||
else clearInterval(typewriterTimer);
|
||||
}, speed || 8);
|
||||
}
|
||||
|
||||
function countUp(el, end, prefix, suffix) {
|
||||
if (!el) return;
|
||||
prefix = prefix || ''; suffix = suffix || '';
|
||||
var start = 0, dur = 600, t0 = performance.now();
|
||||
function step(t) {
|
||||
var p = Math.min(1, (t - t0) / dur);
|
||||
var v = Math.round(start + (end - start) * p);
|
||||
el.textContent = prefix + v.toLocaleString('nl-NL') + suffix;
|
||||
if (p < 1) requestAnimationFrame(step);
|
||||
}
|
||||
requestAnimationFrame(step);
|
||||
}
|
||||
|
||||
function chartColors() {
|
||||
return {
|
||||
gold: 'rgba(252, 211, 77, 0.9)', cyan: 'rgba(56, 189, 248, 0.9)',
|
||||
green: 'rgba(74, 222, 128, 0.9)', red: 'rgba(251, 113, 133, 0.9)',
|
||||
gray: 'rgba(159, 176, 196, 0.85)', grid: 'rgba(159, 176, 196, 0.15)', text: '#c8d4e0',
|
||||
};
|
||||
}
|
||||
|
||||
function renderPipeline(canvas, stats) {
|
||||
if (!canvas || typeof Chart === 'undefined') return;
|
||||
var rows = stats.deals_by_stage || [];
|
||||
var c = chartColors();
|
||||
if (charts.pipeline) charts.pipeline.destroy();
|
||||
charts.pipeline = new Chart(canvas, {
|
||||
type: 'bar',
|
||||
data: { labels: rows.map(function (r) { return r.stage || '?'; }), datasets: [{ label: 'EUR', data: rows.map(function (r) { return Number(r.total) || 0; }), backgroundColor: c.gold, borderRadius: 6 }] },
|
||||
options: { responsive: true, plugins: { legend: { display: false }, title: { display: true, text: 'Pipeline per stage', color: c.text } },
|
||||
scales: { y: { ticks: { color: c.text, callback: function (v) { return '€' + v.toLocaleString('nl-NL'); } }, grid: { color: c.grid } }, x: { ticks: { color: c.text }, grid: { display: false } } } },
|
||||
});
|
||||
}
|
||||
|
||||
function renderSentiment(canvas, stats) {
|
||||
if (!canvas || typeof Chart === 'undefined') return;
|
||||
var files = stats.nas_files || [], counts = { positive: 0, neutral: 0, negative: 0 };
|
||||
files.forEach(function (f) { var s = (f.sentiment_label || 'neutral').toLowerCase(); if (counts[s] !== undefined) counts[s]++; });
|
||||
if (!files.length) counts.neutral = 1;
|
||||
var c = chartColors();
|
||||
if (charts.sentiment) charts.sentiment.destroy();
|
||||
charts.sentiment = new Chart(canvas, {
|
||||
type: 'doughnut',
|
||||
data: { labels: ['Positief', 'Neutraal', 'Negatief'], datasets: [{ data: [counts.positive, counts.neutral, counts.negative], backgroundColor: [c.green, c.gray, c.red], borderWidth: 0 }] },
|
||||
options: { responsive: true, plugins: { legend: { position: 'bottom', labels: { color: c.text } }, title: { display: true, text: 'NAS sentiment', color: c.text } } },
|
||||
});
|
||||
}
|
||||
|
||||
function renderWords(canvas, stats) {
|
||||
if (!canvas || typeof Chart === 'undefined') return;
|
||||
var rows = (stats.top_words || []).slice(0, 8), c = chartColors();
|
||||
if (charts.words) charts.words.destroy();
|
||||
charts.words = new Chart(canvas, {
|
||||
type: 'bar',
|
||||
data: { labels: rows.map(function (r) { return r.lemma; }), datasets: [{ data: rows.map(function (r) { return Number(r.total) || 0; }), backgroundColor: c.cyan, borderRadius: 6 }] },
|
||||
options: { indexAxis: 'y', responsive: true, plugins: { legend: { display: false }, title: { display: true, text: 'Top woorden NAS', color: c.text } },
|
||||
scales: { x: { ticks: { color: c.text }, grid: { color: c.grid } }, y: { ticks: { color: c.text }, grid: { display: false } } } },
|
||||
});
|
||||
}
|
||||
|
||||
function renderAgents(canvas, stats) {
|
||||
if (!canvas || typeof Chart === 'undefined') return;
|
||||
var map = {};
|
||||
(stats.recent_events || []).forEach(function (e) { var a = e.agent_name || 'other'; map[a] = (map[a] || 0) + 1; });
|
||||
var labels = Object.keys(map), c = chartColors();
|
||||
if (charts.agents) charts.agents.destroy();
|
||||
charts.agents = new Chart(canvas, {
|
||||
type: 'polarArea',
|
||||
data: { labels: labels, datasets: [{ data: labels.map(function (k) { return map[k]; }), backgroundColor: [c.gold, c.cyan, c.green, c.red, c.gray] }] },
|
||||
options: { responsive: true, plugins: { legend: { position: 'bottom', labels: { color: c.text } }, title: { display: true, text: 'Agent activiteit', color: c.text } },
|
||||
scales: { r: { ticks: { display: false }, grid: { color: c.grid } } } },
|
||||
});
|
||||
}
|
||||
|
||||
function eqBars() {
|
||||
return '<div class="hm-eq"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></div>';
|
||||
}
|
||||
|
||||
function sparklineSvg(values, trend) {
|
||||
if (!values || !values.length) return '';
|
||||
var min = Math.min.apply(null, values), max = Math.max.apply(null, values);
|
||||
var range = max - min || 1;
|
||||
var pts = values.map(function (v, i) {
|
||||
var x = (i / (values.length - 1 || 1)) * 100;
|
||||
var y = 100 - ((v - min) / range) * 80 - 10;
|
||||
return x.toFixed(1) + ',' + y.toFixed(1);
|
||||
}).join(' ');
|
||||
var color = trend === 'down' ? '#fb7185' : '#4ade80';
|
||||
return '<svg class="hm-spark" viewBox="0 0 100 100" preserveAspectRatio="none"><polyline fill="none" stroke="' + color + '" stroke-width="3" points="' + pts + '"/></svg>';
|
||||
}
|
||||
|
||||
function stockEqBars(trend) {
|
||||
var cls = trend === 'down' ? ' hm-eq-down' : '';
|
||||
return '<div class="hm-eq' + cls + '"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></div>';
|
||||
}
|
||||
|
||||
function renderStocksMini(container, stats) {
|
||||
if (!container) return;
|
||||
var stocks = (stats.market_stocks || []).slice(0, 4);
|
||||
var summary = stats.market_summary || {};
|
||||
if (!stocks.length) {
|
||||
container.innerHTML = '<a href="/beurs" class="btn btn-sm">Beurs openen →</a>';
|
||||
return;
|
||||
}
|
||||
container.innerHTML = stocks.map(function (s) {
|
||||
var pct = Number(s.change_pct || 0);
|
||||
return '<a href="/beurs" class="beurs-mini-chip ' + (pct >= 0 ? 'up' : 'down') + '">' +
|
||||
'<strong>' + (s.symbol || s.name) + '</strong> ' +
|
||||
(pct >= 0 ? '+' : '') + pct.toFixed(2) + '%</a>';
|
||||
}).join('') + '<small style="display:block;margin-top:0.35rem;color:#64748b">Gem. ' +
|
||||
(summary.avg_change_pct || 0) + '% · <a href="/beurs">alle koersen →</a></small>';
|
||||
}
|
||||
|
||||
function renderStocks(container, stats) {
|
||||
if (!container) return;
|
||||
var stocks = stats.market_stocks || [];
|
||||
var summary = stats.market_summary || {};
|
||||
var meta = document.getElementById('market-updated-at');
|
||||
if (meta) {
|
||||
var avg = summary.avg_change_pct;
|
||||
meta.textContent = stocks.length ? ('Gem. ' + (avg >= 0 ? '+' : '') + Number(avg || 0).toFixed(2) + '% · ' + (summary.quote_count || stocks.length) + ' quotes') : 'Beurs data laden…';
|
||||
}
|
||||
if (!stocks.length) {
|
||||
container.innerHTML = '<p class="empty-state">Beursdata tijdelijk niet beschikbaar — probeer Live data opnieuw.</p>';
|
||||
return;
|
||||
}
|
||||
container.innerHTML = stocks.map(function (s) {
|
||||
var pct = Number(s.change_pct || 0);
|
||||
var up = pct >= 0;
|
||||
var price = s.price != null ? Number(s.price).toFixed(2) : '—';
|
||||
var cur = s.currency || 'EUR';
|
||||
return '<div class="hm-stock-card hm-stock-' + (s.trend || (up ? 'up' : 'down')) + '">' +
|
||||
'<div class="hm-stock-head"><div><strong>' + (s.symbol || '') + '</strong><small>' + (s.name || '') + '</small></div>' +
|
||||
'<span class="hm-stock-pct ' + (up ? 'up' : 'down') + '">' + (up ? '▲' : '▼') + ' ' + Math.abs(pct).toFixed(2) + '%</span></div>' +
|
||||
'<div class="hm-stock-price">' + price + ' <small>' + cur + '</small></div>' +
|
||||
'<div class="hm-stock-chain">' + (s.chain || s.market || '') + '</div>' +
|
||||
sparklineSvg(s.sparkline || [], s.trend) + stockEqBars(s.trend) + '</div>';
|
||||
}).join('');
|
||||
}
|
||||
|
||||
function renderFoodHighlights(container, stats) {
|
||||
if (!container) return;
|
||||
var items = stats.food_market_highlights || stats.rss_highlights || [];
|
||||
if (!items.length) {
|
||||
container.innerHTML = '<p class="empty-state">Geen highlights — <a href="/marketing">RSS ophalen</a></p>';
|
||||
return;
|
||||
}
|
||||
container.innerHTML = items.map(function (r) {
|
||||
var cat = (r.category || 'markt').toUpperCase();
|
||||
return '<div class="hm-highlight-item"><span class="hm-cat-badge">' + cat + '</span>' +
|
||||
'<a href="' + (r.link || '#') + '" target="_blank" rel="noopener"><strong>' + (r.title || '') + '</strong></a>' +
|
||||
'<small>' + (r.feed_name || '') + '</small></div>';
|
||||
}).join('');
|
||||
}
|
||||
|
||||
function renderRegulations(container, stats) {
|
||||
if (!container) return;
|
||||
var items = stats.regulation_highlights || [];
|
||||
if (!items.length) {
|
||||
container.innerHTML = '<p class="empty-state">Regelgeving feeds — klik RSS refresh in Retail 360</p>';
|
||||
return;
|
||||
}
|
||||
container.innerHTML = items.map(function (r) {
|
||||
var cat = r.category === 'cbs' ? 'CBS' : 'REG';
|
||||
return '<div class="hm-highlight-item"><span class="hm-cat-badge hm-cat-' + (r.category || 'reg') + '">' + cat + '</span>' +
|
||||
'<a href="' + (r.link || '#') + '" target="_blank" rel="noopener"><strong>' + (r.title || '') + '</strong></a>' +
|
||||
'<small>' + (r.feed_name || '') + '</small></div>';
|
||||
}).join('');
|
||||
}
|
||||
|
||||
function renderTrends(canvas, stats) {
|
||||
if (!canvas || typeof Chart === 'undefined') return;
|
||||
var rows = stats.market_trends || [];
|
||||
var c = chartColors();
|
||||
if (charts.trends) charts.trends.destroy();
|
||||
if (!rows.length) return;
|
||||
charts.trends = new Chart(canvas, {
|
||||
type: 'bar',
|
||||
data: {
|
||||
labels: rows.map(function (r) { return (r.trend_name || '?').slice(0, 18); }),
|
||||
datasets: [{
|
||||
label: 'Kans %',
|
||||
data: rows.map(function (r) { return Math.round(Number(r.opportunity_score || 0) * 100); }),
|
||||
backgroundColor: [c.green, c.cyan, c.gold, c.purple || '#a855f7'],
|
||||
borderRadius: 6,
|
||||
}],
|
||||
},
|
||||
options: {
|
||||
responsive: true,
|
||||
plugins: { legend: { display: false }, title: { display: true, text: 'Markt trend scores', color: c.text } },
|
||||
scales: {
|
||||
y: { max: 100, ticks: { color: c.text, callback: function (v) { return v + '%'; } }, grid: { color: c.grid } },
|
||||
x: { ticks: { color: c.text, maxRotation: 45 }, grid: { display: false } },
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
function renderKpis(container, stats) {
|
||||
if (!container) return;
|
||||
var summary = stats.market_summary || {};
|
||||
var avgPct = Number(summary.avg_change_pct || 0);
|
||||
var best = summary.best_performer || {};
|
||||
var items = [
|
||||
{ label: 'Pipeline', sub: 'actieve deals', icon: '💰', color: '#00e5ff', pct: '72%', val: '€' + Math.round(stats.pipeline_eur || 0).toLocaleString('nl-NL') },
|
||||
{ label: 'Actieve klanten', sub: 'CRM · zaken mee', icon: '🤝', color: '#22c55e', pct: Math.min(95, Math.round(((stats.clients_active || 0) / Math.max(stats.clients_total || 1, 1)) * 100)) + '%', val: (stats.clients_active || 0) + ' / ' + (stats.clients_total || 0), link: '/clients' },
|
||||
{ label: 'CRM partnerships', sub: 'actieve filialen', icon: '🏪', color: '#ff9f43', pct: '45%', val: stats.crm_partnerships || 0, link: '/retail' },
|
||||
{ label: 'Supermarkten', sub: 'Retail 360 DB', icon: '🏪', color: '#b8ff3c', pct: '88%', val: (stats.supermarkets || 0).toLocaleString('nl-NL') },
|
||||
{ label: 'Halal kansen', sub: 'top score', icon: '🎯', color: '#a855f7', pct: '65%', val: stats.top_opportunities && stats.top_opportunities[0] ? Math.round(Number(stats.top_opportunities[0].halal_opportunity_score || 0)) + '/100' : '—' },
|
||||
{ label: 'Goedkeuringen', sub: 'wacht op OK', icon: '✓', color: '#ffd700', pct: '30%', val: stats.pending_approvals || 0 },
|
||||
];
|
||||
container.className = 'hm-neo-kpi-row';
|
||||
container.innerHTML = items.map(function (it) {
|
||||
var inner = '<div class="hm-neo-kpi"><div class="hm-neo-kpi-top">' +
|
||||
'<div class="hm-neo-ring" style="--ring-color:' + it.color + ';--ring-pct:' + it.pct + '"><div class="hm-neo-ring-inner">' + it.icon + '</div></div>' +
|
||||
'<div><div class="hm-neo-kpi-label">' + it.label + '</div><div class="hm-neo-kpi-sub">' + it.sub + '</div></div></div>' +
|
||||
'<div class="hm-neo-kpi-value">' + it.val + '</div>' + eqBars() + '</div>';
|
||||
return it.link ? '<a href="' + it.link + '" class="hm-neo-kpi-link">' + inner + '</a>' : inner;
|
||||
}).join('');
|
||||
}
|
||||
|
||||
function renderRetail(container, stats) {
|
||||
if (!container) return;
|
||||
var opps = stats.top_opportunities || [];
|
||||
if (!opps.length) { container.innerHTML = '<p class="empty-state">Geen kansen — <a href="/retail">open Retail 360</a></p>'; return; }
|
||||
container.innerHTML = opps.map(function (o) {
|
||||
var score = Math.round(Number(o.halal_opportunity_score) || 0);
|
||||
return '<a href="/retail" class="retail-highlight"><span><strong>' + (o.chain || '') + ' · ' + (o.name || '') + '</strong><br><small>' + (o.city || '') + '</small></span><span class="ticker-item">' + score + '/100</span></a>';
|
||||
}).join('');
|
||||
}
|
||||
|
||||
function renderMilestones(container, stats) {
|
||||
if (!container) return;
|
||||
var ms = stats.milestones_pending || [];
|
||||
if (!ms.length) {
|
||||
container.innerHTML = '<p class="empty-state">Nog geen milestones — voeg toe via <a href="/retail">Retail 360 → Sales tab</a></p>';
|
||||
return;
|
||||
}
|
||||
container.innerHTML = ms.map(function (m) {
|
||||
return '<div class="milestone-item"><span class="milestone-dot"></span><div><strong>' + (m.title || '') + '</strong><br><small>' + (m.chain || '') + ' ' + (m.store_name || '') + '</small></div></div>';
|
||||
}).join('');
|
||||
}
|
||||
|
||||
function renderExecutiveSummary(container, stats) {
|
||||
if (!container) return;
|
||||
var items = [
|
||||
{ icon: '🤝', label: 'Actieve klanten', val: (stats.clients_active || 0) + ' van ' + (stats.clients_total || stats.clients || 0), link: '/clients' },
|
||||
{ icon: '💰', label: 'Pipeline', val: '€' + Math.round(stats.pipeline_eur || 0).toLocaleString('nl-NL'), link: '/deals' },
|
||||
{ icon: '🏪', label: 'CRM partnerships', val: stats.crm_partnerships || 0, link: '/retail' },
|
||||
{ icon: '🛒', label: 'Supermarkten DB', val: (stats.supermarkets || 0).toLocaleString('nl-NL'), link: '/retail' },
|
||||
{ icon: '📦', label: 'Groothandels', val: stats.wholesalers || 0, link: '/retail' },
|
||||
{ icon: '✓', label: 'Goedkeuringen open', val: stats.pending_approvals || 0, link: '/' },
|
||||
{ icon: '📁', label: 'Actieve promo\'s', val: stats.promo_campaigns || '—', link: '/marketing?tab=reclame' },
|
||||
{ icon: '📊', label: 'NAS documenten', val: stats.nas_docs || 0, link: '/documents' },
|
||||
];
|
||||
var opps = (stats.top_opportunities || []).slice(0, 3);
|
||||
var ms = (stats.milestones_pending || []).slice(0, 3);
|
||||
var html = '<div class="hm-exec-grid">' + items.map(function (it) {
|
||||
return '<a href="' + it.link + '" class="hm-exec-item"><span class="hm-exec-icon">' + it.icon + '</span>' +
|
||||
'<div><strong>' + it.label + '</strong><div class="hm-exec-val">' + it.val + '</div></div></a>';
|
||||
}).join('') + '</div>';
|
||||
if (opps.length) {
|
||||
html += '<h4 style="margin:1rem 0 0.5rem;font-size:0.8rem;color:#94a3b8">Top halal kansen</h4><ul class="hm-exec-list">';
|
||||
opps.forEach(function (o) {
|
||||
html += '<li><a href="/retail">' + (o.chain || '') + ' · ' + (o.name || '') + ' (' + (o.city || '') + ') — ' + Math.round(Number(o.halal_opportunity_score || 0)) + '/100</a></li>';
|
||||
});
|
||||
html += '</ul>';
|
||||
}
|
||||
if (ms.length) {
|
||||
html += '<h4 style="margin:1rem 0 0.5rem;font-size:0.8rem;color:#94a3b8">Open milestones</h4><ul class="hm-exec-list">';
|
||||
ms.forEach(function (m) {
|
||||
html += '<li>' + (m.title || '') + ' · ' + (m.chain || '') + ' ' + (m.store_name || '') + '</li>';
|
||||
});
|
||||
html += '</ul>';
|
||||
}
|
||||
html += '<p class="hm-exec-footer" style="margin-top:1rem;font-size:0.8rem;color:#64748b">RSS & reclame folders → <a href="/marketing">Marketing Hub</a> · Volledige analytics → <a href="/analytics">Analytics</a></p>';
|
||||
container.innerHTML = html;
|
||||
}
|
||||
|
||||
function renderText(root, content, createdAt) {
|
||||
if (!root) return;
|
||||
var parsed = parseContent(content);
|
||||
var meta = document.getElementById('briefing-meta');
|
||||
if (meta && createdAt) meta.textContent = 'Laatst bijgewerkt: ' + String(createdAt).substring(0, 19).replace('T', ' ');
|
||||
typewriter(document.getElementById('briefing-summary-text'), parsed.summary, 8);
|
||||
var actEl = document.getElementById('briefing-actions-list');
|
||||
if (actEl) actEl.innerHTML = parsed.actions.length ? parsed.actions.map(function (a) { return '<li>' + a + '</li>'; }).join('') : '<li>Genereer dagrapport voor actiepunten</li>';
|
||||
var longEl = document.getElementById('briefing-longterm-list');
|
||||
if (longEl) longEl.innerHTML = parsed.longTerm.length ? parsed.longTerm.map(function (a) { return '<li>' + a + '</li>'; }).join('') : '<li>Halal kant-en-klaar partnerships schalen</li>';
|
||||
}
|
||||
|
||||
function renderLive(root, stats) {
|
||||
if (!root || !stats) return;
|
||||
renderKpis(document.getElementById('briefing-kpis'), stats);
|
||||
renderFoodHighlights(document.getElementById('briefing-food-highlights'), stats);
|
||||
renderExecutiveSummary(document.getElementById('briefing-executive-summary'), stats);
|
||||
renderRetail(document.getElementById('briefing-retail'), stats);
|
||||
renderMilestones(document.getElementById('briefing-milestones'), stats);
|
||||
renderPipeline(document.getElementById('chart-pipeline'), stats);
|
||||
renderSentiment(document.getElementById('chart-sentiment'), stats);
|
||||
renderWords(document.getElementById('chart-words'), stats);
|
||||
renderAgents(document.getElementById('chart-agents'), stats);
|
||||
}
|
||||
|
||||
function render(root, stats, content, createdAt) {
|
||||
renderLive(root, stats);
|
||||
renderText(root, content, createdAt);
|
||||
}
|
||||
|
||||
return { render: render, renderLive: renderLive, renderText: renderText, renderExecutiveSummary: renderExecutiveSummary, destroyAll: destroyAll };
|
||||
})();
|
||||
@@ -0,0 +1,75 @@
|
||||
window.Cockpit = (function () {
|
||||
const API = '/api/admin';
|
||||
|
||||
function toast(message, type) {
|
||||
type = type || 'info';
|
||||
let root = document.getElementById('cockpit-toasts');
|
||||
if (!root) {
|
||||
root = document.createElement('div');
|
||||
root.id = 'cockpit-toasts';
|
||||
root.className = 'toast-container';
|
||||
document.body.appendChild(root);
|
||||
}
|
||||
const el = document.createElement('div');
|
||||
el.className = 'toast toast-' + type;
|
||||
el.textContent = message;
|
||||
root.appendChild(el);
|
||||
setTimeout(function () { el.classList.add('toast-out'); setTimeout(function () { el.remove(); }, 300); }, 3500);
|
||||
}
|
||||
|
||||
function clearEmbeddedIframes() {
|
||||
document.querySelectorAll('iframe.browser-novnc, iframe[data-clear-on-nav]').forEach(function (f) {
|
||||
try { f.src = 'about:blank'; } catch (e) {}
|
||||
});
|
||||
}
|
||||
|
||||
async function request(path, options) {
|
||||
options = options || {};
|
||||
const url = path.startsWith('http') || path.startsWith('/api/') ? path : API + path;
|
||||
const headers = Object.assign({ 'Content-Type': 'application/json' }, options.headers || {});
|
||||
const fetchOpts = Object.assign({}, options, { headers: headers });
|
||||
if (options.signal) fetchOpts.signal = options.signal;
|
||||
const res = await fetch(url, fetchOpts);
|
||||
let data = null;
|
||||
try { data = await res.json(); } catch (e) { data = null; }
|
||||
if (!res.ok) {
|
||||
const msg = (data && (data.detail || data.message)) || res.statusText;
|
||||
throw new Error(typeof msg === 'string' ? msg : JSON.stringify(msg));
|
||||
}
|
||||
return data;
|
||||
}
|
||||
|
||||
function confirmDelete(message) {
|
||||
return window.confirm(message || 'Delete this item?');
|
||||
}
|
||||
|
||||
function openDrawer(id) {
|
||||
document.body.classList.add('drawer-open');
|
||||
var el = document.getElementById(id);
|
||||
if (el) el.classList.add('open');
|
||||
}
|
||||
|
||||
function closeDrawer(id) {
|
||||
document.body.classList.remove('drawer-open');
|
||||
if (id) {
|
||||
var el = document.getElementById(id);
|
||||
if (el) el.classList.remove('open');
|
||||
}
|
||||
document.querySelectorAll('.drawer.open').forEach(function (d) { d.classList.remove('open'); });
|
||||
}
|
||||
|
||||
document.addEventListener('keydown', function (e) {
|
||||
if (e.key === 'Escape') closeDrawer();
|
||||
});
|
||||
|
||||
document.addEventListener('click', function (e) {
|
||||
var link = e.target.closest('a[href]');
|
||||
if (!link || link.target === '_blank' || link.hasAttribute('download')) return;
|
||||
var href = link.getAttribute('href') || '';
|
||||
if (!href || href.charAt(0) === '#') return;
|
||||
if (href.indexOf('6080') !== -1 || href.indexOf('7788') !== -1) return;
|
||||
if (href.charAt(0) === '/' || href.indexOf('http') === 0) clearEmbeddedIframes();
|
||||
}, true);
|
||||
|
||||
return { toast: toast, api: request, confirmDelete: confirmDelete, openDrawer: openDrawer, closeDrawer: closeDrawer, clearIframes: clearEmbeddedIframes };
|
||||
})();
|
||||
@@ -0,0 +1,346 @@
|
||||
/**
|
||||
* Hermes Neo Command Center
|
||||
*/
|
||||
function hermesControl() {
|
||||
const PA_SITES = ['Airbnb', 'Booking.com', 'DuckDuckGo', 'HolidayCheck'];
|
||||
|
||||
/** Canonical team — never duplicate role as name */
|
||||
const ROSTER = [
|
||||
{ chat_id: 8859782446, role: 'CEO', name: 'Aïssa' },
|
||||
{ chat_id: 789036463, role: 'CTO', name: 'Mo' },
|
||||
];
|
||||
|
||||
return {
|
||||
tab: 'feed',
|
||||
live: true,
|
||||
stats: { conversations: 0, messages: 0, edges: 0, embeddings: 0, inbound: 0, outbound: 0 },
|
||||
conversations: [],
|
||||
messages: [],
|
||||
users: [],
|
||||
agentEvents: [],
|
||||
selectedChatId: null,
|
||||
graphChatFilter: '',
|
||||
searchQuery: '',
|
||||
searchResults: [],
|
||||
searchRan: false,
|
||||
graphNetwork: null,
|
||||
pollTimer: null,
|
||||
paPollTimer: null,
|
||||
paPolling: false,
|
||||
paLive: { status: 'idle', query: '', slots: [] },
|
||||
paScreenshotTs: Date.now(),
|
||||
hermesOnline: false,
|
||||
hermesStatus: {},
|
||||
actionBusy: false,
|
||||
actionMsg: '',
|
||||
chartDirection: null,
|
||||
chartAgents: null,
|
||||
|
||||
get teamRoster() {
|
||||
const byId = {};
|
||||
(this.users || []).forEach(u => { byId[u.chat_id] = u; });
|
||||
(this.conversations || []).forEach(c => {
|
||||
if (!byId[c.chat_id]) byId[c.chat_id] = c;
|
||||
else {
|
||||
byId[c.chat_id].message_count = c.message_count || byId[c.chat_id].message_count;
|
||||
}
|
||||
});
|
||||
return ROSTER.map(r => ({
|
||||
...r,
|
||||
online: !!(byId[r.chat_id]?.online),
|
||||
pa_mode: !!(byId[r.chat_id]?.pa_mode),
|
||||
message_count: byId[r.chat_id]?.message_count || 0,
|
||||
}));
|
||||
},
|
||||
|
||||
get paLiveUser() {
|
||||
const cid = this.paLive.chat_id;
|
||||
if (!cid) return '';
|
||||
const m = ROSTER.find(r => r.chat_id === cid);
|
||||
return m ? `${m.role} — ${m.name}` : this.paLive.user_name || '';
|
||||
},
|
||||
|
||||
get paSlots() {
|
||||
const slots = this.paLive.slots || [];
|
||||
if (slots.length >= 4) return slots;
|
||||
const byLabel = {};
|
||||
slots.forEach(s => { byLabel[s.label] = s; });
|
||||
return PA_SITES.map(label => byLabel[label] || {
|
||||
label, status: 'idle', has_screenshot: false,
|
||||
});
|
||||
},
|
||||
|
||||
rosterPerson(chatId) {
|
||||
return ROSTER.find(r => r.chat_id === Number(chatId)) || null;
|
||||
},
|
||||
|
||||
msgLabel(msg) {
|
||||
const p = this.rosterPerson(msg.chat_id);
|
||||
if (p) return `${p.role} (${p.name})`;
|
||||
if (msg.user_role && msg.user_name) return `${msg.user_role} (${msg.user_name})`;
|
||||
return msg.user_role || msg.chat_id || '?';
|
||||
},
|
||||
|
||||
async init() {
|
||||
const hash = (window.location.hash || '').replace('#', '');
|
||||
if (['feed', 'pa', 'graph', 'search', 'control'].includes(hash)) this.tab = hash;
|
||||
await this.refreshStats();
|
||||
await this.refreshConversations();
|
||||
await this.refreshUsers();
|
||||
await this.refreshFeed();
|
||||
await this.refreshPaLive();
|
||||
setTimeout(() => this.initCharts(), 200);
|
||||
this.pollTimer = setInterval(() => {
|
||||
if (this.tab === 'feed' && this.live) this.refreshFeed(true);
|
||||
}, 5000);
|
||||
this.paPollTimer = setInterval(() => {
|
||||
if (this.tab === 'pa' || this.paLive.status === 'running') this.refreshPaLive(true);
|
||||
}, 2000);
|
||||
window.addEventListener('hashchange', () => {
|
||||
const h = (window.location.hash || '').replace('#', '');
|
||||
if (['feed', 'pa', 'graph', 'search', 'control'].includes(h)) this.tab = h;
|
||||
});
|
||||
},
|
||||
|
||||
initCharts() {
|
||||
if (typeof Chart === 'undefined') return;
|
||||
const neoColors = ['#00e5ff', '#ff2d95', '#b8ff3c', '#ff9f43', '#a855f7', '#ffd700'];
|
||||
Chart.defaults.color = '#64748b';
|
||||
Chart.defaults.borderColor = 'rgba(0,229,255,0.08)';
|
||||
|
||||
const dirEl = document.getElementById('hm-chart-direction');
|
||||
if (dirEl && !this.chartDirection) {
|
||||
this.chartDirection = new Chart(dirEl, {
|
||||
type: 'doughnut',
|
||||
data: {
|
||||
labels: ['Inbound', 'Outbound', 'Vectors'],
|
||||
datasets: [{
|
||||
data: [1, 1, 1],
|
||||
backgroundColor: ['#00e5ff', '#a855f7', '#b8ff3c'],
|
||||
borderWidth: 0,
|
||||
hoverOffset: 8,
|
||||
}],
|
||||
},
|
||||
options: {
|
||||
responsive: true,
|
||||
maintainAspectRatio: false,
|
||||
cutout: '62%',
|
||||
plugins: {
|
||||
legend: { position: 'right', labels: { boxWidth: 12, padding: 10, color: '#94a3b8' } },
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
const agEl = document.getElementById('hm-chart-agents');
|
||||
if (agEl && !this.chartAgents) {
|
||||
this.chartAgents = new Chart(agEl, {
|
||||
type: 'bar',
|
||||
data: {
|
||||
labels: ['herman', 'browser', 'marketing'],
|
||||
datasets: [{
|
||||
label: 'events',
|
||||
data: [0, 0, 0],
|
||||
backgroundColor: 'rgba(0, 229, 255, 0.55)',
|
||||
borderColor: '#00e5ff',
|
||||
borderWidth: 1,
|
||||
borderRadius: 4,
|
||||
}],
|
||||
},
|
||||
options: {
|
||||
responsive: true,
|
||||
maintainAspectRatio: false,
|
||||
scales: {
|
||||
y: { beginAtZero: true, grid: { color: 'rgba(255,255,255,0.04)' }, ticks: { stepSize: 1 } },
|
||||
x: { grid: { display: false } },
|
||||
},
|
||||
plugins: { legend: { display: false } },
|
||||
},
|
||||
});
|
||||
}
|
||||
this.updateCharts();
|
||||
},
|
||||
|
||||
updateCharts() {
|
||||
const s = this.stats;
|
||||
if (this.chartDirection) {
|
||||
this.chartDirection.data.datasets[0].data = [
|
||||
Math.max(s.inbound || 0, 0),
|
||||
Math.max(s.outbound || 0, 0),
|
||||
Math.max(s.embeddings || 0, 0),
|
||||
];
|
||||
this.chartDirection.update('none');
|
||||
}
|
||||
if (this.chartAgents) {
|
||||
const counts = {};
|
||||
(this.agentEvents || []).forEach(ev => {
|
||||
const n = (ev.agent_name || 'other').toLowerCase();
|
||||
counts[n] = (counts[n] || 0) + 1;
|
||||
});
|
||||
const labels = Object.keys(counts).slice(0, 8);
|
||||
if (!labels.length) labels.push('herman');
|
||||
this.chartAgents.data.labels = labels;
|
||||
this.chartAgents.data.datasets[0].data = labels.map(l => counts[l] || 0);
|
||||
this.chartAgents.update('none');
|
||||
}
|
||||
},
|
||||
|
||||
setTab(t) {
|
||||
this.tab = t;
|
||||
history.replaceState(null, '', t === 'feed' ? '/hermes' : '/hermes#' + t);
|
||||
if (t === 'graph') setTimeout(() => this.loadGraph(), 100);
|
||||
if (t === 'control') { this.refreshStats(); this.refreshUsers(); }
|
||||
if (t === 'pa') { this.paPolling = true; this.refreshPaLive(); }
|
||||
},
|
||||
|
||||
formatTime(iso) {
|
||||
if (!iso) return '';
|
||||
try {
|
||||
return new Date(iso).toLocaleString('nl-NL', { dateStyle: 'short', timeStyle: 'short' });
|
||||
} catch { return iso; }
|
||||
},
|
||||
|
||||
paStatusLabel() {
|
||||
const m = { idle: 'Idle', running: 'Zoekt…', comparing: 'Vergelijkt…', done: 'Klaar', failed: 'Mislukt' };
|
||||
return m[this.paLive.status] || this.paLive.status || 'Idle';
|
||||
},
|
||||
|
||||
slotStatusLabel(s) {
|
||||
const m = { idle: 'Idle', waiting: 'Wacht', loading: 'Bezig', completed: 'Klaar', failed: 'Fout' };
|
||||
return m[s] || s || 'Idle';
|
||||
},
|
||||
|
||||
slotScreenshotUrl(label) {
|
||||
if (!label) return '';
|
||||
return `/api/admin/hermes/pa/live/${encodeURIComponent(label)}/screenshot.jpg?t=${this.paScreenshotTs}`;
|
||||
},
|
||||
|
||||
async selectChat(chatId) {
|
||||
this.selectedChatId = chatId;
|
||||
await this.refreshFeed();
|
||||
},
|
||||
|
||||
async refreshStats() {
|
||||
try {
|
||||
const data = await Cockpit.api('/hermes/stats');
|
||||
this.stats = data.stats || this.stats;
|
||||
this.agentEvents = data.agent_events || [];
|
||||
this.updateCharts();
|
||||
} catch (e) { console.warn('stats', e); }
|
||||
},
|
||||
|
||||
async refreshUsers() {
|
||||
try {
|
||||
const data = await Cockpit.api('/hermes/users');
|
||||
this.users = data.users || [];
|
||||
} catch (e) { console.warn('users', e); }
|
||||
},
|
||||
|
||||
async refreshConversations() {
|
||||
try {
|
||||
const data = await Cockpit.api('/hermes/conversations');
|
||||
this.conversations = data.items || [];
|
||||
} catch (e) { console.warn('conversations', e); }
|
||||
},
|
||||
|
||||
async refreshFeed(quiet) {
|
||||
try {
|
||||
let path = '/hermes/feed?limit=80';
|
||||
if (this.selectedChatId) path += '&chat_id=' + this.selectedChatId;
|
||||
const data = await Cockpit.api(path);
|
||||
this.messages = data.items || [];
|
||||
if (!quiet) await this.refreshStats();
|
||||
} catch (e) { console.warn('feed', e); }
|
||||
},
|
||||
|
||||
async refreshPaLive(quiet) {
|
||||
try {
|
||||
const data = await Cockpit.api('/hermes/pa/live');
|
||||
this.paLive = data;
|
||||
this.paScreenshotTs = Date.now();
|
||||
if (data.hermes) {
|
||||
this.hermesOnline = data.hermes.online !== false;
|
||||
this.hermesStatus = data.hermes;
|
||||
}
|
||||
} catch (e) {
|
||||
if (!quiet) console.warn('pa live', e);
|
||||
}
|
||||
},
|
||||
|
||||
async loadGraph() {
|
||||
try {
|
||||
let data;
|
||||
if (this.graphChatFilter) {
|
||||
data = await Cockpit.api('/hermes/graph/' + this.graphChatFilter + '?limit=80');
|
||||
} else {
|
||||
data = await Cockpit.api('/hermes/graph?limit=100');
|
||||
}
|
||||
this.renderGraph(data);
|
||||
} catch (e) {
|
||||
Cockpit.toast('Graph laden mislukt: ' + e.message, 'error');
|
||||
}
|
||||
},
|
||||
|
||||
renderGraph(data) {
|
||||
const el = document.getElementById('hermes-graph');
|
||||
if (!el || typeof vis === 'undefined') return;
|
||||
const nodes = new vis.DataSet((data.nodes || []).map(n => ({
|
||||
id: n.id,
|
||||
label: this.truncate(n.label || n.id, 40),
|
||||
color: n.direction === 'in'
|
||||
? { background: '#164e63', border: '#00e5ff' }
|
||||
: { background: '#4c1d95', border: '#a855f7' },
|
||||
font: { color: '#e8edf5', size: 11 },
|
||||
})));
|
||||
const edges = new vis.DataSet((data.edges || []).map(e => ({
|
||||
id: 'e' + e.id, from: e.from, to: e.to,
|
||||
label: e.type || '', arrows: 'to',
|
||||
color: { color: '#ff9f43' },
|
||||
})).filter(e => e.to));
|
||||
if (this.graphNetwork) this.graphNetwork.destroy();
|
||||
this.graphNetwork = new vis.Network(el, { nodes, edges }, {
|
||||
physics: { stabilization: true },
|
||||
interaction: { hover: true },
|
||||
});
|
||||
},
|
||||
|
||||
truncate(s, n) {
|
||||
s = String(s || '');
|
||||
return s.length > n ? s.slice(0, n) + '…' : s;
|
||||
},
|
||||
|
||||
async runSearch() {
|
||||
if (!this.searchQuery || this.searchQuery.length < 2) {
|
||||
Cockpit.toast('Minimaal 2 tekens', 'warn');
|
||||
return;
|
||||
}
|
||||
this.searchRan = true;
|
||||
try {
|
||||
const data = await Cockpit.api('/hermes/search', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ query: this.searchQuery, chat_id: this.selectedChatId || null, limit: 15 }),
|
||||
});
|
||||
this.searchResults = data.results || [];
|
||||
} catch (e) {
|
||||
Cockpit.toast('Zoeken mislukt: ' + e.message, 'error');
|
||||
}
|
||||
},
|
||||
|
||||
async runAction(action) {
|
||||
this.actionBusy = true;
|
||||
this.actionMsg = '';
|
||||
try {
|
||||
const data = await Cockpit.api('/hermes/actions/' + action, { method: 'POST' });
|
||||
this.actionMsg = data.output || '✅ Actie uitgevoerd';
|
||||
Cockpit.toast(this.actionMsg.slice(0, 80), 'success');
|
||||
await this.refreshStats();
|
||||
} catch (e) {
|
||||
this.actionMsg = '❌ ' + e.message;
|
||||
Cockpit.toast(this.actionMsg, 'error');
|
||||
} finally {
|
||||
this.actionBusy = false;
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
window.CockpitLive = (function () {
|
||||
var ws = null;
|
||||
var reconnectTimer = null;
|
||||
|
||||
function startPolling(fn, intervalMs) {
|
||||
intervalMs = intervalMs || 30000;
|
||||
fn();
|
||||
var id = setInterval(fn, intervalMs);
|
||||
return function () { clearInterval(id); };
|
||||
}
|
||||
|
||||
function connectFeed(onMessage) {
|
||||
if (typeof WebSocket === 'undefined') return function () {};
|
||||
var proto = location.protocol === 'https:' ? 'wss:' : 'ws:';
|
||||
function connect() {
|
||||
try {
|
||||
ws = new WebSocket(proto + '//' + location.host + '/ws/feed');
|
||||
ws.onmessage = function (ev) {
|
||||
try {
|
||||
var data = JSON.parse(ev.data);
|
||||
if (onMessage) onMessage(data);
|
||||
} catch (e) {}
|
||||
};
|
||||
ws.onclose = function () {
|
||||
reconnectTimer = setTimeout(connect, 5000);
|
||||
};
|
||||
} catch (e) {
|
||||
reconnectTimer = setTimeout(connect, 5000);
|
||||
}
|
||||
}
|
||||
connect();
|
||||
return function () {
|
||||
if (reconnectTimer) clearTimeout(reconnectTimer);
|
||||
if (ws) { try { ws.close(); } catch (e) {} ws = null; }
|
||||
};
|
||||
}
|
||||
|
||||
function updateLiveBadge(el, at) {
|
||||
if (!el) return;
|
||||
el.textContent = 'Live · ' + (at || new Date().toLocaleTimeString('nl-NL', { hour: '2-digit', minute: '2-digit' }));
|
||||
}
|
||||
|
||||
function renderAgentFeed(container, events) {
|
||||
if (!container || !events) return;
|
||||
container.innerHTML = events.slice(0, 12).map(function (ev) {
|
||||
var t = (ev.created_at || '').substring(11, 16);
|
||||
return '<div class="hub-feed-item"><span>' + t + '</span>' +
|
||||
'<span class="badge badge-agent-' + String(ev.agent_name || '').toLowerCase() + '">' + (ev.agent_name || '') + '</span> ' +
|
||||
(ev.title || ev.event_type || '') + '</div>';
|
||||
}).join('') || '<p class="empty-state">Nog geen events.</p>';
|
||||
}
|
||||
|
||||
return { startPolling: startPolling, connectFeed: connectFeed, updateLiveBadge: updateLiveBadge, renderAgentFeed: renderAgentFeed };
|
||||
})();
|
||||
Reference in New Issue
Block a user