weaver-work-cli 0.1.49 → 0.1.50
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/dist/chunks/{attachment-content-MU2LPI5P.js → attachment-content-EJYIOJPH.js} +3 -3
- package/dist/chunks/{chunk-6GWU63YF.js → chunk-3NCFFHB2.js} +1 -1
- package/dist/chunks/{chunk-NBEWUR7L.js → chunk-6T53BSWZ.js} +158 -44
- package/dist/chunks/{chunk-EJVA5ZVB.js → chunk-7AYQJSFY.js} +2 -2
- package/dist/chunks/{chunk-D2QRZUW4.js → chunk-7ECB22G3.js} +35 -28
- package/dist/chunks/{chunk-72MI3MBX.js → chunk-ATEXBEPD.js} +55 -15
- package/dist/chunks/{chunk-3NV2ETZR.js → chunk-BFKLQLBK.js} +8 -8
- package/dist/chunks/{chunk-BRRW7CWA.js → chunk-HARQF5IP.js} +26 -26
- package/dist/chunks/{chunk-K3BT54CU.js → chunk-K67FODVC.js} +1 -1
- package/dist/chunks/{chunk-YLCYX7LE.js → chunk-KMRT7NAT.js} +18 -5
- package/dist/chunks/{chunk-GEOMANP7.js → chunk-MCZG6HPM.js} +2 -2
- package/dist/chunks/{chunk-ZKEUGS2U.js → chunk-RYFRGTUV.js} +4 -4
- package/dist/chunks/{chunk-3X7VOSBA.js → chunk-WNJUGI2F.js} +1 -1
- package/dist/chunks/{chunk-KV5SOWMS.js → chunk-YB3AJYPY.js} +4 -4
- package/dist/chunks/{conflict-6347A7YK.js → conflict-C4UDHCWV.js} +2 -2
- package/dist/chunks/{contract-N6P2HIIE.js → contract-VUC6JOPG.js} +464 -9
- package/dist/chunks/{create-flow-7WG7LVX5.js → create-flow-6OG2LYBD.js} +6 -6
- package/dist/chunks/{env-LHRKSLG6.js → env-WP57TF2S.js} +2 -2
- package/dist/chunks/{factory-2H7Z4RWJ.js → factory-VUXI7N5C.js} +1 -1
- package/dist/chunks/{fna-ZVB2IILI.js → fna-ECOYBQYL.js} +328 -5
- package/dist/chunks/{group-chat-EW6PNDDT.js → group-chat-UQRGXILK.js} +3 -3
- package/dist/chunks/{im-3RCNL5GT.js → im-TN2JYVGJ.js} +2 -2
- package/dist/chunks/{invoice-FXWH5GPO.js → invoice-E7GOITEU.js} +1 -1
- package/dist/chunks/{meeting-N2FQBHXI.js → meeting-4BBLVAWM.js} +10 -10
- package/dist/chunks/{msg-parse-4GSQ2WTO.js → msg-parse-FPFVPMYI.js} +5 -1
- package/dist/chunks/{reception-MYOKJULO.js → reception-QGPNTGHG.js} +98 -82
- package/dist/chunks/{registry-CKUVBS53.js → registry-5CRCN2TV.js} +10 -10
- package/dist/chunks/{registry-BUTEDK3C.js → registry-E5RQJVWN.js} +2 -2
- package/dist/chunks/{registry-7VZ6YJUF.js → registry-V4CHRQDI.js} +1 -1
- package/dist/chunks/{room-recommend-MBCYENQ2.js → room-recommend-AYR3UG7R.js} +4 -4
- package/dist/chunks/{schedule-5IFMCXME.js → schedule-JZEFIXUS.js} +4 -4
- package/dist/chunks/{workflow-2TRU2ZSP.js → workflow-3ZAF2J5E.js} +1 -1
- package/dist/index.js +7 -7
- package/dist/shortcuts/contract/host.js +11 -0
- package/dist/shortcuts/contract/index.js +13 -0
- package/dist/shortcuts/contract/manifest.js +53 -0
- package/dist/shortcuts/contract/operations/performance.js +58 -7
- package/dist/shortcuts/contract/operations/quote.js +283 -1
- package/dist/shortcuts/contract/operations/registry.js +2 -0
- package/dist/shortcuts/contract/operations/save-recognize.js +151 -0
- package/dist/shortcuts/fna/host.js +4 -2
- package/dist/shortcuts/fna/manifest.js +14 -5
- package/dist/shortcuts/fna/operations/audit.js +334 -0
- package/dist/shortcuts/fna/operations/registry.js +2 -0
- package/dist/shortcuts/im/operations/at-mention.js +6 -3
- package/dist/shortcuts/im/operations/msg-parse.js +35 -5
- package/dist/shortcuts/im/operations/msg-sync.js +3 -1
- package/dist/shortcuts/im/operations/msg-write.js +57 -9
- package/dist/shortcuts/invoice/manifest.js +1 -1
- package/dist/shortcuts/meeting/operations/from-group-chat.js +16 -2
- package/dist/shortcuts/reception/constants.js +3 -7
- package/dist/shortcuts/reception/operations/leads.js +30 -6
- package/dist/shortcuts/reception/operations/panels.js +3 -2
- package/dist/shortcuts/workflow/operations/read.js +58 -14
- package/dist/shortcuts/workflow/operations/todoSmartConvert/todoSmartConvert.collect.js +140 -24
- package/dist/shortcuts/workflow/operations/todoSmartConvert/todoSmartConvert.core.js +42 -14
- package/dist/shortcuts/workflow/operations/todoSmartConvert/todoSmartConvert.js +4 -6
- package/docs/SKILL.md +1 -1
- package/docs/_catalog.md +1 -1
- package/docs/fna.md +11 -4
- package/package.json +1 -1
- package/skill-template/business-info.json +6 -1
- package/skill-template/domains/qiyecheng.md +4 -2
- package/skills/weaver-e10-jinchengda/SKILL.md +1 -1
- package/skills/weaver-e10-jinchengda/references/contract-action-card.md +5 -5
- package/skills/weaver-e10-jinchengda/references/contract-action-engine.md +1 -1
- package/skills/weaver-e10-jinchengda/references/contract-clause-library-crud.md +44 -2
- package/skills/weaver-e10-jinchengda/references/contract-command-index.md +2 -2
- package/skills/weaver-e10-jinchengda/references/contract-element-save-record.md +219 -0
- package/skills/weaver-e10-jinchengda/references/contract-field-extract-new-customer.md +50 -30
- package/skills/weaver-e10-jinchengda/references/contract-field-extract-other-flows.md +24 -15
- package/skills/weaver-e10-jinchengda/references/contract-flow-launch.md +1 -1
- package/skills/weaver-e10-jinchengda/references/contract-performance-query.md +96 -2
- package/skills/weaver-e10-jinchengda/references/contract-quote-to-contract.md +43 -0
- package/skills/weaver-e10-jinchengda/scripts/fill_plan.py +997 -0
- package/skills/weaver-e10-jinchengda/scripts/render_ebdf_list_card.py +265 -0
- package/skills/weaver-e10-jinchengda/scripts/validate_action_card.py +83 -0
- package/skills/weaver-e10-jinchengda/scripts/verify_docx_placeholders.py +118 -0
- package/skills/weaver-e10-qiyecheng/SKILL.md +21 -7
- package/skills/weaver-e10-qiyecheng/references/ai-check-audit.md +104 -0
- package/skills/weaver-e10-qiyecheng/references/catalog.md +17 -3
- package/skills/weaver-e10-qiyecheng/references/source-manifest.json +136 -30
- package/skills/weaver-e10-reception-flow/SKILL.md +43 -6
- package/skills/weaver-e10-reception-flow/references/guide.md +1 -1
- package/skills/weaver-e10-recruit-stage/SKILL.md +1 -1
- package/skills/weaver-e10-recruit-stage/references/recruit-arrange-interview.md +3 -3
- package/skills/weaver-e10-recruit-stage/references/recruit-output-links.md +6 -4
- package/skills/weaver-e10-recruit-stage/references/recruit-resume-import.md +3 -3
- package/skills/weaver-e10-workflow/SKILL.md +2 -1
- package/skills/weaver-e10-workflow/references/todo-smart-convert.md +29 -6
- package/skills/weaver-e10-workflow/tools/todo-summary.cjs +162 -10
- package/skills/weaver-e10-yepiaotong/SKILL.md +10 -5
- package/skills/weaver-e10-yepiaotong/references/invoice-issuing-workflow.md +19 -32
- package/skills/weaver-e10-yepiaotong/references/invoice-reim.md +6 -45
- package/skills/weaver-e10-yepiaotong/references/reim-api-reference.md +5 -5
- package/skills/weaver-e10-yepiaotong/references/reim-examples.md +4 -37
- package/skills/weaver-e10-yepiaotong/references/reim-form-fill-rules.md +2 -2
- package/skills/weaver-e10-yepiaotong/references/reim-phone-subsidy-rules.md +4 -4
- package/skills/weaver-e10-yepiaotong/references/reim-workflow.md +22 -35
- package/skills/weaver-e10-yimiaoban/SKILL.md +8 -6
- package/skills/weaver-e10-yimiaoban/references/msg-read.md +20 -0
- package/skills/weaver-e10-yimiaoban/references/msg-write.md +7 -0
- package/skills/weaver-e10-yimiaoban/references/source-manifest.json +18 -15
|
@@ -0,0 +1,997 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
"""FillPlan 执行器:只执行语义映射,不做任何语义判断。
|
|
3
|
+
|
|
4
|
+
设计原则见 references/contract-fill-plan.md。
|
|
5
|
+
|
|
6
|
+
分工:
|
|
7
|
+
模型 产出 FillPlan JSON(哪张表、哪一行、填什么、扩几行)
|
|
8
|
+
本执行器 校验定位是否唯一、断言是否成立,然后只负责动手
|
|
9
|
+
不做事 「猜」哪张表是费用表、哪行是合计——这些必须在 plan 里写清楚
|
|
10
|
+
|
|
11
|
+
用法:
|
|
12
|
+
# ① 空白单元格审计:列出模板里所有「有标签、无值」的格子,防止漏填
|
|
13
|
+
python fill_plan.py --template <模板.docx> --audit
|
|
14
|
+
|
|
15
|
+
# ② 只校验,不改文件(推荐先跑这步,把解析结果给用户看)
|
|
16
|
+
python fill_plan.py --template <模板.docx> --plan <plan.json> --dry-run
|
|
17
|
+
|
|
18
|
+
# ③ 执行
|
|
19
|
+
python fill_plan.py --template <模板.docx> --plan <plan.json> \
|
|
20
|
+
--out <产物.docx> --report <报告.json>
|
|
21
|
+
|
|
22
|
+
退出码:
|
|
23
|
+
0 = 成功(含 dry-run 校验通过)
|
|
24
|
+
1 = 校验失败或执行失败(不改动任何文件)
|
|
25
|
+
|
|
26
|
+
2026-11-10 根源修复(对应「乙方为空 / 付款金额为空 / 字体字号不匹配」三起事故):
|
|
27
|
+
1. cell 写入默认**继承目标单元格所在语境的原格式**(同侪格 → 同列 → 正文),
|
|
28
|
+
不再产生与模板不一致的默认字体;可用 format_from 显式指定取样格。
|
|
29
|
+
2. 新增 amount_split:按比例拆分合同总额并回填金额列,末行吃尾差,杜绝手算错。
|
|
30
|
+
3. 新增 --audit:把「有标签但值为空」的格子列出来,模型必须逐项处置,
|
|
31
|
+
不得以「模板留空」为由跳过(封面乙方就是这样漏掉的)。
|
|
32
|
+
4. verify.must_fill:交付前断言指定格子非空,空则整单失败。
|
|
33
|
+
5. clone 原型行快照:rows 的 clone_from 即使在前面被 delete_rows 删掉,
|
|
34
|
+
仍能按快照克隆,消除「op 顺序一变就定位不到」的脆弱性。
|
|
35
|
+
"""
|
|
36
|
+
import argparse
|
|
37
|
+
import copy
|
|
38
|
+
import io
|
|
39
|
+
import json
|
|
40
|
+
import os
|
|
41
|
+
import re
|
|
42
|
+
import shutil
|
|
43
|
+
import sys
|
|
44
|
+
import zipfile
|
|
45
|
+
from decimal import Decimal, ROUND_HALF_UP
|
|
46
|
+
|
|
47
|
+
import docx
|
|
48
|
+
from docx.oxml.ns import qn
|
|
49
|
+
|
|
50
|
+
# ── 定位器:语义锚点,禁用裸索引优先 ──────────────────────────────
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def _cell_text(cell):
|
|
54
|
+
return re.sub(r'\s+', ' ', cell.text or '').strip()
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def _row_texts(row):
|
|
58
|
+
seen = []
|
|
59
|
+
for c in row.cells:
|
|
60
|
+
t = _cell_text(c)
|
|
61
|
+
if not seen or seen[-1] != t: # 合并单元格会重复返回同一文本
|
|
62
|
+
seen.append(t)
|
|
63
|
+
return seen
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def match_row(table, matcher, where):
|
|
67
|
+
"""按 matcher 定位唯一行。matcher 支持 row_index / first / contains / first_re / col。"""
|
|
68
|
+
if not isinstance(matcher, dict) or not matcher:
|
|
69
|
+
raise SystemExit('%s:matcher 必须是非空对象' % where)
|
|
70
|
+
|
|
71
|
+
rows = list(table.rows)
|
|
72
|
+
if 'row_index' in matcher:
|
|
73
|
+
idx = int(matcher['row_index'])
|
|
74
|
+
if idx < 0 or idx >= len(rows):
|
|
75
|
+
raise SystemExit('%s:row_index %d 越界(表共 %d 行)' % (where, idx, len(rows)))
|
|
76
|
+
return idx
|
|
77
|
+
|
|
78
|
+
hits = []
|
|
79
|
+
for i, row in enumerate(rows):
|
|
80
|
+
texts = _row_texts(row)
|
|
81
|
+
if not texts:
|
|
82
|
+
continue
|
|
83
|
+
if 'first' in matcher:
|
|
84
|
+
if texts[0] == str(matcher['first']).strip():
|
|
85
|
+
hits.append(i)
|
|
86
|
+
continue
|
|
87
|
+
if 'first_re' in matcher:
|
|
88
|
+
if re.search(matcher['first_re'], texts[0]):
|
|
89
|
+
hits.append(i)
|
|
90
|
+
continue
|
|
91
|
+
if 'contains' in matcher:
|
|
92
|
+
if any(str(matcher['contains']) in t for t in texts):
|
|
93
|
+
hits.append(i)
|
|
94
|
+
continue
|
|
95
|
+
# 按列精确匹配:{"col": 1, "equals": "..."} 或 {"col": 1, "re": "..."}
|
|
96
|
+
# 用于「同一编号在新旧行都出现」时区分旧行,比 first/contains 可靠
|
|
97
|
+
if 'col' in matcher and ('equals' in matcher or 're' in matcher):
|
|
98
|
+
ci = int(matcher['col'])
|
|
99
|
+
cells = row.cells
|
|
100
|
+
if 0 <= ci < len(cells):
|
|
101
|
+
v = _cell_text(cells[ci])
|
|
102
|
+
if 'equals' in matcher and v == str(matcher['equals']).strip():
|
|
103
|
+
hits.append(i)
|
|
104
|
+
elif 're' in matcher and re.search(matcher['re'], v):
|
|
105
|
+
hits.append(i)
|
|
106
|
+
|
|
107
|
+
if not hits:
|
|
108
|
+
raise SystemExit('%s:定位不到任何行,matcher=%r' % (where, matcher))
|
|
109
|
+
if len(hits) > 1:
|
|
110
|
+
raise SystemExit('%s:定位不唯一,命中行 %r,matcher=%r(请改用更精确的锚点)'
|
|
111
|
+
% (where, hits, matcher))
|
|
112
|
+
return hits[0]
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def get_table(doc, plan_op, where):
|
|
116
|
+
idx = plan_op.get('table')
|
|
117
|
+
if not isinstance(idx, int):
|
|
118
|
+
raise SystemExit('%s:table 必须是整数索引' % where)
|
|
119
|
+
if idx < 0 or idx >= len(doc.tables):
|
|
120
|
+
raise SystemExit('%s:table %d 越界(文档共 %d 张表)' % (where, idx, len(doc.tables)))
|
|
121
|
+
return doc.tables[idx]
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
# ── 格式继承(2026-11-10 根源修复)──────────────────────────────
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def _run_rpr(run):
|
|
128
|
+
"""取 run 的 w:rPr 元素;没有则 None。"""
|
|
129
|
+
return run._element.find(qn('w:rPr'))
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def _cell_rpr(cell):
|
|
133
|
+
"""取单元格里第一个「有文字且有 rPr」的 run 的 rPr。"""
|
|
134
|
+
for p in cell.paragraphs:
|
|
135
|
+
for r in p.runs:
|
|
136
|
+
if (r.text or '').strip():
|
|
137
|
+
rpr = _run_rpr(r)
|
|
138
|
+
if rpr is not None:
|
|
139
|
+
return rpr
|
|
140
|
+
return None
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def find_donor_rpr(doc, table, row_idx, col, explicit=None):
|
|
144
|
+
"""为目标格挑选格式取样源。
|
|
145
|
+
|
|
146
|
+
优先级:plan 显式 format_from → 同行其它格 → 同列其它行 → 正文段落。
|
|
147
|
+
「同行其它格」排最前,因为合同表格里标签格与值格通常同字号同字体。
|
|
148
|
+
"""
|
|
149
|
+
if explicit:
|
|
150
|
+
try:
|
|
151
|
+
t2 = doc.tables[int(explicit['table'])]
|
|
152
|
+
r2 = match_row(t2, explicit.get('row_match') or {}, 'format_from')
|
|
153
|
+
c2 = int(explicit['col'])
|
|
154
|
+
rpr = _cell_rpr(t2.rows[r2].cells[c2])
|
|
155
|
+
if rpr is not None:
|
|
156
|
+
return rpr
|
|
157
|
+
except SystemExit:
|
|
158
|
+
pass
|
|
159
|
+
|
|
160
|
+
row = table.rows[row_idx]
|
|
161
|
+
for ci, c in enumerate(row.cells):
|
|
162
|
+
if ci == col:
|
|
163
|
+
continue
|
|
164
|
+
rpr = _cell_rpr(c)
|
|
165
|
+
if rpr is not None:
|
|
166
|
+
return rpr
|
|
167
|
+
|
|
168
|
+
for ri, r in enumerate(table.rows):
|
|
169
|
+
if ri == row_idx:
|
|
170
|
+
continue
|
|
171
|
+
cells = r.cells
|
|
172
|
+
if col < len(cells):
|
|
173
|
+
rpr = _cell_rpr(cells[col])
|
|
174
|
+
if rpr is not None:
|
|
175
|
+
return rpr
|
|
176
|
+
|
|
177
|
+
for p in doc.paragraphs:
|
|
178
|
+
for run in p.runs:
|
|
179
|
+
if (run.text or '').strip():
|
|
180
|
+
rpr = _run_rpr(run)
|
|
181
|
+
if rpr is not None:
|
|
182
|
+
return rpr
|
|
183
|
+
return None
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
def set_cell(cell, text, rpr=None, inherit=True):
|
|
187
|
+
"""写单元格文本。
|
|
188
|
+
|
|
189
|
+
inherit=True 时用 rpr 覆盖 run 的字符格式,使新填文本与模板原有内容一致;
|
|
190
|
+
克隆行场景(rpr=None 或 inherit=False)保持原型行格式不动。
|
|
191
|
+
"""
|
|
192
|
+
for extra in cell.paragraphs[1:]:
|
|
193
|
+
extra._element.getparent().remove(extra._element)
|
|
194
|
+
p = cell.paragraphs[0]
|
|
195
|
+
|
|
196
|
+
if p.runs:
|
|
197
|
+
run = p.runs[0]
|
|
198
|
+
for r in p.runs[1:]:
|
|
199
|
+
r.text = ''
|
|
200
|
+
else:
|
|
201
|
+
run = p.add_run()
|
|
202
|
+
|
|
203
|
+
run.text = str(text)
|
|
204
|
+
|
|
205
|
+
if inherit and rpr is not None:
|
|
206
|
+
existing = _run_rpr(run)
|
|
207
|
+
if existing is not None:
|
|
208
|
+
run._element.remove(existing)
|
|
209
|
+
# w:rPr 必须是 w:r 的第一个子元素
|
|
210
|
+
run._element.insert(0, copy.deepcopy(rpr))
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
# ── 金额工具(amount_split 用)─────────────────────────────────
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
NUM_RE = re.compile(r'-?[0-9][0-9,]*(\.[0-9]+)?')
|
|
217
|
+
|
|
218
|
+
|
|
219
|
+
def parse_money(v):
|
|
220
|
+
"""把 `¥2,221,000` / `2221000元` / 2221000 统一成 Decimal。"""
|
|
221
|
+
if isinstance(v, (int, float, Decimal)):
|
|
222
|
+
return Decimal(str(v))
|
|
223
|
+
s = str(v or '')
|
|
224
|
+
m = NUM_RE.search(s.replace(',', ','))
|
|
225
|
+
if not m:
|
|
226
|
+
raise SystemExit('amount_split:无法从 %r 解析金额' % v)
|
|
227
|
+
return Decimal(m.group(0).replace(',', ''))
|
|
228
|
+
|
|
229
|
+
|
|
230
|
+
def fmt_money(d, currency='¥', decimals=2):
|
|
231
|
+
q = Decimal(d).quantize(Decimal('1.' + '0' * decimals), rounding=ROUND_HALF_UP)
|
|
232
|
+
return currency + '{:,.{d}f}'.format(q, d=decimals)
|
|
233
|
+
|
|
234
|
+
|
|
235
|
+
def parse_ratio(v):
|
|
236
|
+
"""`30%` / `30` → Decimal(30)。"""
|
|
237
|
+
s = str(v or '').strip().replace('%', '%').replace('%', '')
|
|
238
|
+
if not s:
|
|
239
|
+
raise SystemExit('amount_split:比例为空,无法计算')
|
|
240
|
+
return Decimal(s)
|
|
241
|
+
|
|
242
|
+
|
|
243
|
+
# ── 各 op 的校验(不写文件)────────────────────────────────────
|
|
244
|
+
|
|
245
|
+
|
|
246
|
+
def validate_op(doc, op, i):
|
|
247
|
+
where = 'ops[%d]' % i
|
|
248
|
+
t = op.get('type')
|
|
249
|
+
|
|
250
|
+
if t == 'replace_text':
|
|
251
|
+
if not op.get('find') and not op.get('find_re'):
|
|
252
|
+
raise SystemExit('%s:replace_text 需要 find 或 find_re' % where)
|
|
253
|
+
if 'value' not in op:
|
|
254
|
+
raise SystemExit('%s:replace_text 缺 value' % where)
|
|
255
|
+
return {'op': i, 'type': t, 'find': op.get('find'), 'find_re': op.get('find_re'),
|
|
256
|
+
'expect': op.get('expect'), 'status': 'validated'}
|
|
257
|
+
|
|
258
|
+
if t == 'cell':
|
|
259
|
+
table = get_table(doc, op, where)
|
|
260
|
+
ri = match_row(table, op.get('row_match') or {}, where)
|
|
261
|
+
col = op.get('col')
|
|
262
|
+
if not isinstance(col, int):
|
|
263
|
+
raise SystemExit('%s:cell 缺 col' % where)
|
|
264
|
+
ncol = len(table.rows[ri].cells)
|
|
265
|
+
if col < 0 or col >= ncol:
|
|
266
|
+
raise SystemExit('%s:col %d 越界(第 %d 行共 %d 格)' % (where, col, ri, ncol))
|
|
267
|
+
before = _cell_text(table.rows[ri].cells[col])
|
|
268
|
+
donor = find_donor_rpr(doc, table, ri, col, op.get('format_from'))
|
|
269
|
+
return {'op': i, 'type': t, 'table': op['table'], 'row': ri, 'col': col,
|
|
270
|
+
'before': before, 'after': op.get('value'),
|
|
271
|
+
'format_inherit': bool(op.get('inherit_format', True)),
|
|
272
|
+
'format_donor': 'found' if donor is not None else 'none',
|
|
273
|
+
'status': 'validated'}
|
|
274
|
+
|
|
275
|
+
if t == 'rows':
|
|
276
|
+
table = get_table(doc, op, where)
|
|
277
|
+
anchor = match_row(table, op.get('anchor') or {}, where + '.anchor')
|
|
278
|
+
proto = match_row(table, op.get('clone_from') or {}, where + '.clone_from')
|
|
279
|
+
fill = op.get('fill') or []
|
|
280
|
+
if not fill:
|
|
281
|
+
raise SystemExit('%s:rows 缺 fill(至少一行)' % where)
|
|
282
|
+
ncol = len(table.rows[proto].cells)
|
|
283
|
+
for j, line in enumerate(fill):
|
|
284
|
+
if len(line) != ncol:
|
|
285
|
+
raise SystemExit('%s:fill[%d] 有 %d 格,原型行有 %d 格(必须逐格给全,'
|
|
286
|
+
'否则会残留模板旧值)' % (where, j, len(line), ncol))
|
|
287
|
+
return {'op': i, 'type': t, 'table': op['table'], 'anchor_row': anchor,
|
|
288
|
+
'clone_row': proto, 'count': len(fill), 'status': 'validated'}
|
|
289
|
+
|
|
290
|
+
if t == 'delete_rows':
|
|
291
|
+
table = get_table(doc, op, where)
|
|
292
|
+
matchers = op.get('match') or []
|
|
293
|
+
if not isinstance(matchers, list) or not matchers:
|
|
294
|
+
raise SystemExit('%s:delete_rows 的 match 必须是非空数组' % where)
|
|
295
|
+
rows = list(table.rows)
|
|
296
|
+
targets = []
|
|
297
|
+
for m in matchers:
|
|
298
|
+
for i2, row in enumerate(rows):
|
|
299
|
+
texts = _row_texts(row)
|
|
300
|
+
if not texts:
|
|
301
|
+
continue
|
|
302
|
+
hit = False
|
|
303
|
+
if 'first' in m and texts[0] == str(m['first']).strip():
|
|
304
|
+
hit = True
|
|
305
|
+
if 'first_re' in m and re.search(m['first_re'], texts[0]):
|
|
306
|
+
hit = True
|
|
307
|
+
if 'contains' in m and any(str(m['contains']) in x for x in texts):
|
|
308
|
+
hit = True
|
|
309
|
+
if 'col' in m and ('equals' in m or 're' in m):
|
|
310
|
+
ci = int(m['col'])
|
|
311
|
+
cells = row.cells
|
|
312
|
+
if 0 <= ci < len(cells):
|
|
313
|
+
v = _cell_text(cells[ci])
|
|
314
|
+
if 'equals' in m and v == str(m['equals']).strip():
|
|
315
|
+
hit = True
|
|
316
|
+
elif 're' in m and re.search(m['re'], v):
|
|
317
|
+
hit = True
|
|
318
|
+
if hit and i2 not in targets:
|
|
319
|
+
targets.append(i2)
|
|
320
|
+
if not targets:
|
|
321
|
+
raise SystemExit('%s:delete_rows 没匹配到任何行' % where)
|
|
322
|
+
if 0 in targets and not op.get('allow_row0'):
|
|
323
|
+
raise SystemExit('%s:命中第 0 行(通常是分组标题),如确需删除请显式 allow_row0=true'
|
|
324
|
+
% where)
|
|
325
|
+
if len(targets) >= len(rows):
|
|
326
|
+
raise SystemExit('%s:会删掉整张表全部 %d 行,拒绝执行' % (where, len(rows)))
|
|
327
|
+
return {'op': i, 'type': t, 'table': op['table'], 'delete_rows': sorted(targets),
|
|
328
|
+
'status': 'validated'}
|
|
329
|
+
|
|
330
|
+
if t == 'amount_split':
|
|
331
|
+
table = get_table(doc, op, where)
|
|
332
|
+
amount_col = op.get('amount_col')
|
|
333
|
+
if not isinstance(amount_col, int):
|
|
334
|
+
raise SystemExit('%s:amount_split 缺 amount_col' % where)
|
|
335
|
+
matchers = op.get('rows') or []
|
|
336
|
+
if not matchers:
|
|
337
|
+
raise SystemExit('%s:amount_split 缺 rows(每期一个行定位器)' % where)
|
|
338
|
+
ratios = op.get('ratios')
|
|
339
|
+
if ratios is None and not isinstance(op.get('ratio_col'), int):
|
|
340
|
+
raise SystemExit('%s:amount_split 需要 ratios 或 ratio_col' % where)
|
|
341
|
+
total = parse_money(op.get('total'))
|
|
342
|
+
rs = []
|
|
343
|
+
for m in matchers:
|
|
344
|
+
ri = match_row(table, m, where + '.rows')
|
|
345
|
+
if ri in rs:
|
|
346
|
+
raise SystemExit('%s:rows 定位重复命中第 %d 行' % (where, ri))
|
|
347
|
+
rs.append(ri)
|
|
348
|
+
if ratios is not None and len(ratios) != len(rs):
|
|
349
|
+
raise SystemExit('%s:ratios 有 %d 项,rows 有 %d 项,必须一一对应'
|
|
350
|
+
% (where, len(ratios), len(rs)))
|
|
351
|
+
plan_rows = []
|
|
352
|
+
acc = Decimal('0')
|
|
353
|
+
for k, ri in enumerate(rs):
|
|
354
|
+
r = parse_ratio(ratios[k]) if ratios is not None else \
|
|
355
|
+
parse_ratio(_cell_text(table.rows[ri].cells[int(op['ratio_col'])]))
|
|
356
|
+
amt = (total * r / Decimal('100')).quantize(Decimal('0.01'), rounding=ROUND_HALF_UP) \
|
|
357
|
+
if k < len(rs) - 1 else (total - acc)
|
|
358
|
+
acc += amt
|
|
359
|
+
plan_rows.append({'row': ri, 'ratio': str(r), 'amount': fmt_money(
|
|
360
|
+
amt, op.get('currency', '¥'), int(op.get('decimals', 2)))})
|
|
361
|
+
if acc != total:
|
|
362
|
+
raise SystemExit('%s:分期合计 %s 与总额 %s 不符(尾差应落在最后一期)'
|
|
363
|
+
% (where, acc, total))
|
|
364
|
+
return {'op': i, 'type': t, 'table': op['table'], 'total': str(total),
|
|
365
|
+
'rows': plan_rows, 'status': 'validated'}
|
|
366
|
+
|
|
367
|
+
raise SystemExit('%s:未知 op type=%r(支持 replace_text / cell / rows / '
|
|
368
|
+
'delete_rows / amount_split)' % (where, t))
|
|
369
|
+
|
|
370
|
+
|
|
371
|
+
# ── 各 op 的执行 ──────────────────────────────────────────────
|
|
372
|
+
|
|
373
|
+
|
|
374
|
+
def apply_table_ops(doc, ops, report, snapshots=None):
|
|
375
|
+
snapshots = snapshots or {}
|
|
376
|
+
for i, op in enumerate(ops):
|
|
377
|
+
t = op.get('type')
|
|
378
|
+
if t == 'replace_text':
|
|
379
|
+
continue # 走 XML 层,最后统一处理
|
|
380
|
+
where = 'ops[%d]' % i
|
|
381
|
+
|
|
382
|
+
if t == 'cell':
|
|
383
|
+
table = get_table(doc, op, where)
|
|
384
|
+
ri = match_row(table, op.get('row_match') or {}, where)
|
|
385
|
+
cell = table.rows[ri].cells[op['col']]
|
|
386
|
+
before = _cell_text(cell)
|
|
387
|
+
inherit = bool(op.get('inherit_format', True))
|
|
388
|
+
donor = find_donor_rpr(doc, table, ri, op['col'], op.get('format_from'))
|
|
389
|
+
set_cell(cell, op.get('value'), rpr=donor, inherit=inherit)
|
|
390
|
+
report.append({'op': i, 'type': t, 'row': ri, 'col': op['col'],
|
|
391
|
+
'before': before, 'after': str(op.get('value')),
|
|
392
|
+
'format_inherit': inherit,
|
|
393
|
+
'format_donor': 'found' if donor is not None else 'none'})
|
|
394
|
+
|
|
395
|
+
elif t == 'amount_split':
|
|
396
|
+
table = get_table(doc, op, where)
|
|
397
|
+
v = validate_op(doc, op, i)
|
|
398
|
+
detail = []
|
|
399
|
+
for item in v['rows']:
|
|
400
|
+
cell = table.rows[item['row']].cells[op['amount_col']]
|
|
401
|
+
before = _cell_text(cell)
|
|
402
|
+
donor = find_donor_rpr(doc, table, item['row'], op['amount_col'],
|
|
403
|
+
op.get('format_from'))
|
|
404
|
+
set_cell(cell, item['amount'], rpr=donor,
|
|
405
|
+
inherit=bool(op.get('inherit_format', True)))
|
|
406
|
+
detail.append({'row': item['row'], 'ratio': item['ratio'],
|
|
407
|
+
'before': before, 'after': item['amount']})
|
|
408
|
+
report.append({'op': i, 'type': t, 'total': v['total'], 'rows': detail})
|
|
409
|
+
|
|
410
|
+
elif t == 'rows':
|
|
411
|
+
table = get_table(doc, op, where)
|
|
412
|
+
anchor = match_row(table, op.get('anchor') or {}, where + '.anchor')
|
|
413
|
+
anchor_tr = table.rows[anchor]._tr
|
|
414
|
+
try:
|
|
415
|
+
proto = match_row(table, op.get('clone_from') or {}, where + '.clone_from')
|
|
416
|
+
proto_tr = copy.deepcopy(table.rows[proto]._tr)
|
|
417
|
+
proto_src = 'current'
|
|
418
|
+
except SystemExit:
|
|
419
|
+
# 原型行已被前置 delete_rows 删除 → 用预检阶段的快照,顺序不再敏感
|
|
420
|
+
if i not in snapshots:
|
|
421
|
+
raise
|
|
422
|
+
proto_tr = copy.deepcopy(snapshots[i])
|
|
423
|
+
proto = -1
|
|
424
|
+
proto_src = 'snapshot'
|
|
425
|
+
fill = op.get('fill') or []
|
|
426
|
+
pos = (op.get('position') or 'before').lower()
|
|
427
|
+
|
|
428
|
+
inserted = []
|
|
429
|
+
for line in fill:
|
|
430
|
+
clone = copy.deepcopy(proto_tr)
|
|
431
|
+
if pos == 'after':
|
|
432
|
+
# 依次插到 anchor 之后,需保持顺序
|
|
433
|
+
anchor_tr.addnext(clone) if not inserted else inserted[-1].addnext(clone)
|
|
434
|
+
else:
|
|
435
|
+
anchor_tr.addprevious(clone)
|
|
436
|
+
inserted.append(clone)
|
|
437
|
+
|
|
438
|
+
# 用新插入的行对象填值(重新按行取 cells,避免索引漂移)
|
|
439
|
+
for k, line in enumerate(fill):
|
|
440
|
+
tr = inserted[k]
|
|
441
|
+
row_obj = None
|
|
442
|
+
for r in table.rows:
|
|
443
|
+
if r._tr is tr:
|
|
444
|
+
row_obj = r
|
|
445
|
+
break
|
|
446
|
+
if row_obj is None:
|
|
447
|
+
raise SystemExit('%s:插入的第 %d 行无法定位,可能触发合并结构异常' % (where, k))
|
|
448
|
+
for c_idx, val in enumerate(line):
|
|
449
|
+
# 克隆行已带原型格式,重写文本即保留样式,不再覆盖 rPr
|
|
450
|
+
set_cell(row_obj.cells[c_idx], val, rpr=None, inherit=False)
|
|
451
|
+
report.append({'op': i, 'type': t, 'anchor_row': anchor, 'clone_row': proto,
|
|
452
|
+
'clone_source': proto_src,
|
|
453
|
+
'inserted': len(fill), 'position': pos})
|
|
454
|
+
|
|
455
|
+
elif t == 'delete_rows':
|
|
456
|
+
table = get_table(doc, op, where)
|
|
457
|
+
v = validate_op(doc, op, i)
|
|
458
|
+
targets = v['delete_rows']
|
|
459
|
+
trs = [table.rows[r]._tr for r in targets]
|
|
460
|
+
for tr in trs:
|
|
461
|
+
tr.getparent().remove(tr)
|
|
462
|
+
report.append({'op': i, 'type': t, 'deleted': len(targets)})
|
|
463
|
+
|
|
464
|
+
|
|
465
|
+
# ── XML 层文本替换(唯一能覆盖文本框的方式)─────────────────────
|
|
466
|
+
|
|
467
|
+
|
|
468
|
+
W = '{http://schemas.openxmlformats.org/wordprocessingml/2006/main}'
|
|
469
|
+
|
|
470
|
+
|
|
471
|
+
def _direct_ts(p):
|
|
472
|
+
"""取段落**直属**的 w:t,排除嵌套段落(文本框 <w:txbxContent> 内含独立段落)。"""
|
|
473
|
+
out = []
|
|
474
|
+
for t in p.iter(W + 't'):
|
|
475
|
+
anc = t.getparent()
|
|
476
|
+
while anc is not None and anc.tag != W + 'p':
|
|
477
|
+
anc = anc.getparent()
|
|
478
|
+
if anc is p:
|
|
479
|
+
out.append(t)
|
|
480
|
+
return out
|
|
481
|
+
|
|
482
|
+
|
|
483
|
+
def precheck_expect(template, ops):
|
|
484
|
+
"""按「模板原始状态」校验 replace_text 的 expect 指纹。
|
|
485
|
+
|
|
486
|
+
必须在任何写入之前执行:expect 描述的是模板里有几处占位,
|
|
487
|
+
而 cell / rows op 会先改掉其中一部分,导致执行期计数必然偏小。
|
|
488
|
+
"""
|
|
489
|
+
text_ops = [(i, o) for i, o in enumerate(ops) if o.get('type') == 'replace_text']
|
|
490
|
+
if not text_ops:
|
|
491
|
+
return []
|
|
492
|
+
|
|
493
|
+
with zipfile.ZipFile(template) as z:
|
|
494
|
+
xmls = []
|
|
495
|
+
for n in z.namelist():
|
|
496
|
+
if n.startswith('word/') and n.endswith('.xml'):
|
|
497
|
+
xmls.append(re.sub(r'<[^>]+>', '', z.read(n).decode('utf-8', 'ignore')))
|
|
498
|
+
full = '\n'.join(xmls)
|
|
499
|
+
|
|
500
|
+
out = []
|
|
501
|
+
for i, op in text_ops:
|
|
502
|
+
expect = op.get('expect')
|
|
503
|
+
if op.get('find'):
|
|
504
|
+
actual = full.count(op['find'])
|
|
505
|
+
else:
|
|
506
|
+
actual = len(re.findall(op['find_re'], full, re.S))
|
|
507
|
+
if expect is not None and actual != int(expect):
|
|
508
|
+
raise SystemExit('ops[%d]:expect=%s 与模板初始出现次数 %d 不符——'
|
|
509
|
+
'模板已变更,请重新确认 plan(原文件未改动)'
|
|
510
|
+
% (i, expect, actual))
|
|
511
|
+
out.append({'op': i, 'pattern': op.get('find') or op.get('find_re'),
|
|
512
|
+
'template_hits': actual, 'expect': expect})
|
|
513
|
+
return out
|
|
514
|
+
|
|
515
|
+
|
|
516
|
+
def apply_text_ops_lxml(path, ops, report):
|
|
517
|
+
"""基于 lxml 的文本替换。
|
|
518
|
+
|
|
519
|
+
为什么不用正则切分 <w:p>:文本框内的段落是**嵌套**在外层段落里的,
|
|
520
|
+
非贪婪正则会在内层 </w:p> 处提前闭合,把外层段落切成碎片,
|
|
521
|
+
导致正文里的占位符漏替换(实测:3 处只替换到 2 处)。
|
|
522
|
+
lxml 按元素遍历天然规避嵌套问题,且能顺带覆盖页眉页脚/脚注。
|
|
523
|
+
"""
|
|
524
|
+
from lxml import etree
|
|
525
|
+
|
|
526
|
+
text_ops = [(i, o) for i, o in enumerate(ops) if o.get('type') == 'replace_text']
|
|
527
|
+
if not text_ops:
|
|
528
|
+
return
|
|
529
|
+
|
|
530
|
+
with zipfile.ZipFile(path) as z:
|
|
531
|
+
names = z.namelist()
|
|
532
|
+
data = {n: z.read(n) for n in names}
|
|
533
|
+
infos = {i.filename: i for i in z.infolist()}
|
|
534
|
+
|
|
535
|
+
xml_names = [n for n in names if n.startswith('word/') and n.endswith('.xml')]
|
|
536
|
+
|
|
537
|
+
for i, op in text_ops:
|
|
538
|
+
find = op.get('find')
|
|
539
|
+
find_re = op.get('find_re')
|
|
540
|
+
value = str(op['value'])
|
|
541
|
+
total = 0
|
|
542
|
+
merged_cnt = 0
|
|
543
|
+
touched = []
|
|
544
|
+
|
|
545
|
+
for n in xml_names:
|
|
546
|
+
raw = data[n]
|
|
547
|
+
if b'<w:p' not in raw:
|
|
548
|
+
continue
|
|
549
|
+
try:
|
|
550
|
+
root = etree.fromstring(raw)
|
|
551
|
+
except Exception:
|
|
552
|
+
continue
|
|
553
|
+
changed = False
|
|
554
|
+
for p in root.iter(W + 'p'):
|
|
555
|
+
ts = _direct_ts(p)
|
|
556
|
+
if not ts:
|
|
557
|
+
continue
|
|
558
|
+
combined = ''.join(t.text or '' for t in ts)
|
|
559
|
+
if not combined:
|
|
560
|
+
continue
|
|
561
|
+
if find is not None:
|
|
562
|
+
if find not in combined:
|
|
563
|
+
continue
|
|
564
|
+
cnt = combined.count(find)
|
|
565
|
+
new_text = combined.replace(find, value)
|
|
566
|
+
else:
|
|
567
|
+
if not re.search(find_re, combined, re.S):
|
|
568
|
+
continue
|
|
569
|
+
cnt = len(re.findall(find_re, combined, re.S))
|
|
570
|
+
new_text = re.sub(find_re, value, combined, flags=re.S)
|
|
571
|
+
ts[0].text = new_text
|
|
572
|
+
for t in ts[1:]:
|
|
573
|
+
t.text = ''
|
|
574
|
+
total += cnt
|
|
575
|
+
merged_cnt += 1 if len(ts) > 1 else 0
|
|
576
|
+
changed = True
|
|
577
|
+
if changed:
|
|
578
|
+
data[n] = etree.tostring(root, xml_declaration=True,
|
|
579
|
+
encoding='UTF-8', standalone=True)
|
|
580
|
+
touched.append(n)
|
|
581
|
+
|
|
582
|
+
expect = op.get('expect')
|
|
583
|
+
# expect 的语义是「模板初始出现次数」指纹,已在 precheck_expect() 阶段校验过,
|
|
584
|
+
# 此处不再中止:前置的 cell / rows op 可能已经改掉其中若干处。
|
|
585
|
+
report.append({'op': i, 'type': 'replace_text', 'find': find, 'find_re': find_re,
|
|
586
|
+
'replaced': total, 'expect': expect,
|
|
587
|
+
'merged_paragraphs': merged_cnt, 'files': touched})
|
|
588
|
+
|
|
589
|
+
tmp = path + '.fillplan.tmp'
|
|
590
|
+
with zipfile.ZipFile(tmp, 'w', zipfile.ZIP_DEFLATED) as zout:
|
|
591
|
+
for n in names:
|
|
592
|
+
zi = zipfile.ZipInfo(n, date_time=infos[n].date_time)
|
|
593
|
+
zi.compress_type = zipfile.ZIP_DEFLATED
|
|
594
|
+
zout.writestr(zi, data[n])
|
|
595
|
+
shutil.move(tmp, path)
|
|
596
|
+
|
|
597
|
+
|
|
598
|
+
# ── 空白单元格审计(2026-11-10 根源修复)────────────────────────
|
|
599
|
+
|
|
600
|
+
|
|
601
|
+
def audit_blank_cells(doc):
|
|
602
|
+
"""列出「同一行有标签、本格为空」的所有格子。
|
|
603
|
+
|
|
604
|
+
为什么要它:模型的漏填往往不是「填错」,而是「没想到这个格也该填」。
|
|
605
|
+
封面乙方、付款金额都是这样漏的——模板原样为空,模型就当成「留空位置」跳过。
|
|
606
|
+
审计把这类格子显式摊出来,plan 必须逐项写「填什么」或「为什么允许空」。
|
|
607
|
+
"""
|
|
608
|
+
out = []
|
|
609
|
+
for ti, t in enumerate(doc.tables):
|
|
610
|
+
for ri, row in enumerate(t.rows):
|
|
611
|
+
cells = row.cells
|
|
612
|
+
texts = [_cell_text(c) for c in cells]
|
|
613
|
+
seen = set()
|
|
614
|
+
for ci, v in enumerate(texts):
|
|
615
|
+
if v:
|
|
616
|
+
continue
|
|
617
|
+
label = ''
|
|
618
|
+
for k in range(ci - 1, -1, -1):
|
|
619
|
+
if texts[k]:
|
|
620
|
+
label = texts[k]
|
|
621
|
+
break
|
|
622
|
+
key = (ti, ri, ci)
|
|
623
|
+
if key in seen:
|
|
624
|
+
continue
|
|
625
|
+
seen.add(key)
|
|
626
|
+
out.append({'table': ti, 'row': ri, 'col': ci,
|
|
627
|
+
'label': label, 'row_texts': texts})
|
|
628
|
+
return out
|
|
629
|
+
|
|
630
|
+
|
|
631
|
+
# ── 金额溯源与一致性(2026-11-10 第二次根源修复)─────────────────
|
|
632
|
+
#
|
|
633
|
+
# 事故复盘:报价书合计 ¥809,166.76,生成出来的合同却写着 ¥2,221,000。
|
|
634
|
+
# 该数字既不在报价书里,也不是任何计算的结果——它是**模板原文自带的**金额
|
|
635
|
+
# (模板预填 ¥2,096,000 + ¥125,000 = ¥2,221,000),模型直接沿用、未覆盖。
|
|
636
|
+
#
|
|
637
|
+
# 根因不是"算错",而是整条链路缺少三道闸:
|
|
638
|
+
# 闸 1 金额来源可追溯:写进合同的每个金额必须能在报价书里找到,或是声明过的派生值
|
|
639
|
+
# 闸 2 模板残留检测:模板自带金额若从未被 op 覆盖,必须报错而不是静默留存
|
|
640
|
+
# 闸 3 勾稽平衡:总额 = 分项之和 = 分期之和
|
|
641
|
+
# 缺了这三道闸,"模型没算"就等于"用模板旧值",且从报告里完全看不出来。
|
|
642
|
+
|
|
643
|
+
MONEY_CELL_RE = re.compile(r'[¥¥]\s*-?[0-9][0-9,]*(?:\.[0-9]+)?|'
|
|
644
|
+
r'-?[0-9][0-9,]*(?:\.[0-9]+)?\s*元')
|
|
645
|
+
|
|
646
|
+
|
|
647
|
+
def _money_entries(doc, strict=True):
|
|
648
|
+
"""枚举文档里所有含货币符号或「元」的格子,去重(合并单元格会重复返回)。
|
|
649
|
+
|
|
650
|
+
strict=True 时只认「纯金额格」:把金额片段剔除后,剩余不应是成句文字。
|
|
651
|
+
否则备注段落(如「按人天(…元人天)核算」)会被误判为金额格,
|
|
652
|
+
在模板残留检测里产生假阳性——实测踩过一次。
|
|
653
|
+
"""
|
|
654
|
+
entries = []
|
|
655
|
+
seen = set()
|
|
656
|
+
for ti, t in enumerate(doc.tables):
|
|
657
|
+
for ri, row in enumerate(t.rows):
|
|
658
|
+
for ci, c in enumerate(row.cells):
|
|
659
|
+
key = id(c._tc)
|
|
660
|
+
if key in seen:
|
|
661
|
+
continue
|
|
662
|
+
seen.add(key)
|
|
663
|
+
s = _cell_text(c)
|
|
664
|
+
if not s or not MONEY_CELL_RE.search(s):
|
|
665
|
+
continue
|
|
666
|
+
if strict:
|
|
667
|
+
rest = MONEY_CELL_RE.sub('', s)
|
|
668
|
+
rest = re.sub(r'[\s::,,.。、()()\[\]【】//]', '', rest)
|
|
669
|
+
if len(rest) > 2: # 成句文字,不是金额格
|
|
670
|
+
continue
|
|
671
|
+
try:
|
|
672
|
+
val = parse_money(s)
|
|
673
|
+
except SystemExit:
|
|
674
|
+
continue
|
|
675
|
+
entries.append({'table': ti, 'row': ri, 'col': ci,
|
|
676
|
+
'text': s, 'value': val})
|
|
677
|
+
return entries
|
|
678
|
+
|
|
679
|
+
|
|
680
|
+
def audit_money_cells(doc, strict=True):
|
|
681
|
+
"""列出模板里所有金额格。
|
|
682
|
+
|
|
683
|
+
目的:让模型看见"模板预填了哪些金额"。这些值不属于本次交易,
|
|
684
|
+
不显式覆盖就会作为合同金额交付出去——2,221,000 就是这么来的。
|
|
685
|
+
"""
|
|
686
|
+
return [{'table': e['table'], 'row': e['row'], 'col': e['col'],
|
|
687
|
+
'text': e['text'], 'value': str(e['value'])}
|
|
688
|
+
for e in _money_entries(doc, strict=strict)]
|
|
689
|
+
|
|
690
|
+
|
|
691
|
+
def quote_money_values(path):
|
|
692
|
+
"""从报价书里抽出全部数值,作为允许出现在合同中的「合法金额来源」。"""
|
|
693
|
+
raw = ''
|
|
694
|
+
if path.lower().endswith('.json'):
|
|
695
|
+
with io.open(path, encoding='utf-8') as f:
|
|
696
|
+
raw = f.read()
|
|
697
|
+
elif path.lower().endswith(('.docx', '.xlsx')):
|
|
698
|
+
with zipfile.ZipFile(path) as z:
|
|
699
|
+
for n in z.namelist():
|
|
700
|
+
if n.startswith('word/') and n.endswith('.xml') or \
|
|
701
|
+
n.startswith('xl/') and n.endswith('.xml'):
|
|
702
|
+
raw += re.sub(r'<[^>]+>', ' ', z.read(n).decode('utf-8', 'ignore'))
|
|
703
|
+
else:
|
|
704
|
+
raise SystemExit('--quote 只支持 .docx / .xlsx / .json:%s' % path)
|
|
705
|
+
|
|
706
|
+
vals = set()
|
|
707
|
+
for m in re.finditer(r'-?[0-9][0-9,]*(?:\.[0-9]+)?', raw):
|
|
708
|
+
s = m.group(0).replace(',', '')
|
|
709
|
+
try:
|
|
710
|
+
vals.add(Decimal(s))
|
|
711
|
+
except Exception:
|
|
712
|
+
pass
|
|
713
|
+
return vals
|
|
714
|
+
|
|
715
|
+
|
|
716
|
+
def check_provenance(spec, quote_vals):
|
|
717
|
+
"""闸 1:合同里每个金额都必须来自报价书,或出现在 plan 声明的 derived_allowed 里。
|
|
718
|
+
|
|
719
|
+
派生值(分期金额、尾差、拆分明细)本身不在报价书里,
|
|
720
|
+
必须显式声明,避免"凭空冒出一个数"却无从追溯。
|
|
721
|
+
"""
|
|
722
|
+
money = (spec.get('money') or {})
|
|
723
|
+
allowed = money.get('allowed_amounts') or []
|
|
724
|
+
if not allowed:
|
|
725
|
+
return {'ok': True, 'checked': 0, 'untraceable': [],
|
|
726
|
+
'note': '未声明 allowed_amounts,跳过溯源校验'}
|
|
727
|
+
|
|
728
|
+
derived = set()
|
|
729
|
+
for x in (spec.get('derived_allowed') or []):
|
|
730
|
+
derived.add(parse_money(x))
|
|
731
|
+
|
|
732
|
+
untraceable = []
|
|
733
|
+
for x in allowed:
|
|
734
|
+
v = parse_money(x)
|
|
735
|
+
if v in quote_vals or v in derived:
|
|
736
|
+
continue
|
|
737
|
+
untraceable.append(str(v))
|
|
738
|
+
|
|
739
|
+
return {'ok': not untraceable, 'checked': len(allowed),
|
|
740
|
+
'untraceable': untraceable}
|
|
741
|
+
|
|
742
|
+
|
|
743
|
+
def check_money(doc, spec, template_entries=None):
|
|
744
|
+
"""闸 2 + 闸 3:模板残留金额检测 与 勾稽平衡。"""
|
|
745
|
+
money = spec.get('money') or {}
|
|
746
|
+
failures = []
|
|
747
|
+
|
|
748
|
+
def read_cell(item, group, k):
|
|
749
|
+
t = doc.tables[int(item['table'])]
|
|
750
|
+
ri = match_row(t, item.get('row_match') or {},
|
|
751
|
+
'money.%s[%d]' % (group, k))
|
|
752
|
+
ci = int(item['col'])
|
|
753
|
+
txt = _cell_text(t.rows[ri].cells[ci])
|
|
754
|
+
if not txt:
|
|
755
|
+
return None, {'kind': 'empty', 'group': group,
|
|
756
|
+
'label': item.get('label'), 'table': item['table'],
|
|
757
|
+
'row': ri, 'col': ci}
|
|
758
|
+
try:
|
|
759
|
+
v = parse_money(txt)
|
|
760
|
+
except SystemExit:
|
|
761
|
+
return None, {'kind': 'unparsable', 'group': group,
|
|
762
|
+
'label': item.get('label'), 'text': txt}
|
|
763
|
+
if item.get('equals') is not None and v != parse_money(item['equals']):
|
|
764
|
+
return v, {'kind': 'mismatch', 'group': group,
|
|
765
|
+
'label': item.get('label'),
|
|
766
|
+
'expected': str(parse_money(item['equals'])),
|
|
767
|
+
'actual': str(v)}
|
|
768
|
+
return v, None
|
|
769
|
+
|
|
770
|
+
total = None
|
|
771
|
+
if money.get('total') is not None:
|
|
772
|
+
total = parse_money(money['total'])
|
|
773
|
+
tol = Decimal(str(money.get('tolerance', '0.01')))
|
|
774
|
+
|
|
775
|
+
def sum_group(group_name):
|
|
776
|
+
acc = Decimal('0')
|
|
777
|
+
items = []
|
|
778
|
+
for k, item in enumerate(money.get(group_name) or []):
|
|
779
|
+
v, err = read_cell(item, group_name, k)
|
|
780
|
+
if err:
|
|
781
|
+
failures.append(err)
|
|
782
|
+
continue
|
|
783
|
+
acc += v
|
|
784
|
+
items.append({'label': item.get('label'), 'value': str(v)})
|
|
785
|
+
if total is not None and (money.get(group_name)):
|
|
786
|
+
if abs(acc - total) > tol:
|
|
787
|
+
failures.append({'kind': 'sum_mismatch', 'group': group_name,
|
|
788
|
+
'expected': str(total), 'actual': str(acc),
|
|
789
|
+
'diff': str(acc - total), 'items': items})
|
|
790
|
+
return acc, items
|
|
791
|
+
|
|
792
|
+
parts_sum = installments_sum = None
|
|
793
|
+
if money.get('parts'):
|
|
794
|
+
parts_sum, _ = sum_group('parts')
|
|
795
|
+
if money.get('installments'):
|
|
796
|
+
installments_sum, _ = sum_group('installments')
|
|
797
|
+
|
|
798
|
+
# 闸 2:模板残留。模板原有金额若仍原样留在成品里,说明从未被覆盖。
|
|
799
|
+
stale = []
|
|
800
|
+
if template_entries is not None:
|
|
801
|
+
now = {(e['table'], e['row'], e['col']): e for e in _money_entries(doc)}
|
|
802
|
+
tpl_vals = set(e['value'] for e in template_entries)
|
|
803
|
+
declared = set()
|
|
804
|
+
for x in (money.get('allowed_amounts') or []):
|
|
805
|
+
declared.add(parse_money(x))
|
|
806
|
+
for e in _money_entries(doc):
|
|
807
|
+
if e['value'] in tpl_vals and e['value'] not in declared:
|
|
808
|
+
stale.append({'table': e['table'], 'row': e['row'], 'col': e['col'],
|
|
809
|
+
'text': e['text'],
|
|
810
|
+
'note': '该金额与模板原文相同,且未出现在 allowed_amounts 中,'
|
|
811
|
+
'疑似沿用模板预填值'})
|
|
812
|
+
|
|
813
|
+
return {
|
|
814
|
+
'ok': (not failures) and (not stale),
|
|
815
|
+
'total': str(total) if total is not None else None,
|
|
816
|
+
'parts_sum': str(parts_sum) if parts_sum is not None else None,
|
|
817
|
+
'installments_sum': str(installments_sum) if installments_sum is not None else None,
|
|
818
|
+
'failures': failures,
|
|
819
|
+
'stale_amounts': stale,
|
|
820
|
+
}
|
|
821
|
+
|
|
822
|
+
|
|
823
|
+
# ── 交付前校验 ────────────────────────────────────────────────
|
|
824
|
+
|
|
825
|
+
|
|
826
|
+
def check_must_fill(doc, spec):
|
|
827
|
+
"""断言指定格子非空;任一为空即失败。"""
|
|
828
|
+
missing = []
|
|
829
|
+
for k, item in enumerate(spec.get('must_fill') or []):
|
|
830
|
+
ti = item.get('table')
|
|
831
|
+
try:
|
|
832
|
+
table = doc.tables[int(ti)]
|
|
833
|
+
except Exception:
|
|
834
|
+
missing.append({'index': k, 'reason': 'table %r 不存在' % ti})
|
|
835
|
+
continue
|
|
836
|
+
try:
|
|
837
|
+
ri = match_row(table, item.get('row_match') or {}, 'must_fill[%d]' % k)
|
|
838
|
+
except SystemExit as e:
|
|
839
|
+
missing.append({'index': k, 'reason': str(e)})
|
|
840
|
+
continue
|
|
841
|
+
col = int(item.get('col'))
|
|
842
|
+
cells = table.rows[ri].cells
|
|
843
|
+
if col < 0 or col >= len(cells):
|
|
844
|
+
missing.append({'index': k, 'reason': 'col %d 越界' % col})
|
|
845
|
+
continue
|
|
846
|
+
txt = _cell_text(cells[col])
|
|
847
|
+
if not txt:
|
|
848
|
+
missing.append({'index': k, 'table': ti, 'row': ri, 'col': col,
|
|
849
|
+
'label': item.get('label') or ''})
|
|
850
|
+
return missing
|
|
851
|
+
|
|
852
|
+
|
|
853
|
+
def verify(path, spec, template=None):
|
|
854
|
+
full = []
|
|
855
|
+
visible = []
|
|
856
|
+
with zipfile.ZipFile(path) as z:
|
|
857
|
+
for n in z.namelist():
|
|
858
|
+
if n.startswith('word/') and n.endswith('.xml'):
|
|
859
|
+
full.append(re.sub(r'<[^>]+>', '', z.read(n).decode('utf-8', 'ignore')))
|
|
860
|
+
full = '\n'.join(full)
|
|
861
|
+
|
|
862
|
+
d = docx.Document(path)
|
|
863
|
+
visible.append('\n'.join(p.text for p in d.paragraphs))
|
|
864
|
+
for t in d.tables:
|
|
865
|
+
for row in t.rows:
|
|
866
|
+
for c in row.cells:
|
|
867
|
+
visible.append(c.text)
|
|
868
|
+
visible = '\n'.join(visible)
|
|
869
|
+
|
|
870
|
+
residue = {}
|
|
871
|
+
for pat in (spec.get('residue') or []):
|
|
872
|
+
n = full.count(pat)
|
|
873
|
+
if n:
|
|
874
|
+
residue[pat] = n
|
|
875
|
+
|
|
876
|
+
title_hits = None
|
|
877
|
+
title_ok = True
|
|
878
|
+
if spec.get('title'):
|
|
879
|
+
title_hits = full.count(spec['title'])
|
|
880
|
+
want = spec.get('title_count', 2)
|
|
881
|
+
title_ok = (title_hits == want)
|
|
882
|
+
|
|
883
|
+
inconsistent = [pat for pat in (spec.get('residue') or [])
|
|
884
|
+
if visible.count(pat) > full.count(pat)]
|
|
885
|
+
|
|
886
|
+
must_fill_missing = check_must_fill(d, spec)
|
|
887
|
+
|
|
888
|
+
template_entries = _money_entries(docx.Document(template)) if template else None
|
|
889
|
+
money = check_money(d, spec, template_entries)
|
|
890
|
+
|
|
891
|
+
return {
|
|
892
|
+
'ok': (not residue) and title_ok and (not inconsistent)
|
|
893
|
+
and (not must_fill_missing) and money['ok'],
|
|
894
|
+
'residue': residue,
|
|
895
|
+
'title': spec.get('title'),
|
|
896
|
+
'title_hits': title_hits,
|
|
897
|
+
'title_ok': title_ok,
|
|
898
|
+
'cross_inconsistent': inconsistent,
|
|
899
|
+
'must_fill_missing': must_fill_missing,
|
|
900
|
+
'money': money,
|
|
901
|
+
'tables': len(d.tables),
|
|
902
|
+
}
|
|
903
|
+
|
|
904
|
+
|
|
905
|
+
def main():
|
|
906
|
+
ap = argparse.ArgumentParser(description='FillPlan 执行器(只执行,不做语义判断)')
|
|
907
|
+
ap.add_argument('--template', required=True)
|
|
908
|
+
ap.add_argument('--plan', default=None)
|
|
909
|
+
ap.add_argument('--out', default=None)
|
|
910
|
+
ap.add_argument('--report', default=None)
|
|
911
|
+
ap.add_argument('--dry-run', action='store_true', help='只校验定位与断言,不写文件')
|
|
912
|
+
ap.add_argument('--audit', action='store_true',
|
|
913
|
+
help='列出模板中「有标签但为空」的格子与全部金额格,供模型逐项处置')
|
|
914
|
+
ap.add_argument('--quote', default=None,
|
|
915
|
+
help='报价书 .docx/.xlsx/.json;用于校验合同金额是否可溯源到报价书')
|
|
916
|
+
args = ap.parse_args()
|
|
917
|
+
|
|
918
|
+
if args.audit:
|
|
919
|
+
d = docx.Document(args.template)
|
|
920
|
+
blanks = audit_blank_cells(d)
|
|
921
|
+
money = audit_money_cells(d)
|
|
922
|
+
print(json.dumps({'ok': True, 'audit': True, 'tables': len(d.tables),
|
|
923
|
+
'blank_count': len(blanks), 'blanks': blanks,
|
|
924
|
+
'money_count': len(money), 'money_cells': money,
|
|
925
|
+
'note': '① 每个空值格都必须在 plan 里显式填值,'
|
|
926
|
+
'或在 verify.must_fill 声明允许留空;'
|
|
927
|
+
'② money_cells 是模板预填金额,不属于本次交易,'
|
|
928
|
+
'必须被 op 覆盖或在 verify.money.allowed_amounts 中显式放行;'
|
|
929
|
+
'沿用模板金额即视为错误'},
|
|
930
|
+
ensure_ascii=False, indent=2))
|
|
931
|
+
return 0
|
|
932
|
+
|
|
933
|
+
if not args.plan:
|
|
934
|
+
raise SystemExit('未给 --plan(若只想看空白格,请加 --audit)')
|
|
935
|
+
|
|
936
|
+
with io.open(args.plan, encoding='utf-8') as f:
|
|
937
|
+
plan = json.load(f)
|
|
938
|
+
ops = plan.get('ops') or []
|
|
939
|
+
if not ops:
|
|
940
|
+
raise SystemExit('plan 里没有 ops')
|
|
941
|
+
|
|
942
|
+
doc = docx.Document(args.template)
|
|
943
|
+
|
|
944
|
+
# 预检:全部 op 先校验,任一失败立即中止,绝不写半个文件
|
|
945
|
+
checked = [validate_op(doc, op, i) for i, op in enumerate(ops)]
|
|
946
|
+
expect_checks = precheck_expect(args.template, ops)
|
|
947
|
+
|
|
948
|
+
# 闸 1(预检期):金额溯源。写文件之前就拦住「凭空出现的金额」。
|
|
949
|
+
spec = plan.get('verify') or {}
|
|
950
|
+
prov = {'ok': True, 'checked': 0, 'untraceable': [], 'note': '未提供 --quote,跳过溯源'}
|
|
951
|
+
if args.quote:
|
|
952
|
+
prov = check_provenance(spec, quote_money_values(args.quote))
|
|
953
|
+
if not prov['ok']:
|
|
954
|
+
raise SystemExit(
|
|
955
|
+
'金额溯源失败:%r 不在报价书内、也未在 verify.derived_allowed 中声明。'
|
|
956
|
+
'合同金额必须来自报价书或明确声明的派生值(如分期金额),'
|
|
957
|
+
'不得沿用模板预填金额,也不得凭空生成(原文件未改动)。'
|
|
958
|
+
% (prov['untraceable'],))
|
|
959
|
+
|
|
960
|
+
# clone 原型快照:保证 rows 不受前置 delete_rows 影响
|
|
961
|
+
snapshots = {}
|
|
962
|
+
for i, op in enumerate(ops):
|
|
963
|
+
if op.get('type') == 'rows':
|
|
964
|
+
v = checked[i]
|
|
965
|
+
snapshots[i] = copy.deepcopy(doc.tables[op['table']].rows[v['clone_row']]._tr)
|
|
966
|
+
|
|
967
|
+
if args.dry_run:
|
|
968
|
+
print(json.dumps({'ok': True, 'dry_run': True, 'ops': checked,
|
|
969
|
+
'expect_checks': expect_checks,
|
|
970
|
+
'provenance': prov,
|
|
971
|
+
'money_spec': spec.get('money') or {},
|
|
972
|
+
'template_money': audit_money_cells(doc),
|
|
973
|
+
'must_fill': spec.get('must_fill') or []},
|
|
974
|
+
ensure_ascii=False, indent=2))
|
|
975
|
+
return 0
|
|
976
|
+
|
|
977
|
+
if not args.out:
|
|
978
|
+
raise SystemExit('非 dry-run 必须给 --out')
|
|
979
|
+
|
|
980
|
+
report = []
|
|
981
|
+
apply_table_ops(doc, ops, report, snapshots)
|
|
982
|
+
doc.save(args.out)
|
|
983
|
+
apply_text_ops_lxml(args.out, ops, report)
|
|
984
|
+
|
|
985
|
+
v = verify(args.out, spec, template=args.template)
|
|
986
|
+
result = {'ok': v['ok'], 'out': args.out, 'ops': report, 'verify': v}
|
|
987
|
+
|
|
988
|
+
if args.report:
|
|
989
|
+
with io.open(args.report, 'w', encoding='utf-8') as f:
|
|
990
|
+
json.dump(result, f, ensure_ascii=False, indent=2)
|
|
991
|
+
|
|
992
|
+
print(json.dumps(result, ensure_ascii=False, indent=2))
|
|
993
|
+
return 0 if v['ok'] else 1
|
|
994
|
+
|
|
995
|
+
|
|
996
|
+
if __name__ == '__main__':
|
|
997
|
+
sys.exit(main())
|