weaver-work-cli 0.1.52 → 0.1.54
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-MBYYSQIX.js → attachment-content-2EPEI4HV.js} +3 -3
- package/dist/chunks/{chunk-DZOC77ZD.js → chunk-6LGLI46Q.js} +1 -1
- package/dist/chunks/{chunk-RWFRZSIP.js → chunk-7KKI5KDY.js} +2 -2
- package/dist/chunks/{chunk-KLZ3ULQQ.js → chunk-CNVZETM5.js} +1 -1
- package/dist/chunks/{chunk-RPRFIG6I.js → chunk-FE3CQAAM.js} +23 -23
- package/dist/chunks/{chunk-ZRHKGQRQ.js → chunk-JJRIT2ZN.js} +2 -2
- package/dist/chunks/{chunk-LTRLF6MM.js → chunk-LYOFRYC4.js} +4 -4
- package/dist/chunks/{chunk-7UOXOGFL.js → chunk-O6RIBG5E.js} +4 -4
- package/dist/chunks/{chunk-LM2H7SZI.js → chunk-QUDHSMG3.js} +37 -25
- package/dist/chunks/{chunk-IRMA3GVP.js → chunk-XHMJBRLZ.js} +1 -1
- package/dist/chunks/{chunk-LALWNK6M.js → chunk-XPQN4E5O.js} +41 -19
- package/dist/chunks/{chunk-D3TDNRFE.js → chunk-Z7B7QSR2.js} +7 -7
- package/dist/chunks/{conflict-D2HYKBMH.js → conflict-K2IAKKFR.js} +2 -2
- package/dist/chunks/{contract-MFOFMM2J.js → contract-LJRAXVZU.js} +5448 -1857
- package/dist/chunks/{create-flow-7ZATJVTM.js → create-flow-UL37MZGP.js} +6 -6
- package/dist/chunks/{env-5DO4YENS.js → env-BZDB5OVZ.js} +2 -2
- package/dist/chunks/{factory-3M7D7WJC.js → factory-VD3YI6N7.js} +1 -1
- package/dist/chunks/{group-chat-B2HT5NEO.js → group-chat-DHNVO76L.js} +3 -3
- package/dist/chunks/{meeting-HZOX3CBB.js → meeting-OWG4O2XH.js} +10 -10
- package/dist/chunks/{registry-SJHSBO5G.js → registry-ASYCWF2U.js} +10 -10
- package/dist/chunks/{registry-KYPFFQIH.js → registry-CJOVECZD.js} +1 -1
- package/dist/chunks/{room-recommend-5AHR4YQV.js → room-recommend-LSVAMGKV.js} +4 -4
- package/dist/chunks/{schedule-KZPJUPC2.js → schedule-7QOPRUU4.js} +4 -4
- package/dist/chunks/{smart-extract-IXHCZE4R.js → smart-extract-FOUYNIG3.js} +44 -8
- package/dist/chunks/{workflow-UHKCZJMY.js → workflow-YHXFIU63.js} +1 -1
- package/dist/index.js +4 -4
- package/dist/shortcuts/contract/manifest.js +105 -5
- package/dist/shortcuts/contract/ooxml/docx-table.js +233 -0
- package/dist/shortcuts/contract/operations/card-action.js +597 -17
- package/dist/shortcuts/contract/operations/card-ebdf-list.js +258 -2
- 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 +47 -0
- package/dist/shortcuts/contract/operations/first-screen.js +28 -3
- package/dist/shortcuts/contract/operations/ledger.js +438 -0
- package/dist/shortcuts/contract/operations/performance.js +104 -3
- package/dist/shortcuts/contract/operations/quotescreen.js +529 -0
- package/dist/shortcuts/contract/operations/registry.js +10 -0
- package/dist/shortcuts/contract/operations/triage.js +1100 -0
- package/dist/shortcuts/meeting/operations/eb/create-flow.js +21 -0
- package/dist/shortcuts/smart-extract/operations/fill.js +10 -7
- package/dist/shortcuts/smart-extract/operations/validate.js +49 -3
- package/dist/shortcuts/workflow/operations/form.js +68 -33
- package/docs/smart-extract.md +5 -5
- package/package.json +1 -1
- package/skills/weaver-e10-jinchengda/SKILL.md +139 -99
- package/skills/weaver-e10-jinchengda/references/contract-action-card.md +43 -482
- package/skills/weaver-e10-jinchengda/references/contract-action-engine.md +7 -8
- 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 +13 -9
- package/skills/weaver-e10-jinchengda/references/contract-execution-rules.md +2 -2
- package/skills/weaver-e10-jinchengda/references/contract-field-extract-new-customer.md +2 -2
- package/skills/weaver-e10-jinchengda/references/contract-field-extract-other-flows.md +3 -3
- 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 +1 -1
- package/skills/weaver-e10-jinchengda/references/contract-multi-file.md +3 -6
- package/skills/weaver-e10-jinchengda/references/contract-performance-query.md +80 -54
- package/skills/weaver-e10-jinchengda/references/contract-quote-to-contract.md +53 -76
- 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-meeting/SKILL.md +2 -1
- package/skills/weaver-e10-smart-extract/SKILL.md +15 -4
- package/skills/weaver-e10-smart-extract/references/result-format.md +2 -2
- package/skills/weaver-e10-smart-extract/references/troubleshooting.md +2 -1
- 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-jinchengda/scripts/contract_first_screen.py +0 -200
- package/skills/weaver-e10-jinchengda/scripts/fill_contract_from_quote.py +0 -572
- package/skills/weaver-e10-jinchengda/scripts/quote_screen.py +0 -560
- package/skills/weaver-e10-jinchengda/scripts/triage_contract.py +0 -894
- package/skills/weaver-e10-jinchengda/scripts/validate_action_card.py +0 -598
- package/skills/weaver-e10-jinchengda/scripts/verify_docx_placeholders.py +0 -118
|
@@ -1,572 +0,0 @@
|
|
|
1
|
-
# -*- coding: utf-8 -*-
|
|
2
|
-
"""报价单 → 合同 docx 一体化填充:扫描 → 替换 → 填表 → 删行 → 回读校验,一条命令跑完。
|
|
3
|
-
|
|
4
|
-
2026-11-12 新增。背景(实测一次「报价单转合同」耗时 5 分 26 秒,其中约 3 轮纯属白跑):
|
|
5
|
-
1) 用正则拆 document.xml 后直接 print,164 KB / 37 KB 输出被截断落盘,只能改读文件 —— 白跑 2 轮;
|
|
6
|
-
2) 先保存再查占位符,发现 xxx公司 残留后又打补丁,连带把封面标题写成两遍 —— 白跑 3 轮;
|
|
7
|
-
3) 先删 11 行再按原行号删第 20 行,索引漂移直接 IndexError —— 白跑 1 轮;
|
|
8
|
-
4) 填表、补替、诊断、修复被拆成 4 个脚本 4 轮往返。
|
|
9
|
-
|
|
10
|
-
本脚本把这四件事固化为一条命令,并在内部规避上述四个坑:
|
|
11
|
-
- 解析一律走 python-docx 结构化读取,绝不 print 原始 XML(避免超长被截断);
|
|
12
|
-
- 替换前先扫描并列出全部占位符清单,替换 + 保存后立即回读校验(XML 全量 + 可见文本交叉);
|
|
13
|
-
- 明细行只复用模板现有行,多余行**从后往前**删(索引不漂移),绝不用正则重建 <w:tr>;
|
|
14
|
-
- 文本替换做「重复标题折叠」,避免封面标题被写两遍。
|
|
15
|
-
|
|
16
|
-
用法:
|
|
17
|
-
python fill_contract_from_quote.py --template <模板.docx> --data <data.json> --out <输出.docx>
|
|
18
|
-
python fill_contract_from_quote.py --template <模板.docx> --scan-only
|
|
19
|
-
python fill_contract_from_quote.py ... --detail-table 3 --dry-run
|
|
20
|
-
|
|
21
|
-
data.json 结构::
|
|
22
|
-
|
|
23
|
-
{
|
|
24
|
-
"customer": "某某股份有限公司",
|
|
25
|
-
"our_company": "泛微网络科技股份有限公司",
|
|
26
|
-
"sign_date": "2026年11月12日",
|
|
27
|
-
"sign_place": "上海市",
|
|
28
|
-
"title": "某某股份有限公司协同办公系统(e-cology)软件产品及实施服务购买合同",
|
|
29
|
-
"product_total": 1087500,
|
|
30
|
-
"service_total": 167500,
|
|
31
|
-
"grand_total": 1255000,
|
|
32
|
-
"product_items": [{"no": "1.1", "name": "软件功能模块", "amount": 360000}],
|
|
33
|
-
"service_items": [{"no": "2.1", "name": "项目实施服务", "amount": 167500}],
|
|
34
|
-
"payment_ratios": [0.3, 0.3, 0.3, 0.1]
|
|
35
|
-
}
|
|
36
|
-
|
|
37
|
-
退出码:
|
|
38
|
-
0 = 通过;1 = 校验不通过 / 模板结构不满足;2 = 入参或文件错误
|
|
39
|
-
"""
|
|
40
|
-
import argparse
|
|
41
|
-
import json
|
|
42
|
-
import os
|
|
43
|
-
import re
|
|
44
|
-
import sys
|
|
45
|
-
import zipfile
|
|
46
|
-
|
|
47
|
-
import docx
|
|
48
|
-
from docx.oxml.ns import qn
|
|
49
|
-
|
|
50
|
-
# 常见占位模式(可用 --expect 追加)
|
|
51
|
-
PLACEHOLDER_PATTERNS = [
|
|
52
|
-
'xxx公司', 'XXX公司', '***有限公司', '***', '年 月 日', '年 月 日',
|
|
53
|
-
'【】', '____', '{{', '}}',
|
|
54
|
-
]
|
|
55
|
-
|
|
56
|
-
MONEY_FMT = '¥{:,.0f}'
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
def money(v):
|
|
60
|
-
return MONEY_FMT.format(float(v))
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
# --------------------------------------------------------------------------
|
|
64
|
-
# 结构化读取(绝不 print 原始 XML)
|
|
65
|
-
# --------------------------------------------------------------------------
|
|
66
|
-
def para_text(p_el):
|
|
67
|
-
return ''.join(t.text or '' for t in p_el.iter(qn('w:t')))
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
def iter_all_paragraphs(doc):
|
|
71
|
-
"""遍历正文全部段落,含文本框 <w:txbxContent> 内的段落。
|
|
72
|
-
|
|
73
|
-
只遍历 doc.paragraphs 会漏掉文本框;合同标题常被放在文本框里。
|
|
74
|
-
"""
|
|
75
|
-
return list(doc.element.body.iter(qn('w:p')))
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
def set_para_text(p_el, new):
|
|
79
|
-
"""整段替换:首个 w:t 写新值,其余清空(保留首个 run 的格式)。"""
|
|
80
|
-
ts = list(p_el.iter(qn('w:t')))
|
|
81
|
-
if not ts:
|
|
82
|
-
return False
|
|
83
|
-
ts[0].text = new
|
|
84
|
-
try:
|
|
85
|
-
ts[0].set(qn('xml:space'), 'preserve')
|
|
86
|
-
except Exception:
|
|
87
|
-
pass
|
|
88
|
-
for t in ts[1:]:
|
|
89
|
-
t.text = ''
|
|
90
|
-
return True
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
def fold_duplicate(text, unit):
|
|
94
|
-
"""把 text 里连续出现两遍的 unit 折叠成一遍(封面标题被写重时用)。"""
|
|
95
|
-
if not unit:
|
|
96
|
-
return text
|
|
97
|
-
while unit + unit in text:
|
|
98
|
-
text = text.replace(unit + unit, unit)
|
|
99
|
-
return text
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
# --------------------------------------------------------------------------
|
|
103
|
-
# 占位符扫描
|
|
104
|
-
# --------------------------------------------------------------------------
|
|
105
|
-
def scan_placeholders(doc, patterns):
|
|
106
|
-
"""返回 {pattern: [{'loc':..., 'count':...}]},loc 形式为 P#n / T{i}R{r}C{c}。"""
|
|
107
|
-
hits = {}
|
|
108
|
-
|
|
109
|
-
def record(text, loc):
|
|
110
|
-
for p in patterns:
|
|
111
|
-
if p and p in text:
|
|
112
|
-
hits.setdefault(p, []).append({'loc': loc, 'count': text.count(p)})
|
|
113
|
-
|
|
114
|
-
for i, p_el in enumerate(iter_all_paragraphs(doc)):
|
|
115
|
-
record(para_text(p_el), 'P#%d' % i)
|
|
116
|
-
|
|
117
|
-
for ti, tb in enumerate(doc.tables):
|
|
118
|
-
for ri, row in enumerate(tb.rows):
|
|
119
|
-
for ci, cell in enumerate(row.cells):
|
|
120
|
-
record(cell.text, 'T%dR%dC%d' % (ti, ri, ci))
|
|
121
|
-
|
|
122
|
-
return hits
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
def scan_report(hits):
|
|
126
|
-
out = []
|
|
127
|
-
for pat, items in hits.items():
|
|
128
|
-
out.append({
|
|
129
|
-
'placeholder': pat,
|
|
130
|
-
'total': sum(x['count'] for x in items),
|
|
131
|
-
'locations': items,
|
|
132
|
-
})
|
|
133
|
-
out.sort(key=lambda x: -x['total'])
|
|
134
|
-
return out
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
# --------------------------------------------------------------------------
|
|
138
|
-
# 表格探测(按表头特征,不硬编码索引)
|
|
139
|
-
# --------------------------------------------------------------------------
|
|
140
|
-
def table_text(tb):
|
|
141
|
-
buf = []
|
|
142
|
-
for row in tb.rows:
|
|
143
|
-
for c in row.cells:
|
|
144
|
-
buf.append(c.text)
|
|
145
|
-
return '\n'.join(buf)
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
def find_table(doc, must_all=(), must_any=(), min_rows=1):
|
|
149
|
-
for ti, tb in enumerate(doc.tables):
|
|
150
|
-
if len(tb.rows) < min_rows:
|
|
151
|
-
continue
|
|
152
|
-
txt = table_text(tb)
|
|
153
|
-
if must_all and not all(k in txt for k in must_all):
|
|
154
|
-
continue
|
|
155
|
-
if must_any and not any(k in txt for k in must_any):
|
|
156
|
-
continue
|
|
157
|
-
return ti, tb
|
|
158
|
-
return None, None
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
def set_cell(cell, text):
|
|
162
|
-
"""按单元格整体替换:首个段落首 run 写值,清空其余段落与 run。"""
|
|
163
|
-
ps = cell.paragraphs
|
|
164
|
-
if not ps:
|
|
165
|
-
return
|
|
166
|
-
p = ps[0]
|
|
167
|
-
if p.runs:
|
|
168
|
-
p.runs[0].text = text
|
|
169
|
-
for r in p.runs[1:]:
|
|
170
|
-
r.text = ''
|
|
171
|
-
else:
|
|
172
|
-
p.add_run(text)
|
|
173
|
-
for extra in ps[1:]:
|
|
174
|
-
try:
|
|
175
|
-
extra._element.getparent().remove(extra._element)
|
|
176
|
-
except Exception:
|
|
177
|
-
pass
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
def row_text(row):
|
|
181
|
-
return ' | '.join(c.text.strip() for c in row.cells)
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
# --------------------------------------------------------------------------
|
|
185
|
-
# 明细表处理:只复用现有行,多余行从后往前删(索引不漂移)
|
|
186
|
-
# --------------------------------------------------------------------------
|
|
187
|
-
def reshape_rows(table, start_idx, keep, count):
|
|
188
|
-
"""把 table 中 [start_idx, start_idx+count) 区域压缩为 keep 行。
|
|
189
|
-
|
|
190
|
-
只删除,不新增(新增需重建 <w:tr>,会破坏合并单元格)。
|
|
191
|
-
从后往前删,删除过程中前面的行号不受影响。
|
|
192
|
-
"""
|
|
193
|
-
if count < keep:
|
|
194
|
-
return {'ok': False, 'reason': 'not_enough_rows', 'have': count, 'need': keep}
|
|
195
|
-
remove = count - keep
|
|
196
|
-
for idx in range(start_idx + count - 1, start_idx + keep - 1, -1):
|
|
197
|
-
tr = table.rows[idx]._tr
|
|
198
|
-
tr.getparent().remove(tr)
|
|
199
|
-
return {'ok': True, 'removed': remove}
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
def fill_detail_table(tb, data, header_row, product_section_row, product_total_row,
|
|
203
|
-
service_section_row, service_total_row):
|
|
204
|
-
"""按行位填充明细表:产品区、产品合计、服务区、服务明细、服务合计。
|
|
205
|
-
|
|
206
|
-
行位由调用方(本脚本探测)给出;这里只做赋值,不改结构。
|
|
207
|
-
"""
|
|
208
|
-
p_items = data.get('product_items') or []
|
|
209
|
-
s_items = data.get('service_items') or []
|
|
210
|
-
|
|
211
|
-
for i, it in enumerate(p_items):
|
|
212
|
-
row = tb.rows[header_row + 1 + i]
|
|
213
|
-
set_cell(row.cells[0], it.get('no', ''))
|
|
214
|
-
set_cell(row.cells[1], it.get('name', ''))
|
|
215
|
-
amt = it.get('amount')
|
|
216
|
-
set_cell(row.cells[2], money(amt) if amt is not None else '')
|
|
217
|
-
set_cell(row.cells[3], str(it.get('qty', 1)))
|
|
218
|
-
set_cell(row.cells[4], it.get('discount', '100%'))
|
|
219
|
-
set_cell(row.cells[5], money(amt) if amt is not None else '')
|
|
220
|
-
|
|
221
|
-
if product_total_row is not None:
|
|
222
|
-
set_cell(tb.rows[product_total_row].cells[5], money(data['product_total']))
|
|
223
|
-
|
|
224
|
-
if service_section_row is not None and s_items:
|
|
225
|
-
# 服务明细从「服务区标题行」的下一行开始
|
|
226
|
-
for i, it in enumerate(s_items):
|
|
227
|
-
row = tb.rows[service_section_row + 1 + i]
|
|
228
|
-
set_cell(row.cells[0], it.get('no', ''))
|
|
229
|
-
set_cell(row.cells[1], it.get('name', ''))
|
|
230
|
-
amt = it.get('amount')
|
|
231
|
-
set_cell(row.cells[2], money(amt) if amt is not None else '')
|
|
232
|
-
set_cell(row.cells[3], str(it.get('qty', 1)))
|
|
233
|
-
set_cell(row.cells[4], it.get('discount', '100%'))
|
|
234
|
-
set_cell(row.cells[5], money(amt) if amt is not None else '')
|
|
235
|
-
|
|
236
|
-
if service_total_row is not None:
|
|
237
|
-
set_cell(tb.rows[service_total_row].cells[5], money(data['service_total']))
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
# --------------------------------------------------------------------------
|
|
241
|
-
# 回读校验(XML 全量 + 可见文本交叉,覆盖文本框)
|
|
242
|
-
# --------------------------------------------------------------------------
|
|
243
|
-
def xml_full_text(path):
|
|
244
|
-
buf = []
|
|
245
|
-
with zipfile.ZipFile(path) as z:
|
|
246
|
-
for name in z.namelist():
|
|
247
|
-
if name.startswith('word/') and name.endswith('.xml'):
|
|
248
|
-
raw = z.read(name).decode('utf-8', 'ignore')
|
|
249
|
-
buf.append(re.sub(r'<[^>]+>', '', raw))
|
|
250
|
-
return '\n'.join(buf)
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
def visible_text(path):
|
|
254
|
-
d = docx.Document(path)
|
|
255
|
-
buf = [p.text for p in d.paragraphs]
|
|
256
|
-
for t in d.tables:
|
|
257
|
-
for row in t.rows:
|
|
258
|
-
for c in row.cells:
|
|
259
|
-
buf.append(c.text)
|
|
260
|
-
return '\n'.join(buf)
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
def validate(path, patterns, title, expect_title_count):
|
|
264
|
-
full = xml_full_text(path)
|
|
265
|
-
vis = visible_text(path)
|
|
266
|
-
|
|
267
|
-
residue = {}
|
|
268
|
-
cross = {}
|
|
269
|
-
inconsistent = []
|
|
270
|
-
for p in patterns:
|
|
271
|
-
x, v = full.count(p), vis.count(p)
|
|
272
|
-
cross[p] = {'xml': x, 'docx': v}
|
|
273
|
-
if x:
|
|
274
|
-
residue[p] = x
|
|
275
|
-
if v > x:
|
|
276
|
-
inconsistent.append(p)
|
|
277
|
-
|
|
278
|
-
title_hits = full.count(title) if title else None
|
|
279
|
-
title_ok = True
|
|
280
|
-
if title:
|
|
281
|
-
title_ok = (title_hits == expect_title_count) if expect_title_count else (title_hits >= 1)
|
|
282
|
-
|
|
283
|
-
doubled = bool(title and (title + title) in full)
|
|
284
|
-
|
|
285
|
-
d = docx.Document(path)
|
|
286
|
-
struct = [{'index': i, 'rows': len(t.rows), 'cols': len(t.columns)}
|
|
287
|
-
for i, t in enumerate(d.tables)]
|
|
288
|
-
zero_rows = []
|
|
289
|
-
for i, t in enumerate(d.tables):
|
|
290
|
-
for ri, r in enumerate(t.rows):
|
|
291
|
-
if len(r.cells) == 0:
|
|
292
|
-
zero_rows.append('T%dR%d' % (i, ri))
|
|
293
|
-
|
|
294
|
-
ok = (not residue) and (not inconsistent) and title_ok and (not doubled) and (not zero_rows)
|
|
295
|
-
|
|
296
|
-
return {
|
|
297
|
-
'ok': ok,
|
|
298
|
-
'residue': residue,
|
|
299
|
-
'cross_check': cross,
|
|
300
|
-
'inconsistent': inconsistent,
|
|
301
|
-
'title': title,
|
|
302
|
-
'title_hits': title_hits,
|
|
303
|
-
'title_ok': title_ok,
|
|
304
|
-
'title_doubled': doubled,
|
|
305
|
-
'tables': struct,
|
|
306
|
-
'zero_cell_rows': zero_rows,
|
|
307
|
-
}
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
# --------------------------------------------------------------------------
|
|
311
|
-
# 主流程
|
|
312
|
-
# --------------------------------------------------------------------------
|
|
313
|
-
def main():
|
|
314
|
-
ap = argparse.ArgumentParser(description='报价单 → 合同 docx 一体化填充')
|
|
315
|
-
ap.add_argument('--template', required=True, help='模板 docx 绝对路径')
|
|
316
|
-
ap.add_argument('--data', default=None, help='数据 JSON 绝对路径')
|
|
317
|
-
ap.add_argument('--out', default=None, help='输出 docx 绝对路径')
|
|
318
|
-
ap.add_argument('--scan-only', action='store_true', help='只输出占位符清单')
|
|
319
|
-
ap.add_argument('--dry-run', action='store_true', help='只填不存,用于确认行位')
|
|
320
|
-
ap.add_argument('--expect', action='append', default=None, help='追加占位模式')
|
|
321
|
-
ap.add_argument('--detail-table', type=int, default=None, help='明细表索引(0 基)')
|
|
322
|
-
ap.add_argument('--title-count', type=int, default=None,
|
|
323
|
-
help='合同名称期望出现次数;不传则只要求 >=1')
|
|
324
|
-
args = ap.parse_args()
|
|
325
|
-
|
|
326
|
-
patterns = list(PLACEHOLDER_PATTERNS)
|
|
327
|
-
if args.expect:
|
|
328
|
-
patterns.extend(args.expect)
|
|
329
|
-
|
|
330
|
-
if not os.path.isfile(args.template):
|
|
331
|
-
print(json.dumps({'ok': False, 'error': 'template_not_found',
|
|
332
|
-
'detail': args.template}, ensure_ascii=False))
|
|
333
|
-
return 2
|
|
334
|
-
|
|
335
|
-
try:
|
|
336
|
-
doc = docx.Document(args.template)
|
|
337
|
-
except Exception as exc: # noqa: BLE001
|
|
338
|
-
print(json.dumps({'ok': False, 'error': 'unreadable_docx', 'detail': str(exc)},
|
|
339
|
-
ensure_ascii=False))
|
|
340
|
-
return 2
|
|
341
|
-
|
|
342
|
-
# ---- 步骤 1:先扫描占位符清单(不做任何替换)----
|
|
343
|
-
hits = scan_placeholders(doc, patterns)
|
|
344
|
-
report = scan_report(hits)
|
|
345
|
-
|
|
346
|
-
if args.scan_only:
|
|
347
|
-
print(json.dumps({'ok': True, 'mode': 'scan_only', 'placeholders': report},
|
|
348
|
-
ensure_ascii=False, indent=2))
|
|
349
|
-
return 0
|
|
350
|
-
|
|
351
|
-
if not args.data or not args.out:
|
|
352
|
-
print(json.dumps({'ok': False, 'error': 'data_and_out_required'},
|
|
353
|
-
ensure_ascii=False))
|
|
354
|
-
return 2
|
|
355
|
-
|
|
356
|
-
with open(args.data, 'r', encoding='utf-8') as f:
|
|
357
|
-
data = json.load(f)
|
|
358
|
-
|
|
359
|
-
customer = data.get('customer', '')
|
|
360
|
-
our = data.get('our_company', '')
|
|
361
|
-
sign_date = data.get('sign_date', '')
|
|
362
|
-
sign_place = data.get('sign_place', '')
|
|
363
|
-
title = data.get('title', '')
|
|
364
|
-
|
|
365
|
-
warnings = []
|
|
366
|
-
|
|
367
|
-
# ---- 步骤 2:文本级替换(先标题,再通用占位;含去重)----
|
|
368
|
-
replaced = []
|
|
369
|
-
for p_el in iter_all_paragraphs(doc):
|
|
370
|
-
txt = para_text(p_el)
|
|
371
|
-
if not txt:
|
|
372
|
-
continue
|
|
373
|
-
new = txt
|
|
374
|
-
if title:
|
|
375
|
-
# 标题段落:含 xxx公司 且同时含「购买合同」字样的,整段设为 title
|
|
376
|
-
if ('xxx公司' in txt or 'XXX公司' in txt) and '购买合同' in txt:
|
|
377
|
-
new = fold_duplicate(title, title)
|
|
378
|
-
if new == txt:
|
|
379
|
-
new = txt.replace('xxx公司', customer).replace('XXX公司', customer)
|
|
380
|
-
new = new.replace('***有限公司', customer).replace('***', customer)
|
|
381
|
-
if title:
|
|
382
|
-
new = fold_duplicate(new, title)
|
|
383
|
-
if new != txt:
|
|
384
|
-
set_para_text(p_el, new)
|
|
385
|
-
replaced.append({'from': txt.strip()[:60], 'to': new.strip()[:60]})
|
|
386
|
-
|
|
387
|
-
# ---- 步骤 3:表格填充(按特征探测,找不到就跳过并告警)----
|
|
388
|
-
tables_filled = []
|
|
389
|
-
|
|
390
|
-
# 3.1 封面签署块(两列,含「甲方:」「签订时间:」)
|
|
391
|
-
ti, tb = find_table(doc, must_all=('甲方:',), must_any=('签订时间:',), min_rows=2)
|
|
392
|
-
if tb is not None and len(tb.columns) == 2:
|
|
393
|
-
set_cell(tb.rows[0].cells[1], customer)
|
|
394
|
-
for r in tb.rows:
|
|
395
|
-
k = r.cells[0].text.strip()
|
|
396
|
-
if k.startswith('乙方'):
|
|
397
|
-
set_cell(r.cells[1], our)
|
|
398
|
-
elif k.startswith('签订时间'):
|
|
399
|
-
set_cell(r.cells[1], sign_date)
|
|
400
|
-
elif k.startswith('签订地点') and sign_place:
|
|
401
|
-
set_cell(r.cells[1], sign_place)
|
|
402
|
-
tables_filled.append({'table': ti, 'role': 'cover'})
|
|
403
|
-
|
|
404
|
-
# 3.2 双方信息表 / 签署页(四列,含「甲方:」「乙方:」)
|
|
405
|
-
for table_index, tb2 in enumerate(doc.tables):
|
|
406
|
-
if len(tb2.columns) != 4:
|
|
407
|
-
continue
|
|
408
|
-
txt = table_text(tb2)
|
|
409
|
-
if '甲方:' not in txt or '乙方:' not in txt:
|
|
410
|
-
continue
|
|
411
|
-
set_cell(tb2.rows[0].cells[1], customer)
|
|
412
|
-
set_cell(tb2.rows[0].cells[3], our)
|
|
413
|
-
if '生效日期' in txt:
|
|
414
|
-
for r in tb2.rows:
|
|
415
|
-
if r.cells[0].text.strip().startswith('生效日期'):
|
|
416
|
-
set_cell(r.cells[1], sign_date)
|
|
417
|
-
set_cell(r.cells[3], sign_date)
|
|
418
|
-
tables_filled.append({'table': table_index, 'role': 'parties'})
|
|
419
|
-
|
|
420
|
-
# 3.3 合同标的总额表(含「编号」「内容」「价格」「折扣」「金额」)
|
|
421
|
-
ti, tb = find_table(doc, must_all=('编号', '内容', '价格', '折扣', '金额'), min_rows=3)
|
|
422
|
-
if tb is not None:
|
|
423
|
-
for r in tb.rows:
|
|
424
|
-
first = r.cells[0].text.strip()
|
|
425
|
-
joined = row_text(r)
|
|
426
|
-
if first == '总额' or '总额' in r.cells[0].text:
|
|
427
|
-
set_cell(r.cells[-1], money(data['grand_total']))
|
|
428
|
-
elif '产品费用' in joined:
|
|
429
|
-
set_cell(r.cells[-1], money(data['product_total']))
|
|
430
|
-
elif '服务费用' in joined and '产品费用' not in joined:
|
|
431
|
-
set_cell(r.cells[-1], money(data['service_total']))
|
|
432
|
-
tables_filled.append({'table': ti, 'role': 'total'})
|
|
433
|
-
|
|
434
|
-
# 3.4 明细表(6 列:编号/名称/单价/数量/折扣/金额)
|
|
435
|
-
detail_index = args.detail_table
|
|
436
|
-
if detail_index is None:
|
|
437
|
-
ti, tb = find_table(doc, must_all=('名称', '单价', '数量', '折扣', '金额'), min_rows=4)
|
|
438
|
-
detail_index = ti
|
|
439
|
-
|
|
440
|
-
detail_info = None
|
|
441
|
-
if detail_index is not None:
|
|
442
|
-
tb = doc.tables[detail_index]
|
|
443
|
-
rows = tb.rows
|
|
444
|
-
header_row = None
|
|
445
|
-
product_total_row = None
|
|
446
|
-
service_section_row = None
|
|
447
|
-
service_total_row = None
|
|
448
|
-
for ri, r in enumerate(rows):
|
|
449
|
-
joined = row_text(r)
|
|
450
|
-
cells = [c.text.strip() for c in r.cells]
|
|
451
|
-
uniq = set(cells)
|
|
452
|
-
if header_row is None and {'编号', '名称', '单价', '数量', '折扣', '金额'} <= uniq:
|
|
453
|
-
header_row = ri
|
|
454
|
-
continue
|
|
455
|
-
if header_row is None:
|
|
456
|
-
continue
|
|
457
|
-
if '产品费用' in joined and len(uniq) <= 2:
|
|
458
|
-
product_total_row = ri
|
|
459
|
-
elif re.match(r'^\d+\s*服务费用', cells[0]) and len(uniq) <= 2:
|
|
460
|
-
# 服务区分隔行(如「2服务费用」)先判,否则会被下面当成合计行
|
|
461
|
-
service_section_row = ri
|
|
462
|
-
elif '服务费用' in joined and len(uniq) <= 2:
|
|
463
|
-
service_total_row = ri
|
|
464
|
-
|
|
465
|
-
if header_row is None:
|
|
466
|
-
warnings.append('明细表未识别到表头行,跳过行操作以外的处理')
|
|
467
|
-
else:
|
|
468
|
-
p_items = data.get('product_items') or []
|
|
469
|
-
s_items = data.get('service_items') or []
|
|
470
|
-
|
|
471
|
-
# 产品明细区:header_row+1 ~ product_total_row-1
|
|
472
|
-
if product_total_row is not None:
|
|
473
|
-
have = product_total_row - header_row - 1
|
|
474
|
-
if have != len(p_items):
|
|
475
|
-
res = reshape_rows(tb, header_row + 1, len(p_items), have)
|
|
476
|
-
if not res['ok']:
|
|
477
|
-
warnings.append('产品明细行不足:模板 %d 行、需要 %d 行,未自动新增'
|
|
478
|
-
% (res['have'], res['need']))
|
|
479
|
-
# 压缩后重新定位服务区行号
|
|
480
|
-
rows = tb.rows
|
|
481
|
-
for ri, r in enumerate(rows):
|
|
482
|
-
joined = row_text(r)
|
|
483
|
-
cells = [c.text.strip() for c in r.cells]
|
|
484
|
-
uniq = set(cells)
|
|
485
|
-
if ri <= header_row:
|
|
486
|
-
continue
|
|
487
|
-
if '产品费用' in joined and len(uniq) <= 2:
|
|
488
|
-
product_total_row = ri
|
|
489
|
-
elif re.match(r'^\d+\s*服务费用', cells[0]) and len(uniq) <= 2:
|
|
490
|
-
service_section_row = ri
|
|
491
|
-
elif '服务费用' in joined and len(uniq) <= 2:
|
|
492
|
-
service_total_row = ri
|
|
493
|
-
|
|
494
|
-
# 服务明细区:service_section_row+1 ~ service_total_row-1
|
|
495
|
-
if service_section_row is not None and service_total_row is not None:
|
|
496
|
-
have_s = service_total_row - service_section_row - 1
|
|
497
|
-
if have_s != len(s_items):
|
|
498
|
-
res = reshape_rows(tb, service_section_row + 1, len(s_items), have_s)
|
|
499
|
-
if not res['ok']:
|
|
500
|
-
warnings.append('服务明细行不足:模板 %d 行、需要 %d 行,未自动新增'
|
|
501
|
-
% (res['have'], res['need']))
|
|
502
|
-
rows = tb.rows
|
|
503
|
-
for ri, r in enumerate(rows):
|
|
504
|
-
joined = row_text(r)
|
|
505
|
-
uniq = set(c for c in [x.text.strip() for x in r.cells])
|
|
506
|
-
if '服务费用' in joined and len(uniq) <= 2:
|
|
507
|
-
service_total_row = ri
|
|
508
|
-
elif re.match(r'^\d+\s*服务费用', r.cells[0].text.strip()):
|
|
509
|
-
service_section_row = ri
|
|
510
|
-
|
|
511
|
-
fill_detail_table(tb, data, header_row, 0, product_total_row,
|
|
512
|
-
service_section_row, service_total_row)
|
|
513
|
-
detail_info = {
|
|
514
|
-
'table': detail_index,
|
|
515
|
-
'header_row': header_row,
|
|
516
|
-
'product_total_row': product_total_row,
|
|
517
|
-
'service_section_row': service_section_row,
|
|
518
|
-
'service_total_row': service_total_row,
|
|
519
|
-
}
|
|
520
|
-
tables_filled.append({'table': detail_index, 'role': 'detail'})
|
|
521
|
-
else:
|
|
522
|
-
warnings.append('未识别到明细表,明细与合计未填')
|
|
523
|
-
|
|
524
|
-
# 3.5 付款计划表(含「付款比例」「付款金额」)
|
|
525
|
-
ti, tb = find_table(doc, must_all=('付款比例', '付款金额'), min_rows=2)
|
|
526
|
-
if tb is not None:
|
|
527
|
-
ratios = data.get('payment_ratios') or []
|
|
528
|
-
grand = float(data.get('grand_total') or 0)
|
|
529
|
-
for i, rt in enumerate(ratios):
|
|
530
|
-
if 1 + i >= len(tb.rows):
|
|
531
|
-
warnings.append('付款表行数少于比例数量,未追加行')
|
|
532
|
-
break
|
|
533
|
-
row = tb.rows[1 + i]
|
|
534
|
-
set_cell(row.cells[1], '{:.0f}%'.format(float(rt) * 100))
|
|
535
|
-
set_cell(row.cells[2], money(round(grand * float(rt))))
|
|
536
|
-
tables_filled.append({'table': ti, 'role': 'payment'})
|
|
537
|
-
|
|
538
|
-
if args.dry_run:
|
|
539
|
-
print(json.dumps({'ok': True, 'mode': 'dry_run', 'placeholders': report,
|
|
540
|
-
'replaced': len(replaced), 'tables': tables_filled,
|
|
541
|
-
'detail': detail_info, 'warnings': warnings},
|
|
542
|
-
ensure_ascii=False, indent=2))
|
|
543
|
-
return 0
|
|
544
|
-
|
|
545
|
-
# ---- 步骤 4:保存 ----
|
|
546
|
-
out_dir = os.path.dirname(os.path.abspath(args.out))
|
|
547
|
-
if out_dir and not os.path.isdir(out_dir):
|
|
548
|
-
os.makedirs(out_dir, exist_ok=True)
|
|
549
|
-
doc.save(args.out)
|
|
550
|
-
|
|
551
|
-
# ---- 步骤 5:回读校验 ----
|
|
552
|
-
check = validate(args.out, patterns, title, args.title_count)
|
|
553
|
-
|
|
554
|
-
result = {
|
|
555
|
-
'ok': check['ok'],
|
|
556
|
-
'out': os.path.abspath(args.out),
|
|
557
|
-
'template': os.path.abspath(args.template),
|
|
558
|
-
'placeholders_found': report,
|
|
559
|
-
'text_replaced': len(replaced),
|
|
560
|
-
'tables_filled': tables_filled,
|
|
561
|
-
'detail_rows': detail_info,
|
|
562
|
-
'warnings': warnings,
|
|
563
|
-
'validate': check,
|
|
564
|
-
'note': '通过:占位符 0 残留、标题唯一、表格结构完好' if check['ok']
|
|
565
|
-
else '不通过:见 validate.residue / title_doubled / zero_cell_rows',
|
|
566
|
-
}
|
|
567
|
-
print(json.dumps(result, ensure_ascii=False, indent=2))
|
|
568
|
-
return 0 if check['ok'] else 1
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
if __name__ == '__main__':
|
|
572
|
-
sys.exit(main())
|