-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathwidget-mission.ts
More file actions
341 lines (296 loc) · 12.5 KB
/
widget-mission.ts
File metadata and controls
341 lines (296 loc) · 12.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
import { PUBLISHER_IDS } from "@/config";
import { Prisma } from "@/db/core";
import { prismaCore } from "@/db/postgres";
import { missionRepository } from "@/repositories/mission";
import type { WidgetRecord } from "@/types";
import type { MissionRecord, MissionSearchFilters, MissionSelect } from "@/types/mission";
import { buildWhere, missionService } from "./mission";
import publisherOrganizationService from "./publisher-organization";
type Bucket = { key: string; doc_count: number; label?: string };
type PublisherOrganizationTuple = {
publisherId: string;
clientId: string;
};
const buildWidgetWhere = (widget: WidgetRecord, filters: MissionSearchFilters): Prisma.MissionWhereInput => {
if (!widget.jvaModeration) {
return buildWhere(filters);
}
const jvaPublishers = widget.publishers.filter((publisherId) => publisherId === PUBLISHER_IDS.JEVEUXAIDER);
const otherPublishers = widget.publishers.filter((publisherId) => publisherId !== PUBLISHER_IDS.JEVEUXAIDER);
const baseWhere = buildWhere({ ...filters, publisherIds: [], moderationAcceptedFor: undefined });
const orConditions: Prisma.MissionWhereInput[] = [];
if (jvaPublishers.length) {
orConditions.push({ publisherId: { in: jvaPublishers } });
}
if (otherPublishers.length) {
orConditions.push({
publisherId: { in: otherPublishers },
moderationStatuses: { some: { publisherId: PUBLISHER_IDS.JEVEUXAIDER, status: "ACCEPTED" } },
});
}
return orConditions.length ? { AND: [baseWhere, { OR: orConditions }] } : baseWhere;
};
const isPlainObject = (value: unknown): value is Record<string, unknown> => typeof value === "object" && value !== null && !Array.isArray(value) && !(value instanceof Date);
/**
* Builds a mission condition from `(publisherId, clientId)` tuples.
* Returns either one condition or an `OR` of conditions; empty input matches nothing.
*/
const buildMissionConditionFromPublisherOrganizationTuples = (tuples: PublisherOrganizationTuple[]): Prisma.MissionWhereInput => {
if (!tuples.length) {
return { publisherId: { in: [] } };
}
const byPublisher = new Map<string, Set<string>>();
tuples.forEach(({ publisherId, clientId }) => {
if (!byPublisher.has(publisherId)) {
byPublisher.set(publisherId, new Set());
}
byPublisher.get(publisherId)?.add(clientId);
});
const conditions = Array.from(byPublisher.entries()).map(([publisherId, clientIds]) => ({
publisherId,
publisherOrganization: { clientId: { in: Array.from(clientIds) } },
}));
return conditions.length === 1 ? conditions[0] : { OR: conditions };
};
/**
* Replaces `publisherOrganization.is` filters with equivalent mission predicates.
* This avoids replaying expensive relational OR/ILIKE branches on every query.
*/
const inlinePublisherOrganizationFilters = async (where: Prisma.MissionWhereInput): Promise<Prisma.MissionWhereInput> => {
// Request-scoped memoization: identical `publisherOrganization.is` conditions
// are resolved once, then reused during the same where-tree traversal.
const cache = new Map<string, Prisma.MissionWhereInput>();
const resolvePublisherOrganizationCondition = async (condition: Prisma.PublisherOrganizationWhereInput): Promise<Prisma.MissionWhereInput> => {
const cacheKey = JSON.stringify(condition);
const cached = cache.get(cacheKey);
if (cached) {
return cached;
}
const rows = await prismaCore.publisherOrganization.findMany({
where: condition,
select: { publisherId: true, clientId: true },
});
const tuples: PublisherOrganizationTuple[] = rows
.filter((r): r is typeof r & { clientId: string } => r.clientId != null)
.map((r) => ({ publisherId: r.publisherId, clientId: r.clientId }));
const missionCondition = buildMissionConditionFromPublisherOrganizationTuples(tuples);
cache.set(cacheKey, missionCondition);
return missionCondition;
};
const transform = async (node: unknown): Promise<unknown> => {
if (Array.isArray(node)) {
return await Promise.all(node.map((item) => transform(item)));
}
if (!isPlainObject(node)) {
return node;
}
const maybePublisherOrganization = node.publisherOrganization;
if (isPlainObject(maybePublisherOrganization) && isPlainObject(maybePublisherOrganization.is)) {
const missionCondition = await resolvePublisherOrganizationCondition(maybePublisherOrganization.is as Prisma.PublisherOrganizationWhereInput);
const restEntries = Object.entries(node).filter(([key]) => key !== "publisherOrganization");
if (!restEntries.length) {
return missionCondition;
}
const transformedRest = Object.fromEntries(await Promise.all(restEntries.map(async ([key, value]) => [key, await transform(value)] as const)));
return { AND: [transformedRest, missionCondition] };
}
return Object.fromEntries(await Promise.all(Object.entries(node).map(async ([key, value]) => [key, await transform(value)] as const)));
};
return (await transform(where)) as Prisma.MissionWhereInput;
};
const aggregateWidgetAggs = async (
where: Prisma.MissionWhereInput,
requestedAggs: string[]
): Promise<{
domains?: Bucket[];
organizations?: Bucket[];
departments?: Bucket[];
remote?: Bucket[];
countries?: Bucket[];
minor?: Bucket[];
accessibility?: Bucket[];
schedule?: Bucket[];
actions?: Bucket[];
beneficiaries?: Bucket[];
}> => {
const should = (key: string) => requestedAggs.includes(key);
const aggregateMissionField = async (field: Prisma.MissionScalarFieldEnum) => {
const rows = await prismaCore.mission.groupBy({
by: [field],
where,
_count: { _all: true },
});
return rows
.map((row) => ({
key: String((row as any)[field] ?? ""),
doc_count: Number((row as any)._count?._all ?? 0),
}))
.filter((row) => row.key);
};
const aggregateAddressField = async (field: "city" | "departmentName" | "country") => {
const rows = await prismaCore.missionAddress.groupBy({
by: [field, "missionId"],
where: { mission: where },
_count: { _all: true },
});
const counts = new Map<string, number>();
rows.forEach((row) => {
const key = String((row as any)[field] ?? "");
if (!key) {
return;
}
counts.set(key, (counts.get(key) ?? 0) + 1);
});
return Array.from(counts.entries()).map(([key, doc_count]) => ({ key, doc_count }));
};
const aggregateDomainField = async () => {
const rows = await prismaCore.mission.groupBy({
by: ["domainId"],
where,
_count: { _all: true },
});
const domainIds = rows.map((row) => (row as any).domainId).filter((id): id is string => typeof id === "string" && id.length > 0);
const domains = domainIds.length ? await prismaCore.domain.findMany({ where: { id: { in: domainIds } }, select: { id: true, name: true } }) : [];
const nameById = new Map(domains.map((domain) => [domain.id, domain.name ?? ""]));
return rows
.map((row) => {
const domainId = (row as any).domainId as string | null;
return {
key: domainId ? (nameById.get(domainId) ?? "") : "",
doc_count: Number((row as any)._count?._all ?? 0),
};
})
.filter((row) => row.key);
};
const aggregateMissionListField = async (field: "tasks" | "audience") => {
// Resolve filtered mission ids once, then aggregate on that fixed id set.
const missions = await prismaCore.mission.findMany({
where,
select: { id: true },
// Limit to prevent memory issues on extremely large datasets
// For most widgets, this should cover all missions. If more than 50k missions,
// aggregations will be based on a representative sample
take: 50000,
});
if (missions.length === 0) {
return [];
}
const missionIds = missions.map((m) => m.id);
// Aggregate with UNNEST from ids instead of rebuilding full text conditions.
const rows = await missionRepository.aggregateArrayField(missionIds, field);
return rows.map((row) => ({
key: row.value,
doc_count: row.count,
}));
};
const formatOrganization = async () => {
const orgRows = await aggregateMissionField("publisherOrganizationId");
const orgIds = orgRows.map((row) => row.key);
const orgs = orgIds.length ? await publisherOrganizationService.findMany({ ids: orgIds }, { select: { id: true, name: true, clientId: true } }) : [];
const orgById = new Map(orgs.map((org) => [org.id, { name: org.name ?? "", clientId: org.clientId ?? "" }]));
return orgRows
.map((row) => {
const org = orgById.get(row.key);
return { key: org?.clientId ?? "", doc_count: row.doc_count, label: org?.name ?? "" };
})
.filter((row) => row.key);
};
const result: any = {};
const promises = new Map<string, Promise<Bucket[]>>();
if (should("domain")) {
promises.set("domains", aggregateDomainField());
}
if (should("organization")) {
promises.set("organizations", formatOrganization());
}
if (should("department")) {
promises.set("departments", aggregateAddressField("departmentName"));
}
if (should("remote")) {
promises.set("remote", aggregateMissionField("remote"));
}
if (should("country")) {
promises.set("countries", aggregateAddressField("country"));
}
if (should("minor")) {
promises.set("minor", aggregateMissionField("openToMinors"));
}
if (should("schedule")) {
promises.set("schedule", aggregateMissionField("schedule"));
}
if (should("action")) {
promises.set("actions", aggregateMissionListField("tasks"));
}
if (should("beneficiary")) {
promises.set("beneficiaries", aggregateMissionListField("audience"));
}
if (should("accessibility")) {
const reduced = await prismaCore.mission.count({ where: { ...where, reducedMobilityAccessible: true } });
const transport = await prismaCore.mission.count({ where: { ...where, closeToTransport: true } });
result.accessibility = [
{ key: "reducedMobilityAccessible", doc_count: reduced },
{ key: "closeToTransport", doc_count: transport },
];
}
const entries = Array.from(promises.entries());
const values = await Promise.all(entries.map(([, promise]) => promise));
entries.forEach(([key], index) => {
result[key] = values[index];
});
return result;
};
const sortBuckets = (buckets?: Bucket[]) => (buckets ?? []).sort((a, b) => b.doc_count - a.doc_count);
export const widgetMissionService = {
async fetchWidgetMissions(widget: WidgetRecord, filters: MissionSearchFilters, select: MissionSelect | null = null): Promise<{ data: MissionRecord[]; total: number }> {
const rawWhere = buildWidgetWhere(widget, filters);
const where = await inlinePublisherOrganizationFilters(rawWhere);
const [data, total] = await Promise.all([
missionService.findMissionsBy(where, {
select,
orderBy: [{ startAt: Prisma.SortOrder.desc }, { createdAt: Prisma.SortOrder.desc }],
skip: filters.skip,
limit: filters.limit,
moderatedBy: widget.jvaModeration ? PUBLISHER_IDS.JEVEUXAIDER : null,
}),
missionService.countBy(where),
]);
return { data, total };
},
async fetchWidgetAggregations(widget: WidgetRecord, filters: MissionSearchFilters, requestedAggs: string[]) {
const rawWhere = buildWidgetWhere(widget, { ...filters, skip: 0, limit: 0 });
const where = await inlinePublisherOrganizationFilters(rawWhere);
const result = await aggregateWidgetAggs(where, requestedAggs);
const payload: any = {};
if (requestedAggs.includes("domain")) {
payload.domain = sortBuckets(result.domains);
}
if (requestedAggs.includes("organization")) {
payload.organization = sortBuckets(result.organizations);
}
if (requestedAggs.includes("department")) {
payload.department = sortBuckets(result.departments);
}
if (requestedAggs.includes("remote")) {
payload.remote = sortBuckets(result.remote);
}
if (requestedAggs.includes("country")) {
payload.country = sortBuckets(result.countries);
}
if (requestedAggs.includes("minor")) {
payload.minor = sortBuckets(result.minor);
}
if (requestedAggs.includes("accessibility")) {
payload.accessibility = sortBuckets(result.accessibility);
}
if (requestedAggs.includes("schedule")) {
payload.schedule = sortBuckets(result.schedule);
}
if (requestedAggs.includes("action")) {
payload.action = sortBuckets(result.actions);
}
if (requestedAggs.includes("beneficiary")) {
payload.beneficiary = sortBuckets(result.beneficiaries);
}
return payload;
},
};