@critical-path/core 0.17.0 → 0.18.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,403 @@
1
+ import type {
2
+ Task,
3
+ TimeEntry,
4
+ User,
5
+ Team,
6
+ WorkloadInterval,
7
+ WorkloadGroupBy,
8
+ WorkloadMetric,
9
+ WorkloadBucket,
10
+ WorkloadDistribution,
11
+ WorkloadDistributionOptions
12
+ } from '../types/index.js';
13
+
14
+ export interface WorkloadContext {
15
+ tasks: Task[];
16
+ timeEntries?: TimeEntry[];
17
+ users?: User[];
18
+ teams?: Team[];
19
+ projectId?: string;
20
+ }
21
+
22
+ function toDateString(d: Date): string {
23
+ return d.toISOString().split('T')[0];
24
+ }
25
+
26
+ function parseDateOnly(isoString: string): Date {
27
+ const parts = isoString.split('T')[0].split('-');
28
+ return new Date(Date.UTC(parseInt(parts[0], 10), parseInt(parts[1], 10) - 1, parseInt(parts[2], 10)));
29
+ }
30
+
31
+ function addDays(d: Date, days: number): Date {
32
+ const res = new Date(d.getTime());
33
+ res.setUTCDate(res.getUTCDate() + days);
34
+ return res;
35
+ }
36
+
37
+ function startOfWeek(d: Date): Date {
38
+ const date = new Date(d.getTime());
39
+ const day = date.getUTCDay();
40
+ // Monday is day 1, Sunday is day 0 -> shift Sunday to 7
41
+ const diff = date.getUTCDate() - day + (day === 0 ? -6 : 1);
42
+ return new Date(Date.UTC(date.getUTCFullYear(), date.getUTCMonth(), diff));
43
+ }
44
+
45
+ function startOfMonth(d: Date): Date {
46
+ return new Date(Date.UTC(d.getUTCFullYear(), d.getUTCMonth(), 1));
47
+ }
48
+
49
+ function nextBucketDate(d: Date, interval: WorkloadInterval): Date {
50
+ if (interval === 'day') {
51
+ return addDays(d, 1);
52
+ }
53
+ if (interval === 'week') {
54
+ return addDays(d, 7);
55
+ }
56
+ // month: next month 1st
57
+ return new Date(Date.UTC(d.getUTCFullYear(), d.getUTCMonth() + 1, 1));
58
+ }
59
+
60
+ function getBucketKey(d: Date, interval: WorkloadInterval): string {
61
+ if (interval === 'day') {
62
+ return toDateString(d);
63
+ }
64
+ if (interval === 'week') {
65
+ return toDateString(startOfWeek(d));
66
+ }
67
+ return toDateString(startOfMonth(d));
68
+ }
69
+
70
+ function getTaskDurationHours(task: Task): number {
71
+ if (typeof task.estimatedHours === 'number' && task.estimatedHours >= 0) {
72
+ return task.estimatedHours;
73
+ }
74
+ if (typeof task.estimatedDurationMinutes === 'number' && task.estimatedDurationMinutes >= 0) {
75
+ return task.estimatedDurationMinutes / 60;
76
+ }
77
+ if (typeof task.actualHours === 'number' && task.actualHours > 0) {
78
+ return task.actualHours;
79
+ }
80
+ return 1;
81
+ }
82
+
83
+ export function calculateWorkloadDistribution(
84
+ context: WorkloadContext,
85
+ options: WorkloadDistributionOptions = {}
86
+ ): WorkloadDistribution {
87
+ const { tasks, timeEntries = [], users = [], teams = [], projectId } = context;
88
+ const interval: WorkloadInterval = options.interval || 'week';
89
+ const groupBy: WorkloadGroupBy = options.groupBy || 'assignee';
90
+ const metric: WorkloadMetric = options.metric || 'blended';
91
+ const defaultWeeklyCapacity = options.defaultWeeklyCapacityHours ?? 40;
92
+
93
+ // Build lookups for human-readable labels
94
+ const userMap = new Map<string, User>(users.map((u) => [u.id, u]));
95
+ const teamMap = new Map<string, Team>(teams.map((t) => [t.id, t]));
96
+
97
+ // 1. Determine date range
98
+ let minDate: Date | null = options.startDate ? parseDateOnly(options.startDate) : null;
99
+ let maxDate: Date | null = options.endDate ? parseDateOnly(options.endDate) : null;
100
+
101
+ if (!minDate || !maxDate) {
102
+ const dates: number[] = [];
103
+ for (const t of tasks) {
104
+ if (t.plannedStartDate) dates.push(parseDateOnly(t.plannedStartDate).getTime());
105
+ if (t.actualStartDate) dates.push(parseDateOnly(t.actualStartDate).getTime());
106
+ if (t.dueDate) dates.push(parseDateOnly(t.dueDate).getTime());
107
+ if (t.actualEndDate) dates.push(parseDateOnly(t.actualEndDate).getTime());
108
+ if (t.createdAt) dates.push(parseDateOnly(t.createdAt).getTime());
109
+ }
110
+ for (const te of timeEntries) {
111
+ if (te.loggedAt) dates.push(parseDateOnly(te.loggedAt).getTime());
112
+ }
113
+
114
+ if (dates.length > 0) {
115
+ if (!minDate) minDate = new Date(Math.min(...dates));
116
+ if (!maxDate) maxDate = new Date(Math.max(...dates));
117
+ } else {
118
+ const now = new Date();
119
+ if (!minDate) minDate = addDays(now, -7);
120
+ if (!maxDate) maxDate = addDays(now, 28);
121
+ }
122
+ }
123
+
124
+ // Ensure minDate <= maxDate
125
+ if (minDate > maxDate) {
126
+ maxDate = new Date(minDate.getTime());
127
+ }
128
+
129
+ // Align start to bucket boundary
130
+ let cursor = interval === 'week' ? startOfWeek(minDate) : interval === 'month' ? startOfMonth(minDate) : minDate;
131
+ const endLimit = interval === 'week' ? startOfWeek(maxDate) : interval === 'month' ? startOfMonth(maxDate) : maxDate;
132
+
133
+ // Generate contiguous buckets
134
+ interface InternalBucket {
135
+ date: string;
136
+ startDate: Date;
137
+ endDate: Date;
138
+ timestamp: number;
139
+ values: Record<string, number>;
140
+ }
141
+
142
+ const bucketList: InternalBucket[] = [];
143
+ const bucketMap = new Map<string, InternalBucket>();
144
+
145
+ while (cursor <= endLimit || bucketList.length === 0) {
146
+ const dateStr = toDateString(cursor);
147
+ const nextDate = nextBucketDate(cursor, interval);
148
+ const b: InternalBucket = {
149
+ date: dateStr,
150
+ startDate: new Date(cursor.getTime()),
151
+ endDate: nextDate,
152
+ timestamp: cursor.getTime(),
153
+ values: {}
154
+ };
155
+ bucketList.push(b);
156
+ bucketMap.set(dateStr, b);
157
+ cursor = nextDate;
158
+ }
159
+
160
+ const seriesKeySet = new Set<string>();
161
+
162
+ const getDimensionKey = (task: Task, timeEntry?: TimeEntry): string => {
163
+ switch (groupBy) {
164
+ case 'assignee':
165
+ if (timeEntry?.userId) return timeEntry.userId;
166
+ return task.assigneeId || 'unassigned';
167
+ case 'team':
168
+ return task.teamId || (task.customFields?.teamId as string) || 'unassigned';
169
+ case 'taskType':
170
+ return task.taskType || (task.customFields?.type as string) || 'standard';
171
+ case 'priority':
172
+ return task.priority || 'none';
173
+ case 'status':
174
+ return task.status || 'todo';
175
+ default:
176
+ return 'unassigned';
177
+ }
178
+ };
179
+
180
+ const addValue = (bucket: InternalBucket, key: string, hours: number) => {
181
+ if (hours <= 0) return;
182
+ seriesKeySet.add(key);
183
+ bucket.values[key] = (bucket.values[key] || 0) + hours;
184
+ };
185
+
186
+ const todayStr = toDateString(new Date());
187
+ const taskMap = new Map<string, Task>(tasks.map((t) => [t.id, t]));
188
+
189
+ // 2. Process Logged Hours from TimeEntries
190
+ if (metric === 'logged' || metric === 'blended') {
191
+ for (const entry of timeEntries) {
192
+ if (!entry.hours || entry.hours <= 0) continue;
193
+ const entryDate = parseDateOnly(entry.loggedAt);
194
+ const bKey = getBucketKey(entryDate, interval);
195
+ const bucket = bucketMap.get(bKey);
196
+ if (bucket) {
197
+ const associatedTask = taskMap.get(entry.taskId) || ({
198
+ id: entry.taskId,
199
+ projectId: projectId || '',
200
+ title: '',
201
+ status: 'in_progress',
202
+ priority: 'medium',
203
+ createdAt: entry.loggedAt,
204
+ updatedAt: entry.loggedAt
205
+ } as Task);
206
+ const dimKey = getDimensionKey(associatedTask, entry);
207
+ addValue(bucket, dimKey, entry.hours);
208
+ }
209
+ }
210
+ }
211
+
212
+ // 3. Process Scheduled / Remaining / Blended Hours from Tasks
213
+ if (metric === 'scheduled' || metric === 'remaining' || metric === 'blended') {
214
+ for (const task of tasks) {
215
+ const estimated = getTaskDurationHours(task);
216
+ const logged = task.loggedHours || 0;
217
+ let hoursToDistribute = 0;
218
+
219
+ if (metric === 'scheduled') {
220
+ hoursToDistribute = estimated;
221
+ } else if (metric === 'remaining' || metric === 'blended') {
222
+ if (task.semanticStatus === 'completed' || task.semanticStatus === 'canceled') {
223
+ hoursToDistribute = 0;
224
+ } else {
225
+ hoursToDistribute = Math.max(0, estimated - logged);
226
+ }
227
+ }
228
+
229
+ if (hoursToDistribute <= 0) continue;
230
+
231
+ const dimKey = getDimensionKey(task);
232
+
233
+ // Determine task date range
234
+ let taskStart = task.plannedStartDate
235
+ ? parseDateOnly(task.plannedStartDate)
236
+ : task.actualStartDate
237
+ ? parseDateOnly(task.actualStartDate)
238
+ : task.createdAt
239
+ ? parseDateOnly(task.createdAt)
240
+ : minDate;
241
+
242
+ let taskEnd = task.dueDate
243
+ ? parseDateOnly(task.dueDate)
244
+ : taskStart
245
+ ? addDays(taskStart, Math.max(1, Math.ceil(hoursToDistribute / 8)))
246
+ : maxDate;
247
+
248
+ // In blended mode, uncompleted tasks' remaining hours start from today or planned start (whichever is later)
249
+ if (metric === 'blended') {
250
+ const today = parseDateOnly(todayStr);
251
+ if (taskStart < today) {
252
+ taskStart = today;
253
+ }
254
+ if (taskEnd < taskStart) {
255
+ taskEnd = addDays(taskStart, 1);
256
+ }
257
+ }
258
+
259
+ if (taskEnd < taskStart) {
260
+ taskEnd = taskStart;
261
+ }
262
+
263
+ // Calculate days in task window
264
+ const msPerDay = 1000 * 60 * 60 * 24;
265
+ const totalDays = Math.max(1, Math.round((taskEnd.getTime() - taskStart.getTime()) / msPerDay) + 1);
266
+ const hoursPerDay = hoursToDistribute / totalDays;
267
+
268
+ // Distribute across overlapping buckets
269
+ for (const bucket of bucketList) {
270
+ const bucketLastDay = addDays(bucket.endDate, -1);
271
+ const overlapStart = new Date(Math.max(taskStart.getTime(), bucket.startDate.getTime()));
272
+ const overlapEnd = new Date(Math.min(taskEnd.getTime(), bucketLastDay.getTime()));
273
+
274
+ if (overlapStart <= overlapEnd) {
275
+ const overlapDays = Math.round((overlapEnd.getTime() - overlapStart.getTime()) / msPerDay) + 1;
276
+ const bucketEffort = overlapDays * hoursPerDay;
277
+ addValue(bucket, dimKey, bucketEffort);
278
+ }
279
+ }
280
+ }
281
+ }
282
+
283
+ // Ensure all registered users are in series keys if grouping by assignee
284
+ if (groupBy === 'assignee' && users.length > 0) {
285
+ for (const u of users) {
286
+ seriesKeySet.add(u.id);
287
+ }
288
+ }
289
+ if (groupBy === 'team' && teams.length > 0) {
290
+ for (const t of teams) {
291
+ seriesKeySet.add(t.id);
292
+ }
293
+ }
294
+
295
+ const seriesKeys = Array.from(seriesKeySet).sort();
296
+
297
+ // Create human-readable series labels
298
+ const seriesLabels: Record<string, string> = {};
299
+ for (const key of seriesKeys) {
300
+ if (groupBy === 'assignee') {
301
+ const u = userMap.get(key);
302
+ seriesLabels[key] = u ? u.name : key === 'unassigned' ? 'Unassigned' : key;
303
+ } else if (groupBy === 'team') {
304
+ const t = teamMap.get(key);
305
+ seriesLabels[key] = t ? t.name : key === 'unassigned' ? 'Unassigned' : key;
306
+ } else {
307
+ seriesLabels[key] = key.charAt(0).toUpperCase() + key.slice(1).replace(/_/g, ' ');
308
+ }
309
+ }
310
+
311
+ // 4. Calculate Capacity & Normalize Buckets
312
+ let totalDistributedHours = 0;
313
+ let sumCapacityAcrossBuckets = 0;
314
+
315
+ const buckets: WorkloadBucket[] = bucketList.map((ib) => {
316
+ const values: Record<string, number> = {};
317
+ const capacity: Record<string, number> = {};
318
+ let bucketTotalHours = 0;
319
+ let bucketTotalCapacity = 0;
320
+
321
+ for (const key of seriesKeys) {
322
+ const rawHours = ib.values[key] || 0;
323
+ const roundedHours = Math.round(rawHours * 100) / 100;
324
+ values[key] = roundedHours;
325
+ bucketTotalHours += roundedHours;
326
+
327
+ // Capacity calculation
328
+ let weeklyCap = defaultWeeklyCapacity;
329
+ if (options.capacityOverrides && typeof options.capacityOverrides[key] === 'number') {
330
+ weeklyCap = options.capacityOverrides[key];
331
+ } else if (groupBy === 'assignee') {
332
+ const u = userMap.get(key);
333
+ if (u?.weeklyCapacityHours) weeklyCap = u.weeklyCapacityHours;
334
+ else if (key === 'unassigned') weeklyCap = 0;
335
+ } else if (groupBy === 'team') {
336
+ const t = teamMap.get(key);
337
+ if (t?.weeklyCapacityHours) {
338
+ weeklyCap = t.weeklyCapacityHours;
339
+ } else if (t?.memberIds?.length) {
340
+ weeklyCap = t.memberIds.length * defaultWeeklyCapacity;
341
+ } else if (key === 'unassigned') {
342
+ weeklyCap = 0;
343
+ }
344
+ }
345
+
346
+ let bucketCap = 0;
347
+ if (interval === 'week') {
348
+ bucketCap = weeklyCap;
349
+ } else if (interval === 'day') {
350
+ bucketCap = Math.round((weeklyCap / 5) * 100) / 100;
351
+ } else if (interval === 'month') {
352
+ const daysInMonth = new Date(Date.UTC(ib.startDate.getUTCFullYear(), ib.startDate.getUTCMonth() + 1, 0)).getUTCDate();
353
+ bucketCap = Math.round((weeklyCap * (daysInMonth / 7)) * 100) / 100;
354
+ }
355
+
356
+ capacity[key] = bucketCap;
357
+ bucketTotalCapacity += bucketCap;
358
+ }
359
+
360
+ bucketTotalHours = Math.round(bucketTotalHours * 100) / 100;
361
+ bucketTotalCapacity = Math.round(bucketTotalCapacity * 100) / 100;
362
+ totalDistributedHours += bucketTotalHours;
363
+ sumCapacityAcrossBuckets += bucketTotalCapacity;
364
+
365
+ const utilizationRatio =
366
+ bucketTotalCapacity > 0
367
+ ? Math.round((bucketTotalHours / bucketTotalCapacity) * 1000) / 1000
368
+ : undefined;
369
+
370
+ return {
371
+ date: ib.date,
372
+ timestamp: ib.timestamp,
373
+ totalHours: bucketTotalHours,
374
+ values,
375
+ capacity,
376
+ totalCapacity: bucketTotalCapacity,
377
+ utilizationRatio
378
+ };
379
+ });
380
+
381
+ totalDistributedHours = Math.round(totalDistributedHours * 100) / 100;
382
+ sumCapacityAcrossBuckets = Math.round(sumCapacityAcrossBuckets * 100) / 100;
383
+
384
+ const averageUtilization =
385
+ sumCapacityAcrossBuckets > 0
386
+ ? Math.round((totalDistributedHours / sumCapacityAcrossBuckets) * 1000) / 1000
387
+ : undefined;
388
+
389
+ return {
390
+ projectId,
391
+ startDate: toDateString(minDate),
392
+ endDate: toDateString(maxDate),
393
+ interval,
394
+ groupBy,
395
+ metric,
396
+ seriesKeys,
397
+ seriesLabels,
398
+ buckets,
399
+ totalHours: totalDistributedHours,
400
+ totalCapacity: sumCapacityAcrossBuckets,
401
+ averageUtilization
402
+ };
403
+ }
@@ -30,7 +30,9 @@ import type {
30
30
  StandardTaskTimelineItem,
31
31
  ConcreteTaskEvidence,
32
32
  TaskMetrics,
33
- TaskProgressHistory
33
+ TaskProgressHistory,
34
+ WorkloadDistribution,
35
+ WorkloadDistributionOptions
34
36
  } from '../types/index.js';
35
37
  import { StorageAdapter, InMemoryStore } from '../store/index.js';
36
38
  import { PluginRegistry } from '../plugins/index.js';
@@ -84,6 +86,7 @@ import {
84
86
  reconstructTaskProgressHistory,
85
87
  type MetricOptions
86
88
  } from '../domain/metrics.js';
89
+ import { calculateWorkloadDistribution } from '../domain/workload.js';
87
90
 
88
91
  export class CriticalPathEngine {
89
92
  public readonly store: StorageAdapter;
@@ -1509,6 +1512,27 @@ export class CriticalPathEngine {
1509
1512
  });
1510
1513
  }
1511
1514
 
1515
+ async getWorkloadDistribution(
1516
+ projectId?: string,
1517
+ options: WorkloadDistributionOptions = {}
1518
+ ): Promise<WorkloadDistribution> {
1519
+ const tasks = await this.store.getTasks(projectId);
1520
+ const teams = await this.store.getTeams();
1521
+
1522
+ const timeEntriesNested = await Promise.all(tasks.map((t) => this.store.getTimeEntries(t.id)));
1523
+ const timeEntries: TimeEntry[] = timeEntriesNested.flat();
1524
+
1525
+ return calculateWorkloadDistribution(
1526
+ {
1527
+ tasks,
1528
+ timeEntries,
1529
+ teams,
1530
+ projectId
1531
+ },
1532
+ options
1533
+ );
1534
+ }
1535
+
1512
1536
  private async dispatchWebhook(event: WebhookEvent, payload: Record<string, unknown>): Promise<void> {
1513
1537
  const webhooks = await this.store.getWebhooks();
1514
1538
  const active = webhooks.filter((w) => w.active && w.events.includes(event));
@@ -39,6 +39,7 @@ export interface User {
39
39
  email: string;
40
40
  avatarUrl?: string;
41
41
  role: Role;
42
+ weeklyCapacityHours?: number;
42
43
  createdAt: string;
43
44
  }
44
45
 
@@ -48,6 +49,7 @@ export interface Team {
48
49
  description?: string;
49
50
  leaderId?: string;
50
51
  memberIds: string[];
52
+ weeklyCapacityHours?: number;
51
53
  createdAt: string;
52
54
  updatedAt: string;
53
55
  }
@@ -630,3 +632,42 @@ export interface TaskLadderView {
630
632
  metrics?: TaskMetrics;
631
633
  }
632
634
 
635
+ export type WorkloadInterval = 'day' | 'week' | 'month';
636
+ export type WorkloadGroupBy = 'assignee' | 'team' | 'taskType' | 'priority' | 'status';
637
+ export type WorkloadMetric = 'scheduled' | 'logged' | 'remaining' | 'blended';
638
+
639
+ export interface WorkloadBucket {
640
+ date: string; // ISO date string e.g. "2026-09-14" (start of bucket)
641
+ timestamp: number; // Unix timestamp in ms
642
+ totalHours: number;
643
+ values: Record<string, number>; // Dimension key to hours: { [dimensionKey]: hours }
644
+ capacity?: Record<string, number>; // Dimension key to available capacity hours: { [dimensionKey]: capacityHours }
645
+ totalCapacity?: number;
646
+ utilizationRatio?: number; // totalHours / totalCapacity
647
+ }
648
+
649
+ export interface WorkloadDistribution {
650
+ projectId?: string;
651
+ startDate: string;
652
+ endDate: string;
653
+ interval: WorkloadInterval;
654
+ groupBy: WorkloadGroupBy;
655
+ metric: WorkloadMetric;
656
+ seriesKeys: string[]; // Unique series keys sorted across all buckets
657
+ seriesLabels: Record<string, string>; // Human-readable labels e.g. { [key]: "Alice" }
658
+ buckets: WorkloadBucket[];
659
+ totalHours: number;
660
+ totalCapacity?: number;
661
+ averageUtilization?: number;
662
+ }
663
+
664
+ export interface WorkloadDistributionOptions {
665
+ startDate?: string;
666
+ endDate?: string;
667
+ interval?: WorkloadInterval; // default: 'week'
668
+ groupBy?: WorkloadGroupBy; // default: 'assignee'
669
+ metric?: WorkloadMetric; // default: 'blended'
670
+ defaultWeeklyCapacityHours?: number; // default: 40
671
+ capacityOverrides?: Record<string, number>; // e.g. { [assigneeOrTeamId]: weeklyCapacityHours }
672
+ }
673
+
@@ -1 +1 @@
1
- {"root":["./src/deliverables.test.ts","./src/index.test.ts","./src/index.ts","./src/status.test.ts","./src/task-state.test.ts","./src/use-case-validation.test.ts","./src/domain/cpm.test.ts","./src/domain/cpm.ts","./src/domain/custom-fields.ts","./src/domain/ddd.test.ts","./src/domain/entities.ts","./src/domain/events.ts","./src/domain/graph.ts","./src/domain/index.ts","./src/domain/ladder.test.ts","./src/domain/ladder.ts","./src/domain/metrics.test.ts","./src/domain/metrics.ts","./src/engine/index.ts","./src/plugins/index.ts","./src/storage/file-storage.ts","./src/storage/firebase-storage.ts","./src/storage/index.ts","./src/storage/s3.ts","./src/storage/storage.test.ts","./src/store/firebase.test.ts","./src/store/firebase.ts","./src/store/index.ts","./src/store/sqlite.test.ts","./src/store/sqlite.ts","./src/types/index.ts","./src/utils/index.ts","./src/utils/key.test.ts","./src/utils/key.ts","./src/utils/mentions.test.ts","./src/utils/mentions.ts","./src/utils/status.ts","./src/utils/workflow.ts"],"version":"5.9.3"}
1
+ {"root":["./src/deliverables.test.ts","./src/index.test.ts","./src/index.ts","./src/status.test.ts","./src/task-state.test.ts","./src/use-case-validation.test.ts","./src/domain/cpm.test.ts","./src/domain/cpm.ts","./src/domain/custom-fields.ts","./src/domain/ddd.test.ts","./src/domain/entities.ts","./src/domain/events.ts","./src/domain/graph.ts","./src/domain/index.ts","./src/domain/ladder.test.ts","./src/domain/ladder.ts","./src/domain/metrics.test.ts","./src/domain/metrics.ts","./src/domain/workload.test.ts","./src/domain/workload.ts","./src/engine/index.ts","./src/plugins/index.ts","./src/storage/file-storage.ts","./src/storage/firebase-storage.ts","./src/storage/index.ts","./src/storage/s3.ts","./src/storage/storage.test.ts","./src/store/firebase.test.ts","./src/store/firebase.ts","./src/store/index.ts","./src/store/sqlite.test.ts","./src/store/sqlite.ts","./src/types/index.ts","./src/utils/index.ts","./src/utils/key.test.ts","./src/utils/key.ts","./src/utils/mentions.test.ts","./src/utils/mentions.ts","./src/utils/status.ts","./src/utils/workflow.ts"],"version":"5.9.3"}