@jsb188/schedule 1.1.2

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.
Files changed (60) hide show
  1. package/package.json +62 -0
  2. package/src/constants/schedule.ts +549 -0
  3. package/src/css.d.ts +7 -0
  4. package/src/libs/gantt-geometry.ts +771 -0
  5. package/src/libs/gantt-histogram.ts +124 -0
  6. package/src/libs/gantt-keyboard.ts +113 -0
  7. package/src/libs/gantt-state.ts +57 -0
  8. package/src/libs/gantt-url.ts +63 -0
  9. package/src/modules/Gantt.helpers.ts +119 -0
  10. package/src/modules/Gantt.tsx +584 -0
  11. package/src/types/schedule.d.ts +1149 -0
  12. package/src/ui/ActivityFormUI.tsx +133 -0
  13. package/src/ui/GanttEditorsUI.tsx +102 -0
  14. package/src/ui/GanttHistogramUI.tsx +236 -0
  15. package/src/ui/GanttUI.tsx +792 -0
  16. package/src/ui/ProjectFormUI.tsx +250 -0
  17. package/src/ui/ProjectMobileListUI.tsx +80 -0
  18. package/src/ui/ProjectToolbarUI.tsx +54 -0
  19. package/src/ui/RelationshipListUI.tsx +176 -0
  20. package/src/ui/ScheduleRunUI.tsx +173 -0
  21. package/src/ui/ScheduleSettingsUI.tsx +420 -0
  22. package/src/utils/coverage.helpers.ts +679 -0
  23. package/src/utils/coverage.ts +630 -0
  24. package/src/utils/cpm.helpers.ts +674 -0
  25. package/src/utils/cpm.ts +907 -0
  26. package/src/utils/cpmLeveling.helpers.ts +564 -0
  27. package/src/utils/cpmLeveling.ts +367 -0
  28. package/src/utils/defaults.ts +8 -0
  29. package/src/utils/eligibility.ts +457 -0
  30. package/src/utils/planCsv.ts +344 -0
  31. package/src/utils/predecessorText.ts +96 -0
  32. package/src/utils/recurrence.ts +616 -0
  33. package/src/utils/request.ts +153 -0
  34. package/src/utils/resource.ts +182 -0
  35. package/src/utils/rule.ts +216 -0
  36. package/src/utils/run.ts +43 -0
  37. package/src/utils/series.ts +161 -0
  38. package/src/utils/slot.ts +208 -0
  39. package/src/utils/workTime.ts +1382 -0
  40. package/tests/coverage.fixtures.ts +111 -0
  41. package/tests/coverage.test.ts +503 -0
  42. package/tests/cpm.bench.test.ts +154 -0
  43. package/tests/cpm.test.ts +354 -0
  44. package/tests/cpmCorrectness.test.ts +327 -0
  45. package/tests/cpmLeveling.test.ts +471 -0
  46. package/tests/eligibility.test.ts +320 -0
  47. package/tests/gantt-geometry.test.ts +367 -0
  48. package/tests/gantt-histogram.test.ts +78 -0
  49. package/tests/gantt-keyboard.test.ts +69 -0
  50. package/tests/helpers/cpmFixtures.ts +101 -0
  51. package/tests/projectInputs.test.ts +165 -0
  52. package/tests/recurrence.test.ts +68 -0
  53. package/tests/request.test.ts +99 -0
  54. package/tests/resource.test.ts +95 -0
  55. package/tests/rule.test.ts +98 -0
  56. package/tests/series.test.ts +120 -0
  57. package/tests/workTime.test.ts +1007 -0
  58. package/tests/workTimeContracts.test.ts +111 -0
  59. package/tsconfig.json +13 -0
  60. package/vitest.config.ts +8 -0
@@ -0,0 +1,907 @@
1
+ import { SCHEDULE_RELATIONSHIP_TYPE_ENUMS } from '../constants/schedule.ts';
2
+ import type {
3
+ CpmActivityResult,
4
+ CpmScheduleInput,
5
+ CpmScheduleResult,
6
+ ScheduleProjectRunStatsObj,
7
+ } from '../types/schedule.d.ts';
8
+ import {
9
+ addLag,
10
+ addMinutes,
11
+ buildCpmCalendarSet,
12
+ buildWbsPathIndex,
13
+ DiagnosticCollector,
14
+ describeCycle,
15
+ findStronglyConnectedComponents,
16
+ getActivityCalendar,
17
+ getActivityStatus,
18
+ getConstraints,
19
+ getRemainingMinutes,
20
+ getTopologicalOrder,
21
+ getWbsSubtreeRange,
22
+ instant,
23
+ isDrivingActivity,
24
+ isSameWorkingInstant,
25
+ minutesBetween,
26
+ snapFinish,
27
+ snapStart,
28
+ validateCpmScheduleInput,
29
+ type CpmActivityState,
30
+ type CpmContext,
31
+ } from './cpm.helpers.ts';
32
+ import { resolveLevelingOptions, runResourceLeveling } from './cpmLeveling.ts';
33
+ import {
34
+ WorkTimeEmptyCalendarError,
35
+ WorkTimeInvalidZoneError,
36
+ WorkTimeRangeError,
37
+ } from './workTime.ts';
38
+
39
+ /* Construct graph states without mutating the caller's network or options. */
40
+ function buildContext(
41
+ input: CpmScheduleInput,
42
+ collector: DiagnosticCollector,
43
+ referenced: Set<string>,
44
+ ): CpmContext {
45
+ const floorMs = Math.max(
46
+ instant(input.projectStartAt)!,
47
+ instant(input.dataDateAt)!,
48
+ );
49
+ const calendarSet = buildCpmCalendarSet(
50
+ input,
51
+ referenced,
52
+ floorMs,
53
+ resolveLevelingOptions(input.options?.leveling).horizonDays,
54
+ );
55
+ const states = new Map<string, CpmActivityState>();
56
+ for (const activity of input.activities) {
57
+ const status = getActivityStatus(activity);
58
+ states.set(activity.id, {
59
+ input: activity,
60
+ status,
61
+ remaining: getRemainingMinutes(activity, status),
62
+ calendar: getActivityCalendar(calendarSet, activity.calendarId),
63
+ isDriving: isDrivingActivity(activity),
64
+ constraints: getConstraints(activity),
65
+ predecessors: [],
66
+ successors: [],
67
+ es: NaN,
68
+ ef: NaN,
69
+ ls: NaN,
70
+ lf: NaN,
71
+ start: NaN,
72
+ finish: NaN,
73
+ resumeStart: NaN,
74
+ totalFloat: null,
75
+ freeFloat: null,
76
+ drivingPredecessorIds: [],
77
+ drivenBy: 'FLOOR',
78
+ onLongestPath: false,
79
+ isCritical: false,
80
+ levelingDelay: 0,
81
+ constrainedBy: null,
82
+ });
83
+ }
84
+ const pairs = new Set<string>();
85
+ for (const rel of input.relationships) {
86
+ const pred = states.get(rel.predecessorId);
87
+ const succ = states.get(rel.successorId);
88
+ if (!pred || !succ || pred === succ) continue;
89
+ const key = JSON.stringify([rel.predecessorId, rel.successorId]);
90
+ if (pairs.has(key)) continue;
91
+ pairs.add(key);
92
+ if (
93
+ !(SCHEDULE_RELATIONSHIP_TYPE_ENUMS as readonly string[]).includes(
94
+ rel.type,
95
+ )
96
+ )
97
+ continue;
98
+ const normalized = {
99
+ ...rel,
100
+ lagMinutes: Number.isFinite(rel.lagMinutes)
101
+ ? Math.round(rel.lagMinutes!)
102
+ : 0,
103
+ };
104
+ pred.successors.push(normalized);
105
+ succ.predecessors.push(normalized);
106
+ }
107
+ return {
108
+ input,
109
+ states,
110
+ calendarSet,
111
+ collector,
112
+ floorMs,
113
+ dataDateMs: instant(input.dataDateAt)!,
114
+ projectFinishMs: floorMs,
115
+ lateFinishBasisMs: floorMs,
116
+ progressLogic:
117
+ input.options?.progressLogic === 'OVERRIDE' ? 'OVERRIDE' : 'RETAINED',
118
+ lagCalendar: ['CONTINUOUS', 'PROJECT', 'SUCCESSOR'].includes(
119
+ input.options?.lagCalendar || '',
120
+ )
121
+ ? input.options!.lagCalendar!
122
+ : 'PREDECESSOR',
123
+ criticalityMode:
124
+ input.options?.criticalityMode === 'LONGEST_PATH'
125
+ ? 'LONGEST_PATH'
126
+ : 'FLOAT',
127
+ criticalThreshold: Number.isFinite(
128
+ input.options?.criticalFloatThresholdMinutes,
129
+ )
130
+ ? input.options!.criticalFloatThresholdMinutes!
131
+ : 0,
132
+ cursorActivityId: null,
133
+ };
134
+ }
135
+
136
+ /* Apply early dates from predecessor bounds, remaining work, and normalized constraints. */
137
+ function runForwardPass(context: CpmContext, order: CpmActivityState[]): void {
138
+ for (const state of order) {
139
+ context.cursorActivityId = state.input.id;
140
+ const { calendar: cal, remaining, status, constraints: c } = state;
141
+ const actualStart = instant(state.input.actualStartAt);
142
+ const actualFinish = instant(state.input.actualFinishAt);
143
+ if (
144
+ (actualStart != null && actualStart > context.dataDateMs) ||
145
+ (actualFinish != null && actualFinish > context.dataDateMs)
146
+ ) {
147
+ context.collector.add({
148
+ code: 'ACTUALS_AFTER_DATA_DATE',
149
+ severity: 'WARN',
150
+ activityId: state.input.id,
151
+ message: 'Activity actuals are after the project data date.',
152
+ });
153
+ }
154
+ if (status === 'COMPLETE') {
155
+ state.es = actualStart ?? actualFinish!;
156
+ state.ef = actualFinish!;
157
+ state.drivenBy = 'ACTUALS';
158
+ continue;
159
+ }
160
+ const starts: Array<{ id: string; ms: number }> = [];
161
+ const finishes: Array<{ id: string; ms: number }> = [];
162
+ let unfinished: string | null = null;
163
+ for (const rel of state.predecessors) {
164
+ const pred = context.states.get(rel.predecessorId)!;
165
+ if (!pred.isDriving) continue;
166
+ const ms = addLag(
167
+ context,
168
+ rel.type === 'SS' || rel.type === 'SF' ? pred.es : pred.ef,
169
+ rel.lagMinutes || 0,
170
+ pred,
171
+ state,
172
+ );
173
+ (rel.type === 'FS' || rel.type === 'SS' ? starts : finishes).push({
174
+ id: pred.input.id,
175
+ ms,
176
+ });
177
+ if (rel.type === 'FS' && pred.status !== 'COMPLETE')
178
+ unfinished = pred.input.id;
179
+ }
180
+ const startBound = starts.reduce(
181
+ (max, candidate) => Math.max(max, candidate.ms),
182
+ -Infinity,
183
+ );
184
+ const finishBound = finishes.reduce(
185
+ (max, candidate) => Math.max(max, candidate.ms),
186
+ -Infinity,
187
+ );
188
+ /* Record all binding predecessors on the successor's working calendar. */
189
+ const drive = (
190
+ candidates: typeof starts,
191
+ bound: number,
192
+ kind: CpmActivityState['drivenBy'],
193
+ ) => {
194
+ state.drivenBy = kind;
195
+ state.drivingPredecessorIds = candidates
196
+ .filter((candidate) => isSameWorkingInstant(cal, candidate.ms, bound))
197
+ .map((candidate) => candidate.id);
198
+ };
199
+ /* Constraint changes terminate a longest-path driving chain. */
200
+ const constraintDriven = () => {
201
+ state.drivenBy = 'CONSTRAINT';
202
+ state.drivingPredecessorIds = [];
203
+ };
204
+ /* Report a date constraint that cannot put unstarted work before the data date. */
205
+ const beforeFloor = (target: number, floor: number) =>
206
+ context.collector.add({
207
+ code: 'CONSTRAINT_BEFORE_DATA_DATE',
208
+ severity: 'WARN',
209
+ activityId: state.input.id,
210
+ minutes: minutesBetween(cal, target, floor),
211
+ message:
212
+ 'Constraint is before the project data date; remaining work starts at the data date.',
213
+ });
214
+ /* Report a mandatory target that conflicts with logic or remaining progress. */
215
+ const override = () =>
216
+ context.collector.add({
217
+ code: 'CONSTRAINT_OVERRIDES_LOGIC',
218
+ severity: 'WARN',
219
+ activityId: state.input.id,
220
+ message:
221
+ 'Mandatory constraint is earlier than the logic or remaining work allows.',
222
+ });
223
+ const finishConstraint = Math.max(
224
+ c.finish.onMs ?? -Infinity,
225
+ c.finish.onOrAfterMs ?? -Infinity,
226
+ );
227
+ if (status === 'IN_PROGRESS') {
228
+ state.es = actualStart!;
229
+ state.drivenBy = 'ACTUALS';
230
+ if (unfinished)
231
+ context.collector.add({
232
+ code: 'OUT_OF_SEQUENCE',
233
+ severity: 'WARN',
234
+ activityId: state.input.id,
235
+ relatedActivityId: unfinished,
236
+ message:
237
+ 'Activity started before its finish-to-start predecessor finished.',
238
+ });
239
+ let resume = Math.max(context.dataDateMs, state.es);
240
+ if (context.progressLogic === 'RETAINED' && startBound >= resume) {
241
+ resume = startBound;
242
+ drive(starts, startBound, 'ACTUALS');
243
+ }
244
+ state.resumeStart = snapStart(cal, resume);
245
+ state.ef = remaining
246
+ ? addMinutes(cal, resume, remaining)
247
+ : Math.max(
248
+ state.es,
249
+ snapFinish(cal, Math.max(resume, state.resumeStart)),
250
+ );
251
+ if (context.progressLogic === 'RETAINED' && finishBound > state.ef) {
252
+ state.ef = Math.max(state.ef, snapFinish(cal, finishBound));
253
+ drive(finishes, finishBound, 'ACTUALS');
254
+ }
255
+ if (finishConstraint > state.ef) {
256
+ state.ef = Math.max(state.ef, snapFinish(cal, finishConstraint));
257
+ state.drivingPredecessorIds = [];
258
+ }
259
+ if (c.finish.mandatoryMs != null) {
260
+ const target = snapFinish(cal, c.finish.mandatoryMs);
261
+ if (target < state.ef) override();
262
+ state.ef = Math.max(state.ef, target);
263
+ state.drivingPredecessorIds = [];
264
+ }
265
+ if (remaining)
266
+ state.resumeStart = Math.max(
267
+ state.resumeStart,
268
+ addMinutes(cal, state.ef, -remaining),
269
+ );
270
+ continue;
271
+ }
272
+ const floorStart = snapStart(cal, context.floorMs);
273
+ const rawLogic = Math.max(context.floorMs, startBound);
274
+ const logicalStart =
275
+ state.input.type === 'FINISH_MILESTONE' && startBound >= context.floorMs
276
+ ? Math.max(context.floorMs, snapFinish(cal, rawLogic))
277
+ : snapStart(cal, rawLogic);
278
+ state.es = logicalStart;
279
+ if (startBound >= context.floorMs) drive(starts, startBound, 'LOGIC_START');
280
+ const startConstraint = Math.max(
281
+ c.start.onMs ?? -Infinity,
282
+ c.start.onOrAfterMs ?? -Infinity,
283
+ );
284
+ if (startConstraint > rawLogic) {
285
+ state.es = snapStart(cal, startConstraint);
286
+ constraintDriven();
287
+ }
288
+ state.ef = remaining ? addMinutes(cal, state.es, remaining) : state.es;
289
+ if (startConstraint !== -Infinity && startConstraint < context.floorMs)
290
+ beforeFloor(startConstraint, floorStart);
291
+ if (
292
+ finishConstraint !== -Infinity &&
293
+ finishConstraint < addMinutes(cal, floorStart, remaining)
294
+ )
295
+ beforeFloor(finishConstraint, addMinutes(cal, floorStart, remaining));
296
+ const laterFinish = Math.max(finishBound, finishConstraint);
297
+ if (laterFinish > state.ef) {
298
+ const candidateFinish = snapFinish(cal, laterFinish);
299
+ if (candidateFinish > state.ef) {
300
+ state.ef = candidateFinish;
301
+ state.es = remaining ? addMinutes(cal, state.ef, -remaining) : state.ef;
302
+ if (finishConstraint >= finishBound) constraintDriven();
303
+ else drive(finishes, finishBound, 'LOGIC_FINISH');
304
+ }
305
+ }
306
+ if (c.start.mandatoryMs != null) {
307
+ let target = snapStart(cal, c.start.mandatoryMs);
308
+ if (target < floorStart) {
309
+ beforeFloor(target, floorStart);
310
+ target = floorStart;
311
+ } else if (target < logicalStart) override();
312
+ state.es = target;
313
+ state.ef = remaining ? addMinutes(cal, target, remaining) : target;
314
+ constraintDriven();
315
+ }
316
+ if (c.finish.mandatoryMs != null) {
317
+ const target = snapFinish(cal, c.finish.mandatoryMs);
318
+ const start = remaining ? addMinutes(cal, target, -remaining) : target;
319
+ if (start < floorStart) {
320
+ beforeFloor(start, floorStart);
321
+ state.es = floorStart;
322
+ state.ef = remaining
323
+ ? addMinutes(cal, floorStart, remaining)
324
+ : floorStart;
325
+ } else {
326
+ if (target < state.ef) override();
327
+ state.es = start;
328
+ state.ef = target;
329
+ }
330
+ constraintDriven();
331
+ }
332
+ state.resumeStart = state.es;
333
+ }
334
+ }
335
+
336
+ /* Apply finish/start bounds symmetrically and keep actual starts fixed after progress. */
337
+ function runBackwardPass(context: CpmContext, order: CpmActivityState[]): void {
338
+ for (let i = order.length - 1; i >= 0; i--) {
339
+ const state = order[i];
340
+ context.cursorActivityId = state.input.id;
341
+ const { calendar: cal, remaining, constraints: c, status } = state;
342
+ if (status === 'COMPLETE') {
343
+ state.ls = state.es;
344
+ state.lf = state.ef;
345
+ continue;
346
+ }
347
+ let startBound = Infinity;
348
+ let finishBound = Infinity;
349
+ for (const rel of state.successors) {
350
+ const succ = context.states.get(rel.successorId)!;
351
+ if (!succ.isDriving) continue;
352
+ const bound = addLag(
353
+ context,
354
+ rel.type === 'FF' || rel.type === 'SF' ? succ.lf : succ.ls,
355
+ -(rel.lagMinutes || 0),
356
+ state,
357
+ succ,
358
+ );
359
+ if (rel.type === 'FS' || rel.type === 'FF')
360
+ finishBound = Math.min(finishBound, bound);
361
+ else startBound = Math.min(startBound, bound);
362
+ }
363
+ finishBound = Math.min(
364
+ finishBound,
365
+ c.finish.onMs ?? Infinity,
366
+ c.finish.onOrBeforeMs ?? Infinity,
367
+ );
368
+ if (status === 'NOT_STARTED')
369
+ startBound = Math.min(
370
+ startBound,
371
+ c.start.onMs ?? Infinity,
372
+ c.start.onOrBeforeMs ?? Infinity,
373
+ );
374
+ if (startBound === Infinity && finishBound === Infinity)
375
+ finishBound = context.lateFinishBasisMs;
376
+ const finish =
377
+ finishBound === Infinity
378
+ ? Infinity
379
+ : state.input.type === 'START_MILESTONE'
380
+ ? snapStart(cal, finishBound)
381
+ : snapFinish(cal, finishBound);
382
+ const fromFinish =
383
+ finish === Infinity
384
+ ? Infinity
385
+ : remaining
386
+ ? addMinutes(cal, finish, -remaining)
387
+ : finish;
388
+ const fromStart =
389
+ startBound === Infinity
390
+ ? Infinity
391
+ : state.input.type === 'FINISH_MILESTONE'
392
+ ? snapFinish(cal, startBound)
393
+ : snapStart(cal, startBound);
394
+ state.ls = Math.min(fromFinish, fromStart);
395
+ state.lf =
396
+ state.ls === fromFinish
397
+ ? finish
398
+ : remaining
399
+ ? addMinutes(cal, state.ls, remaining)
400
+ : state.ls;
401
+ if (status === 'NOT_STARTED' && c.start.mandatoryMs != null) {
402
+ state.ls = snapStart(cal, c.start.mandatoryMs);
403
+ state.lf = remaining ? addMinutes(cal, state.ls, remaining) : state.ls;
404
+ }
405
+ if (c.finish.mandatoryMs != null) {
406
+ state.lf = snapFinish(cal, c.finish.mandatoryMs);
407
+ state.ls = remaining ? addMinutes(cal, state.lf, -remaining) : state.lf;
408
+ }
409
+ if (status === 'IN_PROGRESS') state.ls = state.es;
410
+ }
411
+ }
412
+
413
+ /* Use the early representation when a late date differs only by nonworking time. */
414
+ function normalizeLateDates(
415
+ context: CpmContext,
416
+ order: CpmActivityState[],
417
+ ): void {
418
+ for (const state of order) {
419
+ context.cursorActivityId = state.input.id;
420
+ if (isSameWorkingInstant(state.calendar, state.es, state.ls))
421
+ state.ls = state.es;
422
+ if (isSameWorkingInstant(state.calendar, state.ef, state.lf))
423
+ state.lf = state.ef;
424
+ }
425
+ }
426
+
427
+ /* Derive total and free float from the unleveled network. */
428
+ function computeFloat(context: CpmContext, order: CpmActivityState[]): void {
429
+ for (const state of order) {
430
+ context.cursorActivityId = state.input.id;
431
+ if (state.status === 'COMPLETE') continue;
432
+ state.totalFloat = minutesBetween(state.calendar, state.ef, state.lf);
433
+ let free = Infinity;
434
+ for (const rel of state.successors) {
435
+ const succ = context.states.get(rel.successorId)!;
436
+ if (!succ.isDriving) continue;
437
+ const target = rel.type === 'FF' || rel.type === 'SF' ? succ.ef : succ.es;
438
+ const origin =
439
+ rel.type === 'SS' || rel.type === 'SF' ? state.es : state.ef;
440
+ free = Math.min(
441
+ free,
442
+ minutesBetween(
443
+ state.calendar,
444
+ origin,
445
+ addLag(context, target, -(rel.lagMinutes || 0), state, succ),
446
+ ),
447
+ );
448
+ }
449
+ state.freeFloat = free === Infinity ? state.totalFloat : free;
450
+ }
451
+ }
452
+
453
+ /* Trace all binding chains from the project finish, independently of float mode. */
454
+ function markLongestPath(context: CpmContext, order: CpmActivityState[]): void {
455
+ const stack = order.filter(
456
+ (state) =>
457
+ state.status !== 'COMPLETE' &&
458
+ isSameWorkingInstant(
459
+ context.calendarSet.defaultCalendar,
460
+ state.ef,
461
+ context.projectFinishMs,
462
+ ),
463
+ );
464
+ while (stack.length) {
465
+ const state = stack.pop()!;
466
+ if (state.onLongestPath || state.status === 'COMPLETE') continue;
467
+ state.onLongestPath = true;
468
+ for (const id of state.drivingPredecessorIds)
469
+ stack.push(context.states.get(id)!);
470
+ }
471
+ for (const state of order)
472
+ state.isCritical =
473
+ state.status !== 'COMPLETE' &&
474
+ (context.criticalityMode === 'LONGEST_PATH'
475
+ ? state.onLongestPath
476
+ : state.totalFloat! <= context.criticalThreshold);
477
+ }
478
+
479
+ /* Move unstarted ALAP activities only through their available free float. */
480
+ function applyAsLateAsPossible(
481
+ context: CpmContext,
482
+ order: CpmActivityState[],
483
+ ): void {
484
+ for (const state of order) {
485
+ context.cursorActivityId = state.input.id;
486
+ if (
487
+ state.status !== 'NOT_STARTED' ||
488
+ !state.constraints.alap ||
489
+ !(state.freeFloat! > 0)
490
+ )
491
+ continue;
492
+ state.es = snapStart(
493
+ state.calendar,
494
+ addMinutes(state.calendar, state.es, state.freeFloat!),
495
+ );
496
+ state.ef = state.remaining
497
+ ? addMinutes(state.calendar, state.es, state.remaining)
498
+ : state.es;
499
+ state.totalFloat = minutesBetween(state.calendar, state.ef, state.lf);
500
+ state.freeFloat = 0;
501
+ if (context.criticalityMode === 'FLOAT')
502
+ state.isCritical = state.totalFloat <= context.criticalThreshold;
503
+ }
504
+ }
505
+
506
+ /* Aggregate one collection of dated members into a summary without scanning unrelated activities. */
507
+ function setSpan(
508
+ context: CpmContext,
509
+ state: CpmActivityState,
510
+ members: CpmActivityState[],
511
+ starts?: number[][],
512
+ finishes?: number[][],
513
+ ): void {
514
+ const floor = snapStart(state.calendar, context.floorMs);
515
+ const fallbackFinish =
516
+ state.input.type === 'LEVEL_OF_EFFORT' && !members.length
517
+ ? Math.max(floor, snapFinish(state.calendar, context.projectFinishMs))
518
+ : floor;
519
+ const fields = [
520
+ ['start', 'finish'],
521
+ ['es', 'ef'],
522
+ ['ls', 'lf'],
523
+ ] as const;
524
+ for (let i = 0; i < fields.length; i++) {
525
+ const [a, b] = fields[i];
526
+ const startValues = starts ? starts[i] : members.map((member) => member[a]);
527
+ const finishValues = finishes
528
+ ? finishes[i]
529
+ : members.map((member) => member[b]);
530
+ state[a] = startValues.reduce(
531
+ (min, value) => Math.min(min, value),
532
+ Infinity,
533
+ );
534
+ if (!Number.isFinite(state[a])) state[a] = floor;
535
+ state[b] = finishValues.reduce(
536
+ (max, value) => Math.max(max, value),
537
+ -Infinity,
538
+ );
539
+ if (!Number.isFinite(state[b]))
540
+ state[b] = startValues.length ? state[a] : fallbackFinish;
541
+ state[b] = Math.max(state[a], state[b]);
542
+ }
543
+ state.status = !members.length
544
+ ? 'NOT_STARTED'
545
+ : members.every((m) => m.status === 'COMPLETE')
546
+ ? 'COMPLETE'
547
+ : members.some((m) => m.status !== 'NOT_STARTED')
548
+ ? 'IN_PROGRESS'
549
+ : 'NOT_STARTED';
550
+ state.remaining =
551
+ state.status === 'COMPLETE'
552
+ ? 0
553
+ : Math.max(
554
+ 0,
555
+ minutesBetween(
556
+ state.calendar,
557
+ Math.max(state.start, context.dataDateMs),
558
+ state.finish,
559
+ ),
560
+ );
561
+ state.totalFloat =
562
+ state.status === 'COMPLETE'
563
+ ? null
564
+ : minutesBetween(state.calendar, state.ef, state.lf);
565
+ state.freeFloat = state.totalFloat;
566
+ }
567
+
568
+ /* Compute WBS subtree summaries and dependency-ordered level-of-effort spans over effective dates. */
569
+ function computeSpanningActivities(context: CpmContext): void {
570
+ const paths = context.input.wbsPaths || {};
571
+ const index = buildWbsPathIndex(paths);
572
+ const membersByNode = new Map<string, CpmActivityState>();
573
+ for (const state of context.states.values()) {
574
+ if (!state.isDriving || !state.input.wbsId) continue;
575
+ const aggregate = membersByNode.get(state.input.wbsId);
576
+ if (!aggregate) {
577
+ membersByNode.set(state.input.wbsId, { ...state });
578
+ continue;
579
+ }
580
+ for (const [start, finish] of [
581
+ ['start', 'finish'],
582
+ ['es', 'ef'],
583
+ ['ls', 'lf'],
584
+ ] as const) {
585
+ aggregate[start] = Math.min(aggregate[start], state[start]);
586
+ aggregate[finish] = Math.max(aggregate[finish], state[finish]);
587
+ }
588
+ if (aggregate.status !== state.status) aggregate.status = 'IN_PROGRESS';
589
+ }
590
+ const { order, residual } = getTopologicalOrder(context.states, false);
591
+ for (const state of context.states.values())
592
+ if (state.input.type === 'WBS_SUMMARY') {
593
+ context.cursorActivityId = state.input.id;
594
+ const prefix = state.input.wbsId && paths[state.input.wbsId];
595
+ const members: CpmActivityState[] = [];
596
+ if (prefix) {
597
+ const [from, to] = getWbsSubtreeRange(index, prefix);
598
+ for (let k = from; k < to; k++) {
599
+ const member = membersByNode.get(index[k][0]);
600
+ if (member) members.push(member);
601
+ }
602
+ }
603
+ setSpan(context, state, members);
604
+ }
605
+ /* Resolve a dated LOE's relationship endpoints for each of its three date pairs. */
606
+ const span = (state: CpmActivityState) => {
607
+ context.cursorActivityId = state.input.id;
608
+ const members = new Set<CpmActivityState>();
609
+ const starts: number[][] = [[], [], []];
610
+ const finishes: number[][] = [[], [], []];
611
+ for (const [i, [a, b]] of (
612
+ [
613
+ ['start', 'finish'],
614
+ ['es', 'ef'],
615
+ ['ls', 'lf'],
616
+ ] as const
617
+ ).entries()) {
618
+ for (const rel of state.predecessors) {
619
+ const pred = context.states.get(rel.predecessorId)!;
620
+ if (!Number.isFinite(pred.es)) continue;
621
+ members.add(pred);
622
+ starts[i].push(
623
+ addLag(
624
+ context,
625
+ rel.type === 'SS' || rel.type === 'SF' ? pred[a] : pred[b],
626
+ rel.lagMinutes || 0,
627
+ pred,
628
+ state,
629
+ ),
630
+ );
631
+ }
632
+ for (const rel of state.successors) {
633
+ const succ = context.states.get(rel.successorId)!;
634
+ if (!Number.isFinite(succ.es)) continue;
635
+ members.add(succ);
636
+ finishes[i].push(
637
+ addLag(
638
+ context,
639
+ rel.type === 'FF' || rel.type === 'FS' ? succ[b] : succ[a],
640
+ -(rel.lagMinutes || 0),
641
+ state,
642
+ succ,
643
+ ),
644
+ );
645
+ }
646
+ }
647
+ setSpan(context, state, [...members], starts, finishes);
648
+ };
649
+ // Seed successor-only spans in reverse, then propagate starts forward and finishes backward.
650
+ for (let i = order.length - 1; i >= 0; i--)
651
+ if (order[i].input.type === 'LEVEL_OF_EFFORT') span(order[i]);
652
+ for (const state of order)
653
+ if (state.input.type === 'LEVEL_OF_EFFORT') span(state);
654
+ for (let i = order.length - 1; i >= 0; i--)
655
+ if (order[i].input.type === 'LEVEL_OF_EFFORT') span(order[i]);
656
+ for (const state of residual) {
657
+ context.collector.add({
658
+ code: 'CYCLE',
659
+ severity: 'WARN',
660
+ activityId: state.input.id,
661
+ message: 'Level-of-effort loop; the activity spans the project.',
662
+ });
663
+ setSpan(context, state, []);
664
+ }
665
+ }
666
+
667
+ /* Report open ends with a single opening/closing exemption and bounded diagnostics. */
668
+ function reportOpenEnds(context: CpmContext, order: CpmActivityState[]): void {
669
+ const starts = order.filter(
670
+ (s) =>
671
+ s.status === 'NOT_STARTED' &&
672
+ !s.constraints.hasStartConstraint &&
673
+ !s.predecessors.some(
674
+ (rel) => context.states.get(rel.predecessorId)!.isDriving,
675
+ ),
676
+ );
677
+ const finishes = order.filter(
678
+ (s) =>
679
+ s.status === 'NOT_STARTED' &&
680
+ !s.successors.some(
681
+ (rel) => context.states.get(rel.successorId)!.isDriving,
682
+ ),
683
+ );
684
+ const first = starts.reduce<CpmActivityState | null>(
685
+ (best, s) => (!best || s.es < best.es ? s : best),
686
+ null,
687
+ );
688
+ const last = finishes.reduce<CpmActivityState | null>(
689
+ (best, s) => (!best || s.ef > best.ef ? s : best),
690
+ null,
691
+ );
692
+ for (const state of starts)
693
+ if (state !== first)
694
+ context.collector.add({
695
+ code: 'OPEN_START',
696
+ severity: 'WARN',
697
+ activityId: state.input.id,
698
+ message: 'Activity has no predecessor.',
699
+ });
700
+ for (const state of finishes)
701
+ if (state !== last)
702
+ context.collector.add({
703
+ code: 'OPEN_FINISH',
704
+ severity: 'WARN',
705
+ activityId: state.input.id,
706
+ message: 'Activity has no successor.',
707
+ });
708
+ }
709
+
710
+ /* Initialize complete run statistics, including exact bounded-diagnostic counts. */
711
+ function getStats(
712
+ input: CpmScheduleInput,
713
+ collector: DiagnosticCollector,
714
+ ): ScheduleProjectRunStatsObj {
715
+ return {
716
+ activityCount: input.activities.length,
717
+ relationshipCount: input.relationships.length,
718
+ criticalCount: 0,
719
+ openStartCount: collector.counts.OPEN_START || 0,
720
+ openFinishCount: collector.counts.OPEN_FINISH || 0,
721
+ negativeFloatCount: collector.counts.NEGATIVE_FLOAT || 0,
722
+ constraintOverrideCount: collector.counts.CONSTRAINT_OVERRIDES_LOGIC || 0,
723
+ cycleCount: 0,
724
+ longestPathCount: 0,
725
+ scheduledFinishAt: null,
726
+ earlyFinishAt: null,
727
+ leveled: false,
728
+ leveledCount: 0,
729
+ totalLevelingDelayMinutes: 0,
730
+ finishDelayMinutes: 0,
731
+ overallocatedResourceDayCount: 0,
732
+ levelingExceededFloatCount: collector.counts.LEVELING_EXCEEDED_FLOAT || 0,
733
+ levelingExceededHorizonCount:
734
+ collector.counts.LEVELING_EXCEEDED_HORIZON || 0,
735
+ diagnosticCounts: { ...collector.counts },
736
+ diagnosticsTruncated: collector.truncated,
737
+ };
738
+ }
739
+
740
+ /* Return no schedule dates when validation, calendar arithmetic, or a driving cycle refuses the run. */
741
+ function getFailedResult(
742
+ input: CpmScheduleInput,
743
+ collector: DiagnosticCollector,
744
+ cycleCount = 0,
745
+ ): CpmScheduleResult {
746
+ return {
747
+ ok: false,
748
+ activities: [],
749
+ scheduledFinishAt: null,
750
+ earlyFinishAt: null,
751
+ lateFinishAt: null,
752
+ resourceUsage: [],
753
+ overallocations: [],
754
+ diagnostics: collector.items,
755
+ stats: { ...getStats(input, collector), cycleCount },
756
+ };
757
+ }
758
+
759
+ /* Schedule one project deterministically: CPM analytics, driving paths, resource leveling, and summaries. */
760
+ export function runCriticalPathSchedule(
761
+ input: CpmScheduleInput,
762
+ ): CpmScheduleResult {
763
+ const collector = new DiagnosticCollector();
764
+ const validated = validateCpmScheduleInput(input, collector);
765
+ if (validated.fatal) return getFailedResult(input, collector);
766
+ let context: CpmContext | undefined;
767
+ try {
768
+ context = buildContext(input, collector, validated.referencedCalendarIds);
769
+ const { order, residual } = getTopologicalOrder(context.states);
770
+ if (residual.length) {
771
+ const cycles = findStronglyConnectedComponents(residual);
772
+ for (const members of cycles)
773
+ collector.add({
774
+ code: 'CYCLE',
775
+ severity: 'ERROR',
776
+ activityId: members[0].input.id,
777
+ activityIds: members.map((s) => s.input.id),
778
+ message: describeCycle(members),
779
+ });
780
+ return getFailedResult(input, collector, cycles.length);
781
+ }
782
+ runForwardPass(context, order);
783
+ context.projectFinishMs = order.reduce(
784
+ (max, state) => Math.max(max, state.ef),
785
+ -Infinity,
786
+ );
787
+ if (!Number.isFinite(context.projectFinishMs))
788
+ context.projectFinishMs = snapFinish(
789
+ context.calendarSet.defaultCalendar,
790
+ context.floorMs,
791
+ );
792
+ context.lateFinishBasisMs = snapFinish(
793
+ context.calendarSet.defaultCalendar,
794
+ instant(input.mustFinishByAt) ?? context.projectFinishMs,
795
+ );
796
+ runBackwardPass(context, order);
797
+ normalizeLateDates(context, order);
798
+ computeFloat(context, order);
799
+ markLongestPath(context, order);
800
+ applyAsLateAsPossible(context, order);
801
+ for (const state of order) {
802
+ state.start = state.es;
803
+ state.finish = state.ef;
804
+ }
805
+ const leveling = input.options?.leveling?.enabled
806
+ ? runResourceLeveling(context, order)
807
+ : {
808
+ resourceUsage: [],
809
+ overallocations: [],
810
+ overallocatedResourceDayCount: 0,
811
+ };
812
+ computeSpanningActivities(context);
813
+ reportOpenEnds(context, order);
814
+ for (const state of order)
815
+ if (state.totalFloat != null && state.totalFloat < 0)
816
+ collector.add({
817
+ code: 'NEGATIVE_FLOAT',
818
+ severity: 'WARN',
819
+ activityId: state.input.id,
820
+ minutes: state.totalFloat,
821
+ message:
822
+ 'Activity has negative float and cannot meet its required late date.',
823
+ });
824
+ const activities: CpmActivityResult[] = [...context.states.values()].map(
825
+ (state) => ({
826
+ id: state.input.id,
827
+ status: state.status,
828
+ earlyStartAt: new Date(state.es),
829
+ earlyFinishAt: new Date(state.ef),
830
+ lateStartAt: new Date(state.ls),
831
+ lateFinishAt: new Date(state.lf),
832
+ startAt: new Date(state.start),
833
+ finishAt: new Date(state.finish),
834
+ remainingDurationMinutes: state.remaining,
835
+ totalFloatMinutes: state.totalFloat,
836
+ freeFloatMinutes: state.freeFloat,
837
+ isCritical: state.isCritical,
838
+ drivingPredecessorIds: state.drivingPredecessorIds,
839
+ levelingDelayMinutes: state.levelingDelay,
840
+ levelingConstrainedByResourceId: state.constrainedBy,
841
+ }),
842
+ );
843
+ const scheduledFinishAt = order.length
844
+ ? new Date(
845
+ order.reduce((max, state) => Math.max(max, state.finish), -Infinity),
846
+ )
847
+ : null;
848
+ const earlyFinishAt = order.length
849
+ ? new Date(context.projectFinishMs)
850
+ : null;
851
+ const stats = getStats(input, collector);
852
+ Object.assign(stats, {
853
+ criticalCount: order.filter((s) => s.isCritical).length,
854
+ longestPathCount: order.filter((s) => s.onLongestPath).length,
855
+ scheduledFinishAt: scheduledFinishAt?.toISOString() || null,
856
+ earlyFinishAt: earlyFinishAt?.toISOString() || null,
857
+ leveled: !!input.options?.leveling?.enabled,
858
+ leveledCount: order.filter((s) => s.levelingDelay > 0).length,
859
+ totalLevelingDelayMinutes: order.reduce(
860
+ (sum, s) => sum + s.levelingDelay,
861
+ 0,
862
+ ),
863
+ finishDelayMinutes:
864
+ scheduledFinishAt && earlyFinishAt
865
+ ? minutesBetween(
866
+ context.calendarSet.defaultCalendar,
867
+ earlyFinishAt.getTime(),
868
+ scheduledFinishAt.getTime(),
869
+ )
870
+ : 0,
871
+ overallocatedResourceDayCount: leveling.overallocatedResourceDayCount,
872
+ });
873
+ return {
874
+ ok: true,
875
+ activities,
876
+ scheduledFinishAt,
877
+ earlyFinishAt,
878
+ lateFinishAt: new Date(context.lateFinishBasisMs),
879
+ resourceUsage: leveling.resourceUsage,
880
+ overallocations: leveling.overallocations,
881
+ diagnostics: collector.items,
882
+ stats,
883
+ };
884
+ } catch (error) {
885
+ if (
886
+ !(
887
+ error instanceof WorkTimeRangeError ||
888
+ error instanceof WorkTimeEmptyCalendarError ||
889
+ error instanceof WorkTimeInvalidZoneError
890
+ )
891
+ )
892
+ throw error;
893
+ collector.add({
894
+ code:
895
+ error instanceof WorkTimeRangeError
896
+ ? 'CALENDAR_RANGE_EXCEEDED'
897
+ : error instanceof WorkTimeEmptyCalendarError
898
+ ? 'EMPTY_CALENDAR'
899
+ : 'INVALID_INPUT',
900
+ severity: 'ERROR',
901
+ calendarId: error.calendarId,
902
+ activityId: context?.cursorActivityId,
903
+ message: error.message,
904
+ });
905
+ return getFailedResult(input, collector);
906
+ }
907
+ }