weaver-work-cli 0.1.50 → 0.1.53
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.
- package/README.md +1 -1
- package/dist/chunks/{attachment-content-EJYIOJPH.js → attachment-content-W3TSJC3Y.js} +3 -3
- package/dist/chunks/{chunk-BFKLQLBK.js → chunk-2J3XY4ED.js} +7 -7
- package/dist/chunks/{chunk-K67FODVC.js → chunk-6GCXWKG6.js} +1 -1
- package/dist/chunks/{chunk-WNJUGI2F.js → chunk-76PRVYH4.js} +1 -1
- package/dist/chunks/{chunk-RYFRGTUV.js → chunk-DEHJ7PMA.js} +4 -4
- package/dist/chunks/{chunk-3NCFFHB2.js → chunk-IF33CG4V.js} +1 -1
- package/dist/chunks/{chunk-YB3AJYPY.js → chunk-PE334WL3.js} +4 -4
- package/dist/chunks/{chunk-MCZG6HPM.js → chunk-QQXMHM3J.js} +2 -2
- package/dist/chunks/{chunk-7ECB22G3.js → chunk-U7ROML5E.js} +23 -23
- package/dist/chunks/{chunk-7AYQJSFY.js → chunk-WTLQGS6D.js} +2 -2
- package/dist/chunks/{chunk-6T53BSWZ.js → chunk-XPQN4E5O.js} +50 -19
- package/dist/chunks/{chunk-HARQF5IP.js → chunk-Z4G7LLDD.js} +25 -25
- package/dist/chunks/{conflict-C4UDHCWV.js → conflict-57WDJWL7.js} +2 -2
- package/dist/chunks/{contract-VUC6JOPG.js → contract-LJRAXVZU.js} +8587 -1421
- package/dist/chunks/{create-flow-6OG2LYBD.js → create-flow-3FMMZBCA.js} +6 -6
- package/dist/chunks/{data-QO7QWOIV.js → data-WK5CQXNF.js} +17 -32
- package/dist/chunks/{env-WP57TF2S.js → env-JYZE3BZB.js} +2 -2
- package/dist/chunks/{factory-VUXI7N5C.js → factory-66SCIKW3.js} +1 -1
- package/dist/chunks/{group-chat-UQRGXILK.js → group-chat-MNRYMLNG.js} +3 -3
- package/dist/chunks/{invoice-E7GOITEU.js → invoice-V7ZTITUO.js} +725 -205
- package/dist/chunks/{meeting-4BBLVAWM.js → meeting-IIY4UAJL.js} +10 -10
- package/dist/chunks/{recruit-stage-FKWS5UQF.js → recruit-stage-XCMVEQA2.js} +718 -131
- package/dist/chunks/{registry-V4CHRQDI.js → registry-CJOVECZD.js} +1 -1
- package/dist/chunks/{registry-5CRCN2TV.js → registry-METZ2LWE.js} +10 -10
- package/dist/chunks/{room-recommend-AYR3UG7R.js → room-recommend-YFY7HTOF.js} +4 -4
- package/dist/chunks/{schedule-JZEFIXUS.js → schedule-6I63TERA.js} +4 -4
- package/dist/chunks/smart-extract-FOUYNIG3.js +2882 -0
- package/dist/chunks/{workflow-3ZAF2J5E.js → workflow-YHXFIU63.js} +1 -1
- package/dist/index.js +11 -6
- package/dist/shortcuts/contract/manifest.js +251 -0
- package/dist/shortcuts/contract/ooxml/docx-table.js +233 -0
- package/dist/shortcuts/contract/operations/card-action.js +1165 -0
- package/dist/shortcuts/contract/operations/card-ebdf-list.js +571 -0
- package/dist/shortcuts/contract/operations/card-plan.js +327 -0
- package/dist/shortcuts/contract/operations/card-risk-report.js +565 -0
- package/dist/shortcuts/contract/operations/card.js +6 -5
- package/dist/shortcuts/contract/operations/docx-fillfromquote.js +532 -0
- package/dist/shortcuts/contract/operations/docx-verify.js +258 -0
- package/dist/shortcuts/contract/operations/elements-build.js +761 -0
- package/dist/shortcuts/contract/operations/elements-spec.js +216 -0
- package/dist/shortcuts/contract/operations/first-screen.js +588 -0
- package/dist/shortcuts/contract/operations/flow.js +81 -25
- package/dist/shortcuts/contract/operations/ledger.js +438 -0
- package/dist/shortcuts/contract/operations/modeltext.js +132 -0
- package/dist/shortcuts/contract/operations/op-resolver.js +22 -0
- package/dist/shortcuts/contract/operations/performance.js +104 -3
- package/dist/shortcuts/contract/operations/quote.js +131 -25
- package/dist/shortcuts/contract/operations/quotescreen.js +529 -0
- package/dist/shortcuts/contract/operations/registry.js +30 -0
- package/dist/shortcuts/contract/operations/review.js +73 -58
- package/dist/shortcuts/contract/operations/summary-validate.js +293 -0
- package/dist/shortcuts/contract/operations/summary.js +4 -2
- package/dist/shortcuts/contract/operations/triage.js +1100 -0
- package/dist/shortcuts/contract/operations/upload.js +48 -7
- package/dist/shortcuts/contract/prewarm-cache.js +90 -0
- package/dist/shortcuts/contract/prewarm.js +88 -0
- package/dist/shortcuts/contract/upload-cache.js +49 -4
- package/dist/shortcuts/data/index.js +1 -6
- package/dist/shortcuts/data/manifest.js +2 -2
- package/dist/shortcuts/data/operations/index.js +1 -1
- package/dist/shortcuts/data/operations/query.js +23 -46
- package/dist/shortcuts/index.js +5 -0
- package/dist/shortcuts/invoice/index.js +0 -12
- package/dist/shortcuts/invoice/manifest.js +200 -49
- package/dist/shortcuts/invoice/operations/registry.js +4 -2
- package/dist/shortcuts/invoice/operations/reim-relation.js +438 -0
- package/dist/shortcuts/invoice/operations/shared.js +3 -19
- package/dist/shortcuts/invoice/operations/upload-and-validate.js +109 -73
- package/dist/shortcuts/recruit-stage/operations/interview-arrange.js +4 -2
- package/dist/shortcuts/recruit-stage/operations/jd-create.js +6 -2
- package/dist/shortcuts/recruit-stage/operations/list.js +217 -1
- package/dist/shortcuts/recruit-stage/operations/resume-import.js +144 -158
- package/dist/shortcuts/recruit-stage/operations/search.js +348 -0
- package/dist/shortcuts/recruit-stage/shared.js +5 -0
- package/dist/shortcuts/recruit-stage/tag-lookup.js +136 -0
- package/dist/shortcuts/smart-extract/constants.js +79 -0
- package/dist/shortcuts/smart-extract/continuation.js +71 -0
- package/dist/shortcuts/smart-extract/errors.js +68 -0
- package/dist/shortcuts/smart-extract/host.js +191 -0
- package/dist/shortcuts/smart-extract/index.js +105 -0
- package/dist/shortcuts/smart-extract/ledger.js +70 -0
- package/dist/shortcuts/smart-extract/manifest.js +35 -0
- package/dist/shortcuts/smart-extract/operations/attachment.js +212 -0
- package/dist/shortcuts/smart-extract/operations/batch.js +67 -0
- package/dist/shortcuts/smart-extract/operations/config.js +118 -0
- package/dist/shortcuts/smart-extract/operations/fill.js +492 -0
- package/dist/shortcuts/smart-extract/operations/preview.js +174 -0
- package/dist/shortcuts/smart-extract/operations/registry.js +34 -0
- package/dist/shortcuts/smart-extract/operations/save.js +355 -0
- package/dist/shortcuts/smart-extract/operations/shared.js +191 -0
- package/dist/shortcuts/smart-extract/operations/structure.js +401 -0
- package/dist/shortcuts/smart-extract/operations/target.js +167 -0
- package/dist/shortcuts/smart-extract/operations/types.js +22 -0
- package/dist/shortcuts/smart-extract/operations/validate.js +454 -0
- package/dist/shortcuts/workflow/operations/form.js +68 -33
- package/dist/shortcuts/workflow/operations/read.js +19 -1
- package/docs/SKILL.md +1 -1
- package/docs/_catalog.md +3 -0
- package/docs/agent-invoice.md +5 -7
- package/docs/data.md +5 -1
- package/docs/fna.md +14 -1
- package/docs/invoice.md +7 -5
- package/docs/smart-extract.md +156 -0
- package/package.json +1 -1
- package/skill-template/business-info.json +16 -1
- package/skill-template/domains/qiyecheng.md +2 -0
- package/skill-template/domains/smart-extract.md +16 -0
- package/skill-template/domains/yepiaotong.md +2 -2
- package/skills/weaver-e10-data/references/scene-and-misc.md +4 -3
- package/skills/weaver-e10-jinchengda/SKILL.md +223 -35
- package/skills/weaver-e10-jinchengda/references/contract-action-card.md +47 -481
- package/skills/weaver-e10-jinchengda/references/contract-action-engine.md +11 -11
- package/skills/weaver-e10-jinchengda/references/contract-agent-entry.md +3 -3
- package/skills/weaver-e10-jinchengda/references/contract-ai-assistant.md +1 -1
- package/skills/weaver-e10-jinchengda/references/contract-ai-review.md +32 -16
- package/skills/weaver-e10-jinchengda/references/contract-card-render-internals.md +478 -0
- package/skills/weaver-e10-jinchengda/references/contract-command-index.md +4 -4
- package/skills/weaver-e10-jinchengda/references/contract-disabled-capabilities.md +2 -2
- package/skills/weaver-e10-jinchengda/references/contract-doc-triage.md +39 -61
- package/skills/weaver-e10-jinchengda/references/contract-element-save-record.md +18 -13
- package/skills/weaver-e10-jinchengda/references/contract-execution-rules.md +2 -2
- package/skills/weaver-e10-jinchengda/references/contract-field-extract-new-customer.md +21 -6
- package/skills/weaver-e10-jinchengda/references/contract-field-extract-other-flows.md +6 -4
- package/skills/weaver-e10-jinchengda/references/contract-flow-launch.md +3 -3
- package/skills/weaver-e10-jinchengda/references/contract-ledger-catalog.md +263 -0
- package/skills/weaver-e10-jinchengda/references/contract-ledger-query-playbook.md +525 -0
- package/skills/weaver-e10-jinchengda/references/contract-ledger-rules.md +36 -0
- package/skills/weaver-e10-jinchengda/references/contract-modeltext-library.md +128 -0
- package/skills/weaver-e10-jinchengda/references/contract-multi-file.md +87 -0
- package/skills/weaver-e10-jinchengda/references/contract-performance-query.md +80 -54
- package/skills/weaver-e10-jinchengda/references/contract-quote-to-contract.md +110 -14
- package/skills/weaver-e10-jinchengda/references/contract-template-selector.md +19 -21
- package/skills/weaver-e10-jinchengda/references/orchestration.md +12 -12
- package/skills/weaver-e10-jinchengda/references/source-manifest.json +1 -6
- package/skills/weaver-e10-jinchengda/scripts/fill_plan.py +2 -1
- package/skills/weaver-e10-qiyecheng/SKILL.md +37 -0
- package/skills/weaver-e10-qiyecheng/references/ai-check-audit.md +14 -0
- package/skills/weaver-e10-qiyecheng/references/budget.md +14 -0
- package/skills/weaver-e10-qiyecheng/references/catalog.md +25 -0
- package/skills/weaver-e10-qiyecheng/references/expense-center.md +8 -0
- package/skills/weaver-e10-qiyecheng/references/expense-chart.md +9 -0
- package/skills/weaver-e10-qiyecheng/references/invoice-writeoff.md +13 -0
- package/skills/weaver-e10-qiyecheng/references/loan-management.md +14 -0
- package/skills/weaver-e10-qiyecheng/references/self-hosted-mode.md +239 -0
- package/skills/weaver-e10-qiyecheng/references/source-manifest.json +34 -27
- package/skills/weaver-e10-recruit-stage/SKILL.md +62 -4
- package/skills/weaver-e10-recruit-stage/agents/openai.yaml +42 -8
- package/skills/weaver-e10-recruit-stage/references/env-ziyong.md +79 -0
- package/skills/weaver-e10-recruit-stage/references/recruit-arrange-interview.md +11 -3
- package/skills/weaver-e10-recruit-stage/references/recruit-edit-interview-feedback.md +3 -2
- package/skills/weaver-e10-recruit-stage/references/recruit-interview-not-attended.md +153 -0
- package/skills/weaver-e10-recruit-stage/references/recruit-jd-create.md +7 -4
- package/skills/weaver-e10-recruit-stage/references/recruit-match-candidates.md +1 -1
- package/skills/weaver-e10-recruit-stage/references/recruit-my-positions.md +66 -0
- package/skills/weaver-e10-recruit-stage/references/recruit-output-links.md +156 -42
- package/skills/weaver-e10-recruit-stage/references/recruit-resume-import-batch.md +122 -0
- package/skills/weaver-e10-recruit-stage/references/recruit-resume-import.md +36 -8
- package/skills/weaver-e10-recruit-stage/references/recruit-search-by-tag.md +157 -0
- package/skills/weaver-e10-recruit-stage/references/recruit-utterance-glossary.md +35 -0
- package/skills/weaver-e10-smart-extract/SKILL.md +180 -0
- package/skills/weaver-e10-smart-extract/references/api-contract.md +71 -0
- package/skills/weaver-e10-smart-extract/references/result-format.md +102 -0
- package/skills/weaver-e10-smart-extract/references/troubleshooting.md +106 -0
- package/skills/weaver-e10-workflow/references/workflow-create.md +6 -5
- package/skills/weaver-e10-workflow/references/workflow-edit.md +1 -1
- package/skills/weaver-e10-workflow/references/workflow-query.md +1 -1
- package/skills/weaver-e10-workflow/references/workflow-view.md +1 -1
- package/skills/weaver-e10-yepiaotong/SKILL.md +46 -33
- package/skills/weaver-e10-yepiaotong/references/invoice-add.md +2 -0
- package/skills/weaver-e10-yepiaotong/references/invoice-file-upload.md +1 -1
- package/skills/weaver-e10-yepiaotong/references/invoice-import.md +19 -2
- package/skills/weaver-e10-yepiaotong/references/invoice-ocr-preview.md +8 -2
- package/skills/weaver-e10-yepiaotong/references/invoice-reim-relation.md +407 -0
- package/skills/weaver-e10-yepiaotong/references/invoice-reim.md +12 -8
- package/skills/weaver-e10-yepiaotong/references/invoice-upload-and-validate.md +97 -39
- package/skills/weaver-e10-yepiaotong/references/reim-api-reference.md +91 -2
- package/skills/weaver-e10-yepiaotong/references/reim-examples.md +1 -1
- package/skills/weaver-e10-yepiaotong/references/reim-form-fill-rules.md +12 -12
- package/skills/weaver-e10-yepiaotong/references/reim-matching-rules.md +8 -4
- package/skills/weaver-e10-yepiaotong/references/reim-phone-subsidy-rules.md +136 -91
- package/skills/weaver-e10-yepiaotong/references/reim-workflow.md +109 -23
- package/skills/weaver-e10-yepiaotong/references/source-manifest.json +110 -43
- package/dist/shortcuts/invoice/operations/validate-preview.js +0 -40
- package/skills/weaver-e10-jinchengda/scripts/plan_actions.py +0 -279
- package/skills/weaver-e10-jinchengda/scripts/render_action_card.py +0 -450
- package/skills/weaver-e10-jinchengda/scripts/render_ebdf_list_card.py +0 -265
- package/skills/weaver-e10-jinchengda/scripts/render_risk_report.py +0 -358
- package/skills/weaver-e10-jinchengda/scripts/validate_action_card.py +0 -588
- package/skills/weaver-e10-jinchengda/scripts/verify_docx_placeholders.py +0 -118
- package/skills/weaver-e10-yepiaotong/references/invoice-validation-preview.md +0 -40
|
@@ -0,0 +1,1100 @@
|
|
|
1
|
+
import { existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from 'node:fs';
|
|
2
|
+
import { basename, join, resolve } from 'node:path';
|
|
3
|
+
import { inflateRawSync } from 'node:zlib';
|
|
4
|
+
import { contractValidationError } from '../errors.js';
|
|
5
|
+
/**
|
|
6
|
+
* 合同首屏阶段1:本地抽正文 + 指纹定 flowKey + 出 AI 语义填空骨架。
|
|
7
|
+
*
|
|
8
|
+
* 迁移自 `scripts/triage_contract.py`(2026-11-13 第六批下沉)。
|
|
9
|
+
* 迁移理由:原脚本 1079 行里只有 PDF 文本层抽取真正依赖 Python 第三方库,
|
|
10
|
+
* 其余(docx/doc 抽取、指纹打分、线索定位、摘要骨架、分节视图)Node 原生即可完成。
|
|
11
|
+
* 保留整包脚本导致 CLI 链路中间断了一个 Python 前置:阶段2 `contract.firstscreen.run`
|
|
12
|
+
* 强依赖 triage.json,缺文件时只能报「请先跑阶段1(Python 抽正文)」。
|
|
13
|
+
*
|
|
14
|
+
* PDF 处置:Node 无内置 PDF 文本层解析,遇到 .pdf 直接返回 `pdf_requires_fallback`,
|
|
15
|
+
* 由上游改用 parse_document 兜底或另存为 .docx,不再要求用户自备 Python 运行时。
|
|
16
|
+
*
|
|
17
|
+
* 行为与原脚本逐段对齐(2026-11-13 已用同一份合同做过产物比对):
|
|
18
|
+
* detect_title / count_chapters / score 指纹打分 / regex_hints / 摘要与要素骨架 /
|
|
19
|
+
* build_section_view 表格块整块保留 / _inject_terms_section 条款单一来源注入 /
|
|
20
|
+
* split_ai_fill / --reuse 阶段2 复用。
|
|
21
|
+
*/
|
|
22
|
+
// ────────────────────────── 通用工具 ──────────────────────────
|
|
23
|
+
/** Python 的 len() 按码点计数,这里保持一致。 */
|
|
24
|
+
function plen(text) {
|
|
25
|
+
return [...text].length;
|
|
26
|
+
}
|
|
27
|
+
/** Python `x or ''`(仅用于字符串兜底)。 */
|
|
28
|
+
function str(value) {
|
|
29
|
+
return typeof value === 'string' ? value : '';
|
|
30
|
+
}
|
|
31
|
+
function isRecord(value) {
|
|
32
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
33
|
+
}
|
|
34
|
+
function readJsonLoose(path) {
|
|
35
|
+
return JSON.parse(readFileSync(path, 'utf8').replace(/^\uFEFF/u, ''));
|
|
36
|
+
}
|
|
37
|
+
function writeJsonFile(path, value) {
|
|
38
|
+
writeFileSync(path, JSON.stringify(value, null, 2), 'utf8');
|
|
39
|
+
}
|
|
40
|
+
// ────────────────────────── 1. 正文抽取 ──────────────────────────
|
|
41
|
+
/** OOXML → 纯文本:段落换行、单元格用竖线分隔,保留表格可读性。 */
|
|
42
|
+
function xmlToText(xml) {
|
|
43
|
+
let x = xml;
|
|
44
|
+
x = x.replace(/<\/w:p>/gu, '\n');
|
|
45
|
+
x = x.replace(/<\/w:tr>/gu, '\n');
|
|
46
|
+
x = x.replace(/<\/w:tc>/gu, ' | ');
|
|
47
|
+
x = x.replace(/<w:tab[^>]*\/>/gu, '\t');
|
|
48
|
+
x = x.replace(/<w:br[^>]*\/>/gu, '\n');
|
|
49
|
+
x = x.replace(/<[^>]+>/gu, '');
|
|
50
|
+
for (const [from, to] of [
|
|
51
|
+
['<', '<'],
|
|
52
|
+
['>', '>'],
|
|
53
|
+
['&', '&'],
|
|
54
|
+
['"', '"'],
|
|
55
|
+
[''', "'"],
|
|
56
|
+
]) {
|
|
57
|
+
x = x.split(from).join(to);
|
|
58
|
+
}
|
|
59
|
+
x = x.replace(/[ \t]+\n/gu, '\n');
|
|
60
|
+
x = x.replace(/\n{3,}/gu, '\n\n');
|
|
61
|
+
return x.trim();
|
|
62
|
+
}
|
|
63
|
+
/** 从 zip 中央目录读取单个条目并解压(docx 本质是 zip)。 */
|
|
64
|
+
function readZipEntry(path, entryName) {
|
|
65
|
+
const buf = readFileSync(path);
|
|
66
|
+
const EOCD = 0x06054b50;
|
|
67
|
+
let eocd = -1;
|
|
68
|
+
const scanFrom = Math.max(0, buf.length - 22 - 0xffff);
|
|
69
|
+
for (let i = buf.length - 22; i >= scanFrom; i -= 1) {
|
|
70
|
+
if (buf.readUInt32LE(i) === EOCD) {
|
|
71
|
+
eocd = i;
|
|
72
|
+
break;
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
if (eocd < 0)
|
|
76
|
+
return null;
|
|
77
|
+
const count = buf.readUInt16LE(eocd + 10);
|
|
78
|
+
const cdOffset = buf.readUInt32LE(eocd + 16);
|
|
79
|
+
let p = cdOffset;
|
|
80
|
+
for (let n = 0; n < count; n += 1) {
|
|
81
|
+
if (p + 46 > buf.length || buf.readUInt32LE(p) !== 0x02014b50)
|
|
82
|
+
return null;
|
|
83
|
+
const method = buf.readUInt16LE(p + 10);
|
|
84
|
+
const compSize = buf.readUInt32LE(p + 20);
|
|
85
|
+
const nameLen = buf.readUInt16LE(p + 28);
|
|
86
|
+
const extraLen = buf.readUInt16LE(p + 30);
|
|
87
|
+
const commentLen = buf.readUInt16LE(p + 32);
|
|
88
|
+
const localOffset = buf.readUInt32LE(p + 42);
|
|
89
|
+
const name = buf.toString('utf8', p + 46, p + 46 + nameLen);
|
|
90
|
+
if (name === entryName) {
|
|
91
|
+
if (localOffset + 30 > buf.length || buf.readUInt32LE(localOffset) !== 0x04034b50)
|
|
92
|
+
return null;
|
|
93
|
+
const localNameLen = buf.readUInt16LE(localOffset + 26);
|
|
94
|
+
const localExtraLen = buf.readUInt16LE(localOffset + 28);
|
|
95
|
+
const dataStart = localOffset + 30 + localNameLen + localExtraLen;
|
|
96
|
+
const data = buf.subarray(dataStart, dataStart + compSize);
|
|
97
|
+
if (method === 0)
|
|
98
|
+
return Buffer.from(data);
|
|
99
|
+
if (method === 8)
|
|
100
|
+
return inflateRawSync(data);
|
|
101
|
+
return null;
|
|
102
|
+
}
|
|
103
|
+
p += 46 + nameLen + extraLen + commentLen;
|
|
104
|
+
}
|
|
105
|
+
return null;
|
|
106
|
+
}
|
|
107
|
+
function extractDocx(path) {
|
|
108
|
+
const xmlBuf = readZipEntry(path, 'word/document.xml');
|
|
109
|
+
if (!xmlBuf) {
|
|
110
|
+
throw contractValidationError('docx_invalid', 'docx 内未找到 word/document.xml(可能是加密或损坏的文件)');
|
|
111
|
+
}
|
|
112
|
+
return xmlToText(xmlBuf.toString('utf8'));
|
|
113
|
+
}
|
|
114
|
+
const DOC_VISIBLE = /[^\u4e00-\u9fa5A-Za-z0-9,。、;:()()【】%¥.\-\s]/gu;
|
|
115
|
+
/**
|
|
116
|
+
* 老式 .doc 无 OOXML,只能尽力抽可见片段(与原脚本同属降级路径)。
|
|
117
|
+
* Word 97 二进制通常以 UTF-16LE 存放正文,故先按 UTF-16LE 解;
|
|
118
|
+
* 命中中文比例过低时回退单字节视图(此时中文会丢,会写入 warnings 提示另存为 .docx)。
|
|
119
|
+
*/
|
|
120
|
+
function extractDoc(path) {
|
|
121
|
+
const raw = readFileSync(path);
|
|
122
|
+
const utf16 = raw.toString('utf16le').replace(DOC_VISIBLE, ' ');
|
|
123
|
+
const cjk = (utf16.match(/[\u4e00-\u9fa5]/gu) ?? []).length;
|
|
124
|
+
const visible = utf16.replace(/\s/gu, '').length || 1;
|
|
125
|
+
if (cjk / visible >= 0.15) {
|
|
126
|
+
return { text: utf16.replace(/\s{2,}/gu, '\n').trim(), degraded: false };
|
|
127
|
+
}
|
|
128
|
+
const latin = raw.toString('latin1').replace(DOC_VISIBLE, ' ');
|
|
129
|
+
return { text: latin.replace(/\s{2,}/gu, '\n').trim(), degraded: true };
|
|
130
|
+
}
|
|
131
|
+
function extractText(path) {
|
|
132
|
+
const lower = path.toLowerCase();
|
|
133
|
+
if (lower.endsWith('.docx'))
|
|
134
|
+
return { text: extractDocx(path), degraded: false };
|
|
135
|
+
if (lower.endsWith('.doc'))
|
|
136
|
+
return extractDoc(path);
|
|
137
|
+
if (lower.endsWith('.pdf')) {
|
|
138
|
+
throw contractValidationError('pdf_requires_fallback', 'Node 无内置 PDF 文本层解析能力:请先用 parse_document 抽取 PDF 正文,或把文件另存为 .docx 后再跑本 operation');
|
|
139
|
+
}
|
|
140
|
+
if (lower.endsWith('.txt') || lower.endsWith('.md')) {
|
|
141
|
+
return { text: readFileSync(path, 'utf8'), degraded: false };
|
|
142
|
+
}
|
|
143
|
+
throw contractValidationError('file_type_unsupported', `不支持的文件类型:${lower.slice(lower.lastIndexOf('.'))}(仅 .docx/.doc/.txt/.md;.pdf 需 parse_document 兜底)`);
|
|
144
|
+
}
|
|
145
|
+
// ────────────────────────── 2. 指纹打分 ──────────────────────────
|
|
146
|
+
/** key = flowKey;label = 指纹编号;标题命中的非 F1 类别优先于新客户。 */
|
|
147
|
+
const TITLE_RULES = [
|
|
148
|
+
{ key: '老客户增值', label: 'F2', pat: /增值服务/u },
|
|
149
|
+
{ key: '常规二次销售', label: 'F3', pat: /年度维护/u },
|
|
150
|
+
{ key: '常规二次销售', label: 'F4', pat: /第三方产品/u },
|
|
151
|
+
{ key: '常规二次销售', label: 'F5', pat: /用户使用许可增购|许可增购|增购/u },
|
|
152
|
+
{ key: '老客户增值', label: 'F6', pat: /升级合同|升级服务合同|版本升级/u },
|
|
153
|
+
{ key: '新客户', label: 'F1', pat: /(软件)?产品及实施服务购买合同/u },
|
|
154
|
+
];
|
|
155
|
+
const QY_SUO_TITLE = /契约锁/u;
|
|
156
|
+
const QY_SUO_CORE = /(电子签章平台|电子签平台|电子签约平台|契约锁平台)/u;
|
|
157
|
+
const F5_TRIPLE = ['原有', '本次购买', '共有'];
|
|
158
|
+
const F6_MIGRATION = /升级为|升级包|升级服务|版本迁移/u;
|
|
159
|
+
const F1_SUBJECT_WORDS = ['系统软件产品费用', '软件产品费用', 'e-cology产品购买', 'e-cology 产品购买'];
|
|
160
|
+
const F3_CHAPTERS = ['服务范围', '服务期限', '服务内容', '合同标的及付费方式'];
|
|
161
|
+
const F1_CHAPTERS = ['授予使用许可权', '产品交付'];
|
|
162
|
+
const F2_SUBJECT = ['软件功能费用', '实施开发费用'];
|
|
163
|
+
/** 全角→半角、去空白,仅用于关键词比对,不改原文。 */
|
|
164
|
+
function norm(input) {
|
|
165
|
+
const chars = [];
|
|
166
|
+
for (const ch of input) {
|
|
167
|
+
const code = ch.codePointAt(0) ?? 0;
|
|
168
|
+
if (code === 0x3000)
|
|
169
|
+
chars.push(' ');
|
|
170
|
+
else if (code >= 0xff01 && code <= 0xff5e)
|
|
171
|
+
chars.push(String.fromCodePoint(code - 0xfee0));
|
|
172
|
+
else
|
|
173
|
+
chars.push(ch);
|
|
174
|
+
}
|
|
175
|
+
return chars.join('').replace(/\s+/gu, '');
|
|
176
|
+
}
|
|
177
|
+
function detectTitle(text) {
|
|
178
|
+
const lines = text
|
|
179
|
+
.split('\n')
|
|
180
|
+
.map((line) => line.trim())
|
|
181
|
+
.filter((line) => line.length > 0);
|
|
182
|
+
const cands = [];
|
|
183
|
+
for (const line of lines.slice(0, 40)) {
|
|
184
|
+
if (!line.includes('合同'))
|
|
185
|
+
continue;
|
|
186
|
+
if (plen(line) > 60)
|
|
187
|
+
continue;
|
|
188
|
+
if (line.startsWith('第') || line.startsWith('TOC') || line.startsWith('目录'))
|
|
189
|
+
continue;
|
|
190
|
+
cands.push(line);
|
|
191
|
+
}
|
|
192
|
+
if (cands.length > 0) {
|
|
193
|
+
let best = cands[0];
|
|
194
|
+
for (const cand of cands) {
|
|
195
|
+
if (plen(cand) > plen(best))
|
|
196
|
+
best = cand;
|
|
197
|
+
}
|
|
198
|
+
return best;
|
|
199
|
+
}
|
|
200
|
+
return lines[0] ?? '';
|
|
201
|
+
}
|
|
202
|
+
function countChapters(text) {
|
|
203
|
+
return (text.match(/第[一二三四五六七八九十百]+章/gu) ?? []).length;
|
|
204
|
+
}
|
|
205
|
+
function scoreContract(text, title) {
|
|
206
|
+
const ntext = norm(text);
|
|
207
|
+
const ntitle = norm(title);
|
|
208
|
+
const evidence = [];
|
|
209
|
+
const cand = new Map();
|
|
210
|
+
const add = (key, value, why) => {
|
|
211
|
+
cand.set(key, (cand.get(key) ?? 0) + value);
|
|
212
|
+
evidence.push({ type: key, score: value, reason: why });
|
|
213
|
+
};
|
|
214
|
+
const result = (flowKey, sc, basis, label, confidence, needsConfirm, ev, candidates) => ({
|
|
215
|
+
flowKey,
|
|
216
|
+
score: sc,
|
|
217
|
+
basis,
|
|
218
|
+
label,
|
|
219
|
+
confidence,
|
|
220
|
+
needsConfirm,
|
|
221
|
+
evidence: ev,
|
|
222
|
+
candidates: Object.fromEntries(candidates),
|
|
223
|
+
});
|
|
224
|
+
// D1 契约锁闸门:只认标题或平台类核心标的,不认明细里出现一次电子签
|
|
225
|
+
if (QY_SUO_TITLE.test(title) || QY_SUO_CORE.test(title)) {
|
|
226
|
+
return result('契约锁', 100, 'title', 'D1', 0.95, false, [
|
|
227
|
+
{ type: '契约锁', score: 100, reason: '标题即契约锁/电子签平台' },
|
|
228
|
+
], new Map([['契约锁', 100]]));
|
|
229
|
+
}
|
|
230
|
+
// D2-a 标题正则(100 分,决定性)
|
|
231
|
+
const titleHits = TITLE_RULES.filter((rule) => rule.pat.test(ntitle));
|
|
232
|
+
if (titleHits.length > 0) {
|
|
233
|
+
const nonF1 = titleHits.filter((rule) => rule.label !== 'F1');
|
|
234
|
+
const pick = (nonF1.length > 0 ? nonF1 : titleHits)[0];
|
|
235
|
+
return result(pick.key, 100, 'title', pick.label, 0.95, false, [
|
|
236
|
+
{ type: pick.key, score: 100, reason: `标题命中 ${pick.label} 正则:${pick.pat.source}` },
|
|
237
|
+
], new Map([[pick.key, 100]]));
|
|
238
|
+
}
|
|
239
|
+
// D2-b 正文强指纹
|
|
240
|
+
if (F5_TRIPLE.every((word) => ntext.includes(word))) {
|
|
241
|
+
add('常规二次销售', 85, '存量增量三连(原有+本次购买+共有)');
|
|
242
|
+
}
|
|
243
|
+
if (F6_MIGRATION.test(ntext)) {
|
|
244
|
+
add('老客户增值', 85, '版本迁移句式(升级为/升级包/升级服务/版本迁移)');
|
|
245
|
+
}
|
|
246
|
+
if (F3_CHAPTERS.every((chapter) => ntext.includes(norm(chapter)))) {
|
|
247
|
+
add('常规二次销售', 80, 'F3 独有章节四连(服务范围/期限/内容/标的及付费方式)');
|
|
248
|
+
}
|
|
249
|
+
if (ntext.includes(norm('交付内容')) && !ntext.includes(norm('产品交付'))) {
|
|
250
|
+
add('常规二次销售', 80, 'F4 独有章节「交付内容」且无「产品交付」');
|
|
251
|
+
}
|
|
252
|
+
if (F1_CHAPTERS.every((chapter) => ntext.includes(norm(chapter)))) {
|
|
253
|
+
add('新客户', 80, 'F1 加分章节(授予使用许可权 + 产品交付)');
|
|
254
|
+
}
|
|
255
|
+
if (F1_SUBJECT_WORDS.some((word) => ntext.includes(norm(word)))) {
|
|
256
|
+
add('新客户', 80, 'F1 标的达标词(系统软件产品费用/软件产品费用/e-cology产品购买)');
|
|
257
|
+
}
|
|
258
|
+
if (F2_SUBJECT.every((word) => ntext.includes(norm(word)))) {
|
|
259
|
+
add('老客户增值', 70, 'F2 标的语义(软件功能费用 + 实施开发服务费用)');
|
|
260
|
+
}
|
|
261
|
+
// 章节数加权
|
|
262
|
+
const chapters = countChapters(text);
|
|
263
|
+
const chapterMap = {
|
|
264
|
+
16: '新客户',
|
|
265
|
+
14: '老客户增值',
|
|
266
|
+
12: '常规二次销售',
|
|
267
|
+
11: '常规二次销售',
|
|
268
|
+
};
|
|
269
|
+
if (chapterMap[chapters]) {
|
|
270
|
+
add(chapterMap[chapters], 10, `章节数 ${chapters} 与某类模板一致(仅加权)`);
|
|
271
|
+
}
|
|
272
|
+
// 反信号
|
|
273
|
+
if (!ntext.includes('知识产权')) {
|
|
274
|
+
const key = '常规二次销售';
|
|
275
|
+
if (!cand.has(key))
|
|
276
|
+
cand.set(key, 0);
|
|
277
|
+
cand.set(key, (cand.get(key) ?? 0) - 20);
|
|
278
|
+
evidence.push({ type: key, score: -20, reason: '反信号:无「知识产权」章' });
|
|
279
|
+
}
|
|
280
|
+
if (cand.size === 0) {
|
|
281
|
+
return result(null, 0, null, null, 0, true, [], new Map());
|
|
282
|
+
}
|
|
283
|
+
let bestKey = '';
|
|
284
|
+
let bestScore = Number.NEGATIVE_INFINITY;
|
|
285
|
+
for (const [key, value] of cand) {
|
|
286
|
+
if (value > bestScore) {
|
|
287
|
+
bestKey = key;
|
|
288
|
+
bestScore = value;
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
let confidence;
|
|
292
|
+
let needsConfirm;
|
|
293
|
+
if (bestScore >= 80) {
|
|
294
|
+
confidence = 0.9;
|
|
295
|
+
needsConfirm = false;
|
|
296
|
+
}
|
|
297
|
+
else if (bestScore >= 60) {
|
|
298
|
+
confidence = 0.65;
|
|
299
|
+
needsConfirm = true;
|
|
300
|
+
}
|
|
301
|
+
else {
|
|
302
|
+
return result(null, bestScore, null, null, 0.3, true, evidence, cand);
|
|
303
|
+
}
|
|
304
|
+
const label = TITLE_RULES.find((rule) => rule.key === bestKey)?.label ?? 'D2';
|
|
305
|
+
return result(bestKey, bestScore, bestScore < 85 ? 'structure' : 'subject-semantic', label, confidence, needsConfirm, evidence, cand);
|
|
306
|
+
}
|
|
307
|
+
// ────────────────────────── 3. 要素线索(仅定位,不取值) ──────────────────────────
|
|
308
|
+
const HINT_PATTERNS = [
|
|
309
|
+
['甲方', /甲方/gu],
|
|
310
|
+
['乙方', /乙方/gu],
|
|
311
|
+
['丙方', /丙方/gu],
|
|
312
|
+
['最终用户', /最终用户/gu],
|
|
313
|
+
['签订时间', /签订时间|签署日期|签订日期/gu],
|
|
314
|
+
['签订地点', /签订地点|签署地点/gu],
|
|
315
|
+
['合同总额', /合同标的总额|总额|合计|合同总价/gu],
|
|
316
|
+
['付款方式', /付款方式|付款阶段|付款比例/gu],
|
|
317
|
+
['交付地点', /交付地点|服务地点|履行地点/gu],
|
|
318
|
+
['生效条件', /生效条件|盖章后生效|生效/gu],
|
|
319
|
+
['发票税率', /增值税|发票|税率/gu],
|
|
320
|
+
['合同编号', /合同编号/gu],
|
|
321
|
+
['维护费', /维护费|维护服务/gu],
|
|
322
|
+
['验收', /验收/gu],
|
|
323
|
+
['知识产权', /知识产权/gu],
|
|
324
|
+
['保密', /保密/gu],
|
|
325
|
+
['违约责任', /违约责任/gu],
|
|
326
|
+
['争议解决', /争议|仲裁|诉讼/gu],
|
|
327
|
+
['交付期限', /交付期限|服务期限|履行期限/gu],
|
|
328
|
+
];
|
|
329
|
+
const OUR_COMPANY_WORDS = ['泛微网络', '泛微软件'];
|
|
330
|
+
/** 只给行号与片段,不返回任何字段值。 */
|
|
331
|
+
function regexHints(text) {
|
|
332
|
+
const hints = [];
|
|
333
|
+
const newlines = [0];
|
|
334
|
+
for (let i = 0; i < text.length; i += 1) {
|
|
335
|
+
if (text[i] === '\n')
|
|
336
|
+
newlines.push(i + 1);
|
|
337
|
+
}
|
|
338
|
+
const lineAt = (index) => {
|
|
339
|
+
let lo = 0;
|
|
340
|
+
let hi = newlines.length - 1;
|
|
341
|
+
while (lo < hi) {
|
|
342
|
+
const mid = Math.ceil((lo + hi) / 2);
|
|
343
|
+
if (newlines[mid] <= index)
|
|
344
|
+
lo = mid;
|
|
345
|
+
else
|
|
346
|
+
hi = mid - 1;
|
|
347
|
+
}
|
|
348
|
+
return lo + 1;
|
|
349
|
+
};
|
|
350
|
+
for (const [kind, pattern] of HINT_PATTERNS) {
|
|
351
|
+
const re = new RegExp(pattern.source, 'gu');
|
|
352
|
+
let count = 0;
|
|
353
|
+
let match;
|
|
354
|
+
while ((match = re.exec(text)) !== null) {
|
|
355
|
+
const seg = text
|
|
356
|
+
.slice(match.index, match.index + 120)
|
|
357
|
+
.split(/\s+/u)
|
|
358
|
+
.filter((part) => part.length > 0)
|
|
359
|
+
.join(' ');
|
|
360
|
+
hints.push({ kind, line: lineAt(match.index), snippet: seg.slice(0, 120) });
|
|
361
|
+
count += 1;
|
|
362
|
+
if (count >= 2)
|
|
363
|
+
break;
|
|
364
|
+
if (match[0].length === 0)
|
|
365
|
+
re.lastIndex += 1;
|
|
366
|
+
}
|
|
367
|
+
}
|
|
368
|
+
return hints;
|
|
369
|
+
}
|
|
370
|
+
// ────────────────────────── 4. 摘要与要素骨架 ──────────────────────────
|
|
371
|
+
const FLOW_LABEL = {
|
|
372
|
+
新客户: '新客户购买合同',
|
|
373
|
+
老客户增值: '老客户增值合同',
|
|
374
|
+
常规二次销售: '常规二次销售合同',
|
|
375
|
+
契约锁: '契约锁合同',
|
|
376
|
+
};
|
|
377
|
+
const BASE_ELEMENT_ROWS = [
|
|
378
|
+
['合同类型', '四类归属 + 细分,如「新客户(标准产品及实施服务)」'],
|
|
379
|
+
['合同总额', '小写金额 + 人民币大写;原文占位标记(如 120,000)原样保留,禁止换算'],
|
|
380
|
+
['甲方(签约相对方)', '甲方全称;代理签约时注明「代理签约,最终用户 XX」'],
|
|
381
|
+
['乙方(我方)', '我方签约主体全称;与甲方不重复展示'],
|
|
382
|
+
['合同标的', '主项 1~3 个 + 「另 N 项」'],
|
|
383
|
+
['付款方式', '比例序列 + 触发节点,如「40%/40%/20%|签约后 / 调研后 / 验收后」'],
|
|
384
|
+
['履行或服务期限', '起止日期;无则「未识别」'],
|
|
385
|
+
['交付或服务地点', '抽不到写「未识别」;禁止用签订地点顶替'],
|
|
386
|
+
['签订时间', '具体日期;留空写「留空待填」'],
|
|
387
|
+
['签订地点', '城市'],
|
|
388
|
+
['生效条件', '如「双方盖章后生效」'],
|
|
389
|
+
['发票类型与税率', '如「13% 增值税专用发票」;税率不得计入付款比例'],
|
|
390
|
+
['合同编号', '有则填,无则「未识别」'],
|
|
391
|
+
['文件信息', '文件名 + 解析字数'],
|
|
392
|
+
];
|
|
393
|
+
const TYPE_EXTRA_ROWS = {
|
|
394
|
+
新客户: [
|
|
395
|
+
['产品交付方式', '现场实施 / 远程 / 分阶段'],
|
|
396
|
+
['许可范围', '用户数、模块范围、部署方式'],
|
|
397
|
+
['实施周期', '开工至验收的周期约定'],
|
|
398
|
+
],
|
|
399
|
+
老客户增值: [
|
|
400
|
+
['功能模块清单', '本次新增或升级的模块'],
|
|
401
|
+
['实施开发范围', '含不含定制开发'],
|
|
402
|
+
['验收标准', '验收条件与依据'],
|
|
403
|
+
],
|
|
404
|
+
常规二次销售: [
|
|
405
|
+
['服务范围', '含不含硬件 / 数据库'],
|
|
406
|
+
['响应时限', 'SLA 约定'],
|
|
407
|
+
['维护内容清单', '维护事项枚举'],
|
|
408
|
+
],
|
|
409
|
+
契约锁: [
|
|
410
|
+
['用印方式', '物理用印 / 电子用印'],
|
|
411
|
+
['签署方式', '顺序签 / 并行签'],
|
|
412
|
+
['印章类型', '公章 / 合同章 / 法人章'],
|
|
413
|
+
],
|
|
414
|
+
};
|
|
415
|
+
const SECTIONS_SPEC = [
|
|
416
|
+
'头部:badge(四类归属)+ title + meta(文件名 + 解析字数)',
|
|
417
|
+
'业务分类归属(reasons):一句话结论 + 2~3 条依据',
|
|
418
|
+
'要素卡(table):上面列出的必填行 + 类型补充行,共 14~18 行',
|
|
419
|
+
'标的明细(table,可选):编号 / 名称 / 单价 / 数量 / 金额,不做求和校验',
|
|
420
|
+
'付款节点(table,可选):阶段 / 比例 / 金额 / 触发条件',
|
|
421
|
+
'其他关键条款(list):不在 ai_fill 里填写,由 elements.terms 在阶段2 自动生成,禁止重复写',
|
|
422
|
+
'下一步(next):一句话说明在右侧卡片里选择',
|
|
423
|
+
];
|
|
424
|
+
const CONSTRAINTS = [
|
|
425
|
+
'禁止使用 grid 类型:CLI 渲染器只输出空容器,内容会整段丢失,一律用 table',
|
|
426
|
+
'摘要只做客观呈现:禁止 alert / checks 风险段、禁止 ⚠️/✅ 标记、禁止「建议核对」类措辞',
|
|
427
|
+
'金额中的原文占位标记(如 120,000)原样保留,禁止换算成数字',
|
|
428
|
+
'税率(如 13% 增值税)不得计入付款比例;付款比例总和一般不超过 100%',
|
|
429
|
+
'交付地点不得用签订地点顶替;两者都没有就写「未识别」',
|
|
430
|
+
'所有取值必须来自 contract_text.txt 原文语义;取不到写「未识别」,禁止推测',
|
|
431
|
+
'签约相对方是甲方;资信查询对象取甲方,不是最终用户',
|
|
432
|
+
];
|
|
433
|
+
const SUMMARY_FORMAT = {
|
|
434
|
+
topLevel: {
|
|
435
|
+
badge: '四类归属,与 flowKey 一致',
|
|
436
|
+
title: '合同标题',
|
|
437
|
+
subtitle: '文件名 | 解析字数',
|
|
438
|
+
sections: '数组,元素按 allowedTypes 组合',
|
|
439
|
+
},
|
|
440
|
+
allowedTypes: {
|
|
441
|
+
reasons: { items: ['字符串', '...'] },
|
|
442
|
+
table: { rows: [['标签', '值'], ['标签', '值']] },
|
|
443
|
+
list: { items: ['字符串', '...'] },
|
|
444
|
+
next: { text: '字符串' },
|
|
445
|
+
},
|
|
446
|
+
forbiddenTypes: ['grid', 'alert', 'checks'],
|
|
447
|
+
hardRules: [
|
|
448
|
+
'table 的 rows 每行只放「标签 + 值」成对出现;禁止对象形式;每行不得出现更多取值',
|
|
449
|
+
'禁止 grid:渲染器只输出空容器,内容整段丢失',
|
|
450
|
+
'禁止 alert / checks:摘要只做客观呈现,风险内容归「合同预审」',
|
|
451
|
+
'以下 4 个标签必须出现在某个 table 的 rows 里:合同类型 / 合同总额 / 甲方 / 乙方',
|
|
452
|
+
'税率不得计入付款比例;付款比例合计不超过 100%',
|
|
453
|
+
'取不到的值写「未识别」,禁止推测或换算原文占位标记',
|
|
454
|
+
],
|
|
455
|
+
requiredRowLabels: ['合同类型', '合同总额', '甲方', '乙方'],
|
|
456
|
+
};
|
|
457
|
+
const ELEMENTS_TEMPLATE = {
|
|
458
|
+
partyA: '',
|
|
459
|
+
partyB: '',
|
|
460
|
+
partyC: '',
|
|
461
|
+
finalUser: '',
|
|
462
|
+
signDate: '',
|
|
463
|
+
signPlace: '',
|
|
464
|
+
deliveryPlace: '',
|
|
465
|
+
effectiveCondition: '',
|
|
466
|
+
contractNo: '',
|
|
467
|
+
totalAmount: '',
|
|
468
|
+
invoiceTax: '',
|
|
469
|
+
version: '',
|
|
470
|
+
payments: [{ node: '', ratio: '', amount: '' }],
|
|
471
|
+
items: [{ name: '', price: '', discount: '', amount: '' }],
|
|
472
|
+
terms: [{ name: '', content: '' }],
|
|
473
|
+
missing: [],
|
|
474
|
+
};
|
|
475
|
+
const ELEMENTS_NEW_CUSTOMER = {
|
|
476
|
+
partyA: '', partyB: '', partyC: '', finalUser: '',
|
|
477
|
+
buyMode: '', partner: '', ourCompany: '', title: '', background: '',
|
|
478
|
+
totalAmount: '', signForm: '', signDate: '', signDateType: '', signWay: '',
|
|
479
|
+
address: '', receiver: '', mobile: '',
|
|
480
|
+
solutions: [{ name: '', amount: '0' }],
|
|
481
|
+
items: [{ name: '', price: '', discount: '', amount: '' }],
|
|
482
|
+
payments: [{ node: '', ratio: '', amount: '' }],
|
|
483
|
+
terms: [{ name: '', content: '' }],
|
|
484
|
+
missing: [],
|
|
485
|
+
};
|
|
486
|
+
const ELEMENTS_QIYUESUO = {
|
|
487
|
+
partyA: '', partyB: '', partyC: '', finalUser: '',
|
|
488
|
+
title: '', contractName: '', totalAmount: '',
|
|
489
|
+
buyMode: '', ourCompany: '', signForm: '', signDateType: '', signWay: '',
|
|
490
|
+
implParty: '', relatedProduct: '', contractType: '', isXinChuang: '',
|
|
491
|
+
partner: '', partySigner: '', partyContact: '',
|
|
492
|
+
address: '', receiver: '', mobile: '',
|
|
493
|
+
items: [{ name: '', price: '', discount: '', amount: '' }],
|
|
494
|
+
payments: [{ node: '', ratio: '', amount: '' }],
|
|
495
|
+
terms: [{ name: '', content: '' }],
|
|
496
|
+
missing: [],
|
|
497
|
+
};
|
|
498
|
+
const ELEMENTS_RESALE = {
|
|
499
|
+
partyA: '', partyB: '', partyC: '', finalUser: '',
|
|
500
|
+
title: '', contractName: '', totalAmount: '', background: '',
|
|
501
|
+
buyMode: '', ourCompany: '', signForm: '', signDateType: '', signWay: '',
|
|
502
|
+
contractType: '', partner: '', purchase: [],
|
|
503
|
+
address: '', receiver: '', mobile: '',
|
|
504
|
+
items: [{ name: '', price: '', discount: '', amount: '' }],
|
|
505
|
+
payments: [{ node: '', ratio: '', amount: '' }],
|
|
506
|
+
terms: [{ name: '', content: '' }],
|
|
507
|
+
missing: [],
|
|
508
|
+
};
|
|
509
|
+
const ELEMENTS_UPSALE = {
|
|
510
|
+
partyA: '', partyB: '', partyC: '', finalUser: '',
|
|
511
|
+
title: '', contractName: '', totalAmount: '', background: '',
|
|
512
|
+
buyMode: '', ourCompany: '', signForm: '', signDateType: '', signWay: '',
|
|
513
|
+
contractType: '', partner: '', purchase: [],
|
|
514
|
+
address: '', receiver: '', mobile: '',
|
|
515
|
+
items: [{ name: '', price: '', discount: '', amount: '' }],
|
|
516
|
+
payments: [{ node: '', ratio: '', amount: '' }],
|
|
517
|
+
terms: [{ name: '', content: '' }],
|
|
518
|
+
missing: [],
|
|
519
|
+
};
|
|
520
|
+
const ELEMENTS_BY_FLOW = {
|
|
521
|
+
新客户: ELEMENTS_NEW_CUSTOMER,
|
|
522
|
+
契约锁: ELEMENTS_QIYUESUO,
|
|
523
|
+
常规二次销售: ELEMENTS_RESALE,
|
|
524
|
+
老客户增值: ELEMENTS_UPSALE,
|
|
525
|
+
};
|
|
526
|
+
/** 按 flowKey 返回 elements 骨架(深拷贝,避免跨次污染)。 */
|
|
527
|
+
function buildElementsTemplate(flowKey) {
|
|
528
|
+
const base = ELEMENTS_BY_FLOW[(flowKey ?? '').trim()] ?? ELEMENTS_TEMPLATE;
|
|
529
|
+
return JSON.parse(JSON.stringify(base));
|
|
530
|
+
}
|
|
531
|
+
function buildSummaryTemplate(flowKey, title, fileName, textLen, rows) {
|
|
532
|
+
const labels = rows.map((row) => row.row);
|
|
533
|
+
return {
|
|
534
|
+
badge: flowKey,
|
|
535
|
+
title: title || '',
|
|
536
|
+
subtitle: `${fileName} | 解析 ${textLen} 字`,
|
|
537
|
+
sections: [
|
|
538
|
+
{
|
|
539
|
+
title: '业务分类归属',
|
|
540
|
+
type: 'reasons',
|
|
541
|
+
items: ['结论:<四类之一 + 一句话>', '依据一:<章节或标的层面的依据>', '依据二:<合同内容层面的依据>'],
|
|
542
|
+
},
|
|
543
|
+
{ title: '合同要素', type: 'table', rows: labels.map((label) => [label, '']) },
|
|
544
|
+
{
|
|
545
|
+
title: '标的明细',
|
|
546
|
+
type: 'table',
|
|
547
|
+
rows: [['编号 1|<标的名称>', '<单价> → <金额>'], ['合计', '']],
|
|
548
|
+
},
|
|
549
|
+
{
|
|
550
|
+
title: '付款节点',
|
|
551
|
+
type: 'table',
|
|
552
|
+
rows: [['<触发节点>', '比例 <x>%|金额 <金额>|<条件>'], ['合计', '100%']],
|
|
553
|
+
},
|
|
554
|
+
{
|
|
555
|
+
title: '下一步',
|
|
556
|
+
type: 'next',
|
|
557
|
+
text: '可在右侧卡片中选择:发起对应合同流程、AI 预审或查对方资信。',
|
|
558
|
+
},
|
|
559
|
+
],
|
|
560
|
+
};
|
|
561
|
+
}
|
|
562
|
+
const TABLE_PROSE_MIN = 60;
|
|
563
|
+
/** 判断某行是否可作为表格块边界(章节标题或成句散文)。 */
|
|
564
|
+
function isProseBoundary(line) {
|
|
565
|
+
const text = (line ?? '').trim();
|
|
566
|
+
if (!text)
|
|
567
|
+
return false;
|
|
568
|
+
if (text.startsWith('|'))
|
|
569
|
+
return false;
|
|
570
|
+
if (/^第[一二三四五六七八九十百零〇\d]+章/u.test(text))
|
|
571
|
+
return true;
|
|
572
|
+
if (plen(text) >= TABLE_PROSE_MIN && /[。;]/u.test(text))
|
|
573
|
+
return true;
|
|
574
|
+
return false;
|
|
575
|
+
}
|
|
576
|
+
/**
|
|
577
|
+
* 表格块覆盖的行下标集合(含块内空行、单元格行与表标题行)。
|
|
578
|
+
* 表格必须整块保留:标的 / 功能清单 / 付款节点表的单元格多为模块名,
|
|
579
|
+
* 不含要素关键词,逐行过滤会把整张表丢掉,导致专项方案整批漏抽。
|
|
580
|
+
*/
|
|
581
|
+
function tableBlockLines(lines) {
|
|
582
|
+
const blocks = new Set();
|
|
583
|
+
const n = lines.length;
|
|
584
|
+
let i = 0;
|
|
585
|
+
while (i < n) {
|
|
586
|
+
if (!lines[i].trim().startsWith('|')) {
|
|
587
|
+
i += 1;
|
|
588
|
+
continue;
|
|
589
|
+
}
|
|
590
|
+
let lo = i;
|
|
591
|
+
while (lo - 1 >= 0 && !isProseBoundary(lines[lo - 1]))
|
|
592
|
+
lo -= 1;
|
|
593
|
+
let hi = i;
|
|
594
|
+
while (hi + 1 < n && !isProseBoundary(lines[hi + 1]))
|
|
595
|
+
hi += 1;
|
|
596
|
+
let cells = 0;
|
|
597
|
+
for (let j = lo; j <= hi; j += 1) {
|
|
598
|
+
if (lines[j].trim().startsWith('|'))
|
|
599
|
+
cells += 1;
|
|
600
|
+
}
|
|
601
|
+
if (cells >= 2) {
|
|
602
|
+
for (let j = lo; j <= hi; j += 1)
|
|
603
|
+
blocks.add(j);
|
|
604
|
+
}
|
|
605
|
+
i = hi + 1;
|
|
606
|
+
}
|
|
607
|
+
return blocks;
|
|
608
|
+
}
|
|
609
|
+
/** 要素区段视图(辅助定位用,取值一律以 contract_text.txt 全文为准)。 */
|
|
610
|
+
function buildSectionView(text, hints, maxChars = 24000) {
|
|
611
|
+
const lines = text.split(/\r?\n/u);
|
|
612
|
+
if (lines.length === 0)
|
|
613
|
+
return '';
|
|
614
|
+
const keep = new Set();
|
|
615
|
+
for (let i = 0; i < Math.min(40, lines.length); i += 1)
|
|
616
|
+
keep.add(i);
|
|
617
|
+
for (let i = Math.max(0, lines.length - 40); i < lines.length; i += 1)
|
|
618
|
+
keep.add(i);
|
|
619
|
+
for (const hint of hints ?? []) {
|
|
620
|
+
const base = (hint.line || 0) - 1;
|
|
621
|
+
for (const delta of [-1, 0, 1]) {
|
|
622
|
+
const index = base + delta;
|
|
623
|
+
if (index >= 0 && index < lines.length)
|
|
624
|
+
keep.add(index);
|
|
625
|
+
}
|
|
626
|
+
}
|
|
627
|
+
for (const index of tableBlockLines(lines))
|
|
628
|
+
keep.add(index);
|
|
629
|
+
const body = [];
|
|
630
|
+
let prev = null;
|
|
631
|
+
for (const index of [...keep].sort((a, b) => a - b)) {
|
|
632
|
+
if (prev !== null && index !== prev + 1)
|
|
633
|
+
body.push('...');
|
|
634
|
+
const line = lines[index].trim();
|
|
635
|
+
if (line)
|
|
636
|
+
body.push(`L${index + 1}: ${[...line].slice(0, 220).join('')}`);
|
|
637
|
+
prev = index;
|
|
638
|
+
}
|
|
639
|
+
let blob = body.join('\n');
|
|
640
|
+
if (plen(blob) > maxChars) {
|
|
641
|
+
const chars = [...blob];
|
|
642
|
+
let cutIndex = maxChars;
|
|
643
|
+
for (let i = Math.min(maxChars, chars.length - 1); i >= 0; i -= 1) {
|
|
644
|
+
if (chars[i] === '\n') {
|
|
645
|
+
cutIndex = i;
|
|
646
|
+
break;
|
|
647
|
+
}
|
|
648
|
+
}
|
|
649
|
+
blob = `${chars.slice(0, cutIndex).join('')}\n...(区段视图已截断,完整正文见 contract_text.txt)`;
|
|
650
|
+
}
|
|
651
|
+
return ('要素区段视图(L=原文行号;辅助定位用,含抬头 + 要素命中行 + 表格块 + 签署尾部;' +
|
|
652
|
+
`取值一律以 contract_text.txt 全文为准)\n${blob}\n`);
|
|
653
|
+
}
|
|
654
|
+
/** 把 elements.terms 渲染成摘要「其他关键条款」段(条款单一来源)。 */
|
|
655
|
+
function injectTermsSection(summary, elements) {
|
|
656
|
+
if (!isRecord(summary))
|
|
657
|
+
return summary;
|
|
658
|
+
const sections = summary.sections;
|
|
659
|
+
if (!Array.isArray(sections))
|
|
660
|
+
return summary;
|
|
661
|
+
for (const section of sections) {
|
|
662
|
+
if (isRecord(section) && String(section.title ?? '').trim() === '其他关键条款')
|
|
663
|
+
return summary;
|
|
664
|
+
}
|
|
665
|
+
const terms = isRecord(elements) ? elements.terms : null;
|
|
666
|
+
if (!Array.isArray(terms))
|
|
667
|
+
return summary;
|
|
668
|
+
const items = [];
|
|
669
|
+
for (const term of terms) {
|
|
670
|
+
if (!isRecord(term))
|
|
671
|
+
continue;
|
|
672
|
+
const name = String(term.name ?? '').trim();
|
|
673
|
+
const content = String(term.content ?? '').trim();
|
|
674
|
+
if (name && content)
|
|
675
|
+
items.push(`${name}:${content}`);
|
|
676
|
+
else if (name || content)
|
|
677
|
+
items.push(name || content);
|
|
678
|
+
}
|
|
679
|
+
if (items.length === 0)
|
|
680
|
+
return summary;
|
|
681
|
+
let index = sections.length;
|
|
682
|
+
for (let i = 0; i < sections.length; i += 1) {
|
|
683
|
+
const section = sections[i];
|
|
684
|
+
if (isRecord(section) && section.type === 'next') {
|
|
685
|
+
index = i;
|
|
686
|
+
break;
|
|
687
|
+
}
|
|
688
|
+
}
|
|
689
|
+
sections.splice(index, 0, { title: '其他关键条款', type: 'list', items });
|
|
690
|
+
return summary;
|
|
691
|
+
}
|
|
692
|
+
/** 把 ai_fill.json 拆成 elements.json 与 summary_data.json。 */
|
|
693
|
+
function splitAiFill(path, outDir) {
|
|
694
|
+
const warnings = [];
|
|
695
|
+
let elementsPath = '';
|
|
696
|
+
let summaryPath = '';
|
|
697
|
+
let data;
|
|
698
|
+
try {
|
|
699
|
+
data = readJsonLoose(path);
|
|
700
|
+
}
|
|
701
|
+
catch (error) {
|
|
702
|
+
return {
|
|
703
|
+
elementsPath: '',
|
|
704
|
+
summaryPath: '',
|
|
705
|
+
warnings: [`ai_fill.json 解析失败:${error instanceof Error ? error.message : String(error)}`],
|
|
706
|
+
};
|
|
707
|
+
}
|
|
708
|
+
if (!isRecord(data)) {
|
|
709
|
+
return { elementsPath: '', summaryPath: '', warnings: ['ai_fill.json 顶层必须是对象'] };
|
|
710
|
+
}
|
|
711
|
+
const elements = data.elements;
|
|
712
|
+
if (isRecord(elements)) {
|
|
713
|
+
elementsPath = join(outDir, 'elements.json');
|
|
714
|
+
writeJsonFile(elementsPath, elements);
|
|
715
|
+
}
|
|
716
|
+
const summary = data.summary;
|
|
717
|
+
if (isRecord(summary)) {
|
|
718
|
+
summaryPath = join(outDir, 'summary_data.json');
|
|
719
|
+
writeJsonFile(summaryPath, injectTermsSection(summary, elements));
|
|
720
|
+
}
|
|
721
|
+
if (!elementsPath && !summaryPath) {
|
|
722
|
+
warnings.push('ai_fill.json 里没有 elements 或 summary 对象');
|
|
723
|
+
}
|
|
724
|
+
return { elementsPath, summaryPath, warnings };
|
|
725
|
+
}
|
|
726
|
+
function buildSummarySkeleton(flowKey, title, text, fileName) {
|
|
727
|
+
const rows = BASE_ELEMENT_ROWS.map(([row, how]) => ({ row, how }));
|
|
728
|
+
for (const [row, how] of TYPE_EXTRA_ROWS[flowKey ?? ''] ?? [])
|
|
729
|
+
rows.push({ row, how });
|
|
730
|
+
return {
|
|
731
|
+
instruction: '阶段1 已产出 ai_fill.json:在它的 elements / summary 里就地填空,再用 --ai-fill 一条命令进阶段2(省一轮写文件)。' +
|
|
732
|
+
'要素取值**必须以 contract_text.txt 全文为准**(禁止只看区段视图);contract_sections.txt 仅用于快速定位行号,不得作为唯一输入。' +
|
|
733
|
+
'本骨架只给必填行与口径,不提供任何字段取值。',
|
|
734
|
+
flowKey,
|
|
735
|
+
flowLabel: FLOW_LABEL[flowKey ?? ''] ?? (flowKey || '待确认'),
|
|
736
|
+
titleFromText: title,
|
|
737
|
+
fileName,
|
|
738
|
+
textLength: plen(text),
|
|
739
|
+
requiredElementRows: rows,
|
|
740
|
+
elementRowCount: rows.length,
|
|
741
|
+
sectionsSpec: SECTIONS_SPEC,
|
|
742
|
+
constraints: CONSTRAINTS,
|
|
743
|
+
aiFillHint: {
|
|
744
|
+
file: 'ai_fill.json',
|
|
745
|
+
how: 'elements 按 elementsContract 填值;summary 按 sectionTemplate 填值;' +
|
|
746
|
+
'阶段2 只需 --ai-fill ai_fill.json,无需再写 elements.json / summary_data.json',
|
|
747
|
+
sectionsView: 'contract_sections.txt(区段视图,辅助定位用:含抬头、要素命中行、表格块与签署尾部;' +
|
|
748
|
+
'取值一律回 contract_text.txt 全文核对,禁止只看视图下结论)',
|
|
749
|
+
},
|
|
750
|
+
summaryFormat: SUMMARY_FORMAT,
|
|
751
|
+
sectionTemplate: buildSummaryTemplate(flowKey, title, fileName, plen(text), rows),
|
|
752
|
+
elementsContract: {
|
|
753
|
+
partyA: '甲方全称',
|
|
754
|
+
partyB: '乙方(我方)全称',
|
|
755
|
+
partyC: '丙方全称,无则空串',
|
|
756
|
+
finalUser: '最终用户全称,无则空串',
|
|
757
|
+
signDate: '签订时间 YYYY年MM月DD日',
|
|
758
|
+
signPlace: '签订地点',
|
|
759
|
+
deliveryPlace: '交付/服务地点',
|
|
760
|
+
effectiveCondition: '生效条件',
|
|
761
|
+
contractNo: '合同编号',
|
|
762
|
+
totalAmount: '合同总额,原文标记原样保留',
|
|
763
|
+
invoiceTax: '发票类型与税率',
|
|
764
|
+
version: '产品版本,无则空串',
|
|
765
|
+
payments: [{ node: '触发节点', ratio: '40%', amount: '金额' }],
|
|
766
|
+
items: [{ name: '标的名称', price: '单价', discount: '折扣', amount: '金额' }],
|
|
767
|
+
terms: [{ name: '条款名', content: '一句话事实' }],
|
|
768
|
+
missing: ['原文缺失或留空的字段名'],
|
|
769
|
+
},
|
|
770
|
+
};
|
|
771
|
+
}
|
|
772
|
+
/** 签约相对方:甲方 → 丙方 → 最终用户,均排除我方主体。 */
|
|
773
|
+
function pickCounterparty(elements) {
|
|
774
|
+
for (const key of ['partyA', 'partyC', 'finalUser']) {
|
|
775
|
+
const value = str(elements[key]).trim();
|
|
776
|
+
if (value && !OUR_COMPANY_WORDS.some((word) => value.includes(word)))
|
|
777
|
+
return value;
|
|
778
|
+
}
|
|
779
|
+
return '';
|
|
780
|
+
}
|
|
781
|
+
function requireOutDir(raw) {
|
|
782
|
+
const text = str(raw).trim();
|
|
783
|
+
if (!text)
|
|
784
|
+
throw contractValidationError('out_dir_required', 'outDir 必须是产物目录');
|
|
785
|
+
const dir = resolve(text);
|
|
786
|
+
mkdirSync(dir, { recursive: true });
|
|
787
|
+
return dir;
|
|
788
|
+
}
|
|
789
|
+
function requireFile(raw, name) {
|
|
790
|
+
const text = str(raw).trim();
|
|
791
|
+
if (!text)
|
|
792
|
+
throw contractValidationError('file_required', `${name} 必须是文件绝对路径`);
|
|
793
|
+
const path = resolve(text);
|
|
794
|
+
if (!existsSync(path))
|
|
795
|
+
throw contractValidationError('file_not_found', `找不到文件:${path}`);
|
|
796
|
+
return path;
|
|
797
|
+
}
|
|
798
|
+
export const contractTriageOperations = [
|
|
799
|
+
{
|
|
800
|
+
name: 'contract.triage.extract',
|
|
801
|
+
async execute(input) {
|
|
802
|
+
const file = requireFile(input.file, 'file');
|
|
803
|
+
const outDir = requireOutDir(input.outDir);
|
|
804
|
+
const attachRaw = Array.isArray(input.attach) ? input.attach : [];
|
|
805
|
+
const attach = attachRaw.map((item, index) => requireFile(item, `attach[${index}]`));
|
|
806
|
+
const elementsArg = str(input.elements).trim();
|
|
807
|
+
const summaryArg = str(input.summaryData).trim();
|
|
808
|
+
const aiFillArg = str(input.aiFill).trim();
|
|
809
|
+
const reuse = input.reuse === true;
|
|
810
|
+
const outputs = {};
|
|
811
|
+
const warnings = [];
|
|
812
|
+
// ── ai_fill 先拆包,后续(含 reuse 路径)完全复用两个既有参数
|
|
813
|
+
let elementsPath = elementsArg;
|
|
814
|
+
let summaryPath = summaryArg;
|
|
815
|
+
if (aiFillArg) {
|
|
816
|
+
if (existsSync(resolve(aiFillArg))) {
|
|
817
|
+
const split = splitAiFill(resolve(aiFillArg), outDir);
|
|
818
|
+
warnings.push(...split.warnings);
|
|
819
|
+
if (split.elementsPath && !elementsPath)
|
|
820
|
+
elementsPath = split.elementsPath;
|
|
821
|
+
if (split.summaryPath && !summaryPath)
|
|
822
|
+
summaryPath = split.summaryPath;
|
|
823
|
+
}
|
|
824
|
+
else {
|
|
825
|
+
warnings.push(`ai_fill.json 不存在:${aiFillArg}`);
|
|
826
|
+
}
|
|
827
|
+
}
|
|
828
|
+
const summaryStateOf = () => {
|
|
829
|
+
if (!summaryPath)
|
|
830
|
+
return 'pending_ai';
|
|
831
|
+
if (!existsSync(resolve(summaryPath))) {
|
|
832
|
+
if (!warnings.some((item) => item.startsWith('summary_data.json 不存在'))) {
|
|
833
|
+
warnings.push(`summary_data.json 不存在:${summaryPath}`);
|
|
834
|
+
}
|
|
835
|
+
return 'pending_ai';
|
|
836
|
+
}
|
|
837
|
+
return 'ai_semantic';
|
|
838
|
+
};
|
|
839
|
+
// ── 阶段2 复用:只合并 elements / summary_data,不再抽正文与打分
|
|
840
|
+
const triagePath = join(outDir, 'triage.json');
|
|
841
|
+
if (reuse && existsSync(triagePath)) {
|
|
842
|
+
let result;
|
|
843
|
+
try {
|
|
844
|
+
result = readJsonLoose(triagePath);
|
|
845
|
+
}
|
|
846
|
+
catch (error) {
|
|
847
|
+
throw contractValidationError('triage_reuse_failed', `triage.json 解析失败:${error instanceof Error ? error.message : String(error)}`);
|
|
848
|
+
}
|
|
849
|
+
const mergedWarnings = [
|
|
850
|
+
...(Array.isArray(result.warnings) ? result.warnings : []),
|
|
851
|
+
...warnings,
|
|
852
|
+
];
|
|
853
|
+
let elements = isRecord(result.elements) ? result.elements : {};
|
|
854
|
+
let elementsSource = str(result.elementsSource) || 'ai_semantic_pending';
|
|
855
|
+
if (elementsPath) {
|
|
856
|
+
if (existsSync(resolve(elementsPath))) {
|
|
857
|
+
try {
|
|
858
|
+
const parsed = readJsonLoose(resolve(elementsPath));
|
|
859
|
+
elements = isRecord(parsed) ? parsed : {};
|
|
860
|
+
elementsSource = 'ai_semantic';
|
|
861
|
+
}
|
|
862
|
+
catch (error) {
|
|
863
|
+
throw contractValidationError('elements_parse_failed', `elements.json 解析失败:${error instanceof Error ? error.message : String(error)}`);
|
|
864
|
+
}
|
|
865
|
+
}
|
|
866
|
+
else {
|
|
867
|
+
mergedWarnings.push(`elements.json 不存在,已跳过:${elementsPath}`);
|
|
868
|
+
}
|
|
869
|
+
}
|
|
870
|
+
if (!isRecord(elements))
|
|
871
|
+
elements = {};
|
|
872
|
+
result.elements = elements;
|
|
873
|
+
result.elementsSource = elementsSource;
|
|
874
|
+
result.counterparty = pickCounterparty(elements);
|
|
875
|
+
result.warnings = mergedWarnings;
|
|
876
|
+
writeJsonFile(triagePath, result);
|
|
877
|
+
outputs.text = join(outDir, 'contract_text.txt');
|
|
878
|
+
outputs.triage = triagePath;
|
|
879
|
+
outputs.skeleton = join(outDir, 'summary_skeleton.json');
|
|
880
|
+
let summaryState = 'pending_ai';
|
|
881
|
+
if (summaryPath) {
|
|
882
|
+
if (existsSync(resolve(summaryPath))) {
|
|
883
|
+
try {
|
|
884
|
+
const summary = readJsonLoose(resolve(summaryPath));
|
|
885
|
+
const outSummary = join(outDir, 'summary_data.json');
|
|
886
|
+
writeJsonFile(outSummary, summary);
|
|
887
|
+
outputs.summary = outSummary;
|
|
888
|
+
summaryState = 'ai_semantic';
|
|
889
|
+
}
|
|
890
|
+
catch (error) {
|
|
891
|
+
mergedWarnings.push(`summary_data.json 解析失败:${error instanceof Error ? error.message : String(error)}`);
|
|
892
|
+
result.warnings = mergedWarnings;
|
|
893
|
+
}
|
|
894
|
+
}
|
|
895
|
+
else {
|
|
896
|
+
mergedWarnings.push(`summary_data.json 不存在:${summaryPath}`);
|
|
897
|
+
result.warnings = mergedWarnings;
|
|
898
|
+
}
|
|
899
|
+
}
|
|
900
|
+
let elementRowCount = 0;
|
|
901
|
+
if (existsSync(outputs.skeleton)) {
|
|
902
|
+
try {
|
|
903
|
+
const skeleton = readJsonLoose(outputs.skeleton);
|
|
904
|
+
elementRowCount = isRecord(skeleton) ? Number(skeleton.elementRowCount ?? 0) : 0;
|
|
905
|
+
}
|
|
906
|
+
catch {
|
|
907
|
+
elementRowCount = 0;
|
|
908
|
+
}
|
|
909
|
+
}
|
|
910
|
+
return {
|
|
911
|
+
status: 'COMPLETE',
|
|
912
|
+
data: {
|
|
913
|
+
ok: true,
|
|
914
|
+
reusedTriage: true,
|
|
915
|
+
flowKey: result.flowKey ?? null,
|
|
916
|
+
typeScore: result.typeScore ?? 0,
|
|
917
|
+
fingerprint: result.fingerprint ?? null,
|
|
918
|
+
needsConfirm: result.needsConfirm === true,
|
|
919
|
+
title: result.title ?? '',
|
|
920
|
+
elementsSource,
|
|
921
|
+
summaryState,
|
|
922
|
+
hintCount: Array.isArray(result.hints) ? result.hints.length : 0,
|
|
923
|
+
elementRowCount,
|
|
924
|
+
counterparty: result.counterparty ?? '',
|
|
925
|
+
warnings: mergedWarnings,
|
|
926
|
+
outputs,
|
|
927
|
+
},
|
|
928
|
+
};
|
|
929
|
+
}
|
|
930
|
+
// ── 多文件:主文件在前,随附文件按序合并,并记录「行号 → 文件」归属
|
|
931
|
+
const sourceFiles = [
|
|
932
|
+
{ index: 0, role: 'primary', path: file, name: basename(file) },
|
|
933
|
+
];
|
|
934
|
+
const seen = new Set([file]);
|
|
935
|
+
for (const attachPath of attach) {
|
|
936
|
+
if (!attachPath || seen.has(attachPath))
|
|
937
|
+
continue;
|
|
938
|
+
seen.add(attachPath);
|
|
939
|
+
sourceFiles.push({
|
|
940
|
+
index: sourceFiles.length,
|
|
941
|
+
role: 'attachment',
|
|
942
|
+
path: attachPath,
|
|
943
|
+
name: basename(attachPath),
|
|
944
|
+
});
|
|
945
|
+
}
|
|
946
|
+
const mergedLines = [];
|
|
947
|
+
const lineMap = [];
|
|
948
|
+
let primaryText = '';
|
|
949
|
+
for (const source of sourceFiles) {
|
|
950
|
+
let extracted;
|
|
951
|
+
try {
|
|
952
|
+
extracted = extractText(source.path);
|
|
953
|
+
}
|
|
954
|
+
catch (error) {
|
|
955
|
+
if (error instanceof Error && 'code' in error)
|
|
956
|
+
throw error;
|
|
957
|
+
throw contractValidationError('extract_failed', `正文抽取失败(${source.name}):${error instanceof Error ? error.message : String(error)}`);
|
|
958
|
+
}
|
|
959
|
+
source.textLength = plen(extracted.text);
|
|
960
|
+
if (extracted.degraded) {
|
|
961
|
+
warnings.push(`${source.name} 为老式 .doc,正文抽取属降级结果,建议另存为 .docx 后重跑`);
|
|
962
|
+
}
|
|
963
|
+
if (source.index === 0) {
|
|
964
|
+
primaryText = extracted.text;
|
|
965
|
+
}
|
|
966
|
+
else {
|
|
967
|
+
for (const line of ['', `===== 随附文件 ${source.index}:${source.name} =====`, '']) {
|
|
968
|
+
mergedLines.push(line);
|
|
969
|
+
lineMap.push(source.index);
|
|
970
|
+
}
|
|
971
|
+
}
|
|
972
|
+
for (const line of extracted.text.split('\n')) {
|
|
973
|
+
mergedLines.push(line);
|
|
974
|
+
lineMap.push(source.index);
|
|
975
|
+
}
|
|
976
|
+
}
|
|
977
|
+
const text = mergedLines.join('\n');
|
|
978
|
+
if (plen(primaryText) < 100) {
|
|
979
|
+
throw contractValidationError('text_too_short', `主文件仅抽到 ${plen(primaryText)} 字,可能是扫描件或加密文件,请改用 parse_document 兜底`);
|
|
980
|
+
}
|
|
981
|
+
// 判定只看主文件:随附协议常含「补充/变更」字样,混入会误改 flowKey
|
|
982
|
+
const title = detectTitle(primaryText);
|
|
983
|
+
const scored = scoreContract(primaryText, title);
|
|
984
|
+
const skeleton = buildSummarySkeleton(scored.flowKey, title, primaryText, basename(file));
|
|
985
|
+
const hints = regexHints(text);
|
|
986
|
+
// 要素只认模型语义结果,本 operation 不猜取值
|
|
987
|
+
let elements = {};
|
|
988
|
+
let elementsSource = 'ai_semantic_pending';
|
|
989
|
+
if (elementsPath) {
|
|
990
|
+
if (existsSync(resolve(elementsPath))) {
|
|
991
|
+
try {
|
|
992
|
+
const parsed = readJsonLoose(resolve(elementsPath));
|
|
993
|
+
elements = isRecord(parsed) ? parsed : {};
|
|
994
|
+
elementsSource = 'ai_semantic';
|
|
995
|
+
}
|
|
996
|
+
catch (error) {
|
|
997
|
+
throw contractValidationError('elements_parse_failed', `elements.json 解析失败:${error instanceof Error ? error.message : String(error)}`);
|
|
998
|
+
}
|
|
999
|
+
}
|
|
1000
|
+
else {
|
|
1001
|
+
warnings.push(`elements.json 不存在,已跳过:${elementsPath}`);
|
|
1002
|
+
}
|
|
1003
|
+
}
|
|
1004
|
+
else if (!summaryPath) {
|
|
1005
|
+
warnings.push('未提供 elements.json:要素为空,发起流程表单需人工填写');
|
|
1006
|
+
}
|
|
1007
|
+
const counterparty = pickCounterparty(elements);
|
|
1008
|
+
const result = {
|
|
1009
|
+
file: {
|
|
1010
|
+
path: file,
|
|
1011
|
+
name: basename(file),
|
|
1012
|
+
size: statSync(file).size,
|
|
1013
|
+
attachments: sourceFiles
|
|
1014
|
+
.filter((source) => source.role === 'attachment')
|
|
1015
|
+
.map((source) => ({ name: source.name, path: source.path, textLength: source.textLength })),
|
|
1016
|
+
},
|
|
1017
|
+
sourceFiles: sourceFiles.map((source) => ({
|
|
1018
|
+
index: source.index,
|
|
1019
|
+
role: source.role,
|
|
1020
|
+
name: source.name,
|
|
1021
|
+
})),
|
|
1022
|
+
fileCount: sourceFiles.length,
|
|
1023
|
+
textLength: plen(primaryText),
|
|
1024
|
+
mergedTextLength: plen(text),
|
|
1025
|
+
title,
|
|
1026
|
+
flowKey: scored.flowKey,
|
|
1027
|
+
typeScore: scored.score,
|
|
1028
|
+
typeBasis: scored.basis,
|
|
1029
|
+
fingerprint: scored.label,
|
|
1030
|
+
confidence: scored.confidence,
|
|
1031
|
+
needsConfirm: scored.needsConfirm,
|
|
1032
|
+
candidates: scored.candidates,
|
|
1033
|
+
evidence: scored.evidence,
|
|
1034
|
+
elements,
|
|
1035
|
+
elementsSource,
|
|
1036
|
+
hints,
|
|
1037
|
+
chapterCount: countChapters(text),
|
|
1038
|
+
counterparty,
|
|
1039
|
+
warnings,
|
|
1040
|
+
};
|
|
1041
|
+
const textPath = join(outDir, 'contract_text.txt');
|
|
1042
|
+
const skeletonPath = join(outDir, 'summary_skeleton.json');
|
|
1043
|
+
const aiFillPath = join(outDir, 'ai_fill.json');
|
|
1044
|
+
const sectionsPath = join(outDir, 'contract_sections.txt');
|
|
1045
|
+
const sourcesPath = join(outDir, 'text_sources.json');
|
|
1046
|
+
writeJsonFile(sourcesPath, { files: sourceFiles, lineMap });
|
|
1047
|
+
writeFileSync(textPath, text, 'utf8');
|
|
1048
|
+
writeJsonFile(triagePath, result);
|
|
1049
|
+
writeJsonFile(skeletonPath, skeleton);
|
|
1050
|
+
writeJsonFile(aiFillPath, {
|
|
1051
|
+
instruction: '就地填值:elements 按本文件给出的键名逐个填(键名即表单字段,禁止增删改名),' +
|
|
1052
|
+
'summary 按 sectionTemplate;table 的 rows 每行只放「标签 + 值」成对出现,禁止 grid。' +
|
|
1053
|
+
'关键条款只写在 elements.terms 一处(name + content),摘要「其他关键条款」段由脚本自动生成,' +
|
|
1054
|
+
'禁止在 summary 里重复摘录同一批条款。' +
|
|
1055
|
+
'【专项方案】必须按 references/contract-field-extract-new-customer.md §5.2 的 15 项' +
|
|
1056
|
+
'逐项核对原文后写入 solutions(name 只能取清单原名,禁止自创);未命中的整行删除,' +
|
|
1057
|
+
'无专属计价 amount 填 0,禁止用「有没有单独列价」反推是否存在。' +
|
|
1058
|
+
'填完直接跑阶段2 --ai-fill ai_fill.json。',
|
|
1059
|
+
flowKey: scored.flowKey,
|
|
1060
|
+
file: { name: basename(file), textLength: plen(text) },
|
|
1061
|
+
elements: buildElementsTemplate(scored.flowKey),
|
|
1062
|
+
summary: buildSummaryTemplate(scored.flowKey, title, basename(file), plen(text), skeleton.requiredElementRows),
|
|
1063
|
+
});
|
|
1064
|
+
writeFileSync(sectionsPath, buildSectionView(text, hints), 'utf8');
|
|
1065
|
+
outputs.text = textPath;
|
|
1066
|
+
outputs.triage = triagePath;
|
|
1067
|
+
outputs.skeleton = skeletonPath;
|
|
1068
|
+
outputs.aiFill = aiFillPath;
|
|
1069
|
+
outputs.sections = sectionsPath;
|
|
1070
|
+
outputs.sources = sourcesPath;
|
|
1071
|
+
let summaryState = summaryStateOf();
|
|
1072
|
+
if (summaryState === 'ai_semantic') {
|
|
1073
|
+
const summary = readJsonLoose(resolve(summaryPath));
|
|
1074
|
+
const outSummary = join(outDir, 'summary_data.json');
|
|
1075
|
+
writeJsonFile(outSummary, summary);
|
|
1076
|
+
outputs.summary = outSummary;
|
|
1077
|
+
summaryState = 'ai_semantic';
|
|
1078
|
+
}
|
|
1079
|
+
return {
|
|
1080
|
+
status: 'COMPLETE',
|
|
1081
|
+
data: {
|
|
1082
|
+
ok: true,
|
|
1083
|
+
flowKey: scored.flowKey,
|
|
1084
|
+
typeScore: scored.score,
|
|
1085
|
+
fingerprint: scored.label,
|
|
1086
|
+
needsConfirm: scored.needsConfirm,
|
|
1087
|
+
title,
|
|
1088
|
+
elementsSource,
|
|
1089
|
+
summaryState,
|
|
1090
|
+
hintCount: hints.length,
|
|
1091
|
+
elementRowCount: skeleton.elementRowCount,
|
|
1092
|
+
fileCount: sourceFiles.length,
|
|
1093
|
+
counterparty,
|
|
1094
|
+
warnings,
|
|
1095
|
+
outputs,
|
|
1096
|
+
},
|
|
1097
|
+
};
|
|
1098
|
+
},
|
|
1099
|
+
},
|
|
1100
|
+
];
|