audit-e2w 0.0.0-stage → 1.11.7

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 (94) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +152 -3
  3. package/cordis.patch.yml +3 -0
  4. package/dsh_plugins/audit-e2w/lib/engine.mjs +174 -0
  5. package/dsh_plugins/audit-e2w/lib/index.js +122 -0
  6. package/dsh_plugins/audit-e2w/lib/skill.js +42 -0
  7. package/excel_word/README.md +388 -0
  8. package/excel_word/qoder_engine.py +437 -0
  9. package/excel_word/requirements.txt +4 -0
  10. package/excel_word/wesync/__init__.py +19 -0
  11. package/excel_word/wesync/__main__.py +6 -0
  12. package/excel_word/wesync/ai/__init__.py +52 -0
  13. package/excel_word/wesync/ai/actions.py +369 -0
  14. package/excel_word/wesync/ai/client.py +340 -0
  15. package/excel_word/wesync/ai/config.py +291 -0
  16. package/excel_word/wesync/ai/docs.py +177 -0
  17. package/excel_word/wesync/ai/prompts.py +288 -0
  18. package/excel_word/wesync/ai/tasks/__init__.py +26 -0
  19. package/excel_word/wesync/ai/tasks/actions_task.py +97 -0
  20. package/excel_word/wesync/ai/tasks/combined.py +123 -0
  21. package/excel_word/wesync/ai/tasks/diff_note.py +61 -0
  22. package/excel_word/wesync/ai/tasks/headings.py +119 -0
  23. package/excel_word/wesync/ai/tasks/help_task.py +69 -0
  24. package/excel_word/wesync/ai/tasks/roles.py +128 -0
  25. package/excel_word/wesync/align.py +155 -0
  26. package/excel_word/wesync/api.py +1292 -0
  27. package/excel_word/wesync/backup_history.py +100 -0
  28. package/excel_word/wesync/changelog.py +58 -0
  29. package/excel_word/wesync/cli.py +191 -0
  30. package/excel_word/wesync/commands/__init__.py +8 -0
  31. package/excel_word/wesync/commands/blank_cmd.py +279 -0
  32. package/excel_word/wesync/commands/bookmark_cmd.py +146 -0
  33. package/excel_word/wesync/commands/clear_cmd.py +50 -0
  34. package/excel_word/wesync/commands/export_cmd.py +270 -0
  35. package/excel_word/wesync/commands/incremental_cmd.py +157 -0
  36. package/excel_word/wesync/commands/marks_cmd.py +160 -0
  37. package/excel_word/wesync/commands/placeholders_cmd.py +92 -0
  38. package/excel_word/wesync/commands/writeback_cmd.py +469 -0
  39. package/excel_word/wesync/config.py +97 -0
  40. package/excel_word/wesync/console.py +85 -0
  41. package/excel_word/wesync/docx_blank.py +156 -0
  42. package/excel_word/wesync/docx_bookmarks.py +294 -0
  43. package/excel_word/wesync/docx_columns.py +257 -0
  44. package/excel_word/wesync/docx_edit.py +77 -0
  45. package/excel_word/wesync/docx_grid.py +212 -0
  46. package/excel_word/wesync/docx_marks.py +399 -0
  47. package/excel_word/wesync/docx_meta.py +157 -0
  48. package/excel_word/wesync/docx_newtable.py +220 -0
  49. package/excel_word/wesync/docx_placeholders.py +200 -0
  50. package/excel_word/wesync/docx_rows.py +67 -0
  51. package/excel_word/wesync/errors.py +5 -0
  52. package/excel_word/wesync/excel_blocks.py +502 -0
  53. package/excel_word/wesync/excel_export.py +143 -0
  54. package/excel_word/wesync/excel_marks.py +265 -0
  55. package/excel_word/wesync/excel_totals.py +53 -0
  56. package/excel_word/wesync/fsops.py +219 -0
  57. package/excel_word/wesync/gui/__init__.py +53 -0
  58. package/excel_word/wesync/gui/__main__.py +6 -0
  59. package/excel_word/wesync/gui/app.py +613 -0
  60. package/excel_word/wesync/gui/manual.py +70 -0
  61. package/excel_word/wesync/gui/pages/__init__.py +80 -0
  62. package/excel_word/wesync/gui/pages/_page.py +211 -0
  63. package/excel_word/wesync/gui/pages/ai_page.py +854 -0
  64. package/excel_word/wesync/gui/pages/batch_page.py +456 -0
  65. package/excel_word/wesync/gui/pages/blank_page.py +530 -0
  66. package/excel_word/wesync/gui/pages/bookmark_page.py +97 -0
  67. package/excel_word/wesync/gui/pages/export_page.py +141 -0
  68. package/excel_word/wesync/gui/pages/feedback_page.py +196 -0
  69. package/excel_word/wesync/gui/pages/format_page.py +551 -0
  70. package/excel_word/wesync/gui/pages/help_page.py +158 -0
  71. package/excel_word/wesync/gui/pages/history_page.py +168 -0
  72. package/excel_word/wesync/gui/pages/marks_page.py +211 -0
  73. package/excel_word/wesync/gui/pages/settings_page.py +450 -0
  74. package/excel_word/wesync/gui/pages/writeback_page.py +473 -0
  75. package/excel_word/wesync/gui/resources.py +22 -0
  76. package/excel_word/wesync/gui/runner.py +90 -0
  77. package/excel_word/wesync/gui/store.py +50 -0
  78. package/excel_word/wesync/gui/theme.py +271 -0
  79. package/excel_word/wesync/gui/widgets/__init__.py +8 -0
  80. package/excel_word/wesync/gui/widgets/ai_config.py +362 -0
  81. package/excel_word/wesync/gui/widgets/cards.py +139 -0
  82. package/excel_word/wesync/gui/widgets/chips.py +565 -0
  83. package/excel_word/wesync/gui/widgets/filebar.py +58 -0
  84. package/excel_word/wesync/gui/widgets/logpane.py +126 -0
  85. package/excel_word/wesync/gui/widgets/nav.py +294 -0
  86. package/excel_word/wesync/gui/widgets/theme_choice.py +93 -0
  87. package/excel_word/wesync/report_format.py +1585 -0
  88. package/excel_word/wesync/settings.py +35 -0
  89. package/excel_word/wesync/sort_rules.py +293 -0
  90. package/excel_word/wesync/valuefmt.py +485 -0
  91. package/package.json +53 -6
  92. package/packaging//344/275/277/347/224/250/350/257/264/346/230/216.txt +247 -0
  93. package/qoder_plugins/audit-toolbox/README.md +159 -0
  94. package/qoder_plugins/audit-toolbox/catalog.mjs +265 -0
@@ -0,0 +1,1292 @@
1
+ """对外稳定接口:把参数打包后调用现有命令实现(供界面等程序调用)。
2
+
3
+ 命令行入口仍走 ``wesync.cli``,行为不变;界面只依赖本模块,
4
+ 这样以后调整命令行参数不会影响界面代码。
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import argparse
10
+ from pathlib import Path
11
+
12
+ from .commands.blank_cmd import cmd_blank_tables
13
+ from .commands.bookmark_cmd import cmd_bookmark, cmd_repair_links
14
+ from .commands.clear_cmd import cmd_clear_bookmarks
15
+ from .commands.export_cmd import cmd_export
16
+ from .commands.incremental_cmd import cmd_incremental_export
17
+ from .commands.marks_cmd import cmd_marks, cmd_marks_sync
18
+ from .commands.writeback_cmd import cmd_writeback
19
+ from .console import log
20
+ from .docx_blank import find_blank_tables
21
+ from .errors import SyncError
22
+ from .fsops import check_file_free, resolve_docx, resolve_xlsx, save_docx_xlsx_transaction, tmp_root
23
+
24
+
25
+ def _options(
26
+ docx: str | Path,
27
+ excel: str | Path | None,
28
+ dry_run: bool,
29
+ force: bool,
30
+ with_excel_links: bool,
31
+ backup: bool = True,
32
+ ) -> argparse.Namespace:
33
+ return argparse.Namespace(
34
+ docx=str(docx),
35
+ excel=None if excel is None else str(excel),
36
+ dry_run=bool(dry_run),
37
+ force=bool(force),
38
+ no_excel_links=not with_excel_links,
39
+ backup=bool(backup),
40
+ )
41
+
42
+
43
+ def workbook_path(docx: str | Path, excel: str | Path | None = None) -> Path:
44
+ """按工具规则计算工作簿路径(界面上显示用)。"""
45
+ return resolve_xlsx(Path(docx), None if excel is None else str(excel))
46
+
47
+
48
+ def run_export(
49
+ docx: str | Path,
50
+ excel: str | Path | None = None,
51
+ *,
52
+ dry_run: bool = False,
53
+ force: bool = False,
54
+ with_excel_links: bool = True,
55
+ totals_formula: bool = True,
56
+ backup: bool = True,
57
+ ) -> int:
58
+ """导出:Word → Excel(按当前 Word 重建工作簿)。
59
+
60
+ totals_formula=True 时,合计行(首列以「合计」开头)的数值列写 =SUM 求和公式,
61
+ 在 Excel 改明细后合计自动更新;置 False 则按原值导出。
62
+ backup=False 时覆盖前不备份原工作簿/Word 到 _backup(默认备份)。
63
+ """
64
+ options = _options(docx, excel, dry_run, force, with_excel_links, backup)
65
+ options.no_total_formulas = not totals_formula
66
+ return cmd_export(options)
67
+
68
+
69
+ def run_incremental_export(
70
+ docx: str | Path,
71
+ excel: str | Path | None = None,
72
+ *,
73
+ dry_run: bool = False,
74
+ force: bool = False,
75
+ with_excel_links: bool = True,
76
+ totals_formula: bool = True,
77
+ backup: bool = True,
78
+ ) -> int:
79
+ """只登记 Word 中尚未锚定的表格、标注与占位符,不改既有工作簿行。"""
80
+ options = _options(docx, excel, dry_run, force, with_excel_links, backup)
81
+ options.no_total_formulas = not totals_formula
82
+ return cmd_incremental_export(options)
83
+
84
+
85
+ def run_rejudge(
86
+ docx: str | Path,
87
+ excel: str | Path | None = None,
88
+ *,
89
+ dry_run: bool = False,
90
+ force: bool = False,
91
+ backup: bool = True,
92
+ ) -> int:
93
+ """按工作簿当前内容重新判定 B 列表头/✓/✕(只改标记,不改数据、不改 Word)。
94
+
95
+ 在 Excel 里增删改内容后点一下,标记自动跟上;「已删」行保持原样;
96
+ 旧布局工作簿没有标记列,会提示先重新导出。
97
+ """
98
+ from .commands.export_cmd import cmd_rejudge
99
+
100
+ return cmd_rejudge(_options(docx, excel, dry_run, force, True, backup))
101
+
102
+
103
+ def run_bookmark(
104
+ docx: str | Path,
105
+ excel: str | Path | None = None,
106
+ *,
107
+ dry_run: bool = False,
108
+ force: bool = False,
109
+ with_excel_links: bool = True,
110
+ backup: bool = True,
111
+ ) -> int:
112
+ """书签工具:迁移/补建书签并清理正文遗留文字,不改数据。"""
113
+ return cmd_bookmark(_options(docx, excel, dry_run, force, with_excel_links, backup))
114
+
115
+
116
+ def run_repair_links(
117
+ docx: str | Path,
118
+ excel: str | Path | None = None,
119
+ *,
120
+ dry_run: bool = False,
121
+ force: bool = False,
122
+ backup: bool = True,
123
+ ) -> int:
124
+ """文件移动或重命名后,修复 Excel 中表格与标注的 Word 定位链接。"""
125
+ return cmd_repair_links(_options(docx, excel, dry_run, force, True, backup))
126
+
127
+
128
+ def run_writeback(
129
+ docx: str | Path,
130
+ excel: str | Path | None = None,
131
+ *,
132
+ dry_run: bool = False,
133
+ force: bool = False,
134
+ backup: bool = True,
135
+ changelog: bool = False,
136
+ delete_empty_rows: bool = False,
137
+ table_zero: str = "excel",
138
+ ) -> int:
139
+ """回写:Excel → Word(含增删行、增删列)。
140
+
141
+ backup=False 时,写盘前不创建 _backup 备份(默认 True,保持原安全行为)。
142
+ changelog=True 时,回写后把逐格改动导出成 Excel 复核清单(保存在工作簿旁)。
143
+ delete_empty_rows=True 时,B 列标记为✕的行(导出时判定为空)连 Word 行一起删除,
144
+ Excel 该行保留为「已删」(改回✓可恢复);旧布局工作簿无标记列时不生效。
145
+ """
146
+ options = _options(docx, excel, dry_run, force, True, backup)
147
+ options.changelog = bool(changelog)
148
+ options.delete_empty_rows = bool(delete_empty_rows)
149
+ options.table_zero = table_zero
150
+ return cmd_writeback(options)
151
+
152
+
153
+ def scan_writeback_diff(docx: str | Path, excel: str | Path | None = None) -> list[dict]:
154
+ """只读差异比对:以预演方式跑回写逻辑,返回逐格改动记录(旧值→新值),不写任何文件。"""
155
+ options = _options(docx, excel, True, False, True)
156
+ options.recorder = []
157
+ cmd_writeback(options)
158
+ return options.recorder
159
+
160
+
161
+ def export_diff_report(docx: str | Path, excel: str | Path | None, records: list[dict]):
162
+ """把差异比对记录导出成 Excel 清单(保存在工作簿旁),返回路径;无记录返回 None。"""
163
+ from .changelog import export_changelog
164
+
165
+ docx_path = resolve_docx(str(docx))
166
+ xlsx_path = resolve_xlsx(docx_path, None if excel is None else str(excel))
167
+ return export_changelog(records, xlsx_path, docx_path.name)
168
+
169
+
170
+ def scan_backups(docx: str | Path, excel: str | Path | None = None) -> dict:
171
+ """只读列出报告 Word 与工作簿 Excel 各自的历史备份(按时间倒序),供回滚页分列展示。"""
172
+ from .backup_history import list_backups
173
+
174
+ docx_path = resolve_docx(str(docx))
175
+ xlsx_path = resolve_xlsx(docx_path, None if excel is None else str(excel))
176
+ return {
177
+ "word": list_backups(docx_path),
178
+ "excel": list_backups(xlsx_path),
179
+ "word_path": str(docx_path),
180
+ "excel_path": str(xlsx_path),
181
+ }
182
+
183
+
184
+ def run_restore_backup(backup: str | Path, target: str | Path, *, safety_backup: bool = True) -> None:
185
+ """用选中的历史备份恢复目标文件(按设置在恢复前备份现状)。"""
186
+ from .backup_history import restore_backup
187
+
188
+ restore_backup(backup, target, backup=safety_backup)
189
+
190
+
191
+ def run_marks(
192
+ docx: str | Path,
193
+ excel: str | Path | None = None,
194
+ *,
195
+ dry_run: bool = False,
196
+ force: bool = False,
197
+ backup: bool = True,
198
+ ) -> int:
199
+ """刷新工作簿里的「链接标注」工作表(高亮标记导出,不改 Word 文字)。"""
200
+ return cmd_marks(_options(docx, excel, dry_run, force, True, backup))
201
+
202
+
203
+ def run_marks_sync(
204
+ docx: str | Path,
205
+ excel: str | Path | None = None,
206
+ *,
207
+ dry_run: bool = False,
208
+ force: bool = False,
209
+ keep_highlight: bool = False,
210
+ backup: bool = True,
211
+ mark_zero: str = "excel",
212
+ _rows: list[dict] | None = None,
213
+ ) -> int:
214
+ """把「链接标注」工作表里填写的新内容/链接同步回 Word。"""
215
+ options = _options(docx, excel, dry_run, force, True, backup)
216
+ options.keep_highlight = bool(keep_highlight)
217
+ options.mark_zero = mark_zero
218
+ options.rows = _rows
219
+ return cmd_marks_sync(options)
220
+
221
+
222
+ def run_placeholder_export(
223
+ docx: str | Path,
224
+ excel: str | Path | None = None,
225
+ *,
226
+ dry_run: bool = False,
227
+ force: bool = False,
228
+ backup: bool = True,
229
+ ) -> int:
230
+ """按当前 Word 的 {字段名} 给工作簿「正文信息」表补齐骨架(保留已填值)。"""
231
+ from .commands.placeholders_cmd import cmd_placeholders
232
+
233
+ return cmd_placeholders(_options(docx, excel, dry_run, force, True, backup))
234
+
235
+
236
+ def run_placeholder_sync(
237
+ docx: str | Path,
238
+ excel: str | Path | None = None,
239
+ *,
240
+ dry_run: bool = False,
241
+ force: bool = False,
242
+ backup: bool = True,
243
+ placeholder_zero: str = "excel",
244
+ _values: dict[str, str] | None = None,
245
+ ) -> int:
246
+ """把「正文信息」表填好的值写回当前 Word 占位符;未填字段保留原样并警告。"""
247
+ from .commands.placeholders_cmd import cmd_placeholders_sync
248
+
249
+ options = _options(docx, excel, dry_run, force, True, backup)
250
+ options.values = _values
251
+ options.placeholder_zero = placeholder_zero
252
+ return cmd_placeholders_sync(options)
253
+
254
+
255
+ def run_sync_content(
256
+ docx: str | Path,
257
+ excel: str | Path | None = None,
258
+ *,
259
+ tables: bool = True,
260
+ marks: bool = False,
261
+ placeholders: bool = False,
262
+ keep_highlight: bool = True,
263
+ dry_run: bool = False,
264
+ force: bool = False,
265
+ backup: bool = False,
266
+ changelog: bool = False,
267
+ delete_empty_rows: bool = False,
268
+ table_zero: str = "excel",
269
+ mark_zero: str = "excel",
270
+ placeholder_zero: str = "excel",
271
+ ) -> dict:
272
+ """按勾选内容编排同步:表格 → 标注 → 占位符,返回各部分执行摘要。
273
+
274
+ 工作簿与 Word 各加载一次;所选修改应用到同一 Word 对象后,以单事务保存。
275
+ 勾选了标注/占位符但工作簿缺对应工作表(或标注无数据行、占位符没填任何值)时
276
+ 警告并跳过该部分内容(不静默);表格部分的备份/改动清单/删除✕行选项只作用于表格。
277
+ """
278
+ import docx as _docx
279
+ from openpyxl import load_workbook
280
+
281
+ from .fsops import load_workbook_for_save
282
+
283
+ from .console import warn
284
+ from .docx_placeholders import VALUES_SHEET, read_placeholder_values
285
+ from .excel_marks import SHEET_MARKS, parse_marks_rows
286
+ from .valuefmt import formula_map
287
+
288
+ if not (tables or marks or placeholders):
289
+ raise SyncError("请至少勾选一项同步内容(表格/标注/占位符)。")
290
+ docx_path = resolve_docx(str(docx))
291
+ xlsx = resolve_xlsx(docx_path, None if excel is None else str(excel))
292
+ if not xlsx.exists():
293
+ raise SyncError(f"找不到 Excel 文件:{xlsx}。请先执行 export 导出,或检查 excel 参数。")
294
+ if not dry_run:
295
+ check_file_free(docx_path, force)
296
+ check_file_free(xlsx, force)
297
+
298
+ wb = load_workbook_for_save(xlsx)
299
+ cached_wb = load_workbook(str(xlsx), data_only=True)
300
+ try:
301
+ marks_rows = None
302
+ placeholder_values = None
303
+ if marks:
304
+ if SHEET_MARKS not in wb.sheetnames:
305
+ marks_rows = []
306
+ else:
307
+ marks_rows = parse_marks_rows(
308
+ wb[SHEET_MARKS], cached_wb[SHEET_MARKS], zero_mode=mark_zero,
309
+ )
310
+ if not marks_rows:
311
+ warn(f"工作簿没有「{SHEET_MARKS}」数据行,跳过标注内容;请先在「标注与占位」页导出/刷新标注。")
312
+ marks = False
313
+ if placeholders:
314
+ placeholder_values = read_placeholder_values(
315
+ xlsx, zero_mode=placeholder_zero, wb=wb, cached_wb=cached_wb,
316
+ )
317
+ if not placeholder_values.filled_fields:
318
+ warn(f"工作簿没有「{VALUES_SHEET}」表或表里没填任何值,跳过占位符内容;请先在「标注与占位」页导出/刷新占位符并填值。")
319
+ placeholders = False
320
+
321
+ summary: dict = {}
322
+ doc = _docx.Document(str(docx_path)) if (tables or marks or placeholders) else None
323
+ table_result = {}
324
+ options = _options(docx_path, xlsx, dry_run, force, True, backup)
325
+ options._doc = doc
326
+ options._skip_save = True
327
+ if tables:
328
+ options.delete_empty_rows = delete_empty_rows
329
+ options.table_zero = table_zero
330
+ options.changelog = changelog
331
+ options._wb = wb
332
+ options._formula_cache = formula_map(xlsx, cached_wb=cached_wb)
333
+ from .commands.writeback_cmd import cmd_writeback
334
+
335
+ summary["tables"] = cmd_writeback(options)
336
+ table_result = getattr(options, "_writeback_result", {})
337
+ if marks:
338
+ from .commands.marks_cmd import cmd_marks_sync
339
+
340
+ options.keep_highlight = keep_highlight
341
+ options.mark_zero = mark_zero
342
+ options.rows = marks_rows
343
+ summary["marks"] = cmd_marks_sync(options)
344
+ if placeholders:
345
+ from .commands.placeholders_cmd import cmd_placeholders_sync
346
+
347
+ options.values = placeholder_values
348
+ options.placeholder_zero = placeholder_zero
349
+ summary["placeholders"] = cmd_placeholders_sync(options)
350
+ if dry_run:
351
+ return summary
352
+
353
+ docx_changed = bool(
354
+ table_result.get("docx_changed")
355
+ or getattr(options, "_marks_changed", False)
356
+ or getattr(options, "_placeholder_changed", False)
357
+ ) if (tables or marks or placeholders) else False
358
+ xlsx_changed = bool(table_result.get("xlsx_changed"))
359
+ backups = {}
360
+ if docx_changed or xlsx_changed:
361
+ backups = save_docx_xlsx_transaction(
362
+ docx_path=docx_path if docx_changed else None, doc=doc if docx_changed else None,
363
+ xlsx_path=xlsx if xlsx_changed else None, wb=wb if xlsx_changed else None,
364
+ backup=backup,
365
+ )
366
+ if table_result.get("xlsx_changed"):
367
+ xlsx_backup = backups.get(xlsx)
368
+ log(
369
+ f"[定位] 已保存 {xlsx.name}(元数据 {table_result['meta_changed']} 处、定义名称 {table_result['name_changes']} 处"
370
+ + (f"、✕行标记已删 {table_result['mark_changed']} 行" if table_result["mark_changed"] else "")
371
+ + f")" + (f"(原文件已备份:{xlsx_backup.name})" if xlsx_backup else "")
372
+ )
373
+ docx_backup = backups.get(docx_path)
374
+ backup_note = f"(原文件已备份:{docx_backup.name})" if docx_backup else ""
375
+ if table_result.get("docx_changed"):
376
+ log(f"[回写] 已保存 {docx_path.name}{backup_note}")
377
+ if getattr(options, "_marks_changed", False):
378
+ log(f"[标记] 已保存 {docx_path.name}{backup_note}")
379
+ if getattr(options, "_placeholder_changed", False):
380
+ log(f"[占位符] 已保存 {docx_path.name}{backup_note}")
381
+ if changelog and tables:
382
+ from .changelog import export_changelog
383
+
384
+ export_changelog(table_result.get("recorder", []), xlsx, docx_path.name)
385
+ return summary
386
+ finally:
387
+ wb.close()
388
+ if getattr(wb, "vba_archive", None):
389
+ wb.vba_archive.close()
390
+ cached_wb.close()
391
+
392
+
393
+ def run_clear_bookmarks(
394
+ docx: str | Path,
395
+ excel: str | Path | None = None,
396
+ *,
397
+ dry_run: bool = False,
398
+ force: bool = False,
399
+ backup: bool = True,
400
+ ) -> int:
401
+ """删除 Word 里所有本工具书签(CPAH_/TBL_/MRK_),保留 Word 自带书签。"""
402
+ return cmd_clear_bookmarks(_options(docx, None, dry_run, force, True, backup))
403
+
404
+
405
+ def scan_blank_tables(docx_path: str | Path) -> list[dict]:
406
+ """只读扫描:返回空白表候选清单(整表全空 / 仅表头有字),供界面展示勾选。"""
407
+ import docx as _docx
408
+
409
+ path = resolve_docx(str(docx_path))
410
+ return find_blank_tables(_docx.Document(str(path)))
411
+
412
+
413
+ def run_blank_tables(
414
+ docx: str | Path,
415
+ *,
416
+ dry_run: bool = False,
417
+ force: bool = False,
418
+ pick: str | None = None,
419
+ keep_caption: bool = False,
420
+ keep_caption_for: str | None = None,
421
+ reversible: bool = False,
422
+ excel: str | Path | None = None,
423
+ backup: bool = True,
424
+ ) -> int:
425
+ """删除空白表。pick 为候选编号(如 "1,3")或 "all";不给 pick 时只列候选不删除。
426
+
427
+ keep_caption=True 全部只删表格;keep_caption_for 指定保留标题的候选编号(如 "2")。
428
+ reversible=True 时可逆删除:Excel 表块保留并标记「已删除」,之后可恢复。
429
+ """
430
+ options = _options(docx, excel, dry_run, force, True)
431
+ options.pick = None if pick in (None, "all") else str(pick)
432
+ options.all = pick == "all"
433
+ options.keep_caption = bool(keep_caption)
434
+ options.keep_caption_for = keep_caption_for
435
+ options.reversible = bool(reversible)
436
+ options.backup = bool(backup)
437
+ return cmd_blank_tables(options)
438
+
439
+
440
+ def list_deleted_blocks(docx: str | Path, excel: str | Path | None = None) -> list[dict]:
441
+ """只读列出工作簿里「已可逆删除」的表块,供界面展示恢复清单。"""
442
+ from .config import DELETED_BOOKMARK
443
+
444
+ return [item for item in list_table_blocks(docx, excel) if item["bookmark"] == DELETED_BOOKMARK]
445
+
446
+
447
+ def run_restore_tables(
448
+ docx: str | Path,
449
+ excel: str | Path | None = None,
450
+ *,
451
+ pick: str = "all",
452
+ dry_run: bool = False,
453
+ force: bool = False,
454
+ backup: bool = True,
455
+ ) -> int:
456
+ """恢复已可逆删除的表。pick 为恢复清单编号(如 "1,3")或 "all"。"""
457
+ options = _options(docx, excel, dry_run, force, True, backup)
458
+ options.restore = str(pick)
459
+ return cmd_blank_tables(options)
460
+
461
+
462
+ def list_table_blocks(docx: str | Path, excel: str | Path | None = None) -> list[dict]:
463
+ """只读列出工作簿里的表块(编号、表名、书签标记),供界面选择插入位置/恢复清单。"""
464
+ from .fsops import load_workbook_for_save as load_workbook
465
+
466
+ from .config import SHEET_NAME, SHEET_NEW_TABLES
467
+ from .excel_blocks import parse_blocks
468
+
469
+ docx_path = resolve_docx(str(docx))
470
+ xlsx_path = resolve_xlsx(docx_path, None if excel is None else str(excel))
471
+ if not xlsx_path.exists():
472
+ return []
473
+ wb = load_workbook(str(xlsx_path))
474
+ order, blocks = parse_blocks(wb[SHEET_NAME])
475
+ if SHEET_NEW_TABLES in wb.sheetnames:
476
+ extra_order, extra_blocks = parse_blocks(wb[SHEET_NEW_TABLES])
477
+ order.extend(extra_order)
478
+ blocks.update(extra_blocks)
479
+ result = []
480
+ for code in order:
481
+ block = blocks[code]
482
+ name = (block.get("meta", {}).get("name") or "").strip()
483
+ result.append(
484
+ {
485
+ "code": code,
486
+ "name": name,
487
+ "bookmark": block.get("bookmark", ""),
488
+ "nrows": len(block["grid_rows"]),
489
+ "ncols": block["ncols"],
490
+ "restore_after": block.get("meta", {}).get("restore_after", ""),
491
+ }
492
+ )
493
+ return result
494
+
495
+
496
+ def _load_blocks(docx, excel):
497
+ from .fsops import load_workbook_for_save as load_workbook
498
+
499
+ from .config import SHEET_NAME, SHEET_NEW_TABLES
500
+ from .excel_blocks import parse_blocks
501
+
502
+ docx_path = resolve_docx(str(docx))
503
+ xlsx_path = resolve_xlsx(docx_path, None if excel is None else str(excel))
504
+ if not xlsx_path.exists():
505
+ raise SyncError(f"找不到工作簿:{xlsx_path}\n请先执行「导出表格到 Excel」生成工作簿。")
506
+ wb = load_workbook(str(xlsx_path))
507
+ if SHEET_NAME not in wb.sheetnames:
508
+ raise SyncError(f"工作簿中找不到工作表“{SHEET_NAME}”,请确认该文件由本工具导出")
509
+ order, blocks = parse_blocks(wb[SHEET_NAME])
510
+ base_codes = set(order)
511
+ if SHEET_NEW_TABLES in wb.sheetnames:
512
+ extra_order, extra_blocks = parse_blocks(wb[SHEET_NEW_TABLES])
513
+ if set(extra_order) & base_codes:
514
+ raise SyncError("工作簿中「表格汇总」与「新增表格」存在重复表编号。")
515
+ order.extend(extra_order)
516
+ blocks.update(extra_blocks)
517
+ for code, block in blocks.items():
518
+ block["sheet_name"] = SHEET_NAME if code in base_codes else SHEET_NEW_TABLES
519
+ block["_ws"] = wb[block["sheet_name"]]
520
+ return xlsx_path, wb, wb[SHEET_NAME], order, blocks
521
+
522
+
523
+ def list_table_sorts(docx: str | Path, excel: str | Path | None = None) -> list[dict]:
524
+ """只读列出各表块的排序设置与可选金额列(表头文字),供界面展示。"""
525
+ from .config import DELETED_BOOKMARK, NEW_BOOKMARK
526
+ from .sort_rules import block_headers, parse_sort_setting
527
+
528
+ _, _, ws, order, blocks = _load_blocks(docx, excel)
529
+ result = []
530
+ for code in order:
531
+ block = blocks[code]
532
+ bookmark = block.get("bookmark", "")
533
+ if bookmark in (NEW_BOOKMARK, DELETED_BOOKMARK):
534
+ continue
535
+ setting = parse_sort_setting(block.get("meta", {}).get("sort", ""))
536
+ result.append(
537
+ {
538
+ "code": code,
539
+ "name": (block.get("meta", {}).get("name") or "").strip(),
540
+ "headers": block_headers(block["_ws"], block),
541
+ "sort_column": setting[0] if setting else "",
542
+ "descending": setting[1] if setting else True,
543
+ "has_sort": setting is not None,
544
+ }
545
+ )
546
+ return result
547
+
548
+
549
+ def set_table_sort(
550
+ docx: str | Path,
551
+ excel: str | Path | None = None,
552
+ *,
553
+ code: str,
554
+ column: str,
555
+ descending: bool = True,
556
+ backup: bool = True,
557
+ ) -> None:
558
+ """保存某表的排序设置(写进工作簿锚点行,随文件保存,同步时自动应用)。"""
559
+ from .sort_rules import write_block_sort
560
+
561
+ xlsx_path, wb, ws, order, blocks = _load_blocks(docx, excel)
562
+ if code not in blocks:
563
+ raise SyncError(f"工作簿中找不到表块 {code}")
564
+ check_file_free(xlsx_path, False)
565
+ write_block_sort(blocks[code]["_ws"], blocks[code], column, descending)
566
+ saved_backup = save_docx_xlsx_transaction(
567
+ xlsx_path=xlsx_path, wb=wb, backup=backup,
568
+ ).get(xlsx_path)
569
+ log(f"[排序] {code}:已保存排序设置「{column} {'降序' if descending else '升序'}」"
570
+ + (f"(原工作簿已备份:{saved_backup.name})" if saved_backup else ""))
571
+
572
+
573
+ def clear_table_sort(docx: str | Path, excel: str | Path | None = None, *, code: str, backup: bool = True) -> None:
574
+ """清除某表的排序设置。"""
575
+ from .sort_rules import clear_block_sort
576
+
577
+ xlsx_path, wb, ws, order, blocks = _load_blocks(docx, excel)
578
+ if code not in blocks:
579
+ raise SyncError(f"工作簿中找不到表块 {code}")
580
+ check_file_free(xlsx_path, False)
581
+ if clear_block_sort(blocks[code]["_ws"], blocks[code]):
582
+ saved_backup = save_docx_xlsx_transaction(
583
+ xlsx_path=xlsx_path, wb=wb, backup=backup,
584
+ ).get(xlsx_path)
585
+ log(f"[排序] {code}:已清除排序设置" + (f"(原工作簿已备份:{saved_backup.name})" if saved_backup else ""))
586
+ else:
587
+ log(f"[排序] {code}:本来就没有排序设置,无需清除")
588
+
589
+
590
+ def run_batch_writeback(
591
+ docx_list: list,
592
+ *,
593
+ dry_run: bool = False,
594
+ backup: bool = True,
595
+ force: bool = False,
596
+ contents: tuple = ("tables",),
597
+ keep_highlight: bool = True,
598
+ table_zero: str = "excel",
599
+ mark_zero: str = "excel",
600
+ placeholder_zero: str = "excel",
601
+ ) -> list[dict]:
602
+ """多报告批量同步:每份 Word 配同名工作簿逐个回写,单份失败不影响其他。
603
+
604
+ contents 为同步内容组合("tables"/"marks"/"placeholders" 任意子集)。
605
+ """
606
+ results: list[dict] = []
607
+ total = len(docx_list)
608
+ for i, docx in enumerate(docx_list, 1):
609
+ path = Path(docx)
610
+ log(f"===== [{i}/{total}] {path.name} =====")
611
+ item = {"docx": str(path), "excel": "", "status": "failed", "reason": ""}
612
+ results.append(item)
613
+ try:
614
+ xlsx = workbook_path(path)
615
+ item["excel"] = str(xlsx)
616
+ if not path.exists():
617
+ item.update(status="skipped", reason="Word 文件不存在")
618
+ log(f"[跳过] {path.name}:Word 文件不存在")
619
+ continue
620
+ if not xlsx.exists():
621
+ item.update(status="skipped", reason="找不到工作簿,请先导出")
622
+ log(f"[跳过] {path.name}:找不到工作簿 {xlsx.name},请先执行「导出表格到 Excel」")
623
+ continue
624
+ run_sync_content(
625
+ path,
626
+ tables="tables" in contents,
627
+ marks="marks" in contents,
628
+ placeholders="placeholders" in contents,
629
+ keep_highlight=keep_highlight,
630
+ dry_run=dry_run,
631
+ backup=backup,
632
+ force=force,
633
+ table_zero=table_zero, mark_zero=mark_zero, placeholder_zero=placeholder_zero,
634
+ )
635
+ item.update(status="ok", reason="预演完成" if dry_run else "同步完成")
636
+ except SyncError as exc:
637
+ item["reason"] = str(exc)
638
+ log(f"[失败] {path.name}:{exc}")
639
+ except Exception as exc:
640
+ item["reason"] = f"{type(exc).__name__}: {exc}"
641
+ log(f"[失败] {path.name}:{item['reason']}")
642
+ ok = sum(1 for r in results if r["status"] == "ok")
643
+ skipped = sum(1 for r in results if r["status"] == "skipped")
644
+ failed = sum(1 for r in results if r["status"] == "failed")
645
+ log(f"批量{'预演' if dry_run else '同步'}结束:成功 {ok} 份,跳过 {skipped} 份,失败 {failed} 份(共 {total} 份)。")
646
+ return results
647
+
648
+
649
+ def run_template_batch(
650
+ templates: list,
651
+ items: list[dict],
652
+ out_dir: str | Path,
653
+ *,
654
+ dry_run: bool = False,
655
+ contents: tuple = ("tables", "placeholders"),
656
+ keep_highlight: bool = True,
657
+ table_zero: str = "excel",
658
+ mark_zero: str = "excel",
659
+ placeholder_zero: str = "excel",
660
+ ) -> list[dict]:
661
+ """模板生成:每个 Excel 同步到指定模板的一份副本,产出若干新 Word。
662
+
663
+ templates 为模板路径清单(编号从 1 起);items 每项 {"excel": 路径, "template": 模板编号}。
664
+ 模板原件与源工作簿都不改动:同步在模板副本与工作簿临时副本上进行。
665
+ contents 为同步内容组合("tables"/"marks"/"placeholders" 任意子集)。
666
+ """
667
+ import shutil
668
+ import tempfile
669
+
670
+ import docx as _docx
671
+
672
+ from .docx_bookmarks import bookmark_names
673
+ from .docx_placeholders import apply_placeholders, read_placeholder_values, scan_placeholders
674
+ from .excel_blocks import read_recorded_bookmarks
675
+
676
+ if not contents:
677
+ raise SyncError("请至少勾选一项同步内容(表格/标注/占位符)。")
678
+ tpl_paths = [Path(t) for t in templates]
679
+ out_root = Path(out_dir)
680
+ if not dry_run:
681
+ out_root.mkdir(parents=True, exist_ok=True)
682
+ tpl_marks: dict[int, set] = {}
683
+ tpl_fields: dict[int, list[str]] = {}
684
+ results: list[dict] = []
685
+ total = len(items)
686
+ for i, item in enumerate(items, 1):
687
+ xlsx = Path(item["excel"])
688
+ tpl_no = int(item.get("template") or 0)
689
+ log(f"===== [{i}/{total}] {xlsx.name} =====")
690
+ record = {"excel": str(xlsx), "template": tpl_no, "output": "", "status": "failed", "reason": ""}
691
+ results.append(record)
692
+ try:
693
+ if not 1 <= tpl_no <= len(tpl_paths):
694
+ record.update(status="skipped", reason="未指定模板")
695
+ log(f"[跳过] {xlsx.name}:未指定所属模板,请在清单第三列选择模板")
696
+ continue
697
+ tpl = tpl_paths[tpl_no - 1]
698
+ if not tpl.exists():
699
+ record.update(status="skipped", reason=f"模板{tpl_no}不存在")
700
+ log(f"[跳过] {xlsx.name}:模板{tpl_no}({tpl.name})不存在")
701
+ continue
702
+ if not xlsx.exists():
703
+ record.update(status="skipped", reason="工作簿不存在")
704
+ log(f"[跳过] 工作簿不存在:{xlsx}")
705
+ continue
706
+ if tpl_no not in tpl_marks:
707
+ tpl_doc = _docx.Document(str(tpl))
708
+ tpl_marks[tpl_no] = set(bookmark_names(tpl_doc.element.body))
709
+ tpl_fields[tpl_no] = scan_placeholders(tpl_doc)
710
+ recorded = {b for b in read_recorded_bookmarks(xlsx).values() if b and b not in ("新增", "已删除")}
711
+ if tpl_marks[tpl_no] and not recorded & tpl_marks[tpl_no]:
712
+ record.update(status="skipped", reason=f"工作簿不是从模板{tpl_no}导出的(书签对不上)")
713
+ log(f"[跳过] {xlsx.name}:书签与模板{tpl_no}({tpl.name})对不上,请先用该模板执行「导出表格到 Excel」")
714
+ continue
715
+ fields = tpl_fields[tpl_no] if "placeholders" in contents else []
716
+ raw_values = read_placeholder_values(xlsx) if fields else {}
717
+ missing = [f for f in fields if f not in raw_values.filled_fields]
718
+ if missing:
719
+ record.update(status="skipped", reason="正文占位符未填:" + "、".join(missing))
720
+ log(f"[跳过] {xlsx.name}:正文占位符未填 {'、'.join('{'+f+'}' for f in missing)},"
721
+ f"请在该工作簿「正文信息」表填写后重试")
722
+ continue
723
+ values = read_placeholder_values(xlsx, zero_mode=placeholder_zero) if fields else {}
724
+ output = out_root / f"{tpl.stem}_{xlsx.stem}.docx"
725
+ seq = 2
726
+ while output.exists():
727
+ output = out_root / f"{tpl.stem}_{xlsx.stem}_{seq}.docx"
728
+ seq += 1
729
+ record["output"] = str(output)
730
+ if dry_run:
731
+ log(f"[模板·预演] 将生成 {output.name}(模板{tpl_no}:{tpl.name})")
732
+ for f in fields:
733
+ log(f"[占位符·预演] {{{f}}} → {values[f]}")
734
+ if "tables" in contents or "marks" in contents:
735
+ run_sync_content(
736
+ tpl, xlsx,
737
+ tables="tables" in contents,
738
+ marks="marks" in contents,
739
+ keep_highlight=keep_highlight,
740
+ table_zero=table_zero, mark_zero=mark_zero, placeholder_zero=placeholder_zero,
741
+ dry_run=True,
742
+ backup=False,
743
+ )
744
+ record.update(status="ok", reason="预演完成")
745
+ continue
746
+ shutil.copy2(tpl, output)
747
+ if fields:
748
+ out_doc = _docx.Document(str(output))
749
+ result = apply_placeholders(out_doc, values)
750
+ out_doc.save(str(output))
751
+ for f, v in result["replaced"]:
752
+ shown = v if len(v) <= 60 else v[:60] + "…"
753
+ log(f"[占位符] {{{f}}} → {shown}")
754
+ if "tables" in contents or "marks" in contents:
755
+ with tempfile.TemporaryDirectory(prefix="wesync_tpl_", dir=tmp_root()) as tmp:
756
+ tmp_xlsx = Path(tmp) / xlsx.name
757
+ shutil.copy2(xlsx, tmp_xlsx)
758
+ run_sync_content(
759
+ output, tmp_xlsx,
760
+ tables="tables" in contents,
761
+ marks="marks" in contents,
762
+ keep_highlight=keep_highlight,
763
+ table_zero=table_zero, mark_zero=mark_zero, placeholder_zero=placeholder_zero,
764
+ backup=False,
765
+ )
766
+ record.update(status="ok", reason="已生成")
767
+ log(f"[模板] 已生成 {output}")
768
+ except SyncError as exc:
769
+ record["reason"] = str(exc)
770
+ log(f"[失败] {xlsx.name}:{exc}")
771
+ except Exception as exc:
772
+ record["reason"] = f"{type(exc).__name__}: {exc}"
773
+ log(f"[失败] {xlsx.name}:{record['reason']}")
774
+ ok = sum(1 for r in results if r["status"] == "ok")
775
+ skipped = sum(1 for r in results if r["status"] == "skipped")
776
+ failed = sum(1 for r in results if r["status"] == "failed")
777
+ log(f"模板生成{'预演' if dry_run else ''}结束:成功 {ok} 份,跳过 {skipped} 份,失败 {failed} 份(共 {total} 份)。输出目录:{out_root}")
778
+ return results
779
+
780
+
781
+ def scan_blank_batch(docx_list: list) -> list[dict]:
782
+ """只读批量扫描空白表:每份报告返回候选清单或错误原因,供界面按报告分组展示。"""
783
+ results = []
784
+ for docx in docx_list:
785
+ path = Path(docx)
786
+ item = {"docx": str(path), "candidates": [], "error": ""}
787
+ try:
788
+ item["candidates"] = scan_blank_tables(path)
789
+ except SyncError as exc:
790
+ item["error"] = str(exc)
791
+ except Exception as exc:
792
+ item["error"] = f"{type(exc).__name__}: {exc}"
793
+ results.append(item)
794
+ return results
795
+
796
+
797
+ def run_blank_batch(items: list[dict], *, dry_run: bool = False, force: bool = False, backup: bool = True) -> list[dict]:
798
+ """批量删除空白表:items 每项 {"docx", "pick", "keep_caption_for", "reversible", "excel"}。
799
+
800
+ 逐份执行,单份失败不影响其他;口径与单文件删除完全一致。
801
+ """
802
+ results = []
803
+ total = len(items)
804
+ for i, item in enumerate(items, 1):
805
+ path = Path(item["docx"])
806
+ log(f"===== [{i}/{total}] {path.name} =====")
807
+ record = {"docx": str(path), "status": "failed", "reason": ""}
808
+ results.append(record)
809
+ try:
810
+ run_blank_tables(
811
+ path,
812
+ dry_run=dry_run,
813
+ force=force,
814
+ pick=item.get("pick"),
815
+ keep_caption_for=item.get("keep_caption_for"),
816
+ reversible=bool(item.get("reversible", True)),
817
+ excel=item.get("excel"),
818
+ backup=backup,
819
+ )
820
+ record.update(status="ok", reason="预演完成" if dry_run else "删除完成")
821
+ except SyncError as exc:
822
+ record["reason"] = str(exc)
823
+ log(f"[失败] {path.name}:{exc}")
824
+ except Exception as exc:
825
+ record["reason"] = f"{type(exc).__name__}: {exc}"
826
+ log(f"[失败] {path.name}:{record['reason']}")
827
+ ok = sum(1 for r in results if r["status"] == "ok")
828
+ failed = sum(1 for r in results if r["status"] == "failed")
829
+ log(f"批量删除空白表{'预演' if dry_run else ''}结束:成功 {ok} 份,失败 {failed} 份(共 {total} 份)。")
830
+ return results
831
+
832
+
833
+ def scan_report_format(
834
+ docx: str | Path,
835
+ template: str | Path | None = None,
836
+ *,
837
+ profile_name: str | None = None,
838
+ scope: dict | None = None,
839
+ heading_batch_id: str | None = None,
840
+ heading_levels: dict | None = None,
841
+ role_batch_id: str | None = None,
842
+ role_overrides: dict | None = None,
843
+ region_start_id: str | None = None,
844
+ ) -> dict:
845
+ """只读扫描格式调整方案:按样板或已存纯格式方案预演,不写任何文件。"""
846
+ from .report_format import scan_report_format as scan
847
+
848
+ return scan(
849
+ docx, template, profile_name=profile_name, scope=scope,
850
+ heading_batch_id=heading_batch_id, heading_levels=heading_levels,
851
+ role_batch_id=role_batch_id, role_overrides=role_overrides,
852
+ region_start_id=region_start_id,
853
+ )
854
+
855
+
856
+ def run_report_format(
857
+ docx: str | Path,
858
+ template: str | Path | None = None,
859
+ *,
860
+ output: str | Path | None = None,
861
+ dry_run: bool = False,
862
+ profile_name: str | None = None,
863
+ scope: dict | None = None,
864
+ heading_batch_id: str | None = None,
865
+ heading_levels: dict | None = None,
866
+ role_batch_id: str | None = None,
867
+ role_overrides: dict | None = None,
868
+ region_start_id: str | None = None,
869
+ ) -> dict:
870
+ """按样板或已存纯格式方案生成副本;默认不覆盖原报告,也不改写原文件。"""
871
+ from .report_format import run_report_format as run
872
+
873
+ return run(
874
+ docx, template, output=output, dry_run=dry_run, profile_name=profile_name, scope=scope,
875
+ heading_batch_id=heading_batch_id, heading_levels=heading_levels,
876
+ role_batch_id=role_batch_id, role_overrides=role_overrides,
877
+ region_start_id=region_start_id,
878
+ )
879
+
880
+
881
+ def scan_format_heading_candidates(docx: str | Path) -> dict:
882
+ """只返回本地筛出的候选标题、疑难角色和附注边界及有限上下文。"""
883
+ from .report_format import scan_heading_candidates
884
+
885
+ return scan_heading_candidates(docx)
886
+
887
+
888
+ def list_format_profiles() -> list[dict]:
889
+ """列出项目内保存的纯格式方案。"""
890
+ from .report_format import list_format_profiles as list_profiles
891
+
892
+ return list_profiles()
893
+
894
+
895
+ def load_format_profile(name: str):
896
+ """读取并校验指定的纯格式方案。"""
897
+ from .report_format import load_format_profile as load
898
+
899
+ return load(name)
900
+
901
+
902
+ def save_format_profile(template: str | Path, name: str, source: str | Path | None = None) -> dict:
903
+ """从样板提取并保存纯格式参数,不保存报告文字、表格内容或样板路径。"""
904
+ from .report_format import save_format_profile as save
905
+
906
+ return save(template, name, source)
907
+
908
+
909
+ def delete_format_profile(name: str) -> dict:
910
+ """删除指定的纯格式方案。"""
911
+ from .report_format import delete_format_profile as delete
912
+
913
+ return delete(name)
914
+
915
+
916
+ def scan_template_placeholders(docx: str | Path) -> list[str]:
917
+ """只读列出模板正文/页眉页脚里的占位符字段名({字段名} 写法)。"""
918
+ import docx as _docx
919
+
920
+ from .docx_placeholders import scan_placeholders
921
+
922
+ path = resolve_docx(str(docx))
923
+ return scan_placeholders(_docx.Document(str(path)))
924
+
925
+
926
+ def fill_placeholder_sheets(template: str | Path, workbooks: list, *, backup: bool = True) -> list[dict]:
927
+ """按模板占位符给各工作簿生成/补齐「正文信息」填写骨架(保留已填值)。"""
928
+ from .docx_placeholders import write_placeholder_sheet
929
+
930
+ fields = scan_template_placeholders(template)
931
+ results = []
932
+ for xlsx in workbooks:
933
+ path = Path(xlsx)
934
+ record = {"excel": str(path), "status": "failed", "reason": "", "added": []}
935
+ results.append(record)
936
+ try:
937
+ if not path.exists():
938
+ record.update(status="skipped", reason="工作簿不存在")
939
+ continue
940
+ added = write_placeholder_sheet(path, fields, backup=backup)
941
+ record.update(status="ok", added=added,
942
+ reason=f"新增 {len(added)} 个字段" if added else "字段已齐全")
943
+ log(f"[正文信息] {path.name}:" + (f"已加入字段 {'、'.join(added)},请在「正文信息」表填值" if added else "字段已齐全,无需改动"))
944
+ except SyncError as exc:
945
+ record["reason"] = str(exc)
946
+ log(f"[失败] {path.name}:{exc}")
947
+ if not fields:
948
+ log("模板正文里没有占位符({字段名} 写法),无需填写清单。")
949
+ return results
950
+
951
+
952
+ # ---------------------------------------------------------------- AI 助手(可选)
953
+ # 设计约定:以下函数全部为“只增不改”,未启用 AI 时不会被任何既有流程调用;
954
+ # 每个函数都在内部延迟导入 wesync.ai,保证关闭状态下不加载该包、不联网、不写盘。
955
+ # AI 只产出“建议数据”,写盘仍由上面各命令函数完成。
956
+
957
+
958
+ def ai_settings() -> dict:
959
+ """只读返回 AI 配置(密钥已脱敏),供界面展示。"""
960
+ from .ai.config import PRIVACY_LEVELS, PROVIDERS, load_ai_config, mask_key, resolve_api_key
961
+
962
+ config = load_ai_config()
963
+ key = resolve_api_key(config)
964
+ return {
965
+ "config": {**config, "api_key_enc": "", "api_key_mask": mask_key(key), "has_key": bool(key)},
966
+ "providers": {name: dict(item) for name, item in PROVIDERS.items()},
967
+ "privacy_levels": dict(PRIVACY_LEVELS),
968
+ }
969
+
970
+
971
+ def ai_save_settings(values: dict, *, api_key: str | None = None, repair: bool = False) -> dict:
972
+ """保存 AI 配置;api_key 传明文时立即加密落盘,传 None 表示不改动现有密钥。"""
973
+ from .ai.config import load_ai_config, save_ai_config, save_api_key
974
+
975
+ payload = dict(values)
976
+ if api_key is not None:
977
+ payload["api_key_enc"] = save_api_key(api_key)
978
+ elif "api_key_enc" not in payload:
979
+ payload["api_key_enc"] = load_ai_config().get("api_key_enc", "")
980
+ return save_ai_config(payload, repair=repair)
981
+
982
+
983
+ def ai_test_connection(values: dict | None = None, *, transport=None) -> dict:
984
+ """测试连通性:发一次最小请求,返回是否可用、模型名与耗时。不写任何文件。"""
985
+ from .ai.client import AiError, ChatClient
986
+ from .ai.config import load_ai_config, resolve_api_key
987
+
988
+ config = {**load_ai_config(), **(values or {})}
989
+ result = {"ok": False, "message": "", "model": "", "elapsed_ms": 0}
990
+ if not config.get("base_url") or not config.get("model"):
991
+ result["message"] = "请先填写接口地址和模型名。"
992
+ return result
993
+ try:
994
+ client = ChatClient(
995
+ base_url=str(config.get("base_url", "")),
996
+ model=str(config.get("model", "")),
997
+ api_key=resolve_api_key(config),
998
+ timeout=min(int(config.get("timeout_seconds", 60)), 30),
999
+ temperature=0.0,
1000
+ transport=transport,
1001
+ thinking=False,
1002
+ )
1003
+ reply = client.chat(
1004
+ [{"role": "user", "content": "回复两个字:就绪"}], max_tokens=16,
1005
+ )
1006
+ except AiError as exc:
1007
+ result["message"] = str(exc)
1008
+ return result
1009
+ except Exception as exc:
1010
+ result["message"] = f"{type(exc).__name__}: {exc}"
1011
+ return result
1012
+ result.update(ok=True, message="连接正常。", model=reply.model, elapsed_ms=reply.elapsed_ms)
1013
+ return result
1014
+
1015
+
1016
+ def ai_list_models(values: dict | None = None, *, api_key: str | None = None, transport=None) -> dict:
1017
+ """查询服务商当前可用的模型名,避免预设模型名过期。不写任何文件。"""
1018
+ from .ai.client import AiError, list_models
1019
+ from .ai.config import load_ai_config, resolve_api_key
1020
+
1021
+ config = {**load_ai_config(), **(values or {})}
1022
+ key = api_key if api_key is not None else resolve_api_key(config)
1023
+ result = {"ok": False, "models": [], "message": ""}
1024
+ if not config.get("base_url"):
1025
+ result["message"] = "请先填写接口地址。"
1026
+ return result
1027
+ try:
1028
+ result["models"] = list_models(
1029
+ str(config.get("base_url", "")),
1030
+ api_key=key,
1031
+ timeout=min(int(config.get("timeout_seconds", 60)), 30),
1032
+ transport=transport,
1033
+ )
1034
+ except AiError as exc:
1035
+ result["message"] = str(exc)
1036
+ return result
1037
+ except Exception as exc:
1038
+ result["message"] = f"{type(exc).__name__}: {exc}"
1039
+ return result
1040
+ if not result["models"]:
1041
+ result["message"] = "服务商没有返回任何模型名。"
1042
+ return result
1043
+ result["ok"] = True
1044
+ result["message"] = f"共 {len(result['models'])} 个可用模型。"
1045
+ return result
1046
+
1047
+
1048
+ def ai_suggest_combined(docx: str | Path, *, transport=None) -> dict:
1049
+ """只读:一次请求同时给出标题级别、疑难角色与附注边界(省一半往返与 token)。"""
1050
+ from .ai.config import load_ai_config
1051
+
1052
+ config = load_ai_config()
1053
+ empty = {
1054
+ "levels": {}, "roles": {}, "region_start_id": "", "batch_id": "",
1055
+ "adopted": False, "reason": "", "elapsed_ms": 0, "prompt_chars": 0,
1056
+ }
1057
+ if not config.get("enabled"):
1058
+ return {**empty, "reason": "AI 未启用。"}
1059
+ if config.get("privacy_level") == "off":
1060
+ return {**empty, "reason": "隐私级别为“禁用发送”。"}
1061
+ from .ai.tasks import suggest_combined as suggest
1062
+
1063
+ package = scan_format_heading_candidates(docx)
1064
+ return suggest(package, config=config, transport=transport)
1065
+
1066
+
1067
+ def ai_suggest_action(instruction: str, *, docx=None, excel=None, transport=None) -> dict:
1068
+ """只读:把自然语言指令解析成工具操作建议(不执行、不写盘)。"""
1069
+ from .ai.config import load_ai_config
1070
+
1071
+ empty = {
1072
+ "action": "", "params": {}, "summary": "", "warning": "", "ask": "",
1073
+ "remaining": [], "valid": False, "reason": "", "spec": {},
1074
+ }
1075
+ config = load_ai_config()
1076
+ if not config.get("enabled"):
1077
+ return {**empty, "reason": "AI 未启用。"}
1078
+ if config.get("privacy_level") == "off":
1079
+ return {**empty, "reason": "隐私级别为“禁用发送”。"}
1080
+ from .ai.tasks import suggest_action as suggest
1081
+
1082
+ context = {"docx": str(docx) if docx else "", "excel": str(excel) if excel else ""}
1083
+ return suggest(instruction, config=config, context=context, transport=transport)
1084
+
1085
+
1086
+ def ai_action_catalog() -> list[dict]:
1087
+ """只读:列出 AI 可建议的全部操作(供界面展示与测试)。"""
1088
+ from .ai.actions import catalog
1089
+
1090
+ return catalog()
1091
+
1092
+
1093
+ def ai_ask_help(question: str, *, transport=None) -> dict:
1094
+ """只读:依据内置使用说明回答问题;只发送本地检索到的片段。"""
1095
+ from .ai.config import load_ai_config
1096
+
1097
+ empty = {"answer": "", "snippets": [], "adopted": False, "reason": ""}
1098
+ config = load_ai_config()
1099
+ if not config.get("enabled"):
1100
+ return {**empty, "reason": "AI 未启用。"}
1101
+ if config.get("privacy_level") == "off":
1102
+ return {**empty, "reason": "隐私级别为“禁用发送”。"}
1103
+ from .ai.tasks import ask_help as ask
1104
+
1105
+ return ask(question, config=config, transport=transport)
1106
+
1107
+
1108
+ def ai_run_action(name: str, params: dict, *, dry_run: bool = True, allowed_picks=None) -> dict:
1109
+ """执行(或预演)一个已校验的操作。
1110
+
1111
+ dry_run=True 为默认:只预演不写盘。正式执行需调用方显式传 dry_run=False,
1112
+ 且必须由界面在用户确认后调用。参数会再过一次本地校验。
1113
+ 只读操作(blank-scan / diff / table-list 等)可直接运行,不涉及写盘。
1114
+ """
1115
+ from .ai.actions import ACTION_SPECS, READ_ACTIONS, ActionError, describe, validate_action
1116
+
1117
+ result = {"ok": False, "operation": name, "dry_run": dry_run, "message": "", "data": None}
1118
+ is_read = name in READ_ACTIONS
1119
+ spec = ACTION_SPECS.get(name)
1120
+ if spec is None and not is_read:
1121
+ result["message"] = f"不支持的操作:{name}(只允许工具已有的操作)"
1122
+ return result
1123
+ try:
1124
+ checked = validate_action(name, params, allow_read=True, allowed_picks=allowed_picks)
1125
+ except ActionError as exc:
1126
+ result["message"] = f"参数不合规:{exc}"
1127
+ return result
1128
+
1129
+ result["spec"] = describe(name)
1130
+ result["params"] = checked
1131
+ if is_read:
1132
+ try:
1133
+ data = _dispatch_read(name, checked)
1134
+ except SyncError as exc:
1135
+ result["message"] = str(exc)
1136
+ return result
1137
+ except Exception as exc:
1138
+ result["message"] = f"{type(exc).__name__}: {exc}"
1139
+ return result
1140
+ result.update(ok=True, data=data, message="只读操作已完成。")
1141
+ return result
1142
+
1143
+ if not spec.get("preview") and dry_run:
1144
+ result["message"] = (
1145
+ f"「{spec.get('label', name)}」不支持预演,需到「"
1146
+ f"{describe(name).get('page', '')}」页手工确认执行。"
1147
+ )
1148
+ return result
1149
+
1150
+ try:
1151
+ data = _dispatch_action(name, checked, dry_run=dry_run)
1152
+ except SyncError as exc:
1153
+ result["message"] = str(exc)
1154
+ return result
1155
+ except Exception as exc: # 任何未预期异常都不静默吞掉
1156
+ result["message"] = f"{type(exc).__name__}: {exc}"
1157
+ return result
1158
+
1159
+ result.update(ok=True, data=data)
1160
+ result["message"] = "预演完成,未写任何文件。" if dry_run else "已执行。"
1161
+ return result
1162
+
1163
+
1164
+ def _dispatch_read(name: str, params: dict) -> object:
1165
+ """只读操作的执行通道:全部调用既有的 scan_* 函数。"""
1166
+ docx = params.get("docx")
1167
+ excel = params.get("excel")
1168
+ if name == "blank-scan":
1169
+ return scan_blank_tables(docx)
1170
+ if name == "deleted-list":
1171
+ return list_deleted_blocks(docx, excel)
1172
+ if name == "diff":
1173
+ return scan_writeback_diff(docx, excel)
1174
+ if name == "table-list":
1175
+ return list_table_blocks(docx, excel)
1176
+ if name == "backup-list":
1177
+ return scan_backups(docx, excel)
1178
+ if name == "template-scan":
1179
+ return scan_template_placeholders(docx)
1180
+ if name == "format-scan":
1181
+ return scan_report_format(docx)
1182
+ raise SyncError(f"只读操作 {name} 尚未接入执行通道。")
1183
+
1184
+
1185
+ def _dispatch_action(name: str, params: dict, *, dry_run: bool) -> object:
1186
+ """把校验后的参数分发给已有的 api 函数(不新增写盘逻辑)。"""
1187
+ docx = params.get("docx")
1188
+ excel = params.get("excel")
1189
+ if name == "export":
1190
+ return run_export(docx, excel, dry_run=dry_run,
1191
+ backup=params.get("backup", True))
1192
+ if name == "incremental-export":
1193
+ return run_incremental_export(docx, excel, dry_run=dry_run,
1194
+ backup=params.get("backup", True))
1195
+ if name == "rejudge":
1196
+ return run_rejudge(docx, excel, dry_run=dry_run, backup=params.get("backup", True))
1197
+ if name == "writeback":
1198
+ return run_writeback(
1199
+ docx, excel, dry_run=dry_run, backup=params.get("backup", True),
1200
+ delete_empty_rows=params.get("deleteEmptyRows", False),
1201
+ changelog=params.get("changelog", False),
1202
+ )
1203
+ if name == "bookmark":
1204
+ return run_bookmark(docx, excel, dry_run=dry_run)
1205
+ if name == "clear-bookmarks":
1206
+ return run_clear_bookmarks(docx, dry_run=dry_run)
1207
+ if name == "marks":
1208
+ return run_marks(docx, excel, dry_run=dry_run)
1209
+ if name == "marks-sync":
1210
+ return run_marks_sync(docx, excel, dry_run=dry_run,
1211
+ keep_highlight=params.get("keepHighlight", True))
1212
+ if name == "placeholders":
1213
+ return run_placeholder_export(docx, excel, dry_run=dry_run)
1214
+ if name == "placeholders-sync":
1215
+ return run_placeholder_sync(docx, excel, dry_run=dry_run)
1216
+ if name == "blank-delete":
1217
+ return run_blank_tables(
1218
+ docx, dry_run=dry_run, pick=params.get("pick", ""),
1219
+ keep_caption=params.get("keepCaption", False),
1220
+ reversible=params.get("reversible", False), excel=excel,
1221
+ )
1222
+ if name == "restore-tables":
1223
+ return run_restore_tables(docx, excel, pick=params.get("pick", "all"), dry_run=dry_run)
1224
+ if name == "diff-export":
1225
+ records = scan_writeback_diff(docx, excel)
1226
+ return export_diff_report(docx, excel, records)
1227
+ if name == "batch-writeback":
1228
+ return run_batch_writeback(
1229
+ params.get("paths") or [], dry_run=dry_run,
1230
+ backup=params.get("backup", True),
1231
+ )
1232
+ if name == "template-batch":
1233
+ return run_template_batch(
1234
+ params.get("templates") or [], params.get("items") or [],
1235
+ params.get("outDir") or "", dry_run=dry_run,
1236
+ )
1237
+ if name == "format-apply":
1238
+ return run_report_format(
1239
+ docx, params.get("template"), output=params.get("output"),
1240
+ dry_run=dry_run, profile_name=params.get("profileName"),
1241
+ )
1242
+ if name == "backup-restore":
1243
+ if dry_run:
1244
+ return None
1245
+ return run_restore_backup(params.get("backupPath"), params.get("target"),
1246
+ safety_backup=True)
1247
+ raise SyncError(f"操作 {name} 尚未接入执行通道。")
1248
+
1249
+
1250
+ def ai_suggest_heading_levels(docx: str | Path, *, transport=None) -> dict:
1251
+ """只读:本地筛候选后交给模型判级,返回可交给 format-apply 的 headingLevels。"""
1252
+ from .ai.config import load_ai_config
1253
+
1254
+ config = load_ai_config()
1255
+ if not config.get("enabled"):
1256
+ return {"levels": {}, "batch_id": "", "adopted": False, "reason": "AI 未启用。"}
1257
+ if config.get("privacy_level") == "off":
1258
+ return {"levels": {}, "batch_id": "", "adopted": False, "reason": "隐私级别为“禁用发送”。"}
1259
+ from .ai.tasks import suggest_heading_levels as suggest
1260
+
1261
+ package = scan_format_heading_candidates(docx)
1262
+ return suggest(package, config=config, transport=transport)
1263
+
1264
+
1265
+ def ai_suggest_role_overrides(docx: str | Path, *, transport=None) -> dict:
1266
+ """只读:本地筛疑难角色与附注边界后交给模型判定。"""
1267
+ from .ai.config import load_ai_config
1268
+
1269
+ config = load_ai_config()
1270
+ if not config.get("enabled"):
1271
+ return {"roles": {}, "region_start_id": "", "batch_id": "", "adopted": False, "reason": "AI 未启用。"}
1272
+ if config.get("privacy_level") == "off":
1273
+ return {"roles": {}, "region_start_id": "", "batch_id": "", "adopted": False, "reason": "隐私级别为“禁用发送”。"}
1274
+ from .ai.tasks import suggest_role_overrides as suggest
1275
+
1276
+ package = scan_format_heading_candidates(docx)
1277
+ return suggest(package, config=config, transport=transport)
1278
+
1279
+
1280
+ def ai_suggest_diff_note(docx: str | Path, excel: str | Path | None = None, *, transport=None) -> dict:
1281
+ """只读:把差异清单写成中文复核说明,不写任何文件。"""
1282
+ from .ai.config import load_ai_config
1283
+
1284
+ config = load_ai_config()
1285
+ if not config.get("enabled"):
1286
+ return {"note": "", "adopted": False, "reason": "AI 未启用。", "count": 0}
1287
+ if config.get("privacy_level") == "off":
1288
+ return {"note": "", "adopted": False, "reason": "隐私级别为“禁用发送”。", "count": 0}
1289
+ from .ai.tasks import suggest_diff_note as suggest
1290
+
1291
+ records = scan_writeback_diff(docx, excel)
1292
+ return suggest(records, config=config, transport=transport)