weaver-work-cli 0.1.49 → 0.1.52

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.
Files changed (207) hide show
  1. package/README.md +1 -1
  2. package/dist/chunks/{attachment-content-MU2LPI5P.js → attachment-content-MBYYSQIX.js} +3 -3
  3. package/dist/chunks/{chunk-ZKEUGS2U.js → chunk-7UOXOGFL.js} +4 -4
  4. package/dist/chunks/{chunk-72MI3MBX.js → chunk-ATEXBEPD.js} +55 -15
  5. package/dist/chunks/{chunk-3NV2ETZR.js → chunk-D3TDNRFE.js} +8 -8
  6. package/dist/chunks/{chunk-6GWU63YF.js → chunk-DZOC77ZD.js} +1 -1
  7. package/dist/chunks/{chunk-K3BT54CU.js → chunk-IRMA3GVP.js} +1 -1
  8. package/dist/chunks/{chunk-3X7VOSBA.js → chunk-KLZ3ULQQ.js} +1 -1
  9. package/dist/chunks/{chunk-YLCYX7LE.js → chunk-KMRT7NAT.js} +18 -5
  10. package/dist/chunks/{chunk-NBEWUR7L.js → chunk-LALWNK6M.js} +167 -44
  11. package/dist/chunks/{chunk-BRRW7CWA.js → chunk-LM2H7SZI.js} +26 -26
  12. package/dist/chunks/{chunk-KV5SOWMS.js → chunk-LTRLF6MM.js} +4 -4
  13. package/dist/chunks/{chunk-D2QRZUW4.js → chunk-RPRFIG6I.js} +35 -28
  14. package/dist/chunks/{chunk-GEOMANP7.js → chunk-RWFRZSIP.js} +2 -2
  15. package/dist/chunks/{chunk-EJVA5ZVB.js → chunk-ZRHKGQRQ.js} +2 -2
  16. package/dist/chunks/{conflict-6347A7YK.js → conflict-D2HYKBMH.js} +2 -2
  17. package/dist/chunks/{contract-N6P2HIIE.js → contract-MFOFMM2J.js} +4284 -254
  18. package/dist/chunks/{create-flow-7WG7LVX5.js → create-flow-7ZATJVTM.js} +6 -6
  19. package/dist/chunks/{data-QO7QWOIV.js → data-WK5CQXNF.js} +17 -32
  20. package/dist/chunks/{env-LHRKSLG6.js → env-5DO4YENS.js} +2 -2
  21. package/dist/chunks/{factory-2H7Z4RWJ.js → factory-3M7D7WJC.js} +1 -1
  22. package/dist/chunks/{fna-ZVB2IILI.js → fna-ECOYBQYL.js} +328 -5
  23. package/dist/chunks/{group-chat-EW6PNDDT.js → group-chat-B2HT5NEO.js} +3 -3
  24. package/dist/chunks/{im-3RCNL5GT.js → im-TN2JYVGJ.js} +2 -2
  25. package/dist/chunks/{invoice-FXWH5GPO.js → invoice-V7ZTITUO.js} +726 -206
  26. package/dist/chunks/{meeting-N2FQBHXI.js → meeting-HZOX3CBB.js} +10 -10
  27. package/dist/chunks/{msg-parse-4GSQ2WTO.js → msg-parse-FPFVPMYI.js} +5 -1
  28. package/dist/chunks/{reception-MYOKJULO.js → reception-QGPNTGHG.js} +98 -82
  29. package/dist/chunks/{recruit-stage-FKWS5UQF.js → recruit-stage-XCMVEQA2.js} +718 -131
  30. package/dist/chunks/{registry-BUTEDK3C.js → registry-E5RQJVWN.js} +2 -2
  31. package/dist/chunks/{registry-7VZ6YJUF.js → registry-KYPFFQIH.js} +1 -1
  32. package/dist/chunks/{registry-CKUVBS53.js → registry-SJHSBO5G.js} +10 -10
  33. package/dist/chunks/{room-recommend-MBCYENQ2.js → room-recommend-5AHR4YQV.js} +4 -4
  34. package/dist/chunks/{schedule-5IFMCXME.js → schedule-KZPJUPC2.js} +4 -4
  35. package/dist/chunks/smart-extract-IXHCZE4R.js +2846 -0
  36. package/dist/chunks/{workflow-2TRU2ZSP.js → workflow-UHKCZJMY.js} +1 -1
  37. package/dist/index.js +14 -9
  38. package/dist/shortcuts/contract/host.js +11 -0
  39. package/dist/shortcuts/contract/index.js +13 -0
  40. package/dist/shortcuts/contract/manifest.js +204 -0
  41. package/dist/shortcuts/contract/operations/card-action.js +585 -0
  42. package/dist/shortcuts/contract/operations/card-ebdf-list.js +315 -0
  43. package/dist/shortcuts/contract/operations/card-plan.js +327 -0
  44. package/dist/shortcuts/contract/operations/card-risk-report.js +565 -0
  45. package/dist/shortcuts/contract/operations/elements-build.js +714 -0
  46. package/dist/shortcuts/contract/operations/elements-spec.js +216 -0
  47. package/dist/shortcuts/contract/operations/first-screen.js +563 -0
  48. package/dist/shortcuts/contract/operations/flow.js +81 -25
  49. package/dist/shortcuts/contract/operations/modeltext.js +132 -0
  50. package/dist/shortcuts/contract/operations/op-resolver.js +22 -0
  51. package/dist/shortcuts/contract/operations/performance.js +58 -7
  52. package/dist/shortcuts/contract/operations/quote.js +410 -22
  53. package/dist/shortcuts/contract/operations/registry.js +22 -0
  54. package/dist/shortcuts/contract/operations/review.js +73 -58
  55. package/dist/shortcuts/contract/operations/save-recognize.js +151 -0
  56. package/dist/shortcuts/contract/operations/summary-validate.js +293 -0
  57. package/dist/shortcuts/contract/operations/summary.js +4 -2
  58. package/dist/shortcuts/contract/operations/upload.js +48 -7
  59. package/dist/shortcuts/contract/prewarm-cache.js +90 -0
  60. package/dist/shortcuts/contract/prewarm.js +88 -0
  61. package/dist/shortcuts/contract/upload-cache.js +49 -4
  62. package/dist/shortcuts/data/index.js +1 -6
  63. package/dist/shortcuts/data/manifest.js +2 -2
  64. package/dist/shortcuts/data/operations/index.js +1 -1
  65. package/dist/shortcuts/data/operations/query.js +23 -46
  66. package/dist/shortcuts/fna/host.js +4 -2
  67. package/dist/shortcuts/fna/manifest.js +14 -5
  68. package/dist/shortcuts/fna/operations/audit.js +334 -0
  69. package/dist/shortcuts/fna/operations/registry.js +2 -0
  70. package/dist/shortcuts/im/operations/at-mention.js +6 -3
  71. package/dist/shortcuts/im/operations/msg-parse.js +35 -5
  72. package/dist/shortcuts/im/operations/msg-sync.js +3 -1
  73. package/dist/shortcuts/im/operations/msg-write.js +57 -9
  74. package/dist/shortcuts/index.js +5 -0
  75. package/dist/shortcuts/invoice/index.js +0 -12
  76. package/dist/shortcuts/invoice/manifest.js +201 -50
  77. package/dist/shortcuts/invoice/operations/registry.js +4 -2
  78. package/dist/shortcuts/invoice/operations/reim-relation.js +438 -0
  79. package/dist/shortcuts/invoice/operations/shared.js +3 -19
  80. package/dist/shortcuts/invoice/operations/upload-and-validate.js +109 -73
  81. package/dist/shortcuts/meeting/operations/from-group-chat.js +16 -2
  82. package/dist/shortcuts/reception/constants.js +3 -7
  83. package/dist/shortcuts/reception/operations/leads.js +30 -6
  84. package/dist/shortcuts/reception/operations/panels.js +3 -2
  85. package/dist/shortcuts/recruit-stage/operations/interview-arrange.js +4 -2
  86. package/dist/shortcuts/recruit-stage/operations/jd-create.js +6 -2
  87. package/dist/shortcuts/recruit-stage/operations/list.js +217 -1
  88. package/dist/shortcuts/recruit-stage/operations/resume-import.js +144 -158
  89. package/dist/shortcuts/recruit-stage/operations/search.js +348 -0
  90. package/dist/shortcuts/recruit-stage/shared.js +5 -0
  91. package/dist/shortcuts/recruit-stage/tag-lookup.js +136 -0
  92. package/dist/shortcuts/smart-extract/constants.js +79 -0
  93. package/dist/shortcuts/smart-extract/continuation.js +71 -0
  94. package/dist/shortcuts/smart-extract/errors.js +68 -0
  95. package/dist/shortcuts/smart-extract/host.js +191 -0
  96. package/dist/shortcuts/smart-extract/index.js +105 -0
  97. package/dist/shortcuts/smart-extract/ledger.js +70 -0
  98. package/dist/shortcuts/smart-extract/manifest.js +35 -0
  99. package/dist/shortcuts/smart-extract/operations/attachment.js +212 -0
  100. package/dist/shortcuts/smart-extract/operations/batch.js +67 -0
  101. package/dist/shortcuts/smart-extract/operations/config.js +118 -0
  102. package/dist/shortcuts/smart-extract/operations/fill.js +489 -0
  103. package/dist/shortcuts/smart-extract/operations/preview.js +174 -0
  104. package/dist/shortcuts/smart-extract/operations/registry.js +34 -0
  105. package/dist/shortcuts/smart-extract/operations/save.js +355 -0
  106. package/dist/shortcuts/smart-extract/operations/shared.js +191 -0
  107. package/dist/shortcuts/smart-extract/operations/structure.js +401 -0
  108. package/dist/shortcuts/smart-extract/operations/target.js +167 -0
  109. package/dist/shortcuts/smart-extract/operations/types.js +22 -0
  110. package/dist/shortcuts/smart-extract/operations/validate.js +408 -0
  111. package/dist/shortcuts/workflow/operations/read.js +77 -15
  112. package/dist/shortcuts/workflow/operations/todoSmartConvert/todoSmartConvert.collect.js +140 -24
  113. package/dist/shortcuts/workflow/operations/todoSmartConvert/todoSmartConvert.core.js +42 -14
  114. package/dist/shortcuts/workflow/operations/todoSmartConvert/todoSmartConvert.js +4 -6
  115. package/docs/SKILL.md +1 -1
  116. package/docs/_catalog.md +4 -1
  117. package/docs/agent-invoice.md +5 -7
  118. package/docs/data.md +5 -1
  119. package/docs/fna.md +24 -4
  120. package/docs/invoice.md +7 -5
  121. package/docs/smart-extract.md +156 -0
  122. package/package.json +1 -1
  123. package/skill-template/business-info.json +21 -1
  124. package/skill-template/domains/qiyecheng.md +6 -2
  125. package/skill-template/domains/smart-extract.md +16 -0
  126. package/skill-template/domains/yepiaotong.md +2 -2
  127. package/skills/weaver-e10-data/references/scene-and-misc.md +4 -3
  128. package/skills/weaver-e10-jinchengda/SKILL.md +159 -11
  129. package/skills/weaver-e10-jinchengda/references/contract-action-card.md +13 -8
  130. package/skills/weaver-e10-jinchengda/references/contract-action-engine.md +5 -4
  131. package/skills/weaver-e10-jinchengda/references/contract-clause-library-crud.md +44 -2
  132. package/skills/weaver-e10-jinchengda/references/contract-command-index.md +2 -2
  133. package/skills/weaver-e10-jinchengda/references/contract-element-save-record.md +220 -0
  134. package/skills/weaver-e10-jinchengda/references/contract-field-extract-new-customer.md +68 -33
  135. package/skills/weaver-e10-jinchengda/references/contract-field-extract-other-flows.md +26 -15
  136. package/skills/weaver-e10-jinchengda/references/contract-flow-launch.md +1 -1
  137. package/skills/weaver-e10-jinchengda/references/contract-modeltext-library.md +128 -0
  138. package/skills/weaver-e10-jinchengda/references/contract-multi-file.md +90 -0
  139. package/skills/weaver-e10-jinchengda/references/contract-performance-query.md +96 -2
  140. package/skills/weaver-e10-jinchengda/references/contract-quote-to-contract.md +167 -5
  141. package/skills/weaver-e10-jinchengda/scripts/contract_first_screen.py +200 -0
  142. package/skills/weaver-e10-jinchengda/scripts/fill_contract_from_quote.py +572 -0
  143. package/skills/weaver-e10-jinchengda/scripts/fill_plan.py +997 -0
  144. package/skills/weaver-e10-jinchengda/scripts/quote_screen.py +560 -0
  145. package/skills/weaver-e10-jinchengda/scripts/triage_contract.py +894 -0
  146. package/skills/weaver-e10-jinchengda/scripts/validate_action_card.py +93 -0
  147. package/skills/weaver-e10-jinchengda/scripts/verify_docx_placeholders.py +118 -0
  148. package/skills/weaver-e10-qiyecheng/SKILL.md +58 -7
  149. package/skills/weaver-e10-qiyecheng/references/ai-check-audit.md +118 -0
  150. package/skills/weaver-e10-qiyecheng/references/budget.md +14 -0
  151. package/skills/weaver-e10-qiyecheng/references/catalog.md +42 -3
  152. package/skills/weaver-e10-qiyecheng/references/expense-center.md +8 -0
  153. package/skills/weaver-e10-qiyecheng/references/expense-chart.md +9 -0
  154. package/skills/weaver-e10-qiyecheng/references/invoice-writeoff.md +13 -0
  155. package/skills/weaver-e10-qiyecheng/references/loan-management.md +14 -0
  156. package/skills/weaver-e10-qiyecheng/references/self-hosted-mode.md +239 -0
  157. package/skills/weaver-e10-qiyecheng/references/source-manifest.json +153 -40
  158. package/skills/weaver-e10-reception-flow/SKILL.md +43 -6
  159. package/skills/weaver-e10-reception-flow/references/guide.md +1 -1
  160. package/skills/weaver-e10-recruit-stage/SKILL.md +62 -4
  161. package/skills/weaver-e10-recruit-stage/agents/openai.yaml +42 -8
  162. package/skills/weaver-e10-recruit-stage/references/env-ziyong.md +79 -0
  163. package/skills/weaver-e10-recruit-stage/references/recruit-arrange-interview.md +11 -3
  164. package/skills/weaver-e10-recruit-stage/references/recruit-edit-interview-feedback.md +3 -2
  165. package/skills/weaver-e10-recruit-stage/references/recruit-interview-not-attended.md +153 -0
  166. package/skills/weaver-e10-recruit-stage/references/recruit-jd-create.md +7 -4
  167. package/skills/weaver-e10-recruit-stage/references/recruit-match-candidates.md +1 -1
  168. package/skills/weaver-e10-recruit-stage/references/recruit-my-positions.md +66 -0
  169. package/skills/weaver-e10-recruit-stage/references/recruit-output-links.md +156 -40
  170. package/skills/weaver-e10-recruit-stage/references/recruit-resume-import-batch.md +122 -0
  171. package/skills/weaver-e10-recruit-stage/references/recruit-resume-import.md +36 -8
  172. package/skills/weaver-e10-recruit-stage/references/recruit-search-by-tag.md +157 -0
  173. package/skills/weaver-e10-recruit-stage/references/recruit-utterance-glossary.md +35 -0
  174. package/skills/weaver-e10-smart-extract/SKILL.md +169 -0
  175. package/skills/weaver-e10-smart-extract/references/api-contract.md +71 -0
  176. package/skills/weaver-e10-smart-extract/references/result-format.md +102 -0
  177. package/skills/weaver-e10-smart-extract/references/troubleshooting.md +105 -0
  178. package/skills/weaver-e10-workflow/SKILL.md +2 -1
  179. package/skills/weaver-e10-workflow/references/todo-smart-convert.md +29 -6
  180. package/skills/weaver-e10-workflow/references/workflow-query.md +1 -1
  181. package/skills/weaver-e10-workflow/references/workflow-view.md +1 -1
  182. package/skills/weaver-e10-workflow/tools/todo-summary.cjs +162 -10
  183. package/skills/weaver-e10-yepiaotong/SKILL.md +53 -35
  184. package/skills/weaver-e10-yepiaotong/references/invoice-add.md +2 -0
  185. package/skills/weaver-e10-yepiaotong/references/invoice-file-upload.md +1 -1
  186. package/skills/weaver-e10-yepiaotong/references/invoice-import.md +19 -2
  187. package/skills/weaver-e10-yepiaotong/references/invoice-issuing-workflow.md +19 -32
  188. package/skills/weaver-e10-yepiaotong/references/invoice-ocr-preview.md +8 -2
  189. package/skills/weaver-e10-yepiaotong/references/invoice-reim-relation.md +407 -0
  190. package/skills/weaver-e10-yepiaotong/references/invoice-reim.md +18 -53
  191. package/skills/weaver-e10-yepiaotong/references/invoice-upload-and-validate.md +97 -39
  192. package/skills/weaver-e10-yepiaotong/references/reim-api-reference.md +96 -7
  193. package/skills/weaver-e10-yepiaotong/references/reim-examples.md +5 -38
  194. package/skills/weaver-e10-yepiaotong/references/reim-form-fill-rules.md +14 -14
  195. package/skills/weaver-e10-yepiaotong/references/reim-matching-rules.md +8 -4
  196. package/skills/weaver-e10-yepiaotong/references/reim-phone-subsidy-rules.md +139 -94
  197. package/skills/weaver-e10-yepiaotong/references/reim-workflow.md +131 -58
  198. package/skills/weaver-e10-yepiaotong/references/source-manifest.json +110 -43
  199. package/skills/weaver-e10-yimiaoban/SKILL.md +8 -6
  200. package/skills/weaver-e10-yimiaoban/references/msg-read.md +20 -0
  201. package/skills/weaver-e10-yimiaoban/references/msg-write.md +7 -0
  202. package/skills/weaver-e10-yimiaoban/references/source-manifest.json +18 -15
  203. package/dist/shortcuts/invoice/operations/validate-preview.js +0 -40
  204. package/skills/weaver-e10-jinchengda/scripts/plan_actions.py +0 -279
  205. package/skills/weaver-e10-jinchengda/scripts/render_action_card.py +0 -450
  206. package/skills/weaver-e10-jinchengda/scripts/render_risk_report.py +0 -358
  207. package/skills/weaver-e10-yepiaotong/references/invoice-validation-preview.md +0 -40
@@ -0,0 +1,572 @@
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())