audit-e2w 1.11.2 → 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 (76) hide show
  1. package/README.md +152 -148
  2. package/dsh_plugins/audit-e2w/lib/index.js +9 -1
  3. package/dsh_plugins/audit-e2w/lib/skill.js +3 -2
  4. package/excel_word/README.md +45 -37
  5. package/excel_word/qoder_engine.py +10 -11
  6. package/excel_word/wesync/__init__.py +1 -1
  7. package/excel_word/wesync/ai/__init__.py +52 -0
  8. package/excel_word/wesync/ai/actions.py +369 -0
  9. package/excel_word/wesync/ai/client.py +340 -0
  10. package/excel_word/wesync/ai/config.py +291 -0
  11. package/excel_word/wesync/ai/docs.py +177 -0
  12. package/excel_word/wesync/ai/prompts.py +288 -0
  13. package/excel_word/wesync/ai/tasks/__init__.py +26 -0
  14. package/excel_word/wesync/ai/tasks/actions_task.py +97 -0
  15. package/excel_word/wesync/ai/tasks/combined.py +123 -0
  16. package/excel_word/wesync/ai/tasks/diff_note.py +61 -0
  17. package/excel_word/wesync/ai/tasks/headings.py +119 -0
  18. package/excel_word/wesync/ai/tasks/help_task.py +69 -0
  19. package/excel_word/wesync/ai/tasks/roles.py +128 -0
  20. package/excel_word/wesync/align.py +1 -0
  21. package/excel_word/wesync/api.py +544 -92
  22. package/excel_word/wesync/backup_history.py +44 -9
  23. package/excel_word/wesync/cli.py +19 -1
  24. package/excel_word/wesync/commands/blank_cmd.py +59 -30
  25. package/excel_word/wesync/commands/bookmark_cmd.py +41 -10
  26. package/excel_word/wesync/commands/clear_cmd.py +5 -3
  27. package/excel_word/wesync/commands/export_cmd.py +270 -220
  28. package/excel_word/wesync/commands/incremental_cmd.py +157 -0
  29. package/excel_word/wesync/commands/marks_cmd.py +24 -16
  30. package/excel_word/wesync/commands/placeholders_cmd.py +12 -7
  31. package/excel_word/wesync/commands/writeback_cmd.py +72 -116
  32. package/excel_word/wesync/config.py +3 -2
  33. package/excel_word/wesync/console.py +9 -2
  34. package/excel_word/wesync/docx_bookmarks.py +12 -5
  35. package/excel_word/wesync/docx_columns.py +1 -1
  36. package/excel_word/wesync/docx_marks.py +183 -75
  37. package/excel_word/wesync/docx_placeholders.py +65 -26
  38. package/excel_word/wesync/excel_blocks.py +144 -185
  39. package/excel_word/wesync/excel_export.py +15 -8
  40. package/excel_word/wesync/excel_marks.py +265 -193
  41. package/excel_word/wesync/fsops.py +11 -6
  42. package/excel_word/wesync/gui/__init__.py +21 -2
  43. package/excel_word/wesync/gui/app.py +243 -29
  44. package/excel_word/wesync/gui/manual.py +5 -3
  45. package/excel_word/wesync/gui/pages/__init__.py +53 -4
  46. package/excel_word/wesync/gui/pages/_page.py +129 -7
  47. package/excel_word/wesync/gui/pages/ai_page.py +854 -0
  48. package/excel_word/wesync/gui/pages/batch_page.py +64 -31
  49. package/excel_word/wesync/gui/pages/blank_page.py +529 -464
  50. package/excel_word/wesync/gui/pages/bookmark_page.py +97 -37
  51. package/excel_word/wesync/gui/pages/export_page.py +140 -87
  52. package/excel_word/wesync/gui/pages/feedback_page.py +196 -0
  53. package/excel_word/wesync/gui/pages/format_page.py +551 -429
  54. package/excel_word/wesync/gui/pages/help_page.py +73 -7
  55. package/excel_word/wesync/gui/pages/history_page.py +167 -144
  56. package/excel_word/wesync/gui/pages/marks_page.py +210 -177
  57. package/excel_word/wesync/gui/pages/settings_page.py +450 -0
  58. package/excel_word/wesync/gui/pages/writeback_page.py +167 -146
  59. package/excel_word/wesync/gui/runner.py +29 -13
  60. package/excel_word/wesync/gui/store.py +23 -7
  61. package/excel_word/wesync/gui/theme.py +220 -49
  62. package/excel_word/wesync/gui/widgets/ai_config.py +362 -0
  63. package/excel_word/wesync/gui/widgets/cards.py +124 -5
  64. package/excel_word/wesync/gui/widgets/chips.py +565 -0
  65. package/excel_word/wesync/gui/widgets/filebar.py +1 -1
  66. package/excel_word/wesync/gui/widgets/logpane.py +24 -8
  67. package/excel_word/wesync/gui/widgets/nav.py +267 -12
  68. package/excel_word/wesync/gui/widgets/theme_choice.py +93 -0
  69. package/excel_word/wesync/report_format.py +9 -1
  70. package/excel_word/wesync/settings.py +35 -0
  71. package/excel_word/wesync/sort_rules.py +75 -26
  72. package/excel_word/wesync/valuefmt.py +40 -17
  73. package/package.json +53 -51
  74. package/packaging//344/275/277/347/224/250/350/257/264/346/230/216.txt +247 -0
  75. package/qoder_plugins/audit-toolbox/README.md +159 -156
  76. package/qoder_plugins/audit-toolbox/catalog.mjs +13 -13
@@ -10,15 +10,16 @@ import argparse
10
10
  from pathlib import Path
11
11
 
12
12
  from .commands.blank_cmd import cmd_blank_tables
13
- from .commands.bookmark_cmd import cmd_bookmark
13
+ from .commands.bookmark_cmd import cmd_bookmark, cmd_repair_links
14
14
  from .commands.clear_cmd import cmd_clear_bookmarks
15
15
  from .commands.export_cmd import cmd_export
16
+ from .commands.incremental_cmd import cmd_incremental_export
16
17
  from .commands.marks_cmd import cmd_marks, cmd_marks_sync
17
18
  from .commands.writeback_cmd import cmd_writeback
18
19
  from .console import log
19
20
  from .docx_blank import find_blank_tables
20
21
  from .errors import SyncError
21
- from .fsops import backup_file, check_file_free, resolve_docx, resolve_xlsx, tmp_root
22
+ from .fsops import check_file_free, resolve_docx, resolve_xlsx, save_docx_xlsx_transaction, tmp_root
22
23
 
23
24
 
24
25
  def _options(
@@ -65,6 +66,22 @@ def run_export(
65
66
  return cmd_export(options)
66
67
 
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
+
68
85
  def run_rejudge(
69
86
  docx: str | Path,
70
87
  excel: str | Path | None = None,
@@ -90,9 +107,22 @@ def run_bookmark(
90
107
  dry_run: bool = False,
91
108
  force: bool = False,
92
109
  with_excel_links: bool = True,
110
+ backup: bool = True,
93
111
  ) -> int:
94
112
  """书签工具:迁移/补建书签并清理正文遗留文字,不改数据。"""
95
- return cmd_bookmark(_options(docx, excel, dry_run, force, with_excel_links))
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))
96
126
 
97
127
 
98
128
  def run_writeback(
@@ -104,6 +134,7 @@ def run_writeback(
104
134
  backup: bool = True,
105
135
  changelog: bool = False,
106
136
  delete_empty_rows: bool = False,
137
+ table_zero: str = "excel",
107
138
  ) -> int:
108
139
  """回写:Excel → Word(含增删行、增删列)。
109
140
 
@@ -115,6 +146,7 @@ def run_writeback(
115
146
  options = _options(docx, excel, dry_run, force, True, backup)
116
147
  options.changelog = bool(changelog)
117
148
  options.delete_empty_rows = bool(delete_empty_rows)
149
+ options.table_zero = table_zero
118
150
  return cmd_writeback(options)
119
151
 
120
152
 
@@ -149,11 +181,11 @@ def scan_backups(docx: str | Path, excel: str | Path | None = None) -> dict:
149
181
  }
150
182
 
151
183
 
152
- def run_restore_backup(backup: str | Path, target: str | Path) -> None:
153
- """用选中的历史备份恢复目标文件(恢复前自动备份现状,可再次回滚)。"""
184
+ def run_restore_backup(backup: str | Path, target: str | Path, *, safety_backup: bool = True) -> None:
185
+ """用选中的历史备份恢复目标文件(按设置在恢复前备份现状)。"""
154
186
  from .backup_history import restore_backup
155
187
 
156
- restore_backup(backup, target)
188
+ restore_backup(backup, target, backup=safety_backup)
157
189
 
158
190
 
159
191
  def run_marks(
@@ -162,9 +194,10 @@ def run_marks(
162
194
  *,
163
195
  dry_run: bool = False,
164
196
  force: bool = False,
197
+ backup: bool = True,
165
198
  ) -> int:
166
199
  """刷新工作簿里的「链接标注」工作表(高亮标记导出,不改 Word 文字)。"""
167
- return cmd_marks(_options(docx, excel, dry_run, force, True))
200
+ return cmd_marks(_options(docx, excel, dry_run, force, True, backup))
168
201
 
169
202
 
170
203
  def run_marks_sync(
@@ -174,11 +207,14 @@ def run_marks_sync(
174
207
  dry_run: bool = False,
175
208
  force: bool = False,
176
209
  keep_highlight: bool = False,
210
+ backup: bool = True,
211
+ mark_zero: str = "excel",
177
212
  _rows: list[dict] | None = None,
178
213
  ) -> int:
179
214
  """把「链接标注」工作表里填写的新内容/链接同步回 Word。"""
180
- options = _options(docx, excel, dry_run, force, True)
215
+ options = _options(docx, excel, dry_run, force, True, backup)
181
216
  options.keep_highlight = bool(keep_highlight)
217
+ options.mark_zero = mark_zero
182
218
  options.rows = _rows
183
219
  return cmd_marks_sync(options)
184
220
 
@@ -189,11 +225,12 @@ def run_placeholder_export(
189
225
  *,
190
226
  dry_run: bool = False,
191
227
  force: bool = False,
228
+ backup: bool = True,
192
229
  ) -> int:
193
230
  """按当前 Word 的 {字段名} 给工作簿「正文信息」表补齐骨架(保留已填值)。"""
194
231
  from .commands.placeholders_cmd import cmd_placeholders
195
232
 
196
- return cmd_placeholders(_options(docx, excel, dry_run, force, True))
233
+ return cmd_placeholders(_options(docx, excel, dry_run, force, True, backup))
197
234
 
198
235
 
199
236
  def run_placeholder_sync(
@@ -202,13 +239,16 @@ def run_placeholder_sync(
202
239
  *,
203
240
  dry_run: bool = False,
204
241
  force: bool = False,
242
+ backup: bool = True,
243
+ placeholder_zero: str = "excel",
205
244
  _values: dict[str, str] | None = None,
206
245
  ) -> int:
207
246
  """把「正文信息」表填好的值写回当前 Word 占位符;未填字段保留原样并警告。"""
208
247
  from .commands.placeholders_cmd import cmd_placeholders_sync
209
248
 
210
- options = _options(docx, excel, dry_run, force, True)
249
+ options = _options(docx, excel, dry_run, force, True, backup)
211
250
  options.values = _values
251
+ options.placeholder_zero = placeholder_zero
212
252
  return cmd_placeholders_sync(options)
213
253
 
214
254
 
@@ -225,55 +265,129 @@ def run_sync_content(
225
265
  backup: bool = False,
226
266
  changelog: bool = False,
227
267
  delete_empty_rows: bool = False,
268
+ table_zero: str = "excel",
269
+ mark_zero: str = "excel",
270
+ placeholder_zero: str = "excel",
228
271
  ) -> dict:
229
272
  """按勾选内容编排同步:表格 → 标注 → 占位符,返回各部分执行摘要。
230
273
 
274
+ 工作簿与 Word 各加载一次;所选修改应用到同一 Word 对象后,以单事务保存。
231
275
  勾选了标注/占位符但工作簿缺对应工作表(或标注无数据行、占位符没填任何值)时
232
276
  警告并跳过该部分内容(不静默);表格部分的备份/改动清单/删除✕行选项只作用于表格。
233
- 标注/占位符在表格保存前读取,避免公式缓存值因工作簿重存而丢失。
234
277
  """
235
- from .fsops import load_workbook_for_save as load_workbook
278
+ import docx as _docx
279
+ from openpyxl import load_workbook
280
+
281
+ from .fsops import load_workbook_for_save
236
282
 
237
283
  from .console import warn
238
284
  from .docx_placeholders import VALUES_SHEET, read_placeholder_values
239
285
  from .excel_marks import SHEET_MARKS, parse_marks_rows
286
+ from .valuefmt import formula_map
240
287
 
241
288
  if not (tables or marks or placeholders):
242
289
  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))
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
248
303
  if marks:
249
304
  if SHEET_MARKS not in wb.sheetnames:
250
305
  marks_rows = []
251
306
  else:
252
- cached_wb = load_workbook(str(xlsx), data_only=True)
253
- marks_rows = parse_marks_rows(wb[SHEET_MARKS], cached_wb[SHEET_MARKS])
307
+ marks_rows = parse_marks_rows(
308
+ wb[SHEET_MARKS], cached_wb[SHEET_MARKS], zero_mode=mark_zero,
309
+ )
254
310
  if not marks_rows:
255
311
  warn(f"工作簿没有「{SHEET_MARKS}」数据行,跳过标注内容;请先在「标注与占位」页导出/刷新标注。")
256
312
  marks = False
257
313
  if placeholders:
258
- placeholder_values = read_placeholder_values(xlsx)
259
- if not placeholder_values:
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:
260
318
  warn(f"工作簿没有「{VALUES_SHEET}」表或表里没填任何值,跳过占位符内容;请先在「标注与占位」页导出/刷新占位符并填值。")
261
319
  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
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()
277
391
 
278
392
 
279
393
  def run_clear_bookmarks(
@@ -282,9 +396,10 @@ def run_clear_bookmarks(
282
396
  *,
283
397
  dry_run: bool = False,
284
398
  force: bool = False,
399
+ backup: bool = True,
285
400
  ) -> int:
286
401
  """删除 Word 里所有本工具书签(CPAH_/TBL_/MRK_),保留 Word 自带书签。"""
287
- return cmd_clear_bookmarks(_options(docx, None, dry_run, force, True))
402
+ return cmd_clear_bookmarks(_options(docx, None, dry_run, force, True, backup))
288
403
 
289
404
 
290
405
  def scan_blank_tables(docx_path: str | Path) -> list[dict]:
@@ -305,6 +420,7 @@ def run_blank_tables(
305
420
  keep_caption_for: str | None = None,
306
421
  reversible: bool = False,
307
422
  excel: str | Path | None = None,
423
+ backup: bool = True,
308
424
  ) -> int:
309
425
  """删除空白表。pick 为候选编号(如 "1,3")或 "all";不给 pick 时只列候选不删除。
310
426
 
@@ -317,6 +433,7 @@ def run_blank_tables(
317
433
  options.keep_caption = bool(keep_caption)
318
434
  options.keep_caption_for = keep_caption_for
319
435
  options.reversible = bool(reversible)
436
+ options.backup = bool(backup)
320
437
  return cmd_blank_tables(options)
321
438
 
322
439
 
@@ -334,9 +451,10 @@ def run_restore_tables(
334
451
  pick: str = "all",
335
452
  dry_run: bool = False,
336
453
  force: bool = False,
454
+ backup: bool = True,
337
455
  ) -> int:
338
456
  """恢复已可逆删除的表。pick 为恢复清单编号(如 "1,3")或 "all"。"""
339
- options = _options(docx, excel, dry_run, force, True)
457
+ options = _options(docx, excel, dry_run, force, True, backup)
340
458
  options.restore = str(pick)
341
459
  return cmd_blank_tables(options)
342
460
 
@@ -345,7 +463,7 @@ def list_table_blocks(docx: str | Path, excel: str | Path | None = None) -> list
345
463
  """只读列出工作簿里的表块(编号、表名、书签标记),供界面选择插入位置/恢复清单。"""
346
464
  from .fsops import load_workbook_for_save as load_workbook
347
465
 
348
- from .config import SHEET_NAME
466
+ from .config import SHEET_NAME, SHEET_NEW_TABLES
349
467
  from .excel_blocks import parse_blocks
350
468
 
351
469
  docx_path = resolve_docx(str(docx))
@@ -353,9 +471,11 @@ def list_table_blocks(docx: str | Path, excel: str | Path | None = None) -> list
353
471
  if not xlsx_path.exists():
354
472
  return []
355
473
  wb = load_workbook(str(xlsx_path))
356
- if SHEET_NAME not in wb.sheetnames:
357
- return []
358
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)
359
479
  result = []
360
480
  for code in order:
361
481
  block = blocks[code]
@@ -373,45 +493,10 @@ def list_table_blocks(docx: str | Path, excel: str | Path | None = None) -> list
373
493
  return result
374
494
 
375
495
 
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
496
  def _load_blocks(docx, excel):
412
497
  from .fsops import load_workbook_for_save as load_workbook
413
498
 
414
- from .config import SHEET_NAME
499
+ from .config import SHEET_NAME, SHEET_NEW_TABLES
415
500
  from .excel_blocks import parse_blocks
416
501
 
417
502
  docx_path = resolve_docx(str(docx))
@@ -422,6 +507,16 @@ def _load_blocks(docx, excel):
422
507
  if SHEET_NAME not in wb.sheetnames:
423
508
  raise SyncError(f"工作簿中找不到工作表“{SHEET_NAME}”,请确认该文件由本工具导出")
424
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"]]
425
520
  return xlsx_path, wb, wb[SHEET_NAME], order, blocks
426
521
 
427
522
 
@@ -442,7 +537,7 @@ def list_table_sorts(docx: str | Path, excel: str | Path | None = None) -> list[
442
537
  {
443
538
  "code": code,
444
539
  "name": (block.get("meta", {}).get("name") or "").strip(),
445
- "headers": block_headers(ws, block),
540
+ "headers": block_headers(block["_ws"], block),
446
541
  "sort_column": setting[0] if setting else "",
447
542
  "descending": setting[1] if setting else True,
448
543
  "has_sort": setting is not None,
@@ -458,6 +553,7 @@ def set_table_sort(
458
553
  code: str,
459
554
  column: str,
460
555
  descending: bool = True,
556
+ backup: bool = True,
461
557
  ) -> None:
462
558
  """保存某表的排序设置(写进工作簿锚点行,随文件保存,同步时自动应用)。"""
463
559
  from .sort_rules import write_block_sort
@@ -466,14 +562,15 @@ def set_table_sort(
466
562
  if code not in blocks:
467
563
  raise SyncError(f"工作簿中找不到表块 {code}")
468
564
  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))
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)
472
569
  log(f"[排序] {code}:已保存排序设置「{column} {'降序' if descending else '升序'}」"
473
- + (f"(原工作簿已备份:{backup.name})" if backup else ""))
570
+ + (f"(原工作簿已备份:{saved_backup.name})" if saved_backup else ""))
474
571
 
475
572
 
476
- def clear_table_sort(docx: str | Path, excel: str | Path | None = None, *, code: str) -> None:
573
+ def clear_table_sort(docx: str | Path, excel: str | Path | None = None, *, code: str, backup: bool = True) -> None:
477
574
  """清除某表的排序设置。"""
478
575
  from .sort_rules import clear_block_sort
479
576
 
@@ -481,10 +578,11 @@ def clear_table_sort(docx: str | Path, excel: str | Path | None = None, *, code:
481
578
  if code not in blocks:
482
579
  raise SyncError(f"工作簿中找不到表块 {code}")
483
580
  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 ""))
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 ""))
488
586
  else:
489
587
  log(f"[排序] {code}:本来就没有排序设置,无需清除")
490
588
 
@@ -497,6 +595,9 @@ def run_batch_writeback(
497
595
  force: bool = False,
498
596
  contents: tuple = ("tables",),
499
597
  keep_highlight: bool = True,
598
+ table_zero: str = "excel",
599
+ mark_zero: str = "excel",
600
+ placeholder_zero: str = "excel",
500
601
  ) -> list[dict]:
501
602
  """多报告批量同步:每份 Word 配同名工作簿逐个回写,单份失败不影响其他。
502
603
 
@@ -529,6 +630,7 @@ def run_batch_writeback(
529
630
  dry_run=dry_run,
530
631
  backup=backup,
531
632
  force=force,
633
+ table_zero=table_zero, mark_zero=mark_zero, placeholder_zero=placeholder_zero,
532
634
  )
533
635
  item.update(status="ok", reason="预演完成" if dry_run else "同步完成")
534
636
  except SyncError as exc:
@@ -552,6 +654,9 @@ def run_template_batch(
552
654
  dry_run: bool = False,
553
655
  contents: tuple = ("tables", "placeholders"),
554
656
  keep_highlight: bool = True,
657
+ table_zero: str = "excel",
658
+ mark_zero: str = "excel",
659
+ placeholder_zero: str = "excel",
555
660
  ) -> list[dict]:
556
661
  """模板生成:每个 Excel 同步到指定模板的一份副本,产出若干新 Word。
557
662
 
@@ -608,13 +713,14 @@ def run_template_batch(
608
713
  log(f"[跳过] {xlsx.name}:书签与模板{tpl_no}({tpl.name})对不上,请先用该模板执行「导出表格到 Excel」")
609
714
  continue
610
715
  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()]
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]
613
718
  if missing:
614
719
  record.update(status="skipped", reason="正文占位符未填:" + "、".join(missing))
615
720
  log(f"[跳过] {xlsx.name}:正文占位符未填 {'、'.join('{'+f+'}' for f in missing)},"
616
721
  f"请在该工作簿「正文信息」表填写后重试")
617
722
  continue
723
+ values = read_placeholder_values(xlsx, zero_mode=placeholder_zero) if fields else {}
618
724
  output = out_root / f"{tpl.stem}_{xlsx.stem}.docx"
619
725
  seq = 2
620
726
  while output.exists():
@@ -631,6 +737,7 @@ def run_template_batch(
631
737
  tables="tables" in contents,
632
738
  marks="marks" in contents,
633
739
  keep_highlight=keep_highlight,
740
+ table_zero=table_zero, mark_zero=mark_zero, placeholder_zero=placeholder_zero,
634
741
  dry_run=True,
635
742
  backup=False,
636
743
  )
@@ -653,6 +760,7 @@ def run_template_batch(
653
760
  tables="tables" in contents,
654
761
  marks="marks" in contents,
655
762
  keep_highlight=keep_highlight,
763
+ table_zero=table_zero, mark_zero=mark_zero, placeholder_zero=placeholder_zero,
656
764
  backup=False,
657
765
  )
658
766
  record.update(status="ok", reason="已生成")
@@ -686,7 +794,7 @@ def scan_blank_batch(docx_list: list) -> list[dict]:
686
794
  return results
687
795
 
688
796
 
689
- def run_blank_batch(items: list[dict], *, dry_run: bool = False, force: bool = False) -> list[dict]:
797
+ def run_blank_batch(items: list[dict], *, dry_run: bool = False, force: bool = False, backup: bool = True) -> list[dict]:
690
798
  """批量删除空白表:items 每项 {"docx", "pick", "keep_caption_for", "reversible", "excel"}。
691
799
 
692
800
  逐份执行,单份失败不影响其他;口径与单文件删除完全一致。
@@ -707,6 +815,7 @@ def run_blank_batch(items: list[dict], *, dry_run: bool = False, force: bool = F
707
815
  keep_caption_for=item.get("keep_caption_for"),
708
816
  reversible=bool(item.get("reversible", True)),
709
817
  excel=item.get("excel"),
818
+ backup=backup,
710
819
  )
711
820
  record.update(status="ok", reason="预演完成" if dry_run else "删除完成")
712
821
  except SyncError as exc:
@@ -814,7 +923,7 @@ def scan_template_placeholders(docx: str | Path) -> list[str]:
814
923
  return scan_placeholders(_docx.Document(str(path)))
815
924
 
816
925
 
817
- def fill_placeholder_sheets(template: str | Path, workbooks: list) -> list[dict]:
926
+ def fill_placeholder_sheets(template: str | Path, workbooks: list, *, backup: bool = True) -> list[dict]:
818
927
  """按模板占位符给各工作簿生成/补齐「正文信息」填写骨架(保留已填值)。"""
819
928
  from .docx_placeholders import write_placeholder_sheet
820
929
 
@@ -828,7 +937,7 @@ def fill_placeholder_sheets(template: str | Path, workbooks: list) -> list[dict]
828
937
  if not path.exists():
829
938
  record.update(status="skipped", reason="工作簿不存在")
830
939
  continue
831
- added = write_placeholder_sheet(path, fields)
940
+ added = write_placeholder_sheet(path, fields, backup=backup)
832
941
  record.update(status="ok", added=added,
833
942
  reason=f"新增 {len(added)} 个字段" if added else "字段已齐全")
834
943
  log(f"[正文信息] {path.name}:" + (f"已加入字段 {'、'.join(added)},请在「正文信息」表填值" if added else "字段已齐全,无需改动"))
@@ -838,3 +947,346 @@ def fill_placeholder_sheets(template: str | Path, workbooks: list) -> list[dict]
838
947
  if not fields:
839
948
  log("模板正文里没有占位符({字段名} 写法),无需填写清单。")
840
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)