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
@@ -1,19 +1,13 @@
1
- """同步页:Excel → Word(含增删行、增删列、按「书签:新增」标记创建新表)。"""
1
+ """同步页:Excel → Word(含增删行、增删列,同步「表格汇总」与「新增表格」)。"""
2
2
 
3
3
  from __future__ import annotations
4
4
 
5
- from PySide6.QtCore import Qt
6
5
  from PySide6.QtWidgets import (
7
6
  QComboBox,
8
- QDialog,
9
- QGridLayout,
10
7
  QHBoxLayout,
11
8
  QHeaderView,
12
9
  QLabel,
13
- QLineEdit,
14
- QMessageBox,
15
10
  QPushButton,
16
- QSpinBox,
17
11
  QTabWidget,
18
12
  QTableWidget,
19
13
  QTableWidgetItem,
@@ -25,12 +19,13 @@ from ... import api
25
19
  from ...console import set_log_sink
26
20
  from ...errors import SyncError
27
21
  from ..widgets.cards import make_checkbutton
22
+ from ..widgets.chips import ChipRow
28
23
  from ._page import BasePage
29
24
 
30
25
 
31
26
  class WritebackPage(BasePage):
32
27
  title = "同步Word"
33
- subtitle = "工作簿改动回写 Word,保留格式、支持增删行列;带「新增」标记的表块会在 Word 里建出新表。"
28
+ subtitle = "工作簿改动回写 Word;保留格式,支持增删行列与新增表格。"
34
29
 
35
30
  def build(self, body: QWidget) -> None:
36
31
  card = self.card(body)
@@ -57,35 +52,40 @@ class WritebackPage(BasePage):
57
52
  content_row.addWidget(box)
58
53
  content_row.addStretch(1)
59
54
  layout.addLayout(content_row)
60
- self.wb_keep_highlight = make_checkbutton(tab, "同步标注后保留高亮(不去色,便于复核)", True)
55
+ self.wb_keep_highlight = make_checkbutton(tab, "保留标注高亮", True)
61
56
  self.wb_keep_highlight.setVisible(False)
62
57
  self.sync_marks.toggled.connect(self.wb_keep_highlight.setVisible)
63
58
  layout.addWidget(self.wb_keep_highlight)
64
- self.tip_label(
65
- tab,
66
- "标注/占位符分别读取「链接标注」「正文信息」工作表(在「标注与占位」页导出并填写);"
67
- "未填的内容保留原样并逐条警告。备份、改动清单、删除✕行只作用于表格。",
68
- )
69
- self.force = make_checkbutton(tab, "强制跳过文件占用检查(文件仍被打开时用)", False)
70
- layout.addWidget(self.force)
71
- self.backup = make_checkbutton(tab, "同步前创建备份(取消勾选则不备份,文件直接覆盖)", False)
72
- layout.addWidget(self.backup)
73
- self.changelog = make_checkbutton(tab, "同时导出改动清单(逐格 旧值→新值,存到工作簿旁,作复核底稿)", False)
74
- layout.addWidget(self.changelog)
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"]
75
69
  self.delete_empty = make_checkbutton(
76
- tab, "删除✕行:同步时把 B 列✕(导出时判定为空)的行连 Word 行一起删除;Excel 该行保留为「已删」,改回✓可恢复", False
70
+ tab, "删除 B 列✕行;Excel 保留为「已删」,改✓可恢复", False
77
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"]
78
83
  layout.addWidget(self.delete_empty)
79
84
 
80
85
  row = self.button_row(tab, lambda: self._start(True), lambda: self._start(False), "仅预演", "开始同步")
81
- btn = QPushButton("追加新表块")
82
- btn.clicked.connect(lambda _checked=False: self._append_block())
83
- row.layout().insertWidget(row.layout().count() - 1, btn)
84
86
  self.tip_label(
85
87
  tab,
86
- "要在报告里加一张新表:点「追加新表块」→ 选插在哪张表下面 → 新表块会直接插到 Excel 里那张表的下面"
87
- "(后续表块下移、编号自动顺延)→ 填好内容(首行为表头,可合并单元格、写公式)→ 点「开始同步」,"
88
- "新表会建到 Word 里同一位置。",
88
+ "Word 新增表格后,先在「创建Excel」点「增量导出」,再在这里同步。",
89
89
  )
90
90
  layout.addStretch(1)
91
91
  return tab
@@ -99,9 +99,7 @@ class WritebackPage(BasePage):
99
99
  layout.setSpacing(10)
100
100
  self.tip_label(
101
101
  tab,
102
- "排序设置:给某张表选定金额列后,每次同步自动按设置重排(Excel 与 Word 一起排),"
103
- "设置保存在工作簿里、随文件走,不用每次重设。项目名为「其他」的行不参与排序,放在合计行之前;"
104
- "表头与合计行不动;数据区有合并单元格的表会跳过排序并提示。",
102
+ "按金额列自动排序 Excel 与 Word;设置随工作簿保存。「其他」行留在合计前,合并单元格表跳过。",
105
103
  )
106
104
  row = QHBoxLayout()
107
105
  row.setSpacing(8)
@@ -123,7 +121,7 @@ class WritebackPage(BasePage):
123
121
  btns = QHBoxLayout()
124
122
  btns.setSpacing(12)
125
123
  refresh = QPushButton("刷新清单")
126
- refresh.clicked.connect(lambda _checked=False: self._reload_sorts())
124
+ refresh.clicked.connect(lambda _checked=False: self._reload_sorts_background())
127
125
  btns.addWidget(refresh)
128
126
  save = QPushButton("保存排序设置")
129
127
  save.setObjectName("Primary")
@@ -136,85 +134,10 @@ class WritebackPage(BasePage):
136
134
  layout.addLayout(btns)
137
135
  self.sort_status = self.tip_label(tab, "尚未加载。选择 Word 文件并生成工作簿后,点「刷新清单」。")
138
136
  self._sort_items: list[dict] = []
137
+ self._sort_file_key: tuple[str | None, str | None] | None = None
139
138
  layout.addStretch(1)
140
139
  return tab
141
140
 
142
- def _append_block(self) -> None:
143
- if not self.ctx.require_docx():
144
- return
145
- excel = self.ctx.workbook_path()
146
- if not excel.exists():
147
- self.ctx.error("未找到工作簿", f"未找到工作簿:\n{excel}\n\n请先执行「导出表格到 Excel」生成工作簿。")
148
- return
149
- dlg = QDialog(self)
150
- dlg.setWindowTitle("追加新表块")
151
- dlg.setModal(True)
152
- grid = QGridLayout(dlg)
153
- grid.setContentsMargins(16, 16, 16, 16)
154
- grid.setHorizontalSpacing(8)
155
- grid.setVerticalSpacing(6)
156
- grid.addWidget(QLabel("表名(将成为 Word 里的表标题):"), 0, 0, 1, 2)
157
- name_edit = QLineEdit()
158
- grid.addWidget(name_edit, 1, 0, 1, 2)
159
- grid.addWidget(QLabel("行数(含表头)"), 2, 0)
160
- rows_spin = QSpinBox()
161
- rows_spin.setRange(1, 200)
162
- rows_spin.setValue(5)
163
- grid.addWidget(rows_spin, 2, 1)
164
- grid.addWidget(QLabel("列数"), 3, 0)
165
- cols_spin = QSpinBox()
166
- cols_spin.setRange(1, 30)
167
- cols_spin.setValue(4)
168
- grid.addWidget(cols_spin, 3, 1)
169
- grid.addWidget(QLabel("插在哪张表下面(Excel 与 Word 建表位置一致)"), 4, 0, 1, 2)
170
- pos_combo = QComboBox()
171
- pos_map: dict[str, str] = {}
172
- pos_combo.addItem("(最后一张表下面)")
173
- try:
174
- for item in api.list_table_blocks(self.ctx.docx, self.ctx.excel):
175
- short = item["name"].split(" · 章节:")[0]
176
- if len(short) > 24:
177
- short = short[:23] + "…"
178
- label = f"{item['code']} · {short}" if short else item["code"]
179
- pos_map[label] = item["code"]
180
- pos_combo.addItem(label)
181
- except SyncError:
182
- pass
183
- grid.addWidget(pos_combo, 5, 0, 1, 2)
184
-
185
- def ok() -> None:
186
- after = pos_map.get(pos_combo.currentText())
187
- set_log_sink(lambda message: self.ctx.log(message))
188
- try:
189
- code = api.run_append_table_block(
190
- self.ctx.docx,
191
- self.ctx.excel,
192
- name=name_edit.text(),
193
- nrows=rows_spin.value(),
194
- ncols=cols_spin.value(),
195
- after=after,
196
- )
197
- except SyncError as exc:
198
- QMessageBox.critical(dlg, "追加失败", str(exc))
199
- return
200
- finally:
201
- set_log_sink(None)
202
- dlg.accept()
203
- self.ctx.log(f"新表块 {code} 已就绪:在 Excel 填好内容后点「开始同步」即可在 Word 里建表。", "ok")
204
-
205
- btns = QHBoxLayout()
206
- btns.addStretch(1)
207
- cancel = QPushButton("取消")
208
- cancel.clicked.connect(lambda _checked=False: dlg.reject())
209
- btns.addWidget(cancel)
210
- append = QPushButton("追加")
211
- append.setObjectName("Primary")
212
- append.clicked.connect(lambda _checked=False: ok())
213
- btns.addWidget(append)
214
- grid.addLayout(btns, 6, 0, 1, 2)
215
- name_edit.returnPressed.connect(ok)
216
- dlg.exec()
217
-
218
141
  def _start(self, dry_run: bool) -> None:
219
142
  if not self.ctx.require_docx():
220
143
  return
@@ -227,7 +150,11 @@ class WritebackPage(BasePage):
227
150
  content_text = "+".join(
228
151
  name for name, on in (("表格", tables), ("标注", marks), ("占位符", placeholders)) if on
229
152
  )
230
- excel = self.ctx.workbook_path()
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)
231
158
  steps: list[tuple[str, object]] = []
232
159
 
233
160
  if not excel.exists():
@@ -240,7 +167,12 @@ class WritebackPage(BasePage):
240
167
  ):
241
168
  self.ctx.log("已取消:缺少工作簿,未执行同步。", "muted")
242
169
  return
243
- steps.append(("导出到 Excel(生成工作簿)", lambda: api.run_export(self.ctx.docx, self.ctx.excel)))
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
+ )))
244
176
  elif not dry_run:
245
177
  backup_note = (
246
178
  "同步前会自动备份 Word(若数据有变化)。" if self.backup.isChecked()
@@ -256,6 +188,9 @@ class WritebackPage(BasePage):
256
188
 
257
189
  force = self.force.isChecked()
258
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()
259
194
  changelog = self.changelog.isChecked()
260
195
  delete_empty = self.delete_empty.isChecked()
261
196
  keep_highlight = self.wb_keep_highlight.isChecked()
@@ -264,16 +199,18 @@ class WritebackPage(BasePage):
264
199
  steps.append(
265
200
  (
266
201
  label,
267
- lambda: api.run_writeback(self.ctx.docx, self.ctx.excel, dry_run=dry_run, force=force, backup=backup, changelog=changelog, delete_empty_rows=delete_empty),
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),
268
203
  )
269
204
  )
270
205
  else:
271
206
  def run_sync() -> int:
272
207
  api.run_sync_content(
273
- self.ctx.docx, self.ctx.excel,
208
+ docx, custom_excel,
274
209
  tables=tables, marks=marks, placeholders=placeholders,
275
210
  keep_highlight=keep_highlight, dry_run=dry_run, force=force,
276
211
  backup=backup, changelog=changelog, delete_empty_rows=delete_empty,
212
+ table_zero=table_zero, mark_zero=mark_zero,
213
+ placeholder_zero=placeholder_zero,
277
214
  )
278
215
  return 0
279
216
 
@@ -282,22 +219,71 @@ class WritebackPage(BasePage):
282
219
 
283
220
  # ---------- 排序设置 ----------
284
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
+
285
228
  def on_show(self) -> None:
286
- if not self._sort_items:
287
- self._reload_sorts(quiet=True)
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)
288
261
 
289
262
  def _reload_sorts(self, quiet: bool = False) -> None:
263
+ key = self._file_key()
264
+ docx, excel = self.ctx.docx, self.ctx.excel
290
265
  self._sort_items = []
291
266
  self.sort_table.clear()
292
267
  self.sort_column.clear()
293
- if self.ctx.docx is None or not self.ctx.workbook_path().exists():
268
+ if docx is None or excel is None or not excel.exists():
269
+ self._sort_file_key = key
294
270
  self.sort_status.setText("尚未加载。选择 Word 文件并生成工作簿后,点「刷新清单」。")
295
271
  return
296
272
  try:
297
- self._sort_items = api.list_table_sorts(self.ctx.docx, self.ctx.excel)
298
- except SyncError as exc:
273
+ items = api.list_table_sorts(docx, excel)
274
+ except Exception as exc:
275
+ self._sort_file_key = key
299
276
  self.sort_status.setText(f"加载失败:{exc}")
300
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()
301
287
  for item in self._sort_items:
302
288
  short = item["name"].split(" · 章节:")[0]
303
289
  if len(short) > 24:
@@ -310,8 +296,6 @@ class WritebackPage(BasePage):
310
296
  self.sort_status.setText(f"共 {len(self._sort_items)} 张表可设置排序;带「已设」标记的表同步时会自动排序。")
311
297
  else:
312
298
  self.sort_status.setText("工作簿里没有可设置排序的表块。")
313
- if not quiet:
314
- self.ctx.log("排序清单已刷新。", "muted")
315
299
 
316
300
  def _sort_table_changed(self) -> None:
317
301
  self.sort_column.clear()
@@ -328,6 +312,15 @@ class WritebackPage(BasePage):
328
312
  self.sort_column.setCurrentText(item["sort_column"])
329
313
  self.sort_dir.setCurrentIndex(0 if item["descending"] else 1)
330
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
+
331
324
  def _save_sort(self) -> None:
332
325
  idx = self.sort_table.currentIndex()
333
326
  if not 0 <= idx < len(self._sort_items):
@@ -337,19 +330,22 @@ class WritebackPage(BasePage):
337
330
  self.ctx.info("未选择金额列", "请先选择按哪一列金额排序。")
338
331
  return
339
332
  item = self._sort_items[idx]
340
- set_log_sink(lambda message: self.ctx.log(message))
341
- try:
342
- api.set_table_sort(
343
- self.ctx.docx, self.ctx.excel,
344
- code=item["code"], column=self.sort_column.currentText(),
345
- descending=self.sort_dir.currentIndex() == 0,
346
- )
347
- except SyncError as exc:
348
- self.ctx.error("保存排序设置失败", str(exc))
333
+ if self._file_key() != self._sort_file_key:
334
+ self.ctx.error("文件已切换", "排序清单与当前文件不一致,请刷新清单后重试。")
335
+ self._reload_sorts_background()
349
336
  return
350
- finally:
351
- set_log_sink(None)
352
- self._reload_sorts(quiet=True)
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
+ )
353
349
 
354
350
  def _clear_sort(self) -> None:
355
351
  idx = self.sort_table.currentIndex()
@@ -357,15 +353,17 @@ class WritebackPage(BasePage):
357
353
  self.ctx.info("未选择", "请先点「刷新清单」并选择表。")
358
354
  return
359
355
  item = self._sort_items[idx]
360
- set_log_sink(lambda message: self.ctx.log(message))
361
- try:
362
- api.clear_table_sort(self.ctx.docx, self.ctx.excel, code=item["code"])
363
- except SyncError as exc:
364
- self.ctx.error("清除排序设置失败", str(exc))
356
+ if self._file_key() != self._sort_file_key:
357
+ self.ctx.error("文件已切换", "排序清单与当前文件不一致,请刷新清单后重试。")
358
+ self._reload_sorts_background()
365
359
  return
366
- finally:
367
- set_log_sink(None)
368
- self._reload_sorts(quiet=True)
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
+ )
369
367
 
370
368
  # ---------- 差异比对 ----------
371
369
 
@@ -376,15 +374,14 @@ class WritebackPage(BasePage):
376
374
  layout.setSpacing(10)
377
375
  self.tip_label(
378
376
  tab,
379
- "差异比对:只读列出 Word 与工作簿当前不一致的单元格(旧值→新值),不写任何文件,"
380
- "供同步前复核。点「差异比对」刷新下表;可「导出差异表」存档。",
377
+ "只读比对 Word 与工作簿差异(旧值→新值),不写文件;可导出复核。",
381
378
  )
382
379
  row = QHBoxLayout()
383
380
  row.setSpacing(12)
384
381
  refresh = QPushButton("差异比对")
385
382
  refresh.setObjectName("Primary")
386
383
  refresh.setToolTip("只读列出 Word 与工作簿不一致的单元格(旧值→新值),不写任何文件。")
387
- refresh.clicked.connect(lambda _checked=False: self._diff())
384
+ refresh.clicked.connect(lambda _checked=False: self._diff_background())
388
385
  row.addWidget(refresh)
389
386
  export = QPushButton("导出差异表")
390
387
  export.clicked.connect(lambda _checked=False: self._export_diff())
@@ -402,23 +399,43 @@ class WritebackPage(BasePage):
402
399
  self.diff_table.setMinimumHeight(180)
403
400
  layout.addWidget(self.diff_table)
404
401
  self._diff_records: list[dict] = []
402
+ self._diff_file_key: tuple[str | None, str | None] | None = None
405
403
  return tab
406
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
+
407
426
  def _diff(self) -> None:
408
427
  if not self.ctx.require_docx():
409
428
  return
410
429
  if not self.ctx.workbook_path().exists():
411
430
  self.ctx.error("未找到工作簿", "请先执行「导出表格到 Excel」生成工作簿,再比对差异。")
412
431
  return
413
- set_log_sink(lambda message: self.ctx.log(message))
414
432
  try:
415
433
  records = api.scan_writeback_diff(self.ctx.docx, self.ctx.excel)
416
- except SyncError as exc:
434
+ except Exception as exc:
417
435
  self.ctx.error("差异比对失败", str(exc))
418
436
  return
419
- finally:
420
- set_log_sink(None)
421
437
  self._diff_records = records
438
+ self._diff_file_key = self._file_key()
422
439
  self._fill_diff(records)
423
440
 
424
441
  def _fill_diff(self, records: list[dict]) -> None:
@@ -440,9 +457,13 @@ class WritebackPage(BasePage):
440
457
  if not self._diff_records:
441
458
  self.ctx.info("无差异可导出", "请先点「差异比对」;当前没有差异记录。")
442
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
443
464
  set_log_sink(lambda message: self.ctx.log(message))
444
465
  try:
445
- path = api.export_diff_report(self.ctx.docx, self.ctx.excel, self._diff_records)
466
+ path = api.export_diff_report(docx, excel, self._diff_records)
446
467
  except SyncError as exc:
447
468
  self.ctx.error("导出差异表失败", str(exc))
448
469
  return
@@ -8,7 +8,7 @@ import time
8
8
  import traceback
9
9
  from typing import Callable, Iterable
10
10
 
11
- from ..console import reset_log_state, set_log_sink
11
+ from ..console import reset_log_state, set_task_log_sink
12
12
  from ..errors import SyncError
13
13
 
14
14
  Step = tuple[str, Callable[[], int]]
@@ -30,37 +30,53 @@ class TaskRunner:
30
30
  def worker() -> None:
31
31
  started = time.perf_counter()
32
32
  done: list[tuple[str, int]] = []
33
+ results: list[object] = []
34
+ current_title = steps[0][0]
33
35
  reset_log_state()
34
- set_log_sink(lambda message: self.queue.put(("log", message)))
36
+ set_task_log_sink(lambda message: self.queue.put(("log", message)))
35
37
  try:
36
38
  for title, func in steps:
39
+ current_title = title
37
40
  self.queue.put(("step", title))
38
- code = func()
39
- if not isinstance(code, int):
40
- code = 0 # 步骤返回摘要等非整数视为成功,避免误报执行失败
41
+ result = func()
42
+ results.append(result)
43
+ code = result if isinstance(result, int) else 0
41
44
  done.append((title, code))
42
- if code not in (0, None):
43
- self.queue.put(("log", f"步骤「{title}」返回码 {code},已停止后续步骤"))
44
- break
45
- self.queue.put(("done", {"steps": done, "elapsed": time.perf_counter() - started}))
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
+ }))
46
61
  except SyncError as exc:
62
+ self.busy = False
47
63
  self.queue.put(
48
- ("error", {"title": steps[-1][0], "message": str(exc), "elapsed": time.perf_counter() - started})
64
+ ("error", {"title": current_title, "message": str(exc), "elapsed": time.perf_counter() - started})
49
65
  )
50
66
  except Exception as exc: # 未预期异常:把堆栈写进日志便于排查
67
+ self.busy = False
51
68
  self.queue.put(
52
69
  (
53
70
  "error",
54
71
  {
55
- "title": steps[-1][0],
72
+ "title": current_title,
56
73
  "message": f"{type(exc).__name__}: {exc}\n{traceback.format_exc()}",
57
74
  "elapsed": time.perf_counter() - started,
58
75
  },
59
76
  )
60
77
  )
61
78
  finally:
62
- set_log_sink(None)
63
- self.busy = False
79
+ set_task_log_sink(None)
64
80
 
65
81
  threading.Thread(target=worker, name="wesync-gui-task", daemon=True).start()
66
82
  return True
@@ -3,6 +3,8 @@
3
3
  from __future__ import annotations
4
4
 
5
5
  import json
6
+ import os
7
+ import tempfile
6
8
  from pathlib import Path
7
9
 
8
10
  from ..fsops import project_root
@@ -12,23 +14,37 @@ def _config_path() -> Path:
12
14
  return project_root() / ".wesync_ui.json"
13
15
 
14
16
 
15
- def load() -> dict:
17
+ def load(*, strict: bool = False) -> dict:
16
18
  path = _config_path()
19
+ if not path.exists():
20
+ return {}
17
21
  try:
18
22
  with path.open("r", encoding="utf-8") as handle:
19
23
  data = json.load(handle)
20
24
  return data if isinstance(data, dict) else {}
21
25
  except Exception:
26
+ if strict:
27
+ raise
22
28
  return {}
23
29
 
24
30
 
25
- def save(values: dict) -> None:
31
+ def save(values: dict, *, repair: bool = False) -> None:
26
32
  path = _config_path()
27
- data = load()
33
+ try:
34
+ data = load(strict=True)
35
+ except (json.JSONDecodeError, UnicodeDecodeError):
36
+ if not repair:
37
+ raise
38
+ data = {}
28
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)
29
43
  try:
30
- path.parent.mkdir(parents=True, exist_ok=True)
31
- with path.open("w", encoding="utf-8") as handle:
44
+ with os.fdopen(fd, "w", encoding="utf-8") as handle:
32
45
  json.dump(data, handle, ensure_ascii=False, indent=2)
33
- except Exception:
34
- pass
46
+ handle.flush()
47
+ os.fsync(handle.fileno())
48
+ os.replace(staged, path)
49
+ finally:
50
+ staged.unlink(missing_ok=True)