-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
479 lines (429 loc) · 17.2 KB
/
app.js
File metadata and controls
479 lines (429 loc) · 17.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
// Utils e formatação
const fmtBRL = new Intl.NumberFormat('pt-BR', { style:'currency', currency:'BRL' });
const fmtPct = new Intl.NumberFormat('pt-BR', { style:'percent', maximumFractionDigits:1 });
const el = (s, r=document)=> r.querySelector(s);
const els = (s, r=document)=> [...r.querySelectorAll(s)];
const toast = (msg)=> {
const t = el('#toast'); t.textContent = msg; t.style.display='block'; t.style.opacity='1';
setTimeout(()=>{ t.style.opacity='0'; setTimeout(()=> t.style.display='none', 300)}, 1800);
};
// Estado
const state = {
range: '1d', // 1d | 7d | 30d | 90d
theme: localStorage.getItem('theme') || 'dark',
data: {
labels: [],
revenue: [],
orders: [],
conv: [],
ticket: [],
categories: [/* valores */],
payments: [/* % por método */],
ops: [/* radar */]
},
charts: {}
};
// Helpers: números aleatórios controlados
function rand(min,max){ return Math.random()*(max-min)+min; }
function randInt(min,max){ return Math.floor(rand(min,max+1)); }
// Labels temporais
function genLabels(len, unit='h'){
const now = new Date();
const lbls = [];
for(let i=len-1;i>=0;i--){
const d = new Date(now);
if (unit==='h') d.setHours(now.getHours()-i);
if (unit==='d') d.setDate(now.getDate()-i);
lbls.push(unit==='h' ? d.getHours().toString().padStart(2,'0') + 'h' : d.toLocaleDateString('pt-BR', { day:'2-digit', month:'2-digit'}));
}
return lbls;
}
// Série com média de retorno (não cai infinito)
function meanRevertingSeries(len, start, targetBase, kappa=0.15, vol=0.08, floor=2000, ceil=20000){
const arr = [];
let v = start;
for (let i=0;i<len;i++){
// alvo levemente ondulante (sazonal) em torno de targetBase
const seasonal = 1 + 0.06*Math.sin(i/6) + 0.03*Math.cos(i/3);
const target = targetBase * seasonal;
const shock = (Math.random()-0.5)*vol*targetBase;
v = v + kappa*(target - v) + shock;
v = Math.max(floor, Math.min(ceil, v));
arr.push(Number(v.toFixed(2)));
}
return arr;
}
// Dados sintéticos por range
function generateData(range){
const map = { '1d': {len:24, unit:'h'}, '7d':{len:7, unit:'d'}, '30d':{len:30, unit:'d'}, '90d':{len:90, unit:'d'} };
const {len, unit} = map[range] || map['7d'];
const labels = genLabels(len, unit);
const targetBase = randInt(7000, 12000);
const start = targetBase * rand(0.9, 1.1);
const revenue = meanRevertingSeries(len, start, targetBase, 0.18, 0.10, 2500, 30000);
const orders = Array.from({length:len}, ()=> randInt(60, 180));
const conv = Array.from({length:len}, ()=> Math.max(0.006, Math.min(0.08, rand(0.02, 0.06))));
const ticket = revenue.map((r,i)=> orders[i] ? r/orders[i] : r/100);
const categories = ['Eletrônicos','Moda','Casa','Esportes','Beleza','Games'].map(()=> randInt(150, 1100));
const payRaw = [randInt(45,70), randInt(20,40), randInt(5,20)];
const paySum = payRaw.reduce((a,b)=>a+b,0);
const payments = payRaw.map(v => Math.round(v/paySum*100));
const ops = ['Entrega','Qualidade','Suporte','SLA','Estoque'].map(()=> randInt(65,95));
return { labels, revenue, orders, conv, ticket, categories, payments, ops };
}
// Cores atuais do tema
function themeColors(){
const s = getComputedStyle(document.documentElement);
return {
text: (s.getPropertyValue('--text')||'#e6edf3').trim(),
grid: (s.getPropertyValue('--border')||'#223147').trim(),
brand:(s.getPropertyValue('--brand')||'#4f8cff').trim(),
accent:(s.getPropertyValue('--accent')||'#22c55e').trim(),
warn: (s.getPropertyValue('--warn')||'#f59e0b').trim()
};
}
// Inicializa gráficos
function initCharts(){
const { text, grid, brand, accent, warn } = themeColors();
// Receita
const ctxRev = el('#chartRevenue').getContext('2d');
state.charts.revenue = new Chart(ctxRev, {
type:'line',
data:{ labels: state.data.labels, datasets:[
{ label:'Receita', data: state.data.revenue, fill:true, borderColor: brand, backgroundColor: 'rgba(79,140,255,0.15)', tension:.35, pointRadius:0, borderWidth:2 }
]},
options:{
responsive:true, maintainAspectRatio:false, animation:{ duration:500, easing:'easeOutQuart' },
scales:{
x:{ ticks:{ color:text }, grid:{ color:grid } },
y:{ beginAtZero:false, ticks:{ color:text, callback:v=>fmtBRL.format(v) }, grid:{ color:grid } }
},
plugins:{
legend:{ labels:{ color:text }},
tooltip:{ callbacks:{ label:(ctx)=> ` ${ctx.dataset.label}: ${fmtBRL.format(ctx.parsed.y)}` } }
}
}
});
// Pagamentos
const ctxPay = el('#chartPayments').getContext('2d');
state.charts.payments = new Chart(ctxPay, {
type:'doughnut',
data:{ labels: ['Cartão','PIX','Boleto'], datasets:[{
data: state.data.payments,
backgroundColor:[brand, accent, warn],
borderColor:'transparent'
}]},
options:{
responsive:true, maintainAspectRatio:false, animation:{ duration:500 },
plugins:{
legend:{ position:'bottom', labels:{ color:text } },
tooltip:{ callbacks:{ label:(ctx)=> ` ${ctx.label}: ${ctx.parsed}%` } }
},
cutout:'62%'
}
});
// Categorias
const ctxCat = el('#chartCategories').getContext('2d');
state.charts.categories = new Chart(ctxCat, {
type:'bar',
data:{ labels: ['Eletrônicos','Moda','Casa','Esportes','Beleza','Games'], datasets:[{
label:'Vendas', data: state.data.categories,
backgroundColor:'rgba(79,140,255,0.35)', borderColor:brand, borderWidth:1.5, borderRadius:8
}]},
options:{
responsive:true, maintainAspectRatio:false, animation:{ duration:500 },
scales:{
x:{ ticks:{ color:text }, grid:{ color:grid, display:false }},
y:{ ticks:{ color:text }, grid:{ color:grid } }
},
plugins:{ legend:{ labels:{ color:text } } }
}
});
// Radar Operacional
const ctxOps = el('#chartOps').getContext('2d');
state.charts.ops = new Chart(ctxOps, {
type:'radar',
data:{ labels: ['Entrega','Qualidade','Suporte','SLA','Estoque'], datasets:[{
label:'Índice', data: state.data.ops, fill:true,
backgroundColor:'rgba(34,197,94,0.20)', borderColor:accent, pointBackgroundColor:accent
}]},
options:{
responsive:true, maintainAspectRatio:false, animation:{ duration:500 },
scales:{ r:{ angleLines:{ color:grid }, grid:{ color:grid }, pointLabels:{ color:text }, ticks:{ display:false, backdropColor:'transparent' } } },
plugins:{ legend:{ labels:{ color:text } } }
}
});
// Sparklines KPIs
function sparkConfig(canvasId, color){
const ctx = el(canvasId).getContext('2d');
return new Chart(ctx, {
type:'line',
data:{ labels: state.data.labels, datasets:[{ data: [], borderColor:color, backgroundColor:'transparent', pointRadius:0, borderWidth:2, tension:.35 }]},
options:{
responsive:true, maintainAspectRatio:false, animation:false,
scales:{ x:{ display:false }, y:{ display:false } },
plugins:{ legend:{ display:false }, tooltip:{ enabled:false } }
}
});
}
state.charts.sparkRevenue = sparkConfig('#sparkRevenue', brand);
state.charts.sparkOrders = sparkConfig('#sparkOrders', '#22c55e');
state.charts.sparkConv = sparkConfig('#sparkConv', '#f59e0b');
state.charts.sparkTicket = sparkConfig('#sparkTicket', '#a78bfa');
}
// Aplica dados e mantém eixos estáveis
function applyDataToCharts(){
const { revenue, orders, conv, ticket, labels, categories, payments, ops } = state.data;
el('#revSub').textContent = ({'1d':'Últimas 24h','7d':'Últimos 7 dias','30d':'Últimos 30 dias','90d':'Últimos 90 dias'})[state.range];
// Faixa sugerida estável para Y (evita “afundar”)
const min = Math.min(...revenue);
const max = Math.max(...revenue);
const pad = Math.max(500, (max - min) * 0.25);
const yMin = Math.max(2000, Math.floor((min - pad)/100)*100);
const yMax = Math.ceil((max + pad)/100)*100;
// Receita
const chRev = state.charts.revenue;
chRev.data.labels = labels;
chRev.data.datasets[0].data = revenue;
chRev.options.scales.y.suggestedMin = yMin;
chRev.options.scales.y.suggestedMax = yMax;
chRev.update('none');
// Donut
const chPay = state.charts.payments;
chPay.data.datasets[0].data = payments;
chPay.update('none');
// Categorias
const chCat = state.charts.categories;
chCat.data.datasets[0].data = categories;
chCat.update('none');
// Radar
const chOps = state.charts.ops;
chOps.data.datasets[0].data = ops;
chOps.update('none');
// Sparklines
state.charts.sparkRevenue.data.labels = labels;
state.charts.sparkOrders.data.labels = labels;
state.charts.sparkConv.data.labels = labels;
state.charts.sparkTicket.data.labels = labels;
state.charts.sparkRevenue.data.datasets[0].data = revenue;
state.charts.sparkOrders.data.datasets[0].data = orders;
state.charts.sparkConv.data.datasets[0].data = conv.map(v=> Number((v*100).toFixed(2)));
state.charts.sparkTicket.data.datasets[0].data = ticket;
state.charts.sparkRevenue.update('none');
state.charts.sparkOrders.update('none');
state.charts.sparkConv.update('none');
state.charts.sparkTicket.update('none');
// KPIs
const sumRev = revenue.reduce((a,b)=>a+b,0);
const sumOrders = orders.reduce((a,b)=>a+b,0);
const avgConv = conv.reduce((a,b)=>a+b,0)/conv.length;
const avgTicket = ticket.reduce((a,b)=>a+b,0)/ticket.length;
el('#kpiRevenue').textContent = fmtBRL.format(sumRev);
el('#kpiOrders').textContent = sumOrders.toLocaleString('pt-BR');
el('#kpiConv').textContent = fmtPct.format(avgConv);
el('#kpiTicket').textContent = fmtBRL.format(avgTicket);
// Deltas
function delta(arr){
if (arr.length < 2) return {v:0, dir:'flat'};
const a = arr[arr.length-2], b = arr[arr.length-1];
const d = a === 0 ? 0 : (b-a)/Math.abs(a);
return { v:d, dir: d>0?'up':(d<0?'down':'flat') };
}
const dRev = delta(revenue);
const dOrd = delta(orders);
const dCon = delta(conv);
const dTic = delta(ticket);
function setDelta(id, d){
const e = el(id);
e.className = 'kpi-delta ' + (d.dir==='up'?'up':(d.dir==='down'?'down':''));
e.textContent = (d.dir==='up'?'▲ ':(d.dir==='down'?'▼ ':'≈ ')) + fmtPct.format(d.v);
}
setDelta('#kpiRevenueDelta', dRev);
setDelta('#kpiOrdersDelta', dOrd);
setDelta('#kpiConvDelta', dCon);
setDelta('#kpiTicketDelta', dTic);
}
// Atividades
const activityPool = [
'Novo pedido confirmado',
'Pagamento aprovado (Cartão)',
'Pagamento via PIX recebido',
'Boleto gerado',
'Cliente abriu ticket de suporte',
'Produto reposto em estoque',
'Pedido enviado ao transporte',
'Entrega realizada',
'Reembolso processado',
'Cupom aplicado em compra'
];
function pushActivity(){
const list = el('#activityList');
const item = document.createElement('li');
const now = new Date();
const msg = activityPool[randInt(0, activityPool.length-1)];
const type = msg.includes('pedido') || msg.includes('Pedido') ? 'Pedido' :
msg.includes('Pagamento') || msg.includes('PIX') || msg.includes('Boleto') ? 'Pagamento' : 'Operação';
item.innerHTML = `
<span class="badge">${now.toLocaleTimeString('pt-BR', {hour:'2-digit', minute:'2-digit'})}</span>
<span>${msg}</span>
<span class="badge" style="margin-left:auto">${type}</span>
`;
list.prepend(item);
const children = list.children;
if (children.length > 50) list.removeChild(children[children.length-1]);
el('#actCount').textContent = `${Math.min(children.length,50)} eventos`;
}
// Exportar CSV
function exportCSV(){
const { labels, revenue, orders } = state.data;
let csv = 'Período,Receita,Pedidos\n';
labels.forEach((l,i)=> csv += `${l},${revenue[i]},${orders[i]}\n`);
const blob = new Blob([csv], {type:'text/csv;charset=utf-8;'});
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url; a.download = `dashboard_${state.range}.csv`; a.click();
URL.revokeObjectURL(url);
toast('CSV exportado!');
}
// Atualização periódica com média de retorno
let timer = null;
function startRealtime(){
if (timer) clearInterval(timer);
timer = setInterval(()=>{
const len = state.data.labels.length;
if (!len) return;
// Define novo targetBase leve (varia com o tempo)
const baseNow = Math.max(4000, Math.min(25000, (state.data.revenue.reduce((a,b)=>a+b,0)/len)));
const target = baseNow * (1 + 0.04*Math.sin(Date.now()/60000));
// Atualiza último ponto com mean reversion e ruído pequeno
function stepMeanRevert(last, tgt, kappa=0.18, vol=0.06){
const shock = (Math.random()-0.5)*vol*tgt;
let v = last + kappa*(tgt - last) + shock;
v = Math.max(2500, Math.min(30000, v));
return Number(v.toFixed(2));
}
const lastRev = state.data.revenue[len-1];
const nextRev = stepMeanRevert(lastRev, target, 0.2, 0.08);
// Shift e push mantendo o comprimento
state.data.revenue.push(nextRev); state.data.revenue.shift();
state.data.orders.push(randInt(60, 180)); state.data.orders.shift();
state.data.conv.push(Math.max(0.006, Math.min(0.08, rand(0.02, 0.06)))); state.data.conv.shift();
state.data.ticket = state.data.revenue.map((r,i)=> state.data.orders[i] ? r/state.data.orders[i] : r/100);
// Oscilações leves nas dimensões
state.data.categories = state.data.categories.map(v=> Math.max(120, Math.min(1500, v + randInt(-20, 20))));
let pays = state.data.payments.map(v=> Math.max(5, Math.min(90, v + randInt(-2,2))));
const s = pays.reduce((a,b)=>a+b,0); state.data.payments = pays.map(v=> Math.round(v/s*100));
state.data.ops = state.data.ops.map(v=> Math.max(55, Math.min(100, v + randInt(-2,2))));
applyDataToCharts();
if (Math.random() < 0.6) pushActivity();
}, 5000);
}
// Tema claro/escuro
function applyTheme(){
if (state.theme === 'light'){
document.documentElement.setAttribute('data-theme', 'light');
el('#iconMoon').style.display='none';
el('#iconSun').style.display='block';
} else {
document.documentElement.removeAttribute('data-theme');
el('#iconMoon').style.display='block';
el('#iconSun').style.display='none';
}
}
function toggleTheme(){
state.theme = state.theme === 'light' ? 'dark' : 'light';
localStorage.setItem('theme', state.theme);
applyTheme();
// Recria gráficos para aplicar novas cores
Object.values(state.charts).forEach(ch => ch.destroy());
initCharts();
applyDataToCharts();
}
// Range chips
function initRangeChips(){
el('#rangeChips').addEventListener('click', (e)=>{
const r = e.target?.dataset?.range;
if (!r) return;
state.range = r;
els('.chip', el('#rangeChips')).forEach(c => c.classList.toggle('active', c.dataset.range === r));
// Dados novos
const gen = generateData(state.range);
state.data.labels = gen.labels;
state.data.revenue = gen.revenue;
state.data.orders = gen.orders;
state.data.conv = gen.conv;
state.data.ticket = gen.ticket;
state.data.categories = gen.categories;
state.data.payments = gen.payments;
state.data.ops = gen.ops;
applyDataToCharts();
toast('Dados atualizados: ' + ({'1d':'Hoje','7d':'7 dias','30d':'30 dias','90d':'90 dias'}[state.range]));
});
}
// Sidebar responsiva
function sidebarControls(){
const btn = el('#collapseSidebar');
btn.addEventListener('click', ()=>{
if (window.innerWidth <= 900){
el('#sidebar').classList.toggle('open');
return;
}
const sb = el('#sidebar');
const wrap = el('.wrapper');
if (!sb.style.transform || sb.style.transform===''){
sb.style.transform = 'translateX(-100%)';
wrap.style.marginLeft = '0';
} else {
sb.style.transform = '';
wrap.style.marginLeft = '260px';
}
});
}
// Inicialização
function init(){
applyTheme();
el('#userName').textContent = 'bimadevfull';
const gen = generateData(state.range);
state.data.labels = gen.labels;
state.data.revenue = gen.revenue;
state.data.orders = gen.orders;
state.data.conv = gen.conv;
state.data.ticket = gen.ticket;
state.data.categories = gen.categories;
state.data.payments = gen.payments;
state.data.ops = gen.ops;
initRangeChips();
sidebarControls();
el('#refreshBtn').addEventListener('click', ()=>{
const genN = generateData(state.range);
state.data.labels = genN.labels;
state.data.revenue = genN.revenue;
state.data.orders = genN.orders;
state.data.conv = genN.conv;
state.data.ticket = genN.ticket;
state.data.categories = genN.categories;
state.data.payments = genN.payments;
state.data.ops = genN.ops;
applyDataToCharts();
pushActivity();
toast('Atualizado!');
});
el('#exportBtn').addEventListener('click', exportCSV);
el('#themeToggle').addEventListener('click', toggleTheme);
el('#logoutBtn').addEventListener('click', ()=> toast('Sessão encerrada (demo)'));
el('#searchInput').addEventListener('input', (e)=> {
if (e.target.value.trim().length>2){
toast('Buscando por: ' + e.target.value.trim());
}
});
// Charts
initCharts();
applyDataToCharts();
// Atividades iniciais
for(let i=0;i<6;i++) pushActivity();
// Realtime
startRealtime();
// Escape fecha sidebar no mobile
document.addEventListener('keydown', (e)=>{ if(e.key==='Escape'){ el('#sidebar').classList.remove('open'); }});
}
document.addEventListener('DOMContentLoaded', init);