// Display-only preview of the search strategy the backend will build // (backend/app/search.py is the authority). Mirrors its rules: terms within a // group are OR-ed, groups are AND-ed, an empty group falls back to its // protocol field, and protocols with no terms at all use the legacy query. import type { ExtractionRecordEntry, ScreeningRecordEntry } from "../types"; import { isFinallyIncluded } from "./screeningStatus"; const PARENTHETICAL = /\([^)]*\)/g; function fieldAsTerm(text: string): string[] { const phrase = text.replace(PARENTHETICAL, "").replace(/"/g, " ").split(/\s+/).filter(Boolean).join(" "); return phrase ? [phrase] : []; } export function describeSearchStrategy( intervention: string, outcome: string, interventionTerms: string[] | undefined, outcomeTerms: string[] | undefined ): { mode: "search_terms" | "legacy_free_text"; text: string } { const exp = interventionTerms ?? []; const out = outcomeTerms ?? []; if (exp.length === 0 && out.length === 0) { const legacy = `${intervention} ${outcome}`.replace(PARENTHETICAL, "").trim(); return { mode: "legacy_free_text", text: legacy }; } const groups = [exp.length ? exp : fieldAsTerm(intervention), out.length ? out : fieldAsTerm(outcome)].filter( (g) => g.length > 0 ); const text = groups.map((g) => "(" + g.map((t) => `"${t}"`).join(" OR ") + ")").join(" AND "); return { mode: "search_terms", text: `${text} — title/abstract` }; } /** Latest extraction per paper whose final title/abstract AND full-text * decisions are both "include" — mirrors backend prisma.latest_extractions_for_included. */ export function extractionsForIncludedPapers( extractions: ExtractionRecordEntry[], history: ScreeningRecordEntry[], reviewersRequired = 1 ): ExtractionRecordEntry[] { const latest = new Map(); [...extractions] .sort((a, b) => a.extracted_at.localeCompare(b.extracted_at)) .forEach((e) => { if (isFinallyIncluded(history, e.paper_id, reviewersRequired)) latest.set(e.paper_id, e); }); return [...latest.values()]; }