audit-e2w 0.0.0-stage → 1.11.2

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 (72) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +147 -2
  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 +114 -0
  6. package/dsh_plugins/audit-e2w/lib/skill.js +41 -0
  7. package/excel_word/README.md +380 -0
  8. package/excel_word/qoder_engine.py +438 -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/align.py +154 -0
  13. package/excel_word/wesync/api.py +840 -0
  14. package/excel_word/wesync/backup_history.py +65 -0
  15. package/excel_word/wesync/changelog.py +58 -0
  16. package/excel_word/wesync/cli.py +173 -0
  17. package/excel_word/wesync/commands/__init__.py +8 -0
  18. package/excel_word/wesync/commands/blank_cmd.py +250 -0
  19. package/excel_word/wesync/commands/bookmark_cmd.py +115 -0
  20. package/excel_word/wesync/commands/clear_cmd.py +48 -0
  21. package/excel_word/wesync/commands/export_cmd.py +220 -0
  22. package/excel_word/wesync/commands/marks_cmd.py +152 -0
  23. package/excel_word/wesync/commands/placeholders_cmd.py +87 -0
  24. package/excel_word/wesync/commands/writeback_cmd.py +513 -0
  25. package/excel_word/wesync/config.py +96 -0
  26. package/excel_word/wesync/console.py +78 -0
  27. package/excel_word/wesync/docx_blank.py +156 -0
  28. package/excel_word/wesync/docx_bookmarks.py +287 -0
  29. package/excel_word/wesync/docx_columns.py +257 -0
  30. package/excel_word/wesync/docx_edit.py +77 -0
  31. package/excel_word/wesync/docx_grid.py +212 -0
  32. package/excel_word/wesync/docx_marks.py +291 -0
  33. package/excel_word/wesync/docx_meta.py +157 -0
  34. package/excel_word/wesync/docx_newtable.py +220 -0
  35. package/excel_word/wesync/docx_placeholders.py +161 -0
  36. package/excel_word/wesync/docx_rows.py +67 -0
  37. package/excel_word/wesync/errors.py +5 -0
  38. package/excel_word/wesync/excel_blocks.py +543 -0
  39. package/excel_word/wesync/excel_export.py +136 -0
  40. package/excel_word/wesync/excel_marks.py +193 -0
  41. package/excel_word/wesync/excel_totals.py +53 -0
  42. package/excel_word/wesync/fsops.py +214 -0
  43. package/excel_word/wesync/gui/__init__.py +34 -0
  44. package/excel_word/wesync/gui/__main__.py +6 -0
  45. package/excel_word/wesync/gui/app.py +399 -0
  46. package/excel_word/wesync/gui/manual.py +68 -0
  47. package/excel_word/wesync/gui/pages/__init__.py +31 -0
  48. package/excel_word/wesync/gui/pages/_page.py +89 -0
  49. package/excel_word/wesync/gui/pages/batch_page.py +423 -0
  50. package/excel_word/wesync/gui/pages/blank_page.py +465 -0
  51. package/excel_word/wesync/gui/pages/bookmark_page.py +37 -0
  52. package/excel_word/wesync/gui/pages/export_page.py +88 -0
  53. package/excel_word/wesync/gui/pages/format_page.py +429 -0
  54. package/excel_word/wesync/gui/pages/help_page.py +92 -0
  55. package/excel_word/wesync/gui/pages/history_page.py +145 -0
  56. package/excel_word/wesync/gui/pages/marks_page.py +178 -0
  57. package/excel_word/wesync/gui/pages/writeback_page.py +452 -0
  58. package/excel_word/wesync/gui/resources.py +22 -0
  59. package/excel_word/wesync/gui/runner.py +74 -0
  60. package/excel_word/wesync/gui/store.py +34 -0
  61. package/excel_word/wesync/gui/theme.py +100 -0
  62. package/excel_word/wesync/gui/widgets/__init__.py +8 -0
  63. package/excel_word/wesync/gui/widgets/cards.py +20 -0
  64. package/excel_word/wesync/gui/widgets/filebar.py +58 -0
  65. package/excel_word/wesync/gui/widgets/logpane.py +110 -0
  66. package/excel_word/wesync/gui/widgets/nav.py +39 -0
  67. package/excel_word/wesync/report_format.py +1577 -0
  68. package/excel_word/wesync/sort_rules.py +244 -0
  69. package/excel_word/wesync/valuefmt.py +462 -0
  70. package/package.json +49 -4
  71. package/qoder_plugins/audit-toolbox/README.md +156 -0
  72. package/qoder_plugins/audit-toolbox/catalog.mjs +265 -0
@@ -0,0 +1,840 @@
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
14
+ from .commands.clear_cmd import cmd_clear_bookmarks
15
+ from .commands.export_cmd import cmd_export
16
+ from .commands.marks_cmd import cmd_marks, cmd_marks_sync
17
+ from .commands.writeback_cmd import cmd_writeback
18
+ from .console import log
19
+ from .docx_blank import find_blank_tables
20
+ from .errors import SyncError
21
+ from .fsops import backup_file, check_file_free, resolve_docx, resolve_xlsx, tmp_root
22
+
23
+
24
+ def _options(
25
+ docx: str | Path,
26
+ excel: str | Path | None,
27
+ dry_run: bool,
28
+ force: bool,
29
+ with_excel_links: bool,
30
+ backup: bool = True,
31
+ ) -> argparse.Namespace:
32
+ return argparse.Namespace(
33
+ docx=str(docx),
34
+ excel=None if excel is None else str(excel),
35
+ dry_run=bool(dry_run),
36
+ force=bool(force),
37
+ no_excel_links=not with_excel_links,
38
+ backup=bool(backup),
39
+ )
40
+
41
+
42
+ def workbook_path(docx: str | Path, excel: str | Path | None = None) -> Path:
43
+ """按工具规则计算工作簿路径(界面上显示用)。"""
44
+ return resolve_xlsx(Path(docx), None if excel is None else str(excel))
45
+
46
+
47
+ def run_export(
48
+ docx: str | Path,
49
+ excel: str | Path | None = None,
50
+ *,
51
+ dry_run: bool = False,
52
+ force: bool = False,
53
+ with_excel_links: bool = True,
54
+ totals_formula: bool = True,
55
+ backup: bool = True,
56
+ ) -> int:
57
+ """导出:Word → Excel(按当前 Word 重建工作簿)。
58
+
59
+ totals_formula=True 时,合计行(首列以「合计」开头)的数值列写 =SUM 求和公式,
60
+ 在 Excel 改明细后合计自动更新;置 False 则按原值导出。
61
+ backup=False 时覆盖前不备份原工作簿/Word 到 _backup(默认备份)。
62
+ """
63
+ options = _options(docx, excel, dry_run, force, with_excel_links, backup)
64
+ options.no_total_formulas = not totals_formula
65
+ return cmd_export(options)
66
+
67
+
68
+ def run_rejudge(
69
+ docx: str | Path,
70
+ excel: str | Path | None = None,
71
+ *,
72
+ dry_run: bool = False,
73
+ force: bool = False,
74
+ backup: bool = True,
75
+ ) -> int:
76
+ """按工作簿当前内容重新判定 B 列表头/✓/✕(只改标记,不改数据、不改 Word)。
77
+
78
+ 在 Excel 里增删改内容后点一下,标记自动跟上;「已删」行保持原样;
79
+ 旧布局工作簿没有标记列,会提示先重新导出。
80
+ """
81
+ from .commands.export_cmd import cmd_rejudge
82
+
83
+ return cmd_rejudge(_options(docx, excel, dry_run, force, True, backup))
84
+
85
+
86
+ def run_bookmark(
87
+ docx: str | Path,
88
+ excel: str | Path | None = None,
89
+ *,
90
+ dry_run: bool = False,
91
+ force: bool = False,
92
+ with_excel_links: bool = True,
93
+ ) -> int:
94
+ """书签工具:迁移/补建书签并清理正文遗留文字,不改数据。"""
95
+ return cmd_bookmark(_options(docx, excel, dry_run, force, with_excel_links))
96
+
97
+
98
+ def run_writeback(
99
+ docx: str | Path,
100
+ excel: str | Path | None = None,
101
+ *,
102
+ dry_run: bool = False,
103
+ force: bool = False,
104
+ backup: bool = True,
105
+ changelog: bool = False,
106
+ delete_empty_rows: bool = False,
107
+ ) -> int:
108
+ """回写:Excel → Word(含增删行、增删列)。
109
+
110
+ backup=False 时,写盘前不创建 _backup 备份(默认 True,保持原安全行为)。
111
+ changelog=True 时,回写后把逐格改动导出成 Excel 复核清单(保存在工作簿旁)。
112
+ delete_empty_rows=True 时,B 列标记为✕的行(导出时判定为空)连 Word 行一起删除,
113
+ Excel 该行保留为「已删」(改回✓可恢复);旧布局工作簿无标记列时不生效。
114
+ """
115
+ options = _options(docx, excel, dry_run, force, True, backup)
116
+ options.changelog = bool(changelog)
117
+ options.delete_empty_rows = bool(delete_empty_rows)
118
+ return cmd_writeback(options)
119
+
120
+
121
+ def scan_writeback_diff(docx: str | Path, excel: str | Path | None = None) -> list[dict]:
122
+ """只读差异比对:以预演方式跑回写逻辑,返回逐格改动记录(旧值→新值),不写任何文件。"""
123
+ options = _options(docx, excel, True, False, True)
124
+ options.recorder = []
125
+ cmd_writeback(options)
126
+ return options.recorder
127
+
128
+
129
+ def export_diff_report(docx: str | Path, excel: str | Path | None, records: list[dict]):
130
+ """把差异比对记录导出成 Excel 清单(保存在工作簿旁),返回路径;无记录返回 None。"""
131
+ from .changelog import export_changelog
132
+
133
+ docx_path = resolve_docx(str(docx))
134
+ xlsx_path = resolve_xlsx(docx_path, None if excel is None else str(excel))
135
+ return export_changelog(records, xlsx_path, docx_path.name)
136
+
137
+
138
+ def scan_backups(docx: str | Path, excel: str | Path | None = None) -> dict:
139
+ """只读列出报告 Word 与工作簿 Excel 各自的历史备份(按时间倒序),供回滚页分列展示。"""
140
+ from .backup_history import list_backups
141
+
142
+ docx_path = resolve_docx(str(docx))
143
+ xlsx_path = resolve_xlsx(docx_path, None if excel is None else str(excel))
144
+ return {
145
+ "word": list_backups(docx_path),
146
+ "excel": list_backups(xlsx_path),
147
+ "word_path": str(docx_path),
148
+ "excel_path": str(xlsx_path),
149
+ }
150
+
151
+
152
+ def run_restore_backup(backup: str | Path, target: str | Path) -> None:
153
+ """用选中的历史备份恢复目标文件(恢复前自动备份现状,可再次回滚)。"""
154
+ from .backup_history import restore_backup
155
+
156
+ restore_backup(backup, target)
157
+
158
+
159
+ def run_marks(
160
+ docx: str | Path,
161
+ excel: str | Path | None = None,
162
+ *,
163
+ dry_run: bool = False,
164
+ force: bool = False,
165
+ ) -> int:
166
+ """刷新工作簿里的「链接标注」工作表(高亮标记导出,不改 Word 文字)。"""
167
+ return cmd_marks(_options(docx, excel, dry_run, force, True))
168
+
169
+
170
+ def run_marks_sync(
171
+ docx: str | Path,
172
+ excel: str | Path | None = None,
173
+ *,
174
+ dry_run: bool = False,
175
+ force: bool = False,
176
+ keep_highlight: bool = False,
177
+ _rows: list[dict] | None = None,
178
+ ) -> int:
179
+ """把「链接标注」工作表里填写的新内容/链接同步回 Word。"""
180
+ options = _options(docx, excel, dry_run, force, True)
181
+ options.keep_highlight = bool(keep_highlight)
182
+ options.rows = _rows
183
+ return cmd_marks_sync(options)
184
+
185
+
186
+ def run_placeholder_export(
187
+ docx: str | Path,
188
+ excel: str | Path | None = None,
189
+ *,
190
+ dry_run: bool = False,
191
+ force: bool = False,
192
+ ) -> int:
193
+ """按当前 Word 的 {字段名} 给工作簿「正文信息」表补齐骨架(保留已填值)。"""
194
+ from .commands.placeholders_cmd import cmd_placeholders
195
+
196
+ return cmd_placeholders(_options(docx, excel, dry_run, force, True))
197
+
198
+
199
+ def run_placeholder_sync(
200
+ docx: str | Path,
201
+ excel: str | Path | None = None,
202
+ *,
203
+ dry_run: bool = False,
204
+ force: bool = False,
205
+ _values: dict[str, str] | None = None,
206
+ ) -> int:
207
+ """把「正文信息」表填好的值写回当前 Word 占位符;未填字段保留原样并警告。"""
208
+ from .commands.placeholders_cmd import cmd_placeholders_sync
209
+
210
+ options = _options(docx, excel, dry_run, force, True)
211
+ options.values = _values
212
+ return cmd_placeholders_sync(options)
213
+
214
+
215
+ def run_sync_content(
216
+ docx: str | Path,
217
+ excel: str | Path | None = None,
218
+ *,
219
+ tables: bool = True,
220
+ marks: bool = False,
221
+ placeholders: bool = False,
222
+ keep_highlight: bool = True,
223
+ dry_run: bool = False,
224
+ force: bool = False,
225
+ backup: bool = False,
226
+ changelog: bool = False,
227
+ delete_empty_rows: bool = False,
228
+ ) -> dict:
229
+ """按勾选内容编排同步:表格 → 标注 → 占位符,返回各部分执行摘要。
230
+
231
+ 勾选了标注/占位符但工作簿缺对应工作表(或标注无数据行、占位符没填任何值)时
232
+ 警告并跳过该部分内容(不静默);表格部分的备份/改动清单/删除✕行选项只作用于表格。
233
+ 标注/占位符在表格保存前读取,避免公式缓存值因工作簿重存而丢失。
234
+ """
235
+ from .fsops import load_workbook_for_save as load_workbook
236
+
237
+ from .console import warn
238
+ from .docx_placeholders import VALUES_SHEET, read_placeholder_values
239
+ from .excel_marks import SHEET_MARKS, parse_marks_rows
240
+
241
+ if not (tables or marks or placeholders):
242
+ raise SyncError("请至少勾选一项同步内容(表格/标注/占位符)。")
243
+ xlsx = workbook_path(docx, excel)
244
+ marks_rows = None
245
+ placeholder_values = None
246
+ if (marks or placeholders) and xlsx.exists():
247
+ wb = load_workbook(str(xlsx))
248
+ if marks:
249
+ if SHEET_MARKS not in wb.sheetnames:
250
+ marks_rows = []
251
+ else:
252
+ cached_wb = load_workbook(str(xlsx), data_only=True)
253
+ marks_rows = parse_marks_rows(wb[SHEET_MARKS], cached_wb[SHEET_MARKS])
254
+ if not marks_rows:
255
+ warn(f"工作簿没有「{SHEET_MARKS}」数据行,跳过标注内容;请先在「标注与占位」页导出/刷新标注。")
256
+ marks = False
257
+ if placeholders:
258
+ placeholder_values = read_placeholder_values(xlsx)
259
+ if not placeholder_values:
260
+ warn(f"工作簿没有「{VALUES_SHEET}」表或表里没填任何值,跳过占位符内容;请先在「标注与占位」页导出/刷新占位符并填值。")
261
+ placeholders = False
262
+ summary: dict = {}
263
+ if tables:
264
+ summary["tables"] = run_writeback(
265
+ docx, excel, dry_run=dry_run, force=force, backup=backup,
266
+ changelog=changelog, delete_empty_rows=delete_empty_rows,
267
+ )
268
+ if marks:
269
+ summary["marks"] = run_marks_sync(
270
+ docx, excel, dry_run=dry_run, force=force, keep_highlight=keep_highlight, _rows=marks_rows
271
+ )
272
+ if placeholders:
273
+ summary["placeholders"] = run_placeholder_sync(
274
+ docx, excel, dry_run=dry_run, force=force, _values=placeholder_values
275
+ )
276
+ return summary
277
+
278
+
279
+ def run_clear_bookmarks(
280
+ docx: str | Path,
281
+ excel: str | Path | None = None,
282
+ *,
283
+ dry_run: bool = False,
284
+ force: bool = False,
285
+ ) -> int:
286
+ """删除 Word 里所有本工具书签(CPAH_/TBL_/MRK_),保留 Word 自带书签。"""
287
+ return cmd_clear_bookmarks(_options(docx, None, dry_run, force, True))
288
+
289
+
290
+ def scan_blank_tables(docx_path: str | Path) -> list[dict]:
291
+ """只读扫描:返回空白表候选清单(整表全空 / 仅表头有字),供界面展示勾选。"""
292
+ import docx as _docx
293
+
294
+ path = resolve_docx(str(docx_path))
295
+ return find_blank_tables(_docx.Document(str(path)))
296
+
297
+
298
+ def run_blank_tables(
299
+ docx: str | Path,
300
+ *,
301
+ dry_run: bool = False,
302
+ force: bool = False,
303
+ pick: str | None = None,
304
+ keep_caption: bool = False,
305
+ keep_caption_for: str | None = None,
306
+ reversible: bool = False,
307
+ excel: str | Path | None = None,
308
+ ) -> int:
309
+ """删除空白表。pick 为候选编号(如 "1,3")或 "all";不给 pick 时只列候选不删除。
310
+
311
+ keep_caption=True 全部只删表格;keep_caption_for 指定保留标题的候选编号(如 "2")。
312
+ reversible=True 时可逆删除:Excel 表块保留并标记「已删除」,之后可恢复。
313
+ """
314
+ options = _options(docx, excel, dry_run, force, True)
315
+ options.pick = None if pick in (None, "all") else str(pick)
316
+ options.all = pick == "all"
317
+ options.keep_caption = bool(keep_caption)
318
+ options.keep_caption_for = keep_caption_for
319
+ options.reversible = bool(reversible)
320
+ return cmd_blank_tables(options)
321
+
322
+
323
+ def list_deleted_blocks(docx: str | Path, excel: str | Path | None = None) -> list[dict]:
324
+ """只读列出工作簿里「已可逆删除」的表块,供界面展示恢复清单。"""
325
+ from .config import DELETED_BOOKMARK
326
+
327
+ return [item for item in list_table_blocks(docx, excel) if item["bookmark"] == DELETED_BOOKMARK]
328
+
329
+
330
+ def run_restore_tables(
331
+ docx: str | Path,
332
+ excel: str | Path | None = None,
333
+ *,
334
+ pick: str = "all",
335
+ dry_run: bool = False,
336
+ force: bool = False,
337
+ ) -> int:
338
+ """恢复已可逆删除的表。pick 为恢复清单编号(如 "1,3")或 "all"。"""
339
+ options = _options(docx, excel, dry_run, force, True)
340
+ options.restore = str(pick)
341
+ return cmd_blank_tables(options)
342
+
343
+
344
+ def list_table_blocks(docx: str | Path, excel: str | Path | None = None) -> list[dict]:
345
+ """只读列出工作簿里的表块(编号、表名、书签标记),供界面选择插入位置/恢复清单。"""
346
+ from .fsops import load_workbook_for_save as load_workbook
347
+
348
+ from .config import SHEET_NAME
349
+ from .excel_blocks import parse_blocks
350
+
351
+ docx_path = resolve_docx(str(docx))
352
+ xlsx_path = resolve_xlsx(docx_path, None if excel is None else str(excel))
353
+ if not xlsx_path.exists():
354
+ return []
355
+ wb = load_workbook(str(xlsx_path))
356
+ if SHEET_NAME not in wb.sheetnames:
357
+ return []
358
+ order, blocks = parse_blocks(wb[SHEET_NAME])
359
+ result = []
360
+ for code in order:
361
+ block = blocks[code]
362
+ name = (block.get("meta", {}).get("name") or "").strip()
363
+ result.append(
364
+ {
365
+ "code": code,
366
+ "name": name,
367
+ "bookmark": block.get("bookmark", ""),
368
+ "nrows": len(block["grid_rows"]),
369
+ "ncols": block["ncols"],
370
+ "restore_after": block.get("meta", {}).get("restore_after", ""),
371
+ }
372
+ )
373
+ return result
374
+
375
+
376
+ def run_append_table_block(
377
+ docx: str | Path,
378
+ excel: str | Path | None = None,
379
+ *,
380
+ name: str,
381
+ nrows: int,
382
+ ncols: int,
383
+ after: str | None = None,
384
+ ) -> str:
385
+ """在指定表块下面插入带「书签:新增」标记的新表块,返回表编号。
386
+
387
+ after 指定插到哪张表下面(如 "T02"),不指定时插到最后一张表下面;
388
+ 后续表块整体下移,全部表块按上下顺序重新编号。Word 建表位置与 Excel 一致。
389
+ 之后在 Excel 里填好内容,执行「同步到 Word」即会在 Word 里创建这张表。
390
+ """
391
+ from .fsops import load_workbook_for_save as load_workbook
392
+
393
+ from .excel_blocks import append_new_block
394
+
395
+ docx_path = resolve_docx(str(docx))
396
+ xlsx_path = resolve_xlsx(docx_path, None if excel is None else str(excel))
397
+ if not xlsx_path.exists():
398
+ raise SyncError(f"找不到工作簿:{xlsx_path}\n请先执行「导出表格到 Excel」生成工作簿。")
399
+ check_file_free(xlsx_path, False)
400
+ wb = load_workbook(str(xlsx_path))
401
+ code = append_new_block(wb, name, nrows, ncols, after=after)
402
+ backup = backup_file(xlsx_path)
403
+ wb.save(str(xlsx_path))
404
+ position = f",插在 {after} 下面" if after else ",插在最后一张表下面"
405
+ log(f"[新表] 已插入 {code}「{name.strip()}」({nrows}行×{ncols}列,书签:新增{position};全部表块已按顺序重新编号)"
406
+ + (f"(原工作簿已备份:{backup.name})" if backup else ""))
407
+ log("[新表] 请在 Excel 里填写该表块内容(首行为表头),再执行「同步到 Word」,新表会建在 Excel 里同一位置对应的 Word 表格之后。")
408
+ return code
409
+
410
+
411
+ def _load_blocks(docx, excel):
412
+ from .fsops import load_workbook_for_save as load_workbook
413
+
414
+ from .config import SHEET_NAME
415
+ from .excel_blocks import parse_blocks
416
+
417
+ docx_path = resolve_docx(str(docx))
418
+ xlsx_path = resolve_xlsx(docx_path, None if excel is None else str(excel))
419
+ if not xlsx_path.exists():
420
+ raise SyncError(f"找不到工作簿:{xlsx_path}\n请先执行「导出表格到 Excel」生成工作簿。")
421
+ wb = load_workbook(str(xlsx_path))
422
+ if SHEET_NAME not in wb.sheetnames:
423
+ raise SyncError(f"工作簿中找不到工作表“{SHEET_NAME}”,请确认该文件由本工具导出")
424
+ order, blocks = parse_blocks(wb[SHEET_NAME])
425
+ return xlsx_path, wb, wb[SHEET_NAME], order, blocks
426
+
427
+
428
+ def list_table_sorts(docx: str | Path, excel: str | Path | None = None) -> list[dict]:
429
+ """只读列出各表块的排序设置与可选金额列(表头文字),供界面展示。"""
430
+ from .config import DELETED_BOOKMARK, NEW_BOOKMARK
431
+ from .sort_rules import block_headers, parse_sort_setting
432
+
433
+ _, _, ws, order, blocks = _load_blocks(docx, excel)
434
+ result = []
435
+ for code in order:
436
+ block = blocks[code]
437
+ bookmark = block.get("bookmark", "")
438
+ if bookmark in (NEW_BOOKMARK, DELETED_BOOKMARK):
439
+ continue
440
+ setting = parse_sort_setting(block.get("meta", {}).get("sort", ""))
441
+ result.append(
442
+ {
443
+ "code": code,
444
+ "name": (block.get("meta", {}).get("name") or "").strip(),
445
+ "headers": block_headers(ws, block),
446
+ "sort_column": setting[0] if setting else "",
447
+ "descending": setting[1] if setting else True,
448
+ "has_sort": setting is not None,
449
+ }
450
+ )
451
+ return result
452
+
453
+
454
+ def set_table_sort(
455
+ docx: str | Path,
456
+ excel: str | Path | None = None,
457
+ *,
458
+ code: str,
459
+ column: str,
460
+ descending: bool = True,
461
+ ) -> None:
462
+ """保存某表的排序设置(写进工作簿锚点行,随文件保存,同步时自动应用)。"""
463
+ from .sort_rules import write_block_sort
464
+
465
+ xlsx_path, wb, ws, order, blocks = _load_blocks(docx, excel)
466
+ if code not in blocks:
467
+ raise SyncError(f"工作簿中找不到表块 {code}")
468
+ check_file_free(xlsx_path, False)
469
+ write_block_sort(ws, blocks[code], column, descending)
470
+ backup = backup_file(xlsx_path)
471
+ wb.save(str(xlsx_path))
472
+ log(f"[排序] {code}:已保存排序设置「{column} {'降序' if descending else '升序'}」"
473
+ + (f"(原工作簿已备份:{backup.name})" if backup else ""))
474
+
475
+
476
+ def clear_table_sort(docx: str | Path, excel: str | Path | None = None, *, code: str) -> None:
477
+ """清除某表的排序设置。"""
478
+ from .sort_rules import clear_block_sort
479
+
480
+ xlsx_path, wb, ws, order, blocks = _load_blocks(docx, excel)
481
+ if code not in blocks:
482
+ raise SyncError(f"工作簿中找不到表块 {code}")
483
+ check_file_free(xlsx_path, False)
484
+ if clear_block_sort(ws, blocks[code]):
485
+ backup = backup_file(xlsx_path)
486
+ wb.save(str(xlsx_path))
487
+ log(f"[排序] {code}:已清除排序设置" + (f"(原工作簿已备份:{backup.name})" if backup else ""))
488
+ else:
489
+ log(f"[排序] {code}:本来就没有排序设置,无需清除")
490
+
491
+
492
+ def run_batch_writeback(
493
+ docx_list: list,
494
+ *,
495
+ dry_run: bool = False,
496
+ backup: bool = True,
497
+ force: bool = False,
498
+ contents: tuple = ("tables",),
499
+ keep_highlight: bool = True,
500
+ ) -> list[dict]:
501
+ """多报告批量同步:每份 Word 配同名工作簿逐个回写,单份失败不影响其他。
502
+
503
+ contents 为同步内容组合("tables"/"marks"/"placeholders" 任意子集)。
504
+ """
505
+ results: list[dict] = []
506
+ total = len(docx_list)
507
+ for i, docx in enumerate(docx_list, 1):
508
+ path = Path(docx)
509
+ log(f"===== [{i}/{total}] {path.name} =====")
510
+ item = {"docx": str(path), "excel": "", "status": "failed", "reason": ""}
511
+ results.append(item)
512
+ try:
513
+ xlsx = workbook_path(path)
514
+ item["excel"] = str(xlsx)
515
+ if not path.exists():
516
+ item.update(status="skipped", reason="Word 文件不存在")
517
+ log(f"[跳过] {path.name}:Word 文件不存在")
518
+ continue
519
+ if not xlsx.exists():
520
+ item.update(status="skipped", reason="找不到工作簿,请先导出")
521
+ log(f"[跳过] {path.name}:找不到工作簿 {xlsx.name},请先执行「导出表格到 Excel」")
522
+ continue
523
+ run_sync_content(
524
+ path,
525
+ tables="tables" in contents,
526
+ marks="marks" in contents,
527
+ placeholders="placeholders" in contents,
528
+ keep_highlight=keep_highlight,
529
+ dry_run=dry_run,
530
+ backup=backup,
531
+ force=force,
532
+ )
533
+ item.update(status="ok", reason="预演完成" if dry_run else "同步完成")
534
+ except SyncError as exc:
535
+ item["reason"] = str(exc)
536
+ log(f"[失败] {path.name}:{exc}")
537
+ except Exception as exc:
538
+ item["reason"] = f"{type(exc).__name__}: {exc}"
539
+ log(f"[失败] {path.name}:{item['reason']}")
540
+ ok = sum(1 for r in results if r["status"] == "ok")
541
+ skipped = sum(1 for r in results if r["status"] == "skipped")
542
+ failed = sum(1 for r in results if r["status"] == "failed")
543
+ log(f"批量{'预演' if dry_run else '同步'}结束:成功 {ok} 份,跳过 {skipped} 份,失败 {failed} 份(共 {total} 份)。")
544
+ return results
545
+
546
+
547
+ def run_template_batch(
548
+ templates: list,
549
+ items: list[dict],
550
+ out_dir: str | Path,
551
+ *,
552
+ dry_run: bool = False,
553
+ contents: tuple = ("tables", "placeholders"),
554
+ keep_highlight: bool = True,
555
+ ) -> list[dict]:
556
+ """模板生成:每个 Excel 同步到指定模板的一份副本,产出若干新 Word。
557
+
558
+ templates 为模板路径清单(编号从 1 起);items 每项 {"excel": 路径, "template": 模板编号}。
559
+ 模板原件与源工作簿都不改动:同步在模板副本与工作簿临时副本上进行。
560
+ contents 为同步内容组合("tables"/"marks"/"placeholders" 任意子集)。
561
+ """
562
+ import shutil
563
+ import tempfile
564
+
565
+ import docx as _docx
566
+
567
+ from .docx_bookmarks import bookmark_names
568
+ from .docx_placeholders import apply_placeholders, read_placeholder_values, scan_placeholders
569
+ from .excel_blocks import read_recorded_bookmarks
570
+
571
+ if not contents:
572
+ raise SyncError("请至少勾选一项同步内容(表格/标注/占位符)。")
573
+ tpl_paths = [Path(t) for t in templates]
574
+ out_root = Path(out_dir)
575
+ if not dry_run:
576
+ out_root.mkdir(parents=True, exist_ok=True)
577
+ tpl_marks: dict[int, set] = {}
578
+ tpl_fields: dict[int, list[str]] = {}
579
+ results: list[dict] = []
580
+ total = len(items)
581
+ for i, item in enumerate(items, 1):
582
+ xlsx = Path(item["excel"])
583
+ tpl_no = int(item.get("template") or 0)
584
+ log(f"===== [{i}/{total}] {xlsx.name} =====")
585
+ record = {"excel": str(xlsx), "template": tpl_no, "output": "", "status": "failed", "reason": ""}
586
+ results.append(record)
587
+ try:
588
+ if not 1 <= tpl_no <= len(tpl_paths):
589
+ record.update(status="skipped", reason="未指定模板")
590
+ log(f"[跳过] {xlsx.name}:未指定所属模板,请在清单第三列选择模板")
591
+ continue
592
+ tpl = tpl_paths[tpl_no - 1]
593
+ if not tpl.exists():
594
+ record.update(status="skipped", reason=f"模板{tpl_no}不存在")
595
+ log(f"[跳过] {xlsx.name}:模板{tpl_no}({tpl.name})不存在")
596
+ continue
597
+ if not xlsx.exists():
598
+ record.update(status="skipped", reason="工作簿不存在")
599
+ log(f"[跳过] 工作簿不存在:{xlsx}")
600
+ continue
601
+ if tpl_no not in tpl_marks:
602
+ tpl_doc = _docx.Document(str(tpl))
603
+ tpl_marks[tpl_no] = set(bookmark_names(tpl_doc.element.body))
604
+ tpl_fields[tpl_no] = scan_placeholders(tpl_doc)
605
+ recorded = {b for b in read_recorded_bookmarks(xlsx).values() if b and b not in ("新增", "已删除")}
606
+ if tpl_marks[tpl_no] and not recorded & tpl_marks[tpl_no]:
607
+ record.update(status="skipped", reason=f"工作簿不是从模板{tpl_no}导出的(书签对不上)")
608
+ log(f"[跳过] {xlsx.name}:书签与模板{tpl_no}({tpl.name})对不上,请先用该模板执行「导出表格到 Excel」")
609
+ continue
610
+ fields = tpl_fields[tpl_no] if "placeholders" in contents else []
611
+ values = read_placeholder_values(xlsx) if fields else {}
612
+ missing = [f for f in fields if not str(values.get(f, "")).strip()]
613
+ if missing:
614
+ record.update(status="skipped", reason="正文占位符未填:" + "、".join(missing))
615
+ log(f"[跳过] {xlsx.name}:正文占位符未填 {'、'.join('{'+f+'}' for f in missing)},"
616
+ f"请在该工作簿「正文信息」表填写后重试")
617
+ continue
618
+ output = out_root / f"{tpl.stem}_{xlsx.stem}.docx"
619
+ seq = 2
620
+ while output.exists():
621
+ output = out_root / f"{tpl.stem}_{xlsx.stem}_{seq}.docx"
622
+ seq += 1
623
+ record["output"] = str(output)
624
+ if dry_run:
625
+ log(f"[模板·预演] 将生成 {output.name}(模板{tpl_no}:{tpl.name})")
626
+ for f in fields:
627
+ log(f"[占位符·预演] {{{f}}} → {values[f]}")
628
+ if "tables" in contents or "marks" in contents:
629
+ run_sync_content(
630
+ tpl, xlsx,
631
+ tables="tables" in contents,
632
+ marks="marks" in contents,
633
+ keep_highlight=keep_highlight,
634
+ dry_run=True,
635
+ backup=False,
636
+ )
637
+ record.update(status="ok", reason="预演完成")
638
+ continue
639
+ shutil.copy2(tpl, output)
640
+ if fields:
641
+ out_doc = _docx.Document(str(output))
642
+ result = apply_placeholders(out_doc, values)
643
+ out_doc.save(str(output))
644
+ for f, v in result["replaced"]:
645
+ shown = v if len(v) <= 60 else v[:60] + "…"
646
+ log(f"[占位符] {{{f}}} → {shown}")
647
+ if "tables" in contents or "marks" in contents:
648
+ with tempfile.TemporaryDirectory(prefix="wesync_tpl_", dir=tmp_root()) as tmp:
649
+ tmp_xlsx = Path(tmp) / xlsx.name
650
+ shutil.copy2(xlsx, tmp_xlsx)
651
+ run_sync_content(
652
+ output, tmp_xlsx,
653
+ tables="tables" in contents,
654
+ marks="marks" in contents,
655
+ keep_highlight=keep_highlight,
656
+ backup=False,
657
+ )
658
+ record.update(status="ok", reason="已生成")
659
+ log(f"[模板] 已生成 {output}")
660
+ except SyncError as exc:
661
+ record["reason"] = str(exc)
662
+ log(f"[失败] {xlsx.name}:{exc}")
663
+ except Exception as exc:
664
+ record["reason"] = f"{type(exc).__name__}: {exc}"
665
+ log(f"[失败] {xlsx.name}:{record['reason']}")
666
+ ok = sum(1 for r in results if r["status"] == "ok")
667
+ skipped = sum(1 for r in results if r["status"] == "skipped")
668
+ failed = sum(1 for r in results if r["status"] == "failed")
669
+ log(f"模板生成{'预演' if dry_run else ''}结束:成功 {ok} 份,跳过 {skipped} 份,失败 {failed} 份(共 {total} 份)。输出目录:{out_root}")
670
+ return results
671
+
672
+
673
+ def scan_blank_batch(docx_list: list) -> list[dict]:
674
+ """只读批量扫描空白表:每份报告返回候选清单或错误原因,供界面按报告分组展示。"""
675
+ results = []
676
+ for docx in docx_list:
677
+ path = Path(docx)
678
+ item = {"docx": str(path), "candidates": [], "error": ""}
679
+ try:
680
+ item["candidates"] = scan_blank_tables(path)
681
+ except SyncError as exc:
682
+ item["error"] = str(exc)
683
+ except Exception as exc:
684
+ item["error"] = f"{type(exc).__name__}: {exc}"
685
+ results.append(item)
686
+ return results
687
+
688
+
689
+ def run_blank_batch(items: list[dict], *, dry_run: bool = False, force: bool = False) -> list[dict]:
690
+ """批量删除空白表:items 每项 {"docx", "pick", "keep_caption_for", "reversible", "excel"}。
691
+
692
+ 逐份执行,单份失败不影响其他;口径与单文件删除完全一致。
693
+ """
694
+ results = []
695
+ total = len(items)
696
+ for i, item in enumerate(items, 1):
697
+ path = Path(item["docx"])
698
+ log(f"===== [{i}/{total}] {path.name} =====")
699
+ record = {"docx": str(path), "status": "failed", "reason": ""}
700
+ results.append(record)
701
+ try:
702
+ run_blank_tables(
703
+ path,
704
+ dry_run=dry_run,
705
+ force=force,
706
+ pick=item.get("pick"),
707
+ keep_caption_for=item.get("keep_caption_for"),
708
+ reversible=bool(item.get("reversible", True)),
709
+ excel=item.get("excel"),
710
+ )
711
+ record.update(status="ok", reason="预演完成" if dry_run else "删除完成")
712
+ except SyncError as exc:
713
+ record["reason"] = str(exc)
714
+ log(f"[失败] {path.name}:{exc}")
715
+ except Exception as exc:
716
+ record["reason"] = f"{type(exc).__name__}: {exc}"
717
+ log(f"[失败] {path.name}:{record['reason']}")
718
+ ok = sum(1 for r in results if r["status"] == "ok")
719
+ failed = sum(1 for r in results if r["status"] == "failed")
720
+ log(f"批量删除空白表{'预演' if dry_run else ''}结束:成功 {ok} 份,失败 {failed} 份(共 {total} 份)。")
721
+ return results
722
+
723
+
724
+ def scan_report_format(
725
+ docx: str | Path,
726
+ template: str | Path | None = None,
727
+ *,
728
+ profile_name: str | None = None,
729
+ scope: dict | None = None,
730
+ heading_batch_id: str | None = None,
731
+ heading_levels: dict | None = None,
732
+ role_batch_id: str | None = None,
733
+ role_overrides: dict | None = None,
734
+ region_start_id: str | None = None,
735
+ ) -> dict:
736
+ """只读扫描格式调整方案:按样板或已存纯格式方案预演,不写任何文件。"""
737
+ from .report_format import scan_report_format as scan
738
+
739
+ return scan(
740
+ docx, template, profile_name=profile_name, scope=scope,
741
+ heading_batch_id=heading_batch_id, heading_levels=heading_levels,
742
+ role_batch_id=role_batch_id, role_overrides=role_overrides,
743
+ region_start_id=region_start_id,
744
+ )
745
+
746
+
747
+ def run_report_format(
748
+ docx: str | Path,
749
+ template: str | Path | None = None,
750
+ *,
751
+ output: str | Path | None = None,
752
+ dry_run: bool = False,
753
+ profile_name: str | None = None,
754
+ scope: dict | None = None,
755
+ heading_batch_id: str | None = None,
756
+ heading_levels: dict | None = None,
757
+ role_batch_id: str | None = None,
758
+ role_overrides: dict | None = None,
759
+ region_start_id: str | None = None,
760
+ ) -> dict:
761
+ """按样板或已存纯格式方案生成副本;默认不覆盖原报告,也不改写原文件。"""
762
+ from .report_format import run_report_format as run
763
+
764
+ return run(
765
+ docx, template, output=output, dry_run=dry_run, profile_name=profile_name, scope=scope,
766
+ heading_batch_id=heading_batch_id, heading_levels=heading_levels,
767
+ role_batch_id=role_batch_id, role_overrides=role_overrides,
768
+ region_start_id=region_start_id,
769
+ )
770
+
771
+
772
+ def scan_format_heading_candidates(docx: str | Path) -> dict:
773
+ """只返回本地筛出的候选标题、疑难角色和附注边界及有限上下文。"""
774
+ from .report_format import scan_heading_candidates
775
+
776
+ return scan_heading_candidates(docx)
777
+
778
+
779
+ def list_format_profiles() -> list[dict]:
780
+ """列出项目内保存的纯格式方案。"""
781
+ from .report_format import list_format_profiles as list_profiles
782
+
783
+ return list_profiles()
784
+
785
+
786
+ def load_format_profile(name: str):
787
+ """读取并校验指定的纯格式方案。"""
788
+ from .report_format import load_format_profile as load
789
+
790
+ return load(name)
791
+
792
+
793
+ def save_format_profile(template: str | Path, name: str, source: str | Path | None = None) -> dict:
794
+ """从样板提取并保存纯格式参数,不保存报告文字、表格内容或样板路径。"""
795
+ from .report_format import save_format_profile as save
796
+
797
+ return save(template, name, source)
798
+
799
+
800
+ def delete_format_profile(name: str) -> dict:
801
+ """删除指定的纯格式方案。"""
802
+ from .report_format import delete_format_profile as delete
803
+
804
+ return delete(name)
805
+
806
+
807
+ def scan_template_placeholders(docx: str | Path) -> list[str]:
808
+ """只读列出模板正文/页眉页脚里的占位符字段名({字段名} 写法)。"""
809
+ import docx as _docx
810
+
811
+ from .docx_placeholders import scan_placeholders
812
+
813
+ path = resolve_docx(str(docx))
814
+ return scan_placeholders(_docx.Document(str(path)))
815
+
816
+
817
+ def fill_placeholder_sheets(template: str | Path, workbooks: list) -> list[dict]:
818
+ """按模板占位符给各工作簿生成/补齐「正文信息」填写骨架(保留已填值)。"""
819
+ from .docx_placeholders import write_placeholder_sheet
820
+
821
+ fields = scan_template_placeholders(template)
822
+ results = []
823
+ for xlsx in workbooks:
824
+ path = Path(xlsx)
825
+ record = {"excel": str(path), "status": "failed", "reason": "", "added": []}
826
+ results.append(record)
827
+ try:
828
+ if not path.exists():
829
+ record.update(status="skipped", reason="工作簿不存在")
830
+ continue
831
+ added = write_placeholder_sheet(path, fields)
832
+ record.update(status="ok", added=added,
833
+ reason=f"新增 {len(added)} 个字段" if added else "字段已齐全")
834
+ log(f"[正文信息] {path.name}:" + (f"已加入字段 {'、'.join(added)},请在「正文信息」表填值" if added else "字段已齐全,无需改动"))
835
+ except SyncError as exc:
836
+ record["reason"] = str(exc)
837
+ log(f"[失败] {path.name}:{exc}")
838
+ if not fields:
839
+ log("模板正文里没有占位符({字段名} 写法),无需填写清单。")
840
+ return results