SysOps: deploy-all — 2026-06-09 10:41 UTC

This commit is contained in:
sysops
2026-06-09 10:41:13 +00:00
parent 69fe67cc0e
commit 21ea3a2c81
82 changed files with 8906 additions and 981 deletions
+109
View File
@@ -0,0 +1,109 @@
/** 3D-style agent poppetjes met headset — consistent team look */
window.AgentAvatars = (function () {
var CFG = {
herman: { hoodie: '#1e3a5f', hair: '#4a3728', skin: '#e8b896', style: 'exec', accent: '#ffd700' },
marketing: { hoodie: '#9d174d', hair: '#1f2937', skin: '#f5c9a8', style: 'bob', accent: '#ff6b9d' },
bizdev: { hoodie: '#0e4d6e', hair: '#2d1810', skin: '#ddb896', style: 'short', accent: '#00e5ff' },
finance: { hoodie: '#14532d', hair: '#3d2314', skin: '#e8b896', style: 'glasses', accent: '#22c55e' },
sourcing: { hoodie: '#9a3412', hair: '#1a1a1a', skin: '#c9a07a', style: 'short', accent: '#f97316' },
product: { hoodie: '#581c87', hair: '#4a3728', skin: '#f5c9a8', style: 'curl', accent: '#a855f7' },
halal: { hoodie: '#065f46', hair: '#1f2937', skin: '#d4a574', style: 'short', accent: '#34d399' },
design: { hoodie: '#831843', hair: '#111827', skin: '#f5c9a8', style: 'long', accent: '#ec4899' },
knowledge: { hoodie: '#312e81', hair: '#374151', skin: '#e8b896', style: 'glasses', accent: '#6366f1' },
retail: { hoodie: '#365314', hair: '#2d1810', skin: '#ddb896', style: 'short', accent: '#b8ff3c' },
browser: { hoodie: '#0c4a6e', hair: '#1f2937', skin: '#c9a07a', style: 'short', accent: '#38bdf8' },
hermes: { hoodie: '#1e40af', hair: '#3d2314', skin: '#e8b896', style: 'short', accent: '#2aabee' },
email: { hoodie: '#334155', hair: '#4a3728', skin: '#ddb896', style: 'short', accent: '#94a3b8' },
research: { hoodie: '#115e59', hair: '#1a1a1a', skin: '#f5c9a8', style: 'glasses', accent: '#14b8a6' },
sysops: { hoodie: '#1e3a5f', hair: '#4a3728', skin: '#e8b896', style: 'short', accent: '#38bdf8', hat: 'cap' },
packaging: { hoodie: '#7c2d12', hair: '#2d1810', skin: '#c9a07a', style: 'short', accent: '#fb923c' },
};
function cfg(key, fallbackColor) {
var k = (key || 'agent').toLowerCase();
var c = CFG[k] || { hoodie: fallbackColor || '#1e3a5f', hair: '#3d2314', skin: '#e8b896', style: 'short', accent: '#38bdf8' };
return c;
}
function capSvg(hid, c) {
return (
'<path d="M22,44 Q50,30 78,44 L82,48 Q50,54 18,48Z" fill="#0f172a" opacity="0.35"/>' +
'<ellipse cx="50" cy="36" rx="26" ry="12" fill="' + c.hoodie + '"/>' +
'<path d="M24,40 Q50,26 76,40 L88,46 Q50,52 14,46Z" fill="#1e40af"/>' +
'<path d="M26,38 Q50,28 74,38" fill="none" stroke="#38bdf8" stroke-width="1.2" opacity="0.5"/>' +
'<rect x="46" y="28" width="8" height="5" rx="1" fill="#38bdf8" opacity="0.85"/>'
);
}
function hairPath(style) {
if (style === 'long') return 'M28,38 Q20,18 40,14 Q60,10 72,22 Q78,32 74,48 Q70,56 62,52 Q58,38 50,36 Q42,36 38,48 Q32,52 28,38Z';
if (style === 'bob') return 'M26,40 Q24,22 42,16 Q62,14 74,28 Q76,42 70,50 Q50,54 30,48 Q24,44 26,40Z';
if (style === 'curl') return 'M28,42 Q22,24 38,16 Q52,12 68,20 Q76,30 72,44 Q66,52 54,48 Q44,52 34,46 Q26,44 28,42Z';
return 'M30,40 Q28,24 44,18 Q58,16 70,26 Q74,36 70,44 Q54,48 38,44 Q30,42 30,40Z';
}
function svgAvatar(key, color) {
var c = cfg(key, color);
var hid = 'av-' + key;
return (
'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 120" class="agent-char-svg" aria-hidden="true">' +
'<defs>' +
'<linearGradient id="' + hid + '-bg" x1="0%" y1="0%" x2="100%" y2="100%">' +
'<stop offset="0%" stop-color="#0c1929"/><stop offset="50%" stop-color="#152238"/><stop offset="100%" stop-color="#0a1020"/>' +
'</linearGradient>' +
'<linearGradient id="' + hid + '-hood" x1="30%" y1="0%" x2="70%" y2="100%">' +
'<stop offset="0%" stop-color="' + c.hoodie + '"/><stop offset="100%" stop-color="#0a0f18"/>' +
'</linearGradient>' +
'<linearGradient id="' + hid + '-skin" x1="40%" y1="0%" x2="60%" y2="100%">' +
'<stop offset="0%" stop-color="' + c.skin + '"/><stop offset="100%" stop-color="#c9956e"/>' +
'</linearGradient>' +
'<radialGradient id="' + hid + '-glow" cx="75%" cy="25%" r="45%">' +
'<stop offset="0%" stop-color="' + c.accent + '" stop-opacity="0.35"/><stop offset="100%" stop-opacity="0"/>' +
'</radialGradient>' +
'<filter id="' + hid + '-sh"><feDropShadow dx="0" dy="2" stdDeviation="2" flood-opacity="0.45"/></filter>' +
'</defs>' +
'<rect width="100" height="120" fill="url(#' + hid + '-bg)"/>' +
'<ellipse cx="78" cy="28" rx="35" ry="30" fill="url(#' + hid + '-glow)"/>' +
'<ellipse cx="50" cy="100" rx="30" ry="14" fill="rgba(0,0,0,0.4)"/>' +
'<path d="M18,118 Q18,74 50,68 Q82,74 82,118Z" fill="url(#' + hid + '-hood)" filter="url(#' + hid + '-sh)"/>' +
'<path d="M20,70 Q50,58 80,70 L76,82 Q50,76 24,82Z" fill="' + c.hoodie + '" opacity="0.9"/>' +
'<path d="M28,68 Q50,48 72,68 L68,78 Q50,72 32,78Z" fill="' + c.hoodie + '"/>' +
'<ellipse cx="50" cy="54" rx="23" ry="25" fill="url(#' + hid + '-skin)" filter="url(#' + hid + '-sh)"/>' +
'<ellipse cx="56" cy="56" rx="10" ry="14" fill="rgba(0,0,0,0.08)"/>' +
(c.hat === 'cap' ? '' : '<path d="' + hairPath(c.style) + '" fill="' + c.hair + '"/>') +
(c.style === 'glasses'
? '<ellipse cx="42" cy="52" rx="8" ry="6" fill="none" stroke="#334155" stroke-width="1.5"/>' +
'<ellipse cx="58" cy="52" rx="8" ry="6" fill="none" stroke="#334155" stroke-width="1.5"/>' +
'<line x1="50" y1="52" x2="50" y2="52" stroke="#334155" stroke-width="1.5"/>'
: '') +
'<ellipse cx="42" cy="52" rx="3" ry="3.5" fill="#1e293b"/><ellipse cx="58" cy="52" rx="3" ry="3.5" fill="#1e293b"/>' +
'<ellipse cx="43" cy="51" rx="1" ry="1.2" fill="#fff" opacity="0.7"/><ellipse cx="59" cy="51" rx="1" ry="1.2" fill="#fff" opacity="0.7"/>' +
'<path d="M44,62 Q50,66 56,62" fill="none" stroke="#b45309" stroke-width="1.5" stroke-linecap="round"/>' +
'<path d="M16,50 Q50,26 84,50" fill="none" stroke="#cbd5e1" stroke-width="4" stroke-linecap="round"/>' +
'<rect x="10" y="44" width="14" height="18" rx="5" fill="#1e293b" stroke="#94a3b8" stroke-width="1.8"/>' +
'<rect x="12" y="47" width="10" height="12" rx="3" fill="#334155"/>' +
'<rect x="76" y="44" width="14" height="18" rx="5" fill="#1e293b" stroke="#94a3b8" stroke-width="1.8"/>' +
'<rect x="78" y="47" width="10" height="12" rx="3" fill="#334155"/>' +
'<path d="M78,60 Q86,72 82,82" fill="none" stroke="#94a3b8" stroke-width="2.8" stroke-linecap="round"/>' +
'<circle cx="82" cy="84" r="3.5" fill="#64748b" stroke="#94a3b8" stroke-width="1"/>' +
'<circle cx="88" cy="32" r="2.5" fill="' + c.accent + '" opacity="0.9"/>' +
'<circle cx="12" cy="40" r="1.5" fill="' + c.accent + '" opacity="0.5"/>' +
(c.hat === 'cap' ? capSvg(hid, c) : '') +
'</svg>'
);
}
function paint(el, key, color) {
if (!el) return;
el.innerHTML = svgAvatar((key || '').toLowerCase(), color);
}
function paintAll(root) {
root = root || document;
root.querySelectorAll('[data-agent-avatar]').forEach(function (el) {
paint(el, el.getAttribute('data-agent-avatar'), el.getAttribute('data-agent-color'));
});
}
return { paint: paint, paintAll: paintAll, svgAvatar: svgAvatar };
})();
+72 -35
View File
@@ -11,12 +11,9 @@
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}`;
function linePath(x1, y1, x2, y2) {
const midY = y1 + (y2 - y1) * 0.45;
return `M ${x1} ${y1} C ${x1} ${midY}, ${x2} ${midY}, ${x2} ${y2}`;
}
async function loadMeshData() {
@@ -28,63 +25,103 @@
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 width = vb && vb.width ? vb.width : 1100;
const height = vb && vb.height ? vb.height : 640;
const cx = width / 2;
const hermanY = 280;
const execY = 75;
const agentY = 520;
const souls = (data.nodes || []).filter((n) => {
const key = (n.agent_key || '').toLowerCase();
return key && key !== 'herman';
});
const souls = (data.nodes || []).filter((n) => (n.agent_key || '').toLowerCase() !== 'herman');
const edgesBySource = {};
(data.edges || []).forEach((e) => { edgesBySource[e.source] = e; });
const agentCount = Math.max(1, souls.length);
const pad = 70;
const span = width - pad * 2;
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;
node._x = pad + (span * i) / Math.max(1, agentCount - 1 || 1);
if (agentCount === 1) node._x = cx;
node._y = agentY;
});
const ceo = { x: cx - 180, y: execY, label: 'CEO', sub: 'Aissa · beslissingen' };
const cto = { x: cx + 180, y: execY, label: 'CTO', sub: 'Platform · techniek' };
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);
function addEdge(x1, y1, x2, y2, pulse) {
const d = linePath(x1, y1, x2, y2);
edgesLayer.appendChild(make('path', { d, class: 'mesh-edge' }));
if (pulse) {
const p = make('path', { d, class: 'mesh-pulse' });
p.style.animationDuration = pulse + 's';
edgesLayer.appendChild(p);
}
}
souls.forEach((node) => {
const weight = edgesBySource[node.agent_key]?.weight || 1;
addEdge(node._x, node._y - 26, cx, hermanY + 48, Math.max(1.2, 3.2 - Math.min(2, weight / 10)));
});
addEdge(cx, hermanY - 48, ceo.x, ceo.y + 28, 2.2);
addEdge(cx, hermanY - 48, cto.x, cto.y + 28, 2.4);
function drawExec(node, cls) {
const g = make('g', { class: `mesh-node mesh-exec ${cls}` });
g.appendChild(make('circle', { cx: node.x, cy: node.y, r: 34, class: 'main' }));
g.appendChild(make('circle', { cx: node.x, cy: node.y, r: 42, class: 'ring' }));
g.appendChild(make('text', { x: node.x, y: node.y - 2, 'font-size': 13 }));
g.lastChild.textContent = node.label;
const sub = make('text', { x: node.x, y: node.y + 14, 'font-size': 9, opacity: 0.85 });
sub.textContent = node.sub;
g.appendChild(sub);
nodesLayer.appendChild(g);
}
drawExec(ceo, 'mesh-ceo');
drawExec(cto, 'mesh-cto');
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' });
herman.appendChild(make('circle', { class: 'ring', cx, cy: hermanY, r: 58 }));
herman.appendChild(make('circle', { class: 'main', cx, cy: hermanY, r: 44 }));
const crown = make('text', { x: cx, y: hermanY - 4, 'font-size': 22, '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);
const hLabel = make('text', { x: cx, y: hermanY + 18 });
hLabel.textContent = 'Herman · Co-CEO';
herman.appendChild(hLabel);
const hSub = make('text', { x: cx, y: hermanY + 34, 'font-size': 10, opacity: 0.85 });
hSub.textContent = 'Takenverdeler';
herman.appendChild(hSub);
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 key = (node.agent_key || '').toLowerCase();
const group = make('g', { class: `mesh-node mesh-agent ${node.health || 'idle'}` });
group.appendChild(make('circle', { cx: node._x, cy: node._y, r: 22 }));
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;
const role = make('text', { x: node._x, y: node._y + 38, 'font-size': 9, opacity: 0.82 });
role.textContent = (node.role_title || key).split('·')[0].trim().slice(0, 18);
group.appendChild(role);
const status = make('text', { x: node._x, y: node._y + 52, 'font-size': 8, class: 'mesh-status' });
status.textContent = (node.health || 'idle').toUpperCase();
group.appendChild(status);
group.addEventListener('click', () => {
if (window.Cockpit && Cockpit.toast) {
Cockpit.toast(`${node.display_name || node.agent_key}: ${node.health || 'idle'}`, 'success');
Cockpit.toast(`${node.display_name || key}: ${node.health || 'idle'}`, 'info');
}
});
nodesLayer.appendChild(group);
+31 -13
View File
@@ -100,40 +100,58 @@ window.AnalyticsCharts = (function () {
}
}
function render(data) {
function render(data, mode) {
if (!data) return;
mode = mode || window.__vizMode || 'neo-bars';
window.__analyticsLastData = data;
renderKpis(document.getElementById('analytics-kpis'), data.kpis);
barChart('chart-deals', (data.deals_by_stage || []).map(function (r) { return r.stage; }),
var useRing = mode === 'neo-rings';
var bar = function (id, labels, values, label, horizontal) {
if (useRing) doughnut(id, labels, values);
else barChart(id, labels, values, label, horizontal);
};
bar('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; }),
bar('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; }),
bar('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); }));
if (useRing) {
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); }));
} else barChart('chart-provinces', (data.supermarkets_by_province || []).map(function (r) { return r.province; }),
(data.supermarkets_by_province || []).map(function (r) { return Number(r.cnt || 0); }), 'Filialen');
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; }),
bar('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); }));
if (mode === 'neo-table') {
lineChart('chart-timeline', [], []);
} else {
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; }),
bar('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; }),
bar('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 || ''); }),
bar('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 || '?'; }),
bar('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);
}
document.addEventListener('foodlinkk:vizmode', function (ev) {
if (window.__analyticsLastData) render(window.__analyticsLastData, ev.detail.mode);
});
return { render: render, destroyAll: destroyAll };
})();
+47 -17
View File
@@ -242,7 +242,7 @@ window.BriefingCharts = (function () {
{ 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: 'Food trends', sub: 'RSS live', icon: '📰', color: '#38bdf8', pct: Math.min(95, ((stats.trending_food || stats.food_market_highlights || []).length * 10)) + '%', val: (stats.trending_food || stats.food_market_highlights || []).length || 0, link: '/marketing' },
{ label: 'Goedkeuringen', sub: 'wacht op OK', icon: '✓', color: '#ffd700', pct: '30%', val: stats.pending_approvals || 0 },
];
container.className = 'hm-neo-kpi-row';
@@ -257,11 +257,16 @@ window.BriefingCharts = (function () {
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>';
var items = (stats.trending_food || stats.food_market_highlights || []).slice(0, 6);
if (!items.length) {
container.innerHTML = '<p class="empty-state">Geen trending — <a href="/marketing">RSS ophalen in Marketing Hub</a></p>';
return;
}
container.innerHTML = items.map(function (r) {
var when = (r.published_at || '').substring(0, 10);
return '<a href="' + (r.link || '#') + '" target="_blank" rel="noopener" class="retail-highlight">' +
'<span><strong>' + (r.title || '') + '</strong><br><small>' + (r.feed_name || 'Retail') + (when ? ' · ' + when : '') + '</small></span>' +
'<span class="ticker-item">' + ((r.category || 'food').toUpperCase()) + '</span></a>';
}).join('');
}
@@ -289,16 +294,17 @@ window.BriefingCharts = (function () {
{ 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 trending = (stats.trending_food || stats.food_market_highlights || []).slice(0, 5);
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>';
if (trending.length) {
html += '<h4 style="margin:1rem 0 0.5rem;font-size:0.8rem;color:#94a3b8"><span class="hm-live-dot" style="display:inline-block;margin-right:0.35rem"></span>Trending food retail</h4><ul class="hm-exec-list hm-trend-list">';
trending.forEach(function (r) {
html += '<li><a href="' + (r.link || '#') + '" target="_blank" rel="noopener">' + (r.title || '') + '</a>' +
' <small>· ' + (r.feed_name || 'RSS') + '</small></li>';
});
html += '</ul>';
}
@@ -309,7 +315,19 @@ window.BriefingCharts = (function () {
});
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>';
var pending = stats.pending_approval_requests || [];
if (pending.length) {
html += '<h4 style="margin:1rem 0 0.5rem;font-size:0.8rem;color:#f59e0b">⏳ Open goedkeuringen</h4><ul class="hm-exec-list">';
pending.forEach(function (p) {
html += '<li><strong>@' + (p.agent_key || '') + '</strong> · ' + (p.title || '') + '</li>';
});
html += '</ul>';
}
html += '<p class="hm-exec-footer" style="margin-top:1rem;font-size:0.8rem;color:#64748b">' +
'<a href="http://10.4.7.18:3001/aissa/foodlinkk-command-center" target="_blank" rel="noopener">Gitea</a> · ' +
'<a href="/ops">IT Ops</a> · <a href="/packaging">Packaging</a> · ' +
'<a href="/marketing?tab=publish">Automatisering</a> · ' +
'<a href="/marketing">Marketing Hub</a> · <a href="/analytics">Analytics</a></p>';
container.innerHTML = html;
}
@@ -325,21 +343,33 @@ window.BriefingCharts = (function () {
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) {
function renderLive(root, stats, vizMode) {
if (!root || !stats) return;
var mode = vizMode || window._dashboardVizMode || 'neo-bars';
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);
var actEl = document.getElementById('briefing-activity-log');
if (actEl) {
var log = stats.activity_log || [];
actEl.innerHTML = log.length ? log.slice(0, 12).map(function (e) { return '<li>' + e + '</li>'; }).join('')
: '<li class="muted">Nog geen agent-acties vandaag.</li>';
}
renderPipeline(document.getElementById('chart-pipeline'), stats);
renderSentiment(document.getElementById('chart-sentiment'), stats);
renderWords(document.getElementById('chart-words'), stats);
renderAgents(document.getElementById('chart-agents'), stats);
if (window.VizEngine) {
VizEngine.renderSentiment(mode, document.getElementById('chart-sentiment'), document.getElementById('viz-sentiment-alt'), stats);
VizEngine.renderAgents(mode, document.getElementById('chart-agents'), document.getElementById('viz-agents-alt'), stats);
} else {
renderSentiment(document.getElementById('chart-sentiment'), stats);
renderAgents(document.getElementById('chart-agents'), stats);
}
}
function render(root, stats, content, createdAt) {
renderLive(root, stats);
function render(root, stats, content, createdAt, vizMode) {
renderLive(root, stats, vizMode);
renderText(root, content, createdAt);
}
+3 -1
View File
@@ -40,7 +40,9 @@ window.Cockpit = (function () {
}
function confirmDelete(message) {
return window.confirm(message || 'Delete this item?');
var msg = message;
if (!msg && window.I18n) msg = window.I18n.t('common.confirm_delete');
return window.confirm(msg || 'Delete this item?');
}
function openDrawer(id) {
+97
View File
@@ -0,0 +1,97 @@
(function (global) {
var WIDGET_META = {
kpis: { title: 'CEO KPI\'s', icon: '📊' },
executive: { title: 'Alles op een rij', icon: '📋' },
briefing: { title: 'Herman briefing', icon: '📝' },
retail: { title: 'Retail operatie', icon: '🏪' },
analytics: { title: 'Data & analytics', icon: '📈' },
approvals: { title: 'Agent goedkeuringen', icon: '✓' },
feed: { title: 'Agent feed', icon: '⚡' },
};
function loadPrefs() {
return fetch('/api/preferences/ui').then(function (r) { return r.json(); }).catch(function () {
return { dashboard_layout: Object.keys(WIDGET_META), global_viz_mode: 'neo-bars', viz_modes: {} };
});
}
function saveLayout(order) {
return fetch('/api/preferences/ui', {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ dashboard_layout: order }),
});
}
function saveViz(globalMode, vizModes) {
return fetch('/api/preferences/ui', {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ global_viz_mode: globalMode, viz_modes: vizModes || {} }),
});
}
function applyOrder(container, order) {
if (!container) return;
var map = {};
Array.from(container.children).forEach(function (el) {
if (el.dataset && el.dataset.widget) map[el.dataset.widget] = el;
});
order.forEach(function (id) {
if (map[id]) container.appendChild(map[id]);
});
}
function initDrag(container, onReorder) {
if (!container) return;
var dragEl = null;
Array.from(container.querySelectorAll('[data-widget]')).forEach(function (el) {
el.setAttribute('draggable', 'true');
el.classList.add('hm-widget-draggable');
el.addEventListener('dragstart', function (ev) {
dragEl = el;
el.classList.add('hm-widget-dragging');
ev.dataTransfer.effectAllowed = 'move';
});
el.addEventListener('dragend', function () {
el.classList.remove('hm-widget-dragging');
dragEl = null;
var order = Array.from(container.querySelectorAll('[data-widget]')).map(function (n) { return n.dataset.widget; });
if (onReorder) onReorder(order);
});
el.addEventListener('dragover', function (ev) {
ev.preventDefault();
if (!dragEl || dragEl === el) return;
var rect = el.getBoundingClientRect();
var after = ev.clientY > rect.top + rect.height / 2;
if (after) el.after(dragEl); else el.before(dragEl);
});
});
}
function buildVizSelector(container, prefs, onChange) {
if (!container || !global.VizEngine) return;
container.innerHTML = '<label class="viz-global-label">Visualisatie:</label>' +
global.VizEngine.MODES.map(function (m) {
var active = prefs.global_viz_mode === m.id ? ' active' : '';
return '<button type="button" class="viz-mode-btn' + active + '" data-viz="' + m.id + '">' + m.label + '</button>';
}).join('');
container.querySelectorAll('.viz-mode-btn').forEach(function (btn) {
btn.addEventListener('click', function () {
container.querySelectorAll('.viz-mode-btn').forEach(function (b) { b.classList.remove('active'); });
btn.classList.add('active');
if (onChange) onChange(btn.dataset.viz);
});
});
}
global.DashboardLayout = {
WIDGET_META: WIDGET_META,
loadPrefs: loadPrefs,
saveLayout: saveLayout,
saveViz: saveViz,
applyOrder: applyOrder,
initDrag: initDrag,
buildVizSelector: buildVizSelector,
};
})(window);
+57
View File
@@ -0,0 +1,57 @@
(function (global) {
var mode = 'neo-bars';
function getMode() {
return mode;
}
function setMode(m, persist) {
mode = m;
global.__vizMode = m;
document.querySelectorAll('#global-viz-toolbar .global-viz-btn').forEach(function (btn) {
btn.classList.toggle('active', btn.dataset.viz === m);
});
document.dispatchEvent(new CustomEvent('foodlinkk:vizmode', { detail: { mode: m } }));
if (persist !== false) {
fetch('/api/preferences/ui', {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ global_viz_mode: m }),
}).catch(function () {});
}
}
function buildToolbar(container) {
if (!container || !global.VizEngine) return;
container.innerHTML = global.VizEngine.MODES.map(function (m) {
var short = m.label.replace('Neo ', '');
var active = mode === m.id ? ' active' : '';
return '<button type="button" class="global-viz-btn' + active + '" data-viz="' + m.id + '" title="' + m.label + '">' + short + '</button>';
}).join('');
container.querySelectorAll('.global-viz-btn').forEach(function (btn) {
btn.addEventListener('click', function () { setMode(btn.dataset.viz); });
});
}
function init() {
if (global.location && global.location.pathname === '/') return;
fetch('/api/preferences/ui')
.then(function (r) { return r.json(); })
.then(function (prefs) {
mode = prefs.global_viz_mode || 'neo-bars';
global.__vizMode = mode;
buildToolbar(document.getElementById('global-viz-toolbar'));
document.dispatchEvent(new CustomEvent('foodlinkk:vizmode', { detail: { mode: mode } }));
})
.catch(function () {
buildToolbar(document.getElementById('global-viz-toolbar'));
});
}
global.GlobalViz = { getMode: getMode, setMode: setMode, init: init };
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', init);
} else {
init();
}
})(window);
+80
View File
@@ -0,0 +1,80 @@
/** Foodlinkk i18n — edit /static/i18n/nl.json and en.json to translate. */
window.I18n = (function () {
var locale = 'nl';
var strings = {};
function t(key, fallback) {
if (!key) return fallback || '';
var parts = String(key).split('.');
var o = strings;
for (var i = 0; i < parts.length; i++) {
if (o == null || typeof o !== 'object') return fallback != null ? fallback : key;
o = o[parts[i]];
}
return typeof o === 'string' ? o : (fallback != null ? fallback : key);
}
function applyDom() {
document.querySelectorAll('[data-i18n]').forEach(function (el) {
var k = el.getAttribute('data-i18n');
if (k) el.textContent = t(k);
});
document.querySelectorAll('[data-i18n-placeholder]').forEach(function (el) {
var k = el.getAttribute('data-i18n-placeholder');
if (k) el.placeholder = t(k);
});
document.querySelectorAll('[data-i18n-title]').forEach(function (el) {
var k = el.getAttribute('data-i18n-title');
if (k) el.title = t(k);
});
document.documentElement.lang = locale;
}
async function loadBundle(loc) {
var r = await fetch('/static/i18n/' + loc + '.json?v=2');
if (!r.ok) throw new Error('Locale ' + loc + ' not found');
strings = await r.json();
}
async function setLocale(loc, persist) {
if (persist == null) persist = true;
locale = loc === 'en' ? 'en' : 'nl';
try {
await loadBundle(locale);
} catch (e) {
if (locale !== 'nl') {
locale = 'nl';
await loadBundle('nl');
}
}
localStorage.setItem('foodlinkk_locale', locale);
applyDom();
window.dispatchEvent(new CustomEvent('foodlinkk:locale', { detail: { locale: locale } }));
if (persist) {
fetch('/api/preferences/ui', {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ locale: locale }),
}).catch(function () {});
}
return locale;
}
async function init() {
var loc = localStorage.getItem('foodlinkk_locale') || 'nl';
try {
var prefs = await fetch('/api/preferences/ui').then(function (r) { return r.json(); });
if (prefs.locale) loc = prefs.locale;
} catch (e) { /* ignore */ }
await setLocale(loc, false);
}
return { t: t, init: init, setLocale: setLocale, locale: function () { return locale; }, applyDom: applyDom };
})();
document.addEventListener('alpine:init', function () {
if (!window.Alpine) return;
Alpine.magic('t', function () {
return function (key, fallback) { return window.I18n.t(key, fallback); };
});
});
+222
View File
@@ -0,0 +1,222 @@
(function () {
const NS = 'http://www.w3.org/2000/svg';
function el(tag, attrs, text) {
const node = document.createElementNS(NS, tag);
Object.entries(attrs || {}).forEach(([k, v]) => node.setAttribute(k, String(v)));
if (text != null) node.textContent = text;
return node;
}
function clear(root) {
while (root.firstChild) root.removeChild(root.firstChild);
}
function statusClass(status) {
const s = (status || 'unknown').toLowerCase();
if (['online', 'running', 'up'].includes(s)) return 'online';
if (['offline', 'down', 'stopped'].includes(s)) return 'offline';
return 'degraded';
}
function flattenTree(nodes, parentId) {
const out = [];
(nodes || []).forEach((n) => {
out.push({ ...n, parentId: parentId || null });
out.push(...flattenTree(n.children || [], n.id));
});
return out;
}
function layoutNodes(flat, width) {
const byType = { hardware: [], proxmox: [], vm: [], service: [] };
flat.forEach((n) => {
const t = n.type || 'service';
(byType[t] || byType.service).push(n);
});
const positions = {};
positions['hardware-r340'] = { x: width / 2, y: 70 };
positions['proxmox-host'] = { x: width / 2, y: 190 };
const vm = byType.vm[0];
if (vm) positions[vm.id] = { x: width / 2, y: 310 };
const services = byType.service;
const count = Math.max(services.length, 1);
const pad = 70;
const span = width - pad * 2;
services.forEach((s, i) => {
positions[s.id] = {
x: pad + (span * (i + 0.5)) / count,
y: 430,
};
});
flat.forEach((n, i) => {
if (!positions[n.id]) {
positions[n.id] = { x: 100 + (i % 6) * (width / 7), y: 430 };
}
});
positions['mon-sysops'] = { x: width * 0.32, y: 570 };
positions['mon-research'] = { x: width * 0.68, y: 570 };
return positions;
}
function drawLayerBands(svg, layers, width) {
const g = el('g', { class: 'ops-layers' });
(layers || []).forEach((layer) => {
g.appendChild(el('line', {
x1: 36, y1: layer.y - 28, x2: width - 36, y2: layer.y - 28,
class: 'ops-layer-line',
}));
g.appendChild(el('text', {
x: 14, y: layer.y - 33, class: 'ops-layer-label',
}, layer.label));
});
svg.appendChild(g);
}
function drawEdges(svg, flat, positions) {
const g = el('g', { class: 'ops-edges' });
flat.forEach((n) => {
if (!n.parentId) return;
const from = positions[n.parentId];
const to = positions[n.id];
if (!from || !to) return;
const yOffFrom = n.parentId === 'hardware-r340' ? 38 : 32;
const yOffTo = n.type === 'hardware' ? -38 : n.type === 'service' ? -22 : -30;
g.appendChild(el('line', {
x1: from.x, y1: from.y + yOffFrom, x2: to.x, y2: to.y + yOffTo,
class: 'topology-line',
}));
g.appendChild(el('line', {
x1: from.x, y1: from.y + yOffFrom, x2: to.x, y2: to.y + yOffTo,
class: 'pulse-line',
}));
});
svg.appendChild(g);
}
function drawHardwareNode(svg, n, pos) {
const cls = statusClass(n.status);
const g = el('g', {
class: `ops-node-group node-hardware status-${cls}`,
transform: `translate(${pos.x},${pos.y})`,
});
g.appendChild(el('rect', { x: -95, y: -36, width: 190, height: 72, rx: 8, class: 'ops-hardware-box' }));
g.appendChild(el('rect', { x: -88, y: -28, width: 12, height: 56, rx: 2, class: 'ops-hardware-slot' }));
g.appendChild(el('rect', { x: -70, y: -28, width: 12, height: 56, rx: 2, class: 'ops-hardware-slot' }));
g.appendChild(el('text', { x: -48, y: -6, class: 'ops-node-title ops-title-left' }, 'Dell PowerEdge'));
g.appendChild(el('text', { x: -48, y: 14, class: 'ops-node-sub ops-title-left' }, 'R340 · Bare metal'));
g.appendChild(el('text', { x: -48, y: 32, class: 'ops-node-role ops-title-left' }, cls.toUpperCase()));
svg.appendChild(g);
}
function drawNode(svg, n, pos) {
if (n.type === 'hardware') {
drawHardwareNode(svg, n, pos);
return;
}
const cls = statusClass(n.status);
const g = el('g', {
class: `ops-node-group node-${n.type || 'service'} status-${cls}`,
transform: `translate(${pos.x},${pos.y})`,
});
const r = n.type === 'proxmox' ? 38 : n.type === 'vm' ? 32 : 24;
g.appendChild(el('circle', { r: r, class: 'ops-node-circle' }));
const title = (n.label || n.id).split('·')[0].trim();
g.appendChild(el('text', { y: -6, class: 'ops-node-title' }, title.length > 18 ? title.slice(0, 16) + '…' : title));
if (n.type === 'vm' && n.vmid) {
g.appendChild(el('text', { y: 10, class: 'ops-node-sub' }, 'ID ' + n.vmid + ' · ' + cls.toUpperCase()));
} else {
g.appendChild(el('text', { y: 10, class: 'ops-node-sub' }, cls.toUpperCase()));
}
if (n.role) {
const role = n.role.length > 28 ? n.role.slice(0, 26) + '…' : n.role;
g.appendChild(el('text', { y: 24, class: 'ops-node-role' }, role));
}
if (n.url && n.type === 'service') {
const link = el('a', { href: n.url, target: '_blank', rel: 'noopener' });
link.appendChild(g);
svg.appendChild(link);
} else {
svg.appendChild(g);
}
}
function drawMonitorAgents(svg, agents, positions, stats) {
(agents || []).forEach((a) => {
const pos = positions[a.id] || { x: 200, y: 570 };
const stat = (stats || {})[a.agent_key] || {};
const health = stat.health || 'idle';
const g = el('g', {
class: `ops-node-group ops-monitor status-${health}`,
transform: `translate(${pos.x},${pos.y})`,
});
g.appendChild(el('rect', { x: -72, y: -30, width: 144, height: 60, rx: 10, class: 'ops-monitor-box' }));
g.appendChild(el('text', { y: -6, class: 'ops-node-title' }, a.label));
g.appendChild(el('text', { y: 10, class: 'ops-node-sub' }, health.toUpperCase()));
g.appendChild(el('text', { y: 24, class: 'ops-node-role' }, a.role || ''));
svg.appendChild(g);
});
}
async function loadAgentHealth() {
try {
const r = await fetch('/api/agents/mesh');
if (!r.ok) return {};
const data = await r.json();
const map = {};
(data.nodes || []).forEach((n) => { map[n.agent_key] = { health: n.health, events_6h: n.events_6h }; });
return map;
} catch (e) {
return {};
}
}
async function render(canvasId, metaEl) {
const svg = document.getElementById(canvasId);
if (!svg) return;
clear(svg);
const width = 1200;
const height = 620;
svg.setAttribute('viewBox', `0 0 ${width} ${height}`);
try {
const [topoRes, agentStats] = await Promise.all([
fetch('/api/ops/topology').then((r) => r.json()),
loadAgentHealth(),
]);
const flat = flattenTree(topoRes.nodes || []);
const positions = layoutNodes(flat, width);
(topoRes.layer_agents || []).forEach((a) => {
if (!positions[a.id]) positions[a.id] = { x: width / 2, y: 570 };
});
drawLayerBands(svg, topoRes.layers, width);
drawEdges(svg, flat, positions);
flat.forEach((n) => {
const pos = positions[n.id];
if (pos) drawNode(svg, n, pos);
});
drawMonitorAgents(svg, topoRes.layer_agents, positions, agentStats);
if (metaEl) {
const online = (topoRes.meta && topoRes.meta.services_online) || 0;
metaEl.textContent =
'Update: ' + (topoRes.generated_at || '—').substring(0, 19).replace('T', ' ') +
' · ' + online + ' services online';
}
} catch (e) {
svg.appendChild(el('text', { x: 40, y: 60, fill: '#ef4444', 'font-size': 14 }, 'Topology laden mislukt: ' + e.message));
}
}
window.OpsTopology = { render };
})();
+27
View File
@@ -0,0 +1,27 @@
(function (global) {
function init(pageKey, renderFn) {
if (!global.DashboardLayout || typeof renderFn !== 'function') return Promise.resolve();
return global.DashboardLayout.loadPrefs().then(function (prefs) {
var mode = (prefs.viz_modes || {})[pageKey] || prefs.global_viz_mode || 'neo-bars';
var toolbar = document.getElementById('viz-toolbar');
if (toolbar) {
global.DashboardLayout.buildVizSelector(
toolbar,
Object.assign({}, prefs, { global_viz_mode: mode }),
function (m) {
var vizModes = Object.assign({}, prefs.viz_modes || {}, {});
vizModes[pageKey] = m;
global.DashboardLayout.saveViz(prefs.global_viz_mode, vizModes);
renderFn(m);
}
);
}
renderFn(mode);
document.addEventListener('foodlinkk:vizmode', function (ev) {
renderFn(ev.detail.mode);
});
});
}
global.PageViz = { init: init };
})(window);
+218
View File
@@ -0,0 +1,218 @@
(function (global) {
var MODES = [
{ id: 'neo-bars', label: 'Neo staafdiagram' },
{ id: 'neo-rings', label: 'Neo ringen' },
{ id: 'neo-equalizer', label: 'Neo equalizer' },
{ id: 'neo-cards', label: 'Neo kaarten' },
{ id: 'neo-table', label: 'Neo tabel' },
];
var charts = {};
function destroy(key) {
if (charts[key]) {
charts[key].destroy();
charts[key] = null;
}
}
function colors() {
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)',
purple: 'rgba(168, 85, 247, 0.9)', gray: 'rgba(159, 176, 196, 0.85)',
grid: 'rgba(159, 176, 196, 0.15)', text: '#c8d4e0',
};
}
function eqBars(counts, cls) {
var max = Math.max.apply(null, counts.concat([1]));
return '<div class="hm-eq viz-eq ' + (cls || '') + '">' +
counts.map(function (v) {
var h = Math.max(18, Math.round((v / max) * 92));
return '<span style="height:' + h + '%"></span>';
}).join('') + '</div>';
}
function findPanel(canvas, alt) {
var el = (canvas && canvas.closest('.page-viz-panel')) || (alt && alt.closest('.page-viz-panel'));
return el || null;
}
function applyPanelLayout(canvas, alt, mode) {
var panel = findPanel(canvas, alt);
if (!panel) return;
var isCanvas = mode === 'neo-bars' || mode === 'neo-rings';
panel.classList.toggle('viz-mode-chart', isCanvas);
panel.classList.toggle('viz-mode-alt', !isCanvas);
panel.classList.toggle('viz-mode-rings', mode === 'neo-rings');
}
function useHorizontal(labels, opts) {
if (opts && opts.horizontal !== undefined) return opts.horizontal;
return (labels || []).length >= 6;
}
function renderBars(canvas, labels, values, opts) {
if (!canvas || typeof Chart === 'undefined') return;
opts = opts || { key: 'chart' };
var c = colors();
var horiz = useHorizontal(labels, opts);
destroy(opts.key);
charts[opts.key] = new Chart(canvas, {
type: 'bar',
data: {
labels: labels,
datasets: [{ data: values, backgroundColor: opts.color || c.cyan, borderRadius: 6, barThickness: horiz ? 'flex' : undefined, maxBarThickness: horiz ? 28 : 48 }],
},
options: {
indexAxis: horiz ? 'y' : 'x',
responsive: true,
maintainAspectRatio: false,
layout: { padding: { top: 4, right: 8, bottom: 4, left: 4 } },
plugins: { legend: { display: false }, title: { display: !!opts.title, text: opts.title, color: c.text, padding: { bottom: 8 } } },
scales: {
y: horiz
? { ticks: { color: c.text, autoSkip: false, font: { size: 11 } }, grid: { color: c.grid } }
: { ticks: { color: c.text }, grid: { color: c.grid }, beginAtZero: true },
x: horiz
? { ticks: { color: c.text }, grid: { display: false }, beginAtZero: true }
: { ticks: { color: c.text, maxRotation: 45, minRotation: 0, autoSkip: false, font: { size: 10 } }, grid: { display: false } },
},
},
});
requestAnimationFrame(function () {
if (charts[opts.key]) charts[opts.key].resize();
});
}
function renderRings(canvas, labels, values, key, title) {
if (!canvas || typeof Chart === 'undefined') return;
var c = colors();
destroy(key);
charts[key] = new Chart(canvas, {
type: 'doughnut',
data: {
labels: labels,
datasets: [{ data: values, backgroundColor: [c.green, c.gray, c.red, c.gold, c.cyan, c.purple], borderWidth: 0 }],
},
options: {
responsive: true,
maintainAspectRatio: false,
cutout: '62%',
layout: { padding: 4 },
plugins: {
legend: { position: 'bottom', labels: { color: c.text, boxWidth: 10, padding: 8, font: { size: 10 } } },
title: { display: !!title, text: title, color: c.text, font: { size: 11 } },
},
},
});
requestAnimationFrame(function () {
if (charts[key]) charts[key].resize();
});
}
function renderCards(container, rows) {
if (!container) return;
container.innerHTML = '<div class="viz-cards">' + rows.map(function (r) {
return '<div class="viz-card"><span class="viz-card-label">' + r.label + '</span><strong class="viz-card-val">' + r.value + '</strong></div>';
}).join('') + '</div>';
}
function renderTable(container, rows) {
if (!container) return;
container.innerHTML = '<table class="data-table viz-table"><thead><tr><th>Item</th><th>Waarde</th></tr></thead><tbody>' +
rows.map(function (r) { return '<tr><td>' + r.label + '</td><td>' + r.value + '</td></tr>'; }).join('') +
'</tbody></table>';
}
function renderEqualizer(container, rows, cls) {
if (!container) return;
container.innerHTML = rows.map(function (r) {
return '<div class="viz-eq-row"><span>' + r.label + '</span><strong>' + r.value + '</strong></div>';
}).join('') + eqBars(rows.map(function (r) { return Number(r.raw) || 0; }), cls);
}
function renderWidget(mode, spec) {
var canvas = spec.canvas;
var alt = spec.altContainer;
applyPanelLayout(canvas, alt, mode);
if (mode === 'neo-bars' && canvas) {
if (alt) alt.innerHTML = '';
canvas.style.display = '';
renderBars(canvas, spec.labels, spec.values, spec.chartOpts || { key: spec.key });
return;
}
if (mode === 'neo-rings' && canvas) {
if (alt) alt.innerHTML = '';
canvas.style.display = '';
renderRings(canvas, spec.labels, spec.values, spec.key, spec.title);
return;
}
if (canvas) canvas.style.display = 'none';
if (!alt) return;
if (mode === 'neo-equalizer') renderEqualizer(alt, spec.rows, spec.eqClass);
else if (mode === 'neo-cards') renderCards(alt, spec.rows);
else if (mode === 'neo-table') renderTable(alt, spec.rows);
else {
if (canvas) { canvas.style.display = ''; renderBars(canvas, spec.labels, spec.values, spec.chartOpts || { key: spec.key }); }
}
}
global.VizEngine = {
MODES: MODES,
renderWidget: renderWidget,
destroyAll: function () { Object.keys(charts).forEach(destroy); },
renderSentiment: function (mode, canvas, alt, stats, widgetMode) {
var m = widgetMode || mode;
var files = stats.nas_files || [];
var 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;
renderWidget(m, {
canvas: canvas, altContainer: alt, key: 'sentiment',
labels: ['Positief', 'Neutraal', 'Negatief'],
values: [counts.positive, counts.neutral, counts.negative],
title: 'NAS sentiment',
rows: [
{ label: 'Positief', value: counts.positive, raw: counts.positive },
{ label: 'Neutraal', value: counts.neutral, raw: counts.neutral },
{ label: 'Negatief', value: counts.negative, raw: counts.negative },
],
eqClass: 'hm-eq-purple',
});
},
renderAgents: function (mode, canvas, alt, stats, widgetMode) {
var m = widgetMode || mode;
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);
var values = labels.map(function (k) { return map[k]; });
if (!labels.length) { labels = ['geen']; values = [0]; }
renderWidget(m, {
canvas: canvas, altContainer: alt, key: 'agents',
labels: labels, values: values, title: 'Agent activiteit',
chartOpts: { key: 'agents', color: colors().gold },
rows: labels.map(function (l, i) { return { label: l, value: values[i], raw: values[i] }; }),
eqClass: 'hm-eq-lime',
});
},
renderFromRows: function (mode, canvas, alt, key, title, rows, eqClass, chartColor) {
var labels = rows.map(function (r) { return r.label; });
var values = rows.map(function (r) { return Number(r.raw) || 0; });
renderWidget(mode, {
canvas: canvas, altContainer: alt, key: key,
labels: labels, values: values, title: title,
chartOpts: { key: key, color: chartColor || colors().cyan },
rows: rows,
eqClass: eqClass || 'hm-eq-cyan',
});
},
};
})(window);