-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathadmin.html
More file actions
971 lines (819 loc) · 33.4 KB
/
Copy pathadmin.html
File metadata and controls
971 lines (819 loc) · 33.4 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
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Admin - Handball Tracker</title>
<link rel="preload" href="fonts/manrope-400-latin.woff2" as="font" type="font/woff2" crossorigin>
<link rel="stylesheet" href="fonts.css">
<script src="https://cdn.jsdelivr.net/npm/@supabase/supabase-js@2"></script>
<link rel="stylesheet" href="polish-theme.css">
<style>
body {
font-family: 'Manrope', sans-serif;
background: var(--bg);
color: var(--text);
margin: 0;
padding: 20px;
}
.container {
max-width: 1200px;
margin: 0 auto;
}
h1 {
color: var(--text);
margin-bottom: 8px;
}
.subtitle {
color: var(--muted);
margin-bottom: 32px;
}
.section {
background: var(--surface);
border-radius: 12px;
padding: 24px;
margin-bottom: 24px;
}
.section-title {
font-size: 18px;
font-weight: 700;
margin-bottom: 16px;
display: flex;
align-items: center;
gap: 8px;
}
table {
width: 100%;
border-collapse: collapse;
}
th {
text-align: left;
padding: 12px;
border-bottom: 2px solid var(--border);
font-weight: 600;
font-size: 13px;
color: var(--muted);
text-transform: uppercase;
}
td {
padding: 12px;
border-bottom: 1px solid var(--border);
}
.badge {
display: inline-block;
padding: 4px 8px;
border-radius: 4px;
font-size: 12px;
font-weight: 600;
}
.badge-pending { background: #FCD34D; color: #78350F; }
.badge-approved { background: #22C55E; color: #065F46; }
.badge-rejected { background: #EF4444; color: #7F1D1D; }
.badge-active { background: #22C55E; color: #065F46; }
.badge-inactive { background: #6B7280; color: #F9FAFB; }
.btn {
padding: 6px 12px;
border-radius: 6px;
font-size: 13px;
font-weight: 600;
cursor: pointer;
border: none;
transition: all 0.2s;
}
.btn-primary {
background: var(--accent);
color: white;
}
.btn-primary:hover {
background: #6B4CE0;
}
.btn-success {
background: #22C55E;
color: white;
}
.btn-success:hover {
background: #16A34A;
}
.btn-danger {
background: #EF4444;
color: white;
}
.btn-danger:hover {
background: #DC2626;
}
.btn-secondary {
background: transparent;
color: var(--text);
border: 1px solid var(--border);
}
.btn-secondary:hover {
border-color: var(--accent);
color: var(--accent);
}
.form-group {
margin-bottom: 16px;
}
label {
display: block;
margin-bottom: 6px;
font-weight: 600;
font-size: 14px;
}
input, select {
width: 100%;
padding: 10px 12px;
background: var(--bg);
border: 1px solid var(--border);
border-radius: 6px;
color: var(--text);
font-size: 14px;
font-family: inherit;
}
.empty-state {
text-align: center;
padding: 40px;
color: var(--muted);
}
.code-display {
background: var(--bg);
padding: 12px;
border-radius: 6px;
font-family: 'Courier New', monospace;
font-size: 16px;
font-weight: 700;
color: var(--accent);
text-align: center;
margin: 16px 0;
}
.progress-bar {
height: 6px;
background: var(--border);
border-radius: 3px;
overflow: hidden;
margin-top: 8px;
}
.progress-fill {
height: 100%;
background: var(--accent);
transition: width 0.3s;
}
.warning { color: #F59E0B; }
.danger { color: #EF4444; }
</style>
</head>
<body>
<div class="container">
<h1>🔐 Handball Tracker Admin</h1>
<p class="subtitle">Manage invite codes, access requests, and club subscriptions</p>
<!-- Pending Access Requests -->
<div class="section">
<div class="section-title">
🎟️ Pending Access Requests
<button class="btn btn-secondary" onclick="loadAccessRequests()" style="margin-left: auto;">↻ Refresh</button>
</div>
<div id="accessRequestsTable"></div>
</div>
<!-- Generate New Invite Code -->
<div class="section">
<div class="section-title">➕ Generate New Invite Code</div>
<div style="display: grid; grid-template-columns: 1fr 1fr; gap: 16px;">
<div>
<div class="form-group">
<label>Code Type</label>
<select id="codeType" onchange="toggleCodeForm()">
<option value="club">Club Code</option>
<option value="personal">Personal Code</option>
</select>
</div>
<div id="clubForm">
<div class="form-group">
<label>Club Name *</label>
<input type="text" id="clubName" placeholder="Ajax Youth Team">
</div>
<div class="form-group">
<label>Plan Name</label>
<select id="planName">
<option value="Small">Small (10 users)</option>
<option value="Medium">Medium (20 users)</option>
<option value="Large">Large (50 users)</option>
</select>
</div>
<div class="form-group">
<label>Max Users</label>
<input type="number" id="maxUsers" value="10">
</div>
<div class="form-group">
<label>Contact Email *</label>
<input type="email" id="contactEmail" placeholder="coach@club.com">
</div>
<div class="form-group">
<label>Contact Name</label>
<input type="text" id="contactName" placeholder="Coach Name">
</div>
<div class="form-group">
<label>Price per Month (€)</label>
<input type="number" id="pricePerMonth" value="20" step="0.01">
</div>
</div>
<div class="form-group">
<label>Invite Code *</label>
<input type="text" id="inviteCode" placeholder="CLUB-AJAX-2024" style="text-transform: uppercase;">
<button class="btn btn-secondary" onclick="generateRandomCode()" style="margin-top: 8px; width: 100%;">
🎲 Generate Random Code
</button>
</div>
<div class="form-group">
<label>Max Uses</label>
<input type="number" id="maxUses" value="10">
</div>
<div class="form-group">
<label>Login Limit (optional)</label>
<input type="number" id="loginLimit" placeholder="e.g. 5 or 10 — blank = unlimited">
<div style="font-size:12px;color:var(--muted);margin-top:4px">
Accounts created with this code get locked out after this many sign-ins, until marked paid in Trial Users below.
</div>
</div>
<div class="form-group">
<label>Expires At (optional)</label>
<input type="date" id="expiresAt">
</div>
</div>
<div>
<div style="background: var(--bg); padding: 20px; border-radius: 8px; height: 100%;">
<h3 style="margin-top: 0;">Preview</h3>
<div id="codePreview"></div>
<button class="btn btn-primary" onclick="createInviteCode()" style="width: 100%; margin-top: 16px;">
✓ Create Invite Code
</button>
</div>
</div>
</div>
</div>
<!-- Active Invite Codes -->
<div class="section">
<div class="section-title">
🔑 Active Invite Codes
<button class="btn btn-secondary" onclick="loadInviteCodes()" style="margin-left: auto;">↻ Refresh</button>
</div>
<div id="inviteCodesTable"></div>
</div>
<!-- Club Subscriptions -->
<div class="section">
<div class="section-title">
🏢 Club Subscriptions
<button class="btn btn-secondary" onclick="loadSubscriptions()" style="margin-left: auto;">↻ Refresh</button>
</div>
<div id="subscriptionsTable"></div>
</div>
<!-- Trial Users -->
<div class="section">
<div class="section-title">
👤 Trial Users
<button class="btn btn-secondary" onclick="loadUsers()" style="margin-left: auto;">↻ Refresh</button>
</div>
<div id="usersTable"></div>
</div>
</div>
<script>
const SUPABASE_URL = 'https://qgqryeanopdxrwrfczcx.supabase.co';
const SUPABASE_KEY = 'sb_publishable_I67bdwmAkdodIk5bAQf1Zw_86KroW5R';
const _supabase = supabase.createClient(SUPABASE_URL, SUPABASE_KEY);
// Only this account may use the admin panel. This is enforced for real by
// the RLS policies in Supabase; the checks below are just the matching UX.
const ADMIN_EMAIL = 'jeremybekkers@icloud.com';
let currentUser = null;
// Check authentication on page load
async function checkAuth() {
const { data: { session } } = await _supabase.auth.getSession();
if (!session) {
// Not logged in - show an inline sign-in form.
renderAdminLogin();
return false;
}
currentUser = session.user;
// Check if user is admin (ADMIN_EMAIL)
if (currentUser.email !== ADMIN_EMAIL) {
document.body.innerHTML = `
<div style="
display: flex;
align-items: center;
justify-content: center;
min-height: 100vh;
background: var(--bg);
color: var(--text);
text-align: center;
padding: 20px;
">
<div style="max-width: 500px;">
<h1 style="font-size: 48px; margin-bottom: 16px;">⛔</h1>
<h2 style="margin-bottom: 8px;">Access Denied</h2>
<p style="color: var(--muted); margin-bottom: 24px;">
You are signed in as: <strong>${currentUser.email}</strong>
</p>
<p style="color: var(--muted); margin-bottom: 24px;">
This admin panel is restricted to authorized administrators only.
</p>
<button onclick="signOut()" style="
background: var(--accent);
color: white;
padding: 12px 24px;
border-radius: 6px;
border: none;
font-weight: 600;
cursor: pointer;
margin-right: 8px;
">Sign Out</button>
<a href="index.html" style="
display: inline-block;
background: transparent;
color: var(--text);
padding: 12px 24px;
border-radius: 6px;
text-decoration: none;
font-weight: 600;
border: 1px solid var(--border);
">Back to App</a>
</div>
</div>
`;
return false;
}
// Show user info
document.querySelector('h1').innerHTML = `🔐 Handball Tracker Admin <small style="font-size:14px;color:var(--muted);font-weight:400;">(${currentUser.email}) <a href="#" onclick="signOut()" style="color:var(--red);text-decoration:none;margin-left:12px;">Sign Out</a></small>`;
return true;
}
function renderAdminLogin() {
document.body.innerHTML = `
<div style="display:flex;align-items:center;justify-content:center;min-height:100vh;background:var(--bg);color:var(--text);padding:20px;">
<form id="adminLoginForm" style="max-width:360px;width:100%;background:var(--surface);padding:32px;border-radius:12px;box-sizing:border-box;">
<h1 style="font-size:44px;text-align:center;margin:0 0 8px;">🔐</h1>
<h2 style="text-align:center;margin:0 0 4px;">Admin Sign In</h2>
<p style="color:var(--muted);text-align:center;margin:0 0 24px;font-size:14px;">Handball Tracker admin panel</p>
<div id="adminLoginError" style="display:none;background:#7F1D1D;color:#FCA5A5;padding:10px 12px;border-radius:6px;font-size:13px;margin-bottom:16px;"></div>
<div style="margin-bottom:16px;">
<label for="adminEmail" style="display:block;margin-bottom:6px;font-weight:600;font-size:14px;">Email</label>
<input type="email" id="adminEmail" autocomplete="username" style="width:100%;padding:10px 12px;background:var(--bg);border:1px solid var(--border);border-radius:6px;color:var(--text);font-size:14px;box-sizing:border-box;">
</div>
<div style="margin-bottom:20px;">
<label for="adminPassword" style="display:block;margin-bottom:6px;font-weight:600;font-size:14px;">Password</label>
<input type="password" id="adminPassword" autocomplete="current-password" style="width:100%;padding:10px 12px;background:var(--bg);border:1px solid var(--border);border-radius:6px;color:var(--text);font-size:14px;box-sizing:border-box;">
</div>
<button type="submit" id="adminLoginBtn" style="width:100%;background:var(--accent);color:white;padding:12px;border:none;border-radius:6px;font-weight:600;font-size:15px;cursor:pointer;">Sign In</button>
</form>
</div>
`;
document.getElementById('adminLoginForm').addEventListener('submit', adminSignIn);
document.getElementById('adminEmail').focus();
}
function showAdminLoginError(msg) {
const el = document.getElementById('adminLoginError');
if (!el) return;
el.textContent = msg;
el.style.display = 'block';
}
async function adminSignIn(e) {
e.preventDefault();
const email = document.getElementById('adminEmail').value.trim();
const password = document.getElementById('adminPassword').value;
const btn = document.getElementById('adminLoginBtn');
if (!email || !password) {
showAdminLoginError('Please enter your email and password.');
return;
}
btn.disabled = true;
btn.textContent = 'Signing in…';
const { data, error } = await _supabase.auth.signInWithPassword({ email, password });
if (error) {
showAdminLoginError(error.message || 'Sign in failed.');
btn.disabled = false;
btn.textContent = 'Sign In';
return;
}
// Enforce admin-only access before revealing the panel. Non-admins are
// signed straight back out. (RLS also blocks them at the data layer.)
if (data.user.email !== ADMIN_EMAIL) {
await _supabase.auth.signOut();
showAdminLoginError('This account is not authorized for the admin panel.');
btn.disabled = false;
btn.textContent = 'Sign In';
return;
}
window.location.reload();
}
async function signOut() {
await _supabase.auth.signOut();
window.location.reload();
}
window.signOut = signOut;
// Load all data on page load
window.addEventListener('DOMContentLoaded', async () => {
const authenticated = await checkAuth();
if (!authenticated) return;
loadAccessRequests();
loadInviteCodes();
loadSubscriptions();
loadUsers();
updateCodePreview();
// Set default expiry to 1 year from now
const oneYearFromNow = new Date();
oneYearFromNow.setFullYear(oneYearFromNow.getFullYear() + 1);
document.getElementById('expiresAt').value = oneYearFromNow.toISOString().split('T')[0];
// Auto-update preview when fields change
['clubName', 'planName', 'maxUsers', 'contactEmail', 'inviteCode', 'maxUses', 'loginLimit', 'codeType'].forEach(id => {
const el = document.getElementById(id);
if (el) el.addEventListener('input', updateCodePreview);
if (el) el.addEventListener('change', updateCodePreview);
});
});
function toggleCodeForm() {
const type = document.getElementById('codeType').value;
document.getElementById('clubForm').style.display = type === 'club' ? 'block' : 'none';
if (type === 'personal') {
document.getElementById('maxUses').value = 1;
} else {
document.getElementById('maxUses').value = 10;
}
updateCodePreview();
}
function generateRandomCode() {
const type = document.getElementById('codeType').value;
const clubName = document.getElementById('clubName').value.trim();
let code;
if (type === 'personal') {
const random = Math.random().toString(36).substring(2, 8).toUpperCase();
code = `PERSONAL-2024-${random}`;
} else if (clubName) {
const cleanName = clubName.replace(/\s+/g, '-').toUpperCase();
const random = Math.random().toString(36).substring(2, 5).toUpperCase();
code = `${cleanName}-2024-${random}`;
} else {
const random = Math.random().toString(36).substring(2, 10).toUpperCase();
code = `CLUB-2024-${random}`;
}
document.getElementById('inviteCode').value = code;
updateCodePreview();
}
function updateCodePreview() {
const type = document.getElementById('codeType').value;
const code = document.getElementById('inviteCode').value.trim().toUpperCase();
const maxUses = document.getElementById('maxUses').value;
const loginLimit = document.getElementById('loginLimit').value;
let html = '<div class="code-display">' + (code || 'CODE-PREVIEW') + '</div>';
html += '<p><strong>Type:</strong> ' + (type === 'club' ? '🏢 Club' : '👤 Personal') + '</p>';
html += '<p><strong>Max Uses:</strong> ' + maxUses + '</p>';
html += '<p><strong>Login Limit:</strong> ' + (loginLimit || 'Unlimited') + '</p>';
if (type === 'club') {
const clubName = document.getElementById('clubName').value || 'Club Name';
const plan = document.getElementById('planName').value || 'Small';
const maxUsers = document.getElementById('maxUsers').value || '10';
html += '<p><strong>Club:</strong> ' + clubName + '</p>';
html += '<p><strong>Plan:</strong> ' + plan + ' (' + maxUsers + ' users)</p>';
}
document.getElementById('codePreview').innerHTML = html;
}
async function loadAccessRequests() {
const { data, error } = await _supabase
.from('access_requests')
.select('*')
.order('created_at', { ascending: false });
if (error) {
console.error('Error loading access requests:', error);
return;
}
const container = document.getElementById('accessRequestsTable');
if (!data || data.length === 0) {
container.innerHTML = '<div class="empty-state">No pending access requests</div>';
return;
}
let html = '<table><thead><tr><th>Name</th><th>Email</th><th>Phone</th><th>Message</th><th>Status</th><th>Date</th><th>Actions</th></tr></thead><tbody>';
data.forEach(req => {
const date = new Date(req.created_at).toLocaleDateString();
const statusClass = req.status === 'pending' ? 'badge-pending' :
req.status === 'approved' ? 'badge-approved' : 'badge-rejected';
html += `
<tr>
<td><strong>${req.name}</strong></td>
<td>${req.email}</td>
<td>${req.phone || '-'}</td>
<td>${req.message || '-'}</td>
<td><span class="badge ${statusClass}">${req.status}</span></td>
<td>${date}</td>
<td>
${req.status === 'pending' ? `
<button class="btn btn-success" onclick="approveRequest('${req.id}', '${req.email}')">✓ Approve</button>
<button class="btn btn-danger" onclick="rejectRequest('${req.id}')">✗ Reject</button>
` : req.invite_code_generated ? `
<div class="code-display" style="margin: 0; padding: 6px; font-size: 12px;">${req.invite_code_generated}</div>
` : '-'}
</td>
</tr>
`;
});
html += '</tbody></table>';
container.innerHTML = html;
}
async function approveRequest(requestId, email) {
// Generate a unique personal code
const random = Math.random().toString(36).substring(2, 8).toUpperCase();
const code = `PERSONAL-2024-${random}`;
try {
// Create invite code
const { error: codeError } = await _supabase.from('invite_codes').insert({
code: code,
club_name: 'Personal User',
plan_type: 'personal',
max_uses: 1,
expires_at: new Date(Date.now() + 365 * 24 * 60 * 60 * 1000).toISOString()
});
if (codeError) throw codeError;
// Update request status
const { error: updateError } = await _supabase
.from('access_requests')
.update({
status: 'approved',
invite_code_generated: code,
processed_at: new Date().toISOString()
})
.eq('id', requestId);
if (updateError) throw updateError;
alert(`✓ Request approved!\n\nGenerated code: ${code}\n\nPlease email this code to: ${email}`);
loadAccessRequests();
loadInviteCodes();
} catch (error) {
console.error('Error approving request:', error);
alert('Failed to approve request: ' + error.message);
}
}
async function rejectRequest(requestId) {
if (!confirm('Are you sure you want to reject this request?')) return;
const { error } = await _supabase
.from('access_requests')
.update({
status: 'rejected',
processed_at: new Date().toISOString()
})
.eq('id', requestId);
if (error) {
console.error('Error rejecting request:', error);
alert('Failed to reject request');
return;
}
alert('Request rejected');
loadAccessRequests();
}
async function createInviteCode() {
const type = document.getElementById('codeType').value;
const code = document.getElementById('inviteCode').value.trim().toUpperCase();
const maxUses = parseInt(document.getElementById('maxUses').value);
const loginLimitRaw = document.getElementById('loginLimit').value;
const loginLimit = loginLimitRaw ? parseInt(loginLimitRaw) : null;
const expiresAt = document.getElementById('expiresAt').value;
if (!code) {
alert('Please enter an invite code');
return;
}
try {
// If club type, create subscription first
if (type === 'club') {
const clubName = document.getElementById('clubName').value.trim();
const planName = document.getElementById('planName').value;
const maxUsers = parseInt(document.getElementById('maxUsers').value);
const contactEmail = document.getElementById('contactEmail').value.trim();
const contactName = document.getElementById('contactName').value.trim();
const pricePerMonth = parseFloat(document.getElementById('pricePerMonth').value);
if (!clubName || !contactEmail) {
alert('Please fill in club name and contact email');
return;
}
// Create subscription
const { error: subError } = await _supabase.from('club_subscriptions').insert({
club_name: clubName,
plan_name: planName,
max_users: maxUsers,
contact_email: contactEmail,
contact_name: contactName,
price_per_month: pricePerMonth,
status: 'active'
});
// Ignore duplicate error
if (subError && !subError.message.includes('duplicate')) {
throw subError;
}
}
// Create invite code
const { error: codeError } = await _supabase.from('invite_codes').insert({
code: code,
club_name: type === 'club' ? document.getElementById('clubName').value.trim() : 'Personal User',
plan_type: type,
max_uses: maxUses,
login_limit: loginLimit,
expires_at: expiresAt ? new Date(expiresAt).toISOString() : null
});
if (codeError) throw codeError;
alert(`✓ Invite code created successfully!\n\nCode: ${code}\nMax uses: ${maxUses}\nLogin limit: ${loginLimit || 'Unlimited'}`);
document.getElementById('inviteCode').value = '';
document.getElementById('clubName').value = '';
document.getElementById('contactEmail').value = '';
document.getElementById('contactName').value = '';
document.getElementById('loginLimit').value = '';
loadInviteCodes();
loadSubscriptions();
updateCodePreview();
} catch (error) {
console.error('Error creating invite code:', error);
alert('Failed to create invite code: ' + error.message);
}
}
async function loadInviteCodes() {
const { data, error } = await _supabase
.from('invite_codes')
.select('*')
.order('created_at', { ascending: false });
if (error) {
console.error('Error loading invite codes:', error);
return;
}
const container = document.getElementById('inviteCodesTable');
if (!data || data.length === 0) {
container.innerHTML = '<div class="empty-state">No invite codes yet</div>';
return;
}
let html = '<table><thead><tr><th>Code</th><th>Club</th><th>Type</th><th>Usage</th><th>Login Limit</th><th>Expires</th><th>Status</th><th>Actions</th></tr></thead><tbody>';
data.forEach(code => {
const usagePercent = Math.round((code.uses_count / code.max_uses) * 100);
const expired = code.expires_at && new Date(code.expires_at) < new Date();
const expiryDate = code.expires_at ? new Date(code.expires_at).toLocaleDateString() : 'Never';
let usageClass = '';
if (usagePercent >= 100) usageClass = 'danger';
else if (usagePercent >= 80) usageClass = 'warning';
html += `
<tr>
<td><strong style="font-family: monospace;">${code.code}</strong></td>
<td>${code.club_name}</td>
<td><span class="badge ${code.plan_type === 'club' ? 'badge-approved' : 'badge-pending'}">${code.plan_type}</span></td>
<td>
<span class="${usageClass}">${code.uses_count} / ${code.max_uses} (${usagePercent}%)</span>
<div class="progress-bar">
<div class="progress-fill" style="width: ${usagePercent}%"></div>
</div>
</td>
<td>${code.login_limit ? code.login_limit + ' logins' : 'Unlimited'}</td>
<td>${expiryDate}${expired ? ' <span class="danger">⚠️</span>' : ''}</td>
<td>
<span class="badge ${code.active ? 'badge-active' : 'badge-inactive'}">${code.active ? 'Active' : 'Inactive'}</span>
${!code.active && code.deactivated_at ? `<div style="font-size:11px;color:var(--muted);margin-top:4px;">${daysUntilAutoDelete(code.deactivated_at)}</div>` : ''}
</td>
<td>
${code.active ? `
<button class="btn btn-danger" onclick="deactivateCode('${code.id}')">Deactivate</button>
` : `
<button class="btn btn-success" onclick="activateCode('${code.id}')">Activate</button>
<button class="btn btn-danger" onclick="deleteInviteCode('${code.id}', '${code.code}')">🗑 Delete</button>
`}
</td>
</tr>
`;
});
html += '</tbody></table>';
container.innerHTML = html;
}
function daysUntilAutoDelete(deactivatedAt) {
const daysInactive = Math.floor((Date.now() - new Date(deactivatedAt).getTime()) / (1000 * 60 * 60 * 24));
const daysLeft = Math.max(0, 30 - daysInactive);
return daysLeft === 0 ? 'auto-deletes soon' : `auto-deletes in ${daysLeft}d`;
}
async function deleteInviteCode(codeId, codeText) {
if (!confirm(`Permanently delete invite code "${codeText}"? This can't be undone.`)) return;
// Guard: only ever deletes if the code is still inactive, even if the
// button was clicked from a stale view of the table.
const { error, count } = await _supabase
.from('invite_codes')
.delete({ count: 'exact' })
.eq('id', codeId)
.eq('active', false);
if (error) {
alert('Failed to delete invite code: ' + error.message);
return;
}
if (!count) {
alert('This code is active — deactivate it first, then delete it.');
}
loadInviteCodes();
}
async function deactivateCode(codeId) {
if (!confirm('Deactivate this invite code? Users won\'t be able to use it anymore.')) return;
const { error } = await _supabase
.from('invite_codes')
.update({ active: false })
.eq('id', codeId);
if (error) {
alert('Failed to deactivate code');
return;
}
loadInviteCodes();
}
async function activateCode(codeId) {
const { error } = await _supabase
.from('invite_codes')
.update({ active: true })
.eq('id', codeId);
if (error) {
alert('Failed to activate code');
return;
}
loadInviteCodes();
}
async function loadSubscriptions() {
const { data, error } = await _supabase
.from('club_subscriptions')
.select('*')
.order('created_at', { ascending: false });
if (error) {
console.error('Error loading subscriptions:', error);
return;
}
const container = document.getElementById('subscriptionsTable');
if (!data || data.length === 0) {
container.innerHTML = '<div class="empty-state">No club subscriptions yet</div>';
return;
}
let html = '<table><thead><tr><th>Club</th><th>Plan</th><th>Users</th><th>Contact</th><th>Price</th><th>Status</th></tr></thead><tbody>';
data.forEach(sub => {
const usagePercent = Math.round((sub.current_users / sub.max_users) * 100);
let usageClass = '';
if (usagePercent >= 100) usageClass = 'danger';
else if (usagePercent >= 80) usageClass = 'warning';
html += `
<tr>
<td><strong>${sub.club_name}</strong></td>
<td>${sub.plan_name}</td>
<td>
<span class="${usageClass}">${sub.current_users} / ${sub.max_users} (${usagePercent}%)</span>
<div class="progress-bar">
<div class="progress-fill" style="width: ${usagePercent}%"></div>
</div>
</td>
<td>
${sub.contact_name || '-'}<br>
<small style="color: var(--muted);">${sub.contact_email}</small>
</td>
<td>€${sub.price_per_month}/mo</td>
<td><span class="badge ${sub.status === 'active' ? 'badge-active' : 'badge-inactive'}">${sub.status}</span></td>
</tr>
`;
});
html += '</tbody></table>';
container.innerHTML = html;
}
async function loadUsers() {
const { data, error } = await _supabase
.from('profiles')
.select('*')
.order('login_count', { ascending: false });
if (error) {
console.error('Error loading users:', error);
return;
}
const container = document.getElementById('usersTable');
if (!data || data.length === 0) {
container.innerHTML = '<div class="empty-state">No users yet</div>';
return;
}
let html = '<table><thead><tr><th>Email</th><th>Team</th><th>Logins</th><th>Status</th><th>Actions</th></tr></thead><tbody>';
data.forEach(profile => {
const hasLimit = profile.login_limit !== null && profile.login_limit !== undefined;
const capped = !profile.is_paid && hasLimit && profile.login_count >= profile.login_limit;
const loginsText = hasLimit ? `${profile.login_count} / ${profile.login_limit}` : `${profile.login_count} (unlimited)`;
html += `
<tr>
<td>${profile.email || '-'}</td>
<td>${profile.team_name || '-'}</td>
<td><span class="${capped ? 'danger' : ''}">${loginsText}</span></td>
<td><span class="badge ${profile.is_paid ? 'badge-active' : (capped ? 'badge-rejected' : 'badge-pending')}">${profile.is_paid ? 'Paid' : (capped ? 'Trial ended' : 'Trial')}</span></td>
<td>
${profile.is_paid ? `
<button class="btn btn-secondary" onclick="togglePaid('${profile.id}', false)">Revert to Trial</button>
` : `
<button class="btn btn-success" onclick="togglePaid('${profile.id}', true)">✓ Upgrade to Paid</button>
`}
</td>
</tr>
`;
});
html += '</tbody></table>';
container.innerHTML = html;
}
async function togglePaid(userId, isPaid) {
const { error } = await _supabase
.from('profiles')
.update({ is_paid: isPaid })
.eq('id', userId);
if (error) {
alert('Failed to update user: ' + error.message);
return;
}
loadUsers();
}
</script>
</body>
</html>