File size: 12,002 Bytes
5091a04
 
 
 
 
 
 
 
 
 
 
 
 
dcc1b84
5091a04
 
 
 
 
 
 
 
 
 
dcc1b84
5091a04
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dcc1b84
5091a04
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dcc1b84
5091a04
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dcc1b84
 
 
 
 
5091a04
 
 
 
 
 
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
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
import { useState } from "react";
import { recordExtraction, recordScreeningDecision } from "../api/protocols";
import type {
  ExtractionRecordEntry,
  ScreeningDecisionValue,
  ScreeningRecordEntry,
  ScreeningStage,
  SearchResultItem,
} from "../types";
import { OTHER_REASON, exclusionReasonPayload } from "../utils/exclusionReasons";
import { reviewerKey, stageStatus, type StageStatus } from "../utils/screeningStatus";
import { ExtractionForm } from "./ExtractionForm";
import { ReasonPicker } from "./ReasonPicker";
import { ExtractionList } from "./ExtractionList";
import type { ReasonOptions } from "./ScreeningBoard";
import "./review-fixes.css";

interface DualScreeningRowProps {
  protocolId: string;
  paper: SearchResultItem;
  reviewer: string;
  screeningHistory: ScreeningRecordEntry[];
  extractionRecords: ExtractionRecordEntry[];
  reasonOptions: ReasonOptions;
  defaultOutcome?: string;
  onRefresh: () => Promise<void>;
}

type Action =
  | { kind: "decide"; stage: ScreeningStage; decision: ScreeningDecisionValue }
  | { kind: "resolve"; stage: ScreeningStage };

const STAGE_LABEL: Record<ScreeningStage, string> = {
  title_abstract: "Title/abstract",
  full_text: "Full text",
};

function decisionText(r: ScreeningRecordEntry): string {
  return r.decision === "include" ? "Included" : `Excluded β€” ${r.reason ?? "no reason recorded"}`;
}

export function DualScreeningRow({
  protocolId,
  paper,
  reviewer,
  screeningHistory,
  extractionRecords,
  reasonOptions,
  defaultOutcome = "",
  onRefresh,
}: DualScreeningRowProps) {
  const [action, setAction] = useState<Action | null>(null);
  const [revising, setRevising] = useState<ScreeningStage | null>(null);
  const [reasonChoice, setReasonChoice] = useState("");
  const [reasonNote, setReasonNote] = useState("");
  const [resolveDecision, setResolveDecision] = useState<ScreeningDecisionValue | "">("");
  const [resolveNote, setResolveNote] = useState("");
  const [showExtraction, setShowExtraction] = useState(false);
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const me = reviewerKey(reviewer);
  const ta = stageStatus(screeningHistory, paper.id, "title_abstract", 2);
  const ft =
    ta.final?.decision === "include"
      ? stageStatus(screeningHistory, paper.id, "full_text", 2)
      : undefined;
  const extraction = extractionRecords
    .filter((r) => r.paper_id === paper.id)
    .sort((a, b) => b.extracted_at.localeCompare(a.extracted_at))[0];

  function resetForms() {
    setAction(null);
    setRevising(null);
    setReasonChoice("");
    setReasonNote("");
    setResolveDecision("");
    setResolveNote("");
    setError(null);
  }

  async function submit(stage: ScreeningStage, decision: ScreeningDecisionValue, adjudication: boolean) {
    setError(null);
    if (!me) {
      setError("Enter your name above first.");
      return;
    }
    const reason = decision === "exclude" ? exclusionReasonPayload(reasonChoice, reasonNote) : null;
    if (decision === "exclude" && !reason) {
      setError(
        reasonChoice === OTHER_REASON ? "Describe the reason when choosing Other." : "Choose a reason for exclusion."
      );
      return;
    }
    if (adjudication && !resolveNote.trim()) {
      setError("Explain how the conflict was resolved.");
      return;
    }
    setBusy(true);
    try {
      await recordScreeningDecision(protocolId, {
        paper_id: paper.id,
        stage,
        decision,
        reviewer: reviewer.trim(),
        reason: reason?.reason ?? null,
        reason_category: reason?.reason_category ?? null,
        role: adjudication ? "adjudication" : "review",
        note: adjudication ? resolveNote.trim() : null,
      });
      resetForms();
      await onRefresh();
    } catch (err) {
      setError(err instanceof Error ? err.message : "Failed to save the decision.");
    } finally {
      setBusy(false);
    }
  }

  function choose(stage: ScreeningStage, decision: ScreeningDecisionValue) {
    if (decision === "include") {
      void submit(stage, "include", false);
    } else {
      setError(null);
      setAction({ kind: "decide", stage, decision: "exclude" });
    }
  }

  function decideButtons(stage: ScreeningStage) {
    return (
      <div className="screening-actions">
        <span className="stage-label">{STAGE_LABEL[stage]}:</span>
        <button className="secondary-btn" disabled={busy} onClick={() => choose(stage, "include")}>
          Include
        </button>
        <button className="secondary-btn" disabled={busy} onClick={() => choose(stage, "exclude")}>
          Exclude
        </button>
        {revising === stage && (
          <button className="change-btn" onClick={resetForms}>
            Cancel
          </button>
        )}
      </div>
    );
  }

  function stageBlock(stage: ScreeningStage, status: StageStatus) {
    const mine = me ? status.byReviewer.get(me) : undefined;
    const others = status.byReviewer.size - (mine ? 1 : 0);
    const label = STAGE_LABEL[stage];

    if (revising === stage) return decideButtons(stage);

    if (status.final) {
      const final = status.final;
      return (
        <div className={`decision-tag ${final.decision === "include" ? "included" : "excluded"}`}>
          {label}: {decisionText(final)} β€”{" "}
          {status.state === "adjudicated"
            ? `conflict resolved by ${final.reviewer}: β€œ${final.note ?? ""}”`
            : `agreed by ${[...status.byReviewer.values()].map((r) => r.reviewer).join(" and ")}`}
          {mine && (
            <>
              {" "}
              <button className="change-btn" onClick={() => setRevising(stage)}>
                Change my decision
              </button>
            </>
          )}
        </div>
      );
    }

    if (status.state === "conflict") {
      return (
        <div className="conflict-box">
          <strong>{label}: conflict</strong>
          <ul className="history-change">
            {[...status.byReviewer.values()].map((r) => (
              <li key={r.id}>
                {r.reviewer}: {decisionText(r)}
              </li>
            ))}
          </ul>
          <div className="screening-actions">
            <button
              className="primary-btn"
              disabled={busy}
              onClick={() => {
                setError(null);
                setAction({ kind: "resolve", stage });
              }}
            >
              Resolve conflict
            </button>
            {mine && (
              <button className="change-btn" onClick={() => setRevising(stage)}>
                Change my decision
              </button>
            )}
          </div>
        </div>
      );
    }

    if (!me) {
      return (
        <div className="decision-line">
          {label}: enter your name above to screen this record.
          {others > 0 && ` (${others} reviewer${others === 1 ? " has" : "s have"} decided β€” hidden)`}
        </div>
      );
    }

    if (mine) {
      return (
        <div className="decision-line">
          {label} β€” your decision: {decisionText(mine)} Β· waiting for a second reviewer
          <button className="change-btn" onClick={() => setRevising(stage)}>
            Change
          </button>
        </div>
      );
    }

    return (
      <>
        {decideButtons(stage)}
        {others > 0 && (
          <div className="decision-line">
            1 of 2 reviewers has decided β€” their decision stays hidden until you decide.
          </div>
        )}
      </>
    );
  }

  const ftIncluded = ft?.final?.decision === "include";

  return (
    <div className="screening-row">
      <p className="screening-title">{paper.title}</p>
      <p className="paper-meta">
        {paper.authors}
        {paper.journal ? ` Β· ${paper.journal}` : ""}
        {paper.year ? ` (${paper.year})` : ""}
      </p>

      {stageBlock("title_abstract", ta)}
      {ft && stageBlock("full_text", ft)}

      {action?.kind === "decide" && (
        <div className="reason-prompt">
          <ReasonPicker
            options={reasonOptions[action.stage]}
            choice={reasonChoice}
            note={reasonNote}
            onChoice={setReasonChoice}
            onNote={setReasonNote}
          />
          <button className="primary-btn" disabled={busy} onClick={() => submit(action.stage, "exclude", false)}>
            Confirm exclude
          </button>
          <button className="change-btn" onClick={resetForms}>
            Cancel
          </button>
        </div>
      )}

      {action?.kind === "resolve" && (
        <div className="resolve-form">
          <strong>Resolve {STAGE_LABEL[action.stage].toLowerCase()} conflict</strong>
          <div className="screening-actions">
            <label className="source-checkbox">
              <input
                type="radio"
                name={`resolve-${paper.id}`}
                checked={resolveDecision === "include"}
                onChange={() => setResolveDecision("include")}
              />
              Include
            </label>
            <label className="source-checkbox">
              <input
                type="radio"
                name={`resolve-${paper.id}`}
                checked={resolveDecision === "exclude"}
                onChange={() => setResolveDecision("exclude")}
              />
              Exclude
            </label>
          </div>
          {resolveDecision === "exclude" && (
            <div className="reason-prompt">
              <ReasonPicker
                options={reasonOptions[action.stage]}
                choice={reasonChoice}
                note={reasonNote}
                onChoice={setReasonChoice}
                onNote={setReasonNote}
              />
            </div>
          )}
          <textarea
            placeholder="Justification (required), e.g. Discussed with both reviewers: the abstract confirms a narrative review"
            value={resolveNote}
            onChange={(e) => setResolveNote(e.target.value)}
          />
          <div className="screening-actions">
            <button
              className="primary-btn"
              disabled={busy || !resolveDecision}
              onClick={() => resolveDecision && submit(action.stage, resolveDecision, true)}
            >
              Save resolution
            </button>
            <button className="change-btn" onClick={resetForms}>
              Cancel
            </button>
          </div>
          <p className="form-hint">Recorded under your name ({reviewer.trim() || "enter it above"}).</p>
        </div>
      )}

      {ftIncluded && !extraction && !showExtraction && (
        <div className="decision-tag included">
          Included β€” ready for extraction
          <button className="secondary-btn" onClick={() => setShowExtraction(true)}>
            Extract data
          </button>
        </div>
      )}
      {ftIncluded && showExtraction && (
        <ExtractionForm
          reviewer={reviewer}
          busy={busy}
          defaultOutcome={defaultOutcome}
          onCancel={() => setShowExtraction(false)}
          onSubmit={async (data) => {
            setBusy(true);
            setError(null);
            try {
              await recordExtraction(protocolId, { ...data, paper_id: paper.id, extracted_by: reviewer.trim() });
              setShowExtraction(false);
              await onRefresh();
            } catch (err) {
              setError(err instanceof Error ? err.message : "Failed to save extraction.");
            } finally {
              setBusy(false);
            }
          }}
        />
      )}
      {ftIncluded && extraction && !showExtraction && (
        <ExtractionList
          records={extractionRecords.filter((r) => r.paper_id === paper.id)}
          onAddAnother={() => setShowExtraction(true)}
        />
      )}

      {error && <div className="form-error">{error}</div>}
    </div>
  );
}