assignment-user-matcher 1.0.11 → 1.0.14

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 CHANGED
@@ -400,6 +400,16 @@ Contributions are welcome! If you have ideas for improvements, new features, or
400
400
 
401
401
  Please open an issue first to discuss significant changes.
402
402
 
403
+ ## Packaging & Publishing
404
+
405
+ The npm package only ships the compiled artifacts in `dist/`. Before publishing:
406
+
407
+ 1. Install dependencies: `pnpm install`
408
+ 2. Build the library: `pnpm run build`
409
+ 3. (Optional) Inspect the publish payload: `pnpm pack --dry-run`
410
+
411
+ Consumers can `import AssignmentMatcher from 'assignment-user-matcher'` or `const { AssignmentMatcher } = require('assignment-user-matcher')` without running TypeScript themselves.
412
+
403
413
  ## License
404
414
 
405
415
  This library is licensed under the MIT License. (Assuming MIT - please update if incorrect)
@@ -0,0 +1,5 @@
1
+ import AssignmentMatcher from './matcher.class';
2
+ export type { Assignment, options, Stats, User } from './matcher.class';
3
+ export { AssignmentMatcher };
4
+ export default AssignmentMatcher;
5
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,iBAAiB,MAAM,iBAAiB,CAAC;AAEhD,YAAY,EAAE,UAAU,EAAE,OAAO,EAAE,KAAK,EAAE,IAAI,EAAE,MAAM,iBAAiB,CAAC;AAExE,OAAO,EAAE,iBAAiB,EAAE,CAAC;AAC7B,eAAe,iBAAiB,CAAC"}
package/dist/index.js ADDED
@@ -0,0 +1,9 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.AssignmentMatcher = void 0;
7
+ const matcher_class_1 = __importDefault(require("./matcher.class"));
8
+ exports.AssignmentMatcher = matcher_class_1.default;
9
+ exports.default = matcher_class_1.default;
@@ -0,0 +1,60 @@
1
+ import { createClient } from 'redis';
2
+ export type RedisClientType = ReturnType<typeof createClient>;
3
+ export interface User {
4
+ id: string;
5
+ tags: string[];
6
+ routingWeights?: Record<string, number>;
7
+ [key: string]: any;
8
+ }
9
+ export type Assignment = {
10
+ id: string;
11
+ tags: string[];
12
+ priority?: number;
13
+ [key: string]: any;
14
+ };
15
+ export type Stats = {
16
+ users?: number;
17
+ usersWithoutAssignment?: string[];
18
+ remainingAssignments?: number;
19
+ };
20
+ export type options = {
21
+ relevantBatchSize?: number;
22
+ redisPrefix?: string;
23
+ maxUserBacklogSize?: number;
24
+ enableDefaultMatching?: boolean;
25
+ prioritizationFunction?: (...args: (Assignment | undefined)[]) => Promise<number>;
26
+ matchingFunction?: (user: User, assignmentTags: string, assignmentPriority: number | string, assignmentId?: string) => Promise<[number, number]>;
27
+ };
28
+ export default class AssignmentMatcher {
29
+ redisClient: RedisClientType;
30
+ relevantBatchSize: number;
31
+ redisPrefix: string;
32
+ assignmentsKey: string;
33
+ assignmentsRefKey: string;
34
+ usersKey: string;
35
+ maxUserBacklogSize: number;
36
+ enableDefaultMatching: boolean;
37
+ constructor(redisClient: RedisClientType, options?: options);
38
+ private initRedis;
39
+ addUser(user: User): Promise<User>;
40
+ addAssignment(assignment: Assignment): Promise<Assignment>;
41
+ removeAssignment(id: string): Promise<string>;
42
+ removeUser(userId: string): Promise<string>;
43
+ getAllAssignments(): Promise<Assignment[]>;
44
+ private matchScore;
45
+ private calculatePriority;
46
+ get stats(): Promise<Stats>;
47
+ get usersWithoutAssignment(): Promise<string[]>;
48
+ setAssignmentPriority(id: string, priority: number): Promise<{
49
+ id: string;
50
+ priority: number;
51
+ }>;
52
+ setAssignmentPriorityByTags(tags: string[], priority: number): Promise<{
53
+ id: string;
54
+ priority: number;
55
+ }[]>;
56
+ private getUserRelatedAssignments;
57
+ matchUsersAssignments(userId?: string): Promise<void>;
58
+ getCurrentAssignmentsForUser(userId: string): Promise<string[]>;
59
+ }
60
+ //# sourceMappingURL=matcher.class.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"matcher.class.d.ts","sourceRoot":"","sources":["../src/matcher.class.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,OAAO,CAAC;AACrC,MAAM,MAAM,eAAe,GAAG,UAAU,CAAC,OAAO,YAAY,CAAC,CAAC;AAE9D,MAAM,WAAW,IAAI;IACjB,EAAE,EAAE,MAAM,CAAC;IACX,IAAI,EAAE,MAAM,EAAE,CAAC;IAGf,cAAc,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IACxC,CAAC,GAAG,EAAE,MAAM,GAAG,GAAG,CAAC;CACtB;AAED,MAAM,MAAM,UAAU,GAAG;IACrB,EAAE,EAAE,MAAM,CAAC;IACX,IAAI,EAAE,MAAM,EAAE,CAAC;IACf,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,CAAC,GAAG,EAAE,MAAM,GAAG,GAAG,CAAC;CACtB,CAAC;AAEF,MAAM,MAAM,KAAK,GAAG;IAChB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,sBAAsB,CAAC,EAAE,MAAM,EAAE,CAAC;IAClC,oBAAoB,CAAC,EAAE,MAAM,CAAC;CACjC,CAAC;AAEF,MAAM,MAAM,OAAO,GAAG;IAClB,iBAAiB,CAAC,EAAE,MAAM,CAAC;IAC3B,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,kBAAkB,CAAC,EAAE,MAAM,CAAC;IAC5B,qBAAqB,CAAC,EAAE,OAAO,CAAC;IAChC,sBAAsB,CAAC,EAAE,CAAC,GAAG,IAAI,EAAE,CAAC,UAAU,GAAG,SAAS,CAAC,EAAE,KAAK,OAAO,CAAC,MAAM,CAAC,CAAC;IAClF,gBAAgB,CAAC,EAAE,CACf,IAAI,EAAE,IAAI,EACV,cAAc,EAAE,MAAM,EACtB,kBAAkB,EAAE,MAAM,GAAG,MAAM,EACnC,YAAY,CAAC,EAAE,MAAM,KACpB,OAAO,CAAC,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,CAAC;CAClC,CAAC;AAEF,MAAM,CAAC,OAAO,OAAO,iBAAiB;IAUvB,WAAW,EAAE,eAAe;IATvC,iBAAiB,EAAE,MAAM,CAAC;IAC1B,WAAW,EAAE,MAAM,CAAC;IACpB,cAAc,EAAE,MAAM,CAAC;IACvB,iBAAiB,EAAE,MAAM,CAAC;IAC1B,QAAQ,EAAE,MAAM,CAAC;IACjB,kBAAkB,EAAE,MAAM,CAAC;IAC3B,qBAAqB,EAAE,OAAO,CAAC;gBAGpB,WAAW,EAAE,eAAe,EACnC,OAAO,CAAC,EAAE,OAAO;YAcP,SAAS;IAQjB,OAAO,CAAC,IAAI,EAAE,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC;IAalC,aAAa,CAAC,UAAU,EAAE,UAAU;IA0CpC,gBAAgB,CAAC,EAAE,EAAE,MAAM;IAyB3B,UAAU,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC;IAU3C,iBAAiB,IAAI,OAAO,CAAC,UAAU,EAAE,CAAC;YAKlC,UAAU;YAkCV,iBAAiB;IAK/B,IAAI,KAAK,IAAI,OAAO,CAAC,KAAK,CAAC,CAY1B;IAED,IAAI,sBAAsB,sBAWzB;IAEK,qBAAqB,CAAC,EAAE,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM;;;;IAyBlD,2BAA2B,CAAC,IAAI,EAAE,MAAM,EAAE,EAAE,QAAQ,EAAE,MAAM;;;;YA6BpD,yBAAyB;IAoHjC,qBAAqB,CAAC,MAAM,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAmDrD,4BAA4B,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,EAAE,CAAC;CAKxE"}
@@ -1,96 +1,41 @@
1
- import { createClient } from 'redis';
2
- export type RedisClientType = ReturnType<typeof createClient>;
3
-
4
- export interface User {
5
- id: string;
6
- tags: string[];
7
- // Optional routing weights per tag; if present, matching will use these weights.
8
- // Example: { english: 100, dutch: 30, brazil: 100, german: 0 }
9
- routingWeights?: Record<string, number>;
10
- [key: string]: any;
11
- }
12
-
13
- export type Assignment = {
14
- id: string;
15
- tags: string[];
16
- priority?: number;
17
- [key: string]: any;
18
- };
19
-
20
- export type Stats = {
21
- users?: number;
22
- usersWithoutAssignment?: string[];
23
- remainingAssignments?: number;
24
- };
25
-
26
- export type options = {
27
- relevantBatchSize?: number;
28
- redisPrefix?: string;
29
- maxUserBacklogSize?: number;
30
- enableDefaultMatching?: boolean;
31
- prioritizationFunction?: (...args: (Assignment | undefined)[]) => Promise<number>;
32
- matchingFunction?: (
33
- user: User,
34
- assignmentTags: string,
35
- assignmentPriority: number | string,
36
- assignmentId?: string,
37
- ) => Promise<[number, number]>;
38
- };
39
-
40
- export default class AssignmentMatcher {
41
- relevantBatchSize: number;
42
- redisPrefix: string;
43
- assignmentsKey: string;
44
- assignmentsRefKey: string;
45
- usersKey: string;
46
- maxUserBacklogSize: number;
47
- enableDefaultMatching: boolean;
48
-
49
- constructor(
50
- public redisClient: RedisClientType,
51
- options?: options,
52
- ) {
53
- this.relevantBatchSize = options?.relevantBatchSize ?? 50;
54
- this.enableDefaultMatching = options?.enableDefaultMatching ?? true;
55
- this.redisPrefix = options?.redisPrefix ?? '';
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ class AssignmentMatcher {
4
+ constructor(redisClient, options) {
5
+ var _a, _b, _c, _d, _e, _f;
6
+ this.redisClient = redisClient;
7
+ this.relevantBatchSize = (_a = options === null || options === void 0 ? void 0 : options.relevantBatchSize) !== null && _a !== void 0 ? _a : 50;
8
+ this.enableDefaultMatching = (_b = options === null || options === void 0 ? void 0 : options.enableDefaultMatching) !== null && _b !== void 0 ? _b : true;
9
+ this.redisPrefix = (_c = options === null || options === void 0 ? void 0 : options.redisPrefix) !== null && _c !== void 0 ? _c : '';
56
10
  this.usersKey = this.redisPrefix + 'users';
57
11
  this.assignmentsKey = this.redisPrefix + 'assignments';
58
12
  this.assignmentsRefKey = this.redisPrefix + 'assignments:ref';
59
- this.maxUserBacklogSize = options?.maxUserBacklogSize ?? 9;
60
- this.calculatePriority = options?.prioritizationFunction ?? this.calculatePriority;
61
- this.matchScore = options?.matchingFunction ?? this.matchScore;
13
+ this.maxUserBacklogSize = (_d = options === null || options === void 0 ? void 0 : options.maxUserBacklogSize) !== null && _d !== void 0 ? _d : 9;
14
+ this.calculatePriority = (_e = options === null || options === void 0 ? void 0 : options.prioritizationFunction) !== null && _e !== void 0 ? _e : this.calculatePriority;
15
+ this.matchScore = (_f = options === null || options === void 0 ? void 0 : options.matchingFunction) !== null && _f !== void 0 ? _f : this.matchScore;
62
16
  this.initRedis();
63
17
  }
64
-
65
- private async initRedis() {
18
+ async initRedis() {
66
19
  // Only attempt to connect if the client isn't already connected
67
20
  if (!this.redisClient.isOpen) {
68
21
  await this.redisClient.connect();
69
22
  }
70
23
  return this;
71
24
  }
72
-
73
- async addUser(user: User): Promise<User> {
74
- await this.redisClient.hSet(
75
- this.usersKey,
76
- user.id,
77
- JSON.stringify({
78
- ...user,
79
- tags: [...user.tags, ...(this.enableDefaultMatching ? ['default'] : [])],
80
- }),
81
- );
82
-
25
+ async addUser(user) {
26
+ await this.redisClient.hSet(this.usersKey, user.id, JSON.stringify({
27
+ ...user,
28
+ tags: [...user.tags, ...(this.enableDefaultMatching ? ['default'] : [])],
29
+ }));
83
30
  return user;
84
31
  }
85
-
86
- async addAssignment(assignment: Assignment) {
32
+ async addAssignment(assignment) {
87
33
  let { id, tags, priority, latitude, longitude } = assignment;
88
- if (!priority) priority = await this.calculatePriority(assignment);
89
-
34
+ if (!priority)
35
+ priority = await this.calculatePriority(assignment);
90
36
  const assignmentPriorityKey = this.redisPrefix + `assignment:${id}:priority`;
91
37
  const assignmentTagsKey = this.redisPrefix + `assignment:${id}:tags`;
92
38
  const assignmentGeoKey = this.redisPrefix + `assignments:geo`;
93
-
94
39
  const multi = this.redisClient
95
40
  .multi()
96
41
  .hSet(this.assignmentsRefKey, id, JSON.stringify(assignment))
@@ -98,10 +43,9 @@ export default class AssignmentMatcher {
98
43
  // Ensure 'default' tag is persisted consistently when enabled
99
44
  .hSet(assignmentTagsKey, 'tags', tags.join(',') + (this.enableDefaultMatching ? ',default' : ''))
100
45
  .zAdd(this.assignmentsKey, {
101
- score: priority,
102
- value: id,
103
- });
104
-
46
+ score: priority,
47
+ value: id,
48
+ });
105
49
  if (latitude && longitude) {
106
50
  multi.geoAdd(assignmentGeoKey, {
107
51
  longitude,
@@ -109,7 +53,6 @@ export default class AssignmentMatcher {
109
53
  member: id,
110
54
  });
111
55
  }
112
-
113
56
  // Also index assignment into per-tag sorted sets (by priority)
114
57
  // This enables efficient weighted matching via ZUNIONSTORE.
115
58
  const indexTags = [...tags, ...(this.enableDefaultMatching ? ['default'] : [])];
@@ -119,21 +62,15 @@ export default class AssignmentMatcher {
119
62
  value: id,
120
63
  });
121
64
  }
122
-
123
65
  await multi.exec();
124
-
125
66
  return assignment;
126
67
  }
127
-
128
- async removeAssignment(id: string) {
68
+ async removeAssignment(id) {
129
69
  const assignmentPriorityKey = this.redisPrefix + `assignment:${id}:priority`;
130
70
  const assignmentTagsKey = this.redisPrefix + `assignment:${id}:tags`;
131
-
132
71
  // Fetch tags to remove from per-tag indices
133
72
  const [tagsCsv] = await this.redisClient.multi().hGet(assignmentTagsKey, 'tags').exec();
134
-
135
- const tags = (typeof tagsCsv === 'string' && tagsCsv.length > 0 ? tagsCsv.split(',') : []) as string[];
136
-
73
+ const tags = (typeof tagsCsv === 'string' && tagsCsv.length > 0 ? tagsCsv.split(',') : []);
137
74
  const multi = this.redisClient.multi();
138
75
  // Remove from reference and per-assignment hashes
139
76
  multi.hDel(this.assignmentsRefKey, id);
@@ -145,32 +82,22 @@ export default class AssignmentMatcher {
145
82
  for (const tag of tags) {
146
83
  multi.zRem(this.redisPrefix + `tag:${tag}:assignments`, id.toString());
147
84
  }
148
-
149
85
  await multi.exec();
150
86
  return id;
151
87
  }
152
-
153
- async removeUser(userId: string): Promise<string> {
88
+ async removeUser(userId) {
154
89
  const multi = this.redisClient
155
90
  .multi()
156
91
  .del(this.redisPrefix + `user:${userId}:assignments`)
157
92
  .hDel(this.usersKey, userId);
158
93
  await multi.exec();
159
-
160
94
  return userId;
161
95
  }
162
-
163
- async getAllAssignments(): Promise<Assignment[]> {
96
+ async getAllAssignments() {
164
97
  const assignments = await this.redisClient.hGetAll(this.assignmentsRefKey);
165
98
  return Object.values(assignments).map((assignment) => JSON.parse(assignment));
166
99
  }
167
-
168
- private async matchScore(
169
- user: User,
170
- assignmentTags: string,
171
- assignmentPriority: string | number,
172
- assignmentId?: string,
173
- ): Promise<[number, number]> {
100
+ async matchScore(user, assignmentTags, assignmentPriority, assignmentId) {
174
101
  // If weighted skills are present, use them for scoring
175
102
  if (user.routingWeights && Object.keys(user.routingWeights).length > 0) {
176
103
  const aTags = assignmentTags ? assignmentTags.split(',') : [];
@@ -183,33 +110,30 @@ export default class AssignmentMatcher {
183
110
  let weightSum = 0;
184
111
  for (const t of aTags) {
185
112
  const w = user.routingWeights[t];
186
- if (typeof w === 'number' && w > 0) weightSum += w;
113
+ if (typeof w === 'number' && w > 0)
114
+ weightSum += w;
187
115
  }
188
116
  const base = Number(assignmentPriority) || 0;
189
117
  // score: total positive weight overlap; priority: base weighted slightly by weight
190
118
  return [weightSum, base + weightSum];
191
119
  }
192
-
193
120
  // Fallback to default tag-intersection scoring
194
121
  const userTagSet = new Set(user.tags);
195
122
  const assignmentTagSet = new Set((assignmentTags || '').split(',').filter(Boolean));
196
123
  const intersection = new Set([...userTagSet].filter((tag) => assignmentTagSet.has(tag)));
197
-
198
124
  const score = userTagSet.size > 0 ? intersection.size / userTagSet.size : 0;
199
125
  const base = Number(assignmentPriority) || 0;
200
126
  return [score || 0, base + (score || 0)];
201
127
  }
202
- private async calculatePriority(...args: (Assignment | undefined)[]) {
128
+ async calculatePriority(...args) {
203
129
  const [assignment] = args;
204
- return new Date().getTime() - assignment?.createdAt || 0;
130
+ return new Date().getTime() - (assignment === null || assignment === void 0 ? void 0 : assignment.createdAt) || 0;
205
131
  }
206
-
207
- get stats(): Promise<Stats> {
132
+ get stats() {
208
133
  return (async () => {
209
134
  const users = await this.redisClient.hGetAll(this.usersKey);
210
135
  const usersWithoutAssignment = await this.usersWithoutAssignment;
211
136
  const remainingAssignments = await this.redisClient.zCount(this.assignmentsKey, '-inf', '+inf');
212
-
213
137
  return {
214
138
  users: Object.keys(users).length,
215
139
  usersWithoutAssignment,
@@ -217,21 +141,20 @@ export default class AssignmentMatcher {
217
141
  };
218
142
  })();
219
143
  }
220
-
221
144
  get usersWithoutAssignment() {
222
145
  return (async () => {
223
146
  const users = await this.redisClient.hGetAll(this.usersKey);
224
- const usersWithoutAssignment: string[] = [];
147
+ const usersWithoutAssignment = [];
225
148
  for (const user of Object.values(users)) {
226
149
  const { id } = JSON.parse(user);
227
150
  const userAssignments = await this.getCurrentAssignmentsForUser(id);
228
- if (userAssignments.length === 0) usersWithoutAssignment.push(id);
151
+ if (userAssignments.length === 0)
152
+ usersWithoutAssignment.push(id);
229
153
  }
230
154
  return usersWithoutAssignment;
231
155
  })();
232
156
  }
233
-
234
- async setAssignmentPriority(id: string, priority: number) {
157
+ async setAssignmentPriority(id, priority) {
235
158
  const assignmentPriorityKey = this.redisPrefix + `assignment:${id}:priority`;
236
159
  // Fetch tags to update per-tag indices
237
160
  const assignmentTagsKey = this.redisPrefix + `assignment:${id}:tags`;
@@ -240,8 +163,7 @@ export default class AssignmentMatcher {
240
163
  .hExists(this.assignmentsRefKey, id)
241
164
  .hGet(assignmentTagsKey, 'tags')
242
165
  .exec();
243
- const tags = (typeof tagsCsv === 'string' && tagsCsv.length > 0 ? tagsCsv.split(',') : []) as string[];
244
-
166
+ const tags = (typeof tagsCsv === 'string' && tagsCsv.length > 0 ? tagsCsv.split(',') : []);
245
167
  const multi = this.redisClient.multi();
246
168
  multi.hSet(assignmentPriorityKey, 'priority', priority);
247
169
  if (existsRef) {
@@ -252,18 +174,15 @@ export default class AssignmentMatcher {
252
174
  }
253
175
  }
254
176
  await multi.exec();
255
-
256
177
  return { id, priority };
257
178
  }
258
-
259
- async setAssignmentPriorityByTags(tags: string[], priority: number) {
179
+ async setAssignmentPriorityByTags(tags, priority) {
260
180
  // Update priorities for all assignments that include any of the specified tags.
261
181
  const assignments = await this.getAllAssignments();
262
182
  const relevantAssignments = assignments.filter((assignment) => {
263
183
  const assignmentTagSet = new Set(assignment.tags);
264
184
  return tags.some((tag) => assignmentTagSet.has(tag));
265
185
  });
266
-
267
186
  if (relevantAssignments.length > 0) {
268
187
  const multi = this.redisClient.multi();
269
188
  for (const assignment of relevantAssignments) {
@@ -281,45 +200,41 @@ export default class AssignmentMatcher {
281
200
  }
282
201
  await multi.exec();
283
202
  }
284
-
285
203
  return relevantAssignments.map((assignment) => ({ id: assignment.id, priority }));
286
204
  }
287
-
288
- private async getUserRelatedAssignments(user: User) {
205
+ async getUserRelatedAssignments(user) {
289
206
  // Build candidate assignments using per-tag zset union with user weights for scalability.
290
- const positiveWeights: Array<{ tag: string; weight: number }> = [];
291
- const zeroWeightTags: string[] = [];
292
-
207
+ const positiveWeights = [];
208
+ const zeroWeightTags = [];
293
209
  if (user.routingWeights && Object.keys(user.routingWeights).length > 0) {
294
210
  for (const [tag, w] of Object.entries(user.routingWeights)) {
295
- if (typeof w === 'number' && w > 0) positiveWeights.push({ tag, weight: w });
296
- else if (w === 0) zeroWeightTags.push(tag);
211
+ if (typeof w === 'number' && w > 0)
212
+ positiveWeights.push({ tag, weight: w });
213
+ else if (w === 0)
214
+ zeroWeightTags.push(tag);
297
215
  }
298
- } else {
216
+ }
217
+ else {
299
218
  // Fallback: use unweighted tags (weight 1)
300
219
  for (const tag of user.tags || []) {
301
220
  positiveWeights.push({ tag, weight: 1 });
302
221
  }
303
222
  }
304
-
305
223
  // Ensure default tag is included if enabled and not explicitly weighted to zero
306
224
  if (this.enableDefaultMatching) {
307
225
  const defaultInPos = positiveWeights.find((t) => t.tag === 'default');
308
226
  const defaultZero = zeroWeightTags.includes('default');
309
- if (!defaultInPos && !defaultZero) positiveWeights.push({ tag: 'default', weight: 1 });
227
+ if (!defaultInPos && !defaultZero)
228
+ positiveWeights.push({ tag: 'default', weight: 1 });
310
229
  }
311
-
312
- const userAssignments: Array<{ id: string; priority: number }> = [];
313
-
314
- if (positiveWeights.length === 0) return userAssignments;
315
-
230
+ const userAssignments = [];
231
+ if (positiveWeights.length === 0)
232
+ return userAssignments;
316
233
  const tempKey = this.redisPrefix + `tmp:user:${user.id}:candidates`;
317
234
  const tempZeroKey = this.redisPrefix + `tmp:user:${user.id}:exclude`;
318
235
  const tempFinalKey = this.redisPrefix + `tmp:user:${user.id}:final`;
319
-
320
236
  const unionKeys = positiveWeights.map((pw) => this.redisPrefix + `tag:${pw.tag}:assignments`);
321
237
  const unionWeights = positiveWeights.map((pw) => pw.weight);
322
-
323
238
  const multi = this.redisClient.multi();
324
239
  // Weighted union of positive tag assignment zsets
325
240
  multi.zUnionStore(tempKey, unionKeys, { WEIGHTS: unionWeights });
@@ -333,43 +248,41 @@ export default class AssignmentMatcher {
333
248
  multi.expire(tempKey, 5);
334
249
  multi.expire(tempZeroKey, 5);
335
250
  multi.expire(tempFinalKey, 5);
336
- } else {
251
+ }
252
+ else {
337
253
  // No exclude; just use tempKey as final (copy into final for uniformity)
338
254
  multi.zUnionStore(tempFinalKey, [tempKey]);
339
255
  multi.expire(tempKey, 5);
340
256
  multi.expire(tempFinalKey, 5);
341
257
  }
342
-
343
258
  await multi.exec();
344
-
345
259
  // Pull top-N in ascending score to preserve previous behavior on ties (lex ascending)
346
260
  const top = await this.redisClient.zRangeWithScores(tempFinalKey, 0, this.relevantBatchSize - 1);
347
-
348
- if (top.length === 0) return userAssignments;
349
-
261
+ if (top.length === 0)
262
+ return userAssignments;
350
263
  // Fetch per-assignment stored (base) priority and tags in a single pipeline (fewer round trips)
351
264
  const batched = this.redisClient.multi();
352
265
  for (const entry of top) {
353
- const assignmentId = (entry as any).value;
266
+ const assignmentId = entry.value;
354
267
  const assignmentPriorityKey = this.redisPrefix + `assignment:${assignmentId}:priority`;
355
268
  const assignmentTagsKey = this.redisPrefix + `assignment:${assignmentId}:tags`;
356
269
  batched.hGet(assignmentPriorityKey, 'priority');
357
270
  batched.hGet(assignmentTagsKey, 'tags');
358
271
  }
359
272
  const flat = await batched.exec();
360
- const details = [] as Array<{ id: string; basePriority: number; tags: string }>;
273
+ const details = [];
361
274
  for (let i = 0; i < top.length; i++) {
362
- const assignmentId = (top[i] as any).value;
275
+ const assignmentId = top[i].value;
363
276
  const priority = Number(flat[i * 2]) || 0;
364
277
  const tags = String(flat[i * 2 + 1] || '');
365
278
  details.push({ id: assignmentId, basePriority: priority, tags });
366
279
  }
367
280
  // Prefer higher base priority first to satisfy tests and practical expectations
368
281
  details.sort((a, b) => b.basePriority - a.basePriority);
369
-
370
- const selected: Array<{ id: string; tags: string }> = [];
282
+ const selected = [];
371
283
  for (const d of details) {
372
- if (userAssignments.length >= this.maxUserBacklogSize) break;
284
+ if (userAssignments.length >= this.maxUserBacklogSize)
285
+ break;
373
286
  // Use custom matchScore (supports weights) for a final check and tie-break
374
287
  const [score, combinedPriority] = await this.matchScore(user, d.tags, d.basePriority, d.id);
375
288
  if (score && combinedPriority) {
@@ -377,7 +290,6 @@ export default class AssignmentMatcher {
377
290
  selected.push({ id: d.id, tags: d.tags });
378
291
  }
379
292
  }
380
-
381
293
  // Batch-remove all selected assignments from indexes and references to reduce round trips
382
294
  if (selected.length > 0) {
383
295
  const rm = this.redisClient.multi();
@@ -391,70 +303,61 @@ export default class AssignmentMatcher {
391
303
  // Remove from global zset
392
304
  rm.zRem(this.assignmentsKey, s.id);
393
305
  // Remove from per-tag zsets
394
- const tags = (s.tags ? s.tags.split(',').filter(Boolean) : []) as string[];
306
+ const tags = (s.tags ? s.tags.split(',').filter(Boolean) : []);
395
307
  for (const tag of tags) {
396
308
  rm.zRem(this.redisPrefix + `tag:${tag}:assignments`, s.id);
397
309
  }
398
310
  }
399
311
  await rm.exec();
400
312
  }
401
-
402
313
  return userAssignments;
403
314
  }
404
- async matchUsersAssignments(userId?: string): Promise<void> {
315
+ async matchUsersAssignments(userId) {
405
316
  // If a specific userId is provided, process only that user for precise per-user matching.
406
317
  if (userId) {
407
318
  const userJson = await this.redisClient.hGet(this.usersKey, userId);
408
- if (!userJson) return;
319
+ if (!userJson)
320
+ return;
409
321
  const user = JSON.parse(userJson);
410
322
  const userMatchesCount = await this.redisClient.sCard(this.redisPrefix + `user:${user.id}:assignments`);
411
- if (userMatchesCount >= this.maxUserBacklogSize) return;
412
-
323
+ if (userMatchesCount >= this.maxUserBacklogSize)
324
+ return;
413
325
  const relevantAssignments = await this.getUserRelatedAssignments(user);
414
326
  const relevantAssignmentKeys = relevantAssignments
415
327
  .sort((a, b) => b.priority - a.priority)
416
328
  .map((a) => `assignment:${a.id}`);
417
-
418
329
  if (relevantAssignmentKeys.length > 0) {
419
330
  await this.redisClient.sAdd(this.redisPrefix + `user:${user.id}:assignments`, relevantAssignmentKeys);
420
331
  }
421
332
  return;
422
333
  }
423
-
424
334
  // Otherwise, process all users in parallel as before.
425
- let users: any[] = [];
335
+ let users = [];
426
336
  let cursor = 0;
427
-
428
337
  // Fetch all users in a single loop
429
338
  do {
430
339
  const { cursor: nextCursor, tuples } = await this.redisClient.hScan(this.usersKey, cursor);
431
- users.push(...tuples.map((t: { value: string }) => JSON.parse(t.value)));
340
+ users.push(...tuples.map((t) => JSON.parse(t.value)));
432
341
  cursor = nextCursor;
433
342
  } while (cursor !== 0);
434
-
435
343
  // Process users in parallel
436
- await Promise.all(
437
- users.map(async (user) => {
438
- const userMatchesCount = await this.redisClient.sCard(this.redisPrefix + `user:${user.id}:assignments`);
439
- if (userMatchesCount >= this.maxUserBacklogSize) {
440
- return;
441
- }
442
-
443
- const relevantAssignments = await this.getUserRelatedAssignments(user);
444
- const relevantAssignmentKeys = relevantAssignments
445
- .sort((a, b) => b.priority - a.priority)
446
- .map((a) => `assignment:${a.id}`);
447
-
448
- if (relevantAssignmentKeys.length > 0) {
449
- await this.redisClient.sAdd(this.redisPrefix + `user:${user.id}:assignments`, relevantAssignmentKeys);
450
- }
451
- }),
452
- );
344
+ await Promise.all(users.map(async (user) => {
345
+ const userMatchesCount = await this.redisClient.sCard(this.redisPrefix + `user:${user.id}:assignments`);
346
+ if (userMatchesCount >= this.maxUserBacklogSize) {
347
+ return;
348
+ }
349
+ const relevantAssignments = await this.getUserRelatedAssignments(user);
350
+ const relevantAssignmentKeys = relevantAssignments
351
+ .sort((a, b) => b.priority - a.priority)
352
+ .map((a) => `assignment:${a.id}`);
353
+ if (relevantAssignmentKeys.length > 0) {
354
+ await this.redisClient.sAdd(this.redisPrefix + `user:${user.id}:assignments`, relevantAssignmentKeys);
355
+ }
356
+ }));
453
357
  }
454
-
455
- async getCurrentAssignmentsForUser(userId: string): Promise<string[]> {
358
+ async getCurrentAssignmentsForUser(userId) {
456
359
  const userAssignments = await this.redisClient.sMembers(this.redisPrefix + `user:${userId}:assignments`);
457
-
458
- return userAssignments.map((el: string) => el.split(':')[1]);
360
+ return userAssignments.map((el) => el.split(':')[1]);
459
361
  }
460
362
  }
363
+ exports.default = AssignmentMatcher;
package/package.json CHANGED
@@ -1,7 +1,20 @@
1
1
  {
2
2
  "name": "assignment-user-matcher",
3
- "version": "1.0.11",
4
- "main": "index.js",
3
+ "version": "1.0.14",
4
+ "main": "dist/index.js",
5
+ "module": "dist/index.js",
6
+ "types": "dist/index.d.ts",
7
+ "files": [
8
+ "dist"
9
+ ],
10
+ "exports": {
11
+ "./package.json": "./package.json",
12
+ ".": {
13
+ "types": "./dist/index.d.ts",
14
+ "require": "./dist/index.js",
15
+ "import": "./dist/index.js"
16
+ }
17
+ },
5
18
  "author": "Viljar Võidula",
6
19
  "license": "MIT",
7
20
  "private": false,