@tekkare/romulus 0.1.347 → 0.1.349

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,984 @@
1
+ /**
2
+ * Ce que la creation guidee propose de ranger dans un nouveau projet, a
3
+ * partir de ses sujets (maladies, molecules, marques).
4
+ *
5
+ * Trois blocs, chacun une liste de familles de OIP_RESOURCE_SPECS, dans
6
+ * l'ordre ou les fiches se deduisent :
7
+ * - Reglementaire : HAS, ANSM, PNDS, patients, Assemblee nationale ;
8
+ * - Drugs : ventes de ville et d'hopital, prix ;
9
+ * - Augmented Science : essais, sites, professionnels, publications, PHRC.
10
+ *
11
+ * Tout se cherche en une passe, des que les sujets sont poses : le nombre de
12
+ * fiches par famille trie les sources du bloc avant meme qu'on les choisisse.
13
+ * Deux pivots, comme dans les apps d'origine :
14
+ * - la marque (fr_drugs_app) : les avis HAS directs, les marques saisies et
15
+ * celles des molecules (repertoire des marques) cherchent les familles qui
16
+ * ne connaissent que la marque (ventes, prix, ANSM...) ;
17
+ * - l'essai (France Augmented Science) : les essais directs en France
18
+ * cherchent leurs sites et leurs investigateurs, puis les publications et
19
+ * les appels a projets qui les citent.
20
+ *
21
+ * Chaque fiche porte l'`_id` Elasticsearch que l'API des projets verifie
22
+ * (R-02), et ses preuves : ce qui la relie au sujet.
23
+ */
24
+
25
+ import { ES_INDEX } from "../oip-drugs/esIndices";
26
+ import scienceIndexConfig from "../oip-science/indexConfig.json";
27
+ import { oipResourceSpec } from "../utils/oipResources";
28
+ import {
29
+ LIMIT,
30
+ clean,
31
+ escapeRegexp,
32
+ guidedHits,
33
+ guidedSearch,
34
+ highlightOf,
35
+ highlightsOf,
36
+ icd10Nested,
37
+ icdPrefix,
38
+ joinDot,
39
+ list,
40
+ textMatch,
41
+ uniq,
42
+ type GuidedEvidence,
43
+ type GuidedLang,
44
+ type GuidedMatchKind,
45
+ type GuidedRow,
46
+ type GuidedSubject,
47
+ } from "./shared";
48
+
49
+ type Text = { fr: string; en: string };
50
+
51
+ export type GuidedBlockKey = "drugs" | "regulatory" | "science";
52
+
53
+ export interface GuidedBlock {
54
+ key: GuidedBlockKey;
55
+ label: Text;
56
+ description: Text;
57
+ icon: string;
58
+ /** Les familles du bloc (`resourceType`), dans l'ordre par defaut. */
59
+ types: string[];
60
+ }
61
+
62
+ export const GUIDED_BLOCKS: GuidedBlock[] = [
63
+ {
64
+ key: "regulatory",
65
+ label: { fr: "Réglementaire", en: "Regulatory" },
66
+ description: {
67
+ fr: "Avis HAS, ANSM, PNDS, associations de patients, Assemblée nationale.",
68
+ en: "HAS opinions, ANSM, PNDS, patient associations, National Assembly.",
69
+ },
70
+ icon: "Scales",
71
+ types: [
72
+ "FrHasBrand",
73
+ "FrHasIndication",
74
+ "FrHasPut",
75
+ "FrMitm",
76
+ "FrAnsmProduct",
77
+ "FrPnds",
78
+ "FrPatientContribution",
79
+ "FrPatientAssociation",
80
+ "FrNationalAssemblySession",
81
+ ],
82
+ },
83
+ {
84
+ key: "drugs",
85
+ label: { fr: "Drugs", en: "Drugs" },
86
+ description: {
87
+ fr: "Ventes en ville et à l'hôpital, prix des marques.",
88
+ en: "Retail and hospital sales, brand prices.",
89
+ },
90
+ icon: "Pill",
91
+ types: ["FrMedicamBrand", "FrOutpatientBrand", "FrSusBrand", "FrRetrocessionBrand", "FrDrugPrice", "FrDrugPriceJo"],
92
+ },
93
+ {
94
+ key: "science",
95
+ label: { fr: "Augmented Science", en: "Augmented Science" },
96
+ description: {
97
+ fr: "Essais en France, sites, investigateurs, publications, appels à projets.",
98
+ en: "Trials in France, sites, investigators, publications, calls for projects.",
99
+ },
100
+ icon: "Flask",
101
+ // Les essais et les publications d'abord : les professionnels et les
102
+ // etablissements s'en deduisent.
103
+ types: ["ClinicalTrialsEUCT", "ClinicalTrialsNCT", "PubMed", "HCP", "Establishment", "PHRC"],
104
+ },
105
+ ];
106
+
107
+ /** Le libelle d'une famille, tel que les projets l'affichent. */
108
+ export function guidedFamilyLabel(type: string, lang: GuidedLang) {
109
+ return oipResourceSpec(type)?.kind.label[lang] ?? type;
110
+ }
111
+
112
+ /** Ou en est la recherche d'une famille. */
113
+ export interface GuidedFamilyState {
114
+ loading: boolean;
115
+ failed: boolean;
116
+ rows: GuidedRow[];
117
+ }
118
+
119
+ const index = (type: string) => oipResourceSpec(type)!.kind.index;
120
+ const cluster = (type: string) => oipResourceSpec(type)!.cluster;
121
+ const search = (type: string, body: Record<string, unknown>) => guidedHits(cluster(type), index(type), body);
122
+
123
+ const KIND_ORDER: Record<GuidedMatchKind, number> = { direct: 0, mention: 1, deduced: 2 };
124
+
125
+ /**
126
+ * Les familles que fr_drugs_app montre par marque (prix, ANSM...) : la revue
127
+ * les range de meme, une ligne par marque, depliable fiche par fiche. Une
128
+ * marque compte souvent des dizaines de presentations : leur liste va
129
+ * au-dela de LIMIT.
130
+ */
131
+ export const GUIDED_GROUPED_TYPES: Record<string, { fr: [string, string]; en: [string, string] }> = {
132
+ FrDrugPrice: { fr: ["présentation", "présentations"], en: ["presentation", "presentations"] },
133
+ FrDrugPriceJo: { fr: ["publication", "publications"], en: ["publication", "publications"] },
134
+ FrAnsmProduct: { fr: ["spécialité", "spécialités"], en: ["product", "products"] },
135
+ FrMitm: { fr: ["spécialité", "spécialités"], en: ["product", "products"] },
136
+ FrHasPut: { fr: ["autorisation", "autorisations"], en: ["authorisation", "authorisations"] },
137
+ FrHasIndication: { fr: ["indication", "indications"], en: ["indication", "indications"] },
138
+ };
139
+ const GROUPED_LIMIT = 500;
140
+
141
+ /** Une fiche trouvee par plusieurs sujets ne sort qu'une fois, sous sa meilleure correspondance. */
142
+ function merge(rows: GuidedRow[], limit = LIMIT) {
143
+ const byId = new Map<string, GuidedRow>();
144
+ for (const row of rows) {
145
+ const known = byId.get(row.id);
146
+ if (!known) byId.set(row.id, row);
147
+ else if (KIND_ORDER[row.kind] < KIND_ORDER[known.kind]) byId.set(row.id, { ...row, evidence: [...row.evidence, ...known.evidence] });
148
+ }
149
+ return [...byId.values()].sort((a, b) => KIND_ORDER[a.kind] - KIND_ORDER[b.kind]).slice(0, limit);
150
+ }
151
+
152
+ /** Lance la recherche de toutes les familles ; `onFamily` recoit chacune des qu'elle repond. */
153
+ export async function collectGuided(
154
+ subjects: GuidedSubject[],
155
+ lang: GuidedLang,
156
+ onFamily: (type: string, state: GuidedFamilyState) => void,
157
+ ) {
158
+ const t = (fr: string, en: string) => (lang === "en" ? en : fr);
159
+ const diseases = subjects.filter((subject) => subject.focus === "disease");
160
+ const molecules = subjects.filter((subject) => subject.focus === "molecule");
161
+ const brandSubjects = subjects.filter((subject) => subject.focus === "brand").map((subject) => subject.label.toUpperCase());
162
+
163
+ /** Pose une famille en chargement, puis sa reponse (ou son echec, sans rien casser). */
164
+ const run = async (type: string, task: () => Promise<GuidedRow[]>) => {
165
+ onFamily(type, { loading: true, failed: false, rows: [] });
166
+ try {
167
+ const rows = merge((await task()).filter((row) => row.id && row.title), type in GUIDED_GROUPED_TYPES ? GROUPED_LIMIT : LIMIT);
168
+ onFamily(type, { loading: false, failed: false, rows });
169
+ return rows;
170
+ } catch {
171
+ onFamily(type, { loading: false, failed: true, rows: [] });
172
+ return [];
173
+ }
174
+ };
175
+
176
+ // --- Pivot marque (fr_drugs_app) ---------------------------------------
177
+
178
+ const HAS_DISEASE_FIELDS = [
179
+ "brand_history.disease_name",
180
+ "brand_history.disease_name_en",
181
+ "brand_history.indication",
182
+ "brand_history.indication_en",
183
+ "brand_history.relevant_indication",
184
+ "brand_history.relevant_indication_en",
185
+ "brand_history.syn_indication",
186
+ "brand_history.syn_indication_en",
187
+ "brand_history.target_population",
188
+ "brand_history.target_population_en",
189
+ "brand_history.syn_target_pop",
190
+ ];
191
+ /** Une correspondance sur ces champs vaut « directe » : le reste n'est qu'une mention. */
192
+ const HAS_DIRECT = new Set(HAS_DISEASE_FIELDS.filter((field) => !/target_pop/.test(field)).concat(["brand_history.molecule", "brand_history.brand"]));
193
+
194
+ const contains = (field: string, term: string) => ({
195
+ regexp: { [`${field}.keyword`]: { value: `.*${escapeRegexp(term)}.*`, flags: "ALL", case_insensitive: true } },
196
+ });
197
+
198
+ /** La requete HAS d'un sujet ; le code d'une maladie part dans sa propre clause, nommee `code`. */
199
+ function hasQuery(subject: GuidedSubject) {
200
+ const innerHits = {
201
+ name: `opinions`,
202
+ size: 3,
203
+ _source: ["brand_history.brand", "brand_history.molecule", "brand_history.disease_name", "brand_history.has_code", "brand_history.decision_date"],
204
+ highlight: highlightOf(subject.focus === "disease" ? HAS_DISEASE_FIELDS : [`brand_history.${subject.focus}`]),
205
+ };
206
+ if (subject.focus === "disease") {
207
+ const byText = {
208
+ nested: {
209
+ path: "brand_history",
210
+ score_mode: "max",
211
+ inner_hits: innerHits,
212
+ query: {
213
+ bool: {
214
+ should: [
215
+ { multi_match: { query: subject.label, fields: ["brand_history.disease_name", "brand_history.disease_name_en"], type: "phrase", slop: 3, boost: 3 } },
216
+ textMatch(subject.label, HAS_DISEASE_FIELDS),
217
+ ],
218
+ minimum_should_match: 1,
219
+ },
220
+ },
221
+ },
222
+ };
223
+ if (!subject.code) return byText;
224
+ const byCode =
225
+ subject.system === "orpha"
226
+ ? [{ term: { "rare_diseases.orpha_code": Number(subject.code) } }, { term: { "rare_diseases_en.orpha_code": Number(subject.code) } }]
227
+ : [icd10Nested("oncology_tagging_fr", subject.code), icd10Nested("oncology_tagging_en", subject.code)];
228
+ return { bool: { should: [byText, { bool: { should: byCode, minimum_should_match: 1, _name: "code" } }], minimum_should_match: 1 } };
229
+ }
230
+ const field = `brand_history.${subject.focus}`;
231
+ return {
232
+ bool: {
233
+ should: [
234
+ ...(subject.focus === "brand" ? [contains("brand_group", subject.label), { match_phrase: { brand_group: subject.label } }] : []),
235
+ {
236
+ nested: {
237
+ path: "brand_history",
238
+ inner_hits: innerHits,
239
+ query: { bool: { should: [contains(field, subject.label), { match_phrase_prefix: { [field]: subject.label } }], minimum_should_match: 1 } },
240
+ },
241
+ },
242
+ ],
243
+ minimum_should_match: 1,
244
+ },
245
+ };
246
+ }
247
+
248
+ /** Les avis HAS d'un sujet, avec leurs marques et leurs contributions de patients. */
249
+ async function hasHitsOf(subject: GuidedSubject) {
250
+ const hits = await search("FrHasBrand", {
251
+ size: 30,
252
+ _source: [
253
+ "brand_group",
254
+ "brand_history.brand",
255
+ "brand_history.molecule",
256
+ "brand_history.disease_name",
257
+ "patient_contribution.contribution_url",
258
+ "patient_contribution.association_label_regroup",
259
+ ],
260
+ query: hasQuery(subject),
261
+ });
262
+ return hits.map((hit) => {
263
+ const opinions = hit.inner_hits?.opinions?.hits?.hits ?? [];
264
+ const matched = opinions.flatMap((opinion: any) => Object.keys(opinion.highlight ?? {}));
265
+ const direct = subject.focus === "brand" || (hit.matched_queries ?? []).includes("code") || matched.some((field: string) => HAS_DIRECT.has(field));
266
+ return { hit, subject, opinions, direct };
267
+ });
268
+ }
269
+
270
+ const hasTask = Promise.all(subjects.map((subject) => hasHitsOf(subject).catch(() => []))).then((lists) => lists.flat());
271
+
272
+ const hasRows = run("FrHasBrand", async () =>
273
+ (await hasTask).map(({ hit, opinions, direct }): GuidedRow => {
274
+ const history = list(hit._source?.brand_history);
275
+ return {
276
+ id: hit._id,
277
+ title: clean(hit._source?.brand_group) || hit._id,
278
+ subtitle: joinDot(
279
+ uniq(history.map((h: any) => h.molecule)).slice(0, 2).join(", "),
280
+ uniq(history.map((h: any) => h.disease_name)).slice(0, 2).join(", "),
281
+ ),
282
+ kind: direct ? "direct" : "mention",
283
+ evidence: opinions.map((opinion: any): GuidedEvidence => {
284
+ const o = opinion._source ?? {};
285
+ return {
286
+ label: joinDot(`${t("Avis", "Opinion")} ${clean(o.has_code)}`, o.decision_date),
287
+ values: [
288
+ ...uniq([o.disease_name]).map((value) => `${t("Maladie", "Disease")} : ${value}`),
289
+ ...uniq([o.molecule]).map((value) => `${t("Molécule", "Molecule")} : ${value}`),
290
+ ...highlightsOf(opinion),
291
+ ],
292
+ };
293
+ }),
294
+ source: hit._source ?? {},
295
+ };
296
+ }),
297
+ );
298
+
299
+ /** Les marques d'une molecule, lues dans le repertoire des marques. */
300
+ async function brandsOfMolecules() {
301
+ if (!molecules.length) return [];
302
+ const response = await guidedSearch("drugs", ES_INDEX.BRAND_DIRECTORY, {
303
+ size: 0,
304
+ query: {
305
+ bool: {
306
+ should: molecules.flatMap((molecule) => [
307
+ { match_phrase: { atc5_french_label: molecule.label } },
308
+ { match_phrase: { atc5_english_label: molecule.label } },
309
+ ]),
310
+ minimum_should_match: 1,
311
+ },
312
+ },
313
+ aggs: { brands: { terms: { field: "brand.keyword", size: 60 } } },
314
+ });
315
+ return (response?.aggregations?.brands?.buckets ?? []).map((bucket: any) => String(bucket.key).toUpperCase());
316
+ }
317
+
318
+ /** Les avis directs : leurs marques sont la cle des familles qui ne connaissent que la marque. */
319
+ const directHas = hasTask.then((rows) => rows.filter((row) => row.direct).map((row) => row.hit));
320
+
321
+ /**
322
+ * Pourquoi chaque marque est retenue, pour expliquer une fiche deduite
323
+ * (« WEGOVY : avis HAS CT-123 sur obesite, indication : ... »). Sans ca, la
324
+ * revue ne disait que « marque en commun », sans lien visible avec le sujet.
325
+ */
326
+ const brandReasons = new Map<string, string[]>();
327
+ const because = (brand: string, reason: string) => {
328
+ const key = brand.toUpperCase();
329
+ const known = brandReasons.get(key) ?? [];
330
+ // Deux raisons suffisent a comprendre ; au-dela la preuve se noie.
331
+ if (known.length < 2 && !known.includes(reason)) brandReasons.set(key, [...known, reason]);
332
+ };
333
+ const brandsOfHit = (hit: any) =>
334
+ uniq([...String(hit._source?.brand_group ?? "").split("+"), ...list(hit._source?.brand_history).map((h: any) => h.brand)]);
335
+
336
+ /** Les avis HAS d'ou vient chaque marque, et les marques qui tiennent sans avis (sujets, molecules). */
337
+ const brandHas = new Map<string, Set<string>>();
338
+ const fixedBrands = new Set<string>(brandSubjects);
339
+
340
+ const brandsTask = Promise.all([hasTask, brandsOfMolecules().catch(() => [] as string[])]).then(([rows, fromMolecules]) => {
341
+ for (const brand of fromMolecules) fixedBrands.add(brand.toUpperCase());
342
+ for (const { hit, direct } of rows) {
343
+ if (!direct) continue;
344
+ for (const brand of brandsOfHit(hit)) {
345
+ const key = brand.toUpperCase();
346
+ brandHas.set(key, (brandHas.get(key) ?? new Set()).add(hit._id));
347
+ }
348
+ }
349
+ for (const brand of brandSubjects) because(brand, t("Marque choisie comme sujet du projet", "Brand chosen as a subject of the project"));
350
+ for (const { hit, subject, opinions, direct } of rows) {
351
+ if (!direct) continue;
352
+ const opinion = opinions[0];
353
+ const o = opinion?._source ?? {};
354
+ const where = joinDot(`${t("Avis HAS", "HAS opinion")} ${clean(o.has_code)}`.trim(), o.decision_date);
355
+ const excerpt = highlightsOf(opinion)[0] || clean(o.disease_name) || (subject.code ? `${subject.system === "orpha" ? "ORPHA:" : "CIM-10 "}${subject.code}` : "");
356
+ const reason = `${where} ${t("sur", "on")} « ${subject.label} »${excerpt ? ` : ${excerpt}` : ""}`;
357
+ for (const brand of brandsOfHit(hit)) because(brand, reason);
358
+ }
359
+ const moleculeNames = molecules.map((molecule) => molecule.label).join(", ");
360
+ for (const brand of fromMolecules) because(brand, t(`Marque de la molécule ${moleculeNames}`, `Brand of the molecule ${moleculeNames}`));
361
+ return uniq([...brandSubjects, ...rows.filter((row) => row.direct).flatMap((row) => brandsOfHit(row.hit)), ...fromMolecules])
362
+ .map((brand) => brand.toUpperCase())
363
+ .slice(0, 80);
364
+ });
365
+
366
+ /** La marque partagee, et ce qui l'a fait retenir. */
367
+ const brandEvidence = (brands: string[]): GuidedEvidence[] =>
368
+ brands.map((brand) => ({
369
+ label: t(`Marque ${brand}, retenue pour`, `Brand ${brand}, kept for`),
370
+ values: brandReasons.get(brand.toUpperCase()) ?? [],
371
+ }));
372
+ const brandKind = (brands: string[]): GuidedMatchKind => (brands.some((brand) => brandSubjects.includes(brand)) ? "direct" : "deduced");
373
+ const shared = (values: unknown[], brands: string[]) => uniq(values).filter((value) => brands.includes(value.toUpperCase()));
374
+
375
+ /** Une fiche retrouvee par sa marque. */
376
+ /** Le lien d'une fiche deduite vers les avis HAS de ses marques. */
377
+ const viaOf = (brands: string[]) => ({
378
+ viaHas: uniq(brands.flatMap((brand) => [...(brandHas.get(brand.toUpperCase()) ?? [])])),
379
+ viaFixed: brands.some((brand) => fixedBrands.has(brand.toUpperCase())),
380
+ });
381
+
382
+ const fromBrands = (hit: any, brands: string[], title: string, subtitle = ""): GuidedRow => ({
383
+ ...viaOf(brands),
384
+ id: hit._id,
385
+ title,
386
+ subtitle,
387
+ kind: brandKind(brands),
388
+ evidence: brandEvidence(brands),
389
+ source: hit._source ?? {},
390
+ });
391
+
392
+ /**
393
+ * Une famille lue par ses marques ; une molecule la cherche aussi par ses
394
+ * propres champs (les generiques n'ont souvent pas d'avis HAS).
395
+ */
396
+ const byBrand =
397
+ (
398
+ type: string,
399
+ field: string,
400
+ fields: string[],
401
+ row: (s: any) => { title: string; subtitle?: string; groupHint?: string; date?: string },
402
+ moleculeFields: string[] = [],
403
+ ) =>
404
+ async () => {
405
+ const brands = await brandsTask;
406
+ const byMolecule = molecules.length > 0 && moleculeFields.length > 0;
407
+ if (!brands.length && !byMolecule) return [];
408
+ const clauses = [
409
+ ...(brands.length
410
+ ? [{ bool: { should: brands.map((brand) => ({ term: { [`${field}.keyword`]: { value: brand, case_insensitive: true } } })), minimum_should_match: 1 } }]
411
+ : []),
412
+ ...(byMolecule ? molecules.map((molecule) => textMatch(molecule.label, moleculeFields)) : []),
413
+ ];
414
+ const grouped = type in GUIDED_GROUPED_TYPES;
415
+ const hits = await search(type, {
416
+ size: grouped ? GROUPED_LIMIT : LIMIT,
417
+ _source: [...new Set([field, ...fields, ...moleculeFields])],
418
+ query: { bool: { should: clauses, minimum_should_match: 1 } },
419
+ ...(byMolecule ? { highlight: highlightOf(moleculeFields) } : {}),
420
+ });
421
+ return hits.map((hit): GuidedRow => {
422
+ const s = hit._source ?? {};
423
+ const { title, subtitle, groupHint, date } = row(s);
424
+ const extra = { ...(grouped ? { group: clean(s[field]).toUpperCase() || title } : {}), groupHint, date };
425
+ const common = shared([s[field]], brands);
426
+ if (common.length) return { ...fromBrands(hit, common, title, subtitle), ...extra };
427
+ return { id: hit._id, title, subtitle, kind: "direct", evidence: [{ label: t("Molécule", "Molecule"), values: highlightsOf(hit) }], source: s, ...extra };
428
+ });
429
+ };
430
+
431
+ /** « 2020-01 » en « janv. 2020 », une annee reste une annee. */
432
+ const periodLabel = (value: unknown) => {
433
+ const text = clean(value);
434
+ const month = text.match(/^(\d{4})-(\d{2})$/);
435
+ if (!month) return text;
436
+ return new Date(Number(month[1]), Number(month[2]) - 1, 1).toLocaleDateString(lang === "en" ? "en-GB" : "fr-FR", { month: "short", year: "numeric" });
437
+ };
438
+ /** « 2026-04-03 » en « 3 avr. 2026 ». */
439
+ const dayLabel = (value: unknown) => {
440
+ const text = clean(value);
441
+ const day = text.match(/^(\d{4})-(\d{2})-(\d{2})/);
442
+ if (!day) return text;
443
+ return new Date(Number(day[1]), Number(day[2]) - 1, Number(day[3])).toLocaleDateString(lang === "en" ? "en-GB" : "fr-FR", { day: "numeric", month: "short", year: "numeric" });
444
+ };
445
+
446
+ /** La periode couverte : l'element designe la marque et tout son historique, pas son dernier mois. */
447
+ const periodRange = (first: unknown, last: unknown) => {
448
+ const from = periodLabel(first);
449
+ const to = periodLabel(last);
450
+ if (!to) return "";
451
+ return from && from !== to ? t(`De ${from} à ${to}`, `From ${from} to ${to}`) : to;
452
+ };
453
+
454
+ /**
455
+ * Le document le plus recent de chaque marque (R-01) : ventes de ville et
456
+ * d'hopital. Il n'est qu'une ancre : la ligne dit toute la periode couverte.
457
+ */
458
+ const latestByBrand = (type: string, filter: Record<string, unknown>[], sortField: string) => async () => {
459
+ const brands = await brandsTask;
460
+ if (!brands.length) return [];
461
+ const response = await guidedSearch(cluster(type), index(type), {
462
+ size: 0,
463
+ query: { bool: { filter: [{ terms: { "code.keyword": brands } }, ...filter] } },
464
+ aggs: {
465
+ brand: {
466
+ terms: { field: "code.keyword", size: brands.length },
467
+ aggs: {
468
+ latest: { top_hits: { size: 1, _source: ["code", "period"], sort: [{ [sortField]: "asc" }] } },
469
+ earliest: { top_hits: { size: 1, _source: ["period"], sort: [{ [sortField]: "desc" }] } },
470
+ },
471
+ },
472
+ },
473
+ });
474
+ return (response?.aggregations?.brand?.buckets ?? [])
475
+ .filter((bucket: any) => bucket.latest?.hits?.hits?.[0])
476
+ .map((bucket: any) => {
477
+ const hit = bucket.latest.hits.hits[0];
478
+ const first = bucket.earliest?.hits?.hits?.[0]?._source?.period;
479
+ return fromBrands(hit, shared([hit._source?.code], brands), clean(hit._source?.code), periodRange(first, hit._source?.period));
480
+ });
481
+ };
482
+
483
+ const brandTasks: Record<string, () => Promise<GuidedRow[]>> = {
484
+ FrHasIndication: byBrand(
485
+ "FrHasIndication",
486
+ "brand",
487
+ ["indication_label_fr", "french_label", "atc5_fr"],
488
+ (s) => ({ title: clean(s.indication_label_fr) || clean(s.french_label), subtitle: clean(s.french_label), groupHint: clean(s.atc5_fr) }),
489
+ ["atc5_fr"],
490
+ ),
491
+ FrHasPut: byBrand(
492
+ "FrHasPut",
493
+ "brand",
494
+ ["aap_type_fr", "authorization_date", "dci"],
495
+ (s) => ({ title: joinDot(s.aap_type_fr, s.authorization_date) || uniq([s.brand]).join(", "), subtitle: clean(s.dci), groupHint: clean(s.dci), date: clean(s.authorization_date) }),
496
+ ["dci", "specialty_dci"],
497
+ ),
498
+ FrMitm: byBrand(
499
+ "FrMitm",
500
+ "brand",
501
+ ["cis_label", "atc5_french_code_label"],
502
+ (s) => ({ title: clean(s.cis_label) || clean(s.brand), groupHint: clean(s.atc5_french_code_label) }),
503
+ ["atc5_french_code_label"],
504
+ ),
505
+ FrAnsmProduct: byBrand(
506
+ "FrAnsmProduct",
507
+ "brand",
508
+ ["cis_label", "owner_regroup", "amm_status", "atc5_french_label"],
509
+ (s) => ({ title: clean(s.cis_label) || clean(s.brand), subtitle: clean(s.amm_status), groupHint: joinDot(s.atc5_french_label, s.owner_regroup) }),
510
+ ["atc5_french_code_label"],
511
+ ),
512
+ FrDrugPrice: byBrand(
513
+ "FrDrugPrice",
514
+ "brand",
515
+ ["label", "last_price_update", "molecule", "manufacturer"],
516
+ (s) => ({
517
+ title: clean(s.label) || clean(s.brand),
518
+ subtitle: s.last_price_update ? t(`Dernier prix : ${dayLabel(s.last_price_update)}`, `Latest price: ${dayLabel(s.last_price_update)}`) : "",
519
+ groupHint: joinDot(s.molecule, s.manufacturer),
520
+ date: clean(s.last_price_update),
521
+ }),
522
+ ["molecule"],
523
+ ),
524
+ FrDrugPriceJo: byBrand("FrDrugPriceJo", "brand", ["label", "jo", "update_date"], (s) => ({ title: clean(s.label) || clean(s.brand), subtitle: clean(s.jo), date: clean(s.update_date) })),
525
+ // Medic'AM : le mois le plus recent de la marque (`period_index` 0).
526
+ FrMedicamBrand: latestByBrand("FrMedicamBrand", [{ term: { period_interval: 1 } }], "period_index"),
527
+ // Liste en sus et retrocession : l'annee la plus recente de la marque.
528
+ FrSusBrand: latestByBrand(
529
+ "FrSusBrand",
530
+ [{ term: { "level.keyword": "brand" } }, { term: { "sector.keyword": "TOTAL" } }, { term: { "activity.keyword": "TOTAL" } }, { term: { analysis_type: 1 } }],
531
+ "period_index",
532
+ ),
533
+ FrRetrocessionBrand: latestByBrand("FrRetrocessionBrand", [{ term: { "level.keyword": "brand" } }], "period_index"),
534
+ // Le total national de la marque : l'`_id` se deduit, la requete verifie qu'il existe.
535
+ FrOutpatientBrand: async () => {
536
+ const brands = await brandsTask;
537
+ if (!brands.length) return [];
538
+ const years = Array.from({ length: 10 }, (_, index) => `value_public_price_p${index}`);
539
+ const hits = await search("FrOutpatientBrand", { size: brands.length, _source: ["code", "max_period", ...years], query: { ids: { values: brands.map((brand) => `${brand}_TOTAL`) } } });
540
+ return hits.map((hit) => {
541
+ // `p0` est l'annee `max_period`, `p1` la precedente... : la plus ancienne renseignee ouvre la periode.
542
+ const last = Number(hit._source?.max_period);
543
+ const depth = years.reduce((deepest, field, index) => (hit._source?.[field] != null ? index : deepest), 0);
544
+ const range = Number.isFinite(last) ? periodRange(last - depth, last) : clean(hit._source?.max_period);
545
+ return fromBrands(hit, shared([hit._source?.code], brands), clean(hit._source?.code), range);
546
+ });
547
+ },
548
+ // Les contributions de patients citees par les avis HAS directs.
549
+ FrPatientContribution: async () => {
550
+ const hits = await directHas;
551
+ const urls = uniq(hits.flatMap((hit: any) => list(hit._source?.patient_contribution).map((c: any) => c.contribution_url)));
552
+ if (!urls.length) return [];
553
+ const found = await search("FrPatientContribution", {
554
+ size: Math.min(urls.length, LIMIT),
555
+ _source: ["association_label_regroup", "has_code", "request_nature", "contribution_date", "contribution_url"],
556
+ query: { terms: { contribution_url: urls } },
557
+ collapse: { field: "contribution_url" },
558
+ });
559
+ return found.map((hit): GuidedRow => ({
560
+ id: hit._id,
561
+ title: joinDot(hit._source?.association_label_regroup, hit._source?.has_code),
562
+ subtitle: joinDot(hit._source?.request_nature, hit._source?.contribution_date),
563
+ kind: "deduced",
564
+ viaHas: hits.filter((has: any) => list(has._source?.patient_contribution).some((c: any) => c.contribution_url === hit._source?.contribution_url)).map((has: any) => has._id),
565
+ evidence: [{ label: t("Contribution citée par un avis HAS retenu", "Contribution cited by a kept HAS opinion"), values: [clean(hit._source?.has_code)] }],
566
+ source: hit._source ?? {},
567
+ }));
568
+ },
569
+ // L'`_id` de l'annuaire est le nom regroupe de l'association.
570
+ FrPatientAssociation: async () => {
571
+ const hits = await directHas;
572
+ const names = uniq(hits.flatMap((hit: any) => list(hit._source?.patient_contribution).map((c: any) => c.association_label_regroup)));
573
+ if (!names.length) return [];
574
+ const found = await search("FrPatientAssociation", { size: Math.min(names.length, LIMIT), _source: ["association_label_regroup"], query: { ids: { values: names } } });
575
+ return found.map((hit): GuidedRow => ({
576
+ id: hit._id,
577
+ title: clean(hit._source?.association_label_regroup) || hit._id,
578
+ kind: "deduced",
579
+ viaHas: hits.filter((has: any) => list(has._source?.patient_contribution).some((c: any) => c.association_label_regroup === hit._id)).map((has: any) => has._id),
580
+ evidence: [{ label: t("A contribué à un avis HAS retenu", "Contributed to a kept HAS opinion"), values: [hit._id] }],
581
+ source: hit._source ?? {},
582
+ }));
583
+ },
584
+ // Les PNDS ne se rattachent a aucune marque : seule une maladie les trouve.
585
+ FrPnds: async () => {
586
+ if (!diseases.length) return [];
587
+ const fields = ["pathology_fr", "pathology_en", "rare_diseases_fr.disease_name", "rare_diseases_en.disease_name", "rare_diseases_fr.disease_synonyms", "rare_diseases_en.disease_synonyms"];
588
+ const hits = await search("FrPnds", {
589
+ size: 20,
590
+ _source: ["pathology_fr", "protocol_date"],
591
+ query: { bool: { should: diseases.map((disease) => textMatch(disease.label, fields)), minimum_should_match: 1 } },
592
+ highlight: highlightOf(fields),
593
+ });
594
+ return hits.map((hit): GuidedRow => ({
595
+ id: hit._id,
596
+ title: clean(hit._source?.pathology_fr),
597
+ subtitle: clean(hit._source?.protocol_date),
598
+ kind: "direct",
599
+ evidence: [{ label: t("Pathologie", "Condition"), values: highlightsOf(hit) }],
600
+ source: hit._source ?? {},
601
+ }));
602
+ },
603
+ // Le texte complet du compte rendu : un sujet s'y dit en seance sans figurer a l'ordre du jour.
604
+ FrNationalAssemblySession: async () => {
605
+ const hits = await search("FrNationalAssemblySession", {
606
+ size: 20,
607
+ _source: ["agenda", "session_date"],
608
+ query: { bool: { should: subjects.map((subject) => textMatch(subject.label, ["document_text", "agenda"])), minimum_should_match: 1 } },
609
+ highlight: highlightOf(["agenda", "document_text"]),
610
+ });
611
+ return hits.map((hit): GuidedRow => ({
612
+ id: hit._id,
613
+ title: clean(hit._source?.agenda),
614
+ subtitle: clean(hit._source?.session_date),
615
+ kind: "direct",
616
+ evidence: [{ label: t("Compte rendu", "Transcript"), values: highlightsOf(hit) }],
617
+ source: hit._source ?? {},
618
+ }));
619
+ },
620
+ };
621
+
622
+ // --- Pivot essai (France Augmented Science) ----------------------------
623
+
624
+ /** Les libelles tagues qui portent le code de la maladie. */
625
+ function codeLabels(source: any, disease: GuidedSubject) {
626
+ if (!disease.code) return [];
627
+ if (disease.system === "orpha") {
628
+ return uniq(list(source?.rare_diseases).filter((tag) => String(tag?.orpha_code) === disease.code).map((tag) => tag.concat_disease_name_orpha_code));
629
+ }
630
+ const code = disease.code.replace(".", "").toUpperCase();
631
+ return uniq(
632
+ list(source?.diseases)
633
+ .flatMap((entry) => list(entry?.icd10))
634
+ .filter((tag) => String(tag?.icd_code ?? "").replace(".", "").toUpperCase().startsWith(code))
635
+ .map((tag) => tag.combined_label || tag.icd_code),
636
+ );
637
+ }
638
+
639
+ /** Les essais d'un sujet, en France. Clauses nommees : `condition`, `code`, `intervention` (direct), `text` (mention). */
640
+ async function trialsOf(type: "ClinicalTrialsNCT" | "ClinicalTrialsEUCT", subject: GuidedSubject): Promise<GuidedRow[]> {
641
+ const nct = type === "ClinicalTrialsNCT";
642
+ const onDisease = subject.focus === "disease";
643
+ const conditionFields = nct ? ["conditions.condition_name_fr", "conditions.condition_name_en"] : ["medical_condition.condition_name_en"];
644
+ const interventionFields = nct
645
+ ? ["intervention.intervention_name", "intervention.intervention_other_name"]
646
+ : ["products.productDictionaryInfo.activeSubstanceName", "products.productDictionaryInfo.prodName", "products.productDictionaryInfo.productOtherName"];
647
+ const titleFields = nct ? ["official_title", "brief_title"] : ["public_title", "full_title"];
648
+ const matchFields = onDisease ? conditionFields : interventionFields;
649
+ const matchName = onDisease ? "condition" : "intervention";
650
+
651
+ const code =
652
+ onDisease && subject.code
653
+ ? subject.system === "orpha"
654
+ ? nct
655
+ ? { nested: { path: "rare_diseases", query: { term: { "rare_diseases.orpha_code.keyword": subject.code } }, _name: "code" } }
656
+ : { term: { "rare_diseases.orpha_code": { value: subject.code, _name: "code" } } }
657
+ : nct
658
+ ? { nested: { ...icd10Nested("diseases", subject.code).nested, _name: "code" } }
659
+ : { bool: { should: [icdPrefix("diseases.icd10.icd_code", subject.code)], _name: "code" } }
660
+ : null;
661
+ const condition = nct
662
+ ? {
663
+ nested: {
664
+ path: onDisease ? "conditions" : "intervention",
665
+ query: textMatch(subject.label, matchFields),
666
+ _name: matchName,
667
+ inner_hits: { name: matchName, size: 3, _source: false, highlight: highlightOf(matchFields) },
668
+ },
669
+ }
670
+ : { bool: { ...textMatch(subject.label, matchFields).bool, _name: matchName } };
671
+ const france = nct
672
+ ? { nested: { path: "countries", query: { term: { "countries.countries_name.keyword": "France" } } } }
673
+ : { term: { "countries.country_name.keyword": "France" } };
674
+
675
+ const hits = await search(type, {
676
+ size: 50,
677
+ sort: [{ _score: "desc" }, { [nct ? "study_first_posted_date" : "first_submitted_date"]: { order: "desc", unmapped_type: "date" } }],
678
+ _source: [
679
+ ...(nct ? ["nct_id", "brief_title", "official_title", "overall_status", "phase"] : ["euct_number", "public_title", "global_status", "trial_phase"]),
680
+ "diseases.icd10.icd_code",
681
+ "diseases.icd10.combined_label",
682
+ "rare_diseases.orpha_code",
683
+ "rare_diseases.concat_disease_name_orpha_code",
684
+ ],
685
+ query: {
686
+ bool: {
687
+ filter: [france],
688
+ should: [condition, { bool: { ...textMatch(subject.label, titleFields).bool, _name: "text" } }, ...(code ? [code] : [])],
689
+ minimum_should_match: 1,
690
+ },
691
+ },
692
+ highlight: highlightOf(nct ? titleFields : [...titleFields, ...matchFields]),
693
+ });
694
+
695
+ return hits.map((hit): GuidedRow => {
696
+ const s = hit._source ?? {};
697
+ const named: string[] = hit.matched_queries ?? [];
698
+ const trialId = clean(nct ? s.nct_id : s.euct_number) || hit._id;
699
+ const matched = nct
700
+ ? uniq((hit.inner_hits?.[matchName]?.hits?.hits ?? []).flatMap((inner: any) => highlightsOf(inner, matchFields)))
701
+ : highlightsOf(hit, matchFields);
702
+ return {
703
+ id: hit._id,
704
+ title: clean(nct ? s.brief_title || s.official_title : s.public_title) || trialId,
705
+ subtitle: joinDot(trialId, nct ? s.overall_status : s.global_status, nct ? s.phase : s.trial_phase),
706
+ kind: named.some((name) => ["condition", "code", "intervention"].includes(name)) ? "direct" : "mention",
707
+ evidence: [
708
+ { label: t("Code de la maladie tagué dans l'essai", "Disease code tagged in the trial"), values: named.includes("code") ? codeLabels(s, subject) : [] },
709
+ { label: t("Pathologies déclarées", "Declared conditions"), values: named.includes("condition") ? matched : [] },
710
+ { label: t("Traitements étudiés", "Studied treatments"), values: named.includes("intervention") ? matched : [] },
711
+ { label: t("Titre", "Title"), values: named.includes("text") ? highlightsOf(hit, titleFields) : [] },
712
+ ].filter((group) => group.values.length),
713
+ source: { ...s, trialId },
714
+ };
715
+ });
716
+ }
717
+
718
+ const trialRows = (type: "ClinicalTrialsNCT" | "ClinicalTrialsEUCT") =>
719
+ run(type, async () => (await Promise.all(subjects.map((subject) => trialsOf(type, subject).catch(() => [])))).flat());
720
+
721
+ const nctRows = trialRows("ClinicalTrialsNCT");
722
+ const euctRows = trialRows("ClinicalTrialsEUCT");
723
+
724
+ /** Les essais directs : la cle des sites, des investigateurs, des publications et des PHRC. */
725
+ const keptTrials = Promise.all([nctRows, euctRows]).then(([nct, euct]) => {
726
+ const ids = (rows: GuidedRow[]) => rows.filter((row) => row.kind === "direct").map((row) => clean(row.source.trialId) || row.id);
727
+ const titles: Record<string, string> = {};
728
+ for (const row of [...nct, ...euct]) titles[clean(row.source.trialId) || row.id] = row.title;
729
+ return { nct: ids(nct), euct: ids(euct), titles };
730
+ });
731
+
732
+ /** Les index de Tekkare Matching : un document par essai, ses sites FINESS et ses investigateurs RPPS. */
733
+ const scienceIndex = (key: "hcoNct" | "hcoEuct" | "hcpNct" | "hcpEuct") => scienceIndexConfig[key].index;
734
+
735
+ /** Les sites ou investigateurs des essais retenus, regroupes par code, les plus investis d'abord. */
736
+ async function actors(field: "hco" | "hcp") {
737
+ const kept = await keptTrials;
738
+ const indexes = field === "hco" ? { nct: scienceIndex("hcoNct"), euct: scienceIndex("hcoEuct") } : { nct: scienceIndex("hcpNct"), euct: scienceIndex("hcpEuct") };
739
+ const docs = (
740
+ await Promise.all(
741
+ (["nct", "euct"] as const)
742
+ .filter((source) => kept[source].length)
743
+ .map((source) => guidedHits("science", indexes[source], { size: kept[source].length, _source: ["clinical_trial_id", field], query: { ids: { values: kept[source] } } })),
744
+ )
745
+ ).flat();
746
+ const byCode = new Map<string, { actor: any; trials: Set<string>; names: Set<string> }>();
747
+ for (const doc of docs) {
748
+ const trialId = clean(doc._source?.clinical_trial_id) || doc._id;
749
+ for (const actor of list(doc._source?.[field])) {
750
+ const code = clean(field === "hco" ? actor?.hco_et_code : actor?.hcp_code);
751
+ if (!code) continue;
752
+ const known = byCode.get(code) ?? { actor, trials: new Set<string>(), names: new Set<string>() };
753
+ known.trials.add(trialId);
754
+ const name = clean(field === "hco" ? actor.name : actor.hcp_full_name);
755
+ if (name) known.names.add(name);
756
+ byCode.set(code, known);
757
+ }
758
+ }
759
+ return { kept, ranked: [...byCode].sort((a, b) => b[1].trials.size - a[1].trials.size) };
760
+ }
761
+
762
+ const trialLine = (titles: Record<string, string>, id: string) => (titles[id] ? `${titles[id]} (${id})` : id);
763
+
764
+ /** « Obesity, Wegovy » : les sujets, pour dire sur quoi portent les essais retenus. */
765
+ const subjectNames = subjects.map((subject) => subject.label).join(", ");
766
+
767
+ /**
768
+ * La preuve d'un site ou d'un investigateur : combien d'essais du sujet il
769
+ * porte (les cinq premiers, puis le compte), et sous quel nom l'essai le
770
+ * cite avant le rapprochement FINESS ou RPPS.
771
+ */
772
+ function actorEvidence(role: "site" | "investigator", trials: Set<string>, names: Set<string>, titles: Record<string, string>, code: string): GuidedEvidence[] {
773
+ const ids = [...trials];
774
+ const lines = ids.slice(0, 5).map((id) => trialLine(titles, id));
775
+ if (ids.length > 5) lines.push(t(`et ${ids.length - 5} autres`, `and ${ids.length - 5} more`));
776
+ const count = ids.length;
777
+ const label =
778
+ role === "site"
779
+ ? t(`Site de ${count} essai${count > 1 ? "s" : ""} en France sur « ${subjectNames} »`, `Site of ${count} trial${count > 1 ? "s" : ""} in France on "${subjectNames}"`)
780
+ : t(`Investigateur dans ${count} essai${count > 1 ? "s" : ""} en France sur « ${subjectNames} »`, `Investigator in ${count} trial${count > 1 ? "s" : ""} in France on "${subjectNames}"`);
781
+ return [
782
+ { label, values: lines },
783
+ {
784
+ label: role === "site" ? t(`Cité dans les essais sous le nom, rapproché du FINESS ${code}`, `Named in the trials as, matched to FINESS ${code}`) : t(`Cité dans les essais sous le nom, rapproché du RPPS ${code}`, `Named in the trials as, matched to RPPS ${code}`),
785
+ values: [...names],
786
+ },
787
+ ].filter((group) => group.values.length);
788
+ }
789
+
790
+ const actorCount = (role: "site" | "investigator", count: number) =>
791
+ role === "site"
792
+ ? t(`${count} essai${count > 1 ? "s" : ""} du sujet`, `${count} trial${count > 1 ? "s" : ""} on the subject`)
793
+ : t(`investigateur dans ${count} essai${count > 1 ? "s" : ""}`, `investigator in ${count} trial${count > 1 ? "s" : ""}`);
794
+
795
+ /** Les `_id` presents dans l'annuaire : l'API refuse un element qu'elle ne retrouve pas. */
796
+ async function existing(type: string, ids: string[]) {
797
+ if (!ids.length) return new Set<string>();
798
+ const hits = await search(type, { size: ids.length, _source: false, query: { ids: { values: ids } } });
799
+ return new Set(hits.map((hit) => String(hit._id)));
800
+ }
801
+
802
+ const hcpId = (code: string) => oipResourceSpec("HCP")?.fromRouteId?.(code) ?? `10_${code}`;
803
+
804
+ const establishmentRows = run("Establishment", async () => {
805
+ const { kept, ranked } = await actors("hco");
806
+ const found = await existing("Establishment", ranked.map(([code]) => code));
807
+ return ranked
808
+ .filter(([code]) => found.has(code))
809
+ .slice(0, LIMIT)
810
+ .map(([code, { actor, trials, names }]): GuidedRow => ({
811
+ id: code,
812
+ title: clean(actor.hco_et_label) || clean(actor.name) || code,
813
+ subtitle: joinDot(actorCount("site", trials.size), actor.hco_et_city, actor.hco_et_dpt_label),
814
+ kind: "deduced",
815
+ evidence: actorEvidence("site", trials, names, kept.titles, code),
816
+ source: { hco_et_code: code },
817
+ }));
818
+ });
819
+
820
+ const hcpRows = run("HCP", async () => {
821
+ const { kept, ranked } = await actors("hcp");
822
+ const found = await existing("HCP", ranked.map(([code]) => hcpId(code)));
823
+ return ranked
824
+ .filter(([code]) => found.has(hcpId(code)))
825
+ .slice(0, LIMIT)
826
+ .map(([code, { actor, trials, names }]): GuidedRow => {
827
+ const specialty = list(actor.specialty).find((entry) => entry?.hcp_specialty_type === "PRINCIPAL") ?? list(actor.specialty)[0];
828
+ const name = clean(actor.hcp_full_name) || `${clean(actor.hcp_first_name)} ${clean(actor.hcp_family_name)}`.trim();
829
+ return {
830
+ id: hcpId(code),
831
+ title: name || code,
832
+ subtitle: joinDot(actorCount("investigator", trials.size), specialty?.hcp_specialty_label_regroup, list(actor.address)[0]?.hcp_city),
833
+ kind: "deduced",
834
+ evidence: actorEvidence("investigator", trials, names, kept.titles, code),
835
+ source: { hcp_code: code },
836
+ };
837
+ });
838
+ });
839
+
840
+ /** Le sujet dans une publication : code ou titre pour une maladie, titre et substances pour le reste. */
841
+ const publicationSubject = {
842
+ bool: {
843
+ should: subjects.flatMap((subject): Record<string, unknown>[] =>
844
+ subject.focus === "disease"
845
+ ? [
846
+ textMatch(subject.label, ["title"]),
847
+ ...(subject.code
848
+ ? [
849
+ subject.system === "orpha"
850
+ ? { nested: { path: "rare_diseases", query: { term: { "rare_diseases.orpha_code.keyword": subject.code } } } }
851
+ : { nested: { path: "diseases.icd10", query: icdPrefix("diseases.icd10.icd_code.keyword", subject.code) } },
852
+ ]
853
+ : []),
854
+ ]
855
+ : [textMatch(subject.label, ["title", "chemical_list"]), { nested: { path: "molecules", query: textMatch(subject.label, ["molecules.label"]) } }],
856
+ ),
857
+ minimum_should_match: 1,
858
+ },
859
+ };
860
+
861
+ const publicationRows = run("PubMed", async () => {
862
+ const [kept, hcps] = await Promise.all([keptTrials, hcpRows]);
863
+ const hcpNames = Object.fromEntries(hcps.map((row) => [clean(row.source.hcp_code), row.title]));
864
+ const hcpCodes = Object.keys(hcpNames);
865
+ const should: Record<string, unknown>[] = [];
866
+ if (kept.nct.length || kept.euct.length) {
867
+ should.push({
868
+ constant_score: {
869
+ filter: {
870
+ bool: {
871
+ should: [
872
+ ...(kept.nct.length ? [{ terms: { "nct_ids.keyword": kept.nct } }] : []),
873
+ ...(kept.euct.length ? [{ terms: { "euct_ids.keyword": kept.euct } }] : []),
874
+ ],
875
+ minimum_should_match: 1,
876
+ _name: "trial",
877
+ },
878
+ },
879
+ boost: 3,
880
+ },
881
+ });
882
+ }
883
+ if (hcpCodes.length) {
884
+ should.push({
885
+ constant_score: {
886
+ filter: { bool: { filter: [{ nested: { path: "authors", query: { terms: { "authors.hcp_code.keyword": hcpCodes } } } }, publicationSubject], _name: "author" } },
887
+ boost: 2,
888
+ },
889
+ });
890
+ }
891
+ // Un auteur francais (RPPS connu) sur le sujet.
892
+ should.push({
893
+ constant_score: {
894
+ filter: { bool: { filter: [publicationSubject, { nested: { path: "authors", query: { exists: { field: "authors.hcp_code" } } } }], _name: "subject" } },
895
+ boost: 1,
896
+ },
897
+ });
898
+ const hits = await search("PubMed", {
899
+ size: LIMIT,
900
+ sort: [{ _score: "desc" }, { pubdate: { order: "desc", unmapped_type: "date" } }],
901
+ _source: ["PubMed_ID", "title", "pubdate", "journal", "nct_ids", "euct_ids", "authors.hcp_code", "diseases.icd10.icd_code", "diseases.icd10.combined_label", "rare_diseases.orpha_code", "rare_diseases.concat_disease_name_orpha_code"],
902
+ query: { bool: { should, minimum_should_match: 1 } },
903
+ highlight: highlightOf(["title", "chemical_list"]),
904
+ });
905
+ const keptIds = new Set([...kept.nct, ...kept.euct]);
906
+ return hits.map((hit): GuidedRow => {
907
+ const s = hit._source ?? {};
908
+ const named: string[] = hit.matched_queries ?? [];
909
+ const cited = uniq([...list(s.nct_ids), ...list(s.euct_ids)].map(String)).filter((id) => keptIds.has(id));
910
+ const authors = uniq(list(s.authors).map((author) => hcpNames[clean(author?.hcp_code)]));
911
+ const pmid = clean(s.PubMed_ID) || hit._id;
912
+ return {
913
+ id: hit._id,
914
+ title: clean(s.title) || `PMID ${pmid}`,
915
+ subtitle: joinDot(`PMID ${pmid}`, s.journal, clean(s.pubdate).slice(0, 10)),
916
+ kind: named.includes("trial") || named.includes("author") ? "deduced" : "direct",
917
+ evidence: [
918
+ { label: t("Cite les essais retenus", "Cites the kept trials"), values: named.includes("trial") ? cited.map((id) => trialLine(kept.titles, id)) : [] },
919
+ { label: t("Auteurs parmi les investigateurs retenus", "Authors among the kept investigators"), values: named.includes("author") ? authors : [] },
920
+ {
921
+ label: t("Le sujet dans la publication", "The subject in the publication"),
922
+ values: uniq([...highlightsOf(hit, ["title", "chemical_list"]), ...diseases.flatMap((disease) => codeLabels(s, disease))]),
923
+ },
924
+ ].filter((group) => group.values.length),
925
+ source: s,
926
+ };
927
+ });
928
+ });
929
+
930
+ const callRows = run("PHRC", async () => {
931
+ const [kept, hcps] = await Promise.all([keptTrials, hcpRows]);
932
+ const hcpNames = Object.fromEntries(hcps.map((row) => [clean(row.source.hcp_code), row.title]));
933
+ const hcpCodes = Object.keys(hcpNames);
934
+ const subject = {
935
+ bool: {
936
+ should: subjects.flatMap((entry) => [
937
+ textMatch(entry.label, ["title_fr", "title_en"]),
938
+ ...(entry.focus === "disease" && entry.code && entry.system === "orpha" ? [{ term: { "rare_diseases_fr.orpha_code": Number(entry.code) } }] : []),
939
+ ]),
940
+ minimum_should_match: 1,
941
+ },
942
+ };
943
+ const should: Record<string, unknown>[] = [{ bool: { filter: [subject], _name: "subject" } }];
944
+ if (kept.nct.length) should.push({ constant_score: { filter: { terms: { "nct_number.keyword": kept.nct, _name: "trial" } }, boost: 3 } });
945
+ if (hcpCodes.length) should.push({ constant_score: { filter: { bool: { filter: [{ terms: { "hcp_code.keyword": hcpCodes } }, subject], _name: "author" } }, boost: 2 } });
946
+ const hits = await search("PHRC", {
947
+ size: LIMIT,
948
+ sort: [{ _score: "desc" }, { period: { order: "desc", unmapped_type: "long" } }],
949
+ _source: ["title_fr", "acronym", "period", "hco_et_label", "nct_number", "hcp_code", "rare_diseases_fr.concat_disease_name_orpha_code"],
950
+ query: { bool: { should, minimum_should_match: 1 } },
951
+ highlight: highlightOf(["title_fr", "title_en"]),
952
+ });
953
+ return hits.map((hit): GuidedRow => {
954
+ const s = hit._source ?? {};
955
+ const named: string[] = hit.matched_queries ?? [];
956
+ return {
957
+ id: hit._id,
958
+ title: clean(s.title_fr) || clean(s.acronym) || hit._id,
959
+ subtitle: joinDot(s.acronym, s.hco_et_label, s.period),
960
+ kind: named.includes("trial") || named.includes("author") ? "deduced" : "direct",
961
+ evidence: [
962
+ { label: t("Lié à un essai retenu", "Linked to a kept trial"), values: named.includes("trial") ? [trialLine(kept.titles, clean(s.nct_number))] : [] },
963
+ { label: t("Porté par un investigateur retenu", "Led by a kept investigator"), values: named.includes("author") ? uniq([hcpNames[clean(s.hcp_code)]]) : [] },
964
+ {
965
+ label: t("Le sujet dans l'appel à projets", "The subject in the call for projects"),
966
+ values: named.includes("subject") ? uniq([...highlightsOf(hit, ["title_fr", "title_en"]), ...list(s.rare_diseases_fr).map((tag) => tag?.concat_disease_name_orpha_code)]) : [],
967
+ },
968
+ ].filter((group) => group.values.length),
969
+ source: s,
970
+ };
971
+ });
972
+ });
973
+
974
+ await Promise.all([
975
+ hasRows,
976
+ ...Object.entries(brandTasks).map(([type, task]) => run(type, task)),
977
+ nctRows,
978
+ euctRows,
979
+ establishmentRows,
980
+ hcpRows,
981
+ publicationRows,
982
+ callRows,
983
+ ]);
984
+ }