// Mirrors backend/app/screening_logic.py: how screening entries become a // final decision per paper and stage. The backend is the authority (PRISMA // counts, synthesis); this copy drives what the screening board shows. import type { ScreeningRecordEntry, ScreeningStage } from "../types"; export type StageState = "single" | "pending" | "awaiting_second" | "agreed" | "conflict" | "adjudicated"; export interface StageStatus { state: StageState; final?: ScreeningRecordEntry; /** Latest review entry per reviewer (dual mode). */ byReviewer: Map; } export function reviewerKey(name: string): string { return name.split(/\s+/).filter(Boolean).join(" ").toLowerCase(); } function reasonKey(r: ScreeningRecordEntry): string { return (r.reason_category || r.reason || "").trim().toLowerCase(); } function allAgree(entries: ScreeningRecordEntry[], stage: ScreeningStage): boolean { if (new Set(entries.map((e) => e.decision)).size !== 1) return false; if (stage === "full_text" && entries[0].decision === "exclude") { return new Set(entries.map(reasonKey)).size === 1; } return true; } export function stageStatus( history: ScreeningRecordEntry[], paperId: string, stage: ScreeningStage, reviewersRequired: number ): StageStatus { const entries = history .filter((r) => r.paper_id === paperId && r.stage === stage) .sort((a, b) => a.decided_at.localeCompare(b.decided_at)); if (reviewersRequired <= 1) { const last = entries[entries.length - 1]; return { state: last ? "single" : "pending", final: last, byReviewer: new Map() }; } const byReviewer = new Map(); let adjudication: ScreeningRecordEntry | undefined; for (const r of entries) { if ((r.role ?? "review") === "adjudication") adjudication = r; else byReviewer.set(reviewerKey(r.reviewer), r); } const reviews = [...byReviewer.values()]; const latestReviewAt = reviews.reduce( (max, r) => (max === null || r.decided_at > max ? r.decided_at : max), null ); if (adjudication && (latestReviewAt === null || adjudication.decided_at >= latestReviewAt)) { return { state: "adjudicated", final: adjudication, byReviewer }; } if (reviews.length === 0) return { state: "pending", byReviewer }; if (reviews.length < 2) return { state: "awaiting_second", byReviewer }; if (allAgree(reviews, stage)) { const first = [...reviews].sort((a, b) => a.decided_at.localeCompare(b.decided_at))[0]; return { state: "agreed", final: first, byReviewer }; } return { state: "conflict", byReviewer }; } /** True when the paper's final decision at both stages is include. */ export function isFinallyIncluded( history: ScreeningRecordEntry[], paperId: string, reviewersRequired: number ): boolean { return ( stageStatus(history, paperId, "title_abstract", reviewersRequired).final?.decision === "include" && stageStatus(history, paperId, "full_text", reviewersRequired).final?.decision === "include" ); }