@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
@@ -1,5 +1,6 @@
1
1
  import i18n from '@jsb188/app/i18n/index.ts';
2
2
  import { memo } from 'react';
3
+ import { SCHEDULE_RESOURCE_KIND_ENUMS } from '../constants/schedule.ts';
3
4
  import type { ScheduleResourceKindEnum } from '../types/schedule.d.ts';
4
5
 
5
6
  export interface ScheduleResourceFormValues {
@@ -13,9 +14,8 @@ export interface ScheduleResourceFormValues {
13
14
  capacity: string;
14
15
  unitOfMeasure: string;
15
16
  canLevel: boolean;
16
- roles: string;
17
17
  tags: string;
18
- ageGroup: string;
18
+ // PERSON only
19
19
  qualifications: Array<{ key: string; expiresAt: string }>;
20
20
  }
21
21
 
@@ -29,7 +29,11 @@ export interface ScheduleWorkCalendarFormValues {
29
29
  days: Array<Array<{ start: string; end: string }>>;
30
30
  }
31
31
 
32
- /* Render resource fields and dated qualifications without owning persistence or authorization. */
32
+ /*
33
+ * Render resource fields and dated qualifications without owning persistence
34
+ * or authorization. A PERSON is a team member and must be linked to their
35
+ * account when created (the link never changes); every other kind has none.
36
+ */
33
37
  export const ScheduleResourceFormUI = memo(
34
38
  (p: {
35
39
  value: ScheduleResourceFormValues;
@@ -61,7 +65,7 @@ export const ScheduleResourceFormUI = memo(
61
65
  value={v.kind}
62
66
  onChange={(event) => change('kind', event.target.value)}
63
67
  >
64
- {['LABOR', 'EQUIPMENT', 'MATERIAL', 'SPACE'].map((kind) => (
68
+ {SCHEDULE_RESOURCE_KIND_ENUMS.map((kind) => (
65
69
  <option
66
70
  key={kind}
67
71
  value={kind}
@@ -84,15 +88,17 @@ export const ScheduleResourceFormUI = memo(
84
88
  />
85
89
  </label>
86
90
  ))}
87
- {v.kind === 'LABOR' && (
91
+ {v.kind === 'PERSON' && (
88
92
  <label>
89
93
  {i18n.t('schedule.settings.account')}
90
94
  <select
91
95
  className="bl w_f p_8 bd_1 bd_bd r_sm"
96
+ required
97
+ disabled={p.existing}
92
98
  value={v.accountId}
93
99
  onChange={(event) => change('accountId', event.target.value)}
94
100
  >
95
- <option value="">{i18n.t('schedule.settings.unlinked')}</option>
101
+ <option value="">{i18n.t('schedule.settings.select')}</option>
96
102
  {p.accounts.map((account) => (
97
103
  <option
98
104
  key={account.id}
@@ -156,23 +162,15 @@ export const ScheduleResourceFormUI = memo(
156
162
  {i18n.t('schedule.settings.can_level')}
157
163
  </label>
158
164
  )}
159
- {(
160
- [
161
- 'roles',
162
- 'tags',
163
- ...(v.kind === 'SPACE' ? ['ageGroup'] : []),
164
- ] as Array<'roles' | 'tags' | 'ageGroup'>
165
- ).map((key) => (
166
- <label key={key}>
167
- {i18n.t('schedule.settings.' + key)}
168
- <input
169
- className="bl w_f p_8 bd_1 bd_bd r_sm"
170
- value={v[key]}
171
- onChange={(event) => change(key, event.target.value)}
172
- />
173
- </label>
174
- ))}
175
- {v.kind === 'LABOR' && (
165
+ <label>
166
+ {i18n.t('schedule.settings.tags')}
167
+ <input
168
+ className="bl w_f p_8 bd_1 bd_bd r_sm"
169
+ value={v.tags}
170
+ onChange={(event) => change('tags', event.target.value)}
171
+ />
172
+ </label>
173
+ {v.kind === 'PERSON' && (
176
174
  <fieldset className="v_stretch gap_xs">
177
175
  <legend>{i18n.t('schedule.settings.qualifications')}</legend>
178
176
  {v.qualifications.map((qualification, index) => (
@@ -0,0 +1,469 @@
1
+ import type {
2
+ CoverageAvailabilityInput,
3
+ CoverageResourceInput,
4
+ CoverageRuleInput,
5
+ CoverageShiftInput,
6
+ CoverageTimeOffInput,
7
+ ScheduleCandidateHistoryObj,
8
+ ScheduleCandidateRankObj,
9
+ ScheduleEligibilityContext,
10
+ ScheduleEligibilityResult,
11
+ ScheduleRosterInput,
12
+ ScheduleRosterResultObj,
13
+ ScheduleRosterUnfilledObj,
14
+ } from '../types/schedule.d.ts';
15
+ import {
16
+ getScheduleCandidateWindow,
17
+ rankShiftCandidates,
18
+ } from './candidates.ts';
19
+ import { evaluateShiftEligibility } from './eligibility.ts';
20
+ import { compareScheduleIds } from './ids.ts';
21
+ import { toScheduleTimeMs } from './localTime.ts';
22
+
23
+ /**
24
+ * Auto-fill of a prepared period (IMPLEMENTATION §1.12): a greedy pass
25
+ * over the open draft seats, scarcest seat first.
26
+ *
27
+ * - The seat with the fewest clean candidates goes first (ties: earlier
28
+ * start, then id). Clean = eligible with no WARN reason:
29
+ * auto-fill never creates a warning a manager would have to accept.
30
+ * - Its clean candidates are ranked with rankShiftCandidates (the recent-slot
31
+ * and fairness signals come from the caller's histories) and rank 1 takes
32
+ * the seat on a simulated timeline. Only the winner's eligibility for the
33
+ * remaining seats changes (eligibility depends on one person's timeline),
34
+ * and only for seats whose candidate window (getScheduleCandidateWindow)
35
+ * the new seat touches, so overlap and the person rules (MAX_HOURS, MIN_REST,
36
+ * MAX_CONSECUTIVE_DAYS, SHIFT_LENGTH) and the target-hours score follow
37
+ * every assignment made so far.
38
+ * - A seat nobody can take cleanly is unfilled: NO_CANDIDATES (nobody holds
39
+ * its role), WARNINGS_ONLY (someone could, with a warning) or
40
+ * NONE_ELIGIBLE (with the BLOCK codes that stopped them).
41
+ * - Pure and deterministic; inputs are not mutated.
42
+ */
43
+
44
+ // One pool person: their filtered evidence and simulated timeline
45
+ interface ScheduleRosterPerson {
46
+ resource: CoverageResourceInput;
47
+ timeline: CoverageShiftInput[];
48
+ timeOff: CoverageTimeOffInput[];
49
+ availability: CoverageAvailabilityInput[];
50
+ rules: CoverageRuleInput[];
51
+ rankingRules: CoverageRuleInput[]; // ELIGIBILITY only (see getRosterRanks)
52
+ }
53
+
54
+ // One seat still to fill: its candidates, their latest eligibility, and
55
+ // the instants a candidate's timeline matters for it (getScheduleCandidateWindow)
56
+ interface ScheduleRosterSeat {
57
+ shift: CoverageShiftInput;
58
+ candidateIds: string[];
59
+ results: Map<string, ScheduleEligibilityResult>;
60
+ fromMs: number;
61
+ toMs: number;
62
+ }
63
+
64
+ const FILE_CONSTANTS = {
65
+ emptyHistory: {
66
+ declinedOfferCount: 0,
67
+ lastShiftEndAt: null,
68
+ sameSlotCount: 0,
69
+ } satisfies ScheduleCandidateHistoryObj,
70
+ };
71
+
72
+ /*
73
+ * The instant window the roster's evidence must cover: the union of
74
+ * getScheduleCandidateWindow over the seats; null when there are none.
75
+ */
76
+ export function getScheduleRosterWindow(args: {
77
+ seats: CoverageShiftInput[];
78
+ timeZone: string;
79
+ payWeekStart: number;
80
+ rules: CoverageRuleInput[];
81
+ }): { from: Date; to: Date } | null {
82
+ let fromMs = Number.POSITIVE_INFINITY;
83
+ let toMs = Number.NEGATIVE_INFINITY;
84
+ for (const shift of args.seats) {
85
+ const window = getScheduleCandidateWindow({
86
+ shift,
87
+ timeZone: args.timeZone,
88
+ payWeekStart: args.payWeekStart,
89
+ rules: args.rules,
90
+ });
91
+ fromMs = Math.min(fromMs, window.from.getTime());
92
+ toMs = Math.max(toMs, window.to.getTime());
93
+ }
94
+ return args.seats.length
95
+ ? { from: new Date(fromMs), to: new Date(toMs) }
96
+ : null;
97
+ }
98
+
99
+ /*
100
+ * Order seats by start, then id.
101
+ */
102
+ function compareRosterSeats(
103
+ a: CoverageShiftInput,
104
+ b: CoverageShiftInput,
105
+ ): number {
106
+ return (
107
+ toScheduleTimeMs(a.startAt) - toScheduleTimeMs(b.startAt) ||
108
+ compareScheduleIds(a.id, b.id)
109
+ );
110
+ }
111
+
112
+ /*
113
+ * Keep a list's first entry per id, sorted by id.
114
+ */
115
+ function dedupeById<T>(rows: T[], getId: (row: T) => string): T[] {
116
+ const byId = new Map<string, T>();
117
+ for (const row of rows) if (!byId.has(getId(row))) byId.set(getId(row), row);
118
+ return [...byId.values()].sort((a, b) =>
119
+ compareScheduleIds(getId(a), getId(b)),
120
+ );
121
+ }
122
+
123
+ /*
124
+ * The seats auto-fill considers: DRAFT, open, of the calendar and starting
125
+ * after now; one per id, by start then id.
126
+ */
127
+ function getRosterSeats(input: ScheduleRosterInput): CoverageShiftInput[] {
128
+ const nowMs = toScheduleTimeMs(input.now);
129
+ return dedupeById(input.seats, (seat) => seat.id)
130
+ .filter(
131
+ (seat) =>
132
+ seat.status === 'DRAFT' &&
133
+ seat.assigneeResourceId === null &&
134
+ seat.calendarId === input.calendarId &&
135
+ toScheduleTimeMs(seat.startAt) > nowMs,
136
+ )
137
+ .sort(compareRosterSeats);
138
+ }
139
+
140
+ /*
141
+ * Build each pool person's evidence (as buildScheduleEligibilityContext
142
+ * filters it: their seats, time off and windows, and the rules of any scope
143
+ * but another person's) and starting timeline. Timeline rows of the seats
144
+ * being filled are left out: those seats are open.
145
+ */
146
+ function getRosterPeople(
147
+ input: ScheduleRosterInput,
148
+ seatIds: Set<string>,
149
+ ): Map<string, ScheduleRosterPerson> {
150
+ const people = new Map<string, ScheduleRosterPerson>();
151
+ for (const resource of dedupeById(input.people, (person) => person.id)) {
152
+ const id = resource.id;
153
+ const rules = input.rules.filter(
154
+ (rule) => rule.resourceId === null || rule.resourceId === id,
155
+ );
156
+ people.set(id, {
157
+ resource,
158
+ timeline: input.timeline.filter(
159
+ (shift) => shift.assigneeResourceId === id && !seatIds.has(shift.id),
160
+ ),
161
+ timeOff: input.timeOff.filter((row) => row.resourceId === id),
162
+ availability: input.availability.filter((row) => row.resourceId === id),
163
+ rules,
164
+ rankingRules: rules.filter((rule) => rule.kind === 'ELIGIBILITY'),
165
+ });
166
+ }
167
+ return people;
168
+ }
169
+
170
+ /*
171
+ * One person's eligibility context on their current simulated timeline
172
+ * (with only the given rules when set).
173
+ */
174
+ function getRosterContext(
175
+ input: ScheduleRosterInput,
176
+ person: ScheduleRosterPerson,
177
+ rules: CoverageRuleInput[] = person.rules,
178
+ ): ScheduleEligibilityContext {
179
+ return {
180
+ calendarId: input.calendarId,
181
+ now: input.now,
182
+ timeZone: input.timeZone,
183
+ payWeekStart: input.payWeekStart,
184
+ roles: input.roles,
185
+ timeline: person.timeline,
186
+ timeOff: person.timeOff,
187
+ availability: person.availability,
188
+ rules,
189
+ };
190
+ }
191
+
192
+ /*
193
+ * The pool people who may take a seat: those holding its role, everyone
194
+ * when it has none (by id).
195
+ */
196
+ function getRosterCandidateIds(
197
+ shift: CoverageShiftInput,
198
+ people: Map<string, ScheduleRosterPerson>,
199
+ ): string[] {
200
+ return [...people.values()]
201
+ .filter(
202
+ (person) =>
203
+ shift.roleId === null || person.resource.roleIds.includes(shift.roleId),
204
+ )
205
+ .map((person) => person.resource.id);
206
+ }
207
+
208
+ /*
209
+ * Clean = eligible with no WARN reason.
210
+ */
211
+ function isCleanEligibility(result: ScheduleEligibilityResult): boolean {
212
+ return (
213
+ result.eligible &&
214
+ !result.reasons.some((reason) => reason.severity === 'WARN')
215
+ );
216
+ }
217
+
218
+ /*
219
+ * Evaluate one person for one seat on their simulated timeline.
220
+ */
221
+ function evaluateRosterCandidate(
222
+ input: ScheduleRosterInput,
223
+ shift: CoverageShiftInput,
224
+ person: ScheduleRosterPerson,
225
+ ): ScheduleEligibilityResult {
226
+ return evaluateShiftEligibility({
227
+ shift,
228
+ resource: person.resource,
229
+ context: getRosterContext(input, person),
230
+ });
231
+ }
232
+
233
+ /*
234
+ * The clean candidates of a seat, by id.
235
+ */
236
+ function getCleanCandidateIds(seat: ScheduleRosterSeat): string[] {
237
+ return seat.candidateIds.filter((id) =>
238
+ isCleanEligibility(seat.results.get(id) as ScheduleEligibilityResult),
239
+ );
240
+ }
241
+
242
+ /*
243
+ * Pick the scarcest remaining seat: the fewest clean candidates, then the
244
+ * earlier start, then the lower id.
245
+ */
246
+ function pickScarcestSeat(seats: ScheduleRosterSeat[]): ScheduleRosterSeat {
247
+ let best = seats[0];
248
+ let bestCount = getCleanCandidateIds(best).length;
249
+ for (const seat of seats.slice(1)) {
250
+ const count = getCleanCandidateIds(seat).length;
251
+ if (
252
+ count < bestCount ||
253
+ (count === bestCount && compareRosterSeats(seat.shift, best.shift) < 0)
254
+ ) {
255
+ best = seat;
256
+ bestCount = count;
257
+ }
258
+ }
259
+ return best;
260
+ }
261
+
262
+ /*
263
+ * Count the BLOCK codes among a seat's candidates (each candidate once per
264
+ * code), by count descending, then code.
265
+ */
266
+ function getRosterBlockCodes(
267
+ seat: ScheduleRosterSeat,
268
+ ): ScheduleRosterUnfilledObj['blockCodes'] {
269
+ const counts = new Map<
270
+ ScheduleRosterUnfilledObj['blockCodes'][number]['code'],
271
+ number
272
+ >();
273
+ for (const result of seat.results.values()) {
274
+ const codes = new Set(
275
+ result.reasons
276
+ .filter((reason) => reason.severity === 'BLOCK')
277
+ .map((reason) => reason.code),
278
+ );
279
+ for (const code of codes) counts.set(code, (counts.get(code) ?? 0) + 1);
280
+ }
281
+ return [...counts]
282
+ .map(([code, count]) => ({ code, count }))
283
+ .sort(
284
+ (a, b) =>
285
+ b.count - a.count || (a.code < b.code ? -1 : a.code > b.code ? 1 : 0),
286
+ );
287
+ }
288
+
289
+ /*
290
+ * The unfilled entry of a seat nobody can take cleanly: WARNINGS_ONLY when
291
+ * some candidate is eligible with a warning, else NONE_ELIGIBLE.
292
+ */
293
+ function getRosterUnfilled(
294
+ seat: ScheduleRosterSeat,
295
+ ): ScheduleRosterUnfilledObj {
296
+ const eligible = [...seat.results.values()].some((result) => result.eligible);
297
+ return {
298
+ shiftId: seat.shift.id,
299
+ reason: eligible ? 'WARNINGS_ONLY' : 'NONE_ELIGIBLE',
300
+ candidateCount: seat.candidateIds.length,
301
+ blockCodes: getRosterBlockCodes(seat),
302
+ };
303
+ }
304
+
305
+ /*
306
+ * Rank a seat's clean candidates (rankShiftCandidates) on their simulated
307
+ * timelines with the caller's histories. The person rules are left out of
308
+ * these contexts: they found nothing for a clean candidate on this same
309
+ * timeline, and a clean candidate has no reason at all (severities are
310
+ * BLOCK or WARN), so the ranks are the same without re-running them.
311
+ */
312
+ function getRosterRanks(
313
+ input: ScheduleRosterInput,
314
+ shift: CoverageShiftInput,
315
+ cleanIds: string[],
316
+ people: Map<string, ScheduleRosterPerson>,
317
+ ): ScheduleCandidateRankObj[] {
318
+ const histories = input.histories[shift.id] ?? {};
319
+ return rankShiftCandidates({
320
+ shift,
321
+ candidates: cleanIds.map((id) => {
322
+ const person = people.get(id) as ScheduleRosterPerson;
323
+ return {
324
+ resource: person.resource,
325
+ context: getRosterContext(input, person, person.rankingRules),
326
+ history: histories[id] ?? FILE_CONSTANTS.emptyHistory,
327
+ };
328
+ }),
329
+ now: input.now,
330
+ });
331
+ }
332
+
333
+ /*
334
+ * Evaluate every candidate of every seat on the starting timelines. A seat
335
+ * nobody holds the role for is NO_CANDIDATES at once.
336
+ */
337
+ function getRosterStartingSeats(
338
+ input: ScheduleRosterInput,
339
+ shifts: CoverageShiftInput[],
340
+ people: Map<string, ScheduleRosterPerson>,
341
+ ): { seats: ScheduleRosterSeat[]; unfilled: ScheduleRosterUnfilledObj[] } {
342
+ const seats: ScheduleRosterSeat[] = [];
343
+ const unfilled: ScheduleRosterUnfilledObj[] = [];
344
+ for (const shift of shifts) {
345
+ const candidateIds = getRosterCandidateIds(shift, people);
346
+ if (!candidateIds.length) {
347
+ unfilled.push({
348
+ shiftId: shift.id,
349
+ reason: 'NO_CANDIDATES',
350
+ candidateCount: 0,
351
+ blockCodes: [],
352
+ });
353
+ continue;
354
+ }
355
+ const window = getScheduleCandidateWindow({
356
+ shift,
357
+ timeZone: input.timeZone,
358
+ payWeekStart: input.payWeekStart,
359
+ rules: input.rules,
360
+ });
361
+ seats.push({
362
+ shift,
363
+ candidateIds,
364
+ results: new Map(
365
+ candidateIds.map((id) => [
366
+ id,
367
+ evaluateRosterCandidate(
368
+ input,
369
+ shift,
370
+ people.get(id) as ScheduleRosterPerson,
371
+ ),
372
+ ]),
373
+ ),
374
+ fromMs: window.from.getTime(),
375
+ toMs: window.to.getTime(),
376
+ });
377
+ }
378
+ return { seats, unfilled };
379
+ }
380
+
381
+ /*
382
+ * Give a seat to its winner on the simulated timeline, then evaluate the
383
+ * winner again for every remaining seat whose candidate window the seat
384
+ * touches (outside it, their eligibility and score cannot change).
385
+ */
386
+ function assignRosterSeat(args: {
387
+ input: ScheduleRosterInput;
388
+ shift: CoverageShiftInput;
389
+ person: ScheduleRosterPerson;
390
+ remaining: ScheduleRosterSeat[];
391
+ }): void {
392
+ const { input, shift, person } = args;
393
+ const resourceId = person.resource.id;
394
+ person.timeline = [
395
+ ...person.timeline,
396
+ { ...shift, assigneeResourceId: resourceId },
397
+ ];
398
+ const startMs = toScheduleTimeMs(shift.startAt);
399
+ const endMs = toScheduleTimeMs(shift.endAt);
400
+ for (const entry of args.remaining)
401
+ if (
402
+ entry.results.has(resourceId) &&
403
+ startMs < entry.toMs &&
404
+ endMs > entry.fromMs
405
+ )
406
+ entry.results.set(
407
+ resourceId,
408
+ evaluateRosterCandidate(input, entry.shift, person),
409
+ );
410
+ }
411
+
412
+ /*
413
+ * Order unfilled seats by their start, then id.
414
+ */
415
+ function sortRosterUnfilled(
416
+ unfilled: ScheduleRosterUnfilledObj[],
417
+ shifts: CoverageShiftInput[],
418
+ ): ScheduleRosterUnfilledObj[] {
419
+ const byId = new Map(shifts.map((shift) => [shift.id, shift]));
420
+ return [...unfilled].sort((a, b) =>
421
+ compareRosterSeats(
422
+ byId.get(a.shiftId) as CoverageShiftInput,
423
+ byId.get(b.shiftId) as CoverageShiftInput,
424
+ ),
425
+ );
426
+ }
427
+
428
+ /*
429
+ * Propose who fills each open draft seat of a period, scarcest seat first
430
+ * (see the module comment). Proposals are in the order chosen; unfilled
431
+ * seats by start, then id.
432
+ */
433
+ export function proposeRoster(
434
+ input: ScheduleRosterInput,
435
+ ): ScheduleRosterResultObj {
436
+ const shifts = getRosterSeats(input);
437
+ const people = getRosterPeople(input, new Set(shifts.map((seat) => seat.id)));
438
+ const start = getRosterStartingSeats(input, shifts, people);
439
+ const proposals: ScheduleRosterResultObj['proposals'] = [];
440
+ const unfilled = start.unfilled;
441
+ let remaining = start.seats;
442
+ while (remaining.length) {
443
+ const seat = pickScarcestSeat(remaining);
444
+ remaining = remaining.filter((entry) => entry !== seat);
445
+ const cleanIds = getCleanCandidateIds(seat);
446
+ const winner = cleanIds.length
447
+ ? getRosterRanks(input, seat.shift, cleanIds, people).find(
448
+ (rank) => rank.rank === 1,
449
+ )
450
+ : undefined;
451
+ if (!winner) {
452
+ unfilled.push(getRosterUnfilled(seat));
453
+ continue;
454
+ }
455
+ proposals.push({
456
+ shiftId: seat.shift.id,
457
+ resourceId: winner.resourceId,
458
+ rank: winner,
459
+ candidateCount: cleanIds.length,
460
+ });
461
+ assignRosterSeat({
462
+ input,
463
+ shift: seat.shift,
464
+ person: people.get(winner.resourceId) as ScheduleRosterPerson,
465
+ remaining,
466
+ });
467
+ }
468
+ return { proposals, unfilled: sortRosterUnfilled(unfilled, shifts) };
469
+ }