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
@@ -7,7 +7,9 @@
7
7
  from __future__ import annotations
8
8
 
9
9
  import datetime as _dt
10
+ import os
10
11
  import shutil
12
+ import tempfile
11
13
  from pathlib import Path
12
14
 
13
15
  from .console import log
@@ -38,28 +40,61 @@ def list_backups(path: str | Path) -> list[dict]:
38
40
  stamp = _parse_stamp(mid)
39
41
  if stamp is None:
40
42
  continue
43
+ sequence = int(mid[16:]) if len(mid) > 15 and mid[15] == "_" and mid[16:].isdigit() else 0
41
44
  items.append({
42
45
  "file": f.name,
43
46
  "path": str(f),
44
47
  "time": stamp.strftime("%Y-%m-%d %H:%M:%S"),
45
48
  "stamp": stamp,
49
+ "sequence": sequence,
46
50
  "size": f.stat().st_size,
47
51
  })
48
- items.sort(key=lambda x: x["stamp"], reverse=True)
52
+ items.sort(key=lambda x: (x["stamp"], x["sequence"]), reverse=True)
49
53
  return items
50
54
 
51
55
 
52
- def restore_backup(backup: str | Path, target: str | Path) -> Path | None:
53
- """用历史版本覆盖目标文件;恢复前先把现状备份一次,返回该安全备份路径。"""
54
- backup = Path(backup)
56
+ def _validate_backup_content(path: Path) -> None:
57
+ """暂存副本必须能被对应 Office 库完整读取,避免损坏备份覆盖目标。"""
58
+ try:
59
+ if path.suffix.lower() == ".docx":
60
+ import docx
61
+
62
+ docx.Document(str(path))
63
+ elif path.suffix.lower() == ".xlsx":
64
+ from openpyxl import load_workbook
65
+
66
+ wb = load_workbook(path)
67
+ wb.close()
68
+ else:
69
+ raise ValueError("不支持的文件类型")
70
+ except Exception as exc:
71
+ raise SyncError(f"备份文件内容损坏或无法读取:{path.name}({exc})") from exc
72
+
73
+
74
+ def restore_backup(backup_path: str | Path, target: str | Path, *, backup: bool = True) -> Path | None:
75
+ """用历史版本覆盖目标文件;按设置在恢复前备份现状。"""
76
+ backup_path = Path(backup_path)
55
77
  target = Path(target)
56
- if not backup.exists():
57
- raise SyncError(f"备份文件不存在:{backup}")
78
+ if not backup_path.is_file():
79
+ raise SyncError(f"备份文件不存在:{backup_path}")
58
80
  if not target.exists():
59
81
  raise SyncError(f"要恢复的文件不存在:{target}\n(可能已被移动或改名)")
82
+ if backup_path.suffix.lower() != target.suffix.lower():
83
+ raise SyncError("备份文件与目标文件类型必须一致")
84
+ if backup_path.resolve() not in {Path(item["path"]).resolve() for item in list_backups(target)}:
85
+ raise SyncError(f"该文件不是 {target.name} 的历史备份;请从备份列表中选择。")
60
86
  check_file_free(target, False)
61
- safety = backup_file(target)
62
- shutil.copy2(backup, target)
63
- log(f"[回滚] 已用 {backup.name} 恢复 {target.name}"
87
+ safety = backup_file(target) if backup else None
88
+ fd, staged_name = tempfile.mkstemp(prefix=f".{target.stem}.restore.", suffix=target.suffix, dir=target.parent)
89
+ os.close(fd)
90
+ staged = Path(staged_name)
91
+ try:
92
+ shutil.copy2(backup_path, staged)
93
+ _validate_backup_content(staged)
94
+ check_file_free(target, False)
95
+ os.replace(staged, target)
96
+ finally:
97
+ staged.unlink(missing_ok=True)
98
+ log(f"[回滚] 已用 {backup_path.name} 恢复 {target.name}"
64
99
  + (f"(恢复前的现状已备份:{safety.name},可再次回滚)" if safety else ""))
65
100
  return safety
@@ -11,9 +11,10 @@ import sys
11
11
  from pathlib import Path
12
12
 
13
13
  from .commands.blank_cmd import cmd_blank_tables
14
- from .commands.bookmark_cmd import cmd_bookmark
14
+ from .commands.bookmark_cmd import cmd_bookmark, cmd_repair_links
15
15
  from .commands.clear_cmd import cmd_clear_bookmarks
16
16
  from .commands.export_cmd import cmd_export, cmd_rejudge
17
+ from .commands.incremental_cmd import cmd_incremental_export
17
18
  from .commands.marks_cmd import cmd_marks, cmd_marks_sync
18
19
  from .commands.placeholders_cmd import cmd_placeholders, cmd_placeholders_sync
19
20
  from .commands.writeback_cmd import cmd_writeback
@@ -61,6 +62,16 @@ def build_parser() -> argparse.ArgumentParser:
61
62
  export_parser.add_argument("--force", action="store_true", help="跳过文件占用检查,强制尝试写入")
62
63
  export_parser.set_defaults(func=cmd_export)
63
64
 
65
+ incremental_parser = sub.add_parser("incremental-export", help="只登记 Word 中新增的表格、标注与占位符,不改既有工作簿行")
66
+ incremental_parser.add_argument("docx", help="Word 文件路径(.docx)")
67
+ incremental_parser.add_argument("--excel", help="现有工作簿路径,默认同目录 <主名>_表格数据.xlsx")
68
+ incremental_parser.add_argument("--no-excel-links", action="store_true", help="不在 Excel 中写 Word 定位链接")
69
+ incremental_parser.add_argument("--no-total-formulas", action="store_true", help="新增表格的合计行不写求和公式")
70
+ incremental_parser.add_argument("--no-backup", dest="backup", action="store_false", default=True, help="覆盖前不备份原文件到 _backup")
71
+ incremental_parser.add_argument("--dry-run", action="store_true", help="只显示将登记的内容,不写文件")
72
+ incremental_parser.add_argument("--force", action="store_true", help="跳过文件占用检查,强制尝试写入")
73
+ incremental_parser.set_defaults(func=cmd_incremental_export)
74
+
64
75
  rejudge_parser = sub.add_parser("rejudge", help="按工作簿当前内容重新判定 B 列表头/✓/✕(只改标记,不改数据)")
65
76
  rejudge_parser.add_argument("docx", help="Word 文件路径(.docx,用于定位默认工作簿)")
66
77
  rejudge_parser.add_argument("--excel", help="工作簿路径,默认同目录 <主名>_表格数据.xlsx")
@@ -77,6 +88,13 @@ def build_parser() -> argparse.ArgumentParser:
77
88
  bookmark_parser.add_argument("--force", action="store_true", help="跳过文件占用检查,强制尝试写入")
78
89
  bookmark_parser.set_defaults(func=cmd_bookmark)
79
90
 
91
+ repair_links_parser = sub.add_parser("repair-links", help="文件移动或重命名后,修复 Excel 中表格与标注的 Word 定位链接")
92
+ repair_links_parser.add_argument("docx", help="当前 Word 文件路径(.docx)")
93
+ repair_links_parser.add_argument("--excel", help="当前工作簿路径,默认同目录 <主名>_表格数据.xlsx")
94
+ repair_links_parser.add_argument("--dry-run", action="store_true", help="只显示需要修复的链接,不写文件")
95
+ repair_links_parser.add_argument("--force", action="store_true", help="跳过文件占用检查,强制尝试写入")
96
+ repair_links_parser.set_defaults(func=cmd_repair_links)
97
+
80
98
  writeback_parser = sub.add_parser("writeback", help="把 Excel 的改动(含增删行、增删列)回写到 Word")
81
99
  writeback_parser.add_argument("docx", help="Word 文件路径(.docx)")
82
100
  writeback_parser.add_argument("--excel", help="工作簿路径,默认同目录 <主名>_表格数据.xlsx")
@@ -10,13 +10,13 @@ from copy import copy
10
10
 
11
11
  import docx
12
12
 
13
- from ..config import DELETED_BOOKMARK, NEW_BOOKMARK, SHEET_NAME
13
+ from ..config import DELETED_BOOKMARK, NEW_BOOKMARK, SHEET_NAME, SHEET_NEW_TABLES
14
14
  from ..console import log
15
15
  from ..docx_blank import delete_blank_tables, find_blank_tables
16
16
  from ..docx_bookmarks import table_index_map_by_bookmark
17
17
  from ..errors import SyncError
18
18
  from ..excel_blocks import parse_blocks
19
- from ..fsops import backup_file, check_file_free, load_workbook_for_save, resolve_docx, resolve_xlsx
19
+ from ..fsops import check_file_free, load_workbook_for_save, resolve_docx, resolve_xlsx, save_docx_xlsx_transaction
20
20
 
21
21
 
22
22
  def _parse_pick(text: str, count: int) -> list[int]:
@@ -35,6 +35,20 @@ def _parse_pick(text: str, count: int) -> list[int]:
35
35
  return nos
36
36
 
37
37
 
38
+ def _load_all_blocks(wb):
39
+ order, blocks = parse_blocks(wb[SHEET_NAME])
40
+ base_codes = set(order)
41
+ for sheet_name in (SHEET_NEW_TABLES,):
42
+ if sheet_name in wb.sheetnames:
43
+ extra_order, extra_blocks = parse_blocks(wb[sheet_name])
44
+ order.extend(extra_order)
45
+ blocks.update(extra_blocks)
46
+ for code, block in blocks.items():
47
+ block["sheet_name"] = SHEET_NAME if code in base_codes else SHEET_NEW_TABLES
48
+ block["_ws"] = wb[block["sheet_name"]]
49
+ return order, blocks
50
+
51
+
38
52
  def _plan_reversible(doc, xlsx_path, selected, force=False):
39
53
  """可逆删除前的准备:找到每个候选对应的工作簿表块与原位置锚点。"""
40
54
  if not xlsx_path.exists():
@@ -43,8 +57,7 @@ def _plan_reversible(doc, xlsx_path, selected, force=False):
43
57
  wb = load_workbook_for_save(xlsx_path)
44
58
  if SHEET_NAME not in wb.sheetnames:
45
59
  raise SyncError(f"工作簿中找不到工作表“{SHEET_NAME}”,请先重新执行「导出表格到 Excel」。")
46
- ws = wb[SHEET_NAME]
47
- _, blocks = parse_blocks(ws)
60
+ _, blocks = _load_all_blocks(wb)
48
61
  name_to_code = {
49
62
  block["bookmark"]: code
50
63
  for code, block in blocks.items()
@@ -66,14 +79,16 @@ def _plan_reversible(doc, xlsx_path, selected, force=False):
66
79
  prev_name = index_to_name[i]
67
80
  break
68
81
  plans.append((cand, with_caption, code, prev_name))
69
- return wb, ws, blocks, plans
82
+ return wb, blocks, plans
70
83
 
71
84
 
72
- def _mark_deleted_blocks(wb, ws, blocks, plans, xlsx_path) -> None:
85
+ def _mark_deleted_blocks(blocks, plans) -> None:
73
86
  """Word 删表后,把工作簿对应表块标记为「已删除」并记录原位置与原标题。"""
74
87
  for cand, with_caption, code, prev_name in plans:
75
- row = blocks[code]["anchor_row"]
76
- col0 = blocks[code].get("col0", 2)
88
+ block = blocks[code]
89
+ ws = block["_ws"]
90
+ row = block["anchor_row"]
91
+ col0 = block.get("col0", 2)
77
92
  ws.cell(row, col0 + 1, f"书签:{DELETED_BOOKMARK}")
78
93
  link = ws.cell(row, col0 + 2)
79
94
  link.value = None
@@ -84,12 +99,6 @@ def _mark_deleted_blocks(wb, ws, blocks, plans, xlsx_path) -> None:
84
99
  anchor_style = ws.cell(row, col0 + 1)._style
85
100
  for col in (col0 + 4, col0 + 5):
86
101
  ws.cell(row, col)._style = copy(anchor_style)
87
- backup = backup_file(xlsx_path)
88
- wb.save(str(xlsx_path))
89
- log(
90
- f"[可逆] 工作簿已标记 {len(plans)} 个表块为「已删除」(内容保留,可随时恢复)"
91
- + (f"(原工作簿已备份:{backup.name})" if backup else "")
92
- )
93
102
 
94
103
 
95
104
  def cmd_blank_tables(args) -> int:
@@ -138,17 +147,32 @@ def cmd_blank_tables(args) -> int:
138
147
  xlsx_path = resolve_xlsx(docx_path, getattr(args, "excel", None))
139
148
  prepared = _plan_reversible(doc, xlsx_path, selected, args.force) if reversible else None
140
149
  result = delete_blank_tables(doc, selected)
141
- backup = backup_file(docx_path)
142
- doc.save(str(docx_path))
150
+ if reversible:
151
+ wb, blocks, plans = prepared
152
+ _mark_deleted_blocks(blocks, plans)
153
+ backups = save_docx_xlsx_transaction(
154
+ docx_path=docx_path, doc=doc, xlsx_path=xlsx_path, wb=wb,
155
+ backup=getattr(args, "backup", True),
156
+ )
157
+ docx_backup = backups.get(docx_path)
158
+ xlsx_backup = backups.get(xlsx_path)
159
+ else:
160
+ backups = save_docx_xlsx_transaction(
161
+ docx_path=docx_path, doc=doc, backup=getattr(args, "backup", True),
162
+ )
163
+ docx_backup = backups.get(docx_path)
164
+ xlsx_backup = None
143
165
  log(
144
166
  f"[空白表] 已删除 {result['tables']} 张空白表、{result['captions']} 个表标题"
145
- + (f"(原文件已备份:{backup.name})" if backup else "")
167
+ + (f"(原文件已备份:{docx_backup.name})" if docx_backup else "")
146
168
  )
147
169
  if result["bookmarks"]:
148
170
  log(f"[空白表] 顺带清理失去配对的定位书签端点 {result['bookmarks']} 个")
149
171
  if reversible:
150
- wb, ws, blocks, plans = prepared
151
- _mark_deleted_blocks(wb, ws, blocks, plans, xlsx_path)
172
+ log(
173
+ f"[可逆] 工作簿已标记 {len(plans)} 个表块为「已删除」(内容保留,可随时恢复)"
174
+ + (f"(原工作簿已备份:{xlsx_backup.name})" if xlsx_backup else "")
175
+ )
152
176
  log("[可逆] Excel 表块已保留;要恢复时在「删除空白表格」页勾选恢复,或命令行 --restore 编号。")
153
177
  else:
154
178
  log("[空白表] 表格有删减,请重新执行「1-导出表格到Excel」重建工作簿,再做同步。")
@@ -173,8 +197,7 @@ def cmd_restore_tables(args) -> int:
173
197
  wb = load_workbook_for_save(xlsx_path)
174
198
  if SHEET_NAME not in wb.sheetnames:
175
199
  raise SyncError(f"工作簿中找不到工作表“{SHEET_NAME}”,请确认该文件由本工具导出")
176
- ws = wb[SHEET_NAME]
177
- order, blocks = parse_blocks(ws)
200
+ order, blocks = _load_all_blocks(wb)
178
201
  deleted = [code for code in order if blocks[code].get("bookmark") == DELETED_BOOKMARK]
179
202
  log(f"读取 Word:{docx_path.name}")
180
203
  if not deleted:
@@ -208,15 +231,16 @@ def cmd_restore_tables(args) -> int:
208
231
  }
209
232
  index_map = table_index_map_by_bookmark(doc, real_names)
210
233
  restored: dict[str, tuple] = {}
211
- for no in nos:
234
+ # 相邻表共享同一原位置锚点,逆序恢复才能保持原有先后顺序。
235
+ for no in reversed(nos):
212
236
  code = deleted[no - 1]
213
237
  block = blocks[code]
214
238
  if not block["grid_rows"]:
215
239
  raise SyncError(f"{code}:表块没有网格行,无法恢复")
216
240
  meta = block.get("meta", {})
217
- grid = _new_table_grid(ws, block, cached)
218
- merges = block_merges(ws, block)
219
- widths = col_widths_from_excel(ws, block["ncols"], total_dxa)
241
+ grid = _new_table_grid(block["_ws"], block, cached)
242
+ merges = block_merges(block["_ws"], block)
243
+ widths = col_widths_from_excel(block["_ws"], block["ncols"], total_dxa, col0=block.get("col0", 2))
220
244
  tbl = build_table(grid, merges, block["ncols"], widths)
221
245
  anchor = meta.get("restore_after") or ""
222
246
  prev_tbl = None
@@ -238,13 +262,18 @@ def cmd_restore_tables(args) -> int:
238
262
  for code, (bookmark, tbl) in restored.items():
239
263
  index = next(i for i, tab in enumerate(doc.tables) if tab._tbl is tbl)
240
264
  info = {**infos[index], "bookmark": bookmark}
241
- refresh_anchor_metadata(ws, blocks[code], info, docx_path.name, with_link=True, ncols=blocks[code]["ncols"])
265
+ refresh_anchor_metadata(
266
+ blocks[code]["_ws"], blocks[code], info, docx_path.name,
267
+ with_link=True, ncols=blocks[code]["ncols"]
268
+ )
242
269
  refresh_defined_names(wb, {code: blocks[code] for code in restored})
243
270
 
244
- docx_backup = backup_file(docx_path)
245
- doc.save(str(docx_path))
271
+ backups = save_docx_xlsx_transaction(
272
+ docx_path=docx_path, doc=doc, xlsx_path=xlsx_path, wb=wb,
273
+ backup=getattr(args, "backup", True),
274
+ )
275
+ docx_backup = backups.get(docx_path)
276
+ xlsx_backup = backups.get(xlsx_path)
246
277
  log(f"[恢复] 已保存 {docx_path.name}" + (f"(原文件已备份:{docx_backup.name})" if docx_backup else ""))
247
- xlsx_backup = backup_file(xlsx_path)
248
- wb.save(str(xlsx_path))
249
278
  log(f"[恢复] 已保存 {xlsx_path.name}(表块标记已改回真实书签)" + (f"(原工作簿已备份:{xlsx_backup.name})" if xlsx_backup else ""))
250
279
  return 0
@@ -12,14 +12,14 @@ import docx
12
12
  from openpyxl import load_workbook
13
13
 
14
14
  from ..align import apply_table_bookmarks, plan_table_bookmarks, split_bookmark_updates
15
- from ..config import EXCEL_LINK_TEXT, SHEET_NAME
15
+ from ..config import EXCEL_LINK_TEXT, SHEET_NAME, SHEET_NEW_TABLES
16
16
  from ..console import log
17
17
  from ..docx_bookmarks import cleanup_excel_markers
18
18
  from ..docx_grid import body_items
19
19
  from ..docx_meta import collect_table_info, dedupe_table_names
20
20
  from ..errors import SyncError
21
- from ..excel_blocks import parse_blocks, read_recorded_bookmarks, refresh_workbook_metadata
22
- from ..fsops import backup_file, check_file_free, resolve_docx, resolve_xlsx
21
+ from ..excel_blocks import parse_blocks, read_recorded_bookmarks, refresh_workbook_metadata, repair_workbook_links
22
+ from ..fsops import check_file_free, resolve_docx, resolve_xlsx, save_docx_xlsx_transaction
23
23
 
24
24
 
25
25
  def _short_list(codes: list[str], limit: int = 12) -> str:
@@ -27,6 +27,27 @@ def _short_list(codes: list[str], limit: int = 12) -> str:
27
27
  return shown + ("…" if len(codes) > limit else "")
28
28
 
29
29
 
30
+ def cmd_repair_links(args) -> int:
31
+ """修复 Excel 中表格与标注指向 Word 的定位链接,不改 Word 和数据。"""
32
+ docx_path = resolve_docx(args.docx)
33
+ xlsx_path = resolve_xlsx(docx_path, args.excel)
34
+ if not xlsx_path.exists():
35
+ raise SyncError(
36
+ f"找不到工作簿:{xlsx_path}\n请先执行「导出表格到 Excel」或「增量导出」。"
37
+ )
38
+ if not args.dry_run:
39
+ check_file_free(xlsx_path, args.force)
40
+
41
+ log(f"读取 Word:{docx_path.name}")
42
+ log(f"读取 Excel:{xlsx_path.name}")
43
+ changed = repair_workbook_links(
44
+ xlsx_path, docx_path, dry_run=args.dry_run, backup=getattr(args, "backup", True)
45
+ )
46
+ if args.dry_run:
47
+ log(f"预演结束:发现 {changed} 个需要修复的链接,未写入任何文件。")
48
+ return 0
49
+
50
+
30
51
  def cmd_bookmark(args) -> int:
31
52
  docx_path = resolve_docx(args.docx)
32
53
  xlsx_path = resolve_xlsx(docx_path, args.excel)
@@ -47,16 +68,23 @@ def cmd_bookmark(args) -> int:
47
68
  blocks: dict = {}
48
69
  if xlsx_path.exists():
49
70
  workbook = load_workbook(str(xlsx_path))
50
- if SHEET_NAME in workbook.sheetnames:
51
- ws = workbook[SHEET_NAME]
52
- _, blocks = parse_blocks(ws)
71
+ if SHEET_NAME in workbook.sheetnames or SHEET_NEW_TABLES in workbook.sheetnames:
72
+ for sheet_name in (SHEET_NAME, SHEET_NEW_TABLES):
73
+ if sheet_name not in workbook.sheetnames:
74
+ continue
75
+ sheet = workbook[sheet_name]
76
+ _, sheet_blocks = parse_blocks(sheet)
77
+ for code, block in sheet_blocks.items():
78
+ block["sheet_name"] = sheet_name
79
+ block["_ws"] = sheet
80
+ blocks[code] = block
53
81
 
54
82
  plan = plan_table_bookmarks(doc, ws, blocks, recorded, name_unmatched=not blocks)
55
83
  code_by_index = {index: code for code, index in plan["mapping"].items()}
56
84
 
57
85
  log(f"读取 Word:{docx_path.name}({len(doc.tables)} 张表)")
58
86
  if blocks:
59
- log(f"读取 Excel:{xlsx_path.name}(工作表:{SHEET_NAME},{len(blocks)} 个表块)")
87
+ log(f"读取 Excel:{xlsx_path.name}({len(blocks)} 个表块)")
60
88
  else:
61
89
  log("未找到可用工作簿:将为每张表新建书签。")
62
90
 
@@ -91,13 +119,15 @@ def cmd_bookmark(args) -> int:
91
119
  log(f"[清理] 已删除 Word 正文中遗留的 {markers} 处 {EXCEL_LINK_TEXT} 文字/断链")
92
120
 
93
121
  if result["removed"] or result["inserted"] or markers:
94
- backup = backup_file(docx_path)
95
- doc.save(str(docx_path))
122
+ backups = save_docx_xlsx_transaction(
123
+ docx_path=docx_path, doc=doc, backup=getattr(args, "backup", True),
124
+ )
125
+ backup = backups.get(docx_path)
96
126
  log(f"[书签] 已保存 {docx_path.name}" + (f"(原文件已备份:{backup.name})" if backup else ""))
97
127
  else:
98
128
  log("[书签] Word 已是目标状态,无需保存")
99
129
 
100
- if ws is not None and blocks:
130
+ if blocks:
101
131
  name_by_index = {index: name for index, name in plan["assignments"]}
102
132
  infos_by_code: dict[str, dict] = {}
103
133
  for code, index in plan["mapping"].items():
@@ -111,5 +141,6 @@ def cmd_bookmark(args) -> int:
111
141
  docx_path.name,
112
142
  infos_by_code,
113
143
  with_links=not getattr(args, "no_excel_links", False),
144
+ backup=getattr(args, "backup", True), docx_path=docx_path,
114
145
  )
115
146
  return 0
@@ -10,7 +10,7 @@ import docx
10
10
 
11
11
  from ..console import log
12
12
  from ..docx_bookmarks import clear_tool_bookmarks
13
- from ..fsops import backup_file, check_file_free, resolve_docx
13
+ from ..fsops import check_file_free, resolve_docx, save_docx_xlsx_transaction
14
14
 
15
15
 
16
16
  def cmd_clear_bookmarks(args) -> int:
@@ -39,8 +39,10 @@ def cmd_clear_bookmarks(args) -> int:
39
39
  log("预演模式(--dry-run):未写入任何文件。")
40
40
  return 0
41
41
 
42
- backup = backup_file(docx_path)
43
- doc.save(str(docx_path))
42
+ backups = save_docx_xlsx_transaction(
43
+ docx_path=docx_path, doc=doc, backup=getattr(args, "backup", True),
44
+ )
45
+ backup = backups.get(docx_path)
44
46
  log(
45
47
  f"[清理] 已从 {docx_path.name} 删除 {result['removed']} 个书签"
46
48
  + (f"(原文件已备份:{backup.name})" if backup else "")