@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.
- package/LICENSE +21 -0
- package/package.json +33 -14
- package/src/constants/schedule.ts +710 -306
- package/src/types/schedule.d.ts +1827 -456
- package/src/ui/ScheduleSettingsUI.tsx +21 -23
- package/src/utils/autofill.ts +469 -0
- package/src/utils/availability.ts +167 -0
- package/src/utils/candidates.ts +447 -0
- package/src/utils/coverage.helpers.ts +509 -554
- package/src/utils/coverage.ts +1121 -526
- package/src/utils/cpm.helpers.ts +27 -29
- package/src/utils/cpm.ts +53 -41
- package/src/utils/cpmLeveling.helpers.ts +89 -16
- package/src/utils/cpmLeveling.ts +28 -26
- package/src/utils/cycle.ts +325 -0
- package/src/utils/demand.ts +239 -0
- package/src/utils/eligibility.ts +553 -400
- package/src/utils/ids.ts +47 -0
- package/src/utils/laborRules.ts +740 -0
- package/src/utils/localTime.ts +312 -0
- package/src/utils/offer.ts +300 -0
- package/src/utils/planCsv.ts +73 -19
- package/src/utils/predicate.ts +111 -0
- package/src/utils/request.ts +212 -114
- package/src/utils/resource.ts +412 -112
- package/src/utils/rule.ts +697 -163
- package/src/utils/rulePresets.ts +116 -0
- package/src/utils/run.ts +0 -8
- package/src/utils/scheduleText.ts +4074 -0
- package/src/utils/shiftChange.ts +279 -0
- package/src/utils/standing.ts +730 -0
- package/src/utils/template.ts +619 -0
- package/src/utils/violation.ts +184 -0
- package/src/utils/workTime.ts +341 -120
- package/src/utils/defaults.ts +0 -8
- package/src/utils/recurrence.ts +0 -616
- package/src/utils/series.ts +0 -161
- package/src/utils/slot.ts +0 -208
- package/tests/coverage.fixtures.ts +0 -111
- package/tests/coverage.test.ts +0 -503
- package/tests/cpm.bench.test.ts +0 -154
- package/tests/cpm.test.ts +0 -354
- package/tests/cpmCorrectness.test.ts +0 -327
- package/tests/cpmLeveling.test.ts +0 -471
- package/tests/eligibility.test.ts +0 -320
- package/tests/gantt-geometry.test.ts +0 -367
- package/tests/gantt-histogram.test.ts +0 -78
- package/tests/gantt-keyboard.test.ts +0 -69
- package/tests/helpers/cpmFixtures.ts +0 -101
- package/tests/projectInputs.test.ts +0 -165
- package/tests/recurrence.test.ts +0 -68
- package/tests/request.test.ts +0 -99
- package/tests/resource.test.ts +0 -95
- package/tests/rule.test.ts +0 -98
- package/tests/series.test.ts +0 -120
- package/tests/workTime.test.ts +0 -1007
- package/tests/workTimeContracts.test.ts +0 -111
- package/tsconfig.json +0 -13
- package/vitest.config.ts +0 -8
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
import { IANAZone } from 'luxon';
|
|
2
|
+
import { SCHEDULE_AVAILABILITY_KIND_ENUMS } from '../constants/schedule.ts';
|
|
3
|
+
import type {
|
|
4
|
+
CoverageAvailabilityInput,
|
|
5
|
+
ScheduleAvailabilityIntervalObj,
|
|
6
|
+
ScheduleAvailabilityKindEnum,
|
|
7
|
+
} from '../types/schedule.d.ts';
|
|
8
|
+
import { compareScheduleIds } from './ids.ts';
|
|
9
|
+
import {
|
|
10
|
+
addScheduleDays,
|
|
11
|
+
getScheduleDaysBetween,
|
|
12
|
+
getScheduleLocalDate,
|
|
13
|
+
getScheduleLocalInterval,
|
|
14
|
+
getScheduleWeekday,
|
|
15
|
+
toScheduleTimeMs,
|
|
16
|
+
} from './localTime.ts';
|
|
17
|
+
import {
|
|
18
|
+
getUnknownScheduleKey,
|
|
19
|
+
isScheduleRecord,
|
|
20
|
+
isScheduleWeekday,
|
|
21
|
+
validateScheduleClockTimesInput,
|
|
22
|
+
validateScheduleEffectiveDatesInput,
|
|
23
|
+
} from './resource.ts';
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* Availability: recurring weekly windows a PERSON cannot work (UNAVAILABLE)
|
|
27
|
+
* or prefers to work (PREFERRED). No rows means available. Each window is
|
|
28
|
+
* stated in its own zone (the person's, not necessarily the calendar's), so
|
|
29
|
+
* it is expanded there. A window whose end is at or before its start ends the
|
|
30
|
+
* next day; '00:00'-'00:00' is the whole day (23 or 25 hours on DST days).
|
|
31
|
+
*/
|
|
32
|
+
|
|
33
|
+
const FILE_CONSTANTS = {
|
|
34
|
+
inputKeys: [
|
|
35
|
+
'kind',
|
|
36
|
+
'weekday',
|
|
37
|
+
'startTime',
|
|
38
|
+
'endTime',
|
|
39
|
+
'timeZone',
|
|
40
|
+
'effectiveFrom',
|
|
41
|
+
'effectiveTo',
|
|
42
|
+
],
|
|
43
|
+
};
|
|
44
|
+
|
|
45
|
+
/*
|
|
46
|
+
* Validate an availability window write: kind, weekday 0..6, times
|
|
47
|
+
* normalized to 'HH:mm', a valid IANA zone, and effective dates.
|
|
48
|
+
*/
|
|
49
|
+
export function validateScheduleAvailabilityInput(input: unknown): {
|
|
50
|
+
availability?: Omit<CoverageAvailabilityInput, 'id' | 'resourceId'>;
|
|
51
|
+
error?: string;
|
|
52
|
+
} {
|
|
53
|
+
if (!isScheduleRecord(input))
|
|
54
|
+
return { error: 'An availability window must be an object.' };
|
|
55
|
+
const unknown = getUnknownScheduleKey(input, FILE_CONSTANTS.inputKeys);
|
|
56
|
+
if (unknown) return { error: `Unknown availability field: ${unknown}.` };
|
|
57
|
+
|
|
58
|
+
if (
|
|
59
|
+
!SCHEDULE_AVAILABILITY_KIND_ENUMS.includes(
|
|
60
|
+
input.kind as ScheduleAvailabilityKindEnum,
|
|
61
|
+
)
|
|
62
|
+
)
|
|
63
|
+
return {
|
|
64
|
+
error: `Availability kind must be ${SCHEDULE_AVAILABILITY_KIND_ENUMS.join(' or ')}.`,
|
|
65
|
+
};
|
|
66
|
+
if (!isScheduleWeekday(input.weekday))
|
|
67
|
+
return { error: 'The weekday must be 0 (Sunday) to 6 (Saturday).' };
|
|
68
|
+
const { times, error } = validateScheduleClockTimesInput(input);
|
|
69
|
+
if (!times) return { error };
|
|
70
|
+
const timeZone =
|
|
71
|
+
typeof input.timeZone === 'string' ? input.timeZone.trim() : '';
|
|
72
|
+
if (!timeZone || !IANAZone.isValidZone(timeZone))
|
|
73
|
+
return {
|
|
74
|
+
error: 'timeZone must be an IANA time zone, such as America/New_York.',
|
|
75
|
+
};
|
|
76
|
+
const { dates, error: datesError } =
|
|
77
|
+
validateScheduleEffectiveDatesInput(input);
|
|
78
|
+
if (!dates) return { error: datesError };
|
|
79
|
+
|
|
80
|
+
return {
|
|
81
|
+
availability: {
|
|
82
|
+
kind: input.kind as ScheduleAvailabilityKindEnum,
|
|
83
|
+
weekday: input.weekday,
|
|
84
|
+
...times,
|
|
85
|
+
timeZone,
|
|
86
|
+
...dates,
|
|
87
|
+
},
|
|
88
|
+
};
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/*
|
|
92
|
+
* Expand one window over its local dates from fromDate to toDate (in its own
|
|
93
|
+
* zone), keeping the occurrences that overlap [fromMs, toMs).
|
|
94
|
+
*/
|
|
95
|
+
function expandScheduleAvailabilityWindow(
|
|
96
|
+
window: CoverageAvailabilityInput,
|
|
97
|
+
fromDate: string,
|
|
98
|
+
toDate: string,
|
|
99
|
+
fromMs: number,
|
|
100
|
+
toMs: number,
|
|
101
|
+
): ScheduleAvailabilityIntervalObj[] {
|
|
102
|
+
const intervals: ScheduleAvailabilityIntervalObj[] = [];
|
|
103
|
+
const firstOffset = (window.weekday - getScheduleWeekday(fromDate) + 7) % 7;
|
|
104
|
+
const lastOffset = getScheduleDaysBetween(fromDate, toDate);
|
|
105
|
+
for (let offset = firstOffset; offset <= lastOffset; offset += 7) {
|
|
106
|
+
const date = addScheduleDays(fromDate, offset);
|
|
107
|
+
if (
|
|
108
|
+
date < window.effectiveFrom ||
|
|
109
|
+
(window.effectiveTo !== null && date > window.effectiveTo)
|
|
110
|
+
)
|
|
111
|
+
continue;
|
|
112
|
+
const interval = getScheduleLocalInterval(
|
|
113
|
+
date,
|
|
114
|
+
window.startTime,
|
|
115
|
+
window.endTime,
|
|
116
|
+
window.timeZone,
|
|
117
|
+
);
|
|
118
|
+
if (
|
|
119
|
+
!interval ||
|
|
120
|
+
interval.startAt.getTime() >= toMs ||
|
|
121
|
+
interval.endAt.getTime() <= fromMs
|
|
122
|
+
)
|
|
123
|
+
continue;
|
|
124
|
+
intervals.push({
|
|
125
|
+
availabilityId: window.id,
|
|
126
|
+
resourceId: window.resourceId,
|
|
127
|
+
kind: window.kind,
|
|
128
|
+
...interval,
|
|
129
|
+
});
|
|
130
|
+
}
|
|
131
|
+
return intervals;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/*
|
|
135
|
+
* Expand weekly windows into the occurrences that overlap [from, to): each
|
|
136
|
+
* window in its own zone, over its local dates from one day before `from` to
|
|
137
|
+
* `to` (so an overnight window from the evening before is included).
|
|
138
|
+
* Intervals are not clipped. Sorted by startAt, resourceId, availabilityId.
|
|
139
|
+
* An unreadable or empty range returns [].
|
|
140
|
+
*/
|
|
141
|
+
export function expandScheduleAvailability(args: {
|
|
142
|
+
windows: CoverageAvailabilityInput[];
|
|
143
|
+
from: Date | string;
|
|
144
|
+
to: Date | string;
|
|
145
|
+
}): ScheduleAvailabilityIntervalObj[] {
|
|
146
|
+
const fromMs = toScheduleTimeMs(args.from);
|
|
147
|
+
const toMs = toScheduleTimeMs(args.to);
|
|
148
|
+
if (!Number.isFinite(fromMs) || !Number.isFinite(toMs) || toMs <= fromMs)
|
|
149
|
+
return [];
|
|
150
|
+
|
|
151
|
+
return args.windows
|
|
152
|
+
.flatMap((window) =>
|
|
153
|
+
expandScheduleAvailabilityWindow(
|
|
154
|
+
window,
|
|
155
|
+
addScheduleDays(getScheduleLocalDate(args.from, window.timeZone), -1),
|
|
156
|
+
getScheduleLocalDate(args.to, window.timeZone),
|
|
157
|
+
fromMs,
|
|
158
|
+
toMs,
|
|
159
|
+
),
|
|
160
|
+
)
|
|
161
|
+
.sort(
|
|
162
|
+
(a, b) =>
|
|
163
|
+
a.startAt.getTime() - b.startAt.getTime() ||
|
|
164
|
+
compareScheduleIds(a.resourceId, b.resourceId) ||
|
|
165
|
+
compareScheduleIds(a.availabilityId, b.availabilityId),
|
|
166
|
+
);
|
|
167
|
+
}
|
|
@@ -0,0 +1,447 @@
|
|
|
1
|
+
import {
|
|
2
|
+
SCHEDULE_CANDIDATE_SCORE_POINTS,
|
|
3
|
+
SCHEDULE_SHIFT_MAX_DURATION_DAYS,
|
|
4
|
+
} from '../constants/schedule.ts';
|
|
5
|
+
import type {
|
|
6
|
+
CoverageRuleInput,
|
|
7
|
+
CoverageShiftInput,
|
|
8
|
+
ScheduleCandidateInput,
|
|
9
|
+
ScheduleCandidateRankObj,
|
|
10
|
+
ScheduleCandidateScoreObj,
|
|
11
|
+
ScheduleCandidateScoreReasonObj,
|
|
12
|
+
ScheduleEligibilityResult,
|
|
13
|
+
} from '../types/schedule.d.ts';
|
|
14
|
+
import { expandScheduleAvailability } from './availability.ts';
|
|
15
|
+
import { evaluateShiftEligibility } from './eligibility.ts';
|
|
16
|
+
import { compareScheduleIds } from './ids.ts';
|
|
17
|
+
import { getScheduleShiftWorkedMinutes } from './laborRules.ts';
|
|
18
|
+
import {
|
|
19
|
+
addScheduleDays,
|
|
20
|
+
getScheduleLocalDate,
|
|
21
|
+
getScheduleLocalInstant,
|
|
22
|
+
getScheduleWeekStart,
|
|
23
|
+
isScheduleDateKey,
|
|
24
|
+
toScheduleTimeMs,
|
|
25
|
+
} from './localTime.ts';
|
|
26
|
+
import { getSchedulePersonRuleWindow } from './rule.ts';
|
|
27
|
+
import { stableStringify } from './violation.ts';
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* Candidate ranking for one open seat (IMPLEMENTATION §1.8): who to
|
|
31
|
+
* offer it to, best first. Offers rank once at creation; Phase 3 auto-fill
|
|
32
|
+
* ranks with the same inputs.
|
|
33
|
+
*
|
|
34
|
+
* - Hard filter: evaluateShiftEligibility (§1.4 BLOCKs and BLOCK person
|
|
35
|
+
* rules). Ineligible candidates are still scored (a manager sees why) and
|
|
36
|
+
* come last, by id, with rank null.
|
|
37
|
+
* - Score: integer points from SCHEDULE_CANDIDATE_SCORE_POINTS, one reason
|
|
38
|
+
* per signal: PREFERRED overlap, hours this pay week against
|
|
39
|
+
* targetWeeklyMinutes, WARN eligibility reasons (a MAX_HOURS WARN weighs
|
|
40
|
+
* most), recent declined offers, days since their last seat at this
|
|
41
|
+
* calendar (fairness) and how often they worked this slot lately.
|
|
42
|
+
* - Order: eligible by total descending, ties by compareScheduleIds; rank is
|
|
43
|
+
* the 1-based position among the eligible.
|
|
44
|
+
* - Pure: every candidate is evaluated at the given `now`.
|
|
45
|
+
*/
|
|
46
|
+
|
|
47
|
+
// Worked-minute shares of the seat's pay week and the target they meet
|
|
48
|
+
type ScheduleWeekLoad = {
|
|
49
|
+
weekMinutes: number;
|
|
50
|
+
seatMinutes: number;
|
|
51
|
+
targetMinutes: number;
|
|
52
|
+
};
|
|
53
|
+
|
|
54
|
+
const FILE_CONSTANTS = {
|
|
55
|
+
minuteMs: 60_000,
|
|
56
|
+
dayMs: 86_400_000,
|
|
57
|
+
};
|
|
58
|
+
|
|
59
|
+
/*
|
|
60
|
+
* Round minutes or a fraction to two decimals (detail values).
|
|
61
|
+
*/
|
|
62
|
+
function roundDetail(value: number): number {
|
|
63
|
+
return Math.round(value * 100) / 100;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/*
|
|
67
|
+
* Return the local business day of a seat: its shiftDate, or the local date
|
|
68
|
+
* of its start in the zone when shiftDate is unreadable.
|
|
69
|
+
*/
|
|
70
|
+
function getSeatDate(
|
|
71
|
+
shift: Pick<CoverageShiftInput, 'shiftDate' | 'startAt'>,
|
|
72
|
+
timeZone: string,
|
|
73
|
+
): string {
|
|
74
|
+
return isScheduleDateKey(shift.shiftDate)
|
|
75
|
+
? shift.shiftDate
|
|
76
|
+
: getScheduleLocalDate(shift.startAt, timeZone);
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/*
|
|
80
|
+
* Return the instants [from, to) of the pay week holding a seat's business
|
|
81
|
+
* day: the local midnight of the week's first day (payWeekStart) to seven
|
|
82
|
+
* days later.
|
|
83
|
+
*/
|
|
84
|
+
function getSeatPayWeek(
|
|
85
|
+
shift: Pick<CoverageShiftInput, 'shiftDate' | 'startAt'>,
|
|
86
|
+
timeZone: string,
|
|
87
|
+
payWeekStart: number,
|
|
88
|
+
): { fromMs: number; toMs: number } {
|
|
89
|
+
const weekStart = getScheduleWeekStart(
|
|
90
|
+
getSeatDate(shift, timeZone),
|
|
91
|
+
payWeekStart,
|
|
92
|
+
);
|
|
93
|
+
return {
|
|
94
|
+
fromMs: getScheduleLocalInstant(weekStart, 0, timeZone).getTime(),
|
|
95
|
+
toMs: getScheduleLocalInstant(
|
|
96
|
+
addScheduleDays(weekStart, 7),
|
|
97
|
+
0,
|
|
98
|
+
timeZone,
|
|
99
|
+
).getTime(),
|
|
100
|
+
};
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/*
|
|
104
|
+
* The instant window a candidate's timeline must cover for ranking: the
|
|
105
|
+
* person-rule window around the seat (lookback before its start, lookahead
|
|
106
|
+
* after its end) united with the seat's whole pay week, widened by the
|
|
107
|
+
* SCHEDULE_SHIFT_MAX_DURATION_DAYS shiftDate margin on both sides. Loading
|
|
108
|
+
* it makes pay-week minutes complete even with no MAX_HOURS rule.
|
|
109
|
+
*/
|
|
110
|
+
export function getScheduleCandidateWindow(args: {
|
|
111
|
+
shift: Pick<CoverageShiftInput, 'shiftDate' | 'startAt' | 'endAt'>;
|
|
112
|
+
timeZone: string;
|
|
113
|
+
payWeekStart: number;
|
|
114
|
+
rules: CoverageRuleInput[];
|
|
115
|
+
}): { from: Date; to: Date } {
|
|
116
|
+
const ruleWindow = getSchedulePersonRuleWindow(args.rules);
|
|
117
|
+
const week = getSeatPayWeek(args.shift, args.timeZone, args.payWeekStart);
|
|
118
|
+
const margin = SCHEDULE_SHIFT_MAX_DURATION_DAYS * FILE_CONSTANTS.dayMs;
|
|
119
|
+
const ruleFromMs =
|
|
120
|
+
toScheduleTimeMs(args.shift.startAt) -
|
|
121
|
+
ruleWindow.lookbackDays * FILE_CONSTANTS.dayMs;
|
|
122
|
+
const ruleToMs =
|
|
123
|
+
toScheduleTimeMs(args.shift.endAt) +
|
|
124
|
+
ruleWindow.lookaheadDays * FILE_CONSTANTS.dayMs;
|
|
125
|
+
return {
|
|
126
|
+
from: new Date(Math.min(ruleFromMs, week.fromMs) - margin),
|
|
127
|
+
to: new Date(Math.max(ruleToMs, week.toMs) + margin),
|
|
128
|
+
};
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/*
|
|
132
|
+
* Return the part of [startMs, endMs) covered by a set of intervals, in ms
|
|
133
|
+
* (overlapping intervals counted once).
|
|
134
|
+
*/
|
|
135
|
+
function getCoveredMs(
|
|
136
|
+
startMs: number,
|
|
137
|
+
endMs: number,
|
|
138
|
+
intervals: Array<{ startAt: Date; endAt: Date }>,
|
|
139
|
+
): number {
|
|
140
|
+
const clipped = intervals
|
|
141
|
+
.map(
|
|
142
|
+
(interval) =>
|
|
143
|
+
[
|
|
144
|
+
Math.max(startMs, interval.startAt.getTime()),
|
|
145
|
+
Math.min(endMs, interval.endAt.getTime()),
|
|
146
|
+
] as const,
|
|
147
|
+
)
|
|
148
|
+
.filter(([from, to]) => to > from)
|
|
149
|
+
.sort((a, b) => a[0] - b[0]);
|
|
150
|
+
let covered = 0;
|
|
151
|
+
let reach = startMs;
|
|
152
|
+
for (const [from, to] of clipped) {
|
|
153
|
+
if (to <= reach) continue;
|
|
154
|
+
covered += to - Math.max(from, reach);
|
|
155
|
+
reach = to;
|
|
156
|
+
}
|
|
157
|
+
return covered;
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/*
|
|
161
|
+
* PREFERRED_TIME: the fraction of the seat inside the candidate's PREFERRED
|
|
162
|
+
* windows (each in its own zone) times its points; none when it rounds to 0.
|
|
163
|
+
*/
|
|
164
|
+
function getPreferredTimeReason(
|
|
165
|
+
shift: CoverageShiftInput,
|
|
166
|
+
candidate: ScheduleCandidateInput,
|
|
167
|
+
): ScheduleCandidateScoreReasonObj | null {
|
|
168
|
+
const startMs = toScheduleTimeMs(shift.startAt);
|
|
169
|
+
const endMs = toScheduleTimeMs(shift.endAt);
|
|
170
|
+
if (!(endMs > startMs)) return null;
|
|
171
|
+
const windows = candidate.context.availability.filter(
|
|
172
|
+
(window) =>
|
|
173
|
+
window.resourceId === candidate.resource.id &&
|
|
174
|
+
window.kind === 'PREFERRED',
|
|
175
|
+
);
|
|
176
|
+
if (!windows.length) return null;
|
|
177
|
+
const intervals = expandScheduleAvailability({
|
|
178
|
+
windows,
|
|
179
|
+
from: shift.startAt,
|
|
180
|
+
to: shift.endAt,
|
|
181
|
+
});
|
|
182
|
+
const fraction = getCoveredMs(startMs, endMs, intervals) / (endMs - startMs);
|
|
183
|
+
const points = Math.round(
|
|
184
|
+
SCHEDULE_CANDIDATE_SCORE_POINTS.preferredTime * fraction,
|
|
185
|
+
);
|
|
186
|
+
if (!points) return null;
|
|
187
|
+
return {
|
|
188
|
+
code: 'PREFERRED_TIME',
|
|
189
|
+
points,
|
|
190
|
+
detail: { fraction: roundDetail(fraction) },
|
|
191
|
+
};
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
/*
|
|
195
|
+
* Return a seat's worked minutes inside [fromMs, toMs), split by overlap.
|
|
196
|
+
*/
|
|
197
|
+
function getWorkedMinutesInside(
|
|
198
|
+
shift: CoverageShiftInput,
|
|
199
|
+
fromMs: number,
|
|
200
|
+
toMs: number,
|
|
201
|
+
): number {
|
|
202
|
+
const startMs = toScheduleTimeMs(shift.startAt);
|
|
203
|
+
const endMs = toScheduleTimeMs(shift.endAt);
|
|
204
|
+
const overlapMs = Math.min(endMs, toMs) - Math.max(startMs, fromMs);
|
|
205
|
+
if (!(endMs > startMs) || !(overlapMs > 0)) return 0;
|
|
206
|
+
return (getScheduleShiftWorkedMinutes(shift) * overlapMs) / (endMs - startMs);
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
/*
|
|
210
|
+
* The candidate's load in the seat's pay week: worked minutes of their other
|
|
211
|
+
* live seats (deduplicated, split by overlap), the seat's own worked minutes
|
|
212
|
+
* inside the week, and their target. Null when they have no target.
|
|
213
|
+
*/
|
|
214
|
+
function getWeekLoad(
|
|
215
|
+
shift: CoverageShiftInput,
|
|
216
|
+
candidate: ScheduleCandidateInput,
|
|
217
|
+
): ScheduleWeekLoad | null {
|
|
218
|
+
const target = candidate.resource.config.preferences?.targetWeeklyMinutes;
|
|
219
|
+
if (typeof target !== 'number' || !Number.isFinite(target) || target < 0)
|
|
220
|
+
return null;
|
|
221
|
+
const { context, resource } = candidate;
|
|
222
|
+
const week = getSeatPayWeek(shift, context.timeZone, context.payWeekStart);
|
|
223
|
+
const seen = new Set<string>([shift.id]);
|
|
224
|
+
let weekMinutes = 0;
|
|
225
|
+
for (const other of context.timeline) {
|
|
226
|
+
if (seen.has(other.id)) continue;
|
|
227
|
+
seen.add(other.id);
|
|
228
|
+
if (other.status === 'CANCELED' || other.assigneeResourceId !== resource.id)
|
|
229
|
+
continue;
|
|
230
|
+
weekMinutes += getWorkedMinutesInside(other, week.fromMs, week.toMs);
|
|
231
|
+
}
|
|
232
|
+
return {
|
|
233
|
+
weekMinutes: roundDetail(weekMinutes),
|
|
234
|
+
seatMinutes: roundDetail(
|
|
235
|
+
getWorkedMinutesInside(shift, week.fromMs, week.toMs),
|
|
236
|
+
),
|
|
237
|
+
targetMinutes: target,
|
|
238
|
+
};
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
/*
|
|
242
|
+
* UNDER_TARGET_HOURS / OVER_TARGET_HOURS: the full under-target points when
|
|
243
|
+
* the seat fits under the target, a pro-rata share plus an over-target
|
|
244
|
+
* penalty when it crosses it, only the penalty when the week is already at
|
|
245
|
+
* or over it. None without a target.
|
|
246
|
+
*/
|
|
247
|
+
function getTargetHoursReasons(
|
|
248
|
+
shift: CoverageShiftInput,
|
|
249
|
+
candidate: ScheduleCandidateInput,
|
|
250
|
+
): ScheduleCandidateScoreReasonObj[] {
|
|
251
|
+
const load = getWeekLoad(shift, candidate);
|
|
252
|
+
if (!load) return [];
|
|
253
|
+
const points = SCHEDULE_CANDIDATE_SCORE_POINTS;
|
|
254
|
+
const { weekMinutes, seatMinutes, targetMinutes } = load;
|
|
255
|
+
const overMinutes = roundDetail(
|
|
256
|
+
Math.max(0, weekMinutes + seatMinutes - targetMinutes),
|
|
257
|
+
);
|
|
258
|
+
const detail = { weekMinutes, targetMinutes, overMinutes };
|
|
259
|
+
if (!overMinutes)
|
|
260
|
+
return [{ code: 'UNDER_TARGET_HOURS', points: points.underTarget, detail }];
|
|
261
|
+
const reasons: ScheduleCandidateScoreReasonObj[] = [];
|
|
262
|
+
if (weekMinutes < targetMinutes) {
|
|
263
|
+
const share = Math.round(
|
|
264
|
+
(points.underTarget * (targetMinutes - weekMinutes)) / seatMinutes,
|
|
265
|
+
);
|
|
266
|
+
if (share)
|
|
267
|
+
reasons.push({ code: 'UNDER_TARGET_HOURS', points: share, detail });
|
|
268
|
+
}
|
|
269
|
+
reasons.push({
|
|
270
|
+
code: 'OVER_TARGET_HOURS',
|
|
271
|
+
points: Math.max(
|
|
272
|
+
points.overTargetFloor,
|
|
273
|
+
points.overTargetPerHour * Math.ceil(overMinutes / 60),
|
|
274
|
+
),
|
|
275
|
+
detail,
|
|
276
|
+
});
|
|
277
|
+
return reasons;
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
/*
|
|
281
|
+
* RULE_WARNING: one reason per distinct WARN eligibility code (several
|
|
282
|
+
* windows or rules of one code count once). MAX_HOURS and UNAVAILABLE have
|
|
283
|
+
* their own points; every other code weighs OTHER.
|
|
284
|
+
*/
|
|
285
|
+
function getRuleWarningReasons(
|
|
286
|
+
eligibility: ScheduleEligibilityResult,
|
|
287
|
+
): ScheduleCandidateScoreReasonObj[] {
|
|
288
|
+
const weights = SCHEDULE_CANDIDATE_SCORE_POINTS.ruleWarning;
|
|
289
|
+
const codes = new Set(
|
|
290
|
+
eligibility.reasons
|
|
291
|
+
.filter((reason) => reason.severity === 'WARN')
|
|
292
|
+
.map((reason) => reason.code),
|
|
293
|
+
);
|
|
294
|
+
return [...codes].map((code) => ({
|
|
295
|
+
code: 'RULE_WARNING',
|
|
296
|
+
points:
|
|
297
|
+
code === 'MAX_HOURS' || code === 'UNAVAILABLE'
|
|
298
|
+
? weights[code]
|
|
299
|
+
: weights.OTHER,
|
|
300
|
+
detail: { code },
|
|
301
|
+
}));
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
/*
|
|
305
|
+
* RECENT_DECLINES: points per declined offer in the lookback, down to the
|
|
306
|
+
* floor; none without declines.
|
|
307
|
+
*/
|
|
308
|
+
function getDeclineReason(
|
|
309
|
+
candidate: ScheduleCandidateInput,
|
|
310
|
+
): ScheduleCandidateScoreReasonObj | null {
|
|
311
|
+
const count = Math.max(0, Math.floor(candidate.history.declinedOfferCount));
|
|
312
|
+
if (!count) return null;
|
|
313
|
+
const points = SCHEDULE_CANDIDATE_SCORE_POINTS;
|
|
314
|
+
return {
|
|
315
|
+
code: 'RECENT_DECLINES',
|
|
316
|
+
points: Math.max(points.declineFloor, points.declinePerOffer * count),
|
|
317
|
+
detail: { count },
|
|
318
|
+
};
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
/*
|
|
322
|
+
* FAIRNESS: points per whole day between their last seat at this calendar
|
|
323
|
+
* and this seat's start, up to the maximum (the maximum when they had none
|
|
324
|
+
* in the lookback). None when it comes to 0 or the instant is unreadable.
|
|
325
|
+
*/
|
|
326
|
+
function getFairnessReason(
|
|
327
|
+
shift: CoverageShiftInput,
|
|
328
|
+
candidate: ScheduleCandidateInput,
|
|
329
|
+
): ScheduleCandidateScoreReasonObj | null {
|
|
330
|
+
const points = SCHEDULE_CANDIDATE_SCORE_POINTS;
|
|
331
|
+
const lastShiftEndAt = candidate.history.lastShiftEndAt;
|
|
332
|
+
if (lastShiftEndAt === null)
|
|
333
|
+
return {
|
|
334
|
+
code: 'FAIRNESS',
|
|
335
|
+
points: points.fairnessMax,
|
|
336
|
+
detail: { days: null },
|
|
337
|
+
};
|
|
338
|
+
const gapMs =
|
|
339
|
+
toScheduleTimeMs(shift.startAt) - toScheduleTimeMs(lastShiftEndAt);
|
|
340
|
+
if (!Number.isFinite(gapMs)) return null;
|
|
341
|
+
const days = Math.max(0, Math.floor(gapMs / FILE_CONSTANTS.dayMs));
|
|
342
|
+
const value = Math.min(points.fairnessMax, points.fairnessPerDay * days);
|
|
343
|
+
return value ? { code: 'FAIRNESS', points: value, detail: { days } } : null;
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
/*
|
|
347
|
+
* RECENT_SLOT: points per recent seat of theirs in this slot (same weekday
|
|
348
|
+
* and role, close start), up to the maximum; none when they had none.
|
|
349
|
+
*/
|
|
350
|
+
function getSameSlotReason(
|
|
351
|
+
candidate: ScheduleCandidateInput,
|
|
352
|
+
): ScheduleCandidateScoreReasonObj | null {
|
|
353
|
+
const count = Math.max(0, Math.floor(candidate.history.sameSlotCount));
|
|
354
|
+
if (!count) return null;
|
|
355
|
+
const points = SCHEDULE_CANDIDATE_SCORE_POINTS;
|
|
356
|
+
return {
|
|
357
|
+
code: 'RECENT_SLOT',
|
|
358
|
+
points: Math.min(points.sameSlotMax, points.sameSlotPerShift * count),
|
|
359
|
+
detail: { count },
|
|
360
|
+
};
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
/*
|
|
364
|
+
* Order score reasons by |points| descending, then code, then detail.
|
|
365
|
+
*/
|
|
366
|
+
function sortScoreReasons(
|
|
367
|
+
reasons: ScheduleCandidateScoreReasonObj[],
|
|
368
|
+
): ScheduleCandidateScoreReasonObj[] {
|
|
369
|
+
return [...reasons].sort((a, b) => {
|
|
370
|
+
const byPoints = Math.abs(b.points) - Math.abs(a.points);
|
|
371
|
+
if (byPoints) return byPoints;
|
|
372
|
+
if (a.code !== b.code) return a.code < b.code ? -1 : 1;
|
|
373
|
+
const left = stableStringify(a.detail);
|
|
374
|
+
const right = stableStringify(b.detail);
|
|
375
|
+
return left < right ? -1 : left > right ? 1 : 0;
|
|
376
|
+
});
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
/*
|
|
380
|
+
* Score one candidate for one seat from every signal, given its
|
|
381
|
+
* eligibility (its WARN reasons are signals too).
|
|
382
|
+
*/
|
|
383
|
+
function scoreShiftCandidate(
|
|
384
|
+
shift: CoverageShiftInput,
|
|
385
|
+
candidate: ScheduleCandidateInput,
|
|
386
|
+
eligibility: ScheduleEligibilityResult,
|
|
387
|
+
): ScheduleCandidateScoreObj {
|
|
388
|
+
const reasons = sortScoreReasons(
|
|
389
|
+
[
|
|
390
|
+
getPreferredTimeReason(shift, candidate),
|
|
391
|
+
...getTargetHoursReasons(shift, candidate),
|
|
392
|
+
...getRuleWarningReasons(eligibility),
|
|
393
|
+
getDeclineReason(candidate),
|
|
394
|
+
getFairnessReason(shift, candidate),
|
|
395
|
+
getSameSlotReason(candidate),
|
|
396
|
+
].filter(
|
|
397
|
+
(reason): reason is ScheduleCandidateScoreReasonObj => reason !== null,
|
|
398
|
+
),
|
|
399
|
+
);
|
|
400
|
+
return {
|
|
401
|
+
total: reasons.reduce((sum, reason) => sum + reason.points, 0),
|
|
402
|
+
reasons,
|
|
403
|
+
};
|
|
404
|
+
}
|
|
405
|
+
|
|
406
|
+
/*
|
|
407
|
+
* Rank candidates for one seat: each is evaluated at `now` (eligibility is
|
|
408
|
+
* the hard filter) and scored. Eligible candidates come first by total
|
|
409
|
+
* descending (ties by compareScheduleIds), ranked 1..n; ineligible ones
|
|
410
|
+
* follow by id with rank null. A candidate listed twice counts once (the
|
|
411
|
+
* first copy).
|
|
412
|
+
*/
|
|
413
|
+
export function rankShiftCandidates(input: {
|
|
414
|
+
shift: CoverageShiftInput;
|
|
415
|
+
candidates: ScheduleCandidateInput[];
|
|
416
|
+
now: Date | string;
|
|
417
|
+
}): ScheduleCandidateRankObj[] {
|
|
418
|
+
const seen = new Set<string>();
|
|
419
|
+
const results: ScheduleCandidateRankObj[] = [];
|
|
420
|
+
for (const candidate of input.candidates) {
|
|
421
|
+
if (seen.has(candidate.resource.id)) continue;
|
|
422
|
+
seen.add(candidate.resource.id);
|
|
423
|
+
const eligibility = evaluateShiftEligibility({
|
|
424
|
+
shift: input.shift,
|
|
425
|
+
resource: candidate.resource,
|
|
426
|
+
context: { ...candidate.context, now: input.now },
|
|
427
|
+
});
|
|
428
|
+
results.push({
|
|
429
|
+
resourceId: candidate.resource.id,
|
|
430
|
+
rank: null,
|
|
431
|
+
eligibility,
|
|
432
|
+
score: scoreShiftCandidate(input.shift, candidate, eligibility),
|
|
433
|
+
});
|
|
434
|
+
}
|
|
435
|
+
const eligible = results
|
|
436
|
+
.filter((result) => result.eligibility.eligible)
|
|
437
|
+
.sort(
|
|
438
|
+
(a, b) =>
|
|
439
|
+
b.score.total - a.score.total ||
|
|
440
|
+
compareScheduleIds(a.resourceId, b.resourceId),
|
|
441
|
+
)
|
|
442
|
+
.map((result, index) => ({ ...result, rank: index + 1 }));
|
|
443
|
+
const ineligible = results
|
|
444
|
+
.filter((result) => !result.eligibility.eligible)
|
|
445
|
+
.sort((a, b) => compareScheduleIds(a.resourceId, b.resourceId));
|
|
446
|
+
return [...eligible, ...ineligible];
|
|
447
|
+
}
|