-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathadmin.html
More file actions
911 lines (776 loc) · 43.1 KB
/
admin.html
File metadata and controls
911 lines (776 loc) · 43.1 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
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
<!DOCTYPE html>
<html lang="de">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>S.I.M. Scouting - Admin Dashboard</title>
<!-- Tailwind CSS -->
<script src="https://cdn.tailwindcss.com"></script>
<!-- FontAwesome -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
<!-- Google Fonts -->
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;600;700&display=swap" rel="stylesheet">
<style>
body { font-family: 'Inter', sans-serif; }
.glass-panel {
background: rgba(30, 41, 59, 0.7);
backdrop-filter: blur(10px);
border: 1px solid rgba(255, 255, 255, 0.1);
}
</style>
</head>
<body class="bg-slate-900 text-white min-h-screen">
<!-- Auth Overlay -->
<div id="auth-layer" class="fixed inset-0 bg-slate-900 z-50 flex items-center justify-center">
<div class="text-center">
<i class="fa-solid fa-lock text-4xl text-slate-500 mb-4"></i>
<p>Authentifizierung...</p>
</div>
</div>
<!-- Scout Detail Modal (Hidden) -->
<div id="scout-modal" class="fixed inset-0 bg-black/80 z-40 hidden flex items-center justify-center p-4 backdrop-blur-sm">
<div class="glass-panel w-full max-w-4xl max-h-[90vh] rounded-2xl flex flex-col shadow-2xl border border-slate-700">
<!-- Modal Header -->
<div class="flex justify-between items-center p-6 border-b border-slate-700 bg-slate-800/50 rounded-t-2xl">
<div class="flex items-center gap-4">
<div class="h-12 w-12 rounded-full bg-blue-500/20 flex items-center justify-center border border-blue-500/30">
<i class="fa-solid fa-user text-blue-400 text-xl"></i>
</div>
<div>
<h2 id="modal-scout-name" class="text-2xl font-bold">Scout Name</h2>
<div class="text-sm text-slate-400">Scout Details & Performance</div>
</div>
</div>
<button onclick="closeScoutModal()" class="h-10 w-10 rounded-full hover:bg-slate-700 flex items-center justify-center transition">
<i class="fa-solid fa-times text-slate-400 text-lg"></i>
</button>
</div>
<!-- Modal Content (Scrollable) -->
<div class="p-6 overflow-y-auto modal-scroll flex-1">
<!-- Mini KPIs -->
<div class="grid grid-cols-1 md:grid-cols-3 gap-4 mb-8">
<div class="bg-slate-800/50 p-4 rounded-xl border border-slate-700">
<div class="text-slate-400 text-xs uppercase font-bold tracking-wider mb-1">Total Leads</div>
<div class="flex items-center gap-2">
<i class="fa-solid fa-user-plus text-emerald-500"></i>
<span id="modal-kpi-leads" class="text-2xl font-bold">0</span>
</div>
</div>
<div class="bg-slate-800/50 p-4 rounded-xl border border-slate-700">
<div class="text-slate-400 text-xs uppercase font-bold tracking-wider mb-1">Link Shares</div>
<div class="flex items-center gap-2">
<i class="fa-solid fa-share-alt text-yellow-500"></i>
<span id="modal-kpi-shares" class="text-2xl font-bold">0</span>
</div>
</div>
<div class="bg-slate-800/50 p-4 rounded-xl border border-slate-700">
<div class="text-slate-400 text-xs uppercase font-bold tracking-wider mb-1">Page Views</div>
<div class="flex items-center gap-2">
<i class="fa-solid fa-eye text-blue-500"></i>
<span id="modal-kpi-views" class="text-2xl font-bold">0</span>
</div>
</div>
</div>
<!-- Recruited Friends Table -->
<h3 class="text-lg font-bold mb-4 flex items-center gap-2">
<i class="fa-solid fa-users text-slate-400"></i> Geworbene Freunde
</h3>
<div class="overflow-hidden rounded-xl border border-slate-700">
<table class="w-full text-left border-collapse">
<thead>
<tr class="bg-slate-800 text-slate-400 text-sm">
<th class="p-3 pl-4">Datum</th>
<th class="p-3">Name</th>
<th class="p-3">Status</th>
</tr>
</thead>
<tbody id="modal-leads-body" class="text-sm divide-y divide-slate-700 bg-slate-800/20">
<tr><td colspan="3" class="p-4 text-center text-slate-500">Keine Daten</td></tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
<!-- Campaign Detail Modal (Hidden) -->
<div id="campaign-modal" class="fixed inset-0 bg-black/80 z-40 hidden flex items-center justify-center p-4 backdrop-blur-sm">
<div class="glass-panel w-full max-w-4xl max-h-[90vh] rounded-2xl flex flex-col shadow-2xl border border-slate-700">
<!-- Modal Header -->
<div class="flex justify-between items-center p-6 border-b border-slate-700 bg-slate-800/50 rounded-t-2xl">
<div class="flex items-center gap-4">
<div class="h-12 w-12 rounded-full bg-indigo-500/20 flex items-center justify-center border border-indigo-500/30">
<i class="fa-solid fa-bullhorn text-indigo-400 text-xl"></i>
</div>
<div>
<h2 id="modal-campaign-name" class="text-2xl font-bold">Campaign Name</h2>
<div class="text-sm text-slate-400">Kampagnen-Details & Performance</div>
</div>
</div>
<button onclick="closeCampaignModal()" class="h-10 w-10 rounded-full hover:bg-slate-700 flex items-center justify-center transition">
<i class="fa-solid fa-times text-slate-400 text-lg"></i>
</button>
</div>
<!-- Modal Content (Scrollable) -->
<div class="p-6 overflow-y-auto modal-scroll flex-1">
<!-- Mini KPIs -->
<div class="grid grid-cols-1 md:grid-cols-2 gap-4 mb-8">
<div class="bg-slate-800/50 p-4 rounded-xl border border-slate-700">
<div class="text-slate-400 text-xs uppercase font-bold tracking-wider mb-1">Total Leads</div>
<div class="flex items-center gap-2">
<i class="fa-solid fa-user-plus text-emerald-500"></i>
<span id="modal-campaign-leads" class="text-2xl font-bold">0</span>
</div>
</div>
</div>
<!-- Campaign Leads Table -->
<h3 class="text-lg font-bold mb-4 flex items-center gap-2">
<i class="fa-solid fa-users text-slate-400"></i> Leads über diese Kampagne
</h3>
<div class="overflow-hidden rounded-xl border border-slate-700">
<table class="w-full text-left border-collapse">
<thead>
<tr class="bg-slate-800 text-slate-400 text-sm">
<th class="p-3 pl-4">Datum</th>
<th class="p-3">Name</th>
<th class="p-3">Scout</th>
</tr>
</thead>
<tbody id="modal-campaign-body" class="text-sm divide-y divide-slate-700 bg-slate-800/20">
<tr><td colspan="3" class="p-4 text-center text-slate-500">Keine Daten</td></tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
<!-- Main Content (Hidden until auth) -->
<div id="dashboard" class="hidden p-6 max-w-7xl mx-auto">
<!-- Header -->
<header class="flex justify-between items-center mb-8">
<div class="flex items-center gap-3">
<img src="https://www.studios-in-motion.de/images/logo_studiosinmotion_2021_rahmen.svg" alt="Logo" class="h-8">
<h1 class="text-2xl font-bold text-slate-100">Scouting Dashboard</h1>
</div>
<button onclick="location.reload()" class="p-2 hover:bg-slate-800 rounded-lg transition">
<i class="fa-solid fa-rotate-right text-slate-400"></i>
</button>
</header>
<!-- KPI Grid -->
<div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-8">
<!-- Total Scouts -->
<div class="glass-panel p-6 rounded-xl relative overflow-hidden group">
<div class="absolute right-0 top-0 p-4 opacity-10 group-hover:opacity-20 transition">
<i class="fa-solid fa-users text-6xl text-blue-500"></i>
</div>
<p class="text-slate-400 text-sm font-semibold uppercase tracking-wider">Total Scouts</p>
<h3 class="text-3xl font-bold mt-2" id="kpi-scouts">-</h3>
<div class="mt-2 text-xs text-blue-400">Registrierte Partner</div>
</div>
<!-- Total Leads -->
<div class="glass-panel p-6 rounded-xl relative overflow-hidden group">
<div class="absolute right-0 top-0 p-4 opacity-10 group-hover:opacity-20 transition">
<i class="fa-solid fa-user-plus text-6xl text-emerald-500"></i>
</div>
<p class="text-slate-400 text-sm font-semibold uppercase tracking-wider">Total Leads</p>
<h3 class="text-3xl font-bold mt-2" id="kpi-leads">-</h3>
<div class="mt-2 text-xs text-emerald-400">Generierte Kontakte</div>
</div>
<!-- Traffic -->
<div class="glass-panel p-6 rounded-xl relative overflow-hidden group">
<div class="absolute right-0 top-0 p-4 opacity-10 group-hover:opacity-20 transition">
<i class="fa-solid fa-eye text-6xl text-indigo-500"></i>
</div>
<p class="text-slate-400 text-sm font-semibold uppercase tracking-wider">Traffic (Views)</p>
<h3 class="text-3xl font-bold mt-2" id="kpi-traffic">-</h3>
<div class="mt-2 text-xs text-indigo-400">Seitenaufrufe</div>
</div>
<!-- Conversion Rate -->
<div class="glass-panel p-6 rounded-xl relative overflow-hidden group">
<div class="absolute right-0 top-0 p-4 opacity-10 group-hover:opacity-20 transition">
<i class="fa-solid fa-chart-pie text-6xl text-amber-500"></i>
</div>
<p class="text-slate-400 text-sm font-semibold uppercase tracking-wider">Conversion Rate</p>
<h3 class="text-3xl font-bold mt-2" id="kpi-conversion">- %</h3>
<div class="mt-2 text-xs text-amber-400">Leads / Views</div>
</div>
</div>
<!-- Content Grid -->
<div class="grid grid-cols-1 lg:grid-cols-3 gap-8 mb-8">
<!-- Leaderboard (2 Cols) -->
<div class="lg:col-span-2 glass-panel rounded-xl p-6">
<h3 class="text-xl font-bold mb-4 flex items-center gap-2">
<i class="fa-solid fa-trophy text-yellow-400"></i> Top Scouts
</h3>
<div class="overflow-x-auto">
<table class="w-full text-left border-collapse">
<thead>
<tr class="text-slate-400 text-sm border-b border-slate-700">
<th class="p-3">#</th>
<th class="p-3">Scout Name</th>
<th class="p-3 text-right">Leads</th>
<th class="p-3 text-right">Performance</th>
</tr>
</thead>
<tbody id="leaderboard-body" class="text-sm">
<tr><td colspan="4" class="p-4 text-center text-slate-500">Lade Daten...</td></tr>
</tbody>
</table>
</div>
</div>
<!-- Activity Feed (1 Col) -->
<div class="glass-panel rounded-xl p-6">
<h3 class="text-xl font-bold mb-4 flex items-center gap-2">
<i class="fa-solid fa-bolt text-blue-400"></i> Live Activity
</h3>
<div id="activity-feed" class="flex flex-col gap-4 max-h-[500px] overflow-y-auto pr-2">
<div class="text-center text-slate-500 py-4">Lade Feed...</div>
</div>
</div>
</div>
<!-- Lead Management Section (New) -->
<div class="glass-panel rounded-xl p-6">
<div class="flex flex-col md:flex-row justify-between items-center mb-6 gap-4">
<div class="flex flex-col gap-2">
<h3 class="text-xl font-bold flex items-center gap-2">
<i class="fa-solid fa-address-book text-emerald-400"></i> Neueste Leads & Anmeldungen
</h3>
<!-- Campaign Filter Box -->
<div id="campaign-filter-container" class="flex flex-wrap gap-2 hidden">
<!-- Populated by JS -->
</div>
</div>
<!-- Search -->
<div class="relative w-full md:w-64">
<input type="text" id="lead-search" placeholder="Suche nach Namen..."
class="w-full bg-slate-800 border border-slate-700 rounded-lg py-2 px-4 pl-10 text-sm focus:outline-none focus:border-blue-500 transition">
<i class="fa-solid fa-search absolute left-3 top-2.5 text-slate-500 text-xs"></i>
</div>
</div>
<div class="overflow-x-auto">
<table class="w-full text-left border-collapse">
<thead>
<tr class="text-slate-400 text-sm border-b border-slate-700 bg-slate-800/50">
<th onclick="handleSort('created_at')" class="p-3 rounded-tl-lg cursor-pointer hover:text-white transition group select-none">
Datum <i class="fa-solid fa-sort text-slate-600 group-hover:text-slate-400 ml-1 text-xs"></i>
</th>
<th class="p-3">Quelle</th>
<th onclick="handleSort('campaign')" class="p-3 cursor-pointer hover:text-white transition group select-none">
Kampagne <i class="fa-solid fa-sort text-slate-600 group-hover:text-slate-400 ml-1 text-xs"></i>
</th>
<th onclick="handleSort('first_name')" class="p-3 cursor-pointer hover:text-white transition group select-none">
Vorname <i class="fa-solid fa-sort text-slate-600 group-hover:text-slate-400 ml-1 text-xs"></i>
</th>
<th onclick="handleSort('last_name')" class="p-3 cursor-pointer hover:text-white transition group select-none">
Nachname <i class="fa-solid fa-sort text-slate-600 group-hover:text-slate-400 ml-1 text-xs"></i>
</th>
<th class="p-3">Telefon</th>
<th onclick="handleSort('scout_name')" class="p-3 rounded-tr-lg cursor-pointer hover:text-white transition group select-none">
Geworben von <i class="fa-solid fa-sort text-slate-600 group-hover:text-slate-400 ml-1 text-xs"></i>
</th>
</tr>
</thead>
<tbody id="leads-body" class="text-sm text-slate-300">
<tr><td colspan="5" class="p-4 text-center text-slate-500">Lade Leads...</td></tr>
</tbody>
</table>
</div>
<div id="leads-count" class="text-xs text-slate-500 mt-2 text-right">0 Einträge</div>
</div>
<!-- Debug / Footer -->
<div class="mt-12 text-center text-slate-600 text-sm">
Admin Dashboard v2.1 • Data based on SIM-Scouting Supabase
<div id="debug-area" class="mt-2 font-mono text-xs text-red-900"></div>
</div>
</div>
<!-- Logic -->
<script type="module">
import { createClient } from 'https://cdn.jsdelivr.net/npm/@supabase/supabase-js@2/+esm';
const SUPABASE_URL = 'https://rmtyebyzitzgkplxvzxg.supabase.co';
const SUPABASE_KEY = 'sb_publishable_2qDg3Jssg_fTPdXl_3Ku-g_1yOkdJ3i';
const TENANT_ID = '79a37c78-7bdf-45e4-a631-fb47926d054d';
// Init Supabase
const supabase = createClient(SUPABASE_URL, SUPABASE_KEY);
// Global State
let allLeads = [];
let allEvents = [];
let scoutMap = {};
let sortConfig = { column: 'created_at', direction: 'desc' };
// --- AUTH ---
window.addEventListener('DOMContentLoaded', () => {
const pass = prompt('Bitte Passwort eingeben:');
if (pass === 'admin123') {
document.getElementById('auth-layer').style.display = 'none';
document.getElementById('dashboard').classList.remove('hidden');
initDashboard();
} else {
alert('Falsches Passwort!');
document.getElementById('auth-layer').innerHTML = '<p class="text-red-500">Zugriff verweigert.</p>';
}
});
// --- DATA LOGIC ---
async function initDashboard() {
try {
// 1. Fetch Scouts
const { data: scouts, error: errScouts } = await supabase
.from('scouts')
.select('id, first_name, last_name')
.eq('tenant_id', TENANT_ID);
if (errScouts) throw errScouts;
scoutMap = {}; // Reset
const scoutIds = [];
scouts.forEach(s => {
scoutMap[s.id] = `${s.first_name} ${s.last_name}`;
scoutIds.push(s.id);
});
document.getElementById('kpi-scouts').textContent = scouts.length;
// 2. Fetch Invites (Leads) WITH joins logic (manual join here for Simplicity/RLS)
// We fetch all invites that match our scout IDs
const { data: invites, error: errInvites } = await supabase
.from('invites')
.select('id, scout_id, created_at, first_name, last_name, phone, lead_data')
.in('scout_id', scoutIds)
.order('created_at', { ascending: false });
if (errInvites) throw errInvites;
// Enrich leads with Scout Name
allLeads = invites.map(inv => ({
...inv,
scout_name: scoutMap[inv.scout_id] || 'Unbekannt'
}));
const totalLeads = allLeads.length;
document.getElementById('kpi-leads').textContent = allLeads.length;
// Render Filter
renderCampaignFilter(allLeads);
renderLeadsTable(allLeads);
renderLeadsTable(allLeads);
// Setup Search Listener
document.getElementById('lead-search').addEventListener('input', (e) => {
filterLeads(e.target.value);
});
// 3. Fetch Tracking Events (Traffic & Shares)
const { data: eventsData, error: errTraffic } = await supabase
.from('tracking_events')
.select('*')
.in('scout_id', scoutIds)
.order('created_at', { ascending: false });
if (errTraffic) throw errTraffic;
allEvents = eventsData || [];
// Calculate total page views for KPI
const trafficCount = allEvents.filter(e => e.event_type === 'page_view').length;
document.getElementById('kpi-traffic').textContent = trafficCount;
// 4. Conversion Rate
const effectiveTraffic = Math.max(trafficCount, totalLeads);
let conversion = 0;
if (effectiveTraffic > 0) {
conversion = (totalLeads / effectiveTraffic) * 100;
}
document.getElementById('kpi-conversion').textContent = conversion.toFixed(1) + '%';
// --- LEADERBOARD LOGIC ---
const leadCounts = {};
allLeads.forEach(inv => {
const sid = inv.scout_id;
leadCounts[sid] = (leadCounts[sid] || 0) + 1;
});
const leaderboard = Object.keys(leadCounts).map(sid => ({
id: sid,
name: scoutMap[sid] || 'Unbekannt',
leads: leadCounts[sid]
})).sort((a, b) => b.leads - a.leads).slice(0, 5);
renderLeaderboard(leaderboard, totalLeads);
// --- ACTIVITY FEED LOGIC ---
// Fetch recent events
const { data: recentEvents, error: errRecent } = await supabase
.from('tracking_events')
.select('*')
.or(`scout_id.in.(${scoutIds.join(',')}),scout_id.is.null`) // Include organic if desired, or strict: .in('scout_id', scoutIds)
.order('created_at', { ascending: false })
.limit(20);
const feedItems = [];
// Add Leads
allLeads.forEach(inv => {
let sourceText = '';
let leadData = inv.lead_data;
if (typeof leadData === 'string') {
try { leadData = JSON.parse(leadData); } catch (e) {}
}
if (leadData && leadData.source) {
const s = leadData.source;
if (s === 'wa') sourceText = ' via WhatsApp';
if (s === 'cp') sourceText = ' via Link';
if (s === 'em') sourceText = ' via E-Mail';
}
feedItems.push({
type: 'lead',
timestamp: new Date(inv.created_at),
scout: inv.scout_name,
details: `Neuer Lead: ${inv.first_name} ${inv.last_name}${sourceText}`,
meta: leadData // Pass full leadData as meta to access campaign
});
});
// Add Tracking Events
if (recentEvents) {
recentEvents.forEach(evt => {
// Filter organic if strictly required, but usually we want to see them
const scoutName = evt.scout_id ? (scoutMap[evt.scout_id] || 'Unbekannt') : 'Organisch';
feedItems.push({
type: evt.event_type,
timestamp: new Date(evt.created_at),
scout: scoutName,
details: '', // Calculated in render
meta: evt.meta_data
});
});
}
feedItems.sort((a, b) => b.timestamp - a.timestamp);
renderFeed(feedItems.slice(0, 15));
} catch (err) {
console.error(err);
document.getElementById('debug-area').textContent = 'Error: ' + err.message;
}
}
// --- MODAL LOGIC (Global) ---
window.openScoutModal = function(scoutId) {
const modal = document.getElementById('scout-modal');
const scoutName = scoutMap[scoutId] || 'Unbekannt';
// 1. Set Header
document.getElementById('modal-scout-name').textContent = scoutName;
// 2. Filter Leads for this Scout
const myLeads = allLeads.filter(l => l.scout_id === scoutId);
document.getElementById('modal-kpi-leads').textContent = myLeads.length;
// 3. Filter Events for stats
const myEvents = allEvents.filter(e => e.scout_id === scoutId);
// Views
const myViews = myEvents.filter(e => e.event_type === 'page_view').length;
document.getElementById('modal-kpi-views').textContent = myViews;
// Shares (Whatsapp + Email + Copy + Save)
const myShares = myEvents.filter(e =>
e.event_type === 'share_whatsapp' ||
e.event_type === 'share_copy' ||
e.event_type === 'share_email' ||
e.event_type === 'save_link'
).length;
document.getElementById('modal-kpi-shares').textContent = myShares;
// 4. Render Table
const tbody = document.getElementById('modal-leads-body');
tbody.innerHTML = '';
if (myLeads.length === 0) {
tbody.innerHTML = '<tr><td colspan="3" class="p-4 text-center text-slate-500">Keine geworbenen Freunde</td></tr>';
} else {
myLeads.forEach(lead => {
const date = new Date(lead.created_at).toLocaleDateString();
const row = `
<tr class="border-b border-slate-700/50">
<td class="p-3 pl-4 text-slate-400 font-mono text-xs">${date}</td>
<td class="p-3 font-medium text-white">${lead.first_name} ${lead.last_name}</td>
<td class="p-3">
<span class="text-xs px-2 py-0.5 rounded bg-emerald-500/20 text-emerald-400">Lead</span>
</td>
</tr>
`;
tbody.innerHTML += row;
});
}
// Show
modal.classList.remove('hidden');
};
window.closeScoutModal = function() {
document.getElementById('scout-modal').classList.add('hidden');
};
// Close on escape key
document.addEventListener('keydown', (e) => {
if (e.key === 'Escape') {
window.closeScoutModal();
window.closeCampaignModal();
}
});
// --- CAMPAIGN MODAL LOGIC ---
window.openCampaignModal = function(campaignName) {
if (!campaignName) return;
const modal = document.getElementById('campaign-modal');
// 1. Set Header
document.getElementById('modal-campaign-name').textContent = campaignName;
// 2. Filter Leads for this Campaign
const myLeads = allLeads.filter(l => {
let data = l.lead_data;
if (typeof data === 'string') try { data = JSON.parse(data); } catch(e){}
return data && (data.campaign === campaignName || data.utm_campaign === campaignName);
});
document.getElementById('modal-campaign-leads').textContent = myLeads.length;
// 3. Render Table
const tbody = document.getElementById('modal-campaign-body');
tbody.innerHTML = '';
if (myLeads.length === 0) {
tbody.innerHTML = '<tr><td colspan="3" class="p-4 text-center text-slate-500">Keine Leads in dieser Kampagne</td></tr>';
} else {
// Sort by date desc for modal
const sorted = [...myLeads].sort((a,b) => new Date(b.created_at) - new Date(a.created_at));
sorted.forEach(lead => {
const date = new Date(lead.created_at).toLocaleDateString();
const row = `
<tr class="border-b border-slate-700/50">
<td class="p-3 pl-4 text-slate-400 font-mono text-xs">${date}</td>
<td class="p-3 font-medium text-white">${lead.first_name} ${lead.last_name}</td>
<td class="p-3 text-slate-400 text-sm">${lead.scout_name}</td>
</tr>
`;
tbody.innerHTML += row;
});
}
// Show
modal.classList.remove('hidden');
};
window.closeCampaignModal = function() {
document.getElementById('campaign-modal').classList.add('hidden');
};
// --- SORTING LOGIC ---
window.handleSort = function(column) {
if (sortConfig.column === column) {
// Toggle direction
sortConfig.direction = sortConfig.direction === 'asc' ? 'desc' : 'asc';
} else {
sortConfig.column = column;
sortConfig.direction = 'asc'; // Default to asc for new column (names etc), but maybe desc for date?
if (column === 'created_at') sortConfig.direction = 'desc'; // Exception for date
}
// Re-render
// Note: We need to respect the active filter if any exists!
// Currently renderLeadsTable takes "leads" as input.
// But we trigger re-render of the *current view*.
// Re-apply filter and sort
if (activeCampaignFilter) {
setCampaignFilter(activeCampaignFilter);
} else if (document.getElementById('lead-search').value) {
filterLeads(document.getElementById('lead-search').value);
} else {
renderLeadsTable(allLeads);
}
};
function sortLeads(leads) {
const { column, direction } = sortConfig;
return [...leads].sort((a, b) => {
let valA, valB;
if (column === 'campaign') {
// Extract campaign
let dataA = a.lead_data;
let dataB = b.lead_data;
if (typeof dataA === 'string') try { dataA = JSON.parse(dataA); } catch(e){}
if (typeof dataB === 'string') try { dataB = JSON.parse(dataB); } catch(e){}
valA = (dataA?.campaign || dataA?.utm_campaign || '').toLowerCase();
valB = (dataB?.campaign || dataB?.utm_campaign || '').toLowerCase();
} else {
valA = (a[column] || '').toString().toLowerCase();
valB = (b[column] || '').toString().toLowerCase();
}
if (column === 'created_at') {
valA = new Date(a.created_at).getTime();
valB = new Date(b.created_at).getTime();
}
if (valA < valB) return direction === 'asc' ? -1 : 1;
if (valA > valB) return direction === 'asc' ? 1 : -1;
return 0;
});
}
// --- RENDER FUNCTIONS ---
function renderLeadsTable(leads) {
// Apply Sort
const sortedLeads = sortLeads(leads);
const tbody = document.getElementById('leads-body');
const counter = document.getElementById('leads-count');
tbody.innerHTML = '';
counter.textContent = `${sortedLeads.length} Einträge`;
if (sortedLeads.length === 0) {
tbody.innerHTML = '<tr><td colspan="5" class="p-4 text-center text-slate-500">Keine Leads gefunden</td></tr>';
return;
}
sortedLeads.forEach(lead => {
const date = new Date(lead.created_at).toLocaleDateString('de-DE', { day: '2-digit', month: '2-digit', year: 'numeric', hour: '2-digit', minute:'2-digit' });
// Determine Source Icon
let sourceIcon = '<i class="fa-solid fa-link text-slate-600" title="Direkt / Unbekannt"></i>';
let leadData = lead.lead_data;
if (typeof leadData === 'string') {
try {
leadData = JSON.parse(leadData);
} catch (e) {
console.warn('Could not parse lead_data', e);
leadData = {};
}
}
const src = leadData && leadData.source ? leadData.source : 'direct';
if (src === 'wa') sourceIcon = '<i class="fa-brands fa-whatsapp text-green-500" title="Quelle: WhatsApp"></i>';
if (src === 'cp') sourceIcon = '<i class="fa-solid fa-copy text-blue-400" title="Quelle: Link kopiert"></i>';
if (src === 'em') sourceIcon = '<i class="fa-solid fa-envelope text-blue-600" title="Quelle: E-Mail"></i>';
if (src === 'qr') sourceIcon = '<i class="fa-solid fa-qrcode text-white" title="Quelle: QR Code"></i>';
const row = `
<tr class="border-b border-slate-800 hover:bg-slate-800/50 transition">
<td class="p-3 text-slate-400 font-mono text-xs">${date}</td>
<td class="p-3 text-center">${sourceIcon}</td>
<td class="p-3">
${renderCampaignBadge(leadData)}
</td>
<td class="p-3 font-medium text-white" title="Leaddetails ansehen">${lead.first_name || '-'}</td>
<td class="p-3 font-medium text-white" title="Leaddetails ansehen">${lead.last_name || '-'}</td>
<td class="p-3 text-slate-400">${lead.phone || '-'}</td>
<td class="p-3">
<button onclick="openScoutModal('${lead.scout_id}')" title="Scoutdetails ansehen" class="px-2 py-1 bg-blue-900/30 text-blue-400 rounded text-xs border border-blue-500/20 hover:bg-blue-900/50 transition cursor-pointer">
${lead.scout_name}
</button>
</td>
</tr>
`;
tbody.innerHTML += row;
});
}
function filterLeads(query) {
const term = query.toLowerCase();
const filtered = allLeads.filter(l =>
(l.first_name && l.first_name.toLowerCase().includes(term)) ||
(l.last_name && l.last_name.toLowerCase().includes(term)) ||
(l.scout_name && l.scout_name.toLowerCase().includes(term))
);
renderLeadsTable(filtered);
}
function renderLeaderboard(data, totalLeads) {
const tbody = document.getElementById('leaderboard-body');
tbody.innerHTML = '';
if (data.length === 0) {
tbody.innerHTML = '<tr><td colspan="4" class="p-4 text-center text-slate-500">Noch keine Daten</td></tr>';
return;
}
data.forEach((item, index) => {
let badge = '';
if (index === 0) badge = '🥇';
if (index === 1) badge = '🥈';
if (index === 2) badge = '🥉';
const share = totalLeads > 0 ? ((item.leads / totalLeads) * 100).toFixed(0) : 0;
const row = `
<tr onclick="openScoutModal('${item.id}')" title="Scoutdetails ansehen" class="border-b border-slate-800 hover:bg-slate-800/50 transition cursor-pointer group">
<td class="p-4 font-bold text-slate-400 group-hover:text-white transition">${index + 1}.</td>
<td class="p-4 font-semibold group-hover:text-blue-400 transition">${badge} ${item.name}</td>
<td class="p-4 text-right font-mono text-blue-400">${item.leads}</td>
<td class="p-4 text-right">
<div class="w-full bg-slate-700 rounded-full h-1.5 mt-2">
<div class="bg-blue-500 h-1.5 rounded-full" style="width: ${share}%"></div>
</div>
</td>
</tr>
`;
tbody.innerHTML += row;
});
}
function renderFeed(items) {
const container = document.getElementById('activity-feed');
container.innerHTML = '';
items.forEach(item => {
const time = item.timestamp.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
let iconClass = 'fa-solid fa-circle text-slate-600';
let bgClass = 'bg-slate-800';
let borderClass = 'border-slate-700';
let label = item.details;
// --- NEW ICON LOGIC ---
switch(item.type) {
case 'page_view':
iconClass = 'fa-solid fa-eye text-blue-400';
label = 'Seite besucht';
break;
case 'share_whatsapp':
iconClass = 'fa-brands fa-whatsapp text-yellow-500'; // Yellow as requested (or strictly brand color)
label = 'Teilen gestartet (WhatsApp)';
break;
case 'conversion':
iconClass = 'fa-solid fa-check-circle text-green-500';
const convName = (item.meta && item.meta.conversion_name) ? item.meta.conversion_name : 'Conversion';
label = `Conversion: <span class="text-green-300">${convName}</span>`;
bgClass = 'bg-green-900/10';
borderClass = 'border-green-500/20';
break;
case 'lead':
iconClass = 'fa-solid fa-fire text-orange-500';
bgClass = 'bg-orange-900/10';
borderClass = 'border-orange-500/20';
break;
case 'share_copy':
iconClass = 'fa-solid fa-copy text-indigo-400';
label = 'Link kopiert';
break;
case 'save_link':
iconClass = 'fa-solid fa-floppy-disk text-purple-400';
label = 'Dashboard gespeichert';
break;
}
const el = `
<div class="flex items-start gap-4 p-3 rounded-lg border ${borderClass} ${bgClass}">
<div class="mt-1"><i class="${iconClass} text-lg"></i></div>
<div class="flex-1 min-w-0">
<div class="flex items-center justify-between mb-0.5">
<span class="text-xs font-mono text-slate-500">${time}</span>
<span class="text-xs font-bold text-slate-400">${item.scout}</span>
</div>
<div class="text-sm font-medium text-slate-200 break-words">
${label}
${ renderCampaignBadge(item.meta) }
</div>
</div>
</div>
`;
container.innerHTML += el;
});
}
// --- FILTER HELPERS ---
let activeCampaignFilter = null;
function renderCampaignFilter(leads) {
const container = document.getElementById('campaign-filter-container');
const campaigns = new Set();
leads.forEach(l => {
let data = l.lead_data;
if (typeof data === 'string') try { data = JSON.parse(data); } catch(e){}
if (data && (data.campaign || data.utm_campaign)) {
campaigns.add(data.campaign || data.utm_campaign);
}
});
if (campaigns.size === 0) {
container.classList.add('hidden');
return;
}
container.classList.remove('hidden');
container.innerHTML = '';
// 'All' Button
const allBtn = document.createElement('button');
allBtn.className = `px-3 py-1 rounded text-xs border font-medium transition ${activeCampaignFilter === null ? 'bg-blue-600 border-blue-500 text-white' : 'bg-slate-800 border-slate-700 text-slate-400 hover:text-white'}`;
allBtn.textContent = 'Alle';
allBtn.onclick = () => setCampaignFilter(null);
container.appendChild(allBtn);
campaigns.forEach(camp => {
const btn = document.createElement('button');
btn.className = `px-3 py-1 rounded text-xs border font-medium transition uppercase ${activeCampaignFilter === camp ? 'bg-indigo-600 border-indigo-500 text-white' : 'bg-slate-800 border-slate-700 text-slate-400 hover:text-white'}`;
btn.textContent = camp;
btn.onclick = () => setCampaignFilter(camp);
container.appendChild(btn);
});
}
function setCampaignFilter(camp) {
activeCampaignFilter = camp;
// Re-render buttons to update active state
renderCampaignFilter(allLeads);
// Filter Leads
if (!camp) {
renderLeadsTable(allLeads);
} else {
const filtered = allLeads.filter(l => {
let data = l.lead_data;
if (typeof data === 'string') try { data = JSON.parse(data); } catch(e){}
return data && (data.campaign === camp || data.utm_campaign === camp);
});
renderLeadsTable(filtered);
}
}
// Helper
function renderCampaignBadge(meta) {
if (!meta || (!meta.campaign && !meta.utm_campaign)) return '';
const camp = meta.campaign || meta.utm_campaign;
// Removed "Via " and added click handler
return `<span onclick="event.stopPropagation(); openCampaignModal('${camp}')" class="inline-block px-1.5 py-0.5 text-[10px] uppercase font-bold tracking-wider rounded border border-indigo-500/30 bg-indigo-500/20 text-indigo-300 cursor-pointer hover:bg-indigo-500/40 hover:text-white transition">
${camp}
</span>`;
}
</script>
</body>
</html>