@jsb188/schedule 1.1.12 → 1.1.13

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 (59) hide show
  1. package/LICENSE +21 -0
  2. package/package.json +33 -14
  3. package/src/constants/schedule.ts +710 -306
  4. package/src/types/schedule.d.ts +1827 -456
  5. package/src/ui/ScheduleSettingsUI.tsx +21 -23
  6. package/src/utils/autofill.ts +469 -0
  7. package/src/utils/availability.ts +167 -0
  8. package/src/utils/candidates.ts +447 -0
  9. package/src/utils/coverage.helpers.ts +509 -554
  10. package/src/utils/coverage.ts +1121 -526
  11. package/src/utils/cpm.helpers.ts +27 -29
  12. package/src/utils/cpm.ts +53 -41
  13. package/src/utils/cpmLeveling.helpers.ts +89 -16
  14. package/src/utils/cpmLeveling.ts +28 -26
  15. package/src/utils/cycle.ts +325 -0
  16. package/src/utils/demand.ts +239 -0
  17. package/src/utils/eligibility.ts +553 -400
  18. package/src/utils/ids.ts +47 -0
  19. package/src/utils/laborRules.ts +740 -0
  20. package/src/utils/localTime.ts +312 -0
  21. package/src/utils/offer.ts +300 -0
  22. package/src/utils/planCsv.ts +73 -19
  23. package/src/utils/predicate.ts +111 -0
  24. package/src/utils/request.ts +212 -114
  25. package/src/utils/resource.ts +412 -112
  26. package/src/utils/rule.ts +697 -163
  27. package/src/utils/rulePresets.ts +116 -0
  28. package/src/utils/run.ts +0 -8
  29. package/src/utils/scheduleText.ts +4074 -0
  30. package/src/utils/shiftChange.ts +279 -0
  31. package/src/utils/standing.ts +730 -0
  32. package/src/utils/template.ts +619 -0
  33. package/src/utils/violation.ts +184 -0
  34. package/src/utils/workTime.ts +341 -120
  35. package/src/utils/defaults.ts +0 -8
  36. package/src/utils/recurrence.ts +0 -616
  37. package/src/utils/series.ts +0 -161
  38. package/src/utils/slot.ts +0 -208
  39. package/tests/coverage.fixtures.ts +0 -111
  40. package/tests/coverage.test.ts +0 -503
  41. package/tests/cpm.bench.test.ts +0 -154
  42. package/tests/cpm.test.ts +0 -354
  43. package/tests/cpmCorrectness.test.ts +0 -327
  44. package/tests/cpmLeveling.test.ts +0 -471
  45. package/tests/eligibility.test.ts +0 -320
  46. package/tests/gantt-geometry.test.ts +0 -367
  47. package/tests/gantt-histogram.test.ts +0 -78
  48. package/tests/gantt-keyboard.test.ts +0 -69
  49. package/tests/helpers/cpmFixtures.ts +0 -101
  50. package/tests/projectInputs.test.ts +0 -165
  51. package/tests/recurrence.test.ts +0 -68
  52. package/tests/request.test.ts +0 -99
  53. package/tests/resource.test.ts +0 -95
  54. package/tests/rule.test.ts +0 -98
  55. package/tests/series.test.ts +0 -120
  56. package/tests/workTime.test.ts +0 -1007
  57. package/tests/workTimeContracts.test.ts +0 -111
  58. package/tsconfig.json +0 -13
  59. package/vitest.config.ts +0 -8
@@ -32,6 +32,8 @@ export interface ScheduleCsvPlan {
32
32
  plannedDurationMinutes?: number;
33
33
  workCalendarKey?: string;
34
34
  levelingPriority?: number;
35
+ actualStartAt?: string; // from an 'Actual Start' column, never a plain 'Start'
36
+ actualFinishAt?: string; // from an 'Actual Finish' column, never a plain 'Finish'
35
37
  primaryConstraintType?: ScheduleConstraintTypeEnum;
36
38
  primaryConstraintAt?: string;
37
39
  secondaryConstraintType?: ScheduleConstraintTypeEnum;
@@ -50,6 +52,14 @@ export interface ScheduleCsvPlan {
50
52
  unitsPerDay: number | null;
51
53
  }>;
52
54
  }
55
+ export interface ScheduleCsvParseOptions {
56
+ minutesPerDay: number;
57
+ timeZone: string;
58
+ calendar?: ScheduleWorkCalendarDef;
59
+ // Planned 'Start' / 'Finish' become START_ON_OR_AFTER / FINISH_ON_OR_BEFORE
60
+ // constraints; off by default, when planned dates are not imported.
61
+ plannedDatesAsConstraints?: boolean;
62
+ }
53
63
 
54
64
  /* Read RFC 4180 fields including quoted commas, escaped quotes and embedded newlines. */
55
65
  export function readScheduleCsvRows(text: string): string[][] {
@@ -92,34 +102,50 @@ export function readScheduleCsvRows(text: string): string[][] {
92
102
  if (row.some((value) => value.trim())) rows.push(row);
93
103
  return rows;
94
104
  }
95
- /* Convert date text into a calendar-aware working boundary for an import. */
105
+ /* Read one CSV date cell as the start of its local day in the import zone. */
106
+ function readCsvDay(text: string, timeZone: string): DateTime {
107
+ let date = DateTime.fromISO(text, { zone: timeZone });
108
+ if (!date.isValid)
109
+ date = DateTime.fromFormat(text, 'M/d/yyyy', { zone: timeZone });
110
+ if (!date.isValid) throw new Error('DATE');
111
+ return date.startOf('day');
112
+ }
113
+ /* Convert date text into a calendar-aware working boundary for an imported constraint. */
96
114
  function csvDate(
97
115
  text: string,
98
116
  calendar: ScheduleWorkCalendarDef,
99
117
  timeZone: string,
100
118
  finish: boolean,
101
119
  ): string {
102
- let date = DateTime.fromISO(text, { zone: timeZone });
103
- if (!date.isValid)
104
- date = DateTime.fromFormat(text, 'M/d/yyyy', { zone: timeZone });
105
- if (!date.isValid) throw new Error('DATE');
120
+ const day = readCsvDay(text, timeZone);
106
121
  return (
107
122
  finish
108
- ? snapToWorkingFinish(
109
- calendar,
110
- date.plus({ days: 1 }).startOf('day').toJSDate(),
111
- )
112
- : snapToWorkingStart(calendar, date.startOf('day').toJSDate())
123
+ ? snapToWorkingFinish(calendar, day.plus({ days: 1 }).toJSDate())
124
+ : snapToWorkingStart(calendar, day.toJSDate())
113
125
  ).toISOString();
114
126
  }
115
- /* Turn one bounded CSV into typed activity, hierarchy, relationship and resource import sections. */
127
+ /* Keep a reported actual date on its own local day: its first or last working instant, else the day's bound. */
128
+ function csvActualDate(
129
+ text: string,
130
+ calendar: ScheduleWorkCalendarDef,
131
+ timeZone: string,
132
+ finish: boolean,
133
+ ): string {
134
+ const day = readCsvDay(text, timeZone);
135
+ const dayStart = day.toJSDate();
136
+ const dayEnd = day.plus({ days: 1 }).toJSDate();
137
+ // Work on a nonworking day happened that day; never snap it to another day.
138
+ if (finish) {
139
+ const snapped = snapToWorkingFinish(calendar, dayEnd);
140
+ return (snapped > dayStart ? snapped : dayEnd).toISOString();
141
+ }
142
+ const snapped = snapToWorkingStart(calendar, dayStart);
143
+ return (snapped < dayEnd ? snapped : dayStart).toISOString();
144
+ }
145
+ /* Turn one bounded CSV into typed activity, hierarchy, relationship and resource import sections; actuals come only from 'Actual Start' / 'Actual Finish'. */
116
146
  export function parseSchedulePlanCsv(
117
147
  text: string,
118
- options: {
119
- minutesPerDay: number;
120
- timeZone: string;
121
- calendar?: ScheduleWorkCalendarDef;
122
- },
148
+ options: ScheduleCsvParseOptions,
123
149
  ): { plan: ScheduleCsvPlan; errors: ScheduleCsvError[] } {
124
150
  const plan: ScheduleCsvPlan = {
125
151
  wbs: [],
@@ -174,6 +200,8 @@ export function parseSchedulePlanCsv(
174
200
  predecessor: 'predecessors',
175
201
  'start date': 'start',
176
202
  'finish date': 'finish',
203
+ 'actual start date': 'actual start',
204
+ 'actual finish date': 'actual finish',
177
205
  resource: 'resources',
178
206
  };
179
207
  const headers = rows.shift()!.map((value) => {
@@ -250,8 +278,28 @@ export function parseSchedulePlanCsv(
250
278
  invalid('priority');
251
279
  else activity.levelingPriority = priority;
252
280
  }
281
+ for (const [column, key] of [
282
+ ['actual start', 'actualStartAt'],
283
+ ['actual finish', 'actualFinishAt'],
284
+ ] as const) {
285
+ const value = raw[column];
286
+ // Exporters write placeholders such as 'NA' (MS Project), 'N/A' or '-' for a date not reached yet.
287
+ if (!value || /^(n\/?a|-+)$/i.test(value)) continue;
288
+ try {
289
+ activity[key] = csvActualDate(
290
+ value,
291
+ calendar,
292
+ options.timeZone,
293
+ key === 'actualFinishAt',
294
+ );
295
+ } catch {
296
+ invalid(column);
297
+ }
298
+ }
299
+ const plannedStart = options.plannedDatesAsConstraints && raw.start;
300
+ const plannedFinish = options.plannedDatesAsConstraints && raw.finish;
253
301
  try {
254
- if (raw.start) {
302
+ if (plannedStart) {
255
303
  activity.primaryConstraintType = 'START_ON_OR_AFTER';
256
304
  activity.primaryConstraintAt = csvDate(
257
305
  raw.start,
@@ -260,8 +308,8 @@ export function parseSchedulePlanCsv(
260
308
  false,
261
309
  );
262
310
  }
263
- if (raw.finish) {
264
- const slot = raw.start ? 'secondary' : 'primary';
311
+ if (plannedFinish) {
312
+ const slot = plannedStart ? 'secondary' : 'primary';
265
313
  activity[`${slot}ConstraintType`] = 'FINISH_ON_OR_BEFORE';
266
314
  activity[`${slot}ConstraintAt`] = csvDate(
267
315
  raw.finish,
@@ -290,6 +338,12 @@ export function parseSchedulePlanCsv(
290
338
  } catch {
291
339
  invalid('date');
292
340
  }
341
+ if (
342
+ activity.actualStartAt &&
343
+ activity.actualFinishAt &&
344
+ Date.parse(activity.actualFinishAt) < Date.parse(activity.actualStartAt)
345
+ )
346
+ invalid('actual finish');
293
347
  for (const [key, value] of Object.entries(raw))
294
348
  if (key.startsWith('code:') && value)
295
349
  activity.codes.push({ typeKey: key.slice(5), valueKey: value });
@@ -0,0 +1,111 @@
1
+ import {
2
+ SCHEDULE_RESOURCE_MAX_QUALIFICATIONS,
3
+ SCHEDULE_RESOURCE_MAX_TAGS,
4
+ SCHEDULE_RULE_MAX_ROLE_IDS,
5
+ } from '../constants/schedule.ts';
6
+ import type {
7
+ CoverageResourceInput,
8
+ SchedulePredicateObj,
9
+ } from '../types/schedule.d.ts';
10
+ import { compareScheduleIds, normalizeScheduleIdList } from './ids.ts';
11
+ import { isScheduleRecord, validateScheduleKeyList } from './resource.ts';
12
+
13
+ /**
14
+ * Rule predicates: who counts as an adult for RATIO and OPERATING_HOURS.
15
+ * A person matches when they hold at least one of roleIdsAny, every listed
16
+ * qualification key and every listed tag. Qualification EXPIRY is judged
17
+ * separately (ELIGIBILITY), because a lapsed certificate is a different
18
+ * finding from a missing one.
19
+ */
20
+
21
+ type PredicateResource = Pick<CoverageResourceInput, 'roleIds' | 'config'>;
22
+
23
+ /*
24
+ * Validate one predicate object. Unknown keys are rejected, empty lists are
25
+ * dropped, and an empty predicate is returned as null (anyone countable).
26
+ */
27
+ export function validateSchedulePredicate(input: unknown): {
28
+ predicate?: SchedulePredicateObj | null;
29
+ error?: string;
30
+ } {
31
+ if (input === undefined || input === null) return { predicate: null };
32
+ if (!isScheduleRecord(input))
33
+ return { error: 'A rule predicate must be an object.' };
34
+
35
+ const unknown = Object.keys(input).find(
36
+ (key) => !['roleIdsAny', 'qualifications', 'tags'].includes(key),
37
+ );
38
+ if (unknown) return { error: `Unknown rule predicate key: ${unknown}.` };
39
+
40
+ const predicate: SchedulePredicateObj = {};
41
+ if (input.roleIdsAny != null) {
42
+ const roleIds = normalizeScheduleIdList(
43
+ input.roleIdsAny,
44
+ SCHEDULE_RULE_MAX_ROLE_IDS,
45
+ );
46
+ if (!roleIds)
47
+ return {
48
+ error: 'Rule predicate "roleIdsAny" must be a list of role ids.',
49
+ };
50
+ if (roleIds.length) predicate.roleIdsAny = roleIds;
51
+ }
52
+
53
+ for (const [key, limit] of [
54
+ ['qualifications', SCHEDULE_RESOURCE_MAX_QUALIFICATIONS],
55
+ ['tags', SCHEDULE_RESOURCE_MAX_TAGS],
56
+ ] as const) {
57
+ if (input[key] == null) continue;
58
+ const keys = validateScheduleKeyList(input[key], limit);
59
+ if (!keys)
60
+ return { error: `Rule predicate "${key}" must be a list of names.` };
61
+ if (keys.length) predicate[key] = keys;
62
+ }
63
+
64
+ return { predicate: Object.keys(predicate).length ? predicate : null };
65
+ }
66
+
67
+ /*
68
+ * Return what a resource lacks for a predicate, independently of expiry:
69
+ * roleIdsAny lists every wanted role when the resource holds none of them
70
+ * (else []); qualifications and tags list the missing keys. Sorted.
71
+ */
72
+ export function getSchedulePredicateMissing(
73
+ resource: PredicateResource | null | undefined,
74
+ predicate: SchedulePredicateObj | null | undefined,
75
+ ): { roleIdsAny: string[]; qualifications: string[]; tags: string[] } {
76
+ const roleIds = new Set(resource?.roleIds ?? []);
77
+ const qualifications = new Set(
78
+ (resource?.config?.qualifications ?? []).map((item) => item.key),
79
+ );
80
+ const tags = new Set(resource?.config?.tags ?? []);
81
+ const wantedRoles = predicate?.roleIdsAny ?? [];
82
+
83
+ return {
84
+ roleIdsAny: wantedRoles.some((roleId) => roleIds.has(roleId))
85
+ ? []
86
+ : [...new Set(wantedRoles)].sort(compareScheduleIds),
87
+ qualifications: [...new Set(predicate?.qualifications ?? [])]
88
+ .filter((key) => !qualifications.has(key))
89
+ .sort(),
90
+ tags: [...new Set(predicate?.tags ?? [])]
91
+ .filter((key) => !tags.has(key))
92
+ .sort(),
93
+ };
94
+ }
95
+
96
+ /*
97
+ * Check whether a resource satisfies a predicate (a null predicate matches
98
+ * anyone). Expiry is not judged here.
99
+ */
100
+ export function doesResourceMatchPredicate(
101
+ resource: PredicateResource | null | undefined,
102
+ predicate: SchedulePredicateObj | null | undefined,
103
+ ): boolean {
104
+ if (!predicate) return true;
105
+ const missing = getSchedulePredicateMissing(resource, predicate);
106
+ return (
107
+ !missing.roleIdsAny.length &&
108
+ !missing.qualifications.length &&
109
+ !missing.tags.length
110
+ );
111
+ }
@@ -1,87 +1,148 @@
1
1
  import { SCHEDULE_CALENDAR_DEFAULT_SETTINGS } from '../constants/schedule.ts';
2
2
  import type {
3
+ CoverageEvaluationInput,
4
+ CoverageViolationDiff,
5
+ ScheduleRequestActorEnum,
3
6
  ScheduleRequestKindEnum,
4
7
  ScheduleRequestPolicyObj,
5
8
  ScheduleRequestStatusEnum,
9
+ ScheduleRequestSubjectObj,
10
+ ScheduleRequestTransitionEnum,
11
+ ScheduleShiftSimulationObj,
6
12
  } from '../types/schedule.d.ts';
13
+ import { evaluateScheduleCoverage, simulateShiftChange } from './coverage.ts';
14
+ import { isScheduleRecord } from './resource.ts';
15
+ import { diffCoverageViolations } from './violation.ts';
7
16
 
8
- export type ScheduleRequestActor =
9
- | 'REQUESTER'
10
- | 'COUNTERPARTY'
11
- | 'MANAGER'
12
- | 'SYSTEM';
13
- export type ScheduleRequestTransition =
14
- | 'CREATE'
15
- | 'AUTO_APPROVE'
16
- | 'CONSENT'
17
- | 'REFUSE_CONSENT'
18
- | 'WITHDRAW'
19
- | 'APPROVE'
20
- | 'DECLINE'
21
- | 'EXPIRE'
22
- | 'CASCADE_CANCEL';
23
- export type ScheduleRequestVerb =
24
- | 'approve'
25
- | 'decline'
26
- | 'consent'
27
- | 'refuse'
28
- | 'withdraw';
17
+ /**
18
+ * Requests (IMPLEMENTATION §1.6): the state machine, the calendar's
19
+ * request policy, auto-approval, expiry and notice, and a request's seat
20
+ * change and coverage impact as pure functions.
21
+ *
22
+ * CLAIM take an open seat; minNoticeHours never applies
23
+ * DROP give up a seat; it stays theirs until approved
24
+ * CALL_OUT cannot work it; minNoticeHours never applies
25
+ * RETIME keep the seat with the proposed hours
26
+ * SWAP trade seats; the counterparty consents, then a decision
27
+ */
29
28
 
30
29
  const FILE_CONSTANTS = {
30
+ hourMs: 3_600_000,
31
+ maxPolicyHours: 8760,
31
32
  live: ['PENDING', 'ACCEPTED_BY_COUNTERPARTY'] as ScheduleRequestStatusEnum[],
32
- verbs: {
33
- approve: 'APPROVE',
34
- decline: 'DECLINE',
35
- consent: 'CONSENT',
36
- refuse: 'REFUSE_CONSENT',
37
- withdraw: 'WITHDRAW',
38
- } as Record<ScheduleRequestVerb, ScheduleRequestTransition>,
33
+ policySwitches: [
34
+ 'autoApproveClaims',
35
+ 'autoApproveDrops',
36
+ 'autoApproveCallOuts',
37
+ 'autoApproveSwaps',
38
+ ] as const,
39
+ policyHours: ['minNoticeHours', 'requestExpiryHours'] as const,
39
40
  };
40
41
 
41
- /* Return the live states an authorized actor may leave through this transition. */
42
+ /*
43
+ * Resolve a calendar's request policy from its settings object: each known,
44
+ * well-typed field of settings.requestPolicy overrides
45
+ * SCHEDULE_CALENDAR_DEFAULT_SETTINGS.requestPolicy; anything else takes the
46
+ * default. Never throws (the calendar write path validates).
47
+ */
48
+ export function getScheduleRequestPolicy(
49
+ settings: unknown,
50
+ ): ScheduleRequestPolicyObj {
51
+ const policy = { ...SCHEDULE_CALENDAR_DEFAULT_SETTINGS.requestPolicy };
52
+ const raw =
53
+ isScheduleRecord(settings) && isScheduleRecord(settings.requestPolicy)
54
+ ? settings.requestPolicy
55
+ : {};
56
+ for (const key of FILE_CONSTANTS.policySwitches)
57
+ if (typeof raw[key] === 'boolean') policy[key] = raw[key];
58
+ for (const key of FILE_CONSTANTS.policyHours) {
59
+ const value = raw[key];
60
+ if (
61
+ typeof value === 'number' &&
62
+ Number.isFinite(value) &&
63
+ value >= 0 &&
64
+ value <= FILE_CONSTANTS.maxPolicyHours
65
+ )
66
+ policy[key] = value;
67
+ }
68
+ return policy;
69
+ }
70
+
71
+ /*
72
+ * Return the statuses a request may leave through a transition by an actor
73
+ * ([] = not allowed). Live = PENDING or ACCEPTED_BY_COUNTERPARTY. SYSTEM
74
+ * expires and cascade-cancels live requests and auto-approves PENDING ones
75
+ * (a SWAP only after consent); the requester withdraws a live request; the
76
+ * counterparty of a SWAP consents to a PENDING one or refuses a live one;
77
+ * the manager declines a live request and approves a PENDING one (a SWAP
78
+ * only after consent).
79
+ */
42
80
  export function getScheduleRequestTransitionSources(
43
81
  kind: ScheduleRequestKindEnum,
44
- transition: ScheduleRequestTransition,
45
- actor: ScheduleRequestActor,
46
- _policy: ScheduleRequestPolicyObj,
82
+ transition: ScheduleRequestTransitionEnum,
83
+ actor: ScheduleRequestActorEnum,
47
84
  ): ScheduleRequestStatusEnum[] {
48
- if (
49
- actor === 'SYSTEM' &&
50
- (transition === 'EXPIRE' || transition === 'CASCADE_CANCEL')
51
- )
52
- return [...FILE_CONSTANTS.live];
53
- if (actor === 'REQUESTER' && transition === 'WITHDRAW')
54
- return [...FILE_CONSTANTS.live];
55
- if (actor === 'COUNTERPARTY' && kind === 'SWAP') {
56
- if (transition === 'CONSENT') return ['PENDING'];
57
- if (transition === 'REFUSE_CONSENT') return [...FILE_CONSTANTS.live];
58
- }
59
- if (actor === 'MANAGER') {
60
- if (transition === 'DECLINE') return [...FILE_CONSTANTS.live];
61
- if (transition === 'APPROVE')
62
- return kind === 'SWAP'
63
- ? ['ACCEPTED_BY_COUNTERPARTY']
64
- : ['PENDING'];
85
+ const approvable: ScheduleRequestStatusEnum[] =
86
+ kind === 'SWAP' ? ['ACCEPTED_BY_COUNTERPARTY'] : ['PENDING'];
87
+ switch (actor) {
88
+ case 'SYSTEM':
89
+ if (transition === 'EXPIRE' || transition === 'CASCADE_CANCEL')
90
+ return [...FILE_CONSTANTS.live];
91
+ return transition === 'AUTO_APPROVE' ? approvable : [];
92
+ case 'REQUESTER':
93
+ return transition === 'WITHDRAW' ? [...FILE_CONSTANTS.live] : [];
94
+ case 'COUNTERPARTY':
95
+ if (kind !== 'SWAP') return [];
96
+ if (transition === 'CONSENT') return ['PENDING'];
97
+ return transition === 'REFUSE_CONSENT' ? [...FILE_CONSTANTS.live] : [];
98
+ case 'MANAGER':
99
+ if (transition === 'DECLINE') return [...FILE_CONSTANTS.live];
100
+ return transition === 'APPROVE' ? approvable : [];
101
+ default:
102
+ return [];
65
103
  }
66
- return [];
67
104
  }
68
105
 
69
- /* Auto-approve only a clean claim or drop made by the worker under an enabled policy. */
70
- export function getScheduleRequestInitialStatus(
71
- kind: ScheduleRequestKindEnum,
106
+ /*
107
+ * Return a new request's status. `clean` = eligibility returned no BLOCK and
108
+ * no WARN. A CLAIM is approved when clean and its rule allows: an offer's
109
+ * own autoApprove for a claim that answers an offer (offerAutoApprove, null
110
+ * for any other claim; an offer that waits for a manager holds the claim
111
+ * whatever the location's policy), else autoApproveClaims. A DROP with
112
+ * autoApproveDrops; a CALL_OUT with autoApproveCallOuts. RETIME and SWAP
113
+ * always start PENDING (a SWAP waits for the counterparty first).
114
+ */
115
+ export function getScheduleRequestInitialStatus(args: {
116
+ kind: ScheduleRequestKindEnum;
117
+ policy: ScheduleRequestPolicyObj;
118
+ clean: boolean;
119
+ offerAutoApprove: boolean | null;
120
+ }): 'PENDING' | 'APPROVED' {
121
+ const { kind, policy } = args;
122
+ const approved =
123
+ kind === 'CLAIM'
124
+ ? args.clean && (args.offerAutoApprove ?? policy.autoApproveClaims)
125
+ : kind === 'DROP'
126
+ ? policy.autoApproveDrops
127
+ : kind === 'CALL_OUT' && policy.autoApproveCallOuts;
128
+ return approved ? 'APPROVED' : 'PENDING';
129
+ }
130
+
131
+ /*
132
+ * Decide whether a SWAP the counterparty has agreed to is approved without a
133
+ * manager: autoApproveSwaps and a clean eligibility check both ways.
134
+ */
135
+ export function shouldAutoApproveSwap(
72
136
  policy: ScheduleRequestPolicyObj,
73
- verdictClean: boolean,
74
- onBehalf: boolean,
75
- ): 'PENDING' | 'APPROVED' {
76
- return verdictClean &&
77
- !onBehalf &&
78
- ((kind === 'CLAIM' && policy.autoApproveClaims) ||
79
- (kind === 'DROP' && policy.autoApproveDrops))
80
- ? 'APPROVED'
81
- : 'PENDING';
137
+ clean: boolean,
138
+ ): boolean {
139
+ return policy.autoApproveSwaps && clean;
82
140
  }
83
141
 
84
- /* Bound a request's lifetime by its subject shift, including policies with no hour cap. */
142
+ /*
143
+ * Return when a request expires: requestExpiryHours after now, never after
144
+ * the subject seat's start; 0 hours = at the seat's start.
145
+ */
85
146
  export function getScheduleRequestExpiry(
86
147
  policy: ScheduleRequestPolicyObj,
87
148
  now: Date,
@@ -90,64 +151,101 @@ export function getScheduleRequestExpiry(
90
151
  return new Date(
91
152
  policy.requestExpiryHours > 0
92
153
  ? Math.min(
93
- now.getTime() + policy.requestExpiryHours * 3_600_000,
154
+ now.getTime() + policy.requestExpiryHours * FILE_CONSTANTS.hourMs,
94
155
  subjectStartAt.getTime(),
95
156
  )
96
157
  : subjectStartAt.getTime(),
97
158
  );
98
159
  }
99
160
 
100
- /* Resolve known request policy fields and reject invalid persisted or edited settings. */
101
- export function getScheduleRequestPolicy(calendar: {
102
- settings?: unknown;
103
- }): ScheduleRequestPolicyObj {
104
- const settings =
105
- calendar.settings && typeof calendar.settings === 'object'
106
- ? (calendar.settings as Record<string, unknown>)
107
- : {};
108
- const raw =
109
- settings.requests && typeof settings.requests === 'object'
110
- ? (settings.requests as Record<string, unknown>)
111
- : {};
112
- const policy: ScheduleRequestPolicyObj = {
113
- ...SCHEDULE_CALENDAR_DEFAULT_SETTINGS.requests,
114
- };
115
- for (const key of [
116
- 'autoApproveClaims',
117
- 'autoApproveDrops',
118
- ] as const) {
119
- if (raw[key] !== undefined) {
120
- if (typeof raw[key] !== 'boolean') throw new Error('20150 POLICY');
121
- policy[key] = raw[key];
122
- }
123
- }
124
- if (raw.requireCounterpartyConsent !== undefined && raw.requireCounterpartyConsent !== true) throw new Error('20150 POLICY');
125
- for (const key of ['minNoticeHours', 'requestExpiryHours'] as const) {
126
- if (raw[key] !== undefined) {
127
- if (
128
- typeof raw[key] !== 'number' ||
129
- !Number.isFinite(raw[key]) ||
130
- raw[key] < 0 ||
131
- raw[key] > 8760
132
- )
133
- throw new Error('20150 POLICY');
134
- policy[key] = raw[key];
135
- }
161
+ /*
162
+ * Check that a request gives enough notice. Notice limits giving a seat away
163
+ * (DROP, SWAP, RETIME): a CALL_OUT and a CLAIM of an open seat always pass;
164
+ * otherwise the seat must start at least minNoticeHours after now.
165
+ */
166
+ export function hasScheduleRequestNotice(args: {
167
+ kind: ScheduleRequestKindEnum;
168
+ policy: ScheduleRequestPolicyObj;
169
+ now: Date;
170
+ subjectStartAt: Date;
171
+ }): boolean {
172
+ return (
173
+ args.kind === 'CALL_OUT' ||
174
+ args.kind === 'CLAIM' ||
175
+ args.subjectStartAt.getTime() - args.now.getTime() >=
176
+ args.policy.minNoticeHours * FILE_CONSTANTS.hourMs
177
+ );
178
+ }
179
+
180
+ /*
181
+ * Return the seat change a request asks for, as a coverage simulation: CLAIM
182
+ * assigns the requester; DROP and CALL_OUT unassign; RETIME retimes to the
183
+ * proposed hours; SWAP unassigns both seats and assigns each person to the
184
+ * other's. A RETIME without hours or a SWAP without its target throws a
185
+ * RangeError (the DDL forbids both).
186
+ */
187
+ export function getScheduleRequestSimulation(
188
+ request: ScheduleRequestSubjectObj,
189
+ ): ScheduleShiftSimulationObj {
190
+ switch (request.kind) {
191
+ case 'CLAIM':
192
+ return {
193
+ assign: [
194
+ { shiftId: request.shiftId, resourceId: request.requesterResourceId },
195
+ ],
196
+ };
197
+ case 'DROP':
198
+ case 'CALL_OUT':
199
+ return { unassign: [request.shiftId] };
200
+ case 'RETIME':
201
+ if (!request.proposedStartAt || !request.proposedEndAt)
202
+ throw new RangeError('A RETIME request needs its proposed hours');
203
+ return {
204
+ retime: [
205
+ {
206
+ shiftId: request.shiftId,
207
+ startAt: request.proposedStartAt,
208
+ endAt: request.proposedEndAt,
209
+ },
210
+ ],
211
+ };
212
+ case 'SWAP':
213
+ if (!request.targetShiftId || !request.counterpartyResourceId)
214
+ throw new RangeError('A SWAP request needs its target seat and person');
215
+ return {
216
+ unassign: [request.shiftId, request.targetShiftId],
217
+ assign: [
218
+ {
219
+ shiftId: request.targetShiftId,
220
+ resourceId: request.requesterResourceId,
221
+ },
222
+ {
223
+ shiftId: request.shiftId,
224
+ resourceId: request.counterpartyResourceId,
225
+ },
226
+ ],
227
+ };
228
+ default:
229
+ throw new RangeError(`Unknown request kind: ${String(request.kind)}`);
136
230
  }
137
- return policy;
138
231
  }
139
232
 
140
- /* Keep client actions aligned with the server's conditional transition predicates. */
141
- export function canActOnScheduleRequest(
142
- verb: ScheduleRequestVerb,
143
- request: { kind: ScheduleRequestKindEnum; status: ScheduleRequestStatusEnum },
144
- actor: ScheduleRequestActor,
145
- policy: ScheduleRequestPolicyObj,
146
- ): boolean {
147
- return getScheduleRequestTransitionSources(
148
- request.kind,
149
- FILE_CONSTANTS.verbs[verb],
150
- actor,
151
- policy,
152
- ).includes(request.status);
233
+ /*
234
+ * Return a request's coverage impact: the violations its seat change would
235
+ * introduce, worsen or resolve, comparing an evaluation of the snapshot with
236
+ * one of the simulated change (diffCoverageViolations: coverage gaps per
237
+ * instant, so a new gap is reported even when the rule is already short at
238
+ * another time). The caller puts the people gaining seats into the snapshot
239
+ * (resources, external, time off, availability) first.
240
+ */
241
+ export function getScheduleRequestImpact(
242
+ snapshot: CoverageEvaluationInput,
243
+ request: ScheduleRequestSubjectObj,
244
+ ): CoverageViolationDiff {
245
+ return diffCoverageViolations(
246
+ evaluateScheduleCoverage(snapshot).violations,
247
+ evaluateScheduleCoverage(
248
+ simulateShiftChange(snapshot, getScheduleRequestSimulation(request)),
249
+ ).violations,
250
+ );
153
251
  }