Mirror of https://github.com/roostorg/coop
github.com/roostorg/coop
1import _ from 'lodash';
2
3import { inject } from '../iocContainer/utils.js';
4import { RuleEnvironment } from '../rule_engine/RuleEngine.js';
5import { toCorrelationId } from '../utils/correlationIds.js';
6
7const { groupBy } = _;
8
9export default inject(
10 [
11 'RuleEngine',
12 'UserStatisticsService',
13 'closeSharedResourcesForShutdown',
14 'ModerationConfigService',
15 'getItemTypeEventuallyConsistent',
16 ],
17 (
18 RuleEngine,
19 userStatisticsService,
20 sharedResourceShutdown,
21 moderationConfigService,
22 getItemTypeEventuallyConsistent,
23 ) => ({
24 type: 'Job' as const,
25 async run() {
26 // TODO: we may have to do only some orgs per job run at some point.
27 // For now, though, this is fine.
28 const userRules = await moderationConfigService.findEnabledUserRules();
29
30 if (!userRules.length) {
31 return;
32 }
33
34 const userRulesByOrgId = groupBy(userRules, (it) => it.orgId);
35 const nowString = new Date().toISOString();
36
37 await userStatisticsService.handleUsersWithChangedScores(
38 'user-rules-runner',
39 async (rescoredUsers: readonly { userId: string; userTypeId: string; orgId: string }[]) => {
40 await Promise.all(
41 rescoredUsers.map(async ({ userId, userTypeId, orgId }: { userId: string; userTypeId: string; orgId: string }) => {
42 const rulesForUser = userRulesByOrgId[orgId];
43
44 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
45 if (!rulesForUser?.length) {
46 return;
47 }
48
49 const itemType = await getItemTypeEventuallyConsistent({
50 orgId,
51 typeSelector: { id: userTypeId },
52 });
53
54 await RuleEngine.runRuleSet(
55 rulesForUser,
56 RuleEngine.makeRuleExecutionContext({
57 orgId,
58 input: {
59 itemId: userId,
60 itemType: {
61 id: userTypeId,
62 kind: 'USER',
63 name: itemType?.name ?? "unknown",
64 },
65 },
66 }),
67 RuleEnvironment.LIVE,
68 toCorrelationId({ type: 'user-rule-run', id: nowString }),
69 );
70 }),
71 );
72 },
73 );
74 },
75 async shutdown() {
76 await sharedResourceShutdown();
77 },
78 }),
79);