Repository navigation
Expand file tree
/
Copy pathenhanced_template.html
More file actions
1307 lines (1154 loc) · 61.5 KB
/
Copy pathenhanced_template.html
File metadata and controls
1307 lines (1154 loc) · 61.5 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
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>OpenAI API Usage Dashboard</title>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); min-height: 100vh; padding: 20px; }
.container { max-width: 1400px; margin: 0 auto; }
.header { text-align: center; color: white; margin-bottom: 30px; }
.header h1 { font-size: 2.5rem; margin-bottom: 10px; text-shadow: 0 2px 4px rgba(0,0,0,0.3); }
.header p { font-size: 1.1rem; opacity: 0.9; }
.dashboard { background: white; border-radius: 12px; box-shadow: 0 20px 40px rgba(0,0,0,0.1); padding: 30px; margin-bottom: 20px; }
/* Navigation Tabs */
.nav-tabs { display: flex; gap: 0; margin-bottom: 30px; border-bottom: 1px solid #e5e7eb; }
.nav-tab { background: none; border: none; padding: 12px 24px; font-weight: 600; cursor: pointer; border-bottom: 3px solid transparent; transition: all 0.3s ease; }
.nav-tab.active { color: #667eea; border-bottom-color: #667eea; }
.nav-tab:hover { background: #f8fafc; }
/* Tab Content */
.tab-content { display: none; }
.tab-content.active { display: block; }
/* Account Management */
.account-section { background: #f8fafc; border: 1px solid #e2e8f0; border-radius: 8px; padding: 20px; margin-bottom: 30px; }
.account-section h3 { color: #1f2937; margin-bottom: 15px; display: flex; align-items: center; gap: 10px; }
.account-list { display: grid; gap: 10px; margin-bottom: 20px; }
.account-item { display: flex; align-items: center; justify-content: space-between; background: white; padding: 15px; border-radius: 6px; border: 1px solid #e5e7eb; }
.account-info { flex: 1; }
.account-email { font-weight: 600; color: #1f2937; }
.account-details { font-size: 12px; color: #6b7280; margin-top: 4px; }
.account-actions { display: flex; gap: 8px; }
/* Key Management */
.key-management { background: #f8fafc; border: 1px solid #e2e8f0; border-radius: 8px; padding: 20px; margin-bottom: 30px; }
.key-management h3 { color: #1f2937; margin-bottom: 15px; display: flex; align-items: center; gap: 10px; }
.key-list { display: grid; gap: 10px; margin-bottom: 20px; }
.key-item { display: flex; align-items: center; justify-content: space-between; background: white; padding: 15px; border-radius: 6px; border: 1px solid #e5e7eb; }
.key-info { flex: 1; }
.key-name { font-weight: 600; color: #1f2937; }
.key-display { font-family: monospace; font-size: 12px; color: #6b7280; margin-top: 4px; }
.key-metadata { font-size: 11px; color: #9ca3af; margin-top: 2px; }
.key-actions { display: flex; gap: 8px; }
.key-type-badge { padding: 2px 8px; border-radius: 12px; font-size: 10px; font-weight: 600; text-transform: uppercase; }
.key-type-admin { background: #dcfce7; color: #166534; }
.key-type-project { background: #dbeafe; color: #1d4ed8; }
.provider-badge { padding: 2px 6px; border-radius: 10px; font-size: 9px; font-weight: 600; text-transform: uppercase; margin-left: 4px; }
.provider-openai { background: #dcfce7; color: #166534; }
.provider-anthropic { background: #fef3c7; color: #92400e; }
.provider-brave { background: #e0f2fe; color: #0277bd; }
/* Controls */
.controls { display: flex; gap: 15px; margin-bottom: 30px; flex-wrap: wrap; align-items: end; }
.control-group { flex: 1; min-width: 200px; }
.control-group label { display: block; margin-bottom: 5px; font-weight: 600; color: #374151; }
.control-group input, .control-group select { width: 100%; padding: 10px; border: 2px solid #e5e7eb; border-radius: 6px; font-size: 14px; transition: border-color 0.3s ease; }
.control-group input:focus, .control-group select:focus { outline: none; border-color: #667eea; }
/* Buttons */
.btn { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; border: none; padding: 12px 24px; border-radius: 6px; font-weight: 600; cursor: pointer; transition: transform 0.2s ease; margin-right: 10px; }
.btn:hover { transform: translateY(-2px); }
.btn:disabled { opacity: 0.6; cursor: not-allowed; transform: none; }
.btn-secondary { background: linear-gradient(135deg, #6b7280 0%, #4b5563 100%); }
.btn-danger { background: linear-gradient(135deg, #ef4444 0%, #dc2626 100%); }
.btn-success { background: linear-gradient(135deg, #10b981 0%, #059669 100%); }
.btn-small { padding: 8px 16px; font-size: 12px; }
/* Modal Styles */
.modal-overlay { position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.5); display: flex; align-items: center; justify-content: center; z-index: 1000; opacity: 0; visibility: hidden; transition: all 0.3s ease; }
.modal-overlay.active { opacity: 1; visibility: visible; }
.modal { background: white; border-radius: 12px; padding: 30px; max-width: 600px; width: 90%; max-height: 80vh; overflow-y: auto; transform: translateY(-20px); transition: transform 0.3s ease; position: relative; }
.modal-overlay.active .modal { transform: translateY(0); }
.modal h3 { margin-bottom: 20px; color: #1f2937; }
.modal .form-group { margin-bottom: 20px; }
.modal .form-group label { display: block; margin-bottom: 8px; font-weight: 600; color: #374151; }
.modal .form-group input, .modal .form-group textarea, .modal .form-group select { width: 100%; padding: 12px; border: 2px solid #e5e7eb; border-radius: 6px; font-size: 14px; transition: border-color 0.3s ease; }
.modal .form-group input:focus, .modal .form-group textarea:focus, .modal .form-group select:focus { outline: none; border-color: #667eea; }
.modal .form-group textarea { height: 80px; resize: vertical; font-family: monospace; }
.modal-actions { display: flex; gap: 12px; justify-content: flex-end; margin-top: 30px; }
.modal-close { position: absolute; top: 15px; right: 15px; background: none; border: none; font-size: 24px; cursor: pointer; color: #6b7280; }
.modal-close:hover { color: #374151; }
/* Form validation */
.form-group.error input, .form-group.error textarea, .form-group.error select { border-color: #ef4444; }
.form-error { color: #ef4444; font-size: 12px; margin-top: 4px; }
/* Test Result Styles */
.test-result { margin-top: 15px; padding: 12px; border-radius: 6px; font-size: 14px; }
.test-result.success { background: #dcfce7; color: #166534; border: 1px solid #bbf7d0; }
.test-result.error { background: #fee2e2; color: #991b1b; border: 1px solid #fecaca; }
/* Usage Dashboard Styles */
.api-key-item { background: #f8fafc; border: 1px solid #e2e8f0; border-radius: 8px; padding: 20px; margin-bottom: 20px; position: relative; }
.api-key-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 15px; }
.api-key-name { font-weight: 600; color: #1f2937; font-size: 1.1rem; }
.status-badge { padding: 4px 12px; border-radius: 20px; font-size: 12px; font-weight: 600; text-transform: uppercase; }
.status-active { background: #dcfce7; color: #166534; }
.status-error { background: #fee2e2; color: #991b1b; }
.status-partial { background: #fef3c7; color: #92400e; }
.status-basic { background: #e0f2fe; color: #0277bd; }
.status-info { background: #f3f4f6; color: #374151; }
.status-no-usage { background: #fef2f2; color: #b91c1c; }
.usage-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 15px; margin-top: 15px; }
.usage-card { background: white; padding: 15px; border-radius: 6px; border-left: 4px solid #667eea; }
.usage-card h4 { color: #6b7280; font-size: 12px; font-weight: 600; text-transform: uppercase; margin-bottom: 8px; }
.usage-card .value { font-size: 1.5rem; font-weight: 700; color: #1f2937; }
.usage-card .subtext { font-size: 12px; color: #9ca3af; margin-top: 5px; }
.error-details { background: #fef2f2; border: 1px solid #fecaca; border-radius: 6px; padding: 15px; margin-top: 10px; }
.error-title { font-weight: 600; color: #991b1b; margin-bottom: 8px; display: flex; align-items: center; gap: 8px; }
.error-description { color: #7f1d1d; font-size: 13px; line-height: 1.4; margin-bottom: 10px; }
.error-solutions { background: #fff; border-radius: 4px; padding: 10px; margin-top: 8px; }
.error-solutions h5 { font-size: 12px; font-weight: 600; color: #374151; margin-bottom: 6px; text-transform: uppercase; }
.error-solutions ul { margin-left: 16px; color: #6b7280; font-size: 12px; }
.error-solutions li { margin-bottom: 4px; }
.error-message { background: #fee2e2; color: #991b1b; padding: 15px; border-radius: 6px; margin-top: 10px; font-size: 14px; }
.loading { text-align: center; padding: 40px; color: #6b7280; }
.spinner { border: 3px solid #f3f4f6; border-top: 3px solid #667eea; border-radius: 50%; width: 30px; height: 30px; animation: spin 1s linear infinite; margin: 0 auto 15px; }
@keyframes spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } }
.summary-cards { display: grid; grid-template-columns: repeat(auto-fit, minmax(250px, 1fr)); gap: 20px; margin-bottom: 30px; }
.summary-card { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; padding: 25px; border-radius: 12px; text-align: center; }
.summary-card h3 { font-size: 2rem; margin-bottom: 5px; }
.summary-card p { opacity: 0.9; font-size: 1.1rem; }
.key-display-container { display: flex; align-items: center; gap: 8px; margin-top: 8px; }
.key-display-text { font-family: monospace; font-size: 12px; background: #f1f5f9; padding: 6px 8px; border-radius: 4px; border: 1px solid #e2e8f0; flex: 1; }
.key-toggle-btn { background: #6b7280; color: white; border: none; padding: 4px 8px; border-radius: 4px; font-size: 10px; cursor: pointer; transition: background 0.2s; }
.key-toggle-btn:hover { background: #4b5563; }
.key-copy-btn { background: #10b981; color: white; border: none; padding: 4px 8px; border-radius: 4px; font-size: 10px; cursor: pointer; transition: background 0.2s; }
.key-copy-btn:hover { background: #059669; }
.key-copy-btn:disabled { background: #9ca3af; cursor: not-allowed; }
</style>
</head>
<body>
<div class="container">
<div class="header">
<h1>🔧 API Usage Dashboard</h1>
<p>Real-time monitoring of usage, costs, and limits across multiple API providers</p>
</div>
<div class="dashboard">
<!-- Navigation Tabs -->
<div class="nav-tabs">
<button class="nav-tab active" onclick="switchTab('accounts')">👤 Accounts</button>
<button class="nav-tab" onclick="switchTab('keys')">🔑 API Keys</button>
<button class="nav-tab" onclick="switchTab('usage')">📊 Usage Dashboard</button>
</div>
<!-- Account Management Tab -->
<div id="accounts-tab" class="tab-content active">
<div class="account-section">
<h3>👤 Account Management</h3>
<div id="accountList" class="account-list"></div>
<button class="btn btn-success" onclick="showAddAccountModal()">
+ Add New Account
</button>
</div>
</div>
<!-- API Key Management Tab -->
<div id="keys-tab" class="tab-content">
<div class="key-management">
<h3>🔑 API Key Management</h3>
<div id="keyList" class="key-list"></div>
<button class="btn btn-success" onclick="showAddKeyModal()">
+ Add New API Key
</button>
</div>
</div>
<!-- Usage Dashboard Tab -->
<div id="usage-tab" class="tab-content">
<div class="controls">
<div class="control-group">
<label for="timeRange">Time Range</label>
<select id="timeRange">
<option value="7">Last 7 days</option>
<option value="30" selected>Last 30 days</option>
<option value="90">Last 90 days</option>
</select>
</div>
<div class="control-group">
<label> </label>
<button class="btn" onclick="refreshData()" id="refreshBtn">
🔄 Refresh Data
</button>
</div>
</div>
<div id="summarySection"></div>
<div id="apiKeysSection"></div>
</div>
</div>
</div>
<!-- Account Modal -->
<div id="accountModal" class="modal-overlay">
<div class="modal">
<button class="modal-close" onclick="closeAccountModal()">×</button>
<h3 id="accountModalTitle">Add New Account</h3>
<form id="accountForm">
<div class="form-group">
<label for="accountEmail">Email Address *</label>
<input type="email" id="accountEmail" placeholder="e.g., user@company.com" required>
<div class="form-error" id="accountEmailError"></div>
</div>
<div class="form-group">
<label for="accountName">Name</label>
<input type="text" id="accountName" placeholder="e.g., John Smith">
<div class="form-error" id="accountNameError"></div>
</div>
<div class="form-group">
<label for="organizationName">Organization</label>
<input type="text" id="organizationName" placeholder="e.g., My Company">
<div class="form-error" id="organizationError"></div>
</div>
<div class="modal-actions">
<button type="button" class="btn btn-secondary" onclick="closeAccountModal()">
Cancel
</button>
<button type="submit" class="btn btn-success">
Save Account
</button>
</div>
</form>
</div>
</div>
<!-- API Key Modal -->
<div id="keyModal" class="modal-overlay">
<div class="modal">
<button class="modal-close" onclick="closeKeyModal()">×</button>
<h3 id="keyModalTitle">Add New API Key</h3>
<form id="keyForm">
<div class="form-group">
<label for="keyAccount">Account *</label>
<select id="keyAccount" required>
<option value="">Select an account</option>
</select>
<div class="form-error" id="keyAccountError"></div>
</div>
<div class="form-group">
<label for="keyName">Key Name *</label>
<input type="text" id="keyName" placeholder="e.g., Production Key, Development Key" required>
<div class="form-error" id="keyNameError"></div>
</div>
<div class="form-group">
<label for="keyValue">API Key *</label>
<textarea id="keyValue" placeholder="sk-proj-... (OpenAI) sk-ant-... (Anthropic) gsk_... (Groq) pplx-... (Perplexity) BSA... (Brave Search) hf_... (HuggingFace) xai-... (xAI) AIzaSy... (Google/Gemini)" required></textarea>
<div class="form-error" id="keyValueError"></div>
<div style="font-size: 11px; color: #6b7280; margin-top: 4px;">
Supported: OpenAI (sk-*), Anthropic (sk-ant-*), Groq (gsk_*), Perplexity (pplx-*), Brave (BSA*), HuggingFace (hf_*), xAI (xai-*), Google (AIzaSy*), AWS (AKIA*/ASIA*), Replicate (rplx-*), and more
</div>
</div>
<div class="form-group" id="adminKeyGroup" style="display: none;">
<label for="adminKey">Associated Admin Key</label>
<select id="adminKey">
<option value="">No admin key association</option>
</select>
<div class="form-error" id="adminKeyError"></div>
</div>
<div id="testResult" class="test-result" style="display: none;"></div>
<div class="modal-actions">
<button type="button" class="btn btn-secondary" onclick="testApiKey()">
Test Key
</button>
<button type="button" class="btn btn-secondary" onclick="closeKeyModal()">
Cancel
</button>
<button type="submit" class="btn btn-success">
Save Key
</button>
</div>
</form>
</div>
</div>
<script>
let usageData = {};
let apiKeys = [];
let accounts = [];
let editingKeyId = null;
let editingAccountId = null;
// Tab Management
function switchTab(tabName) {
document.querySelectorAll('.tab-content').forEach(tab => tab.classList.remove('active'));
document.querySelectorAll('.nav-tab').forEach(tab => tab.classList.remove('active'));
document.getElementById(`${tabName}-tab`).classList.add('active');
event.target.classList.add('active');
if (tabName === 'accounts') {
loadAccounts();
} else if (tabName === 'keys') {
loadApiKeys();
} else if (tabName === 'usage') {
if (apiKeys.length > 0) {
refreshData();
}
}
}
// Account Management Functions
async function loadAccounts() {
try {
const response = await fetch('/api/accounts');
accounts = await response.json();
renderAccountList();
} catch (error) {
console.error('Failed to load accounts:', error);
}
}
function renderAccountList() {
const accountList = document.getElementById('accountList');
if (accounts.length === 0) {
accountList.innerHTML = `
<div style="text-align: center; color: #6b7280; padding: 20px;">
No accounts configured. Add your first account to get started!
</div>
`;
return;
}
accountList.innerHTML = accounts.map(account => `
<div class="account-item">
<div class="account-info">
<div class="account-email">${account.email}</div>
<div class="account-details">
${account.name ? account.name : 'No name'} •
${account.organization_name ? account.organization_name : 'No organization'}
</div>
</div>
<div class="account-actions">
<button class="btn btn-secondary btn-small" onclick="editAccount('${account.id}')">
Edit
</button>
<button class="btn btn-danger btn-small" onclick="deleteAccount('${account.id}', '${account.email}')">
Delete
</button>
</div>
</div>
`).join('');
}
function showAddAccountModal() {
editingAccountId = null;
document.getElementById('accountModalTitle').textContent = 'Add New Account';
document.getElementById('accountEmail').value = '';
document.getElementById('accountName').value = '';
document.getElementById('organizationName').value = '';
clearAccountErrors();
document.getElementById('accountModal').classList.add('active');
}
function editAccount(accountId) {
const account = accounts.find(a => a.id == accountId);
if (!account) return;
editingAccountId = accountId;
document.getElementById('accountModalTitle').textContent = 'Edit Account';
document.getElementById('accountEmail').value = account.email;
document.getElementById('accountName').value = account.name || '';
document.getElementById('organizationName').value = account.organization_name || '';
clearAccountErrors();
document.getElementById('accountModal').classList.add('active');
}
function closeAccountModal() {
document.getElementById('accountModal').classList.remove('active');
editingAccountId = null;
clearAccountErrors();
}
async function deleteAccount(accountId, email) {
if (!confirm(`Are you sure you want to delete account "${email}" and all associated API keys?`)) {
return;
}
try {
const response = await fetch(`/api/accounts/${accountId}`, { method: 'DELETE' });
if (response.ok) {
await loadAccounts();
await loadApiKeys();
} else {
const error = await response.json();
alert(`Failed to delete account: ${error.error}`);
}
} catch (error) {
alert(`Network error: ${error.message}`);
}
}
function clearAccountErrors() {
document.querySelectorAll('#accountModal .form-group').forEach(group => {
group.classList.remove('error');
});
document.querySelectorAll('#accountModal .form-error').forEach(error => {
error.textContent = '';
});
}
function showAccountError(elementId, message) {
const errorElement = document.getElementById(elementId);
errorElement.textContent = message;
errorElement.closest('.form-group').classList.add('error');
}
// Account form submission
document.getElementById('accountForm').addEventListener('submit', async function(e) {
e.preventDefault();
const email = document.getElementById('accountEmail').value.trim();
const name = document.getElementById('accountName').value.trim();
const organizationName = document.getElementById('organizationName').value.trim();
clearAccountErrors();
if (!email) {
showAccountError('accountEmailError', 'Email is required');
return;
}
try {
const payload = { email, name, organization_name: organizationName };
const url = editingAccountId ? `/api/accounts/${editingAccountId}` : '/api/accounts';
const method = editingAccountId ? 'PUT' : 'POST';
const response = await fetch(url, {
method: method,
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload)
});
if (response.ok) {
closeAccountModal();
await loadAccounts();
await loadApiKeys();
} else {
const error = await response.json();
if (error.error.includes('email already exists')) {
showAccountError('accountEmailError', error.error);
} else {
alert(`Error: ${error.error}`);
}
}
} catch (error) {
alert(`Network error: ${error.message}`);
}
});
// API Key Management Functions
async function loadApiKeys() {
try {
const response = await fetch('/api/keys');
const keys = await response.json();
apiKeys = keys.map(key => {
const account = accounts.find(a => a.id == key.account_id);
return {
...key,
account_email: account ? account.email : 'Unknown Account',
account_name: account ? account.name : '',
organization_name: account ? account.organization_name : ''
};
});
renderKeyList();
} catch (error) {
console.error('Failed to load API keys:', error);
}
}
function renderKeyList() {
const keyList = document.getElementById('keyList');
if (apiKeys.length === 0) {
keyList.innerHTML = `
<div style="text-align: center; color: #6b7280; padding: 20px;">
No API keys configured. Add your first key to get started!
</div>
`;
return;
}
// Group keys by account
const keysByAccount = {};
apiKeys.forEach(key => {
const accountKey = key.account_email || 'No Account';
if (!keysByAccount[accountKey]) {
keysByAccount[accountKey] = [];
}
keysByAccount[accountKey].push(key);
});
let html = '';
Object.entries(keysByAccount).forEach(([accountEmail, keys]) => {
html += `
<div style="margin-bottom: 20px;">
<h4 style="color: #4b5563; margin-bottom: 10px; font-size: 14px; font-weight: 600;">
📧 ${accountEmail}
</h4>
<div style="margin-left: 10px; border-left: 2px solid #e5e7eb; padding-left: 15px;">
`;
keys.forEach(key => {
html += `
<div class="key-item" style="margin-bottom: 10px;">
<div class="key-info">
<div style="display: flex; align-items: center; gap: 8px; margin-bottom: 4px;">
<span class="key-name">${key.name}</span>
<span class="key-type-badge ${key.key_type === 'admin' ? 'key-type-admin' : 'key-type-project'}">
${key.key_type}
</span>
<span class="provider-badge provider-${key.provider || 'openai'}">
${(key.provider || 'openai').toUpperCase()}
</span>
</div>
<div class="key-display-container">
<div class="key-display-text" id="key-display-${key.id}">
${key.masked_key}
</div>
<button class="key-toggle-btn" onclick="toggleKeyVisibility('${key.id}', '${key.full_key}')">
👁️ Show
</button>
<button class="key-copy-btn" id="copy-btn-${key.id}" onclick="copyKey('${key.id}')" disabled>
📋 Copy
</button>
</div>
<div class="key-metadata">
${key.admin_name ? `🔗 Admin: ${key.admin_name}` : ''}
${key.organization_name ? `🏢 ${key.organization_name}` : ''}
</div>
</div>
<div class="key-actions">
<button class="btn btn-secondary btn-small" onclick="testSingleKey('${key.id}')">
Test
</button>
<button class="btn btn-secondary btn-small" onclick="editKey('${key.id}')">
Edit
</button>
<button class="btn btn-danger btn-small" onclick="deleteKey('${key.id}', '${key.name}')">
Delete
</button>
</div>
</div>
`;
});
html += `
</div>
</div>
`;
});
keyList.innerHTML = html;
}
async function showAddKeyModal() {
editingKeyId = null;
document.getElementById('keyModalTitle').textContent = 'Add New API Key';
document.getElementById('keyName').value = '';
document.getElementById('keyValue').value = '';
document.getElementById('keyAccount').value = '';
document.getElementById('adminKey').value = '';
document.getElementById('adminKeyGroup').style.display = 'none';
clearKeyErrors();
hideTestResult();
await loadAccountsIntoDropdown();
document.getElementById('keyModal').classList.add('active');
}
async function editKey(keyId) {
const key = apiKeys.find(k => k.id === keyId);
if (!key) return;
editingKeyId = keyId;
document.getElementById('keyModalTitle').textContent = 'Edit API Key';
document.getElementById('keyName').value = key.name;
document.getElementById('keyValue').value = '';
document.getElementById('keyValue').placeholder = 'Leave empty to keep current key, or enter new key';
document.getElementById('keyAccount').value = key.account_id || '';
clearKeyErrors();
hideTestResult();
await loadAccountsIntoDropdown();
await loadAdminKeysForAccount(key.account_id);
if (key.key_type === 'project') {
document.getElementById('adminKeyGroup').style.display = 'block';
document.getElementById('adminKey').value = key.admin_key_id || '';
}
document.getElementById('keyModal').classList.add('active');
}
function closeKeyModal() {
document.getElementById('keyModal').classList.remove('active');
editingKeyId = null;
clearKeyErrors();
hideTestResult();
}
async function loadAccountsIntoDropdown() {
if (accounts.length === 0) {
await loadAccounts();
}
const dropdown = document.getElementById('keyAccount');
dropdown.innerHTML = '<option value="">Select an account</option>';
accounts.forEach(account => {
dropdown.innerHTML += `<option value="${account.id}">${account.email}</option>`;
});
}
async function loadAdminKeysForAccount(accountId) {
if (!accountId) return;
try {
const response = await fetch(`/api/accounts/${accountId}/admin-keys`);
const adminKeys = await response.json();
const dropdown = document.getElementById('adminKey');
dropdown.innerHTML = '<option value="">No admin key association</option>';
adminKeys.forEach(key => {
dropdown.innerHTML += `<option value="${key.id}">${key.name} (${key.masked_key})</option>`;
});
} catch (error) {
console.error('Failed to load admin keys:', error);
}
}
// Event handlers for key form
document.getElementById('keyAccount').addEventListener('change', function() {
const accountId = this.value;
const keyValue = document.getElementById('keyValue').value;
if (accountId && keyValue.startsWith('sk-proj-')) {
document.getElementById('adminKeyGroup').style.display = 'block';
loadAdminKeysForAccount(accountId);
} else {
document.getElementById('adminKeyGroup').style.display = 'none';
}
});
document.getElementById('keyValue').addEventListener('input', function() {
const keyValue = this.value;
const accountId = document.getElementById('keyAccount').value;
if (keyValue.startsWith('sk-proj-') && accountId) {
document.getElementById('adminKeyGroup').style.display = 'block';
loadAdminKeysForAccount(accountId);
} else {
document.getElementById('adminKeyGroup').style.display = 'none';
}
});
async function deleteKey(keyId, keyName) {
if (!confirm(`Are you sure you want to delete "${keyName}"?`)) {
return;
}
try {
const response = await fetch(`/api/keys/${keyId}`, { method: 'DELETE' });
if (response.ok) {
await loadApiKeys();
if (Object.keys(usageData).length > 0) {
refreshData();
}
} else {
const error = await response.json();
alert(`Failed to delete key: ${error.error}`);
}
} catch (error) {
alert(`Network error: ${error.message}`);
}
}
async function testSingleKey(keyId) {
try {
const response = await fetch(`/api/keys/${keyId}/test`, { method: 'POST' });
const result = await response.json();
if (result.status === 'success') {
alert(`✓ ${result.message}`);
} else {
alert(`✗ ${result.message}`);
}
} catch (error) {
alert(`Network error: ${error.message}`);
}
}
async function testApiKey() {
const keyValue = document.getElementById('keyValue').value.trim();
const accountId = document.getElementById('keyAccount').value;
if (!keyValue) {
showKeyError('keyValueError', 'API key is required for testing');
return;
}
if (!accountId) {
showKeyError('keyAccountError', 'Account selection is required');
return;
}
if (!keyValue.match(/^(sk-|BSA|pub_|gsk_|pplx-|AIzaSy|AKIA|ASIA|claude-|hf_|xai-|rplx-|gcp_|[a-f0-9]{32}$|[a-f0-9-]{36}$|[a-f0-9]{64}$|[A-Za-z0-9]{39}$|[A-Za-z0-9_\-:]{10,})/)) {
showKeyError('keyValueError', 'Invalid API key format');
return;
}
const testResult = document.getElementById('testResult');
testResult.style.display = 'block';
testResult.className = 'test-result';
testResult.innerHTML = 'Testing API key...';
try {
const tempResponse = await fetch('/api/keys', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
name: `temp_test_${Date.now()}`,
full_key: keyValue,
account_id: accountId
})
});
if (!tempResponse.ok) {
const error = await tempResponse.json();
throw new Error(error.error);
}
const tempKey = await tempResponse.json();
const testResponse = await fetch(`/api/keys/${tempKey.id}/test`, { method: 'POST' });
const result = await testResponse.json();
// Clean up temp key
await fetch(`/api/keys/${tempKey.id}`, { method: 'DELETE' });
if (result.status === 'success') {
testResult.className = 'test-result success';
testResult.innerHTML = `✓ ${result.message}`;
} else {
testResult.className = 'test-result error';
testResult.innerHTML = `✗ ${result.message}`;
}
} catch (error) {
testResult.className = 'test-result error';
testResult.innerHTML = `✗ Test failed: ${error.message}`;
}
}
function clearKeyErrors() {
document.querySelectorAll('#keyModal .form-group').forEach(group => {
group.classList.remove('error');
});
document.querySelectorAll('#keyModal .form-error').forEach(error => {
error.textContent = '';
});
}
function showKeyError(elementId, message) {
const errorElement = document.getElementById(elementId);
errorElement.textContent = message;
errorElement.closest('.form-group').classList.add('error');
}
function hideTestResult() {
document.getElementById('testResult').style.display = 'none';
}
// Key form submission
document.getElementById('keyForm').addEventListener('submit', async function(e) {
e.preventDefault();
const name = document.getElementById('keyName').value.trim();
const keyValue = document.getElementById('keyValue').value.trim();
const accountId = document.getElementById('keyAccount').value;
const adminKeyId = document.getElementById('adminKey').value;
clearKeyErrors();
if (!name) {
showKeyError('keyNameError', 'Key name is required');
return;
}
if (!accountId) {
showKeyError('keyAccountError', 'Account selection is required');
return;
}
if (editingKeyId === null && !keyValue) {
showKeyError('keyValueError', 'API key is required');
return;
}
if (keyValue && !keyValue.match(/^(sk-|BSA|pub_|gsk_|pplx-|AIzaSy|AKIA|ASIA|claude-|hf_|xai-|rplx-|gcp_|[a-f0-9]{32}$|[a-f0-9-]{36}$|[a-f0-9]{64}$|[A-Za-z0-9]{39}$|[A-Za-z0-9_\-:]{10,})/)) {
showKeyError('keyValueError', 'Invalid API key format');
return;
}
try {
const payload = {
name,
account_id: accountId,
admin_key_id: adminKeyId || null
};
if (keyValue) {
payload.full_key = keyValue;
}
const url = editingKeyId ? `/api/keys/${editingKeyId}` : '/api/keys';
const method = editingKeyId ? 'PUT' : 'POST';
const response = await fetch(url, {
method: method,
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload)
});
if (response.ok) {
closeKeyModal();
await loadApiKeys();
if (Object.keys(usageData).length > 0) {
refreshData();
}
} else {
const error = await response.json();
if (error.error.includes('name already exists')) {
showKeyError('keyNameError', error.error);
} else if (error.error.includes('Invalid')) {
showKeyError('keyValueError', error.error);
} else if (error.error.includes('Account')) {
showKeyError('keyAccountError', error.error);
} else {
alert(`Error: ${error.error}`);
}
}
} catch (error) {
alert(`Network error: ${error.message}`);
}
});
// Modal event handlers
document.getElementById('accountModal').addEventListener('click', function(e) {
if (e.target === this) {
closeAccountModal();
}
});
document.getElementById('keyModal').addEventListener('click', function(e) {
if (e.target === this) {
closeKeyModal();
}
});
// Usage Dashboard Functions
async function refreshData() {
if (apiKeys.length === 0) {
document.getElementById('apiKeysSection').innerHTML = `
<div style="text-align: center; color: #6b7280; padding: 40px;">
<h3>No API Keys Configured</h3>
<p>Add some API keys above to start monitoring usage data.</p>
</div>
`;
document.getElementById('summarySection').innerHTML = '';
return;
}
const refreshBtn = document.getElementById('refreshBtn');
const timeRange = document.getElementById('timeRange').value;
refreshBtn.disabled = true;
refreshBtn.innerHTML = '🔄 Loading...';
document.getElementById('apiKeysSection').innerHTML = `
<div class="loading">
<div class="spinner"></div>
<p>Fetching usage data from API providers...</p>
</div>
`;
try {
const response = await fetch(`/api/usage?days=${timeRange}`);
const data = await response.json();
usageData = data;
renderDashboard();
} catch (error) {
document.getElementById('apiKeysSection').innerHTML = `
<div class="error-message">
✗ Failed to fetch data: ${error.message}
</div>
`;
}
refreshBtn.disabled = false;
refreshBtn.innerHTML = '🔄 Refresh Data';
}
function renderDashboard() {
renderSummary();
renderApiKeys();
}
function renderSummary() {
const summarySection = document.getElementById('summarySection');
let totalActiveKeys = 0;
let totalCost = 0;
let totalTokens = 0;
let providerCounts = {};
Object.values(usageData).forEach(keyData => {
const provider = keyData.provider || 'unknown';
if (!providerCounts[provider]) {
providerCounts[provider] = 0;
}
providerCounts[provider]++;
if (keyData.status === 'success') {
totalActiveKeys++;
if (provider === 'openai') {
if (keyData.costs && keyData.costs.data) {
const dailyCosts = keyData.costs.data;
totalCost += dailyCosts.reduce((sum, day) => sum + (day.cost || 0), 0);
}
if (keyData.usage && keyData.usage.data) {
const dailyUsage = keyData.usage.data;
totalTokens += dailyUsage.reduce((sum, day) => sum + (day.n_requests || 0), 0);
}
}
}
});
const providerBreakdown = Object.entries(providerCounts)
.map(([provider, count]) => `${provider.toUpperCase()}: ${count}`)
.join(' • ');
summarySection.innerHTML = `
<div class="summary-cards">
<div class="summary-card">
<h3>${totalActiveKeys}</h3>
<p>Active API Keys</p>
</div>
<div class="summary-card">
<h3>${totalCost.toFixed(2)}</h3>
<p>OpenAI Spend</p>
</div>
<div class="summary-card">
<h3>${totalTokens.toLocaleString()}</h3>
<p>OpenAI Requests</p>
</div>
<div class="summary-card">
<h3>${Object.keys(providerCounts).length}</h3>
<p>Providers: ${providerBreakdown}</p>
</div>
</div>
`;
}
function renderApiKeys() {
const apiKeysSection = document.getElementById('apiKeysSection');
let html = '';
Object.values(usageData).forEach(keyData => {
html += renderApiKeyCard(keyData);
});
apiKeysSection.innerHTML = html;
}
function renderApiKeyCard(keyData) {
const statusMap = {
'success': { class: 'status-active', text: 'Active' },
'error': { class: 'status-error', text: 'Error' },
'partial': { class: 'status-partial', text: 'Partial' },
'basic_only': { class: 'status-basic', text: 'Basic Only' },
'info_only': { class: 'status-info', text: 'Info Only' },
'no_usage_access': { class: 'status-no-usage', text: 'No Usage Access' }
};
const status = statusMap[keyData.status] || { class: 'status-error', text: 'Unknown' };
const provider = keyData.provider || 'unknown';
const providerBadge = `<span class="provider-badge provider-${provider}">${provider.toUpperCase()}</span>`;
let html = `