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,65 @@
1
+ """备份历史与回滚:列出 _backup 里某文件的历史版本,按时间点恢复(恢复前先备份现状)。
2
+
3
+ 备份命名沿用 fsops.backup_file:<主名>.<时间戳>.bak<扩展名>(重名追加 _1、_2)。
4
+ 恢复是可逆的:先把当前文件再备份一次,再用选中的历史版本覆盖。
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import datetime as _dt
10
+ import shutil
11
+ from pathlib import Path
12
+
13
+ from .console import log
14
+ from .errors import SyncError
15
+ from .fsops import backup_file, check_file_free
16
+
17
+
18
+ def _parse_stamp(mid: str) -> _dt.datetime | None:
19
+ try:
20
+ return _dt.datetime.strptime(mid[:15], "%Y%m%d_%H%M%S")
21
+ except ValueError:
22
+ return None
23
+
24
+
25
+ def list_backups(path: str | Path) -> list[dict]:
26
+ """列出某文件(docx/xlsx)在 _backup 里的历史版本,按时间倒序。"""
27
+ path = Path(path)
28
+ backup_dir = path.parent / "_backup"
29
+ if not backup_dir.is_dir():
30
+ return []
31
+ prefix = f"{path.stem}."
32
+ suffix = f".bak{path.suffix}"
33
+ items = []
34
+ for f in backup_dir.iterdir():
35
+ if not f.is_file() or not f.name.startswith(prefix) or not f.name.endswith(suffix):
36
+ continue
37
+ mid = f.name[len(prefix):-len(suffix)]
38
+ stamp = _parse_stamp(mid)
39
+ if stamp is None:
40
+ continue
41
+ items.append({
42
+ "file": f.name,
43
+ "path": str(f),
44
+ "time": stamp.strftime("%Y-%m-%d %H:%M:%S"),
45
+ "stamp": stamp,
46
+ "size": f.stat().st_size,
47
+ })
48
+ items.sort(key=lambda x: x["stamp"], reverse=True)
49
+ return items
50
+
51
+
52
+ def restore_backup(backup: str | Path, target: str | Path) -> Path | None:
53
+ """用历史版本覆盖目标文件;恢复前先把现状备份一次,返回该安全备份路径。"""
54
+ backup = Path(backup)
55
+ target = Path(target)
56
+ if not backup.exists():
57
+ raise SyncError(f"备份文件不存在:{backup}")
58
+ if not target.exists():
59
+ raise SyncError(f"要恢复的文件不存在:{target}\n(可能已被移动或改名)")
60
+ check_file_free(target, False)
61
+ safety = backup_file(target)
62
+ shutil.copy2(backup, target)
63
+ log(f"[回滚] 已用 {backup.name} 恢复 {target.name}"
64
+ + (f"(恢复前的现状已备份:{safety.name},可再次回滚)" if safety else ""))
65
+ return safety
@@ -0,0 +1,58 @@
1
+ """改动留痕清单:把一次回写的逐格改动(旧值→新值)导出成 Excel 复核底稿。
2
+
3
+ 记录由回写过程收集(见 writeback_cmd),本模块只负责落盘成清单。
4
+ 清单保存在工作簿同目录,命名 <报告主名>_改动清单_<时间戳>.xlsx,不覆盖报告与工作簿。
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import datetime as _dt
10
+ from pathlib import Path
11
+
12
+ from openpyxl import Workbook
13
+ from openpyxl.styles import Alignment, Font, PatternFill
14
+
15
+ from .config import FONT_NAME, FONT_SIZE
16
+ from .console import log
17
+
18
+ HEADERS = ["表号", "表名", "行", "列", "项目", "旧值", "新值", "类型"]
19
+ _HEADER_FILL = PatternFill("solid", fgColor="1F4E79")
20
+
21
+
22
+ def export_changelog(records: list[dict], xlsx_path: Path, docx_name: str) -> Path | None:
23
+ """把改动记录导出为 Excel 清单;无记录时返回 None。"""
24
+ if not records:
25
+ return None
26
+ stamp = _dt.datetime.now().strftime("%Y%m%d_%H%M%S")
27
+ stem = Path(docx_name).stem
28
+ target = xlsx_path.parent / f"{stem}_改动清单_{stamp}.xlsx"
29
+ counter = 1
30
+ while target.exists():
31
+ target = xlsx_path.parent / f"{stem}_改动清单_{stamp}_{counter}.xlsx"
32
+ counter += 1
33
+
34
+ wb = Workbook()
35
+ ws = wb.active
36
+ ws.title = "改动清单"
37
+ ws.cell(1, 1, f"报告:{docx_name} 生成时间:{_dt.datetime.now():%Y-%m-%d %H:%M:%S} 共 {len(records)} 条改动")
38
+ ws.cell(1, 1).font = Font(name=FONT_NAME, size=FONT_SIZE, bold=True, color="1F4E79")
39
+ ws.merge_cells(start_row=1, start_column=1, end_row=1, end_column=len(HEADERS))
40
+ for c, title in enumerate(HEADERS, 1):
41
+ cell = ws.cell(2, c, title)
42
+ cell.font = Font(name=FONT_NAME, size=FONT_SIZE, bold=True, color="FFFFFF")
43
+ cell.fill = _HEADER_FILL
44
+ cell.alignment = Alignment(horizontal="center", vertical="center")
45
+ for i, rec in enumerate(records, 3):
46
+ values = [rec.get("code", ""), rec.get("name", ""), rec.get("row", ""), rec.get("col", ""),
47
+ rec.get("item", ""), rec.get("old", ""), rec.get("new", ""), rec.get("kind", "")]
48
+ for c, value in enumerate(values, 1):
49
+ cell = ws.cell(i, c, value)
50
+ cell.font = Font(name=FONT_NAME, size=FONT_SIZE)
51
+ cell.alignment = Alignment(horizontal="left", vertical="center", wrap_text=True)
52
+ widths = [8, 28, 6, 6, 24, 24, 24, 10]
53
+ for c, width in enumerate(widths, 1):
54
+ ws.column_dimensions[ws.cell(2, c).column_letter].width = width
55
+ ws.freeze_panes = "A3"
56
+ wb.save(str(target))
57
+ log(f"[留痕] 已导出改动清单:{target.name}({len(records)} 条)")
58
+ return target
@@ -0,0 +1,173 @@
1
+ """命令行入口:定义 export / bookmark / writeback 三个子命令与 main()。
2
+
3
+ 直接用包运行:``python -m wesync.cli <子命令> "<Word文件.docx>"``;
4
+ 中文入口脚本(1-导出表格到Excel.py 等)通过 ``base_dir`` 启用“自动识别同目录唯一 docx”。
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import argparse
10
+ import sys
11
+ from pathlib import Path
12
+
13
+ from .commands.blank_cmd import cmd_blank_tables
14
+ from .commands.bookmark_cmd import cmd_bookmark
15
+ from .commands.clear_cmd import cmd_clear_bookmarks
16
+ from .commands.export_cmd import cmd_export, cmd_rejudge
17
+ from .commands.marks_cmd import cmd_marks, cmd_marks_sync
18
+ from .commands.placeholders_cmd import cmd_placeholders, cmd_placeholders_sync
19
+ from .commands.writeback_cmd import cmd_writeback
20
+ from .console import USAGE_HINT
21
+ from .errors import SyncError
22
+ from .fsops import fill_docx_argument
23
+
24
+
25
+ def cmd_writeback_content(args) -> int:
26
+ """writeback 子命令:勾选了标注/占位符时走内容编排,否则保持原回写命令。"""
27
+ if not (args.with_marks or args.with_placeholders):
28
+ return cmd_writeback(args)
29
+ from . import api
30
+
31
+ api.run_sync_content(
32
+ args.docx,
33
+ args.excel,
34
+ tables=True,
35
+ marks=args.with_marks,
36
+ placeholders=args.with_placeholders,
37
+ keep_highlight=args.keep_highlight,
38
+ dry_run=args.dry_run,
39
+ force=args.force,
40
+ backup=True,
41
+ delete_empty_rows=args.delete_empty_rows,
42
+ )
43
+ return 0
44
+
45
+
46
+ def build_parser() -> argparse.ArgumentParser:
47
+ parser = argparse.ArgumentParser(
48
+ prog="word_excel_sync.py",
49
+ description="Word 表格 ⇄ Excel 双向同步工具(导出、书签定位、回写)",
50
+ formatter_class=argparse.RawDescriptionHelpFormatter,
51
+ )
52
+ sub = parser.add_subparsers(dest="command", required=True)
53
+
54
+ export_parser = sub.add_parser("export", help="导出 Word 全部表格到 Excel,并创建/归一化书签")
55
+ export_parser.add_argument("docx", help="Word 文件路径(.docx)")
56
+ export_parser.add_argument("--excel", help="输出工作簿路径,默认同目录 <主名>_表格数据.xlsx")
57
+ export_parser.add_argument("--no-excel-links", action="store_true", help="不在 Excel 中写“→定位Word表”跳转链接")
58
+ export_parser.add_argument("--no-total-formulas", action="store_true", help="合计行不写求和公式(默认写 =SUM,改明细后合计自动更新)")
59
+ export_parser.add_argument("--no-backup", dest="backup", action="store_false", default=True, help="覆盖前不备份原工作簿/Word 到 _backup(默认备份)")
60
+ export_parser.add_argument("--dry-run", action="store_true", help="只显示将导出的内容,不写文件")
61
+ export_parser.add_argument("--force", action="store_true", help="跳过文件占用检查,强制尝试写入")
62
+ export_parser.set_defaults(func=cmd_export)
63
+
64
+ rejudge_parser = sub.add_parser("rejudge", help="按工作簿当前内容重新判定 B 列表头/✓/✕(只改标记,不改数据)")
65
+ rejudge_parser.add_argument("docx", help="Word 文件路径(.docx,用于定位默认工作簿)")
66
+ rejudge_parser.add_argument("--excel", help="工作簿路径,默认同目录 <主名>_表格数据.xlsx")
67
+ rejudge_parser.add_argument("--no-backup", dest="backup", action="store_false", default=True, help="覆盖前不备份原工作簿到 _backup(默认备份)")
68
+ rejudge_parser.add_argument("--dry-run", action="store_true", help="只显示将变化的标记行数,不写文件")
69
+ rejudge_parser.add_argument("--force", action="store_true", help="跳过文件占用检查,强制尝试写入")
70
+ rejudge_parser.set_defaults(func=cmd_rejudge)
71
+
72
+ bookmark_parser = sub.add_parser("bookmark", help="只重建/迁移 Word 书签并清理遗留文字,不动数据")
73
+ bookmark_parser.add_argument("docx", help="Word 文件路径(.docx)")
74
+ bookmark_parser.add_argument("--excel", help="工作簿路径,默认同目录 <主名>_表格数据.xlsx")
75
+ bookmark_parser.add_argument("--no-excel-links", action="store_true", help="不在 Excel 中写“→定位Word表”跳转链接")
76
+ bookmark_parser.add_argument("--dry-run", action="store_true", help="只显示将处理的内容,不写文件")
77
+ bookmark_parser.add_argument("--force", action="store_true", help="跳过文件占用检查,强制尝试写入")
78
+ bookmark_parser.set_defaults(func=cmd_bookmark)
79
+
80
+ writeback_parser = sub.add_parser("writeback", help="把 Excel 的改动(含增删行、增删列)回写到 Word")
81
+ writeback_parser.add_argument("docx", help="Word 文件路径(.docx)")
82
+ writeback_parser.add_argument("--excel", help="工作簿路径,默认同目录 <主名>_表格数据.xlsx")
83
+ writeback_parser.add_argument("--dry-run", action="store_true", help="只显示将回写的改动,不写文件")
84
+ writeback_parser.add_argument("--force", action="store_true", help="跳过文件占用检查,强制尝试写入")
85
+ writeback_parser.add_argument("--delete-empty-rows", action="store_true", help="把 B 列标记为✕的行连 Word 行一起删除(Excel 保留为「已删」,改回✓可恢复)")
86
+ writeback_parser.add_argument("--with-marks", action="store_true", help="同时同步「链接标注」内容(默认只同步表格)")
87
+ writeback_parser.add_argument("--with-placeholders", action="store_true", help="同时按「正文信息」表替换 Word 的 {字段名} 占位符(默认只同步表格)")
88
+ writeback_parser.add_argument("--keep-highlight", action="store_true", help="同步标注后保留高亮(默认去色;仅 --with-marks 时有意义)")
89
+ writeback_parser.set_defaults(func=cmd_writeback_content)
90
+
91
+ marks_parser = sub.add_parser("marks", help="把 Word 里的高亮标记导出/刷新到工作表的「链接标注」页")
92
+ marks_parser.add_argument("docx", help="Word 文件路径(.docx)")
93
+ marks_parser.add_argument("--excel", help="工作簿路径,默认同目录 <主名>_表格数据.xlsx")
94
+ marks_parser.add_argument("--dry-run", action="store_true", help="只显示将导出的标记,不写文件")
95
+ marks_parser.add_argument("--force", action="store_true", help="跳过文件占用检查,强制尝试写入")
96
+ marks_parser.set_defaults(func=cmd_marks)
97
+
98
+ marks_sync_parser = sub.add_parser("marks-sync", help="把「链接标注」页里填写的内容同步回 Word")
99
+ marks_sync_parser.add_argument("docx", help="Word 文件路径(.docx)")
100
+ marks_sync_parser.add_argument("--excel", help="工作簿路径,默认同目录 <主名>_表格数据.xlsx")
101
+ marks_sync_parser.add_argument(
102
+ "--keep-highlight", action="store_true", help="同步后保留该处高亮(默认同步后自动去色)"
103
+ )
104
+ marks_sync_parser.add_argument("--dry-run", action="store_true", help="只显示将同步的改动,不写文件")
105
+ marks_sync_parser.add_argument("--force", action="store_true", help="跳过文件占用检查,强制尝试写入")
106
+ marks_sync_parser.set_defaults(func=cmd_marks_sync)
107
+
108
+ ph_parser = sub.add_parser("placeholders", help="按 Word 的 {字段名} 给工作簿「正文信息」表补齐填写骨架(保留已填值)")
109
+ ph_parser.add_argument("docx", help="Word 文件路径(.docx)")
110
+ ph_parser.add_argument("--excel", help="工作簿路径,默认同目录 <主名>_表格数据.xlsx")
111
+ ph_parser.add_argument("--dry-run", action="store_true", help="只显示将补齐的字段,不写文件")
112
+ ph_parser.add_argument("--force", action="store_true", help="跳过文件占用检查,强制尝试写入")
113
+ ph_parser.set_defaults(func=cmd_placeholders)
114
+
115
+ ph_sync_parser = sub.add_parser("placeholders-sync", help="把「正文信息」表填好的值写回 Word 占位符(未填保留原样并警告)")
116
+ ph_sync_parser.add_argument("docx", help="Word 文件路径(.docx)")
117
+ ph_sync_parser.add_argument("--excel", help="工作簿路径,默认同目录 <主名>_表格数据.xlsx")
118
+ ph_sync_parser.add_argument("--dry-run", action="store_true", help="只显示将替换的占位符,不写文件")
119
+ ph_sync_parser.add_argument("--force", action="store_true", help="跳过文件占用检查,强制尝试写入")
120
+ ph_sync_parser.set_defaults(func=cmd_placeholders_sync)
121
+
122
+ blank_parser = sub.add_parser("blank", help="删除 Word 里的空白表格(整表全空/仅表头有字),可连表标题一起删")
123
+ blank_parser.add_argument("docx", help="Word 文件路径(.docx)")
124
+ blank_parser.add_argument("--pick", help="要删除的候选编号,逗号分隔,如 1,3(编号见扫描清单)")
125
+ blank_parser.add_argument("--all", action="store_true", help="删除全部候选空白表")
126
+ blank_parser.add_argument("--keep-caption", action="store_true", help="只删表格,保留表标题段落")
127
+ blank_parser.add_argument("--reversible", action="store_true", help="可逆删除:Excel 表块保留并标记,可随时恢复")
128
+ blank_parser.add_argument("--restore", help="恢复已可逆删除的表:删除清单编号(逗号分隔)或 all")
129
+ blank_parser.add_argument("--excel", help="工作簿路径(默认同目录 <主名>_表格数据.xlsx)")
130
+ blank_parser.add_argument("--dry-run", action="store_true", help="只列出候选空白表,不写文件")
131
+ blank_parser.add_argument("--force", action="store_true", help="跳过文件占用检查,强制尝试写入")
132
+ blank_parser.set_defaults(func=cmd_blank_tables)
133
+
134
+ clear_parser = sub.add_parser("clear-bookmarks", help="删除 Word 里所有本工具书签(CPAH_/TBL_/MRK_),保留自带书签")
135
+ clear_parser.add_argument("docx", help="Word 文件路径(.docx)")
136
+ clear_parser.add_argument("--dry-run", action="store_true", help="只显示将删除哪些书签,不写文件")
137
+ clear_parser.add_argument("--force", action="store_true", help="跳过文件占用检查,强制尝试写入")
138
+ clear_parser.set_defaults(func=cmd_clear_bookmarks)
139
+
140
+ return parser
141
+
142
+
143
+ def main(argv: list[str] | None = None, base_dir: Path | None = None) -> int:
144
+ """运行入口。
145
+
146
+ base_dir 不为 None 时(中文入口脚本使用),若没有显式给出 Word 文件,
147
+ 会自动使用该目录下唯一的 .docx;给出多个或没有时打印中文提示并退出。
148
+ """
149
+ try:
150
+ sys.stdout.reconfigure(encoding="utf-8") # type: ignore[attr-defined]
151
+ except Exception:
152
+ pass
153
+ arguments = list(sys.argv[1:] if argv is None else argv)
154
+ if not arguments:
155
+ print(USAGE_HINT, flush=True)
156
+ return 2
157
+ subcommand, rest = arguments[0], arguments[1:]
158
+ try:
159
+ if base_dir is not None and not any(item in ("-h", "--help") for item in rest):
160
+ rest = fill_docx_argument(rest, base_dir)
161
+ parser = build_parser()
162
+ args = parser.parse_args([subcommand, *rest])
163
+ return args.func(args)
164
+ except SyncError as exc:
165
+ print(f"错误:{exc}", file=sys.stderr, flush=True)
166
+ return 2
167
+ except FileNotFoundError as exc:
168
+ print(f"错误:找不到文件或路径不可用({exc})", file=sys.stderr, flush=True)
169
+ return 2
170
+
171
+
172
+ if __name__ == "__main__":
173
+ raise SystemExit(main())
@@ -0,0 +1,8 @@
1
+ """子命令实现集合:export(导出)/ bookmark(书签)/ writeback(回写)。"""
2
+
3
+ from .bookmark_cmd import cmd_bookmark
4
+ from .export_cmd import cmd_export
5
+ from .marks_cmd import cmd_marks, cmd_marks_sync
6
+ from .writeback_cmd import cmd_writeback
7
+
8
+ __all__ = ["cmd_export", "cmd_bookmark", "cmd_writeback", "cmd_marks", "cmd_marks_sync"]
@@ -0,0 +1,250 @@
1
+ """blank 子命令:删除 Word 里的空白表格(整表全空 / 仅表头有字),可连表标题一起删。
2
+
3
+ 默认只扫描列出候选,不删任何内容;用 --pick 1,3 或 --all 明确选择后才删除。
4
+ 正式删除前自动备份原文件到 _backup。
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from copy import copy
10
+
11
+ import docx
12
+
13
+ from ..config import DELETED_BOOKMARK, NEW_BOOKMARK, SHEET_NAME
14
+ from ..console import log
15
+ from ..docx_blank import delete_blank_tables, find_blank_tables
16
+ from ..docx_bookmarks import table_index_map_by_bookmark
17
+ from ..errors import SyncError
18
+ from ..excel_blocks import parse_blocks
19
+ from ..fsops import backup_file, check_file_free, load_workbook_for_save, resolve_docx, resolve_xlsx
20
+
21
+
22
+ def _parse_pick(text: str, count: int) -> list[int]:
23
+ nos: list[int] = []
24
+ for part in text.split(","):
25
+ part = part.strip()
26
+ if not part:
27
+ continue
28
+ if not part.isdigit() or not 1 <= int(part) <= count:
29
+ raise SyncError(f"候选编号无效:{part}(应为 1~{count} 的数字,逗号分隔)")
30
+ no = int(part)
31
+ if no not in nos:
32
+ nos.append(no)
33
+ if not nos:
34
+ raise SyncError("--pick 未给出有效编号,例如 --pick 1,3")
35
+ return nos
36
+
37
+
38
+ def _plan_reversible(doc, xlsx_path, selected, force=False):
39
+ """可逆删除前的准备:找到每个候选对应的工作簿表块与原位置锚点。"""
40
+ if not xlsx_path.exists():
41
+ raise SyncError("可逆删除需要工作簿来保留表块:请先执行「导出表格到 Excel」生成工作簿。")
42
+ check_file_free(xlsx_path, force)
43
+ wb = load_workbook_for_save(xlsx_path)
44
+ if SHEET_NAME not in wb.sheetnames:
45
+ raise SyncError(f"工作簿中找不到工作表“{SHEET_NAME}”,请先重新执行「导出表格到 Excel」。")
46
+ ws = wb[SHEET_NAME]
47
+ _, blocks = parse_blocks(ws)
48
+ name_to_code = {
49
+ block["bookmark"]: code
50
+ for code, block in blocks.items()
51
+ if block.get("bookmark") and block["bookmark"] not in (NEW_BOOKMARK, DELETED_BOOKMARK)
52
+ }
53
+ index_map = table_index_map_by_bookmark(doc, set(name_to_code))
54
+ index_to_name = {index: name for name, index in index_map.items()}
55
+ sel_indices = {cand["index"] for cand, _ in selected}
56
+ plans = []
57
+ for cand, with_caption in selected:
58
+ code = name_to_code.get(index_to_name.get(cand["index"], ""))
59
+ if not code:
60
+ raise SyncError(
61
+ f"候选{cand['no']} 在工作簿中找不到对应表块(可能未导出或已重建),请先重新执行「导出表格到 Excel」。"
62
+ )
63
+ prev_name = ""
64
+ for i in range(cand["index"] - 1, -1, -1):
65
+ if i not in sel_indices and i in index_to_name:
66
+ prev_name = index_to_name[i]
67
+ break
68
+ plans.append((cand, with_caption, code, prev_name))
69
+ return wb, ws, blocks, plans
70
+
71
+
72
+ def _mark_deleted_blocks(wb, ws, blocks, plans, xlsx_path) -> None:
73
+ """Word 删表后,把工作簿对应表块标记为「已删除」并记录原位置与原标题。"""
74
+ for cand, with_caption, code, prev_name in plans:
75
+ row = blocks[code]["anchor_row"]
76
+ col0 = blocks[code].get("col0", 2)
77
+ ws.cell(row, col0 + 1, f"书签:{DELETED_BOOKMARK}")
78
+ link = ws.cell(row, col0 + 2)
79
+ link.value = None
80
+ link.hyperlink = None
81
+ ws.cell(row, col0 + 4, f"原位置:{prev_name}之后" if prev_name else "原位置:文档末尾")
82
+ caption = cand["caption_text"] if with_caption and cand["caption_p"] is not None else ""
83
+ ws.cell(row, col0 + 5, f"原标题:{caption}" if caption else None)
84
+ anchor_style = ws.cell(row, col0 + 1)._style
85
+ for col in (col0 + 4, col0 + 5):
86
+ 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
+
94
+
95
+ def cmd_blank_tables(args) -> int:
96
+ if getattr(args, "restore", None):
97
+ return cmd_restore_tables(args)
98
+ docx_path = resolve_docx(args.docx)
99
+ doc = docx.Document(str(docx_path))
100
+ candidates = find_blank_tables(doc)
101
+
102
+ log(f"读取 Word:{docx_path.name}")
103
+ if not candidates:
104
+ log("[空白表] 未发现空白表格(整表全空或仅表头有字),无需处理")
105
+ return 0
106
+ log(f"[空白表] 发现候选空白表:{len(candidates)} 张")
107
+ for cand in candidates:
108
+ caption = f",表标题:{cand['caption_text']}" if cand["caption_text"] else ",未识别到表标题"
109
+ log(f" [候选{cand['no']}] {cand['code']}({cand['kind']},{cand['nrows']}行×{cand['ncols']}列){caption}")
110
+
111
+ if args.dry_run:
112
+ log("预演模式(--dry-run):未写入任何文件。删除请用 --pick 编号 或 --all。")
113
+ return 0
114
+
115
+ pick_text = getattr(args, "pick", None)
116
+ if getattr(args, "all", False):
117
+ nos = [cand["no"] for cand in candidates]
118
+ elif pick_text:
119
+ nos = _parse_pick(pick_text, len(candidates))
120
+ else:
121
+ log("[空白表] 未指定要删除的候选,本次未改动文件。")
122
+ log(" 删除示例:--pick 1,3(按候选编号)或 --all(全部);只删表格保留标题加 --keep-caption")
123
+ return 0
124
+
125
+ keep_all = bool(getattr(args, "keep_caption", False))
126
+ keep_nos = set()
127
+ keep_for = getattr(args, "keep_caption_for", None)
128
+ if keep_for:
129
+ keep_nos = set(_parse_pick(keep_for, len(candidates)))
130
+ selected = [
131
+ (cand, not keep_all and cand["no"] not in keep_nos and cand["caption_p"] is not None)
132
+ for cand in candidates
133
+ if cand["no"] in nos
134
+ ]
135
+
136
+ check_file_free(docx_path, args.force)
137
+ reversible = bool(getattr(args, "reversible", False))
138
+ xlsx_path = resolve_xlsx(docx_path, getattr(args, "excel", None))
139
+ prepared = _plan_reversible(doc, xlsx_path, selected, args.force) if reversible else None
140
+ result = delete_blank_tables(doc, selected)
141
+ backup = backup_file(docx_path)
142
+ doc.save(str(docx_path))
143
+ log(
144
+ f"[空白表] 已删除 {result['tables']} 张空白表、{result['captions']} 个表标题"
145
+ + (f"(原文件已备份:{backup.name})" if backup else "")
146
+ )
147
+ if result["bookmarks"]:
148
+ log(f"[空白表] 顺带清理失去配对的定位书签端点 {result['bookmarks']} 个")
149
+ if reversible:
150
+ wb, ws, blocks, plans = prepared
151
+ _mark_deleted_blocks(wb, ws, blocks, plans, xlsx_path)
152
+ log("[可逆] Excel 表块已保留;要恢复时在「删除空白表格」页勾选恢复,或命令行 --restore 编号。")
153
+ else:
154
+ log("[空白表] 表格有删减,请重新执行「1-导出表格到Excel」重建工作簿,再做同步。")
155
+ return 0
156
+
157
+
158
+ def cmd_restore_tables(args) -> int:
159
+ """恢复已可逆删除的表:按工作簿保留的表块在原位置重建 Word 表格。"""
160
+ from ..docx_bookmarks import bookmark_names, insert_table_bookmark, new_cpah_name, next_bookmark_id
161
+ from ..docx_grid import body_items
162
+ from ..docx_meta import collect_table_info
163
+ from ..docx_newtable import available_width_dxa, build_table, col_widths_from_excel, insert_new_table
164
+ from ..excel_blocks import block_merges, refresh_anchor_metadata, refresh_defined_names
165
+ from ..valuefmt import formula_map
166
+ from .writeback_cmd import _block_label, _new_table_grid
167
+
168
+ docx_path = resolve_docx(args.docx)
169
+ xlsx_path = resolve_xlsx(docx_path, getattr(args, "excel", None))
170
+ if not xlsx_path.exists():
171
+ raise SyncError(f"找不到工作簿:{xlsx_path}\n恢复需要工作簿里保留的表块。")
172
+ doc = docx.Document(str(docx_path))
173
+ wb = load_workbook_for_save(xlsx_path)
174
+ if SHEET_NAME not in wb.sheetnames:
175
+ raise SyncError(f"工作簿中找不到工作表“{SHEET_NAME}”,请确认该文件由本工具导出")
176
+ ws = wb[SHEET_NAME]
177
+ order, blocks = parse_blocks(ws)
178
+ deleted = [code for code in order if blocks[code].get("bookmark") == DELETED_BOOKMARK]
179
+ log(f"读取 Word:{docx_path.name}")
180
+ if not deleted:
181
+ log("[恢复] 工作簿中没有「已删除」标记的表块,无需恢复")
182
+ return 0
183
+ log(f"[恢复] 可恢复的表块:{len(deleted)} 个")
184
+ for no, code in enumerate(deleted, 1):
185
+ block = blocks[code]
186
+ meta = block.get("meta", {})
187
+ pos = meta.get("restore_after") or "末尾"
188
+ log(f" [{no}] {code} {_block_label(block)}({len(block['grid_rows'])}行×{block['ncols']}列,原位置:{pos})")
189
+
190
+ restore_arg = str(args.restore).strip()
191
+ if restore_arg.lower() == "all":
192
+ nos = list(range(1, len(deleted) + 1))
193
+ else:
194
+ nos = _parse_pick(restore_arg, len(deleted))
195
+ if args.dry_run:
196
+ log(f"预演模式(--dry-run):将恢复 {len(nos)} 张表,未写入任何文件。")
197
+ return 0
198
+
199
+ check_file_free(docx_path, args.force)
200
+ check_file_free(xlsx_path, args.force)
201
+ cached = formula_map(xlsx_path)
202
+ existing_names = bookmark_names(doc.element.body)
203
+ bookmark_id = next_bookmark_id(doc)
204
+ total_dxa = available_width_dxa(doc)
205
+ real_names = {
206
+ blocks[c]["bookmark"] for c in order
207
+ if blocks[c].get("bookmark") and blocks[c]["bookmark"] not in (NEW_BOOKMARK, DELETED_BOOKMARK)
208
+ }
209
+ index_map = table_index_map_by_bookmark(doc, real_names)
210
+ restored: dict[str, tuple] = {}
211
+ for no in nos:
212
+ code = deleted[no - 1]
213
+ block = blocks[code]
214
+ if not block["grid_rows"]:
215
+ raise SyncError(f"{code}:表块没有网格行,无法恢复")
216
+ 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)
220
+ tbl = build_table(grid, merges, block["ncols"], widths)
221
+ anchor = meta.get("restore_after") or ""
222
+ prev_tbl = None
223
+ if anchor and anchor != "末尾" and anchor in index_map:
224
+ prev_tbl = doc.tables[index_map[anchor]]._tbl
225
+ elif anchor and anchor != "末尾":
226
+ log(f"[提醒] {code} 原位置的锚点表已不在 Word 中,恢复到文档末尾")
227
+ caption = meta.get("caption") or _block_label(block, limit=60) or code
228
+ insert_new_table(doc, prev_tbl, tbl, caption)
229
+ bookmark = new_cpah_name(existing_names)
230
+ existing_names.add(bookmark)
231
+ insert_table_bookmark(tbl, bookmark, bookmark_id)
232
+ bookmark_id += 1
233
+ restored[code] = (bookmark, tbl)
234
+ log(f"[恢复] {code} {caption}:已重建({len(grid)}行×{block['ncols']}列,书签 {bookmark})")
235
+
236
+ items = body_items(doc)
237
+ infos = [collect_table_info(doc, items, idx, tab) for idx, tab in enumerate(doc.tables)]
238
+ for code, (bookmark, tbl) in restored.items():
239
+ index = next(i for i, tab in enumerate(doc.tables) if tab._tbl is tbl)
240
+ info = {**infos[index], "bookmark": bookmark}
241
+ refresh_anchor_metadata(ws, blocks[code], info, docx_path.name, with_link=True, ncols=blocks[code]["ncols"])
242
+ refresh_defined_names(wb, {code: blocks[code] for code in restored})
243
+
244
+ docx_backup = backup_file(docx_path)
245
+ doc.save(str(docx_path))
246
+ 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
+ log(f"[恢复] 已保存 {xlsx_path.name}(表块标记已改回真实书签)" + (f"(原工作簿已备份:{xlsx_backup.name})" if xlsx_backup else ""))
250
+ return 0