audit-e2w 0.0.0-stage → 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 (94) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +152 -3
  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 +122 -0
  6. package/dsh_plugins/audit-e2w/lib/skill.js +42 -0
  7. package/excel_word/README.md +388 -0
  8. package/excel_word/qoder_engine.py +437 -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/ai/__init__.py +52 -0
  13. package/excel_word/wesync/ai/actions.py +369 -0
  14. package/excel_word/wesync/ai/client.py +340 -0
  15. package/excel_word/wesync/ai/config.py +291 -0
  16. package/excel_word/wesync/ai/docs.py +177 -0
  17. package/excel_word/wesync/ai/prompts.py +288 -0
  18. package/excel_word/wesync/ai/tasks/__init__.py +26 -0
  19. package/excel_word/wesync/ai/tasks/actions_task.py +97 -0
  20. package/excel_word/wesync/ai/tasks/combined.py +123 -0
  21. package/excel_word/wesync/ai/tasks/diff_note.py +61 -0
  22. package/excel_word/wesync/ai/tasks/headings.py +119 -0
  23. package/excel_word/wesync/ai/tasks/help_task.py +69 -0
  24. package/excel_word/wesync/ai/tasks/roles.py +128 -0
  25. package/excel_word/wesync/align.py +155 -0
  26. package/excel_word/wesync/api.py +1292 -0
  27. package/excel_word/wesync/backup_history.py +100 -0
  28. package/excel_word/wesync/changelog.py +58 -0
  29. package/excel_word/wesync/cli.py +191 -0
  30. package/excel_word/wesync/commands/__init__.py +8 -0
  31. package/excel_word/wesync/commands/blank_cmd.py +279 -0
  32. package/excel_word/wesync/commands/bookmark_cmd.py +146 -0
  33. package/excel_word/wesync/commands/clear_cmd.py +50 -0
  34. package/excel_word/wesync/commands/export_cmd.py +270 -0
  35. package/excel_word/wesync/commands/incremental_cmd.py +157 -0
  36. package/excel_word/wesync/commands/marks_cmd.py +160 -0
  37. package/excel_word/wesync/commands/placeholders_cmd.py +92 -0
  38. package/excel_word/wesync/commands/writeback_cmd.py +469 -0
  39. package/excel_word/wesync/config.py +97 -0
  40. package/excel_word/wesync/console.py +85 -0
  41. package/excel_word/wesync/docx_blank.py +156 -0
  42. package/excel_word/wesync/docx_bookmarks.py +294 -0
  43. package/excel_word/wesync/docx_columns.py +257 -0
  44. package/excel_word/wesync/docx_edit.py +77 -0
  45. package/excel_word/wesync/docx_grid.py +212 -0
  46. package/excel_word/wesync/docx_marks.py +399 -0
  47. package/excel_word/wesync/docx_meta.py +157 -0
  48. package/excel_word/wesync/docx_newtable.py +220 -0
  49. package/excel_word/wesync/docx_placeholders.py +200 -0
  50. package/excel_word/wesync/docx_rows.py +67 -0
  51. package/excel_word/wesync/errors.py +5 -0
  52. package/excel_word/wesync/excel_blocks.py +502 -0
  53. package/excel_word/wesync/excel_export.py +143 -0
  54. package/excel_word/wesync/excel_marks.py +265 -0
  55. package/excel_word/wesync/excel_totals.py +53 -0
  56. package/excel_word/wesync/fsops.py +219 -0
  57. package/excel_word/wesync/gui/__init__.py +53 -0
  58. package/excel_word/wesync/gui/__main__.py +6 -0
  59. package/excel_word/wesync/gui/app.py +613 -0
  60. package/excel_word/wesync/gui/manual.py +70 -0
  61. package/excel_word/wesync/gui/pages/__init__.py +80 -0
  62. package/excel_word/wesync/gui/pages/_page.py +211 -0
  63. package/excel_word/wesync/gui/pages/ai_page.py +854 -0
  64. package/excel_word/wesync/gui/pages/batch_page.py +456 -0
  65. package/excel_word/wesync/gui/pages/blank_page.py +530 -0
  66. package/excel_word/wesync/gui/pages/bookmark_page.py +97 -0
  67. package/excel_word/wesync/gui/pages/export_page.py +141 -0
  68. package/excel_word/wesync/gui/pages/feedback_page.py +196 -0
  69. package/excel_word/wesync/gui/pages/format_page.py +551 -0
  70. package/excel_word/wesync/gui/pages/help_page.py +158 -0
  71. package/excel_word/wesync/gui/pages/history_page.py +168 -0
  72. package/excel_word/wesync/gui/pages/marks_page.py +211 -0
  73. package/excel_word/wesync/gui/pages/settings_page.py +450 -0
  74. package/excel_word/wesync/gui/pages/writeback_page.py +473 -0
  75. package/excel_word/wesync/gui/resources.py +22 -0
  76. package/excel_word/wesync/gui/runner.py +90 -0
  77. package/excel_word/wesync/gui/store.py +50 -0
  78. package/excel_word/wesync/gui/theme.py +271 -0
  79. package/excel_word/wesync/gui/widgets/__init__.py +8 -0
  80. package/excel_word/wesync/gui/widgets/ai_config.py +362 -0
  81. package/excel_word/wesync/gui/widgets/cards.py +139 -0
  82. package/excel_word/wesync/gui/widgets/chips.py +565 -0
  83. package/excel_word/wesync/gui/widgets/filebar.py +58 -0
  84. package/excel_word/wesync/gui/widgets/logpane.py +126 -0
  85. package/excel_word/wesync/gui/widgets/nav.py +294 -0
  86. package/excel_word/wesync/gui/widgets/theme_choice.py +93 -0
  87. package/excel_word/wesync/report_format.py +1585 -0
  88. package/excel_word/wesync/settings.py +35 -0
  89. package/excel_word/wesync/sort_rules.py +293 -0
  90. package/excel_word/wesync/valuefmt.py +485 -0
  91. package/package.json +53 -6
  92. package/packaging//344/275/277/347/224/250/350/257/264/346/230/216.txt +247 -0
  93. package/qoder_plugins/audit-toolbox/README.md +159 -0
  94. package/qoder_plugins/audit-toolbox/catalog.mjs +265 -0
@@ -0,0 +1,473 @@
1
+ """同步页:Excel → Word(含增删行、增删列,同步「表格汇总」与「新增表格」)。"""
2
+
3
+ from __future__ import annotations
4
+
5
+ from PySide6.QtWidgets import (
6
+ QComboBox,
7
+ QHBoxLayout,
8
+ QHeaderView,
9
+ QLabel,
10
+ QPushButton,
11
+ QTabWidget,
12
+ QTableWidget,
13
+ QTableWidgetItem,
14
+ QVBoxLayout,
15
+ QWidget,
16
+ )
17
+
18
+ from ... import api
19
+ from ...console import set_log_sink
20
+ from ...errors import SyncError
21
+ from ..widgets.cards import make_checkbutton
22
+ from ..widgets.chips import ChipRow
23
+ from ._page import BasePage
24
+
25
+
26
+ class WritebackPage(BasePage):
27
+ title = "同步Word"
28
+ subtitle = "工作簿改动回写 Word;保留格式,支持增删行列与新增表格。"
29
+
30
+ def build(self, body: QWidget) -> None:
31
+ card = self.card(body)
32
+ tabs = QTabWidget()
33
+ card.layout().addWidget(tabs)
34
+ tabs.addTab(self._build_sync_tab(), "同步回写")
35
+ tabs.addTab(self._build_sort_tab(), "排序设置")
36
+ tabs.addTab(self._build_diff_tab(), "差异比对")
37
+
38
+ # ---------- 同步回写 tab ----------
39
+
40
+ def _build_sync_tab(self) -> QWidget:
41
+ tab = QWidget()
42
+ layout = QVBoxLayout(tab)
43
+ layout.setContentsMargins(12, 12, 12, 12)
44
+ layout.setSpacing(10)
45
+ content_row = QHBoxLayout()
46
+ content_row.setSpacing(8)
47
+ content_row.addWidget(QLabel("同步内容:"))
48
+ self.sync_tables = make_checkbutton(tab, "表格", True)
49
+ self.sync_marks = make_checkbutton(tab, "标注", False)
50
+ self.sync_placeholders = make_checkbutton(tab, "占位符", False)
51
+ for box in (self.sync_tables, self.sync_marks, self.sync_placeholders):
52
+ content_row.addWidget(box)
53
+ content_row.addStretch(1)
54
+ layout.addLayout(content_row)
55
+ self.wb_keep_highlight = make_checkbutton(tab, "保留标注高亮", True)
56
+ self.wb_keep_highlight.setVisible(False)
57
+ self.sync_marks.toggled.connect(self.wb_keep_highlight.setVisible)
58
+ layout.addWidget(self.wb_keep_highlight)
59
+ self.tip_label(tab, "标注/占位符读对应工作表;未填保留并警告。备份与删除只作用于表格。")
60
+ self.options = ChipRow([
61
+ ("force", "忽略文件占用", False, "文件仍被打开时使用"),
62
+ ("backup", "同步前备份", False, "关闭则直接覆盖", True),
63
+ ("changelog", "导出改动清单", False, "逐格记录旧值→新值"),
64
+ ])
65
+ tab.layout().addWidget(self.options)
66
+ self.force = self.options["force"]
67
+ self.backup = self.options["backup"]
68
+ self.changelog = self.options["changelog"]
69
+ self.delete_empty = make_checkbutton(
70
+ tab, "删除 B 列✕行;Excel 保留为「已删」,改✓可恢复", False
71
+ )
72
+ self.zero_controls = {}
73
+ self.bind_defaults(layout, {
74
+ "sync_tables": self.sync_tables,
75
+ "sync_marks": self.sync_marks,
76
+ "sync_placeholders": self.sync_placeholders,
77
+ "keep_highlight": self.wb_keep_highlight,
78
+ "auto_backup": self.backup,
79
+ }, [("表格", "table_zero"), ("标注", "mark_zero"), ("占位符", "placeholder_zero")], self.zero_controls)
80
+ self.table_zero = self.zero_controls["table_zero"]
81
+ self.mark_zero = self.zero_controls["mark_zero"]
82
+ self.placeholder_zero = self.zero_controls["placeholder_zero"]
83
+ layout.addWidget(self.delete_empty)
84
+
85
+ row = self.button_row(tab, lambda: self._start(True), lambda: self._start(False), "仅预演", "开始同步")
86
+ self.tip_label(
87
+ tab,
88
+ "Word 新增表格后,先在「创建Excel」点「增量导出」,再在这里同步。",
89
+ )
90
+ layout.addStretch(1)
91
+ return tab
92
+
93
+ # ---------- 排序设置 tab ----------
94
+
95
+ def _build_sort_tab(self) -> QWidget:
96
+ tab = QWidget()
97
+ layout = QVBoxLayout(tab)
98
+ layout.setContentsMargins(12, 12, 12, 12)
99
+ layout.setSpacing(10)
100
+ self.tip_label(
101
+ tab,
102
+ "按金额列自动排序 Excel 与 Word;设置随工作簿保存。「其他」行留在合计前,合并单元格表跳过。",
103
+ )
104
+ row = QHBoxLayout()
105
+ row.setSpacing(8)
106
+ row.addWidget(QLabel("表"))
107
+ self.sort_table = QComboBox()
108
+ self.sort_table.setMinimumWidth(220)
109
+ self.sort_table.currentIndexChanged.connect(lambda _i: self._sort_table_changed())
110
+ row.addWidget(self.sort_table, 2)
111
+ row.addWidget(QLabel("金额列"))
112
+ self.sort_column = QComboBox()
113
+ self.sort_column.setMinimumWidth(150)
114
+ row.addWidget(self.sort_column, 1)
115
+ row.addWidget(QLabel("方向"))
116
+ self.sort_dir = QComboBox()
117
+ self.sort_dir.addItems(["降序(从大到小)", "升序(从小到大)"])
118
+ row.addWidget(self.sort_dir)
119
+ layout.addLayout(row)
120
+
121
+ btns = QHBoxLayout()
122
+ btns.setSpacing(12)
123
+ refresh = QPushButton("刷新清单")
124
+ refresh.clicked.connect(lambda _checked=False: self._reload_sorts_background())
125
+ btns.addWidget(refresh)
126
+ save = QPushButton("保存排序设置")
127
+ save.setObjectName("Primary")
128
+ save.clicked.connect(lambda _checked=False: self._save_sort())
129
+ btns.addWidget(save)
130
+ clear = QPushButton("清除该表排序")
131
+ clear.clicked.connect(lambda _checked=False: self._clear_sort())
132
+ btns.addWidget(clear)
133
+ btns.addStretch(1)
134
+ layout.addLayout(btns)
135
+ self.sort_status = self.tip_label(tab, "尚未加载。选择 Word 文件并生成工作簿后,点「刷新清单」。")
136
+ self._sort_items: list[dict] = []
137
+ self._sort_file_key: tuple[str | None, str | None] | None = None
138
+ layout.addStretch(1)
139
+ return tab
140
+
141
+ def _start(self, dry_run: bool) -> None:
142
+ if not self.ctx.require_docx():
143
+ return
144
+ tables = self.sync_tables.isChecked()
145
+ marks = self.sync_marks.isChecked()
146
+ placeholders = self.sync_placeholders.isChecked()
147
+ if not (tables or marks or placeholders):
148
+ self.ctx.error("未选择同步内容", "请至少勾选一项同步内容(表格/标注/占位符)。")
149
+ return
150
+ content_text = "+".join(
151
+ name for name, on in (("表格", tables), ("标注", marks), ("占位符", placeholders)) if on
152
+ )
153
+ docx = self.ctx.docx
154
+ custom_excel = self.ctx.excel
155
+ links = self.ctx.global_settings()["excel_links"]
156
+ totals = self.ctx.global_settings()["totals_formula"]
157
+ excel = api.workbook_path(docx, custom_excel)
158
+ steps: list[tuple[str, object]] = []
159
+
160
+ if not excel.exists():
161
+ if dry_run:
162
+ self.ctx.log(f"未找到工作簿:{excel}\n请先执行导出生成工作簿,再预演同步。", "error")
163
+ return
164
+ if not self.ctx.confirm(
165
+ "未找到工作簿",
166
+ f"未找到工作簿:\n{excel}\n\n是否现在从 Word 导出生成工作簿?\n生成后将继续执行同步。",
167
+ ):
168
+ self.ctx.log("已取消:缺少工作簿,未执行同步。", "muted")
169
+ return
170
+ steps.append(("导出到 Excel(生成工作簿)", lambda: api.run_export(
171
+ docx, custom_excel,
172
+ with_excel_links=links,
173
+ totals_formula=totals,
174
+ backup=self.backup.isChecked(),
175
+ )))
176
+ elif not dry_run:
177
+ backup_note = (
178
+ "同步前会自动备份 Word(若数据有变化)。" if self.backup.isChecked()
179
+ else "未勾选备份:将直接覆盖原文件,不创建 _backup 备份。"
180
+ )
181
+ message = (
182
+ f"将把以下内容同步到 Word:{content_text}\n\nWord:{self.ctx.docx}\nExcel:{excel}\n\n"
183
+ + backup_note + " 确认开始同步?"
184
+ )
185
+ if not self.ctx.confirm("确认同步", message):
186
+ self.ctx.log("已取消同步。", "muted")
187
+ return
188
+
189
+ force = self.force.isChecked()
190
+ backup = self.backup.isChecked()
191
+ table_zero = self.table_zero.currentData()
192
+ mark_zero = self.mark_zero.currentData()
193
+ placeholder_zero = self.placeholder_zero.currentData()
194
+ changelog = self.changelog.isChecked()
195
+ delete_empty = self.delete_empty.isChecked()
196
+ keep_highlight = self.wb_keep_highlight.isChecked()
197
+ label = ("同步到 Word(预演)" if dry_run else "同步到 Word") + f"·{content_text}"
198
+ if tables and not marks and not placeholders:
199
+ steps.append(
200
+ (
201
+ label,
202
+ lambda: api.run_writeback(docx, custom_excel, dry_run=dry_run, force=force, backup=backup, changelog=changelog, delete_empty_rows=delete_empty, table_zero=table_zero),
203
+ )
204
+ )
205
+ else:
206
+ def run_sync() -> int:
207
+ api.run_sync_content(
208
+ docx, custom_excel,
209
+ tables=tables, marks=marks, placeholders=placeholders,
210
+ keep_highlight=keep_highlight, dry_run=dry_run, force=force,
211
+ backup=backup, changelog=changelog, delete_empty_rows=delete_empty,
212
+ table_zero=table_zero, mark_zero=mark_zero,
213
+ placeholder_zero=placeholder_zero,
214
+ )
215
+ return 0
216
+
217
+ steps.append((label, run_sync))
218
+ self.ctx.run_steps(steps)
219
+
220
+ # ---------- 排序设置 ----------
221
+
222
+ def _file_key(self) -> tuple[str | None, str | None]:
223
+ return (
224
+ str(self.ctx.docx) if self.ctx.docx is not None else None,
225
+ str(self.ctx.excel) if self.ctx.excel is not None else None,
226
+ )
227
+
228
+ def on_show(self) -> None:
229
+ super().on_show()
230
+ key = self._file_key()
231
+ if key != self._diff_file_key:
232
+ self._diff_records = []
233
+ self.diff_table.setRowCount(0)
234
+ self.diff_status.setText("尚未比对。选择 Word 文件并生成工作簿后,点「差异比对」。")
235
+ self._diff_file_key = key
236
+ if not self.ctx.busy and key != self._sort_file_key:
237
+ self._reload_sorts_background()
238
+
239
+ def _reload_sorts_background(self) -> None:
240
+ if self.ctx.busy:
241
+ return
242
+ key = self._file_key()
243
+ docx, excel = self.ctx.docx, self.ctx.excel
244
+ if docx is None or excel is None or not excel.exists():
245
+ self._sort_file_key = key
246
+ self._sort_items = []
247
+ self.sort_table.clear()
248
+ self.sort_column.clear()
249
+ self.sort_status.setText("尚未加载。选择 Word 文件并生成工作簿后,点「刷新清单」。")
250
+ return
251
+ self.sort_status.setText("正在加载排序清单…")
252
+
253
+ def work():
254
+ return api.list_table_sorts(docx, excel)
255
+
256
+ def done(data):
257
+ if self._file_key() == key:
258
+ self._apply_sorts(data["results"][0], key)
259
+
260
+ self.run_background("加载排序清单", work, done)
261
+
262
+ def _reload_sorts(self, quiet: bool = False) -> None:
263
+ key = self._file_key()
264
+ docx, excel = self.ctx.docx, self.ctx.excel
265
+ self._sort_items = []
266
+ self.sort_table.clear()
267
+ self.sort_column.clear()
268
+ if docx is None or excel is None or not excel.exists():
269
+ self._sort_file_key = key
270
+ self.sort_status.setText("尚未加载。选择 Word 文件并生成工作簿后,点「刷新清单」。")
271
+ return
272
+ try:
273
+ items = api.list_table_sorts(docx, excel)
274
+ except Exception as exc:
275
+ self._sort_file_key = key
276
+ self.sort_status.setText(f"加载失败:{exc}")
277
+ return
278
+ self._apply_sorts(items, key)
279
+ if not quiet:
280
+ self.ctx.log("排序清单已刷新。", "muted")
281
+
282
+ def _apply_sorts(self, items: list[dict], key: tuple[str | None, str | None]) -> None:
283
+ self._sort_file_key = key
284
+ self._sort_items = items
285
+ self.sort_table.clear()
286
+ self.sort_column.clear()
287
+ for item in self._sort_items:
288
+ short = item["name"].split(" · 章节:")[0]
289
+ if len(short) > 24:
290
+ short = short[:23] + "…"
291
+ mark = f"(已设:{item['sort_column']} {'降序' if item['descending'] else '升序'})" if item["has_sort"] else ""
292
+ self.sort_table.addItem(f"{item['code']} · {short}{mark}")
293
+ if self._sort_items:
294
+ self.sort_table.setCurrentIndex(0)
295
+ self._sort_table_changed()
296
+ self.sort_status.setText(f"共 {len(self._sort_items)} 张表可设置排序;带「已设」标记的表同步时会自动排序。")
297
+ else:
298
+ self.sort_status.setText("工作簿里没有可设置排序的表块。")
299
+
300
+ def _sort_table_changed(self) -> None:
301
+ self.sort_column.clear()
302
+ idx = self.sort_table.currentIndex()
303
+ if not 0 <= idx < len(self._sort_items):
304
+ return
305
+ item = self._sort_items[idx]
306
+ seen = []
307
+ for h in item["headers"]:
308
+ if h and h not in seen:
309
+ seen.append(h)
310
+ self.sort_column.addItems(seen)
311
+ if item["has_sort"] and item["sort_column"] in seen:
312
+ self.sort_column.setCurrentText(item["sort_column"])
313
+ self.sort_dir.setCurrentIndex(0 if item["descending"] else 1)
314
+
315
+ def _run_sort_action(self, title: str, work) -> None:
316
+ key = self._file_key()
317
+
318
+ def done(_data):
319
+ if self._file_key() == key:
320
+ self._reload_sorts_background()
321
+
322
+ self.run_background(title, work, done)
323
+
324
+ def _save_sort(self) -> None:
325
+ idx = self.sort_table.currentIndex()
326
+ if not 0 <= idx < len(self._sort_items):
327
+ self.ctx.info("未选择", "请先点「刷新清单」并选择要排序的表。")
328
+ return
329
+ if not self.sort_column.currentText():
330
+ self.ctx.info("未选择金额列", "请先选择按哪一列金额排序。")
331
+ return
332
+ item = self._sort_items[idx]
333
+ if self._file_key() != self._sort_file_key:
334
+ self.ctx.error("文件已切换", "排序清单与当前文件不一致,请刷新清单后重试。")
335
+ self._reload_sorts_background()
336
+ return
337
+ docx, excel = self.ctx.docx, self.ctx.excel
338
+ backup = self.backup.isChecked()
339
+ code = item["code"]
340
+ column = self.sort_column.currentText()
341
+ descending = self.sort_dir.currentIndex() == 0
342
+ self._run_sort_action(
343
+ "保存排序设置",
344
+ lambda: api.set_table_sort(
345
+ docx, excel, code=code, column=column,
346
+ descending=descending, backup=backup,
347
+ ),
348
+ )
349
+
350
+ def _clear_sort(self) -> None:
351
+ idx = self.sort_table.currentIndex()
352
+ if not 0 <= idx < len(self._sort_items):
353
+ self.ctx.info("未选择", "请先点「刷新清单」并选择表。")
354
+ return
355
+ item = self._sort_items[idx]
356
+ if self._file_key() != self._sort_file_key:
357
+ self.ctx.error("文件已切换", "排序清单与当前文件不一致,请刷新清单后重试。")
358
+ self._reload_sorts_background()
359
+ return
360
+ docx, excel = self.ctx.docx, self.ctx.excel
361
+ backup = self.backup.isChecked()
362
+ code = item["code"]
363
+ self._run_sort_action(
364
+ "清除排序设置",
365
+ lambda: api.clear_table_sort(docx, excel, code=code, backup=backup),
366
+ )
367
+
368
+ # ---------- 差异比对 ----------
369
+
370
+ def _build_diff_tab(self) -> QWidget:
371
+ tab = QWidget()
372
+ layout = QVBoxLayout(tab)
373
+ layout.setContentsMargins(12, 12, 12, 12)
374
+ layout.setSpacing(10)
375
+ self.tip_label(
376
+ tab,
377
+ "只读比对 Word 与工作簿差异(旧值→新值),不写文件;可导出复核。",
378
+ )
379
+ row = QHBoxLayout()
380
+ row.setSpacing(12)
381
+ refresh = QPushButton("差异比对")
382
+ refresh.setObjectName("Primary")
383
+ refresh.setToolTip("只读列出 Word 与工作簿不一致的单元格(旧值→新值),不写任何文件。")
384
+ refresh.clicked.connect(lambda _checked=False: self._diff_background())
385
+ row.addWidget(refresh)
386
+ export = QPushButton("导出差异表")
387
+ export.clicked.connect(lambda _checked=False: self._export_diff())
388
+ row.addWidget(export)
389
+ row.addStretch(1)
390
+ layout.addLayout(row)
391
+ self.diff_status = self.tip_label(tab, "尚未比对。选择 Word 文件并生成工作簿后,点「差异比对」。")
392
+ self.diff_table = QTableWidget(0, 7)
393
+ self.diff_table.setHorizontalHeaderLabels(["表号", "行", "列", "项目", "旧值", "新值", "类型"])
394
+ self.diff_table.horizontalHeader().setSectionResizeMode(3, QHeaderView.Stretch)
395
+ self.diff_table.horizontalHeader().setSectionResizeMode(4, QHeaderView.Stretch)
396
+ self.diff_table.horizontalHeader().setSectionResizeMode(5, QHeaderView.Stretch)
397
+ self.diff_table.setSelectionBehavior(QTableWidget.SelectRows)
398
+ self.diff_table.setEditTriggers(QTableWidget.NoEditTriggers)
399
+ self.diff_table.setMinimumHeight(180)
400
+ layout.addWidget(self.diff_table)
401
+ self._diff_records: list[dict] = []
402
+ self._diff_file_key: tuple[str | None, str | None] | None = None
403
+ return tab
404
+
405
+ def _diff_background(self) -> None:
406
+ if not self.ctx.require_docx():
407
+ return
408
+ if not self.ctx.workbook_path().exists():
409
+ self.ctx.error("未找到工作簿", "请先执行「导出表格到 Excel」生成工作簿,再比对差异。")
410
+ return
411
+ docx, excel = self.ctx.docx, self.ctx.excel
412
+ key = self._file_key()
413
+ self.diff_status.setText("正在比对差异…")
414
+
415
+ def work():
416
+ return api.scan_writeback_diff(docx, excel)
417
+
418
+ def done(data):
419
+ if self._file_key() == key:
420
+ self._diff_records = data["results"][0]
421
+ self._diff_file_key = key
422
+ self._fill_diff(self._diff_records)
423
+
424
+ self.run_background("差异比对", work, done)
425
+
426
+ def _diff(self) -> None:
427
+ if not self.ctx.require_docx():
428
+ return
429
+ if not self.ctx.workbook_path().exists():
430
+ self.ctx.error("未找到工作簿", "请先执行「导出表格到 Excel」生成工作簿,再比对差异。")
431
+ return
432
+ try:
433
+ records = api.scan_writeback_diff(self.ctx.docx, self.ctx.excel)
434
+ except Exception as exc:
435
+ self.ctx.error("差异比对失败", str(exc))
436
+ return
437
+ self._diff_records = records
438
+ self._diff_file_key = self._file_key()
439
+ self._fill_diff(records)
440
+
441
+ def _fill_diff(self, records: list[dict]) -> None:
442
+ self.diff_table.setRowCount(0)
443
+ for rec in records:
444
+ row = self.diff_table.rowCount()
445
+ self.diff_table.insertRow(row)
446
+ values = [rec.get("code", ""), rec.get("row", ""), rec.get("col", ""), rec.get("item", ""),
447
+ rec.get("old", ""), rec.get("new", ""), rec.get("kind", "")]
448
+ for c, value in enumerate(values):
449
+ self.diff_table.setItem(row, c, QTableWidgetItem(str(value)))
450
+ cells = sum(1 for r in records if r.get("kind") == "单元格")
451
+ if records:
452
+ self.diff_status.setText(f"共 {len(records)} 条差异(其中单元格改动 {cells} 处)。确认无误后点「开始同步」。")
453
+ else:
454
+ self.diff_status.setText("Word 与工作簿一致,没有差异。")
455
+
456
+ def _export_diff(self) -> None:
457
+ if not self._diff_records:
458
+ self.ctx.info("无差异可导出", "请先点「差异比对」;当前没有差异记录。")
459
+ return
460
+ if self._diff_file_key != self._file_key():
461
+ self.ctx.error("文件已切换", "差异记录与当前文件不一致,请重新比对后再导出。")
462
+ return
463
+ docx, excel = self.ctx.docx, self.ctx.excel
464
+ set_log_sink(lambda message: self.ctx.log(message))
465
+ try:
466
+ path = api.export_diff_report(docx, excel, self._diff_records)
467
+ except SyncError as exc:
468
+ self.ctx.error("导出差异表失败", str(exc))
469
+ return
470
+ finally:
471
+ set_log_sink(None)
472
+ if path:
473
+ self.ctx.log(f"差异表已导出:{path}", "ok")
@@ -0,0 +1,22 @@
1
+ """界面资源路径:同时兼容源码运行与 PyInstaller 打包。"""
2
+
3
+ from __future__ import annotations
4
+
5
+ import sys
6
+ from pathlib import Path
7
+
8
+
9
+ def _resource_path(name: str) -> Path:
10
+ if getattr(sys, "frozen", False):
11
+ return Path(sys._MEIPASS) / "wesync" / "resources" / name
12
+ return Path(__file__).resolve().parents[1] / "resources" / name
13
+
14
+
15
+ def icon_path() -> Path:
16
+ return _resource_path("audit_toolbox.png")
17
+
18
+
19
+ def manual_path() -> Path:
20
+ if getattr(sys, "frozen", False):
21
+ return _resource_path("使用说明.txt")
22
+ return Path(__file__).resolve().parents[3] / "packaging" / "使用说明.txt"
@@ -0,0 +1,90 @@
1
+ """后台任务执行器:在子线程里跑命令,把日志与结果投递到界面队列。"""
2
+
3
+ from __future__ import annotations
4
+
5
+ import queue
6
+ import threading
7
+ import time
8
+ import traceback
9
+ from typing import Callable, Iterable
10
+
11
+ from ..console import reset_log_state, set_task_log_sink
12
+ from ..errors import SyncError
13
+
14
+ Step = tuple[str, Callable[[], int]]
15
+
16
+
17
+ class TaskRunner:
18
+ """串行执行若干步骤;同一时刻只允许一个任务。"""
19
+
20
+ def __init__(self) -> None:
21
+ self.queue: queue.Queue[tuple[str, object]] = queue.Queue()
22
+ self.busy = False
23
+
24
+ def submit(self, steps: Iterable[Step]) -> bool:
25
+ steps = list(steps)
26
+ if self.busy or not steps:
27
+ return False
28
+ self.busy = True
29
+
30
+ def worker() -> None:
31
+ started = time.perf_counter()
32
+ done: list[tuple[str, int]] = []
33
+ results: list[object] = []
34
+ current_title = steps[0][0]
35
+ reset_log_state()
36
+ set_task_log_sink(lambda message: self.queue.put(("log", message)))
37
+ try:
38
+ for title, func in steps:
39
+ current_title = title
40
+ self.queue.put(("step", title))
41
+ result = func()
42
+ results.append(result)
43
+ code = result if isinstance(result, int) else 0
44
+ done.append((title, code))
45
+ if code != 0:
46
+ self.busy = False
47
+ self.queue.put(
48
+ ("error", {
49
+ "title": title,
50
+ "message": f"步骤返回码 {code},已停止后续步骤。",
51
+ "elapsed": time.perf_counter() - started,
52
+ })
53
+ )
54
+ return
55
+ self.busy = False
56
+ self.queue.put(("done", {
57
+ "steps": done,
58
+ "results": results,
59
+ "elapsed": time.perf_counter() - started,
60
+ }))
61
+ except SyncError as exc:
62
+ self.busy = False
63
+ self.queue.put(
64
+ ("error", {"title": current_title, "message": str(exc), "elapsed": time.perf_counter() - started})
65
+ )
66
+ except Exception as exc: # 未预期异常:把堆栈写进日志便于排查
67
+ self.busy = False
68
+ self.queue.put(
69
+ (
70
+ "error",
71
+ {
72
+ "title": current_title,
73
+ "message": f"{type(exc).__name__}: {exc}\n{traceback.format_exc()}",
74
+ "elapsed": time.perf_counter() - started,
75
+ },
76
+ )
77
+ )
78
+ finally:
79
+ set_task_log_sink(None)
80
+
81
+ threading.Thread(target=worker, name="wesync-gui-task", daemon=True).start()
82
+ return True
83
+
84
+ def drain(self) -> list[tuple[str, object]]:
85
+ items: list[tuple[str, object]] = []
86
+ while True:
87
+ try:
88
+ items.append(self.queue.get_nowait())
89
+ except queue.Empty:
90
+ return items
@@ -0,0 +1,50 @@
1
+ """界面偏好持久化:窗口尺寸与上次使用的文件(写在项目内,不进入系统目录)。"""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import os
7
+ import tempfile
8
+ from pathlib import Path
9
+
10
+ from ..fsops import project_root
11
+
12
+
13
+ def _config_path() -> Path:
14
+ return project_root() / ".wesync_ui.json"
15
+
16
+
17
+ def load(*, strict: bool = False) -> dict:
18
+ path = _config_path()
19
+ if not path.exists():
20
+ return {}
21
+ try:
22
+ with path.open("r", encoding="utf-8") as handle:
23
+ data = json.load(handle)
24
+ return data if isinstance(data, dict) else {}
25
+ except Exception:
26
+ if strict:
27
+ raise
28
+ return {}
29
+
30
+
31
+ def save(values: dict, *, repair: bool = False) -> None:
32
+ path = _config_path()
33
+ try:
34
+ data = load(strict=True)
35
+ except (json.JSONDecodeError, UnicodeDecodeError):
36
+ if not repair:
37
+ raise
38
+ data = {}
39
+ data.update(values)
40
+ path.parent.mkdir(parents=True, exist_ok=True)
41
+ fd, temp_name = tempfile.mkstemp(prefix=f".{path.name}.", dir=path.parent)
42
+ staged = Path(temp_name)
43
+ try:
44
+ with os.fdopen(fd, "w", encoding="utf-8") as handle:
45
+ json.dump(data, handle, ensure_ascii=False, indent=2)
46
+ handle.flush()
47
+ os.fsync(handle.fileno())
48
+ os.replace(staged, path)
49
+ finally:
50
+ staged.unlink(missing_ok=True)