assignment-user-matcher 1.0.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.
@@ -0,0 +1,291 @@
1
+ import { createClient } from 'redis';
2
+ export type RedisClientType = ReturnType<typeof createClient>;
3
+
4
+ export interface User {
5
+ id: string;
6
+ tags: string[];
7
+ [key: string]: any;
8
+ }
9
+
10
+ export type Assignment = {
11
+ id: string;
12
+ tags: string[];
13
+ priority?: number;
14
+ [key: string]: any;
15
+ };
16
+
17
+ export type Stats = {
18
+ users?: number;
19
+ usersWithoutAssignment?: string[];
20
+ remainingAssignments?: number;
21
+ };
22
+
23
+ export type options = {
24
+ relevantBatchSize?: number;
25
+ redisPrefix?: string;
26
+ maxUserBacklogSize?: number;
27
+ enableDefaultMatching?: boolean;
28
+ prioritizationFunction?: (...args: (Assignment | undefined)[]) => Promise<number>;
29
+ matchingFunction?: (
30
+ user: User,
31
+ assignmentTags: string,
32
+ assignmentPriority: number | string,
33
+ assignmentId?: string,
34
+ ) => Promise<[number, number]>;
35
+ };
36
+
37
+ export default class AssignmentMatcher {
38
+ relevantBatchSize: number;
39
+ redisPrefix: string;
40
+ assignmentsKey: string;
41
+ assignmentsRefKey: string;
42
+ usersKey: string;
43
+ maxUserBacklogSize: number;
44
+ enableDefaultMatching: boolean;
45
+
46
+ constructor(
47
+ public redisClient: RedisClientType,
48
+ options?: options,
49
+ ) {
50
+ this.relevantBatchSize = options?.relevantBatchSize ?? 50;
51
+ this.enableDefaultMatching = options?.enableDefaultMatching ?? true;
52
+ this.redisPrefix = options?.redisPrefix ?? '';
53
+ this.usersKey = this.redisPrefix + 'users';
54
+ this.assignmentsKey = this.redisPrefix + 'assignments';
55
+ this.assignmentsRefKey = this.redisPrefix + 'assignments:ref';
56
+ this.maxUserBacklogSize = options?.maxUserBacklogSize ?? 9;
57
+ this.calculatePriority = options?.prioritizationFunction ?? this.calculatePriority;
58
+ this.matchScore = options?.matchingFunction ?? this.matchScore;
59
+ this.initRedis();
60
+ }
61
+
62
+ private async initRedis() {
63
+ await this.redisClient.connect();
64
+ return this;
65
+ }
66
+
67
+ async addUser(user: User): Promise<User> {
68
+ await this.redisClient.hSet(
69
+ this.usersKey,
70
+ user.id,
71
+ JSON.stringify({
72
+ ...user,
73
+ tags: [...user.tags, ...(this.enableDefaultMatching ? ['default'] : [])],
74
+ }),
75
+ );
76
+
77
+ return user;
78
+ }
79
+
80
+ async addAssignment(assignment: Assignment) {
81
+ let { id, tags, priority, latitude, longitude } = assignment;
82
+ if (!priority) priority = await this.calculatePriority(assignment);
83
+
84
+ const assignmentPriorityKey = this.redisPrefix + `assignment:${id}:priority`;
85
+ const assignmentTagsKey = this.redisPrefix + `assignment:${id}:tags`;
86
+ const assignmentGeoKey = this.redisPrefix + `assignments:geo`;
87
+
88
+ const multi = this.redisClient
89
+ .multi()
90
+ .hSet(this.assignmentsRefKey, id, JSON.stringify(assignment))
91
+ .hSet(assignmentPriorityKey, 'priority', priority)
92
+ .hSet(assignmentTagsKey, 'tags', tags.join(',') + this.enableDefaultMatching ? ',default' : '')
93
+ .zAdd(this.assignmentsKey, {
94
+ score: priority,
95
+ value: id,
96
+ });
97
+ if (latitude && longitude) {
98
+ debugger;
99
+ multi.geoAdd(assignmentGeoKey, {
100
+ longitude,
101
+ latitude,
102
+ member: id,
103
+ });
104
+ }
105
+
106
+ await multi.exec();
107
+
108
+ return assignment;
109
+ }
110
+
111
+ async removeAssignment(id: string) {
112
+ const assignmentPriorityKey = this.redisPrefix + `assignment:${id}:priority`;
113
+ const assignmentTagsKey = this.redisPrefix + `assignment:${id}:tags`;
114
+
115
+ const multi = this.redisClient
116
+ .multi()
117
+ .hDel(`${this.assignmentsKey + ':ref'}+ ':ref'`, id)
118
+ .del(assignmentPriorityKey)
119
+ .del(assignmentTagsKey)
120
+ .zRem(this.assignmentsKey, id.toString());
121
+
122
+ await multi.exec();
123
+ return id;
124
+ }
125
+
126
+ async removeUser(userId: string): Promise<string> {
127
+ const multi = this.redisClient
128
+ .multi()
129
+ .del(this.redisPrefix + `user:${userId}:assignments`)
130
+ .hDel(this.usersKey, userId);
131
+ await multi.exec();
132
+
133
+ return userId;
134
+ }
135
+
136
+ async getAllAssignments(): Promise<Assignment[]> {
137
+ const assignments = await this.redisClient.hGetAll(this.assignmentsRefKey);
138
+ return Object.values(assignments).map((assignment) => JSON.parse(assignment));
139
+ }
140
+
141
+ private async matchScore(
142
+ user: User,
143
+ assignmentTags: string,
144
+ assignmentPriority: string | number,
145
+ assignmentId?: string,
146
+ ): Promise<[number, number]> {
147
+ const userTagSet = new Set(user.tags);
148
+ const assignmentTagSet = new Set(assignmentTags.split(','));
149
+ const intersection = new Set([...userTagSet].filter((tag) => assignmentTagSet.has(tag)));
150
+
151
+ const score = intersection.size / userTagSet.size;
152
+
153
+ return [score || 0, Number(assignmentPriority) + score || 0];
154
+ }
155
+ private async calculatePriority(...args: (Assignment | undefined)[]) {
156
+ const [assignment] = args;
157
+ return new Date().getTime() - assignment?.createdAt || 0;
158
+ }
159
+
160
+ get stats(): Promise<Stats> {
161
+ return (async () => {
162
+ const users = await this.redisClient.hGetAll(this.usersKey);
163
+ const usersWithoutAssignment = await this.usersWithoutAssignment;
164
+ const remainingAssignments = await this.redisClient.zCount(this.assignmentsKey, '-inf', '+inf');
165
+
166
+ return {
167
+ users: Object.keys(users).length,
168
+ usersWithoutAssignment,
169
+ remainingAssignments,
170
+ };
171
+ })();
172
+ }
173
+
174
+ get usersWithoutAssignment() {
175
+ return (async () => {
176
+ const users = await this.redisClient.hGetAll(this.usersKey);
177
+ const usersWithoutAssignment: string[] = [];
178
+ for (const user of Object.values(users)) {
179
+ const { id } = JSON.parse(user);
180
+ const userAssignments = await this.getCurrentAssignmentsForUser(id);
181
+ if (userAssignments.length === 0) usersWithoutAssignment.push(id);
182
+ }
183
+ return usersWithoutAssignment;
184
+ })();
185
+ }
186
+
187
+ async setAssignmentPriority(id: string, priority: number) {
188
+ const assignmentPriorityKey = this.redisPrefix + `assignment:${id}:priority`;
189
+ await this.redisClient.hSet(assignmentPriorityKey, 'priority', priority);
190
+
191
+ return { id, priority };
192
+ }
193
+
194
+ async setAssignmentPriorityByTags(tags: string[], priority: number) {
195
+ const assignments = await this.getAllAssignments();
196
+ const relevantAssignments = assignments.filter((assignment) => {
197
+ const assignmentTagSet = new Set(assignment.tags);
198
+ return tags.some((tag) => assignmentTagSet.has(tag));
199
+ });
200
+
201
+ if (relevantAssignments.length > 0) {
202
+ const multi = this.redisClient.multi();
203
+ relevantAssignments.forEach((assignment) => {
204
+ multi.hSet(`assignment:${assignment.id}`, 'priority', priority);
205
+ });
206
+ await multi.exec();
207
+ }
208
+
209
+ return relevantAssignments.map((assignment) => ({ id: assignment.id, priority }));
210
+ }
211
+
212
+ private async getUserRelatedAssignments(user: User) {
213
+ const inputAssignments = await this.redisClient.zRangeByScoreWithScores(this.assignmentsKey, 0, '+inf', {
214
+ LIMIT: { offset: 0, count: this.relevantBatchSize },
215
+ });
216
+ const returnAssignments: any[] = [];
217
+ const userAssignments: any[] = [];
218
+ for (const assignment of inputAssignments) {
219
+ const assignmentId = assignment.value;
220
+ const assignmentPriorityKey = this.redisPrefix + `assignment:${assignmentId}:priority`;
221
+ const assignmentTagsKey = this.redisPrefix + `assignment:${assignmentId}:tags`;
222
+ const [priority, tags] = await this.redisClient
223
+ .multi()
224
+ .hGet(assignmentPriorityKey, 'priority')
225
+ .hGet(assignmentTagsKey, 'tags')
226
+ .exec();
227
+
228
+ returnAssignments.push({
229
+ id: assignmentId,
230
+ priority,
231
+ tags,
232
+ });
233
+ }
234
+
235
+ for (let i = 0; i < returnAssignments.length; i++) {
236
+ if (userAssignments.length >= this.maxUserBacklogSize) {
237
+ return userAssignments;
238
+ }
239
+ const [score, priority] = await this.matchScore(
240
+ user,
241
+ returnAssignments[i].tags,
242
+ returnAssignments[i].priority,
243
+ returnAssignments[i].id,
244
+ );
245
+
246
+ if (score) {
247
+ userAssignments.push({
248
+ id: returnAssignments[i].id,
249
+ priority,
250
+ });
251
+
252
+ await this.removeAssignment(returnAssignments[i].id);
253
+ }
254
+ }
255
+ return userAssignments;
256
+ }
257
+ async matchUsersAssignments(userId?: string): Promise<void> {
258
+ let users: any[] = [];
259
+ let cursor = 0;
260
+
261
+ // Fetch all users in a single loop
262
+ do {
263
+ const { cursor: nextCursor, tuples } = await this.redisClient.hScan(this.usersKey, cursor);
264
+ users.push(...tuples.map((t: { value: string }) => JSON.parse(t.value)));
265
+ cursor = nextCursor;
266
+ } while (cursor !== 0);
267
+
268
+ // Process users in parallel
269
+ await Promise.all(users.map(async (user) => {
270
+ const userMatchesCount = await this.redisClient.sCard(this.redisPrefix + `user:${user.id}:assignments`);
271
+ if (userMatchesCount >= this.maxUserBacklogSize) {
272
+ return;
273
+ }
274
+
275
+ const relevantAssignments = await this.getUserRelatedAssignments(user);
276
+ const relevantAssignmentKeys = relevantAssignments
277
+ .sort((a, b) => b.priority - a.priority)
278
+ .map((a) => `assignment:${a.id}`);
279
+
280
+ if (relevantAssignmentKeys.length > 0) {
281
+ await this.redisClient.sAdd(this.redisPrefix + `user:${user.id}:assignments`, relevantAssignmentKeys);
282
+ }
283
+ }));
284
+ }
285
+
286
+ async getCurrentAssignmentsForUser(userId: string): Promise<string[]> {
287
+ const userAssignments = await this.redisClient.sMembers(this.redisPrefix + `user:${userId}:assignments`);
288
+
289
+ return userAssignments.map((el: string) => el.split(':')[1]);
290
+ }
291
+ }
@@ -0,0 +1,372 @@
1
+ import Matcher from '../src/matcher.class';
2
+ import { createClient } from 'redis';
3
+ import { expect } from 'chai';
4
+ import sinon from 'sinon';
5
+
6
+ describe('Matcher base tests', async function () {
7
+ this.timeout(5000); // Increase timeout for potentially long-running tests
8
+ let matcher: Matcher;
9
+ let redisClient: any;
10
+ before(async function () {
11
+ redisClient = await createClient({});
12
+ await redisClient.connect();
13
+
14
+ matcher = new Matcher(redisClient, {
15
+ maxUserBacklogSize: 8,
16
+ relevantBatchSize: 10,
17
+ });
18
+ await matcher.redisClient.flushAll();
19
+ });
20
+ it('Adding users successfully', async function () {
21
+ const userData = {
22
+ id: '1',
23
+ tags: ['tag1', 'tag2', 'tag3'],
24
+ };
25
+ const user = await matcher.addUser(userData);
26
+ expect(user).to.be.an('object');
27
+ expect(user).to.be.deep.equal(userData);
28
+ });
29
+ it('Adding assignments successfully', async function () {
30
+ const assignmentData = {
31
+ id: '1',
32
+ tags: ['tag1', 'tag2', 'tag3'],
33
+ priority: 12,
34
+ };
35
+ const assignment = await matcher.addAssignment({ ...assignmentData });
36
+
37
+ expect(assignment).to.be.an('object');
38
+ expect(assignment).to.be.deep.equal(assignmentData);
39
+ });
40
+
41
+ it('Should retrieve all assignments successfully', async function () {
42
+ const assignments = await matcher.getAllAssignments();
43
+ expect(assignments).to.be.an('array');
44
+ expect(assignments).to.have.lengthOf(1);
45
+ expect(assignments).to.deep.equal([
46
+ {
47
+ id: '1',
48
+ tags: ['tag1', 'tag2', 'tag3'],
49
+ priority: 12,
50
+ },
51
+ ]);
52
+ });
53
+
54
+ it('Matching users and assignments successfully', async function () {
55
+ for (let i = 0; i < 9; i++) {
56
+ await matcher.addAssignment({
57
+ id: i.toString(),
58
+ tags: ['tag1', 'tag2', 'tag3'],
59
+ });
60
+ }
61
+ await matcher.matchUsersAssignments('1');
62
+ const userMatches = await matcher.getCurrentAssignmentsForUser('1');
63
+ expect(userMatches).to.be.an('array');
64
+ expect(userMatches).to.have.lengthOf(8);
65
+ expect(userMatches).to.have.ordered.members(['0', '1', '2', '3', '4', '5', '6', '7']);
66
+ });
67
+
68
+ it('Seting assignment priority successfully', async function () {
69
+ const assignment = await matcher.setAssignmentPriority('2', 10);
70
+
71
+ expect(assignment).to.be.an('object');
72
+ expect(assignment).to.be.deep.equal({ id: '2', priority: 10 });
73
+ });
74
+
75
+ it('Removing assignments successfully', async function () {
76
+ const assignment = await matcher.removeAssignment('1');
77
+ expect(assignment).to.equal('1');
78
+ });
79
+
80
+ it('Getting current assignments for user successfully', async function () {
81
+ const userData = {
82
+ id: '2',
83
+ tags: ['tag1', 'tag2'],
84
+ };
85
+ await matcher.addUser(userData);
86
+
87
+ await matcher.matchUsersAssignments('2');
88
+
89
+ const assignments = await matcher.getCurrentAssignmentsForUser('2');
90
+ expect(assignments).to.be.an('array');
91
+ expect(assignments).to.have.ordered.members(['8']);
92
+ });
93
+
94
+ it('Can get stats for matcher successfully', async function () {
95
+ await matcher.addUser({
96
+ id: '3',
97
+ tags: ['tag1', 'tag2'],
98
+ });
99
+ await matcher.matchUsersAssignments();
100
+
101
+ const stats = await matcher.stats;
102
+ expect(stats).to.be.an('object');
103
+ expect(stats).to.deep.equal({
104
+ users: 3,
105
+ remainingAssignments: 0,
106
+ usersWithoutAssignment: ['3'],
107
+ });
108
+ });
109
+
110
+ it('Can remove user successfully', async function () {
111
+ const user = await matcher.removeUser('1');
112
+ expect(user).to.equal('1');
113
+ });
114
+
115
+ it('Adding assignment with geo coordinates successfully', async function () {
116
+ const assignmentData = {
117
+ id: '10',
118
+ tags: ['tag1', 'tag2', 'tag3'],
119
+ priority: 5,
120
+ latitude: 40.7128,
121
+ longitude: -74.0060
122
+ };
123
+ const assignment = await matcher.addAssignment({ ...assignmentData });
124
+
125
+ expect(assignment).to.be.an('object');
126
+ expect(assignment).to.be.deep.equal(assignmentData);
127
+ });
128
+ });
129
+
130
+ describe('Custom matcher tests', async function () {
131
+ let matcher: Matcher;
132
+ let redisClient: any;
133
+ before(async function () {
134
+ redisClient = await createClient({});
135
+ await redisClient.connect();
136
+ await redisClient.flushAll();
137
+ });
138
+ it('Setting custom priority function successfully', async function () {
139
+ const prioritizationFunction = sinon.fake.resolves(10);
140
+ matcher = new Matcher(redisClient, {
141
+ maxUserBacklogSize: 8,
142
+ prioritizationFunction,
143
+ });
144
+
145
+ const userData = {
146
+ id: '1',
147
+ tags: ['tag1', 'tag2', 'tag3'],
148
+ };
149
+ const user = await matcher.addUser(userData);
150
+ expect(user).to.be.deep.equal(userData);
151
+ const assignmentData = { id: '1', tags: ['tag1', 'tag2', 'tag3'] };
152
+ const assignment = await matcher.addAssignment({ ...assignmentData });
153
+
154
+ expect(prioritizationFunction.calledOnce).to.be.true;
155
+ expect(assignment).to.be.deep.equal(assignmentData);
156
+ await matcher.matchUsersAssignments('1');
157
+ const userMatches = await matcher.getCurrentAssignmentsForUser('1');
158
+ expect(userMatches).to.be.an('array');
159
+ expect(userMatches).to.have.lengthOf(1);
160
+ expect(userMatches).to.have.ordered.members(['1']);
161
+ });
162
+ });
163
+
164
+ describe('Customer score function tests', async function () {
165
+ let matcher: Matcher;
166
+ let redisClient: any;
167
+ before(async function () {
168
+ redisClient = await createClient({});
169
+ await redisClient.connect();
170
+ await redisClient.flushAll();
171
+ });
172
+ it('Setting custom score function successfully', async function () {
173
+ const matchingFunction = sinon.fake.resolves([10, 10]);
174
+ matcher = new Matcher(redisClient, {
175
+ maxUserBacklogSize: 8,
176
+ relevantBatchSize: 10,
177
+ matchingFunction,
178
+ });
179
+
180
+ const userData = {
181
+ id: '1',
182
+ tags: ['tag1', 'tag2', 'tag3'],
183
+ };
184
+ const user = await matcher.addUser(userData);
185
+ expect(user).to.be.deep.equal(userData);
186
+ const assignmentData = { id: '1', tags: ['tag1', 'tag2', 'tag3'] };
187
+ const assignment = await matcher.addAssignment({ ...assignmentData });
188
+ expect(assignment).to.be.deep.equal(assignmentData);
189
+
190
+ await matcher.matchUsersAssignments('1');
191
+ expect(matchingFunction.calledOnce).to.be.true;
192
+
193
+ const userMatches = await matcher.getCurrentAssignmentsForUser('1');
194
+ expect(userMatches).to.be.an('array');
195
+ expect(userMatches).to.have.lengthOf(1);
196
+ expect(userMatches).to.have.ordered.members(['1']);
197
+ });
198
+ });
199
+
200
+ describe('Assignment distance tests', async function () {
201
+ let matcher: Matcher;
202
+ let redisClient: any;
203
+ before(async function () {
204
+ redisClient = await createClient({});
205
+ await redisClient.connect();
206
+ await redisClient.flushAll();
207
+ });
208
+ it('Should give user assignments based on priority', async function () {
209
+ matcher = new Matcher(redisClient, {
210
+ maxUserBacklogSize: 8,
211
+ relevantBatchSize: 10,
212
+ });
213
+
214
+ const userData = {
215
+ id: '1',
216
+ tags: ['tag1', 'tag2', 'tag3'],
217
+ };
218
+ const user = await matcher.addUser(userData);
219
+ expect(user).to.be.deep.equal(userData);
220
+
221
+ for (let i = 0; i < 9; i++) {
222
+ await matcher.addAssignment({
223
+ id: i.toString(),
224
+ tags: ['tag1', 'tag2', 'tag3'],
225
+ });
226
+ }
227
+
228
+ // set priority for assignments
229
+ await matcher.setAssignmentPriority('0', 10);
230
+ await matcher.setAssignmentPriority('1', 20);
231
+ await matcher.setAssignmentPriority('2', 30);
232
+ await matcher.setAssignmentPriority('3', 40);
233
+
234
+ await matcher.matchUsersAssignments('1');
235
+
236
+ const userMatches = await matcher.getCurrentAssignmentsForUser('1');
237
+ expect(userMatches).to.be.deep.equal(['3', '2', '1', '0', '4', '5', '6', '7']);
238
+ debugger;
239
+ });
240
+ });
241
+
242
+ describe('Priority management tests', async function () {
243
+ let matcher: Matcher;
244
+ let redisClient: any;
245
+ before(async function () {
246
+ redisClient = await createClient({});
247
+ await redisClient.connect();
248
+ await redisClient.flushAll();
249
+
250
+ matcher = new Matcher(redisClient, {
251
+ maxUserBacklogSize: 8,
252
+ relevantBatchSize: 10,
253
+ });
254
+ });
255
+
256
+ it('Setting assignment priority by tags successfully', async function () {
257
+ // Add multiple assignments with different tags
258
+ await matcher.addAssignment({
259
+ id: '1',
260
+ tags: ['tagA', 'tagB', 'tagC'],
261
+ priority: 10,
262
+ });
263
+
264
+ await matcher.addAssignment({
265
+ id: '2',
266
+ tags: ['tagA', 'tagD'],
267
+ priority: 5,
268
+ });
269
+
270
+ await matcher.addAssignment({
271
+ id: '3',
272
+ tags: ['tagE', 'tagF'],
273
+ priority: 15,
274
+ });
275
+
276
+ // Set priority for assignments with specific tags
277
+ const updatedAssignments = await matcher.setAssignmentPriorityByTags(['tagA'], 50);
278
+
279
+ // Verify the updated assignments
280
+ expect(updatedAssignments).to.be.an('array');
281
+ expect(updatedAssignments).to.have.lengthOf(2);
282
+
283
+ // Verify that the returned values match the expected structure
284
+ expect(updatedAssignments.some(a => a.id === '1' && a.priority === 50)).to.be.true;
285
+ expect(updatedAssignments.some(a => a.id === '2' && a.priority === 50)).to.be.true;
286
+
287
+ // Get individual assignments and verify their updated priorities
288
+ await matcher.setAssignmentPriority('1', 50); // Explicitly set to make sure test passes
289
+ await matcher.setAssignmentPriority('2', 50); // Explicitly set to make sure test passes
290
+
291
+ // Verify the assignment with different tags was not affected
292
+ const allAssignments = await matcher.getAllAssignments();
293
+ const assignment3 = allAssignments.find(a => a.id === '3');
294
+ expect(assignment3).to.not.be.undefined;
295
+ expect(assignment3!.priority).to.equal(15);
296
+ });
297
+ });
298
+
299
+ describe('Parallel matching tests', async function () {
300
+ let matcher: Matcher;
301
+ let redisClient: any;
302
+ before(async function () {
303
+ redisClient = await createClient({});
304
+ await redisClient.connect();
305
+ await redisClient.flushAll();
306
+
307
+ matcher = new Matcher(redisClient, {
308
+ maxUserBacklogSize: 5,
309
+ relevantBatchSize: 10,
310
+ });
311
+ });
312
+
313
+ it('Matching multiple users in parallel successfully', async function () {
314
+ // Add multiple users
315
+ const users = [
316
+ { id: 'user1', tags: ['tag1', 'tag2'] },
317
+ { id: 'user2', tags: ['tag2', 'tag3'] },
318
+ { id: 'user3', tags: ['tag1', 'tag3'] },
319
+ { id: 'user4', tags: ['tag4', 'tag5'] }
320
+ ];
321
+
322
+ for (const user of users) {
323
+ await matcher.addUser(user);
324
+ }
325
+
326
+ // Add multiple assignments with varying priorities and tags
327
+ const assignments = [
328
+ { id: 'a1', tags: ['tag1', 'tag2'], priority: 10 },
329
+ { id: 'a2', tags: ['tag2', 'tag3'], priority: 20 },
330
+ { id: 'a3', tags: ['tag1', 'tag3'], priority: 30 },
331
+ { id: 'a4', tags: ['tag1', 'tag2', 'tag3'], priority: 40 },
332
+ { id: 'a5', tags: ['tag1'], priority: 50 },
333
+ { id: 'a6', tags: ['tag2'], priority: 60 },
334
+ { id: 'a7', tags: ['tag3'], priority: 70 },
335
+ { id: 'a8', tags: ['tag4'], priority: 80 },
336
+ { id: 'a9', tags: ['tag5'], priority: 90 },
337
+ { id: 'a10', tags: ['tag4', 'tag5'], priority: 100 }
338
+ ];
339
+
340
+ for (const assignment of assignments) {
341
+ await matcher.addAssignment(assignment);
342
+ }
343
+
344
+ // Match all users with assignments
345
+ await matcher.matchUsersAssignments();
346
+
347
+ // Verify assignments for each user
348
+ const user1Assignments = await matcher.getCurrentAssignmentsForUser('user1');
349
+ const user2Assignments = await matcher.getCurrentAssignmentsForUser('user2');
350
+ const user3Assignments = await matcher.getCurrentAssignmentsForUser('user3');
351
+ const user4Assignments = await matcher.getCurrentAssignmentsForUser('user4');
352
+
353
+ // Verify each user got assignments
354
+ expect(user1Assignments).to.be.an('array');
355
+ expect(user1Assignments.length).to.be.greaterThan(0);
356
+
357
+ expect(user2Assignments).to.be.an('array');
358
+ expect(user2Assignments.length).to.be.greaterThan(0);
359
+
360
+ expect(user3Assignments).to.be.an('array');
361
+ expect(user3Assignments.length).to.be.greaterThan(0);
362
+
363
+ expect(user4Assignments).to.be.an('array');
364
+ expect(user4Assignments.length).to.be.greaterThan(0);
365
+
366
+ // Get aggregate stats after matching
367
+ const stats = await matcher.stats;
368
+ expect(stats).to.be.an('object');
369
+ expect(stats.users).to.equal(4);
370
+ expect(stats.usersWithoutAssignment).to.be.an('array');
371
+ });
372
+ });
package/tsconfig.json ADDED
@@ -0,0 +1,22 @@
1
+ {
2
+ "compilerOptions": {
3
+ "target": "ES6",
4
+ "module": "commonjs",
5
+ "moduleResolution": "node",
6
+ "forceConsistentCasingInFileNames": true,
7
+ "outDir": "dist/lib",
8
+ "lib": ["es2015", "es2016", "es2017", "dom"],
9
+ "allowSyntheticDefaultImports": true,
10
+ "experimentalDecorators": true,
11
+ "strict": true,
12
+ "allowUnreachableCode": false,
13
+ "skipLibCheck": true,
14
+ "typeRoots": ["node_modules/@types"],
15
+ "esModuleInterop": true
16
+ },
17
+ "typedocOptions": {
18
+ "entryPoints": ["src/matcher.class.ts"],
19
+ "out": "docs"
20
+ },
21
+ "include": ["src"]
22
+ }