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,156 @@
1
+ """空白表识别与删除:整表全空 / 仅表头有字的表格列为候选,确认后可连表标题一起删除。
2
+
3
+ 判定口径(保守,宁可漏报不误报):
4
+ - 首列(多为行次/项目名称)不参与判断;单列表除外,首列即全部内容;
5
+ - 整表全空:除首列外所有单元格都没有文字(空白字符不算文字);
6
+ - 仅表头有字:有文字的行全部是表头行(w:tblHeader 标记,未标记时按首行),
7
+ 且表头之外至少还有一行数据区、数据区全空。
8
+ 数据区只有 —、0 等占位内容的表**不算**空白。
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import re
14
+
15
+ from docx.oxml.ns import qn
16
+
17
+ from .config import DATE_RE
18
+ from .docx_bookmarks import is_tool_bookmark
19
+ from .docx_grid import body_items, build_cellmap, header_rows, para_text, text_grid
20
+ from .docx_meta import clean_paragraph_text
21
+
22
+ # 章节大标题(一、/第X节 等)不是表标题,删表时不应连带删除
23
+ SECTION_RE = re.compile(r"^(第[一二三四五六七八九十百\d]+[节章部分]|[一二三四五六七八九十]+、)")
24
+
25
+ CAPTION_MAX_LEN = 60
26
+ SENTENCE_ENDS = "。;!?;!?"
27
+
28
+
29
+ def _looks_like_caption(text: str) -> bool:
30
+ if not text or len(text) > CAPTION_MAX_LEN:
31
+ return False
32
+ if SECTION_RE.match(text):
33
+ return False
34
+ return text[-1] not in SENTENCE_ENDS
35
+
36
+
37
+ def _caption_before(items: list, pos: int):
38
+ """从表格位置向前找表标题:跳过空段与日期行,遇到正文句/另一张表即止。
39
+
40
+ 返回 (标题段落元素或 None, 标题文字, 标题与表格之间的空段/日期段列表)。
41
+ """
42
+ extras: list = []
43
+ idx = pos - 1
44
+ while idx >= 0:
45
+ kind, obj = items[idx]
46
+ if kind != "p":
47
+ break
48
+ text = clean_paragraph_text(para_text(obj._p))
49
+ if text == "" or DATE_RE.match(text):
50
+ extras.append(obj._p)
51
+ idx -= 1
52
+ continue
53
+ if _looks_like_caption(text):
54
+ return obj._p, text, extras
55
+ break
56
+ return None, "", []
57
+
58
+
59
+ def _blank_kind(trs, grid) -> str | None:
60
+ nrows = len(trs)
61
+ ncols = max((len(row) for row in grid), default=0)
62
+ # 首列多为行次/项目名称,不参与空白判断;单列表除外(首列即全部内容)
63
+ start_col = 1 if ncols >= 2 else 0
64
+ filled = [
65
+ (r, c)
66
+ for r, row in enumerate(grid)
67
+ for c, text in enumerate(row)
68
+ if c >= start_col and text is not None and text.strip()
69
+ ]
70
+ if not filled:
71
+ return "整表全空"
72
+ heads = header_rows(trs) or {0}
73
+ if nrows > max(heads) + 1 and all(r in heads for r, _ in filled):
74
+ return "仅表头有字"
75
+ return None
76
+
77
+
78
+ def find_blank_tables(doc) -> list[dict]:
79
+ """扫描全文,返回空白表候选清单(只读,不改文档)。"""
80
+ items = body_items(doc)
81
+ candidates: list[dict] = []
82
+ table_index = -1
83
+ for pos, (kind, obj) in enumerate(items):
84
+ if kind != "tbl":
85
+ continue
86
+ table_index += 1
87
+ tbl = obj._tbl
88
+ trs, cellmap, ncols = build_cellmap(tbl)
89
+ grid = text_grid(tbl, cellmap)
90
+ blank_kind = _blank_kind(trs, grid)
91
+ if blank_kind is None:
92
+ continue
93
+ caption_p, caption_text, extra_ps = _caption_before(items, pos)
94
+ candidates.append(
95
+ {
96
+ "no": len(candidates) + 1,
97
+ "index": table_index,
98
+ "code": f"T{table_index + 1:02d}",
99
+ "kind": blank_kind,
100
+ "nrows": len(trs),
101
+ "ncols": ncols,
102
+ "tbl": tbl,
103
+ "caption_p": caption_p,
104
+ "caption_text": caption_text,
105
+ "extra_ps": extra_ps,
106
+ }
107
+ )
108
+ return candidates
109
+
110
+
111
+ def _tool_bookmark_ids(doc) -> set[str]:
112
+ ids = set()
113
+ for el in doc.element.body.iter(qn("w:bookmarkStart")):
114
+ name = el.get(qn("w:name")) or ""
115
+ if is_tool_bookmark(name):
116
+ ids.add(el.get(qn("w:id")))
117
+ return ids
118
+
119
+
120
+ def _cleanup_orphan_bookmarks(doc, tool_ids: set[str]) -> int:
121
+ """删表/删标题后,清掉失去配对的本工具书签端点(Word 自带书签不动)。"""
122
+ body = doc.element.body
123
+ start_ids = {el.get(qn("w:id")) for el in body.iter(qn("w:bookmarkStart"))}
124
+ end_ids = {el.get(qn("w:id")) for el in body.iter(qn("w:bookmarkEnd"))}
125
+ removed = 0
126
+ for el in list(body.iter(qn("w:bookmarkStart"))):
127
+ if el.get(qn("w:id")) in tool_ids and el.get(qn("w:id")) not in end_ids:
128
+ el.getparent().remove(el)
129
+ removed += 1
130
+ for el in list(body.iter(qn("w:bookmarkEnd"))):
131
+ if el.get(qn("w:id")) in tool_ids and el.get(qn("w:id")) not in start_ids:
132
+ el.getparent().remove(el)
133
+ removed += 1
134
+ return removed
135
+
136
+
137
+ def delete_blank_tables(doc, selected: list[tuple[dict, bool]]) -> dict:
138
+ """按选择删除空白表。selected 为 (候选, 是否连表标题一起删) 列表。
139
+
140
+ 返回 {"tables": 删表数, "captions": 删标题数, "bookmarks": 清理书签端点数}。
141
+ """
142
+ tool_ids = _tool_bookmark_ids(doc)
143
+ removed_tables = 0
144
+ removed_captions = 0
145
+ for cand, with_caption in selected:
146
+ tbl = cand["tbl"]
147
+ if tbl.getparent() is not None:
148
+ tbl.getparent().remove(tbl)
149
+ removed_tables += 1
150
+ if with_caption and cand["caption_p"] is not None:
151
+ for p_el in [cand["caption_p"], *cand["extra_ps"]]:
152
+ if p_el.getparent() is not None:
153
+ p_el.getparent().remove(p_el)
154
+ removed_captions += 1
155
+ removed_bookmarks = _cleanup_orphan_bookmarks(doc, tool_ids)
156
+ return {"tables": removed_tables, "captions": removed_captions, "bookmarks": removed_bookmarks}
@@ -0,0 +1,287 @@
1
+ """Word 书签层:书签读写、Table_ 随机命名与旧书签迁移、遗留〔→Excel〕文字与超链接域清理。"""
2
+
3
+ import secrets
4
+ import string
5
+ from docx.oxml import OxmlElement
6
+ from docx.oxml.ns import qn
7
+ from .config import BOOKMARK_PREFIX, EXCEL_LINK_TEXT, LEGACY_BOOKMARK_RE
8
+
9
+
10
+ def bookmark_names(root) -> set[str]:
11
+ names = set()
12
+ for el in root.iter(qn("w:bookmarkStart")):
13
+ value = el.get(qn("w:name"))
14
+ if value:
15
+ names.add(value)
16
+ return names
17
+
18
+
19
+ def used_bookmark_ids(doc) -> set[int]:
20
+ ids = set()
21
+ for el in doc.element.body.iter():
22
+ if el.tag in (qn("w:bookmarkStart"), qn("w:bookmarkEnd")):
23
+ value = el.get(qn("w:id"))
24
+ if value and value.lstrip("-").isdigit():
25
+ ids.add(int(value))
26
+ return ids
27
+
28
+
29
+ def first_bookmark_in_table(tbl) -> str | None:
30
+ for el in tbl.iter(qn("w:bookmarkStart")):
31
+ name = el.get(qn("w:name"))
32
+ if name:
33
+ return name
34
+ return None
35
+
36
+
37
+ def pair_anchor_bookmarks_with_tables(doc, candidates: set[str]) -> dict[str, int]:
38
+ """把“锚点段落里的书签”与“紧随其后的表格”配对。
39
+
40
+ 只认 ``candidates`` 里的书签名(通常是工作簿 C 列记录的那些);段落里其它书签
41
+ (例如 ``_Toc…``)忽略、不打断配对。返回 ``{书签名: 表格序号}``(序号即 doc.tables 顺序):
42
+ 没出现在结果里的候选书签,即“对应的表格已从 Word 中删除”。
43
+ """
44
+ if not candidates:
45
+ return {}
46
+ pairing: dict[str, int] = {}
47
+ pending: str | None = None
48
+ table_index = -1
49
+ for child in doc.element.body.iterchildren():
50
+ tag = child.tag.split("}")[1]
51
+ if tag == "p":
52
+ hits = [
53
+ name
54
+ for name in (
55
+ el.get(qn("w:name")) for el in child.iter(qn("w:bookmarkStart"))
56
+ )
57
+ if name in candidates
58
+ ]
59
+ if hits:
60
+ pending = hits[-1] # 同一段落有多个候选书签时,取最后插入的那个
61
+ elif tag == "tbl":
62
+ table_index += 1
63
+ if pending is not None:
64
+ pairing[pending] = table_index
65
+ pending = None
66
+ return pairing
67
+
68
+
69
+ def unclaimed_table_indices(doc, pairing: dict[str, int]) -> list[int]:
70
+ """返回没有匹配到任何书签的 Word 表格序号列表。"""
71
+ claimed = set(pairing.values())
72
+ return [index for index in range(len(doc.tables)) if index not in claimed]
73
+
74
+
75
+ def table_index_map_by_bookmark(
76
+ doc, candidates: set[str], *, include_anchors: bool = False
77
+ ) -> dict[str, int]:
78
+ """书签名 → 表格序号;可兼容表内书签与旧式标题段落书签。"""
79
+ if not candidates:
80
+ return {}
81
+ result: dict[str, int] = {}
82
+ for index, tab in enumerate(doc.tables):
83
+ for el in tab._tbl.iter(qn("w:bookmarkStart")):
84
+ name = el.get(qn("w:name"))
85
+ if name in candidates:
86
+ result.setdefault(name, index)
87
+ if include_anchors:
88
+ for name, index in pair_anchor_bookmarks_with_tables(doc, candidates).items():
89
+ result.setdefault(name, index)
90
+ return result
91
+
92
+
93
+ def _ensure_cell_paragraph(tc, last: bool):
94
+ """取单元格里的第一个/最后一个段落,没有就补一个。"""
95
+ paragraphs = tc.findall(qn("w:p"))
96
+ if paragraphs:
97
+ return paragraphs[-1] if last else paragraphs[0]
98
+ paragraph = OxmlElement("w:p")
99
+ tc.append(paragraph)
100
+ return paragraph
101
+
102
+
103
+ def insert_table_bookmark(tbl, name: str, bookmark_id: int) -> bool:
104
+ """把书签**整表锚定**:起点在首行首格首段开头,终点在末行末格末段末尾。
105
+
106
+ 这样从 Excel 点“→定位Word表”会直接选中整张表格,而不是只停在标题行。
107
+ """
108
+ rows = tbl.findall(qn("w:tr"))
109
+ if not rows:
110
+ return False
111
+ first_tc = rows[0].find(qn("w:tc"))
112
+ last_row_cells = rows[-1].findall(qn("w:tc"))
113
+ if first_tc is None or not last_row_cells:
114
+ return False
115
+ last_tc = last_row_cells[-1]
116
+
117
+ start_paragraph = _ensure_cell_paragraph(first_tc, last=False)
118
+ end_paragraph = _ensure_cell_paragraph(last_tc, last=True)
119
+ start = OxmlElement("w:bookmarkStart")
120
+ start.set(qn("w:id"), str(bookmark_id))
121
+ start.set(qn("w:name"), name)
122
+ end = OxmlElement("w:bookmarkEnd")
123
+ end.set(qn("w:id"), str(bookmark_id))
124
+ pPr = start_paragraph.find(qn("w:pPr"))
125
+ if pPr is not None:
126
+ pPr.addnext(start)
127
+ else:
128
+ start_paragraph.insert(0, start)
129
+ end_paragraph.append(end)
130
+ return True
131
+
132
+
133
+ def next_bookmark_id(doc) -> int:
134
+ ids = used_bookmark_ids(doc)
135
+ return (max(ids) + 1) if ids else 1
136
+
137
+
138
+ def new_cpah_name(existing: set[str]) -> str:
139
+ """生成 Table_ + 4 位大写字母/数字随机书签名(如 Table_3K9Q)。"""
140
+ alphabet = string.ascii_uppercase + string.digits
141
+ while True:
142
+ name = BOOKMARK_PREFIX + "".join(secrets.choice(alphabet) for _ in range(4))
143
+ if name not in existing:
144
+ existing.add(name)
145
+ return name
146
+
147
+
148
+ def remove_bookmark(doc, name: str) -> bool:
149
+ body = doc.element.body
150
+ removed = False
151
+ for start in list(body.iter(qn("w:bookmarkStart"))):
152
+ if start.get(qn("w:name")) != name:
153
+ continue
154
+ bookmark_id = start.get(qn("w:id"))
155
+ start.getparent().remove(start)
156
+ removed = True
157
+ if bookmark_id is not None:
158
+ for end in list(body.iter(qn("w:bookmarkEnd"))):
159
+ if end.get(qn("w:id")) == bookmark_id:
160
+ end.getparent().remove(end)
161
+ return removed
162
+
163
+
164
+ def is_tool_bookmark(name: str) -> bool:
165
+ """判断是否本工具写入的书签(Table_ / 旧 CPAH_ / 旧 TBL_ / 标注 MRK_ 前缀)。
166
+
167
+ Word 自带书签(如 ``_Toc…`` 目录书签)不在此列,清理时保留不动。
168
+ """
169
+ return (
170
+ name.startswith(BOOKMARK_PREFIX)
171
+ or name.startswith("CPAH_")
172
+ or bool(LEGACY_BOOKMARK_RE.match(name))
173
+ or name.startswith("MRK_")
174
+ )
175
+
176
+
177
+ def clear_tool_bookmarks(doc) -> dict:
178
+ """删除文档里所有本工具书签(start 与配对的 end 一起移除)。
179
+
180
+ 返回 ``{"removed": int, "kept": int, "names": [...]}``:removed 为本工具书签数,
181
+ kept 为保留的 Word 自带书签数。
182
+ """
183
+ body = doc.element.body
184
+ names = bookmark_names(body)
185
+ tool_names = sorted(n for n in names if is_tool_bookmark(n))
186
+ kept = len(names) - len(tool_names)
187
+ removed = 0
188
+ for name in tool_names:
189
+ if remove_bookmark(doc, name):
190
+ removed += 1
191
+ return {"removed": removed, "kept": kept, "names": tool_names}
192
+
193
+
194
+ def bookmark_starts_in(p_el) -> list[str]:
195
+ return [b.get(qn("w:name")) for b in p_el.iter(qn("w:bookmarkStart")) if b.get(qn("w:name"))]
196
+
197
+
198
+ def _remove_link_fields(p_el) -> int:
199
+ """删除段落里由本工具写入的 HYPERLINK 域(Word 会把超链接规范化为域)。"""
200
+ removed = 0
201
+ runs = list(p_el.findall(qn("w:r")))
202
+ index = 0
203
+ while index < len(runs):
204
+ fld = runs[index].find(qn("w:fldChar"))
205
+ if fld is None or fld.get(qn("w:fldCharType")) != "begin":
206
+ index += 1
207
+ continue
208
+ depth = 0
209
+ end = index
210
+ instr_parts: list[str] = []
211
+ display_parts: list[str] = []
212
+ separated = False
213
+ while end < len(runs):
214
+ inner = runs[end].find(qn("w:fldChar"))
215
+ if inner is not None:
216
+ fld_type = inner.get(qn("w:fldCharType"))
217
+ if fld_type == "begin":
218
+ depth += 1
219
+ elif fld_type == "end":
220
+ depth -= 1
221
+ elif fld_type == "separate":
222
+ separated = True
223
+ for node in runs[end].findall(qn("w:instrText")):
224
+ instr_parts.append(node.text or "")
225
+ if separated:
226
+ for node in runs[end].findall(qn("w:t")):
227
+ display_parts.append(node.text or "")
228
+ if depth == 0 and end > index:
229
+ break
230
+ end += 1
231
+ instr = "".join(instr_parts)
232
+ display = "".join(display_parts)
233
+ ours = (
234
+ EXCEL_LINK_TEXT in display
235
+ or "_表格数据.xlsx" in instr
236
+ or '\\l "EX_T' in instr
237
+ )
238
+ if ours and "HYPERLINK" in instr.upper():
239
+ for run in runs[index : end + 1]:
240
+ p_el.remove(run)
241
+ removed += 1
242
+ runs = list(p_el.findall(qn("w:r")))
243
+ continue
244
+ index = end + 1
245
+ return removed
246
+
247
+
248
+ def _strip_marker_from_paragraph(p_el) -> int:
249
+ """删除段落文本中的〔→Excel〕(可能被 Word 拆成多个 run),其余文字与格式不动。"""
250
+ removed = 0
251
+ while True:
252
+ runs = list(p_el.findall(qn("w:r")))
253
+ full = "".join("".join(t.text or "" for t in run.findall(qn("w:t"))) for run in runs)
254
+ start = full.find(EXCEL_LINK_TEXT)
255
+ if start < 0:
256
+ return removed
257
+ end = start + len(EXCEL_LINK_TEXT)
258
+ removed += 1
259
+ offset = 0
260
+ for run in runs:
261
+ texts = run.findall(qn("w:t"))
262
+ run_text = "".join(t.text or "" for t in texts)
263
+ run_start, run_end = offset, offset + len(run_text)
264
+ offset = run_end
265
+ if run_end <= start or run_start >= end:
266
+ continue
267
+ new_text = run_text[: max(0, start - run_start)] + run_text[max(0, end - run_start) :]
268
+ if new_text == "" and run.find(qn("w:drawing")) is None:
269
+ p_el.remove(run)
270
+ continue
271
+ for idx, node in enumerate(texts):
272
+ node.text = new_text if idx == 0 else ""
273
+ node.set(qn("xml:space"), "preserve")
274
+
275
+
276
+ def cleanup_excel_markers(doc) -> int:
277
+ """删除 Word 里遗留的〔→Excel〕文字与超链接域,段落其余内容与格式不动。"""
278
+ removed = 0
279
+ for p_el in doc.element.body.iter(qn("w:p")):
280
+ for hyperlink in list(p_el.findall(qn("w:hyperlink"))):
281
+ text = "".join(t.text or "" for t in hyperlink.iter(qn("w:t")))
282
+ if EXCEL_LINK_TEXT in text:
283
+ p_el.remove(hyperlink)
284
+ removed += 1
285
+ removed += _remove_link_fields(p_el)
286
+ removed += _strip_marker_from_paragraph(p_el)
287
+ return removed
@@ -0,0 +1,257 @@
1
+ """列结构同步:用表头文本打分定位列、在 Word 中插入/删除列并同步合并区,空白新增列按表忽略。"""
2
+
3
+ import copy
4
+ import itertools
5
+ from docx.oxml import OxmlElement
6
+ from docx.oxml.ns import qn
7
+ from .config import MAX_COLUMN_SHIFT, SKIP_COLUMN
8
+ from .console import log
9
+ from .docx_edit import _remove_text_nodes
10
+ from .docx_grid import build_cellmap, cell_text, header_rows, parse_tc_props
11
+ from .errors import SyncError
12
+ from .valuefmt import display_cell
13
+
14
+
15
+ def _set_grid_span(tc, span: int) -> None:
16
+ tcPr = tc.find(qn("w:tcPr"))
17
+ if tcPr is None:
18
+ tcPr = OxmlElement("w:tcPr")
19
+ tc.insert(0, tcPr)
20
+ node = tcPr.find(qn("w:gridSpan"))
21
+ if span <= 1:
22
+ if node is not None:
23
+ tcPr.remove(node)
24
+ return
25
+ if node is None:
26
+ node = OxmlElement("w:gridSpan")
27
+ tcPr.append(node)
28
+ node.set(qn("w:val"), str(span))
29
+
30
+
31
+ def _clone_empty_tc(tc):
32
+ """克隆单元格格式(宽度/边框/对齐)并清空内容,作为新列的单元格。"""
33
+ new_tc = copy.deepcopy(tc)
34
+ tcPr = new_tc.find(qn("w:tcPr"))
35
+ if tcPr is not None:
36
+ for tag in ("w:vMerge", "w:gridSpan"):
37
+ node = tcPr.find(qn(tag))
38
+ if node is not None:
39
+ tcPr.remove(node)
40
+ for node in list(new_tc.iter(qn("w:bookmarkStart"))) + list(new_tc.iter(qn("w:bookmarkEnd"))):
41
+ parent = node.getparent()
42
+ if parent is not None:
43
+ parent.remove(node)
44
+ paragraphs = new_tc.findall(qn("w:p"))
45
+ for extra in paragraphs[1:]:
46
+ new_tc.remove(extra)
47
+ if paragraphs:
48
+ _remove_text_nodes(paragraphs[0])
49
+ else:
50
+ new_tc.append(OxmlElement("w:p"))
51
+ return new_tc
52
+
53
+
54
+ def _insert_tc_at(tr, pos: int) -> None:
55
+ col = 0
56
+ prev = None
57
+ for tc in tr.findall(qn("w:tc")):
58
+ span, _ = parse_tc_props(tc)
59
+ if col < pos < col + span:
60
+ _set_grid_span(tc, span + 1) # 插入点落在横向合并区内部:扩展合并
61
+ return
62
+ if col == pos:
63
+ tc.addprevious(_clone_empty_tc(tc))
64
+ return
65
+ prev = tc
66
+ col += span
67
+ if prev is None:
68
+ raise SyncError("表格行内没有可复制的单元格,无法插入列")
69
+ prev.addnext(_clone_empty_tc(prev))
70
+
71
+
72
+ def insert_word_column(tbl, pos: int) -> None:
73
+ grid = tbl.find(qn("w:tblGrid"))
74
+ if grid is not None:
75
+ cols = grid.findall(qn("w:gridCol"))
76
+ if cols:
77
+ source = cols[pos - 1] if 0 < pos <= len(cols) else cols[0]
78
+ new_col = copy.deepcopy(source)
79
+ if pos < len(cols):
80
+ cols[pos].addprevious(new_col)
81
+ else:
82
+ cols[-1].addnext(new_col)
83
+ for tr in tbl.findall(qn("w:tr")):
84
+ _insert_tc_at(tr, pos)
85
+
86
+
87
+ def delete_word_column(tbl, pos: int) -> None:
88
+ grid = tbl.find(qn("w:tblGrid"))
89
+ if grid is not None:
90
+ cols = grid.findall(qn("w:gridCol"))
91
+ if len(cols) <= 1:
92
+ raise SyncError("表格只剩一列,无法再删除")
93
+ if pos < len(cols):
94
+ grid.remove(cols[pos])
95
+ for tr in tbl.findall(qn("w:tr")):
96
+ col = 0
97
+ for tc in tr.findall(qn("w:tc")):
98
+ span, _ = parse_tc_props(tc)
99
+ if col <= pos < col + span:
100
+ if span > 1:
101
+ _set_grid_span(tc, span - 1)
102
+ else:
103
+ tr.remove(tc)
104
+ break
105
+ col += span
106
+
107
+
108
+ def _excel_cell_display(ws, row: int, col: int, cached=None) -> str:
109
+ cell = ws.cell(row, col)
110
+ value = cell.value
111
+ if isinstance(value, str) and value.startswith("=") and cached is not None:
112
+ value = cached.get((row, col))
113
+ return display_cell(cell, value).strip()
114
+
115
+
116
+ def _word_column_signatures(trs, cellmap, ncols: int) -> list[tuple[str, ...]]:
117
+ header_idx = sorted(header_rows(trs)) or list(range(min(2, len(trs))))
118
+ signatures = []
119
+ for col in range(ncols):
120
+ texts = []
121
+ for row in header_idx:
122
+ if row >= len(cellmap):
123
+ texts.append("")
124
+ continue
125
+ pos = cellmap[row][col]
126
+ texts.append(cell_text(pos.tc).strip() if (pos is not None and pos.owner) else "")
127
+ signatures.append(tuple(texts))
128
+ return signatures
129
+
130
+
131
+ def _excel_column_signatures(ws, grid_rows: list[int], ncols: int, header_count: int, cached=None, col0: int = 2) -> list[tuple[str, ...]]:
132
+ rows = grid_rows[: max(1, header_count)]
133
+ signatures = []
134
+ for col in range(ncols):
135
+ signatures.append(tuple(_excel_cell_display(ws, row, col0 + col, cached) for row in rows))
136
+ return signatures
137
+
138
+
139
+ def _score_mapping(word_sigs, excel_sigs, mapping: list[int | None]) -> tuple[float, int, int]:
140
+ """返回 (匹配得分, 参与比较的列数, 文本真正匹配上的单元格数)。"""
141
+ matched = 0.0
142
+ compared = 0
143
+ non_empty = 0
144
+ for excel_col, word_col in enumerate(mapping):
145
+ if word_col is None or word_col < 0 or word_col >= len(word_sigs):
146
+ continue
147
+ compared += 1
148
+ for word_text, excel_text in zip(word_sigs[word_col], excel_sigs[excel_col]):
149
+ if word_text and excel_text:
150
+ if word_text == excel_text:
151
+ matched += 1.0
152
+ non_empty += 1
153
+ elif not word_text and not excel_text:
154
+ matched += 0.5
155
+ score = matched / compared if compared else 0.0
156
+ return score, compared, non_empty
157
+
158
+
159
+ def _column_is_empty(ws, col: int, grid_rows: list[int], col0: int = 2) -> bool:
160
+ return all(_excel_cell_display(ws, row, col0 + col) == "" for row in grid_rows)
161
+
162
+
163
+ def plan_column_alignment(word_sigs, excel_sigs, word_ncols: int, excel_ncols: int, ws, grid_rows, code: str, col0: int = 2):
164
+ """用表头文本逐列比对,返回 Excel 列映射。
165
+
166
+ 映射值含义:整数 = 对应的旧 Word 列;None = 需要新增的 Word 列;
167
+ SKIP_COLUMN = 该 Excel 列在本表中整列空白,本次忽略(不写入 Word)。
168
+ """
169
+ if excel_ncols == word_ncols:
170
+ return list(range(word_ncols))
171
+ shift = abs(excel_ncols - word_ncols)
172
+ if shift > MAX_COLUMN_SHIFT:
173
+ raise SyncError(
174
+ f"{code}:Excel 与 Word 相差 {shift} 列,超出自动同步范围(最多 {MAX_COLUMN_SHIFT} 列)。"
175
+ f"请重新执行 export,或手工把列结构改回一致后重试"
176
+ )
177
+ best = None
178
+ if excel_ncols > word_ncols:
179
+ for combo in itertools.combinations(range(excel_ncols), shift):
180
+ inserted = set(combo)
181
+ mapping: list[int | None] = []
182
+ word_col = 0
183
+ for excel_col in range(excel_ncols):
184
+ if excel_col in inserted:
185
+ # 有内容的新增列同步到 Word;整列空白的新增列在本表中忽略
186
+ mapping.append(SKIP_COLUMN if _column_is_empty(ws, excel_col, grid_rows, col0) else None)
187
+ else:
188
+ mapping.append(word_col)
189
+ word_col += 1
190
+ score, compared, non_empty = _score_mapping(word_sigs, excel_sigs, mapping)
191
+ skips = sum(1 for value in mapping if value == SKIP_COLUMN)
192
+ inserts = sum(1 for value in mapping if value is None)
193
+ key = (round(score, 6), non_empty, skips, -inserts, -min(inserted))
194
+ if best is None or key > best[0]:
195
+ best = (key, mapping, min(inserted), compared, non_empty)
196
+ else:
197
+ for combo in itertools.combinations(range(word_ncols), shift):
198
+ deleted = set(combo)
199
+ remaining = [col for col in range(word_ncols) if col not in deleted]
200
+ mapping = list(remaining)
201
+ score, compared, non_empty = _score_mapping(word_sigs, excel_sigs, mapping)
202
+ key = (round(score, 6), non_empty, 0, -min(deleted))
203
+ if best is None or key > best[0]:
204
+ best = (key, mapping, min(deleted), compared, non_empty)
205
+ if best is None:
206
+ raise SyncError(f"{code}:无法判断列位置,请重新执行 export 或手工调整列结构")
207
+ score, compared, non_empty = best[0][0], best[3], best[4]
208
+ if compared < 2 or non_empty < 2 or score < 0.8:
209
+ raise SyncError(
210
+ f"{code}:Word 为 {word_ncols} 列、Excel 为 {excel_ncols} 列,表头文本匹配不足"
211
+ f"(得分 {score:.2f}、可比列 {compared}、真实匹配 {non_empty}),"
212
+ f"为避免写错列已跳过该表。请核对书签是否锚定正确,或重新执行 export"
213
+ )
214
+ return best[1]
215
+
216
+
217
+ def sync_columns(tbl, ws, block: dict, code: str, cached=None) -> tuple[list[int], int, int]:
218
+ """按 Excel 列结构同步 Word 表格的列,返回 (有效 Excel 列顺序, 新增列数, 删除列数)。"""
219
+ trs, cellmap, word_ncols = build_cellmap(tbl)
220
+ excel_ncols = block["ncols"]
221
+ if word_ncols == excel_ncols:
222
+ return list(range(excel_ncols)), 0, 0
223
+ word_sigs = _word_column_signatures(trs, cellmap, word_ncols)
224
+ header_count = len(sorted(header_rows(trs))) or min(2, len(trs))
225
+ excel_sigs = _excel_column_signatures(ws, block["grid_rows"], excel_ncols, header_count, cached, block.get("col0", 2))
226
+ mapping = plan_column_alignment(word_sigs, excel_sigs, word_ncols, excel_ncols, ws, block["grid_rows"], code, block.get("col0", 2))
227
+
228
+ inserted = 0
229
+ deleted = 0
230
+ if excel_ncols > word_ncols:
231
+ positions = [col for col, word_col in enumerate(mapping) if word_col is None]
232
+ for pos in sorted(positions, reverse=True):
233
+ insert_word_column(tbl, pos)
234
+ inserted += 1
235
+ skipped = [col for col, word_col in enumerate(mapping) if word_col == SKIP_COLUMN]
236
+ if inserted:
237
+ log(f"[结构] {code}:Word 新增 {inserted} 列(插入于第 {min(positions) + 1} 列起)")
238
+ if skipped:
239
+ log(
240
+ f"[结构] {code}:Excel 第 {'、'.join(str(col + 1) for col in skipped)} 列在本表整列空白,"
241
+ f"已按空白列忽略(填入表头或数据后即可同步到 Word)"
242
+ )
243
+ else:
244
+ used = {col for col in mapping if col is not None and col >= 0}
245
+ positions = [col for col in range(word_ncols) if col not in used]
246
+ for pos in sorted(positions, reverse=True):
247
+ delete_word_column(tbl, pos)
248
+ deleted += 1
249
+ log(f"[结构] {code}:Word 删除 {deleted} 列(第 {min(positions) + 1} 列起)")
250
+
251
+ include = [col for col, word_col in enumerate(mapping) if word_col != SKIP_COLUMN]
252
+ _, _, new_ncols = build_cellmap(tbl)
253
+ if new_ncols != len(include):
254
+ raise SyncError(
255
+ f"{code}:列结构同步后 Word 为 {new_ncols} 列、Excel 有效列为 {len(include)} 列,未对齐"
256
+ )
257
+ return include, inserted, deleted