-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
11642 lines (10227 loc) · 433 KB
/
Copy pathapp.js
File metadata and controls
11642 lines (10227 loc) · 433 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
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
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Global state
let uploadedData = [];
let uploadedFiles = []; // v3.0: Track multiple file sources
let currentStep = 1;
let columnMapping = {};
let screeningResults = null;
let fileFormat = 'unknown';
let formatSource = 'Unknown';
let currentTheme = 'subtle';
const APP_RELEASE_VERSION = '2.5-dual-review-release';
const FEATURE_FLAGS = Object.freeze({
ENABLE_QUALITY_ASSESSMENT: true,
ENABLE_STREAMING_IMPORT_V21: true,
});
const WORKFLOW_STEP_COUNT = FEATURE_FLAGS.ENABLE_QUALITY_ASSESSMENT ? 6 : 5;
const QUALITY_ENGINE = typeof globalThis !== 'undefined' ? globalThis.QualityEngine || null : null;
const IMPORT_JOB_RUNTIME = typeof globalThis !== 'undefined' ? globalThis.ImportJobRuntime || null : null;
const AUDIT_ENGINE = typeof globalThis !== 'undefined' ? globalThis.AuditEngine || null : null;
const DUAL_REVIEW_ENGINE = typeof globalThis !== 'undefined' ? globalThis.DualReviewEngine || null : null;
const AI_PROVIDER_ENGINE = typeof globalThis !== 'undefined' ? globalThis.AiProviderEngine || null : null;
const CONSERVATIVE_AI_ENGINE = typeof globalThis !== 'undefined' ? globalThis.ConservativeAiEngine || null : null;
const PROJECT_HISTORY_ENGINE = typeof globalThis !== 'undefined' ? globalThis.ProjectHistoryEngine || null : null;
const REVIEWER_BUNDLE_ENGINE = typeof globalThis !== 'undefined' ? globalThis.ReviewerBundleEngine || null : null;
const REVIEWER_BUNDLE_ENGINE_SCRIPT = 'reviewer-bundle-engine.js';
const AUDIT_EXPORT_TYPES = Object.freeze([
'audit_manifest',
'audit_events',
'audit_screening_decisions',
'audit_exclusion_reasons',
'audit_prisma_counts',
'audit_summary',
'defense_audit_pack',
'ai_usage_registry',
'ai_suggestions',
'prisma_traice_report',
]);
const DUAL_REVIEW_EXPORT_TYPES = Object.freeze([
'dual_review_conflicts',
'dual_review_agreement',
]);
const V25_FINAL_CONFLICT_GATED_EXPORT_TYPES = Object.freeze([
'included',
'excluded',
'included_ris',
'excluded_ris',
'included_bibtex',
'excluded_bibtex',
'svg-colorful',
'svg-blackwhite',
'svg-subtle',
'report',
'quality_appraisal',
'evidence_table',
'grade_summary',
'audit_prisma_counts',
'audit_summary',
]);
const V25_CONFLICT_EVIDENCE_EXPORT_TYPES = Object.freeze([
'audit_manifest',
'audit_events',
'audit_screening_decisions',
'audit_exclusion_reasons',
'defense_audit_pack',
'ai_usage_registry',
'ai_suggestions',
'prisma_traice_report',
'dual_review_conflicts',
'dual_review_agreement',
]);
const QUALITY_DISPLAY_LABELS = Object.freeze({
status: {
not_started: { zh: '未开始', en: 'Not started' },
queued: { zh: '已排队', en: 'Queued' },
in_progress: { zh: '进行中', en: 'In progress' },
complete: { zh: '已完成', en: 'Complete' },
completed: { zh: '已完成', en: 'Completed' },
needs_full_text: { zh: '需全文确认', en: 'Needs full text' },
},
studyDesign: {
rct: { zh: '随机对照试验', en: 'Randomized trial' },
systematic_review: { zh: '系统综述 / Meta 分析', en: 'Systematic review / meta-analysis' },
cohort: { zh: '队列研究', en: 'Cohort study' },
case_control: { zh: '病例对照研究', en: 'Case-control study' },
cross_sectional: { zh: '横断面研究', en: 'Cross-sectional study' },
diagnostic_accuracy: { zh: '诊断准确性研究', en: 'Diagnostic accuracy study' },
non_randomized_intervention: { zh: '非随机干预研究', en: 'Non-randomized intervention' },
case_report: { zh: '病例报告', en: 'Case report' },
case_series: { zh: '病例系列', en: 'Case series' },
other: { zh: '其他 / 待确认', en: 'Other / needs review' },
},
toolFamily: {
rob2: { zh: 'RoB 2', en: 'RoB 2' },
robins_i: { zh: 'ROBINS-I', en: 'ROBINS-I' },
newcastle_ottawa_scale: { zh: 'Newcastle-Ottawa 量表', en: 'Newcastle-Ottawa Scale' },
jbi: { zh: 'JBI 清单', en: 'JBI checklist' },
quadas_2: { zh: 'QUADAS-2', en: 'QUADAS-2' },
amstar_2: { zh: 'AMSTAR 2', en: 'AMSTAR 2' },
rob2_lite: { zh: 'RoB 2 简版', en: 'RoB 2 Lite' },
amstar2_lite: { zh: 'AMSTAR 2 简版', en: 'AMSTAR 2 Lite' },
jbi_nos_lite: { zh: 'JBI / NOS 简版', en: 'JBI / NOS Lite' },
robins_i_lite: { zh: 'ROBINS-I 简版', en: 'ROBINS-I Lite' },
case_report_lite: { zh: '病例报告简版', en: 'Case report lite' },
generic_quality_shell: { zh: '通用质量评价框架', en: 'Generic quality shell' },
},
evidence: {
high: { zh: '高', en: 'High' },
moderate: { zh: '中等', en: 'Moderate' },
low: { zh: '低', en: 'Low' },
very_low: { zh: '很低', en: 'Very low' },
},
judgement: {
low_risk: { zh: '低风险', en: 'Low risk' },
some_concerns: { zh: '有一些顾虑', en: 'Some concerns' },
high_risk: { zh: '高风险', en: 'High risk' },
unclear: { zh: '信息不清', en: 'Unclear' },
not_applicable: { zh: '不适用', en: 'Not applicable' },
not_assessed: { zh: '未评价', en: 'Not assessed' },
},
});
let qualityAssessments = [];
let importJobs = [];
let projectManifest = null;
let auditEvents = [];
let screeningDecisions = [];
let aiSuggestionEvents = [];
let conservativeAiQueueFilter = 'all';
let conservativeAiQueueSortMode = 'original';
let conservativeAiQueueReviewStateFilter = 'all';
let currentConservativeAiQueueContext = null;
let projectHistory = [];
// Runtime mode state (Task 8)
const RUNTIME_MODE = {
SINGLE: 'single',
DUAL_MAIN: 'dual-main',
DUAL_SECONDARY: 'dual-secondary'
};
let runtimeMode = RUNTIME_MODE.SINGLE;
let runtimeSession = null;
// v1.1 collaboration globals (explicit declarations to avoid runtime ReferenceError)
let currentUserSession = null;
let isDualReviewMode = false;
let currentReviewer = 'A';
let reviewerNames = { A: '审查员A', B: '审查员B' };
let dualReviewResults = { A: {}, B: {}, final: {} };
let dualReviewConflictState = {
screeningPairs: [],
screeningConflicts: [],
qualityConflicts: [],
agreementMetrics: null,
exportGate: null,
};
function getEmptyDualReviewConflictState() {
return {
screeningPairs: [],
screeningConflicts: [],
qualityConflicts: [],
agreementMetrics: null,
exportGate: null,
};
}
let projectData = null;
let collaborationSyncInterval = null;
const COLLAB_PROJECTS_KEY = 'prisma_projects';
const USER_SESSION_KEY = 'prisma_user_session';
// v1.5: Smart batch import system (4 mechanisms)
const SMART_IMPORT_CONFIG = {
MAX_CHUNK_SIZE: 5000, // 单批次最大记录数
CHECKPOINT_INTERVAL: 1000, // Checkpoint间隔
PARSE_CHUNK_SIZE: 50000, // 流式解析块大小(bytes)
MAX_RETRY: 3 // 最大重试次数
};
const PARSER_WORKER_URL = 'parser-worker.js?v=20260422-streaming-v2';
const LOCAL_FILE_WORKER_FALLBACK_MAX_BYTES = 20 * 1024 * 1024;
let importQueue = {
tasks: [], // 待导入任务队列
currentTask: null, // 当前执行任务
checkpoints: [], // Checkpoint记录
status: 'idle', // idle|running|paused|failed
progress: { total: 0, processed: 0, failed: 0 }
};
// v1.4: Project-level exclusion reason template (customizable & persisted)
const DEFAULT_EXCLUSION_REASONS = [
'人群不符',
'干预不符',
'对照不符',
'缺乏结局',
'数据不完整',
'研究设计不合适'
];
let exclusionReasons = [...DEFAULT_EXCLUSION_REASONS];
// v1.4: Explicit state split
let filterRules = null; // last used rules
let currentProjectId = null; // local project id for persistence
// v1.1: Multi-user collaboration variables
let projectCollaboration = {
reviewers: {},
decisions: {},
status: 'active',
createdAt: null,
lastSync: null
};
// Color themes
const colorThemes = {
colorful: {
name: '活力彩色',
colors: {
identified: '#FF6B6B',
screened: '#4ECDC4',
included: '#45B7D1',
excluded: '#FFA07A',
duplicates: '#FFD93D',
text: '#2C3E50',
border: '#34495E'
}
},
blackwhite: {
name: '黑白',
colors: {
identified: '#1A1A1A',
screened: '#4D4D4D',
included: '#808080',
excluded: '#B3B3B3',
duplicates: '#E6E6E6',
text: '#000000',
border: '#333333'
}
},
subtle: {
name: '柔和',
colors: {
identified: '#8B4F8B',
screened: '#5B7C99',
included: '#6B8E6F',
excluded: '#C89B6B',
duplicates: '#A89968',
text: '#3E3E3E',
border: '#6B6B6B'
}
}
};
// Sample data for demonstration
const sampleData = [
{
title: "中医针灸对慢性疼痛的疗效研究",
abstract: "本研究探讨了针灸治疗慢性疼痛的临床效果,采用随机对照试验方法,结果显示针灸组疼痛评分显著低于对照组。",
year: 2020,
journal: "中华中医药杂志",
authors: "张三;李四",
doi: "10.1234/tcm.2020.001",
keywords: "中医;针灸;慢性疼痛"
},
{
title: "Acupuncture for chronic pain: systematic review",
abstract: "This systematic review evaluates the efficacy of acupuncture in treating chronic pain conditions. Meta-analysis shows significant pain reduction.",
year: 2021,
journal: "Pain Medicine",
authors: "Smith J, Johnson A",
doi: "10.5678/pain.2021.042",
keywords: "acupuncture;chronic pain;systematic review"
},
{
title: "医保支付方式改革与价值医疗",
abstract: "探讨医保支付方式改革对医疗服务价值导向的影响,采用差分中的差分方法评估政策效果。",
year: 2022,
journal: "中国卫生经济",
authors: "王五;赵六",
doi: "10.9012/che.2022.018",
keywords: "医保;支付方式;价值医疗;DID"
},
{
title: "Animal study of acupuncture mechanisms",
abstract: "This study investigates the neurobiological mechanisms of acupuncture using animal models. Rats were subjected to acupuncture treatment.",
year: 2019,
journal: "Neuroscience Letters",
authors: "Chen L, Wang M",
doi: "10.3456/neuro.2019.089",
keywords: "animal study;acupuncture;mechanisms"
},
{
title: "Editorial: Future of Traditional Chinese Medicine",
abstract: "This editorial discusses the future directions and challenges facing traditional Chinese medicine research and practice.",
year: 2023,
journal: "Journal of TCM",
authors: "Li H",
doi: "10.7890/jtcm.2023.005",
keywords: "editorial;traditional chinese medicine"
},
{
title: "Causal inference in health economics using AIPW",
abstract: "We apply augmented inverse probability weighting (AIPW) to estimate causal effects of medical insurance on healthcare utilization.",
year: 2022,
journal: "Health Economics",
authors: "Brown R, Davis K",
doi: "10.2468/he.2022.134",
keywords: "causal inference;AIPW;medical insurance"
},
{
title: "In vitro study of herbal medicine efficacy",
abstract: "Cell culture experiments demonstrate the anti-inflammatory effects of traditional herbal compounds in vitro.",
year: 2021,
journal: "Phytomedicine",
authors: "Liu Y, Zhou X",
doi: "10.1357/phyto.2021.067",
keywords: "in vitro;herbal medicine;cell culture"
},
{
title: "Protocol: RCT of acupuncture for migraine",
abstract: "This paper presents the study protocol for a randomized controlled trial evaluating acupuncture for migraine prevention.",
year: 2023,
journal: "Trials",
authors: "Martinez P, Garcia S",
doi: "10.8642/trials.2023.091",
keywords: "protocol;acupuncture;migraine;RCT"
},
{
title: "Overlap weighting for observational studies in medical insurance",
abstract: "We propose using overlap weighting to improve balance and efficiency in estimating treatment effects from medical insurance data.",
year: 2023,
journal: "Statistics in Medicine",
authors: "Wilson T, Anderson M",
doi: "10.9753/sim.2023.156",
keywords: "overlap weighting;medical insurance;causal inference"
},
{
title: "Case report: Rare complication of acupuncture",
abstract: "We report a case of pneumothorax following acupuncture treatment, highlighting the importance of proper technique and safety precautions.",
year: 2020,
journal: "Case Reports in Medicine",
authors: "Taylor E",
doi: "10.4826/crm.2020.023",
keywords: "case report;acupuncture;complication"
}
];
// Default rules
const defaultRules = {
time_window: {
start_year: 2000,
end_year: 2030
},
include_any: [
// v3.0: 默认为空,不进行关键词过滤
// 用户可以根据需要自行添加关键词
],
exclude: [
{ keyword: "animal study", reason: "不属于人群研究(动物实验)" },
{ keyword: "editorial", reason: "非研究性文献(社论/评论)" },
{ keyword: "protocol", reason: "仅研究方案,无结果" },
{ keyword: "in vitro", reason: "体外实验,非目标范围" },
{ keyword: "case report", reason: "病例报道,证据等级不足" }
],
language: {
allow: ["english", "chinese"]
},
required_one_of: ["title", "abstract"]
};
function normalizeQualityAssessmentsState(list) {
if (!Array.isArray(list)) return [];
return list
.filter(Boolean)
.map((assessment, index) => {
if (QUALITY_ENGINE && typeof QUALITY_ENGINE.createQualityAssessment === 'function') {
const normalized = QUALITY_ENGINE.createQualityAssessment(
{
id: assessment.record_id || assessment.recordId || `record-${index + 1}`,
title: assessment.title || '',
abstract: assessment.abstract || '',
publication_type: assessment.publication_type || assessment.study_design || '',
},
{
id: assessment.id || `qa-${index + 1}`,
projectId: assessment.project_id || assessment.projectId || currentProjectId || null,
recordId: assessment.record_id || assessment.recordId || `record-${index + 1}`,
status: assessment.status,
studyDesignFamily: assessment.study_design || assessment.studyDesignFamily,
toolFamily: assessment.tool_family || assessment.toolFamily,
domainScores: assessment.domain_scores || assessment.domainScores || [],
overallRisk: assessment.overall_risk || assessment.overallRisk,
evidenceAdjustments: assessment.evidence_adjustments || assessment.evidenceAdjustments || [],
evidenceFinal: assessment.evidence_final || assessment.evidenceFinal,
overallJudgement: assessment.overall_judgement || assessment.overallJudgement,
overrideReason: assessment.override_reason || assessment.overrideReason || '',
reviewerId: assessment.reviewer_id || assessment.reviewerId || '',
notes: assessment.notes || '',
updatedAt: assessment.updated_at || assessment.updatedAt,
}
);
return {
...normalized,
reviewer_assessments: preserveQualityReviewerAssessments(assessment),
};
}
return {
id: assessment.id || `qa-${index + 1}`,
project_id: assessment.project_id || assessment.projectId || currentProjectId || null,
record_id: assessment.record_id || assessment.recordId || `record-${index + 1}`,
status: assessment.status || 'not_started',
study_design: assessment.study_design || assessment.studyDesignFamily || 'other',
study_type: assessment.study_type || assessment.study_design || assessment.studyDesignFamily || 'other',
tool_family: assessment.tool_family || assessment.toolFamily || 'generic_quality_shell',
template_id: assessment.template_id || assessment.templateId || '',
template_version: assessment.template_version || assessment.templateVersion || '',
domain_scores: assessment.domain_scores || assessment.domainScores || [],
domains: assessment.domains || assessment.domain_scores || assessment.domainScores || [],
overall_risk: assessment.overall_risk || assessment.overallRisk || 'unclear',
overall_judgement: assessment.overall_judgement || assessment.overallJudgement || assessment.overall_risk || assessment.overallRisk || 'unclear',
evidence_initial: assessment.evidence_initial || assessment.evidenceInitial || 'very_low',
evidence_adjustments: assessment.evidence_adjustments || assessment.evidenceAdjustments || [],
evidence_final: assessment.evidence_final || assessment.evidenceFinal || 'very_low',
override_reason: assessment.override_reason || assessment.overrideReason || '',
reviewer_id: assessment.reviewer_id || assessment.reviewerId || '',
reviewer_assessments: preserveQualityReviewerAssessments(assessment),
notes: assessment.notes || '',
updated_at: assessment.updated_at || assessment.updatedAt || new Date().toISOString(),
};
});
}
function preserveQualityReviewerAssessments(assessment) {
if (!assessment || typeof assessment !== 'object' || !assessment.reviewer_assessments || typeof assessment.reviewer_assessments !== 'object') {
return {};
}
return Object.keys(assessment.reviewer_assessments).reduce((acc, reviewerId) => {
const entry = assessment.reviewer_assessments[reviewerId];
if (entry && typeof entry === 'object') {
acc[reviewerId] = { ...entry };
}
return acc;
}, {});
}
function normalizeImportJobsState(list) {
if (!Array.isArray(list)) return [];
return list
.filter(Boolean)
.map((job) => {
if (IMPORT_JOB_RUNTIME && typeof IMPORT_JOB_RUNTIME.createImportJob === 'function') {
const base = IMPORT_JOB_RUNTIME.createImportJob({
id: job.id,
projectId: job.project_id || job.projectId || currentProjectId || null,
fileName: job.file_name || job.fileName || 'unknown',
fileSize: job.file_size || job.fileSize || 0,
format: job.format || 'unknown',
stage: job.stage,
bytesRead: job.bytes_read || job.bytesRead || 0,
recordsParsed: job.records_parsed || job.recordsParsed || 0,
recordsWritten: job.records_written || job.recordsWritten || 0,
checkpoint: job.checkpoint_json || job.checkpoint || null,
error: job.error || '',
startedAt: job.started_at || job.startedAt,
timestamp: job.updated_at || job.updatedAt,
});
return IMPORT_JOB_RUNTIME.patchImportJob(base, {
stage: job.stage,
bytesRead: job.bytes_read || job.bytesRead || 0,
recordsParsed: job.records_parsed || job.recordsParsed || 0,
recordsWritten: job.records_written || job.recordsWritten || 0,
checkpoint: job.checkpoint_json || job.checkpoint || null,
error: job.error || '',
updatedAt: job.updated_at || job.updatedAt,
});
}
return {
id: job.id || `import-${Date.now()}`,
project_id: job.project_id || job.projectId || currentProjectId || null,
file_name: job.file_name || job.fileName || 'unknown',
file_size: job.file_size || job.fileSize || 0,
format: job.format || 'unknown',
stage: job.stage || 'queued',
bytes_read: job.bytes_read || job.bytesRead || 0,
records_parsed: job.records_parsed || job.recordsParsed || 0,
records_written: job.records_written || job.recordsWritten || 0,
checkpoint_json: job.checkpoint_json || job.checkpoint || null,
error: job.error || '',
started_at: job.started_at || job.startedAt || new Date().toISOString(),
updated_at: job.updated_at || job.updatedAt || new Date().toISOString(),
};
});
}
function buildQualityRecordId(record, fallbackIndex) {
if (QUALITY_ENGINE && typeof QUALITY_ENGINE.getAssessmentRecordId === 'function') {
return QUALITY_ENGINE.getAssessmentRecordId(record, fallbackIndex);
}
return String(record?.record_id || record?.id || record?.doi || record?.title || `record-${fallbackIndex + 1}`);
}
function createQualityAssessmentShellRecord(record, index) {
const recordId = buildQualityRecordId(record, index);
if (QUALITY_ENGINE && typeof QUALITY_ENGINE.createQualityAssessment === 'function') {
return QUALITY_ENGINE.createQualityAssessment(record, {
projectId: currentProjectId || null,
recordId,
});
}
return {
id: `qa-${recordId}`,
project_id: currentProjectId || null,
record_id: recordId,
status: 'not_started',
study_design: 'other',
tool_family: 'generic_quality_shell',
domain_scores: [],
overall_risk: 'unclear',
evidence_initial: 'very_low',
evidence_adjustments: [],
evidence_final: 'very_low',
override_reason: '',
notes: '',
updated_at: new Date().toISOString(),
};
}
function getQualitySourceField(record, fields = []) {
if (!record || typeof record !== 'object') return '';
for (const field of fields) {
const value = record[field];
if (Array.isArray(value)) {
const joined = value
.map((item) => String(item === undefined || item === null ? '' : item).trim())
.filter(Boolean)
.join('; ');
if (joined) return joined;
continue;
}
if (value !== undefined && value !== null && String(value).trim()) {
return String(value).trim();
}
}
return '';
}
function rehydrateQualityAssessmentFromSourceRecord(record, assessment, index) {
const recordId = buildQualityRecordId(record, index);
if (QUALITY_ENGINE && typeof QUALITY_ENGINE.createQualityAssessment === 'function') {
const normalized = QUALITY_ENGINE.createQualityAssessment(record, {
id: assessment.id || `qa-${recordId}`,
projectId: currentProjectId || assessment.project_id || assessment.projectId || null,
recordId,
status: assessment.status,
domainScores: assessment.domain_scores || assessment.domainScores || [],
overallRisk: assessment.overall_risk || assessment.overallRisk,
overallJudgement: assessment.overall_judgement || assessment.overallJudgement,
evidenceAdjustments: assessment.evidence_adjustments || assessment.evidenceAdjustments || [],
evidenceFinal: assessment.evidence_final || assessment.evidenceFinal,
overrideReason: assessment.override_reason || assessment.overrideReason || '',
reviewerId: assessment.reviewer_id || assessment.reviewerId || '',
notes: assessment.notes || '',
updatedAt: assessment.updated_at || assessment.updatedAt,
});
return {
...normalized,
reviewer_assessments: preserveQualityReviewerAssessments(assessment),
};
}
return {
...assessment,
id: assessment.id || `qa-${recordId}`,
project_id: currentProjectId || assessment.project_id || assessment.projectId || null,
record_id: recordId,
title: assessment.title || getQualitySourceField(record, ['title', 'TI', 'T1', 'dc:title', 'dcterms:title']) || recordId,
abstract: assessment.abstract || getQualitySourceField(record, ['abstract', 'AB', 'N2', 'dcterms:abstract', 'dc:description', 'Abstract Note', 'Notes']),
publication_type: assessment.publication_type || getQualitySourceField(record, ['publication_type', 'type', 'TY', 'PT', 'z:itemType']),
};
}
function prepareQualityAssessmentShell(options = {}) {
const { persist = true, silent = false } = options;
const includedRecords = Array.isArray(screeningResults?.included) ? screeningResults.included : [];
if (!FEATURE_FLAGS.ENABLE_QUALITY_ASSESSMENT || includedRecords.length === 0) {
qualityAssessments = [];
renderQualityAssessmentShell();
return qualityAssessments;
}
const existing = new Map(
normalizeQualityAssessmentsState(qualityAssessments).map((assessment) => [
String(assessment.record_id),
assessment,
])
);
qualityAssessments = includedRecords.map((record, index) => {
const recordId = buildQualityRecordId(record, index);
const fromState = existing.get(recordId);
if (fromState) {
return rehydrateQualityAssessmentFromSourceRecord(record, fromState, index);
}
return createQualityAssessmentShellRecord(record, index);
});
if (persist && typeof appendAuditEventsSafe === 'function') {
const qualityEvents = [{
eventType: 'quality_appraisal_started',
recordId: '',
after: {
assessmentCount: qualityAssessments.length,
},
source: 'system',
metadata: {
includedCount: includedRecords.length,
},
}].concat(qualityAssessments.map((assessment) => ({
eventType: 'quality_appraisal_updated',
recordId: String(assessment.record_id || ''),
after: {
templateId: assessment.template_id || '',
studyDesign: assessment.study_design || '',
toolFamily: assessment.tool_family || '',
domainCount: Array.isArray(assessment.domain_scores) ? assessment.domain_scores.length : 0,
evidenceInitial: assessment.evidence_initial || '',
},
source: 'system',
metadata: {
status: assessment.status || '',
schemaVersion: assessment.schema_version || '',
},
})));
appendAuditEventsSafe(qualityEvents, { persist: false });
}
if (persist) persistCurrentProjectState();
renderQualityAssessmentShell();
if (!silent) {
showToast(`已准备 ${qualityAssessments.length} 条质量评价记录`, 'success');
}
return qualityAssessments;
}
function getQualityDisplayLabel(labelGroup, value, lang) {
const key = String(value || '').trim();
const group = QUALITY_DISPLAY_LABELS[labelGroup] || {};
const label = group[key];
if (label && label[lang]) {
return label[lang];
}
if (!key) {
return lang === 'zh' ? '待确认' : 'Pending';
}
return key.replace(/_/g, ' ');
}
function renderQualityDisplayLabel(labelGroup, value) {
return `
<span class="zh">${escapeShellText(getQualityDisplayLabel(labelGroup, value, 'zh'))}</span>
<span class="en">${escapeShellText(getQualityDisplayLabel(labelGroup, value, 'en'))}</span>
`;
}
function renderQualityMetaPill(labelZh, labelEn, labelGroup, value) {
return `
<span class="quality-meta-pill">
<span class="quality-meta-label"><span class="zh">${labelZh}</span><span class="en">${labelEn}</span></span>
<span class="quality-meta-value">${renderQualityDisplayLabel(labelGroup, value)}</span>
</span>
`;
}
function renderQualityConflictResolverPanel() {
if (!isDualReviewMode || runtimeMode !== RUNTIME_MODE.DUAL_MAIN || !DUAL_REVIEW_ENGINE) {
return '';
}
const conflicts = refreshDualReviewConflictState().qualityConflicts || [];
const pendingConflicts = conflicts.filter((conflict) => conflict.status !== 'resolved');
const resolvedCount = conflicts.length - pendingConflicts.length;
return `
<div class="quality-conflict-panel">
<div>
<strong><span class="zh">质量评价分歧</span><span class="en">Quality conflicts</span></strong>
<div class="muted-text">
<span class="zh">待处理 ${pendingConflicts.length} 条,已解决 ${resolvedCount} 条。</span>
<span class="en">${pendingConflicts.length} pending, ${resolvedCount} resolved.</span>
</div>
</div>
<button type="button" class="btn btn-secondary" onclick="showQualityConflictResolver()" ${pendingConflicts.length === 0 ? 'disabled' : ''}>
<span class="zh">处理质量分歧</span><span class="en">Resolve quality conflicts</span>
</button>
</div>
`;
}
function renderQualityDistribution(entries, labelGroup) {
if (!entries || entries.length === 0) {
return '<span class="zh">待生成</span><span class="en">Pending</span>';
}
return entries
.map(([key, value]) => `
<span class="quality-summary-chip">
<span>${renderQualityDisplayLabel(labelGroup, key)}</span>
<strong>${Number(value) || 0}</strong>
</span>
`)
.join('');
}
function getQualityStatusOptions(selectedValue) {
const selected = String(selectedValue || '');
return ['not_started', 'queued', 'in_progress', 'complete', 'completed', 'needs_full_text']
.map((status) => `<option value="${status}" ${status === selected ? 'selected' : ''}>${escapeShellText(getQualityDisplayLabel('status', status, 'zh'))} / ${escapeShellText(getQualityDisplayLabel('status', status, 'en'))}</option>`)
.join('');
}
function getQualityJudgementOptions(selectedValue) {
const selected = String(selectedValue || '');
return ['not_assessed', 'low_risk', 'some_concerns', 'high_risk', 'unclear', 'not_applicable']
.map((judgement) => `<option value="${judgement}" ${judgement === selected ? 'selected' : ''}>${escapeShellText(getQualityDisplayLabel('judgement', judgement, 'zh'))} / ${escapeShellText(getQualityDisplayLabel('judgement', judgement, 'en'))}</option>`)
.join('');
}
function getQualityDomainInputId(recordId, domainId, field) {
const encodedRecordId = encodeURIComponent(String(recordId || ''));
const encodedDomainId = encodeURIComponent(String(domainId || ''));
return `quality-domain-${encodedRecordId}-${encodedDomainId}-${field}`;
}
function getQualityAssessmentInputId(recordId, field) {
return `quality-assessment-${encodeURIComponent(String(recordId || ''))}-${field}`;
}
function readQualityInputValue(id) {
const element = document.getElementById(id);
return element ? String(element.value || '').trim() : '';
}
function findQualityAssessmentIndex(recordId) {
const normalizedRecordId = String(recordId || '');
return qualityAssessments.findIndex((assessment) => String(assessment.record_id || '') === normalizedRecordId);
}
function cloneQualityAssessmentForAudit(assessment) {
if (!assessment || typeof assessment !== 'object') {
return null;
}
return {
assessmentId: assessment.assessment_id || assessment.id || '',
recordId: assessment.record_id || '',
status: assessment.status || '',
overallJudgement: assessment.overall_judgement || '',
domainScores: Array.isArray(assessment.domain_scores)
? assessment.domain_scores.map((domain) => ({
domainId: domain.domain_id || '',
judgement: domain.judgement || '',
supportingQuote: domain.supporting_quote || '',
reviewerNote: domain.reviewer_note || '',
}))
: [],
notes: assessment.notes || '',
reviewerId: assessment.reviewer_id || '',
updatedAt: assessment.updated_at || '',
};
}
function getCurrentReviewerId() {
if (currentUserSession?.role === 'reviewer-a') return 'reviewer_A';
if (currentUserSession?.role === 'reviewer-b') return 'reviewer_B';
return isDualReviewMode ? `reviewer_${currentReviewer}` : 'reviewer_1';
}
function getReviewerSlotFromRole(role) {
if (role === 'reviewer-a') return 'A';
if (role === 'reviewer-b') return 'B';
return currentReviewer === 'B' ? 'B' : 'A';
}
function normalizeFulltextSelection(value) {
if (DUAL_REVIEW_ENGINE && typeof DUAL_REVIEW_ENGINE.normalizeReviewSelection === 'function') {
return DUAL_REVIEW_ENGINE.normalizeReviewSelection(value);
}
const rawValue = String(value || '').trim();
if (rawValue === '__uncertain__') {
return { decision: 'uncertain', exclusionReason: '', originalValue: rawValue };
}
if (!rawValue) {
return { decision: 'include', exclusionReason: '', originalValue: rawValue };
}
return { decision: 'exclude', exclusionReason: rawValue, originalValue: rawValue };
}
function getFulltextSelectValueFromDecision(decisionInput) {
const decision = String(decisionInput?.decision || decisionInput?.human_decision || '').trim();
if (decision === 'uncertain') return '__uncertain__';
if (decision === 'exclude') return String(decisionInput?.exclusionReason || decisionInput?.exclusion_reason || decisionInput?.originalValue || '').trim() || '其他';
return '';
}
function getReviewerLabelForSlot(slot) {
return reviewerNames?.[slot] || (slot === 'B' ? '审查员B' : '审查员A');
}
function getAuditRecordIndexMap(records) {
const map = new Map();
(Array.isArray(records) ? records : []).forEach((record, index) => {
map.set(getRecordAuditId(record, index), index);
});
return map;
}
function syncDualReviewResultsFromDecisions() {
if (!DUAL_REVIEW_ENGINE || !Array.isArray(screeningDecisions)) return dualReviewResults;
const currentFinal = dualReviewResults?.final || {};
const latest = DUAL_REVIEW_ENGINE.getLatestScreeningDecisions(screeningDecisions);
const recordIndexMap = getAuditRecordIndexMap(screeningResults?.included || []);
const next = { A: {}, B: {}, final: { ...currentFinal } };
latest
.filter((decision) => decision.stage === 'full_text')
.forEach((decision) => {
const index = recordIndexMap.get(decision.recordId);
if (!Number.isFinite(index)) return;
if (DUAL_REVIEW_ENGINE.isResolverDecision(decision)) {
next.final[index] = {
finalDecision: getFulltextSelectValueFromDecision(decision),
decision: decision.decision,
exclusionReason: decision.exclusionReason,
discussion: decision.notes || decision.metadata?.resolutionNote || '',
reviewerAOriginal: decision.metadata?.reviewerA?.exclusionReason || decision.metadata?.reviewerA?.decision || '',
reviewerBOriginal: decision.metadata?.reviewerB?.exclusionReason || decision.metadata?.reviewerB?.decision || '',
resolvedBy: decision.reviewerId || 'resolver_1',
timestamp: decision.updatedAt || decision.decidedAt || '',
};
return;
}
const slot = DUAL_REVIEW_ENGINE.getReviewerSlot(decision.reviewerId);
if (slot !== 'A' && slot !== 'B') return;
next[slot][index] = {
decision: getFulltextSelectValueFromDecision(decision),
normalizedDecision: decision.decision,
exclusionReason: decision.exclusionReason,
timestamp: decision.updatedAt || decision.decidedAt || '',
reviewer: decision.reviewerId,
};
});
dualReviewResults = next;
return dualReviewResults;
}
function getReviewerDecisionEntry(slot, index) {
syncDualReviewResultsFromDecisions();
return dualReviewResults?.[slot]?.[index] || null;
}
function recordFulltextReviewerDecision(index, rawValue, options = {}) {
if (!screeningResults || !Array.isArray(screeningResults.included)) return null;
const record = screeningResults.included[index];
if (!record) return null;
const slot = options.slot || getReviewerSlotFromRole(currentUserSession?.role);
const reviewerId = options.reviewerId || (slot === 'B' ? 'reviewer_B' : 'reviewer_A');
const selection = normalizeFulltextSelection(rawValue);
const timestamp = new Date().toISOString();
const entry = {
decision: selection.originalValue,
normalizedDecision: selection.decision,
exclusionReason: selection.exclusionReason,
timestamp,
reviewer: reviewerId,
};
const recordId = getRecordAuditId(record, index);
if (!dualReviewResults[slot]) dualReviewResults[slot] = {};
dualReviewResults[slot][index] = entry;
if (currentUserSession && projectData) {
if (!projectData.reviewDecisions) projectData.reviewDecisions = {};
if (!projectData.reviewDecisions[currentUserSession.role]) {
projectData.reviewDecisions[currentUserSession.role] = {};
}
projectData.reviewDecisions[currentUserSession.role][index] = {
decision: selection.originalValue,
normalizedDecision: selection.decision,
exclusionReason: selection.exclusionReason,
timestamp,
reviewer: currentUserSession.username || reviewerId,
reviewerId,
recordId,
};
}
if (typeof upsertScreeningDecisionSafe === 'function') {
upsertScreeningDecisionSafe({
recordId,
stage: 'full_text',
decision: selection.decision,
exclusionReason: normalizeAuditExclusionReason(selection.exclusionReason),
reviewerId,
conflictStatus: 'none',
source: 'human',
notes: selection.exclusionReason,
metadata: {
originalReason: selection.exclusionReason,
originalSelection: selection.originalValue,
reviewIndex: index,
reviewerSlot: slot,
},
}, { persist: false });
}
return entry;
}
function getQualityReviewConflictInputs() {
const rows = [];
(Array.isArray(qualityAssessments) ? qualityAssessments : []).forEach((assessment) => {
if (!assessment || typeof assessment !== 'object') return;
const reviewerAssessments = assessment.reviewer_assessments && typeof assessment.reviewer_assessments === 'object'
? assessment.reviewer_assessments
: {};
Object.keys(reviewerAssessments).forEach((reviewerId) => {
rows.push({
...assessment,
...reviewerAssessments[reviewerId],
reviewer_id: reviewerId,
assessment_id: `${assessment.assessment_id || assessment.id || assessment.record_id || 'qa'}-${reviewerId}`,
record_id: assessment.record_id,
});
});
if (assessment.reviewer_id && !reviewerAssessments[assessment.reviewer_id]) {
rows.push(assessment);
}
});
return rows;
}
function getQualityConflictIndexMap() {
const map = new Map();
refreshDualReviewConflictState().qualityConflicts.forEach((conflict, index) => {
map.set(conflict.conflictId, index);
});
return map;
}
function getFulltextReviewRecordsForConflictState() {
const included = Array.isArray(screeningResults?.included) ? screeningResults.included : [];
const excluded = Array.isArray(screeningResults?.excluded)
? screeningResults.excluded.filter((record) => record && record._exclude_stage === 'fulltext')
: [];
return included.concat(excluded);
}
function refreshDualReviewConflictState(options = {}) {
if (!DUAL_REVIEW_ENGINE) return dualReviewConflictState;
const records = getFulltextReviewRecordsForConflictState();
const screeningConflicts = DUAL_REVIEW_ENGINE.buildScreeningConflictQueue(screeningDecisions, records);
const qualityConflicts = DUAL_REVIEW_ENGINE.buildQualityConflictQueue(getQualityReviewConflictInputs());
const pendingScreeningConflicts = screeningConflicts.filter((conflict) => conflict.status !== 'resolved');
const screeningPairs = typeof DUAL_REVIEW_ENGINE.buildScreeningAgreementPairs === 'function'
? DUAL_REVIEW_ENGINE.buildScreeningAgreementPairs(screeningDecisions, records)
: [];
const agreementMetrics = screeningPairs.length > 0
? (typeof DUAL_REVIEW_ENGINE.calculateScreeningAgreementMetrics === 'function'