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,115 @@
1
+ """bookmark 子命令:按内容把书签重新对齐到正确的表格,并把书签整表锚定。
2
+
3
+ 用法要点:
4
+ * 默认**修复**:用「列数+行数+首行+首列」内容签名把工作簿表块与 Word 表格 1:1 配对,
5
+ 然后把书签重建到对应表格内部(覆盖整张表),Excel 里点“→定位Word表”会选中整张表。
6
+ * 只接受完全一致的签名,不做模糊猜测;对不上的表会列为“未对齐”。
7
+ * 只删除“本工具自己的书签”(名字记录在工作簿 C 列里的,以及早期的 TBL_*),
8
+ 审计软件的书签与 `_Toc…` 一律不动。
9
+ """
10
+
11
+ import docx
12
+ from openpyxl import load_workbook
13
+
14
+ from ..align import apply_table_bookmarks, plan_table_bookmarks, split_bookmark_updates
15
+ from ..config import EXCEL_LINK_TEXT, SHEET_NAME
16
+ from ..console import log
17
+ from ..docx_bookmarks import cleanup_excel_markers
18
+ from ..docx_grid import body_items
19
+ from ..docx_meta import collect_table_info, dedupe_table_names
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
23
+
24
+
25
+ def _short_list(codes: list[str], limit: int = 12) -> str:
26
+ shown = "、".join(codes[:limit])
27
+ return shown + ("…" if len(codes) > limit else "")
28
+
29
+
30
+ def cmd_bookmark(args) -> int:
31
+ docx_path = resolve_docx(args.docx)
32
+ xlsx_path = resolve_xlsx(docx_path, args.excel)
33
+ if not args.dry_run:
34
+ check_file_free(docx_path, args.force)
35
+ if xlsx_path.exists():
36
+ check_file_free(xlsx_path, args.force)
37
+
38
+ doc = docx.Document(str(docx_path))
39
+ if not doc.tables:
40
+ raise SyncError("Word 文档中没有任何表格,无需处理")
41
+ items = body_items(doc)
42
+ infos = [collect_table_info(doc, items, idx, tab) for idx, tab in enumerate(doc.tables)]
43
+ dedupe_table_names(infos)
44
+ recorded = read_recorded_bookmarks(xlsx_path)
45
+
46
+ ws = None
47
+ blocks: dict = {}
48
+ if xlsx_path.exists():
49
+ workbook = load_workbook(str(xlsx_path))
50
+ if SHEET_NAME in workbook.sheetnames:
51
+ ws = workbook[SHEET_NAME]
52
+ _, blocks = parse_blocks(ws)
53
+
54
+ plan = plan_table_bookmarks(doc, ws, blocks, recorded, name_unmatched=not blocks)
55
+ code_by_index = {index: code for code, index in plan["mapping"].items()}
56
+
57
+ log(f"读取 Word:{docx_path.name}({len(doc.tables)} 张表)")
58
+ if blocks:
59
+ log(f"读取 Excel:{xlsx_path.name}(工作表:{SHEET_NAME},{len(blocks)} 个表块)")
60
+ else:
61
+ log("未找到可用工作簿:将为每张表新建书签。")
62
+
63
+ for index, name in sorted(plan["assignments"]):
64
+ code = code_by_index.get(index, "(新表)")
65
+ log(f"[对齐] 第 {index + 1} 张表 ↔ {code}(书签 {name})")
66
+ for index in plan["unmatched_tables"]:
67
+ if code_by_index: # 有工作簿时才提示“未对齐”
68
+ log(f"[未对齐] 第 {index + 1} 张表:内容与任何表块都不匹配(建议重新导出工作簿)")
69
+ if plan["unmatched_codes"]:
70
+ log(
71
+ f"[提示] {len(plan['unmatched_codes'])} 个表块在 Word 中已删除,不会被同步:"
72
+ f"{_short_list(plan['unmatched_codes'])}"
73
+ )
74
+
75
+ if args.dry_run:
76
+ log("预演模式(--dry-run):以上为将执行的书签对齐,未写入任何文件。")
77
+ return 0
78
+
79
+ # 已经正确锚定在目标表内的书签不必重建(保证重复运行幂等)
80
+ assignments, remove_names = split_bookmark_updates(doc, plan["assignments"], recorded)
81
+ result = apply_table_bookmarks(doc, assignments, remove_names)
82
+ if result["removed"]:
83
+ log(f"[书签] 已移除旧的/锚错的工具书签 {result['removed']} 个")
84
+ if result["inserted"]:
85
+ log(f"[书签] 已把 {result['inserted']} 个书签整表锚定(点击可选中整张表格)")
86
+ if not result["removed"] and not result["inserted"]:
87
+ log("[书签] 书签已全部正确锚定,无需重建")
88
+
89
+ markers = cleanup_excel_markers(doc)
90
+ if markers:
91
+ log(f"[清理] 已删除 Word 正文中遗留的 {markers} 处 {EXCEL_LINK_TEXT} 文字/断链")
92
+
93
+ if result["removed"] or result["inserted"] or markers:
94
+ backup = backup_file(docx_path)
95
+ doc.save(str(docx_path))
96
+ log(f"[书签] 已保存 {docx_path.name}" + (f"(原文件已备份:{backup.name})" if backup else ""))
97
+ else:
98
+ log("[书签] Word 已是目标状态,无需保存")
99
+
100
+ if ws is not None and blocks:
101
+ name_by_index = {index: name for index, name in plan["assignments"]}
102
+ infos_by_code: dict[str, dict] = {}
103
+ for code, index in plan["mapping"].items():
104
+ info = dict(infos[index]) if index < len(infos) else None
105
+ if info is None:
106
+ continue
107
+ info["bookmark"] = name_by_index.get(index, "")
108
+ infos_by_code[code] = info
109
+ refresh_workbook_metadata(
110
+ xlsx_path,
111
+ docx_path.name,
112
+ infos_by_code,
113
+ with_links=not getattr(args, "no_excel_links", False),
114
+ )
115
+ return 0
@@ -0,0 +1,48 @@
1
+ """clear-bookmarks 子命令:删除 Word 里所有本工具写入的书签(CPAH_/TBL_/MRK_)。
2
+
3
+ 只清本工具自己创建的定位/标注书签;Word 自带书签(如 _Toc 目录)一律保留。
4
+ 正式执行前自动备份原文件到 _backup。
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import docx
10
+
11
+ from ..console import log
12
+ from ..docx_bookmarks import clear_tool_bookmarks
13
+ from ..fsops import backup_file, check_file_free, resolve_docx
14
+
15
+
16
+ def cmd_clear_bookmarks(args) -> int:
17
+ docx_path = resolve_docx(args.docx)
18
+ if not args.dry_run:
19
+ check_file_free(docx_path, args.force)
20
+
21
+ doc = docx.Document(str(docx_path))
22
+ result = clear_tool_bookmarks(doc)
23
+
24
+ log(f"读取 Word:{docx_path.name}")
25
+ log(f"[清理] 发现本工具书签(CPAH_/TBL_/MRK_):{result['removed']} 个")
26
+ if result["names"]:
27
+ shown = "、".join(result["names"][:12])
28
+ if len(result["names"]) > 12:
29
+ shown += f" …(共 {len(result['names'])} 个)"
30
+ log(f"[清理] 将删除:{shown}")
31
+ if result["kept"]:
32
+ log(f"[清理] 保留 Word 自带书签 {result['kept']} 个(如 _Toc 目录书签),未改动")
33
+
34
+ if not result["removed"]:
35
+ log("[清理] 没有发现本工具书签,无需处理")
36
+ return 0
37
+
38
+ if args.dry_run:
39
+ log("预演模式(--dry-run):未写入任何文件。")
40
+ return 0
41
+
42
+ backup = backup_file(docx_path)
43
+ doc.save(str(docx_path))
44
+ log(
45
+ f"[清理] 已从 {docx_path.name} 删除 {result['removed']} 个书签"
46
+ + (f"(原文件已备份:{backup.name})" if backup else "")
47
+ )
48
+ return 0
@@ -0,0 +1,220 @@
1
+ """export 子命令:按当前 Word 重新生成工作簿,并把书签整表锚定。
2
+
3
+ 导出时会先按内容把现有工作簿的表块与当前 Word 表格对齐,沿用原有的书签名
4
+ (对不上的块/表会自动报告),然后把书签重建到表格内部(覆盖整张表)。
5
+ """
6
+
7
+ import docx
8
+ from openpyxl import load_workbook
9
+
10
+ from ..align import apply_table_bookmarks, plan_table_bookmarks, split_bookmark_updates
11
+ from ..config import DELETED_BOOKMARK, EXCEL_LINK_TEXT, NEW_BOOKMARK, SHEET_NAME
12
+ from ..console import log
13
+ from ..docx_bookmarks import cleanup_excel_markers
14
+ from ..docx_grid import body_items
15
+ from ..docx_marks import ensure_mark_bookmarks, find_marks, processed_marks
16
+ from ..docx_meta import collect_table_info, dedupe_table_names
17
+ from ..docx_placeholders import VALUES_SHEET, init_placeholder_sheet, read_placeholder_values, scan_placeholders
18
+ from ..errors import SyncError
19
+ from ..excel_blocks import carry_over_deleted_blocks, parse_blocks, read_recorded_bookmarks, rejudge_marks
20
+ from ..excel_export import export_workbook
21
+ from ..excel_marks import SHEET_MARKS, build_marks_sheet, read_previous_marks
22
+ from ..fsops import backup_file, check_file_free, load_workbook_for_save, resolve_docx, resolve_xlsx
23
+
24
+
25
+ def _code_number(code: str) -> int:
26
+ try:
27
+ return int(code[1:])
28
+ except ValueError:
29
+ return 0
30
+
31
+
32
+ def _removed_block_hints(xlsx_path, recorded: dict[str, str], blocks_old: dict, plan: dict) -> list[str]:
33
+ """导出前提醒:现有工作簿里有块在 Word 中已找不到对应表格(按实际对齐结果判断)。"""
34
+ if not recorded:
35
+ if xlsx_path.exists():
36
+ return ["[提醒] 现有工作簿没有书签记录,本次导出将按当前 Word 重建并重新登记书签。"]
37
+ return []
38
+ missing = sorted(
39
+ (
40
+ code for code in plan["unmatched_codes"]
41
+ if (blocks_old.get(code) or {}).get("bookmark") != DELETED_BOOKMARK
42
+ ),
43
+ key=_code_number,
44
+ )
45
+ unnamed = sorted((code for code, name in recorded.items() if not name), key=_code_number)
46
+ hints: list[str] = []
47
+ if missing:
48
+ shown = "、".join(missing[:8]) + ("…" if len(missing) > 8 else "")
49
+ hints.append(
50
+ f"[提醒] 现有工作簿中有 {len(missing)} 个表块在 Word 中已找不到对应表格"
51
+ f"(可能是已删除的表:{shown});导出将按当前 Word 重建,这些块会消失。"
52
+ )
53
+ if unnamed:
54
+ hints.append(f"[提醒] 现有工作簿中有 {len(unnamed)} 个表块没有书签记录,导出后将重新登记书签。")
55
+ return hints
56
+
57
+
58
+ def _load_previous_workbook(xlsx_path):
59
+ """读取现有工作簿(表块 + 工作表),用于沿用书签名;不存在或读不了时返回 (None, {})。"""
60
+ if not xlsx_path.exists():
61
+ return None, {}
62
+ try:
63
+ workbook = load_workbook(str(xlsx_path))
64
+ except Exception as exc: # 文件被占用或损坏时不阻断导出
65
+ log(f"[提醒] 读取现有工作簿失败({exc}),本次不沿用旧书签名。")
66
+ return None, {}
67
+ if SHEET_NAME not in workbook.sheetnames:
68
+ return None, {}
69
+ ws = workbook[SHEET_NAME]
70
+ _, blocks = parse_blocks(ws)
71
+ return ws, blocks
72
+
73
+
74
+ def cmd_export(args) -> int:
75
+ docx_path = resolve_docx(args.docx)
76
+ xlsx_path = resolve_xlsx(docx_path, args.excel)
77
+ if not args.dry_run:
78
+ check_file_free(docx_path, args.force)
79
+ check_file_free(xlsx_path, args.force)
80
+
81
+ doc = docx.Document(str(docx_path))
82
+ items = body_items(doc)
83
+ infos = [collect_table_info(doc, items, idx, tab) for idx, tab in enumerate(doc.tables)]
84
+ dedupe_table_names(infos)
85
+ recorded = {
86
+ code: name
87
+ for code, name in read_recorded_bookmarks(xlsx_path).items()
88
+ if name not in (NEW_BOOKMARK, DELETED_BOOKMARK)
89
+ }
90
+ ws_old, blocks_old = _load_previous_workbook(xlsx_path)
91
+ previous_marks = read_previous_marks(xlsx_path)
92
+ marks = find_marks(doc)
93
+ processed = processed_marks(doc, {mark.bookmark for mark in marks if mark.bookmark})
94
+ ph_fields = scan_placeholders(doc)
95
+ ph_values_old = {}
96
+ if ph_fields and xlsx_path.exists():
97
+ try:
98
+ ph_values_old = read_placeholder_values(xlsx_path, resolve_formulas=False)
99
+ except Exception as exc: # 旧工作簿读不了时不影响导出,只是带不过来已填值
100
+ log(f"[提醒] 读取原「{VALUES_SHEET}」表失败({exc}),本次无法保留已填值。")
101
+
102
+ plan = plan_table_bookmarks(doc, ws_old, blocks_old, recorded, name_unmatched=True)
103
+ name_by_index = {index: name for index, name in plan["assignments"]}
104
+ for info in infos:
105
+ info["bookmark"] = name_by_index.get(info["index"], "")
106
+
107
+ log(f"读取 Word:{docx_path.name}")
108
+ log(f"发现表格:{len(infos)} 张" + ("(无表格,工作表「" + SHEET_NAME + "」将为空)" if not infos else ""))
109
+ with_links = not getattr(args, "no_excel_links", False)
110
+ for info in infos:
111
+ log(
112
+ f" {info['code']} {info['name']}({info['nrows']} 行 × {info['ncols']} 列,"
113
+ f"合并区 {sum(1 for m in info['merges'] if m[2] > 1 or m[3] > 1)} 处,书签 {info['bookmark']})"
114
+ )
115
+ log(f"目标工作簿:{xlsx_path.name}(工作表:{SHEET_NAME})")
116
+ log(f"高亮标记:{len(marks)} 处(将写入工作表「{SHEET_MARKS}」)")
117
+ if ph_fields:
118
+ log(f"正文占位符:{len(ph_fields)} 个(将写入工作表「{VALUES_SHEET}」)")
119
+ else:
120
+ log(f"正文占位符:未发现(工作表「{VALUES_SHEET}」将为空)")
121
+ for hint in _removed_block_hints(xlsx_path, recorded, blocks_old, plan):
122
+ log(hint)
123
+
124
+ if args.dry_run:
125
+ log("预演模式(--dry-run):以上为将导出的内容,未写入任何文件。")
126
+ return 0
127
+
128
+ assignments, remove_names = split_bookmark_updates(doc, plan["assignments"], recorded)
129
+ result = apply_table_bookmarks(doc, assignments, remove_names)
130
+ if result["inserted"]:
131
+ log(f"[书签] 已把 {result['inserted']} 个书签整表锚定(点击可选中整张表格)")
132
+ created_marks = ensure_mark_bookmarks(doc, marks)
133
+ if created_marks:
134
+ log(f"[标记] 已为 {created_marks} 处高亮标记插入定位书签(MRK_xxxx,正文外观不变)")
135
+ removed_markers = cleanup_excel_markers(doc)
136
+ if removed_markers:
137
+ log(f"[清理] 已删除 Word 正文中遗留的 {removed_markers} 处 {EXCEL_LINK_TEXT} 文字/断链")
138
+
139
+ workbook = export_workbook(
140
+ infos, docx_path.name, with_links=with_links,
141
+ totals_formula=not getattr(args, "no_total_formulas", False),
142
+ )
143
+ if ws_old is not None:
144
+ carried = carry_over_deleted_blocks(workbook, ws_old, blocks_old)
145
+ if carried:
146
+ log(f"[保留] 已可逆删除的 {len(carried)} 个表块原样保留({'、'.join(carried)}),可在「删除空白表格」页恢复。")
147
+ from ..sort_rules import carry_over_sort_settings
148
+
149
+ sort_carried = carry_over_sort_settings(workbook, ws_old, blocks_old)
150
+ if sort_carried:
151
+ log(f"[保留] {len(sort_carried)} 个表块的排序设置已按书签沿用({'、'.join(sort_carried)})。")
152
+ mark_stats = build_marks_sheet(workbook, docx_path.name, marks, previous_marks, processed)
153
+ log(
154
+ f"[标记] 工作表「{SHEET_MARKS}」已写入 {mark_stats['marks']} 行"
155
+ + (f",{mark_stats['processed']} 行已处理" if mark_stats.get("processed") else "")
156
+ + (f",另有 {mark_stats['orphans']} 行已删除记录" if mark_stats["orphans"] else "")
157
+ )
158
+ if ph_fields:
159
+ ws_ph = init_placeholder_sheet(workbook)
160
+ for field in ph_fields:
161
+ ws_ph.append([field, ph_values_old.get(field, "")])
162
+ kept = sum(1 for f in ph_fields if ph_values_old.get(f))
163
+ log(
164
+ f"[占位符] 工作表「{VALUES_SHEET}」已写入 {len(ph_fields)} 个字段"
165
+ + (f",保留已填值 {kept} 个" if kept else "(待填写)")
166
+ )
167
+ else:
168
+ init_placeholder_sheet(workbook)
169
+ log(f"[占位符] 正文无 {{字段名}},工作表「{VALUES_SHEET}」已创建为空表。")
170
+ backup = getattr(args, "backup", True)
171
+ if not backup:
172
+ log("[导出] 按选项不备份原文件(--no-backup / 界面取消勾选),直接覆盖。")
173
+ xlsx_backup = backup_file(xlsx_path) if backup else None
174
+ workbook.save(str(xlsx_path))
175
+ log(f"[导出] 已写入 {xlsx_path.name}" + (f"(原文件已备份:{xlsx_backup.name})" if xlsx_backup else ""))
176
+
177
+ if result["removed"] or result["inserted"] or created_marks or removed_markers:
178
+ docx_backup = backup_file(docx_path) if backup else None
179
+ doc.save(str(docx_path))
180
+ log(f"[导出] 已更新 {docx_path.name}" + (f"(原文件已备份:{docx_backup.name})" if docx_backup else ""))
181
+ else:
182
+ log("[导出] Word 中的书签已是目标状态,无需改动。")
183
+ return 0
184
+
185
+
186
+ def cmd_rejudge(args) -> int:
187
+ """按工作簿当前内容重新判定 B 列表头/✓/✕(只改标记,不改数据、不改 Word)。"""
188
+ docx_path = resolve_docx(args.docx)
189
+ xlsx_path = resolve_xlsx(docx_path, args.excel)
190
+ if not xlsx_path.exists():
191
+ raise SyncError(f"找不到工作簿:{xlsx_path}\n请先执行「导出表格到 Excel」。")
192
+ if not args.dry_run:
193
+ check_file_free(xlsx_path, args.force)
194
+ workbook = load_workbook_for_save(xlsx_path)
195
+ if SHEET_NAME not in workbook.sheetnames:
196
+ raise SyncError(f"工作簿中找不到工作表“{SHEET_NAME}”,请确认该文件由本工具导出")
197
+ ws = workbook[SHEET_NAME]
198
+ _, blocks = parse_blocks(ws)
199
+ if not blocks:
200
+ raise SyncError("工作簿中没有表块,请先执行「导出表格到 Excel」")
201
+ log(f"读取工作簿:{xlsx_path.name}(表块 {len(blocks)} 个)")
202
+ stats = rejudge_marks(ws, blocks)
203
+ if stats["old"]:
204
+ log(
205
+ f"[提醒] {'、'.join(stats['old'])} 为旧布局(没有标记列),无法重新判定;"
206
+ f"请执行一次「导出表格到 Excel」升级为新布局。"
207
+ )
208
+ prefix = "[判定·预演]" if args.dry_run else "[判定]"
209
+ log(f"{prefix} 重新判定 {stats['rows']} 行,标记变化 {stats['changed']} 行(表头/✓/✕;「已删」行保持原样)")
210
+ if args.dry_run:
211
+ log("预演模式(--dry-run):未写入任何文件。")
212
+ return 0
213
+ if not stats["changed"]:
214
+ log("标记与当前内容一致,工作簿无需写入。")
215
+ return 0
216
+ backup = getattr(args, "backup", True)
217
+ xlsx_backup = backup_file(xlsx_path) if backup else None
218
+ workbook.save(str(xlsx_path))
219
+ log(f"[判定] 已保存 {xlsx_path.name}" + (f"(原文件已备份:{xlsx_backup.name})" if xlsx_backup else ""))
220
+ return 0
@@ -0,0 +1,152 @@
1
+ """marks / marks-sync 子命令:高亮标记导出到「链接标注」工作表,并把填写内容同步回 Word。"""
2
+
3
+ import docx
4
+ from openpyxl import load_workbook
5
+
6
+ from ..console import log, warn
7
+ from ..docx_marks import (
8
+ apply_mark_change,
9
+ ensure_mark_bookmarks,
10
+ find_marks,
11
+ mark_payload_by_bookmark,
12
+ processed_marks,
13
+ )
14
+ from ..errors import SyncError
15
+ from ..excel_marks import SHEET_MARKS, build_marks_sheet, parse_marks_rows, read_previous_marks
16
+ from ..fsops import backup_file, check_file_free, load_workbook_for_save, resolve_docx, resolve_xlsx
17
+
18
+
19
+ def _mark_label(bookmark: str, fallback: str) -> str:
20
+ return bookmark or fallback
21
+
22
+
23
+ def cmd_marks(args) -> int:
24
+ """刷新工作簿里的「链接标注」工作表(不动表格数据,不改 Word 文字)。"""
25
+ docx_path = resolve_docx(args.docx)
26
+ xlsx_path = resolve_xlsx(docx_path, args.excel)
27
+ if not xlsx_path.exists():
28
+ raise SyncError(
29
+ f"找不到工作簿:{xlsx_path}\n请先执行「导出表格到 Excel」(或界面上的“导出/刷新标注”会自动先导出)。"
30
+ )
31
+ if not args.dry_run:
32
+ check_file_free(docx_path, args.force)
33
+ check_file_free(xlsx_path, args.force)
34
+
35
+ doc = docx.Document(str(docx_path))
36
+ marks = find_marks(doc)
37
+ previous = read_previous_marks(xlsx_path)
38
+ processed = processed_marks(doc, {mark.bookmark for mark in marks if mark.bookmark})
39
+
40
+ log(f"读取 Word:{docx_path.name}")
41
+ log(f"发现高亮标记(待处理):{len(marks)} 处" + (f",已处理:{len(processed)} 处" if processed else ""))
42
+ for mark in marks:
43
+ filled = "已填" if any(row["bookmark"] == mark.bookmark and (row["new"] or row["link"]) for row in previous) else "未填"
44
+ log(f" M{mark.index:02d} {mark.location}({filled}):{mark.text[:40]}")
45
+ known = {m.bookmark for m in marks if m.bookmark} | {item["bookmark"] for item in processed}
46
+ stale = [row for row in previous if row["bookmark"] and row["bookmark"] not in known]
47
+ if stale:
48
+ log(f" (另有 {len(stale)} 处工作簿里记录过的标记在 Word 中已删除,将保留为记录行)")
49
+
50
+ if args.dry_run:
51
+ log("预演模式(--dry-run):以上为将写入「链接标注」工作表的标记,未写入任何文件。")
52
+ return 0
53
+
54
+ created = ensure_mark_bookmarks(doc, marks)
55
+ if created:
56
+ backup = backup_file(docx_path)
57
+ doc.save(str(docx_path))
58
+ log(f"[标记] 已为 {created} 处标记插入定位书签并保存 Word(备份:{backup.name if backup else '无'})")
59
+ else:
60
+ log("[标记] 所有标记都已有定位书签,Word 无需改动")
61
+
62
+ workbook = load_workbook_for_save(xlsx_path)
63
+ stats = build_marks_sheet(workbook, docx_path.name, marks, previous, processed)
64
+ xlsx_backup = backup_file(xlsx_path)
65
+ workbook.save(str(xlsx_path))
66
+ log(
67
+ f"[标记] 已刷新工作表「{SHEET_MARKS}」:{stats['marks']} 行标记"
68
+ + (f",{stats['processed']} 行已处理" if stats.get("processed") else "")
69
+ + (f",{stats['orphans']} 行已删除记录" if stats["orphans"] else "")
70
+ + (f"(原文件已备份:{xlsx_backup.name})" if xlsx_backup else "")
71
+ )
72
+ return 0
73
+
74
+
75
+ def cmd_marks_sync(args) -> int:
76
+ """把「链接标注」工作表里填写的内容同步回 Word。"""
77
+ docx_path = resolve_docx(args.docx)
78
+ xlsx_path = resolve_xlsx(docx_path, args.excel)
79
+ if not xlsx_path.exists():
80
+ raise SyncError(f"找不到工作簿:{xlsx_path}\n请先执行「导出表格到 Excel」或「导出/刷新标注」。")
81
+ if not args.dry_run:
82
+ check_file_free(docx_path, args.force)
83
+ check_file_free(xlsx_path, args.force)
84
+
85
+ workbook = load_workbook(str(xlsx_path))
86
+ if SHEET_MARKS not in workbook.sheetnames:
87
+ raise SyncError(f"工作簿里没有「{SHEET_MARKS}」工作表,请先在界面上执行“导出/刷新标注”。")
88
+ rows = getattr(args, "rows", None)
89
+ if rows is None:
90
+ cached_workbook = load_workbook(str(xlsx_path), data_only=True)
91
+ rows = parse_marks_rows(workbook[SHEET_MARKS], cached_workbook[SHEET_MARKS])
92
+ if not rows:
93
+ raise SyncError(f"「{SHEET_MARKS}」工作表里没有数据行,请先执行“导出/刷新标注”。")
94
+
95
+ doc = docx.Document(str(docx_path))
96
+ keep_highlight = bool(getattr(args, "keep_highlight", False))
97
+ log(f"读取 Word:{docx_path.name}")
98
+ log(f"读取 Excel:{xlsx_path.name}(工作表:{SHEET_MARKS},{len(rows)} 行)")
99
+ if keep_highlight:
100
+ log("[标记] 本次同步保留高亮(不去色),便于人工复核")
101
+ if args.dry_run:
102
+ log("预演模式(--dry-run):只显示将发生的改动,不写入文件。")
103
+
104
+ changed = 0
105
+ deleted = 0
106
+ pending = 0
107
+ for row in rows:
108
+ label = row["label"]
109
+ bookmark = row["bookmark"]
110
+ if not bookmark:
111
+ deleted += 1
112
+ log(f"[跳过] {label}:该行没有书签,无法定位")
113
+ continue
114
+ payload = mark_payload_by_bookmark(doc, bookmark)
115
+ if payload is None:
116
+ deleted += 1
117
+ log(f"[跳过] {label} {row['original'][:24]}:Word 中该标记已删除")
118
+ continue
119
+ if not row["new"] and not row["link"]:
120
+ pending += 1
121
+ warn(f"{label} {row['position']}:新内容与链接地址均未填,保留原样未同步。")
122
+ continue
123
+ p_el, children, runs = payload
124
+ result = apply_mark_change(
125
+ doc.part, p_el, children, runs, row["new"], row["link"], keep_highlight=keep_highlight
126
+ )
127
+ if result == "deleted":
128
+ deleted += 1
129
+ log(f"[跳过] {label}:标记内容在 Word 中已为空")
130
+ elif result == "changed":
131
+ changed += 1
132
+ detail = row["new"] if row["new"] else "(文字不变)"
133
+ extra = f",链接 → {row['link']}" if row["link"] else ""
134
+ log(f"[标记] {label} {row['position']}:{row['original'][:20]} → {detail}{extra}")
135
+
136
+ log(
137
+ f"合计:同步 {changed} 处标记"
138
+ + (f",跳过 {deleted} 处(已删除/无书签)" if deleted else "")
139
+ + (f",待填写 {pending} 处(新内容与链接地址均为空)" if pending else "")
140
+ + "。"
141
+ )
142
+
143
+ if args.dry_run:
144
+ log("预演结束,未写入任何文件。")
145
+ return 0
146
+ if not changed:
147
+ log("标注表与 Word 内容一致,未做任何写入。")
148
+ return 0
149
+ backup = backup_file(docx_path)
150
+ doc.save(str(docx_path))
151
+ log(f"[标记] 已保存 {docx_path.name}" + (f"(原文件已备份:{backup.name})" if backup else ""))
152
+ return 0
@@ -0,0 +1,87 @@
1
+ """placeholders / placeholders-sync 子命令:{字段名} 骨架导出到「正文信息」表、填值写回 Word。"""
2
+
3
+ import docx
4
+
5
+ from ..console import log, warn
6
+ from ..docx_placeholders import (
7
+ VALUES_SHEET,
8
+ apply_placeholders,
9
+ read_placeholder_values,
10
+ scan_placeholders,
11
+ write_placeholder_sheet,
12
+ )
13
+ from ..errors import SyncError
14
+ from ..fsops import backup_file, check_file_free, resolve_docx, resolve_xlsx
15
+
16
+
17
+ def cmd_placeholders(args) -> int:
18
+ """按当前 Word 的 {字段名} 给工作簿「正文信息」表补齐骨架(保留已填值)。"""
19
+ docx_path = resolve_docx(args.docx)
20
+ xlsx_path = resolve_xlsx(docx_path, args.excel)
21
+ if not xlsx_path.exists():
22
+ raise SyncError(
23
+ f"找不到工作簿:{xlsx_path}\n请先执行「导出表格到 Excel」(界面上“导出/刷新占位符”会确认后自动先导出)。"
24
+ )
25
+ if not args.dry_run:
26
+ check_file_free(xlsx_path, args.force)
27
+ doc = docx.Document(str(docx_path))
28
+ fields = scan_placeholders(doc)
29
+ log(f"读取 Word:{docx_path.name}")
30
+ if not fields:
31
+ log("Word 中没有 {字段名} 占位符,无需生成「正文信息」表。")
32
+ return 0
33
+ log(f"发现占位符 {len(fields)} 个字段:{'、'.join(fields)}")
34
+ if args.dry_run:
35
+ log("预演模式(--dry-run):以上字段将加入/补齐「正文信息」表,未写入任何文件。")
36
+ return 0
37
+ added = write_placeholder_sheet(xlsx_path, fields)
38
+ log(
39
+ f"[占位符] 「{VALUES_SHEET}」表已就绪({len(fields)} 个字段"
40
+ + (f",本次新增 {len(added)} 个" if added else ",无新增字段")
41
+ + "),已填值保留;请在 B 列填值后执行「同步占位符」。"
42
+ )
43
+ return 0
44
+
45
+
46
+ def cmd_placeholders_sync(args) -> int:
47
+ """把「正文信息」表填好的值写回当前 Word 的占位符;未填字段保留原样并逐条警告。"""
48
+ docx_path = resolve_docx(args.docx)
49
+ xlsx_path = resolve_xlsx(docx_path, args.excel)
50
+ if not xlsx_path.exists():
51
+ raise SyncError(f"找不到工作簿:{xlsx_path}\n请先执行「导出表格到 Excel」或「导出/刷新占位符」。")
52
+ if not args.dry_run:
53
+ check_file_free(docx_path, args.force)
54
+ check_file_free(xlsx_path, args.force)
55
+ values = getattr(args, "values", None)
56
+ if values is None:
57
+ values = read_placeholder_values(xlsx_path)
58
+ doc = docx.Document(str(docx_path))
59
+ fields = scan_placeholders(doc)
60
+ log(f"读取 Word:{docx_path.name}")
61
+ if not fields:
62
+ log("Word 中没有 {字段名} 占位符,无需同步。")
63
+ return 0
64
+ if not values:
65
+ raise SyncError(
66
+ f"工作簿没有「{VALUES_SHEET}」表或表里没填任何值,请先执行「导出/刷新占位符」并在 B 列填值。"
67
+ )
68
+ result = apply_placeholders(doc, values, dry_run=args.dry_run)
69
+ for field, new in result["replaced"]:
70
+ log(f"[占位符] {{{field}}} → {new}")
71
+ for field in result["missing"]:
72
+ warn(f"占位符 {{{field}}} 在「{VALUES_SHEET}」表未填值,保留原样未同步。")
73
+ log(
74
+ f"合计:替换 {len(result['replaced'])} 处占位符"
75
+ + (f",未填保留原样 {len(result['missing'])} 处" if result["missing"] else "")
76
+ + "。"
77
+ )
78
+ if args.dry_run:
79
+ log("预演结束,未写入任何文件。")
80
+ return 0
81
+ if not result["replaced"]:
82
+ log("没有可替换的占位符,未做任何写入。")
83
+ return 0
84
+ backup = backup_file(docx_path)
85
+ doc.save(str(docx_path))
86
+ log(f"[占位符] 已保存 {docx_path.name}" + (f"(原文件已备份:{backup.name})" if backup else ""))
87
+ return 0