forked from xebia/github-copilot-premium-reqs-usage
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.ts
More file actions
1277 lines (1083 loc) · 41.8 KB
/
utils.ts
File metadata and controls
1277 lines (1083 loc) · 41.8 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
import { clsx, type ClassValue } from "clsx"
import { twMerge } from "tailwind-merge"
import { defaultServerMainFields } from "vite";
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs))
}
export interface CopilotUsageData {
timestamp: Date;
user: string;
model: string;
requestsUsed: number;
exceedsQuota: boolean;
totalMonthlyQuota: string;
}
export interface AggregatedData {
date: string; // YYYY-MM-DD format
model: string;
compliantRequests: number;
exceedingRequests: number;
}
export function parseCSV(csv: string): CopilotUsageData[] {
const lines = csv.trim().split('\n');
if (lines.length < 2) {
throw new Error('CSV must contain a header row and at least one data row');
}
// Parse header row and build a mapping from expected field to column index (case-insensitive)
const headerLine = lines[0].trim();
const headerMatches = headerLine.match(/("([^"]*)"|([^,]*))(,|$)/g);
if (!headerMatches) {
throw new Error('CSV header could not be parsed');
}
const headers = headerMatches.map(m => {
let processed = m.endsWith(',') ? m.slice(0, -1) : m;
processed = processed.replace(/^"(.*)"$/, '$1');
return processed.trim();
});
// Map new CSV field names to expected fields (case-insensitive)
const FIELD_MAP: Record<string, string> = {
'date': 'timestamp',
'username': 'user',
'quantity': 'requestsUsed',
'exceeds_quota': 'exceedsQuota',
'total_monthly_quota': 'totalMonthlyQuota',
// Backward compatibility (old headers)
'timestamp': 'timestamp',
'user': 'user',
'model': 'model',
'requests used': 'requestsUsed',
'exceeds monthly quota': 'exceedsQuota',
'total monthly quota': 'totalMonthlyQuota',
};
// For error messages, map internal field names to original header names
const INTERNAL_TO_HEADER: Record<string, string> = {
'timestamp': 'Timestamp',
'user': 'User',
'model': 'Model',
'requestsUsed': 'Requests Used',
'exceedsQuota': 'Exceeds Monthly Quota',
'totalMonthlyQuota': 'Total Monthly Quota',
};
// Build a mapping from expected field to column index (case-insensitive)
const fieldToIndex: Partial<Record<keyof CopilotUsageData, number>> = {};
headers.forEach((header, idx) => {
const mapped = FIELD_MAP[header.toLowerCase()];
if (mapped) {
fieldToIndex[mapped as keyof CopilotUsageData] = idx;
}
});
// Ensure all required fields are present
const requiredFields: Array<keyof CopilotUsageData> = [
'timestamp', 'user', 'model', 'requestsUsed', 'exceedsQuota', 'totalMonthlyQuota'
];
const missingFields = requiredFields.filter(f => fieldToIndex[f] === undefined);
if (missingFields.length > 0) {
// If all columns are missing, check for too few columns
if (headers.length < 6) {
throw new Error('CSV header must contain at least 6 columns');
}
// Compose error message with original header names
const missingHeaderNames = missingFields.map(f => INTERNAL_TO_HEADER[f]);
throw new Error(`CSV is missing required columns: ${missingHeaderNames.join(', ')}. Expected columns: ${Object.values(INTERNAL_TO_HEADER).join(', ')}`);
}
// Parse data rows
return lines.slice(1).map((line, index) => {
const trimmedLine = line.trim();
if (!trimmedLine) return null;
const matches = trimmedLine.match(/("([^"]*)"|([^,]*))(,|$)/g);
if (!matches) {
throw new Error(`Invalid CSV row format at line ${index + 2}`);
}
// Pad matches to header length (in case of trailing commas)
while (matches.length < headers.length) matches.push('');
// Extract values by mapped index
const getValue = (field: keyof CopilotUsageData) => {
const idx = fieldToIndex[field]!;
let val = matches[idx] || '';
val = val.endsWith(',') ? val.slice(0, -1) : val;
val = val.replace(/^"(.*)"$/, '$1');
return val.trim();
};
// Validate and parse fields
const timestampStr = getValue('timestamp');
const timestamp = new Date(timestampStr);
if (isNaN(timestamp.getTime())) {
throw new Error(`Invalid timestamp format at line ${index + 2}: "${timestampStr}"`);
}
const user = getValue('user');
const model = getValue('model');
const requestsUsedStr = getValue('requestsUsed');
const requestsUsed = parseFloat(requestsUsedStr);
if (isNaN(requestsUsed)) {
throw new Error(`Invalid requests used value at line ${index + 2}: "${requestsUsedStr}" must be a number`);
}
const exceedsQuotaValue = getValue('exceedsQuota').toLowerCase();
if (exceedsQuotaValue !== 'true' && exceedsQuotaValue !== 'false') {
throw new Error(`Invalid exceeds quota value at line ${index + 2}: "${getValue('exceedsQuota')}" must be "true" or "false"`);
}
const totalMonthlyQuota = getValue('totalMonthlyQuota');
return {
timestamp,
user,
model,
requestsUsed,
exceedsQuota: exceedsQuotaValue === 'true',
totalMonthlyQuota,
};
}).filter(Boolean) as CopilotUsageData[];
}
export interface ModelUsageSummary {
model: string;
displayName: string; // For grouping default models
totalRequests: number;
compliantRequests: number;
exceedingRequests: number;
multiplier: number;
individualPlanLimit: number;
businessPlanLimit: number;
enterprisePlanLimit: number;
excessCost: number; // Cost for exceeding requests
}
export interface DailyModelData {
date: string;
model: string;
requests: number;
}
export function aggregateDataByDay(data: CopilotUsageData[]): AggregatedData[] {
const aggregated: Record<string, AggregatedData> = {};
data.forEach(item => {
const date = item.timestamp.toISOString().split('T')[0];
const key = `${date}-${item.model}`;
if (!aggregated[key]) {
aggregated[key] = {
date,
model: item.model,
compliantRequests: 0,
exceedingRequests: 0,
};
}
if (item.exceedsQuota) {
aggregated[key].exceedingRequests += item.requestsUsed;
} else {
aggregated[key].compliantRequests += item.requestsUsed;
}
});
// Convert to array and sort by date and model
return Object.values(aggregated).sort((a, b) => {
if (a.date !== b.date) return a.date.localeCompare(b.date);
return a.model.localeCompare(b.model);
});
}
export function getModelUsageSummary(data: CopilotUsageData[]): ModelUsageSummary[] {
const summary: Record<string, ModelUsageSummary> = {};
data.forEach(item => {
if (!summary[item.model]) {
const multiplier = getModelMultiplier(item.model);
const displayName = isDefaultModel(item.model) ? 'Default' : item.model;
summary[item.model] = {
model: item.model,
displayName,
totalRequests: 0,
compliantRequests: 0,
exceedingRequests: 0,
multiplier,
individualPlanLimit: PLAN_MONTHLY_LIMITS[COPILOT_PLANS.INDIVIDUAL],
businessPlanLimit: PLAN_MONTHLY_LIMITS[COPILOT_PLANS.BUSINESS],
enterprisePlanLimit: PLAN_MONTHLY_LIMITS[COPILOT_PLANS.ENTERPRISE],
excessCost: 0
};
}
summary[item.model].totalRequests += item.requestsUsed;
if (item.exceedsQuota) {
summary[item.model].exceedingRequests += item.requestsUsed;
} else {
summary[item.model].compliantRequests += item.requestsUsed;
}
});
// Calculate excess costs and group default models
const summaryArray = Object.values(summary);
const groupedSummary: Record<string, ModelUsageSummary> = {};
summaryArray.forEach(item => {
const key = item.displayName;
if (!groupedSummary[key]) {
groupedSummary[key] = {
...item,
model: key === 'Default' ? 'Default (GPT-4o, GPT-4.1)' : item.model
};
} else {
// Merge default models
groupedSummary[key].totalRequests += item.totalRequests;
groupedSummary[key].compliantRequests += item.compliantRequests;
groupedSummary[key].exceedingRequests += item.exceedingRequests;
}
// For grouped default models, ensure multiplier is 0 and limits use constant values
if (key === 'Default') {
groupedSummary[key].multiplier = 0;
groupedSummary[key].individualPlanLimit = PLAN_MONTHLY_LIMITS[COPILOT_PLANS.INDIVIDUAL];
groupedSummary[key].businessPlanLimit = PLAN_MONTHLY_LIMITS[COPILOT_PLANS.BUSINESS];
groupedSummary[key].enterprisePlanLimit = PLAN_MONTHLY_LIMITS[COPILOT_PLANS.ENTERPRISE];
}
// Calculate excess cost
// Free models (multiplier = 0) have no excess cost
if (groupedSummary[key].multiplier === 0) {
groupedSummary[key].excessCost = 0;
} else {
groupedSummary[key].excessCost = groupedSummary[key].exceedingRequests * EXCESS_REQUEST_COST;
}
});
// Convert to array and sort by total requests (descending)
return Object.values(groupedSummary).sort((a, b) => b.totalRequests - a.totalRequests);
}
export function getDailyModelData(data: CopilotUsageData[]): DailyModelData[] {
const aggregated: Record<string, DailyModelData> = {};
data.forEach(item => {
const date = item.timestamp.toISOString().split('T')[0];
const key = `${date}-${item.model}`;
if (!aggregated[key]) {
aggregated[key] = {
date,
model: item.model,
requests: 0
};
}
aggregated[key].requests += item.requestsUsed;
});
// Convert to array and sort by date
return Object.values(aggregated).sort((a, b) => {
if (a.date !== b.date) return a.date.localeCompare(b.date);
return a.model.localeCompare(b.model);
});
}
// Power user interfaces and functions
export interface PowerUserData {
user: string;
totalRequests: number;
exceedingRequests: number;
requestsByModel: Record<string, number>;
dailyActivity: Array<{
date: string;
requests: number;
}>;
}
export interface PowerUserSummary {
powerUsers: PowerUserData[];
totalPowerUsers: number;
totalPowerUserRequests: number;
powerUserModelSummary: ModelUsageSummary[];
}
export interface PowerUserDailyBreakdown {
date: string;
compliantRequests: number;
exceedingRequests: number;
// Model breakdown - each model will have its own field for recharts stacking
[key: string]: string | number; // Allow dynamic model fields
}
export interface ProjectedUserData {
user: string;
currentRequests: number;
projectedMonthlyTotal: number;
daysElapsed: number;
dailyAverage: number;
}
// Copilot plan constants
export const COPILOT_PLANS = {
INDIVIDUAL: 'Individual',
BUSINESS: 'Business',
ENTERPRISE: 'Enterprise'
} as const;
export const PLAN_MONTHLY_LIMITS = {
[COPILOT_PLANS.INDIVIDUAL]: 50,
[COPILOT_PLANS.BUSINESS]: 300,
[COPILOT_PLANS.ENTERPRISE]: 1000
} as const;
// Model multipliers based on GitHub documentation (for paid plans)
// Uses display names as they appear in GitHub Copilot exports.
export const MODEL_MULTIPLIERS: Record<string, number> = {
// Current default models (0x multiplier for paid plans)
'GPT-4.1': 0,
'GPT-4o': 0,
'GPT-5 mini': 0,
'Raptor mini': 0,
// OpenAI models
'GPT-5.1': 1,
'GPT-5.1-Codex': 1,
'GPT-5.1-Codex-Mini': 0.33,
'GPT-5.1-Codex-Max': 1,
'GPT-5.2': 1,
'GPT-5.2-Codex': 1,
'GPT-5.3-Codex': 1,
'GPT-5.4': 1,
'GPT-5.4 mini': 0.33,
// Anthropic models
'Claude Haiku 4.5': 0.33,
'Claude Sonnet 4': 1,
'Claude Sonnet 4.5': 1,
'Claude Sonnet 4.6': 1,
'Claude Opus 4.5': 3,
'Claude Opus 4.6': 3,
'Claude Opus 4.6 (fast mode) (preview)': 30,
// Google models
'Gemini 2.5 Pro': 1,
'Gemini 3 Flash': 0.33,
'Gemini 3 Pro': 1,
'Gemini 3.1 Pro': 1,
// xAI and other models
'Grok Code Fast 1': 0.25,
'Goldeneye': 1,
// Backward compatibility for older exports
'gpt-4o-2024-11-20': 0,
'gpt-4.1-2025-04-14': 0,
'gpt-4o': 0,
'gpt-4.1': 0,
'gpt-4.5': 50,
'gpt-4.1-vision': 0,
'claude-sonnet-3.5': 1,
'claude-sonnet-3.7': 1,
'claude-sonnet-3.7-thinking': 1.25,
'claude-sonnet-4': 1,
'claude-opus-4': 10,
'gemini-2.0-flash': 0.25,
'gemini-2.5-pro': 1,
'o1': 10,
'o3': 1,
'o3-mini': 0.33,
'o3-mini-2025-01-31': 0.33,
'o4-mini': 0.33,
'o4-mini-2025-04-16': 0.33,
// Add other models as needed - fallback to 1x for unknown models
};
// Default models that should be grouped
export const DEFAULT_MODELS = ['GPT-4o', 'GPT-4.1', 'GPT-5 mini', 'gpt-4o-2024-11-20', 'gpt-4.1-2025-04-14'];
function normalizeModelName(model: string): string {
return model.replace(/^Auto:\s*/, '').trim();
}
function getModelMultiplier(model: string): number {
return MODEL_MULTIPLIERS[normalizeModelName(model)] ?? 1;
}
function isDefaultModel(model: string): boolean {
return DEFAULT_MODELS.includes(normalizeModelName(model));
}
// Cost per excess request (in USD) for premium requests
export const EXCESS_REQUEST_COST = 0.04; // $0.04 per excess request
export function getPowerUsers(data: CopilotUsageData[]): PowerUserSummary {
// First, aggregate total requests per user
const userTotals: Record<string, number> = {};
data.forEach(item => {
userTotals[item.user] = (userTotals[item.user] || 0) + item.requestsUsed;
});
// Get all users sorted by total requests (descending)
const allUsersSorted = Object.keys(userTotals).sort(
(a, b) => userTotals[b] - userTotals[a]
);
// Calculate top 10% of users (at least 1 user if any users exist)
const powerUserCount = Math.max(1, Math.ceil(allUsersSorted.length * 0.1));
// Take the top 10% of users as power users
const powerUserNames = allUsersSorted.slice(0, powerUserCount);
// Filter data to only power users
const powerUserData = data.filter(item => powerUserNames.includes(item.user));
// Create detailed power user objects
const powerUsers: PowerUserData[] = powerUserNames.map(userName => {
const userRequests = powerUserData.filter(item => item.user === userName);
// Aggregate by model
const requestsByModel: Record<string, number> = {};
userRequests.forEach(item => {
requestsByModel[item.model] = (requestsByModel[item.model] || 0) + item.requestsUsed;
});
// Calculate exceeding requests
const exceedingRequests = userRequests
.filter(item => item.exceedsQuota)
.reduce((sum, item) => sum + item.requestsUsed, 0);
// Aggregate daily activity
const dailyActivity: Record<string, number> = {};
userRequests.forEach(item => {
const date = item.timestamp.toISOString().split('T')[0];
dailyActivity[date] = (dailyActivity[date] || 0) + item.requestsUsed;
});
const dailyActivityArray = Object.entries(dailyActivity)
.map(([date, requests]) => ({ date, requests }))
.sort((a, b) => a.date.localeCompare(b.date));
return {
user: userName,
totalRequests: userTotals[userName],
exceedingRequests,
requestsByModel,
dailyActivity: dailyActivityArray
};
});
// Sort power users by total requests (descending)
powerUsers.sort((a, b) => b.totalRequests - a.totalRequests);
// Calculate total power user requests
const totalPowerUserRequests = powerUsers.reduce((sum, user) => sum + user.totalRequests, 0);
// Get model usage summary for power users
const powerUserModelSummary = getModelUsageSummary(powerUserData);
return {
powerUsers,
totalPowerUsers: powerUsers.length,
totalPowerUserRequests,
powerUserModelSummary
};
}
export function getPowerUserDailyData(powerUsers: PowerUserData[]): Array<{
date: string;
requests: number;
}> {
const dailyTotals: Record<string, number> = {};
powerUsers.forEach(user => {
user.dailyActivity.forEach(day => {
dailyTotals[day.date] = (dailyTotals[day.date] || 0) + day.requests;
});
});
return Object.entries(dailyTotals)
.map(([date, requests]) => ({ date, requests }))
.sort((a, b) => a.date.localeCompare(b.date));
}
export function getPowerUserDailyBreakdown(data: CopilotUsageData[], powerUserNames: string[]): PowerUserDailyBreakdown[] {
// Filter data to only include power users
const powerUserData = data.filter(item => powerUserNames.includes(item.user));
const dailyBreakdown: Record<string, PowerUserDailyBreakdown> = {};
powerUserData.forEach(item => {
const date = item.timestamp.toISOString().split('T')[0];
if (!dailyBreakdown[date]) {
dailyBreakdown[date] = {
date,
compliantRequests: 0,
exceedingRequests: 0,
};
}
// Track model usage - create field name for this model
const modelFieldName = item.model;
if (!dailyBreakdown[date][modelFieldName]) {
dailyBreakdown[date][modelFieldName] = 0;
}
// Add to model-specific field
dailyBreakdown[date][modelFieldName] = (dailyBreakdown[date][modelFieldName] as number) + item.requestsUsed;
// Keep the existing compliant/exceeding breakdown for backwards compatibility
if (item.exceedsQuota) {
dailyBreakdown[date].exceedingRequests += item.requestsUsed;
} else {
dailyBreakdown[date].compliantRequests += item.requestsUsed;
}
});
// Convert to array and sort by date
return Object.values(dailyBreakdown).sort((a, b) => a.date.localeCompare(b.date));
}
// Helper function to extract all unique models from power user daily breakdown data
export function getUniqueModelsFromBreakdown(breakdownData: PowerUserDailyBreakdown[]): string[] {
const modelSet = new Set<string>();
breakdownData.forEach(dayData => {
Object.keys(dayData).forEach(key => {
// Skip non-model fields (date, compliantRequests, exceedingRequests)
if (key !== 'date' && key !== 'compliantRequests' && key !== 'exceedingRequests') {
modelSet.add(key);
}
});
});
return Array.from(modelSet).sort();
}
// Function to get the last date from CSV data
export function getLastDateFromData(data: CopilotUsageData[]): string | null {
if (!data.length) return null;
// Get all dates and find the maximum
const dates = data.map(item => item.timestamp.toISOString().split('T')[0]);
const sortedDates = dates.sort((a, b) => a.localeCompare(b));
return sortedDates[sortedDates.length - 1];
}
export interface ExceededRequestDetail {
user: string;
date: string;
exceededRequests: number;
totalRequestsOnDay: number;
compliantRequestsOnDay: number;
modelsUsed: string[];
exceedingByModel: Record<string, number>;
}
export function getExceededRequestDetails(data: CopilotUsageData[], targetDate?: string, targetUser?: string): ExceededRequestDetail[] {
const exceededDetails: Record<string, ExceededRequestDetail> = {};
// Filter data if specific date or user is provided
let filteredData = data;
if (targetDate) {
filteredData = filteredData.filter(item =>
item.timestamp.toISOString().split('T')[0] === targetDate
);
}
if (targetUser) {
filteredData = filteredData.filter(item => item.user === targetUser);
}
// Process all data to find users who exceeded limits
filteredData.forEach(item => {
const date = item.timestamp.toISOString().split('T')[0];
const key = `${item.user}-${date}`;
if (!exceededDetails[key]) {
exceededDetails[key] = {
user: item.user,
date,
exceededRequests: 0,
totalRequestsOnDay: 0,
compliantRequestsOnDay: 0,
modelsUsed: [],
exceedingByModel: {},
};
}
const detail = exceededDetails[key];
// Track total requests for this day
detail.totalRequestsOnDay += item.requestsUsed;
// Track models used
if (!detail.modelsUsed.includes(item.model)) {
detail.modelsUsed.push(item.model);
}
// Track exceeded vs compliant requests
if (item.exceedsQuota) {
detail.exceededRequests += item.requestsUsed;
detail.exceedingByModel[item.model] = (detail.exceedingByModel[item.model] || 0) + item.requestsUsed;
} else {
detail.compliantRequestsOnDay += item.requestsUsed;
}
});
// Filter to only return entries where users actually exceeded limits
return Object.values(exceededDetails)
.filter(detail => detail.exceededRequests > 0)
.sort((a, b) => {
if (a.date !== b.date) return b.date.localeCompare(a.date); // Most recent first
return b.exceededRequests - a.exceededRequests; // Highest exceeded requests first
});
}
export function getUserExceededRequestSummary(data: CopilotUsageData[], userName: string): {
totalExceededDays: number;
totalExceededRequests: number;
averageExceededPerDay: number;
worstDay: { date: string; exceededRequests: number; totalRequests: number } | null;
} {
const userExceededDetails = getExceededRequestDetails(data, undefined, userName);
if (userExceededDetails.length === 0) {
return {
totalExceededDays: 0,
totalExceededRequests: 0,
averageExceededPerDay: 0,
worstDay: null,
};
}
const totalExceededRequests = userExceededDetails.reduce((sum, detail) => sum + detail.exceededRequests, 0);
const worstDay = userExceededDetails.reduce((worst, current) =>
current.exceededRequests > worst.exceededRequests ? current : worst
);
return {
totalExceededDays: userExceededDetails.length,
totalExceededRequests,
averageExceededPerDay: totalExceededRequests / userExceededDetails.length,
worstDay: {
date: worstDay.date,
exceededRequests: worstDay.exceededRequests,
totalRequests: worstDay.totalRequestsOnDay,
},
};
}
export interface ExceededUserSummary {
user: string;
daysExceeded: number;
totalExceededRequests: number;
totalRequestsOnExceededDays: number;
compliantRequestsOnExceededDays: number;
worstDay: { date: string; exceededRequests: number; totalRequests: number };
}
/**
* Get a per-user overview of all users who have exceeded their quota at least once.
* Sorted by total exceeded requests descending.
*/
export function getExceededUsersOverview(data: CopilotUsageData[]): ExceededUserSummary[] {
const allDetails = getExceededRequestDetails(data);
if (allDetails.length === 0) return [];
const byUser: Record<string, ExceededUserSummary> = {};
allDetails.forEach(detail => {
if (!byUser[detail.user]) {
byUser[detail.user] = {
user: detail.user,
daysExceeded: 0,
totalExceededRequests: 0,
totalRequestsOnExceededDays: 0,
compliantRequestsOnExceededDays: 0,
worstDay: { date: detail.date, exceededRequests: 0, totalRequests: 0 },
};
}
const summary = byUser[detail.user];
summary.daysExceeded += 1;
summary.totalExceededRequests += detail.exceededRequests;
summary.totalRequestsOnExceededDays += detail.totalRequestsOnDay;
summary.compliantRequestsOnExceededDays += detail.compliantRequestsOnDay;
if (detail.exceededRequests > summary.worstDay.exceededRequests) {
summary.worstDay = {
date: detail.date,
exceededRequests: detail.exceededRequests,
totalRequests: detail.totalRequestsOnDay,
};
}
});
return Object.values(byUser).sort((a, b) => b.totalExceededRequests - a.totalExceededRequests);
}
/**
* Get the count of unique users who have exceeded their quota limits
* @param data - Array of Copilot usage data
* @param plan - The plan type to check limits against (defaults to BUSINESS)
*/
export function getUniqueUsersExceedingQuota(data: CopilotUsageData[], plan: string = COPILOT_PLANS.BUSINESS): number {
if (!data.length) return 0;
// Get the plan limit for comparison
const planLimit = PLAN_MONTHLY_LIMITS[plan] || PLAN_MONTHLY_LIMITS[COPILOT_PLANS.BUSINESS];
// Aggregate total requests per user
const userTotals: Record<string, number> = {};
data.forEach(item => {
userTotals[item.user] = (userTotals[item.user] || 0) + item.requestsUsed;
});
// Count users who exceed the plan limit
const usersExceedingPlan = Object.keys(userTotals).filter(user => userTotals[user] > planLimit);
return usersExceedingPlan.length;
}
/**
* Get the total requests made by users who have exceeded their quota limits
* @param data - Array of Copilot usage data
* @param plan - The plan type to check limits against (defaults to BUSINESS)
*/
export function getTotalRequestsForUsersExceedingQuota(data: CopilotUsageData[], plan: string = COPILOT_PLANS.BUSINESS): number {
if (!data.length) return 0;
// Get the plan limit for comparison
const planLimit = PLAN_MONTHLY_LIMITS[plan] || PLAN_MONTHLY_LIMITS[COPILOT_PLANS.BUSINESS];
// Aggregate total requests per user
const userTotals: Record<string, number> = {};
data.forEach(item => {
userTotals[item.user] = (userTotals[item.user] || 0) + item.requestsUsed;
});
// Get users who exceed the plan limit and sum their total requests
const usersExceedingPlan = Object.keys(userTotals).filter(user => userTotals[user] > planLimit);
return usersExceedingPlan.reduce((sum, user) => sum + userTotals[user], 0);
}
/**
* Project the number of users who will exceed their quota limits by month-end
* based on their current usage patterns
* @param data - Array of Copilot usage data
* @param plan - The plan type to check limits against (defaults to BUSINESS)
*/
export function getProjectedUsersExceedingQuota(data: CopilotUsageData[], plan: string = COPILOT_PLANS.BUSINESS): number {
if (!data.length) return 0;
// Get the plan limit for comparison
const planLimit = PLAN_MONTHLY_LIMITS[plan] || PLAN_MONTHLY_LIMITS[COPILOT_PLANS.BUSINESS];
// Get the last date from the data to determine the current month and days elapsed
const lastDate = getLastDateFromData(data);
if (!lastDate) return 0;
const lastDateObj = new Date(lastDate);
const year = lastDateObj.getFullYear();
const month = lastDateObj.getMonth();
// Calculate the first day of the month and days elapsed (inclusive)
const firstDayOfMonth = new Date(year, month, 1);
const daysElapsed = lastDateObj.getDate(); // getDate() returns day of month (1-31)
// Calculate total days in this month
const totalDaysInMonth = new Date(year, month + 1, 0).getDate();
// Aggregate total requests per user for the current month only
const userTotals: Record<string, number> = {};
data.forEach(item => {
const itemDate = new Date(item.timestamp);
// Only count data from the current month (same year and month as last date)
if (itemDate.getFullYear() === year && itemDate.getMonth() === month) {
userTotals[item.user] = (userTotals[item.user] || 0) + item.requestsUsed;
}
});
// For each user, calculate their projected monthly usage
let projectedExceedingUsers = 0;
Object.entries(userTotals).forEach(([user, totalRequests]) => {
// Calculate average daily requests for this user
const averageDailyRequests = totalRequests / daysElapsed;
// Project to full month
const projectedMonthlyRequests = averageDailyRequests * totalDaysInMonth;
// Check if they would exceed the limit
if (projectedMonthlyRequests > planLimit) {
projectedExceedingUsers++;
}
});
return projectedExceedingUsers;
}
/**
* Get detailed data for users projected to exceed their quota by month-end
* @param data - Array of Copilot usage data
* @param plan - The plan type to check limits against (defaults to BUSINESS)
*/
export function getProjectedUsersExceedingQuotaDetails(data: CopilotUsageData[], plan: string = COPILOT_PLANS.BUSINESS): ProjectedUserData[] {
if (!data.length) return [];
// Get the plan limit for comparison
const planLimit = PLAN_MONTHLY_LIMITS[plan] || PLAN_MONTHLY_LIMITS[COPILOT_PLANS.BUSINESS];
// Get the last date from the data to determine the current month and days elapsed
const lastDate = getLastDateFromData(data);
if (!lastDate) return [];
const lastDateObj = new Date(lastDate);
const year = lastDateObj.getFullYear();
const month = lastDateObj.getMonth();
// Calculate the first day of the month and days elapsed (inclusive)
const firstDayOfMonth = new Date(year, month, 1);
const daysElapsed = lastDateObj.getDate(); // getDate() returns day of month (1-31)
// Calculate total days in this month
const totalDaysInMonth = new Date(year, month + 1, 0).getDate();
// Aggregate total requests per user for the current month only
const userTotals: Record<string, number> = {};
data.forEach(item => {
const itemDate = new Date(item.timestamp);
// Only count data from the current month (same year and month as last date)
if (itemDate.getFullYear() === year && itemDate.getMonth() === month) {
userTotals[item.user] = (userTotals[item.user] || 0) + item.requestsUsed;
}
});
// Build the list of users projected to exceed quota
const projectedUsers: ProjectedUserData[] = [];
Object.entries(userTotals).forEach(([user, totalRequests]) => {
// Calculate average daily requests for this user
const averageDailyRequests = totalRequests / daysElapsed;
// Project to full month
const projectedMonthlyRequests = averageDailyRequests * totalDaysInMonth;
// Check if they would exceed the limit
if (projectedMonthlyRequests > planLimit) {
projectedUsers.push({
user,
currentRequests: totalRequests,
projectedMonthlyTotal: projectedMonthlyRequests,
daysElapsed,
dailyAverage: averageDailyRequests
});
}
});
// Sort by projected total descending (highest projected usage first)
return projectedUsers.sort((a, b) => b.projectedMonthlyTotal - a.projectedMonthlyTotal);
}
/**
* Calculate the total expected excess cost if there were no monthly quota limit.
* For each user who has reached the plan limit:
* 1. Find the day their cumulative requests hit the limit (budget exhaustion day).
* 2. Compute daily average requests per model, excluding the last usage day (to avoid partial-day skew).
* 3. Project those requests over the remaining days after the exhaustion day.
* 4. Apply each model's cost multiplier and sum the cost at $0.04/PRU.
*/
export function getExpectedExcessCost(data: CopilotUsageData[], plan: string = COPILOT_PLANS.BUSINESS): number {
if (!data.length) return 0;
const planLimit = (PLAN_MONTHLY_LIMITS as Record<string, number>)[plan] ?? PLAN_MONTHLY_LIMITS[COPILOT_PLANS.BUSINESS];
const lastDate = getLastDateFromData(data);
if (!lastDate) return 0;
const lastDateObj = new Date(lastDate);
const totalDaysInMonth = new Date(lastDateObj.getFullYear(), lastDateObj.getMonth() + 1, 0).getDate();
// Group all items by user
const userDataMap: Record<string, CopilotUsageData[]> = {};
data.forEach(item => {
if (!userDataMap[item.user]) userDataMap[item.user] = [];
userDataMap[item.user].push(item);
});
let totalExpectedCost = 0;
Object.values(userDataMap).forEach(userItems => {
// Only process users who have reached the plan limit
const totalRequests = userItems.reduce((sum, item) => sum + item.requestsUsed, 0);
if (totalRequests < planLimit) return;
// Group by date (YYYY-MM-DD), sorted ascending
const byDate: Record<string, CopilotUsageData[]> = {};
userItems.forEach(item => {
const date = item.timestamp.toISOString().split('T')[0];
if (!byDate[date]) byDate[date] = [];
byDate[date].push(item);
});
const sortedDates = Object.keys(byDate).sort();
// Find the day cumulative requests first reach the plan limit
let cumulative = 0;
let budgetExhaustionDayOfMonth: number | null = null;
for (const date of sortedDates) {
const dayTotal = byDate[date].reduce((sum, item) => sum + item.requestsUsed, 0);
cumulative += dayTotal;
if (cumulative >= planLimit) {
budgetExhaustionDayOfMonth = new Date(date).getDate();
break;
}
}
if (budgetExhaustionDayOfMonth === null) return;
const remainingDays = totalDaysInMonth - budgetExhaustionDayOfMonth;
if (remainingDays <= 0) return;
// Compute daily average per model, excluding the last usage day (which may be partial)
const lastUsageDate = sortedDates[sortedDates.length - 1];
const datesForAverage = sortedDates.filter(d => d !== lastUsageDate);
if (datesForAverage.length === 0) return;
const modelTotals: Record<string, number> = {};
datesForAverage.forEach(date => {
byDate[date].forEach(item => {
modelTotals[item.model] = (modelTotals[item.model] || 0) + item.requestsUsed;
});
});
const numDays = datesForAverage.length;
// Project extra requests per model over remaining days
Object.entries(modelTotals).forEach(([model, total]) => {
const multiplier = getModelMultiplier(model);
if (multiplier === 0) return; // Free models have no cost
const dailyAvg = total / numDays;
const projectedExtra = dailyAvg * remainingDays;
totalExpectedCost += projectedExtra * EXCESS_REQUEST_COST;
});
});
return totalExpectedCost;
}
// Re-export month utilities for backward compatibility
export { getAvailableMonths, filterDataByMonth, getMonthCoverage } from './month-utils';
export type { MonthOption } from '../types/month';
// User-specific analysis interfaces and functions
export interface UserWeeklyData {
year: number;
week: number; // ISO week number
startDate: string; // YYYY-MM-DD format
endDate: string; // YYYY-MM-DD format
compliantRequests: number;
exceedingRequests: number;
totalRequests: number;
modelsUsed: string[];
}
export interface UserAnalysisData {
user: string;
totalRequests: number;
compliantRequests: number;
exceedingRequests: number;
exceedsFreeBudget: boolean;
expectedCostWithoutLimit: number;
uniqueModels: string[];
weeklyBreakdown: UserWeeklyData[];
dailyAverage: number;
firstActivityDate: string;
lastActivityDate: string;