assignment-user-matcher 1.9.0 → 1.11.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +164 -10
- package/dist/index.d.ts +2 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +19 -1
- package/dist/learning/auto-weights.d.ts +7 -4
- package/dist/learning/auto-weights.d.ts.map +1 -1
- package/dist/learning/auto-weights.js +7 -6
- package/dist/lua/workflow-transition.lua +8 -2
- package/dist/managers/LearningManager.d.ts.map +1 -1
- package/dist/managers/LearningManager.js +47 -0
- package/dist/managers/WorkflowManager.d.ts +7 -1
- package/dist/managers/WorkflowManager.d.ts.map +1 -1
- package/dist/managers/WorkflowManager.js +85 -12
- package/dist/matcher.class.d.ts +35 -3
- package/dist/matcher.class.d.ts.map +1 -1
- package/dist/matcher.class.js +319 -76
- package/dist/queries/users.d.ts +34 -0
- package/dist/queries/users.d.ts.map +1 -0
- package/dist/queries/users.js +227 -0
- package/dist/scheduling/constraints/availability.d.ts +43 -0
- package/dist/scheduling/constraints/availability.d.ts.map +1 -0
- package/dist/scheduling/constraints/availability.js +165 -0
- package/dist/scheduling/constraints/consecutive.d.ts +25 -0
- package/dist/scheduling/constraints/consecutive.d.ts.map +1 -0
- package/dist/scheduling/constraints/consecutive.js +215 -0
- package/dist/scheduling/constraints/constraint.d.ts +35 -0
- package/dist/scheduling/constraints/constraint.d.ts.map +1 -0
- package/dist/scheduling/constraints/constraint.js +97 -0
- package/dist/scheduling/constraints/contract.d.ts +21 -0
- package/dist/scheduling/constraints/contract.d.ts.map +1 -0
- package/dist/scheduling/constraints/contract.js +120 -0
- package/dist/scheduling/constraints/cost.d.ts +18 -0
- package/dist/scheduling/constraints/cost.d.ts.map +1 -0
- package/dist/scheduling/constraints/cost.js +65 -0
- package/dist/scheduling/constraints/daily-rest.d.ts +22 -0
- package/dist/scheduling/constraints/daily-rest.d.ts.map +1 -0
- package/dist/scheduling/constraints/daily-rest.js +123 -0
- package/dist/scheduling/constraints/duty-quota.d.ts +20 -0
- package/dist/scheduling/constraints/duty-quota.d.ts.map +1 -0
- package/dist/scheduling/constraints/duty-quota.js +95 -0
- package/dist/scheduling/constraints/engagement-floor.d.ts +28 -0
- package/dist/scheduling/constraints/engagement-floor.d.ts.map +1 -0
- package/dist/scheduling/constraints/engagement-floor.js +79 -0
- package/dist/scheduling/constraints/fairness.d.ts +34 -0
- package/dist/scheduling/constraints/fairness.d.ts.map +1 -0
- package/dist/scheduling/constraints/fairness.js +149 -0
- package/dist/scheduling/constraints/group-composition.d.ts +19 -0
- package/dist/scheduling/constraints/group-composition.d.ts.map +1 -0
- package/dist/scheduling/constraints/group-composition.js +92 -0
- package/dist/scheduling/constraints/hour-budget.d.ts +13 -0
- package/dist/scheduling/constraints/hour-budget.d.ts.map +1 -0
- package/dist/scheduling/constraints/hour-budget.js +65 -0
- package/dist/scheduling/constraints/in-shift-breaks.d.ts +24 -0
- package/dist/scheduling/constraints/in-shift-breaks.d.ts.map +1 -0
- package/dist/scheduling/constraints/in-shift-breaks.js +99 -0
- package/dist/scheduling/constraints/intervals.d.ts +5 -0
- package/dist/scheduling/constraints/intervals.d.ts.map +1 -0
- package/dist/scheduling/constraints/intervals.js +17 -0
- package/dist/scheduling/constraints/max-shift-duration.d.ts +7 -0
- package/dist/scheduling/constraints/max-shift-duration.d.ts.map +1 -0
- package/dist/scheduling/constraints/max-shift-duration.js +38 -0
- package/dist/scheduling/constraints/min-rest.d.ts +22 -0
- package/dist/scheduling/constraints/min-rest.d.ts.map +1 -0
- package/dist/scheduling/constraints/min-rest.js +49 -0
- package/dist/scheduling/constraints/min-staffing.d.ts +14 -0
- package/dist/scheduling/constraints/min-staffing.d.ts.map +1 -0
- package/dist/scheduling/constraints/min-staffing.js +59 -0
- package/dist/scheduling/constraints/night-work.d.ts +24 -0
- package/dist/scheduling/constraints/night-work.d.ts.map +1 -0
- package/dist/scheduling/constraints/night-work.js +179 -0
- package/dist/scheduling/constraints/no-overlap.d.ts +11 -0
- package/dist/scheduling/constraints/no-overlap.d.ts.map +1 -0
- package/dist/scheduling/constraints/no-overlap.js +35 -0
- package/dist/scheduling/constraints/notice.d.ts +44 -0
- package/dist/scheduling/constraints/notice.d.ts.map +1 -0
- package/dist/scheduling/constraints/notice.js +140 -0
- package/dist/scheduling/constraints/one-shift-per-day.d.ts +7 -0
- package/dist/scheduling/constraints/one-shift-per-day.d.ts.map +1 -0
- package/dist/scheduling/constraints/one-shift-per-day.js +35 -0
- package/dist/scheduling/constraints/overtime.d.ts +47 -0
- package/dist/scheduling/constraints/overtime.d.ts.map +1 -0
- package/dist/scheduling/constraints/overtime.js +149 -0
- package/dist/scheduling/constraints/protections.d.ts +21 -0
- package/dist/scheduling/constraints/protections.d.ts.map +1 -0
- package/dist/scheduling/constraints/protections.js +93 -0
- package/dist/scheduling/constraints/qualification.d.ts +18 -0
- package/dist/scheduling/constraints/qualification.d.ts.map +1 -0
- package/dist/scheduling/constraints/qualification.js +78 -0
- package/dist/scheduling/constraints/rest-days.d.ts +30 -0
- package/dist/scheduling/constraints/rest-days.d.ts.map +1 -0
- package/dist/scheduling/constraints/rest-days.js +133 -0
- package/dist/scheduling/constraints/rolling-hours.d.ts +24 -0
- package/dist/scheduling/constraints/rolling-hours.d.ts.map +1 -0
- package/dist/scheduling/constraints/rolling-hours.js +147 -0
- package/dist/scheduling/constraints/start-interval.d.ts +20 -0
- package/dist/scheduling/constraints/start-interval.d.ts.map +1 -0
- package/dist/scheduling/constraints/start-interval.js +53 -0
- package/dist/scheduling/constraints/support.d.ts +48 -0
- package/dist/scheduling/constraints/support.d.ts.map +1 -0
- package/dist/scheduling/constraints/support.js +97 -0
- package/dist/scheduling/constraints/time-off.d.ts +7 -0
- package/dist/scheduling/constraints/time-off.d.ts.map +1 -0
- package/dist/scheduling/constraints/time-off.js +42 -0
- package/dist/scheduling/constraints/weekly-rest.d.ts +22 -0
- package/dist/scheduling/constraints/weekly-rest.d.ts.map +1 -0
- package/dist/scheduling/constraints/weekly-rest.js +103 -0
- package/dist/scheduling/cost.d.ts +56 -0
- package/dist/scheduling/cost.d.ts.map +1 -0
- package/dist/scheduling/cost.js +120 -0
- package/dist/scheduling/engine/construction.d.ts +22 -0
- package/dist/scheduling/engine/construction.d.ts.map +1 -0
- package/dist/scheduling/engine/construction.js +104 -0
- package/dist/scheduling/engine/explain.d.ts +12 -0
- package/dist/scheduling/engine/explain.d.ts.map +1 -0
- package/dist/scheduling/engine/explain.js +24 -0
- package/dist/scheduling/engine/objective.d.ts +73 -0
- package/dist/scheduling/engine/objective.d.ts.map +1 -0
- package/dist/scheduling/engine/objective.js +164 -0
- package/dist/scheduling/engine/prng.d.ts +5 -0
- package/dist/scheduling/engine/prng.d.ts.map +1 -0
- package/dist/scheduling/engine/prng.js +24 -0
- package/dist/scheduling/engine/propagation.d.ts +19 -0
- package/dist/scheduling/engine/propagation.d.ts.map +1 -0
- package/dist/scheduling/engine/propagation.js +40 -0
- package/dist/scheduling/engine/search.d.ts +50 -0
- package/dist/scheduling/engine/search.d.ts.map +1 -0
- package/dist/scheduling/engine/search.js +127 -0
- package/dist/scheduling/engine/state.d.ts +28 -0
- package/dist/scheduling/engine/state.d.ts.map +1 -0
- package/dist/scheduling/engine/state.js +96 -0
- package/dist/scheduling/engine/timeline.d.ts +179 -0
- package/dist/scheduling/engine/timeline.d.ts.map +1 -0
- package/dist/scheduling/engine/timeline.js +416 -0
- package/dist/scheduling/engine/verdicts.d.ts +18 -0
- package/dist/scheduling/engine/verdicts.d.ts.map +1 -0
- package/dist/scheduling/engine/verdicts.js +74 -0
- package/dist/scheduling/index.d.ts +10 -0
- package/dist/scheduling/index.d.ts.map +1 -0
- package/dist/scheduling/index.js +29 -0
- package/dist/scheduling/model.d.ts +53 -0
- package/dist/scheduling/model.d.ts.map +1 -0
- package/dist/scheduling/model.js +380 -0
- package/dist/scheduling/operations.d.ts +134 -0
- package/dist/scheduling/operations.d.ts.map +1 -0
- package/dist/scheduling/operations.js +376 -0
- package/dist/scheduling/provenance.d.ts +33 -0
- package/dist/scheduling/provenance.d.ts.map +1 -0
- package/dist/scheduling/provenance.js +70 -0
- package/dist/scheduling/rules.d.ts +23 -0
- package/dist/scheduling/rules.d.ts.map +1 -0
- package/dist/scheduling/rules.js +37 -0
- package/dist/scheduling/scheduler.class.d.ts +24 -0
- package/dist/scheduling/scheduler.class.d.ts.map +1 -0
- package/dist/scheduling/scheduler.class.js +150 -0
- package/dist/scheduling/time.d.ts +138 -0
- package/dist/scheduling/time.d.ts.map +1 -0
- package/dist/scheduling/time.js +267 -0
- package/dist/scheduling/types.d.ts +938 -0
- package/dist/scheduling/types.d.ts.map +1 -0
- package/dist/scheduling/types.js +19 -0
- package/dist/types/matcher.d.ts +86 -2
- package/dist/types/matcher.d.ts.map +1 -1
- package/dist/utils/keys.d.ts +1 -0
- package/dist/utils/keys.d.ts.map +1 -1
- package/dist/utils/keys.js +6 -0
- package/package.json +4 -2
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* User status & workload query helpers: paginated user scans with
|
|
3
|
+
* status/backlog filters, batch summaries, and per-user accepted-work reads.
|
|
4
|
+
*
|
|
5
|
+
* All reads are bounded: the users hash is paged with HSCAN, per-page reads
|
|
6
|
+
* are batched into a single multi(), and JSON.parse is always guarded.
|
|
7
|
+
*/
|
|
8
|
+
import type { KeyBuilders } from '../utils/keys';
|
|
9
|
+
import type { RedisClientType, User, ActiveAssignmentInfo, UserQueryOptions, UserQueryResult, UserSummary } from '../matcher.class';
|
|
10
|
+
/**
|
|
11
|
+
* Effective backlog cap for one user. Injected by the facade because the pure
|
|
12
|
+
* module cannot see the matcher-wide default (`backlogLimitFor` is private).
|
|
13
|
+
*/
|
|
14
|
+
export type MaxBacklogSizeFor = (user: User) => number;
|
|
15
|
+
/**
|
|
16
|
+
* Paginated user scan with composable filters. The cursor is an opaque HSCAN
|
|
17
|
+
* cursor — pass `nextCursor` back verbatim. Because a scan page is never
|
|
18
|
+
* split mid-way, a returned page may exceed `limit` by less than one scan
|
|
19
|
+
* page, and filtered scans may return fewer than `limit` users while
|
|
20
|
+
* `hasMore` is still true; keep consuming until `hasMore` is false.
|
|
21
|
+
*/
|
|
22
|
+
export declare function getUsersPaginatedFromStore(redisClient: RedisClientType, keys: KeyBuilders, options: UserQueryOptions | undefined, maxBacklogSizeFor: MaxBacklogSizeFor): Promise<UserQueryResult>;
|
|
23
|
+
/**
|
|
24
|
+
* Order-preserving batch summary read. Missing users are omitted (mirrors
|
|
25
|
+
* getAssignmentsByIds). Chunked multi() keeps pipelines bounded.
|
|
26
|
+
*/
|
|
27
|
+
export declare function getUserSummariesBatch(redisClient: RedisClientType, keys: KeyBuilders, userIds: string[], maxBacklogSizeFor: MaxBacklogSizeFor): Promise<UserSummary[]>;
|
|
28
|
+
/**
|
|
29
|
+
* A user's accepted (in-progress) assignments, newest first. Verified against
|
|
30
|
+
* the accepted hash: members orphaned by a missed index removal are dropped
|
|
31
|
+
* from the result and self-healed with a zRem.
|
|
32
|
+
*/
|
|
33
|
+
export declare function getActiveAssignmentsFromStore(redisClient: RedisClientType, keys: KeyBuilders, userId: string): Promise<ActiveAssignmentInfo[]>;
|
|
34
|
+
//# sourceMappingURL=users.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"users.d.ts","sourceRoot":"","sources":["../../src/queries/users.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AACH,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AACjD,OAAO,KAAK,EACR,eAAe,EACf,IAAI,EACJ,oBAAoB,EACpB,gBAAgB,EAChB,eAAe,EACf,WAAW,EACd,MAAM,kBAAkB,CAAC;AAY1B;;;GAGG;AACH,MAAM,MAAM,iBAAiB,GAAG,CAAC,IAAI,EAAE,IAAI,KAAK,MAAM,CAAC;AAiBvD;;;;;;GAMG;AACH,wBAAsB,0BAA0B,CAC5C,WAAW,EAAE,eAAe,EAC5B,IAAI,EAAE,WAAW,EACjB,OAAO,EAAE,gBAAgB,GAAG,SAAS,EACrC,iBAAiB,EAAE,iBAAiB,GACrC,OAAO,CAAC,eAAe,CAAC,CAiI1B;AAED;;;GAGG;AACH,wBAAsB,qBAAqB,CACvC,WAAW,EAAE,eAAe,EAC5B,IAAI,EAAE,WAAW,EACjB,OAAO,EAAE,MAAM,EAAE,EACjB,iBAAiB,EAAE,iBAAiB,GACrC,OAAO,CAAC,WAAW,EAAE,CAAC,CAyCxB;AAED;;;;GAIG;AACH,wBAAsB,6BAA6B,CAC/C,WAAW,EAAE,eAAe,EAC5B,IAAI,EAAE,WAAW,EACjB,MAAM,EAAE,MAAM,GACf,OAAO,CAAC,oBAAoB,EAAE,CAAC,CAuBjC"}
|
|
@@ -0,0 +1,227 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.getActiveAssignmentsFromStore = exports.getUserSummariesBatch = exports.getUsersPaginatedFromStore = void 0;
|
|
4
|
+
/** HSCAN page hint, matching the matcher-wide convention. */
|
|
5
|
+
const USER_SCAN_COUNT = 500;
|
|
6
|
+
/** Hard ceiling for a single user-query page. */
|
|
7
|
+
const MAX_USER_QUERY_LIMIT = 1000;
|
|
8
|
+
const DEFAULT_USER_QUERY_LIMIT = 100;
|
|
9
|
+
/** Chunk size for batched multi() reads. */
|
|
10
|
+
const MULTI_CHUNK_SIZE = 500;
|
|
11
|
+
/** Backlog set members are stored as `assignment:{id}`. */
|
|
12
|
+
const BACKLOG_MEMBER_PREFIX = 'assignment:';
|
|
13
|
+
function clampLimit(limit) {
|
|
14
|
+
if (typeof limit !== 'number' || !Number.isFinite(limit))
|
|
15
|
+
return DEFAULT_USER_QUERY_LIMIT;
|
|
16
|
+
return Math.max(1, Math.min(Math.floor(limit), MAX_USER_QUERY_LIMIT));
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* Paginated user scan with composable filters. The cursor is an opaque HSCAN
|
|
20
|
+
* cursor — pass `nextCursor` back verbatim. Because a scan page is never
|
|
21
|
+
* split mid-way, a returned page may exceed `limit` by less than one scan
|
|
22
|
+
* page, and filtered scans may return fewer than `limit` users while
|
|
23
|
+
* `hasMore` is still true; keep consuming until `hasMore` is false.
|
|
24
|
+
*/
|
|
25
|
+
async function getUsersPaginatedFromStore(redisClient, keys, options, maxBacklogSizeFor) {
|
|
26
|
+
const limit = clampLimit(options?.limit);
|
|
27
|
+
const status = options?.status ?? 'all';
|
|
28
|
+
const hasBacklog = options?.hasBacklog ?? false;
|
|
29
|
+
const atCapacity = options?.atCapacity ?? false;
|
|
30
|
+
const includeAssignments = options?.includeAssignments ?? false;
|
|
31
|
+
// Idle predicate: needs a threshold. 'idle' status without one matches
|
|
32
|
+
// nobody (the facade substitutes idleUserTimeoutMs when configured).
|
|
33
|
+
const idleForMs = options?.idleForMs;
|
|
34
|
+
const idleCutoff = typeof idleForMs === 'number' && Number.isFinite(idleForMs) ? Date.now() - idleForMs : null;
|
|
35
|
+
const idleFilterActive = idleCutoff !== null;
|
|
36
|
+
const idleRequired = status === 'idle';
|
|
37
|
+
// The paused pool is small by design: one read per call, not per user.
|
|
38
|
+
const pausedMembers = new Set(await redisClient.sMembers(keys.pausedUsers()));
|
|
39
|
+
const matches = [];
|
|
40
|
+
let cursor = options?.cursor ?? '0';
|
|
41
|
+
do {
|
|
42
|
+
const { cursor: nextCursor, entries } = await redisClient.hScan(keys.users(), cursor, {
|
|
43
|
+
// Adapt the hint to what's still needed, floored at 100 (don't
|
|
44
|
+
// dribble) and capped at the scan-page convention.
|
|
45
|
+
COUNT: Math.max(Math.min(limit - matches.length, USER_SCAN_COUNT), 100),
|
|
46
|
+
});
|
|
47
|
+
cursor = nextCursor;
|
|
48
|
+
// Cheap pre-filter on fields already in hand (status), so the
|
|
49
|
+
// pipelined reads below only run for survivors.
|
|
50
|
+
const page = [];
|
|
51
|
+
for (const entry of entries) {
|
|
52
|
+
let user;
|
|
53
|
+
try {
|
|
54
|
+
user = JSON.parse(entry.value);
|
|
55
|
+
}
|
|
56
|
+
catch {
|
|
57
|
+
// Skip corrupt entries (same precedent as getAllAssignmentsFromStores)
|
|
58
|
+
continue;
|
|
59
|
+
}
|
|
60
|
+
const paused = pausedMembers.has(user.id);
|
|
61
|
+
if (status === 'paused' && !paused)
|
|
62
|
+
continue;
|
|
63
|
+
if (status === 'active' && paused)
|
|
64
|
+
continue;
|
|
65
|
+
page.push({ user, paused });
|
|
66
|
+
}
|
|
67
|
+
if (page.length > 0) {
|
|
68
|
+
// One multi() per page: backlog depth, activity score, accepted count.
|
|
69
|
+
const multi = redisClient.multi();
|
|
70
|
+
for (const { user } of page) {
|
|
71
|
+
multi.sCard(keys.userAssignments(user.id));
|
|
72
|
+
multi.zScore(keys.userActivity(), user.id);
|
|
73
|
+
multi.zCard(keys.userAcceptedAssignments(user.id));
|
|
74
|
+
}
|
|
75
|
+
const results = (await multi.exec());
|
|
76
|
+
for (let i = 0; i < page.length; i++) {
|
|
77
|
+
const { user, paused } = page[i];
|
|
78
|
+
const backlog = Number(results[i * 3] ?? 0);
|
|
79
|
+
const activityScore = results[i * 3 + 1];
|
|
80
|
+
const lastActiveAt = activityScore === null || activityScore === undefined ? null : Number(activityScore);
|
|
81
|
+
const acceptedCount = Number(results[i * 3 + 2] ?? 0);
|
|
82
|
+
const maxBacklogSize = maxBacklogSizeFor(user);
|
|
83
|
+
const entry = {
|
|
84
|
+
user,
|
|
85
|
+
paused,
|
|
86
|
+
backlog,
|
|
87
|
+
lastActiveAt,
|
|
88
|
+
acceptedCount,
|
|
89
|
+
maxBacklogSize,
|
|
90
|
+
atCapacity: backlog >= maxBacklogSize,
|
|
91
|
+
};
|
|
92
|
+
// Users with no recorded activity are not idle: idleness needs
|
|
93
|
+
// a reference point (addUser touches on creation, so null only
|
|
94
|
+
// appears for externally-written records).
|
|
95
|
+
const idle = entry.lastActiveAt !== null && idleCutoff !== null && entry.lastActiveAt <= idleCutoff;
|
|
96
|
+
if ((idleRequired || idleFilterActive) && !idle)
|
|
97
|
+
continue;
|
|
98
|
+
if (hasBacklog && entry.backlog === 0)
|
|
99
|
+
continue;
|
|
100
|
+
if (atCapacity && !entry.atCapacity)
|
|
101
|
+
continue;
|
|
102
|
+
matches.push(entry);
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
// A scan page is never split: stop only at a page boundary.
|
|
106
|
+
} while (matches.length < limit && cursor !== '0');
|
|
107
|
+
const hasMore = cursor !== '0';
|
|
108
|
+
const users = matches.map((entry) => ({
|
|
109
|
+
userId: entry.user.id,
|
|
110
|
+
user: entry.user,
|
|
111
|
+
paused: entry.paused,
|
|
112
|
+
lastActiveAt: entry.lastActiveAt,
|
|
113
|
+
backlog: entry.backlog,
|
|
114
|
+
acceptedCount: entry.acceptedCount,
|
|
115
|
+
maxBacklogSize: entry.maxBacklogSize,
|
|
116
|
+
atCapacity: entry.atCapacity,
|
|
117
|
+
}));
|
|
118
|
+
if (includeAssignments && matches.length > 0) {
|
|
119
|
+
// Per-user assignment ids for the returned page only, chunked.
|
|
120
|
+
for (let start = 0; start < matches.length; start += MULTI_CHUNK_SIZE) {
|
|
121
|
+
const chunk = matches.slice(start, start + MULTI_CHUNK_SIZE);
|
|
122
|
+
const multi = redisClient.multi();
|
|
123
|
+
for (const { user } of chunk) {
|
|
124
|
+
multi.sMembers(keys.userAssignments(user.id));
|
|
125
|
+
multi.zRange(keys.userAcceptedAssignments(user.id), 0, -1, { REV: true });
|
|
126
|
+
}
|
|
127
|
+
const results = (await multi.exec());
|
|
128
|
+
for (let i = 0; i < chunk.length; i++) {
|
|
129
|
+
const summary = users[start + i];
|
|
130
|
+
// Backlog members are `assignment:{id}`; accepted ids are raw.
|
|
131
|
+
// Accepted ids are NOT verified against the accepted hash here
|
|
132
|
+
// (a stale member may appear); getActiveAssignmentsForUser is
|
|
133
|
+
// the verified read.
|
|
134
|
+
summary.pendingAssignmentIds = (results[i * 2] ?? []).map((m) => m.slice(BACKLOG_MEMBER_PREFIX.length));
|
|
135
|
+
summary.acceptedAssignmentIds = results[i * 2 + 1] ?? [];
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
const result = {
|
|
140
|
+
users,
|
|
141
|
+
nextCursor: hasMore ? cursor : null,
|
|
142
|
+
hasMore,
|
|
143
|
+
};
|
|
144
|
+
if (options?.includeTotal) {
|
|
145
|
+
result.total = await redisClient.hLen(keys.users());
|
|
146
|
+
}
|
|
147
|
+
return result;
|
|
148
|
+
}
|
|
149
|
+
exports.getUsersPaginatedFromStore = getUsersPaginatedFromStore;
|
|
150
|
+
/**
|
|
151
|
+
* Order-preserving batch summary read. Missing users are omitted (mirrors
|
|
152
|
+
* getAssignmentsByIds). Chunked multi() keeps pipelines bounded.
|
|
153
|
+
*/
|
|
154
|
+
async function getUserSummariesBatch(redisClient, keys, userIds, maxBacklogSizeFor) {
|
|
155
|
+
if (userIds.length === 0)
|
|
156
|
+
return [];
|
|
157
|
+
const summaries = [];
|
|
158
|
+
for (let start = 0; start < userIds.length; start += MULTI_CHUNK_SIZE) {
|
|
159
|
+
const chunk = userIds.slice(start, start + MULTI_CHUNK_SIZE);
|
|
160
|
+
const multi = redisClient.multi();
|
|
161
|
+
for (const userId of chunk) {
|
|
162
|
+
multi.hGet(keys.users(), userId);
|
|
163
|
+
multi.sIsMember(keys.pausedUsers(), userId);
|
|
164
|
+
multi.sCard(keys.userAssignments(userId));
|
|
165
|
+
multi.zCard(keys.userAcceptedAssignments(userId));
|
|
166
|
+
multi.zScore(keys.userActivity(), userId);
|
|
167
|
+
}
|
|
168
|
+
const results = (await multi.exec());
|
|
169
|
+
for (let i = 0; i < chunk.length; i++) {
|
|
170
|
+
const json = results[i * 5];
|
|
171
|
+
if (typeof json !== 'string')
|
|
172
|
+
continue; // missing user: omitted
|
|
173
|
+
let user;
|
|
174
|
+
try {
|
|
175
|
+
user = JSON.parse(json);
|
|
176
|
+
}
|
|
177
|
+
catch {
|
|
178
|
+
continue; // corrupt entry: omitted
|
|
179
|
+
}
|
|
180
|
+
const activityScore = results[i * 5 + 4];
|
|
181
|
+
const backlog = Number(results[i * 5 + 2] ?? 0);
|
|
182
|
+
const maxBacklogSize = maxBacklogSizeFor(user);
|
|
183
|
+
summaries.push({
|
|
184
|
+
userId: user.id,
|
|
185
|
+
user,
|
|
186
|
+
paused: Boolean(results[i * 5 + 1]),
|
|
187
|
+
lastActiveAt: activityScore === null || activityScore === undefined ? null : Number(activityScore),
|
|
188
|
+
backlog,
|
|
189
|
+
acceptedCount: Number(results[i * 5 + 3] ?? 0),
|
|
190
|
+
maxBacklogSize,
|
|
191
|
+
atCapacity: backlog >= maxBacklogSize,
|
|
192
|
+
});
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
return summaries;
|
|
196
|
+
}
|
|
197
|
+
exports.getUserSummariesBatch = getUserSummariesBatch;
|
|
198
|
+
/**
|
|
199
|
+
* A user's accepted (in-progress) assignments, newest first. Verified against
|
|
200
|
+
* the accepted hash: members orphaned by a missed index removal are dropped
|
|
201
|
+
* from the result and self-healed with a zRem.
|
|
202
|
+
*/
|
|
203
|
+
async function getActiveAssignmentsFromStore(redisClient, keys, userId) {
|
|
204
|
+
const entries = await redisClient.zRangeWithScores(keys.userAcceptedAssignments(userId), 0, -1, { REV: true });
|
|
205
|
+
if (entries.length === 0)
|
|
206
|
+
return [];
|
|
207
|
+
const multi = redisClient.multi();
|
|
208
|
+
for (const entry of entries) {
|
|
209
|
+
multi.hGet(keys.acceptedAssignments(), entry.value);
|
|
210
|
+
}
|
|
211
|
+
const jsons = (await multi.exec());
|
|
212
|
+
const active = [];
|
|
213
|
+
const stale = [];
|
|
214
|
+
for (let i = 0; i < entries.length; i++) {
|
|
215
|
+
if (jsons[i]) {
|
|
216
|
+
active.push({ assignmentId: entries[i].value, acceptedAt: Number(entries[i].score) });
|
|
217
|
+
}
|
|
218
|
+
else {
|
|
219
|
+
stale.push(entries[i].value);
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
if (stale.length > 0) {
|
|
223
|
+
await redisClient.zRem(keys.userAcceptedAssignments(userId), stale);
|
|
224
|
+
}
|
|
225
|
+
return active;
|
|
226
|
+
}
|
|
227
|
+
exports.getActiveAssignmentsFromStore = getActiveAssignmentsFromStore;
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Availability and preferences.
|
|
3
|
+
*
|
|
4
|
+
* Four kinds, deliberately distinct rather than a single boolean:
|
|
5
|
+
*
|
|
6
|
+
* - `unavailable` — a hard blackout, like time off.
|
|
7
|
+
* - `available` — an allow-list. Once a person declares *any* availability
|
|
8
|
+
* window, anything outside every window is ineligible. This is the
|
|
9
|
+
* part-time and student pattern, and it inverts the default.
|
|
10
|
+
* - `preferred` / `avoid` — soft, weighted. A preference model that only has
|
|
11
|
+
* "can't work" cannot express "would rather not", so every unwanted shift
|
|
12
|
+
* becomes a refusal and the roster loses the flexibility it needs.
|
|
13
|
+
*
|
|
14
|
+
* The soft half matters for more than morale: pro-rata fairness in shift quality
|
|
15
|
+
* is a live discrimination question under the part-time and fixed-term
|
|
16
|
+
* directives, and it can only be traded off if it is scored rather than binary.
|
|
17
|
+
*/
|
|
18
|
+
import type { AvailabilityRule, SchedulingConstraint, SearchState, ShiftInstance } from '../types';
|
|
19
|
+
export declare function availability(): SchedulingConstraint;
|
|
20
|
+
declare function overlapsRule(clock: {
|
|
21
|
+
minutesInClockRange: (r: {
|
|
22
|
+
start: number;
|
|
23
|
+
end: number;
|
|
24
|
+
}, c: {
|
|
25
|
+
from: string;
|
|
26
|
+
to: string;
|
|
27
|
+
}) => number;
|
|
28
|
+
}, range: {
|
|
29
|
+
start: number;
|
|
30
|
+
end: number;
|
|
31
|
+
}, rule: AvailabilityRule): number;
|
|
32
|
+
/**
|
|
33
|
+
* Weighted preference term over the whole roster, for the soft objective:
|
|
34
|
+
* every assigned pair contributes its `avoid` weights and is credited its
|
|
35
|
+
* `preferred` weights. This is what makes `preferred`/`avoid` *scored* rather
|
|
36
|
+
* than advisory — without it, the solver would treat a roster of avoided
|
|
37
|
+
* shifts and a roster of preferred ones as equal.
|
|
38
|
+
*/
|
|
39
|
+
export declare function preferencePenalty(state: SearchState): number;
|
|
40
|
+
/** Soft preference score for a pair: negative is better. Used by candidate ranking. */
|
|
41
|
+
export declare function preferenceScore(clock: Parameters<typeof overlapsRule>[0], rules: AvailabilityRule[] | undefined, inst: ShiftInstance): number;
|
|
42
|
+
export {};
|
|
43
|
+
//# sourceMappingURL=availability.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"availability.d.ts","sourceRoot":"","sources":["../../../src/scheduling/constraints/availability.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;GAgBG;AAEH,OAAO,KAAK,EAAE,gBAAgB,EAAe,oBAAoB,EAAE,WAAW,EAAE,aAAa,EAAE,MAAM,UAAU,CAAC;AAIhH,wBAAgB,YAAY,IAAI,oBAAoB,CAqFnD;AAkCD,iBAAS,YAAY,CACjB,KAAK,EAAE;IAAE,mBAAmB,EAAE,CAAC,CAAC,EAAE;QAAE,KAAK,EAAE,MAAM,CAAC;QAAC,GAAG,EAAE,MAAM,CAAA;KAAE,EAAE,CAAC,EAAE;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,EAAE,EAAE,MAAM,CAAA;KAAE,KAAK,MAAM,CAAA;CAAE,EAC9G,KAAK,EAAE;IAAE,KAAK,EAAE,MAAM,CAAC;IAAC,GAAG,EAAE,MAAM,CAAA;CAAE,EACrC,IAAI,EAAE,gBAAgB,GACvB,MAAM,CAGR;AAED;;;;;;GAMG;AACH,wBAAgB,iBAAiB,CAAC,KAAK,EAAE,WAAW,GAAG,MAAM,CAW5D;AAED,uFAAuF;AACvF,wBAAgB,eAAe,CAC3B,KAAK,EAAE,UAAU,CAAC,OAAO,YAAY,CAAC,CAAC,CAAC,CAAC,EACzC,KAAK,EAAE,gBAAgB,EAAE,GAAG,SAAS,EACrC,IAAI,EAAE,aAAa,GACpB,MAAM,CAWR"}
|
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* Availability and preferences.
|
|
4
|
+
*
|
|
5
|
+
* Four kinds, deliberately distinct rather than a single boolean:
|
|
6
|
+
*
|
|
7
|
+
* - `unavailable` — a hard blackout, like time off.
|
|
8
|
+
* - `available` — an allow-list. Once a person declares *any* availability
|
|
9
|
+
* window, anything outside every window is ineligible. This is the
|
|
10
|
+
* part-time and student pattern, and it inverts the default.
|
|
11
|
+
* - `preferred` / `avoid` — soft, weighted. A preference model that only has
|
|
12
|
+
* "can't work" cannot express "would rather not", so every unwanted shift
|
|
13
|
+
* becomes a refusal and the roster loses the flexibility it needs.
|
|
14
|
+
*
|
|
15
|
+
* The soft half matters for more than morale: pro-rata fairness in shift quality
|
|
16
|
+
* is a live discrimination question under the part-time and fixed-term
|
|
17
|
+
* directives, and it can only be traded off if it is scored rather than binary.
|
|
18
|
+
*/
|
|
19
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
20
|
+
exports.preferenceScore = exports.preferencePenalty = exports.availability = void 0;
|
|
21
|
+
const model_1 = require("../model");
|
|
22
|
+
const support_1 = require("./support");
|
|
23
|
+
function availability() {
|
|
24
|
+
const constraint = (0, support_1.fromVerdict)({
|
|
25
|
+
id: 'availability',
|
|
26
|
+
hardness: 'hard',
|
|
27
|
+
weight: 1,
|
|
28
|
+
verdict(state, pair) {
|
|
29
|
+
const inst = (0, support_1.instanceOf)(state, pair);
|
|
30
|
+
const employee = state.ctx.employeeById.get(pair.employeeId);
|
|
31
|
+
if (!inst || !employee?.availability?.length)
|
|
32
|
+
return (0, support_1.pass)('availability', 'no availability rules');
|
|
33
|
+
const clock = state.ctx.clock;
|
|
34
|
+
const range = { start: inst.startMinute, end: inst.endMinute };
|
|
35
|
+
const span = range.end - range.start;
|
|
36
|
+
const matching = employee.availability.filter((rule) => (0, model_1.availabilityApplies)(rule, inst));
|
|
37
|
+
for (const rule of matching.filter((r) => r.kind === 'unavailable')) {
|
|
38
|
+
if (overlapsRule(clock, range, rule) > 0) {
|
|
39
|
+
return (0, support_1.fail)('availability', 'hard', `employee "${pair.employeeId}" is unavailable during "${inst.id}"`);
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
// Declaring any 'available' window inverts the default: everything
|
|
43
|
+
// outside every declared window is ineligible, including days no
|
|
44
|
+
// window mentions — a Monday-only declaration bars Tuesdays too.
|
|
45
|
+
// Coverage is the UNION of the declared windows: a shift spanning
|
|
46
|
+
// two contiguous windows lies inside the declaration.
|
|
47
|
+
const allowLists = employee.availability.filter((r) => r.kind === 'available');
|
|
48
|
+
if (allowLists.length > 0) {
|
|
49
|
+
const covered = unionCoveredMinutes(clock, range, matching.filter((r) => r.kind === 'available'));
|
|
50
|
+
if (covered < span) {
|
|
51
|
+
return (0, support_1.fail)('availability', 'hard', `"${inst.id}" falls outside employee "${pair.employeeId}"'s declared availability`, { actual: covered, required: span, unit: 'minutes' });
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
const avoided = matching.find((r) => r.kind === 'avoid' && overlapsRule(clock, range, r) > 0);
|
|
55
|
+
if (avoided) {
|
|
56
|
+
return (0, support_1.fail)('availability', 'soft', `employee "${pair.employeeId}" prefers to avoid "${inst.id}"`, {
|
|
57
|
+
actual: avoided.weight ?? 1,
|
|
58
|
+
});
|
|
59
|
+
}
|
|
60
|
+
const preferred = matching.find((r) => r.kind === 'preferred' && overlapsRule(clock, range, r) > 0);
|
|
61
|
+
return (0, support_1.pass)('availability', preferred ? `matches a preferred window` : 'no availability objection');
|
|
62
|
+
},
|
|
63
|
+
});
|
|
64
|
+
// A soft breach must not make the pair ineligible, and it must not leak
|
|
65
|
+
// into the hard score bucket (the SPI levels by constraint, not by
|
|
66
|
+
// verdict), so `delta` reports hard breaches only. The soft half is scored
|
|
67
|
+
// by `preferencePenalty`, which the objective adds at the soft level.
|
|
68
|
+
const innerDelta = constraint.delta;
|
|
69
|
+
constraint.delta = (state, pair) => {
|
|
70
|
+
const v = constraint.verdict(state, pair);
|
|
71
|
+
if (v.pass)
|
|
72
|
+
return 0;
|
|
73
|
+
return v.severity === 'hard' ? innerDelta(state, pair) : 0;
|
|
74
|
+
};
|
|
75
|
+
constraint.evaluate = (state) => {
|
|
76
|
+
const out = [];
|
|
77
|
+
for (const [instanceId, employees] of state.assignments) {
|
|
78
|
+
for (const employeeId of employees) {
|
|
79
|
+
const v = constraint.verdict(state, { employeeId, shiftInstanceId: instanceId });
|
|
80
|
+
if (v.pass || v.severity === 'hard')
|
|
81
|
+
continue;
|
|
82
|
+
out.push({
|
|
83
|
+
constraintId: 'availability',
|
|
84
|
+
severity: v.severity,
|
|
85
|
+
employeeId,
|
|
86
|
+
shiftInstanceId: instanceId,
|
|
87
|
+
message: v.message,
|
|
88
|
+
});
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
return out;
|
|
92
|
+
};
|
|
93
|
+
return constraint;
|
|
94
|
+
}
|
|
95
|
+
exports.availability = availability;
|
|
96
|
+
/**
|
|
97
|
+
* Minutes of `range` covered by the union of the given windows. A window with
|
|
98
|
+
* no `from`/`to` covers the whole range; timed windows are projected onto the
|
|
99
|
+
* range via the clock (same per-day band semantics as `overlapsRule`) and
|
|
100
|
+
* merged, so contiguous or overlapping declarations never undercount.
|
|
101
|
+
*/
|
|
102
|
+
function unionCoveredMinutes(clock, range, rules) {
|
|
103
|
+
const intervals = [];
|
|
104
|
+
for (const rule of rules) {
|
|
105
|
+
if (rule.from === undefined || rule.to === undefined)
|
|
106
|
+
return range.end - range.start;
|
|
107
|
+
intervals.push(...clock.clockRangeIntervals(range, { from: rule.from, to: rule.to }));
|
|
108
|
+
}
|
|
109
|
+
intervals.sort((a, b) => a.start - b.start);
|
|
110
|
+
let covered = 0;
|
|
111
|
+
let cursor = range.start;
|
|
112
|
+
for (const interval of intervals) {
|
|
113
|
+
if (interval.end <= cursor)
|
|
114
|
+
continue;
|
|
115
|
+
covered += interval.end - Math.max(interval.start, cursor);
|
|
116
|
+
cursor = interval.end;
|
|
117
|
+
}
|
|
118
|
+
return covered;
|
|
119
|
+
}
|
|
120
|
+
function overlapsRule(clock, range, rule) {
|
|
121
|
+
if (rule.from === undefined || rule.to === undefined)
|
|
122
|
+
return range.end - range.start;
|
|
123
|
+
return clock.minutesInClockRange(range, { from: rule.from, to: rule.to });
|
|
124
|
+
}
|
|
125
|
+
/**
|
|
126
|
+
* Weighted preference term over the whole roster, for the soft objective:
|
|
127
|
+
* every assigned pair contributes its `avoid` weights and is credited its
|
|
128
|
+
* `preferred` weights. This is what makes `preferred`/`avoid` *scored* rather
|
|
129
|
+
* than advisory — without it, the solver would treat a roster of avoided
|
|
130
|
+
* shifts and a roster of preferred ones as equal.
|
|
131
|
+
*/
|
|
132
|
+
function preferencePenalty(state) {
|
|
133
|
+
let penalty = 0;
|
|
134
|
+
for (const [instanceId, employees] of state.assignments) {
|
|
135
|
+
const inst = state.ctx.instanceById.get(instanceId);
|
|
136
|
+
if (!inst)
|
|
137
|
+
continue;
|
|
138
|
+
for (const employeeId of employees) {
|
|
139
|
+
const rules = state.ctx.employeeById.get(employeeId)?.availability;
|
|
140
|
+
if (rules?.length)
|
|
141
|
+
penalty += preferenceScore(state.ctx.clock, rules, inst);
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
return penalty;
|
|
145
|
+
}
|
|
146
|
+
exports.preferencePenalty = preferencePenalty;
|
|
147
|
+
/** Soft preference score for a pair: negative is better. Used by candidate ranking. */
|
|
148
|
+
function preferenceScore(clock, rules, inst) {
|
|
149
|
+
if (!rules?.length)
|
|
150
|
+
return 0;
|
|
151
|
+
const range = { start: inst.startMinute, end: inst.endMinute };
|
|
152
|
+
let score = 0;
|
|
153
|
+
for (const rule of rules) {
|
|
154
|
+
if (!(0, model_1.availabilityApplies)(rule, inst))
|
|
155
|
+
continue;
|
|
156
|
+
if (overlapsRule(clock, range, rule) <= 0)
|
|
157
|
+
continue;
|
|
158
|
+
if (rule.kind === 'preferred')
|
|
159
|
+
score -= rule.weight ?? 1;
|
|
160
|
+
if (rule.kind === 'avoid')
|
|
161
|
+
score += rule.weight ?? 1;
|
|
162
|
+
}
|
|
163
|
+
return score;
|
|
164
|
+
}
|
|
165
|
+
exports.preferenceScore = preferenceScore;
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Sequence rules — limits on runs rather than on totals.
|
|
3
|
+
*
|
|
4
|
+
* These are the rules a per-assignment check structurally cannot see, because
|
|
5
|
+
* the breach lives in the *pattern*, not in any one shift:
|
|
6
|
+
*
|
|
7
|
+
* - **Consecutive working days.** Portugal caps a shift worker at six.
|
|
8
|
+
* - **Consecutive night shifts, and the rest owed when the run ends.** Finland
|
|
9
|
+
* allows five and then requires 24h off; the Netherlands allows seven (eight
|
|
10
|
+
* by collective agreement) and then requires 46h. Only NL and FI legislate a
|
|
11
|
+
* cap at all — elsewhere it is collective-agreement territory, which is
|
|
12
|
+
* exactly why it has to be configuration rather than a built-in number.
|
|
13
|
+
* - **Forbidden successions.** The "quick return" — a late shift followed by
|
|
14
|
+
* an early one — is the single most-requested constraint in nurse rostering
|
|
15
|
+
* and is invisible to a rest rule whenever the gap technically clears the
|
|
16
|
+
* minimum.
|
|
17
|
+
*/
|
|
18
|
+
import type { ConsecutiveRule, SchedulingConstraint } from '../types';
|
|
19
|
+
export declare const CONSECUTIVE_CITATION = "National working-time law / collective agreement";
|
|
20
|
+
/** Every sequence constraint the rule configures. */
|
|
21
|
+
export declare function consecutiveConstraints(rule: ConsecutiveRule): SchedulingConstraint[];
|
|
22
|
+
export declare function consecutiveDays(maxDays: number): SchedulingConstraint;
|
|
23
|
+
export declare function consecutiveNights(rule: ConsecutiveRule): SchedulingConstraint;
|
|
24
|
+
export declare function shiftSuccession(forbidden: NonNullable<ConsecutiveRule['forbiddenSuccessions']>): SchedulingConstraint;
|
|
25
|
+
//# sourceMappingURL=consecutive.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"consecutive.d.ts","sourceRoot":"","sources":["../../../src/scheduling/constraints/consecutive.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;GAgBG;AAEH,OAAO,KAAK,EAAE,eAAe,EAAe,oBAAoB,EAA8B,MAAM,UAAU,CAAC;AAI/G,eAAO,MAAM,oBAAoB,qDAAqD,CAAC;AAEvF,qDAAqD;AACrD,wBAAgB,sBAAsB,CAAC,IAAI,EAAE,eAAe,GAAG,oBAAoB,EAAE,CAQpF;AAED,wBAAgB,eAAe,CAAC,OAAO,EAAE,MAAM,GAAG,oBAAoB,CAiCrE;AAED,wBAAgB,iBAAiB,CAAC,IAAI,EAAE,eAAe,GAAG,oBAAoB,CAqE7E;AAED,wBAAgB,eAAe,CAAC,SAAS,EAAE,WAAW,CAAC,eAAe,CAAC,sBAAsB,CAAC,CAAC,GAAG,oBAAoB,CA6DrH"}
|