build_prd_traceability.py
15.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
#!/usr/bin/env python3
"""Build the PRD mail/attachment traceability appendix.
The script reads the explicitly scoped requirement-review EML files from the
user's Downloads directory. It records only filenames, message dates and
attachment metadata; it never copies mail bodies or original attachments into
the repository.
"""
from __future__ import annotations
import argparse
import hashlib
import io
import re
from collections import defaultdict
from dataclasses import dataclass, field
from datetime import datetime
from email import policy
from email.parser import BytesParser
from email.utils import parsedate_to_datetime
from pathlib import Path
from typing import Iterable
from docx import Document
from pypdf import PdfReader
PRD_SUFFIXES = {".doc", ".docx", ".pdf"}
SCOPE_BRAND_RE = re.compile(r"(SAAS|saas|生意助手)")
SCOPE_REQUIREMENT_RE = re.compile(
r"需求评审|需求文档|紧急需求|版本需求|需求改动|紧急需求通过"
)
SCOPE_QR_RE = re.compile(r"关于1\.1订单加微二维码逻辑调整")
TOPIC_TERMS = {
"下单与工单": ("新建工单", "工单", "订单", "下单", "录单", "补录"),
"撤销与退款": ("撤销", "退款", "错误订单", "错误单", "改单"),
"施工履约": ("施工单", "施工", "领单", "完工", "返工", "技师"),
"库存与出库": ("出库", "库存", "物料", "扫码枪", "产品编码"),
"套餐与商品": ("套餐", "子订单", "商品", "服务项目"),
"营销与审批": ("活动商品", "营销", "低价", "审批"),
"统计与报表": ("日报", "产值", "喜报", "报表", "BI"),
}
RELEVANCE_TERMS = (
"新建工单",
"撤销工单",
"撤销",
"退款",
"施工单",
"施工",
"领单",
"出库",
"完工",
"返工",
"补录",
"改单",
"套餐",
"订单",
)
@dataclass
class AttachmentRecord:
sha256: str
size: int
suffix: str
filenames: set[str] = field(default_factory=set)
mail_ids: list[str] = field(default_factory=list)
mail_dates: list[datetime] = field(default_factory=list)
mail_statuses: list[str] = field(default_factory=list)
text: str = ""
evidence_id: str = ""
version_relation: str = "唯一版本"
@dataclass
class MailRecord:
path: Path
mail_id: str = ""
subject: str = ""
date: datetime | None = None
status: str = ""
attachment_hashes: list[str] = field(default_factory=list)
def is_scoped_mail(path: Path) -> bool:
name = path.name
return bool(
(SCOPE_BRAND_RE.search(name) and SCOPE_REQUIREMENT_RE.search(name))
or SCOPE_QR_RE.search(name)
)
def parse_message_date(raw_date: str | None, fallback_path: Path) -> datetime:
if raw_date:
try:
value = parsedate_to_datetime(raw_date)
if value.tzinfo:
value = value.astimezone().replace(tzinfo=None)
return value
except (TypeError, ValueError, OverflowError):
pass
return datetime.fromtimestamp(fallback_path.stat().st_mtime)
def classify_mail_status(name: str) -> str:
if re.search(r"文档更新|文档补充|补充修改|需求调整", name):
return "更新稿"
if re.search(
r"评审通过|评审完成|评审结果|通过邮件|紧急需求通过|评审完毕|需求改动评审通过",
name,
):
return "已通过/完成"
if "需求文档" in name:
return "评审材料"
return "评审通知/初稿"
def extract_docx_text(payload: bytes) -> str:
document = Document(io.BytesIO(payload))
chunks: list[str] = []
for paragraph in document.paragraphs:
if paragraph.text:
chunks.append(paragraph.text)
for table in document.tables:
for row in table.rows:
chunks.append(" ".join(cell.text for cell in row.cells if cell.text))
return "\n".join(chunks)
def extract_pdf_text(payload: bytes) -> str:
reader = PdfReader(io.BytesIO(payload))
return "\n".join((page.extract_text() or "") for page in reader.pages)
def extract_attachment_text(filename: str, payload: bytes) -> str:
suffix = Path(filename).suffix.lower()
try:
if suffix == ".docx":
return extract_docx_text(payload)
if suffix == ".pdf":
return extract_pdf_text(payload)
except Exception as exc: # pragma: no cover - source-file tolerance
return f"[文本提取失败:{type(exc).__name__}]"
return ""
def normalize_group_name(filename: str) -> str:
stem = Path(filename).stem.lower()
stem = re.sub(r"\s+", "", stem)
stem = re.sub(r"(最终版|终稿|最新版|修改版|更新版|评审版|v\d+(?:\.\d+)*)", "", stem)
return stem
def classify_topics(record: AttachmentRecord) -> tuple[list[str], int]:
haystack = "\n".join(record.filenames) + "\n" + record.text
topics = [
topic
for topic, terms in TOPIC_TERMS.items()
if any(term in haystack for term in terms)
]
score = sum(haystack.count(term) for term in RELEVANCE_TERMS)
return topics, score
def escape_cell(value: object) -> str:
return str(value).replace("|", r"\|").replace("\r", " ").replace("\n", "<br>")
def join_cell(values: Iterable[object]) -> str:
return "<br>".join(escape_cell(value) for value in values)
def build_inventory(mail_dir: Path) -> tuple[list[MailRecord], dict[str, AttachmentRecord]]:
paths = sorted(
(path for path in mail_dir.glob("*.eml") if is_scoped_mail(path)),
key=lambda path: path.name.casefold(),
)
mails: list[MailRecord] = []
attachments: dict[str, AttachmentRecord] = {}
for path in paths:
with path.open("rb") as stream:
message = BytesParser(policy=policy.default).parse(stream)
record = MailRecord(
path=path,
subject=str(message.get("subject") or path.stem),
date=parse_message_date(message.get("date"), path),
status=classify_mail_status(path.name),
)
for part in message.walk():
filename = part.get_filename()
if not filename or Path(filename).suffix.lower() not in PRD_SUFFIXES:
continue
payload = part.get_payload(decode=True) or b""
digest = hashlib.sha256(payload).hexdigest()
record.attachment_hashes.append(digest)
attachment = attachments.get(digest)
if attachment is None:
attachment = AttachmentRecord(
sha256=digest,
size=len(payload),
suffix=Path(filename).suffix.lower(),
text=extract_attachment_text(filename, payload),
)
attachments[digest] = attachment
attachment.filenames.add(filename)
attachment.mail_dates.append(record.date)
attachment.mail_statuses.append(record.status)
mails.append(record)
mails.sort(key=lambda item: (item.date or datetime.min, item.path.name.casefold()))
for index, mail in enumerate(mails, start=1):
mail.mail_id = f"MAIL-{index:03d}"
for digest in mail.attachment_hashes:
attachments[digest].mail_ids.append(mail.mail_id)
ordered_attachments = sorted(
attachments.values(),
key=lambda item: (
min(item.mail_dates) if item.mail_dates else datetime.min,
sorted(item.filenames)[0].casefold(),
item.sha256,
),
)
date_counts: defaultdict[str, int] = defaultdict(int)
for attachment in ordered_attachments:
date_key = (
min(attachment.mail_dates).strftime("%Y%m%d")
if attachment.mail_dates
else "UNKNOWN"
)
date_counts[date_key] += 1
attachment.evidence_id = f"PRD-{date_key}-{date_counts[date_key]:02d}"
groups: defaultdict[str, list[AttachmentRecord]] = defaultdict(list)
for attachment in ordered_attachments:
primary_name = sorted(attachment.filenames)[0]
groups[normalize_group_name(primary_name)].append(attachment)
for group in groups.values():
group.sort(
key=lambda item: (
min(item.mail_dates) if item.mail_dates else datetime.min,
item.sha256,
)
)
if len(group) > 1:
for index, attachment in enumerate(group, start=1):
attachment.version_relation = f"同名/同主题修订 {index}/{len(group)}"
return mails, attachments
def render_markdown(
mails: list[MailRecord], attachments: dict[str, AttachmentRecord], output: Path
) -> None:
evidence_by_hash = {
digest: attachment.evidence_id for digest, attachment in attachments.items()
}
ordered_attachments = sorted(
attachments.values(), key=lambda item: item.evidence_id
)
lines = [
"# PRD 追溯矩阵与需求—代码偏差清单",
"",
"> 本文档用于追溯订单生命周期维护手册中的业务依据。邮件正文、收发件人和原始附件均未复制到仓库;仅保留文件名、日期、评审状态、附件哈希和采用结论。",
"",
"## 1. 统计与采用规则",
"",
f"- 邮件:**{len(mails)}** 封。",
f"- PRD 附件实例:**{sum(len(mail.attachment_hashes) for mail in mails)}** 个。",
f"- 按完整 SHA-256 去重后的唯一附件:**{len(attachments)}** 份。",
"- 采用优先级:文档更新/补充稿 > 评审通过/完成稿 > 评审材料 > 评审通知/初稿。",
"- 当前分支代码是已上线现状;PRD 用于解释业务背景、识别目标态和发现偏差。",
"",
"## 2. 需求—代码偏差清单",
"",
"| 编号 | 当前代码行为 | PRD 描述 | 风险/影响 | 建议确认方 |",
"|---|---|---|---|---|",
"| GAP-01 | 撤销按钮过滤微信、POS、支付宝(`selectPayType` 1/3/4),并在确认前后两次检查退款步骤;门店、嘀加、转账、其他收款可能进入撤销分支。 | 11 月评审完成稿描述为“除待跟进工单外,仅门店收款订单可撤销;线上支付走退款”。 | 支付类型 5/6/7 的撤销与退款口径可能不一致。 | 产品、支付后端、订单前端 |",
"| GAP-02 | 出库页要求出库数量大于 0。 | 2026 年 5 月施工单出入库 PRD 允许虚拟/手工库存场景填 0。 | 虚拟商品无法按目标规则提交。 | 产品、库存后端、施工单前端 |",
"| GAP-03(已关闭) | 低价单提交资格满足后展示审批确认弹层,确认提交成功后返回“待审批”列表。 | 2026 年 6 月 PRD 描述活动商品低价审批及审批中状态。 | 前端入口偏差已补齐;后端审批状态与消息通知仍需联调验证。 | 订单后端、消息中心 |",
"| GAP-04 | 技师编辑、商品/服务项目编辑分别受 `SHIGONGQUEREN` 与 `CHUANGJIANSHIGONGDAN` 权限控制,页面不直接按“是否技师”硬编码。 | 施工单 PRD 表述为技师不可修改商品和服务项目。 | 若角色权限配置不严,角色语义与页面能力可能偏离。 | 权限平台、产品、施工单前端 |",
"| GAP-05 | 标记错误前会查询退款步骤和施工汇总;存在未完成施工单时弹警告后仍可进入纠错流程。 | 10 月 PRD 表述错误订单不能继续施工,已有施工数据应清理。 | 清理动作依赖后端,前端无法证明最终数据一致性。 | 订单后端、施工后端 |",
"",
"## 3. 关键证据索引",
"",
"| 证据编号 | 附件 | 主题 | 版本关系 | 评审状态 | 采用结论 |",
"|---|---|---|---|---|---|",
]
for attachment in ordered_attachments:
topics, score = classify_topics(attachment)
statuses = sorted(set(attachment.mail_statuses))
if score == 0:
conclusion = "已解析;与订单主链路无直接关系"
elif "更新稿" in statuses or "已通过/完成" in statuses:
conclusion = "采用;作为业务背景/目标依据,现状以代码为准"
else:
conclusion = "历史参考;用于版本演进,不单独作为现状结论"
lines.append(
"| {evidence} | {filenames} | {topics} | {version} | {statuses} | {conclusion} |".format(
evidence=attachment.evidence_id,
filenames=join_cell(sorted(attachment.filenames)),
topics=join_cell(topics or ["非订单主链路"]),
version=escape_cell(attachment.version_relation),
statuses=join_cell(statuses),
conclusion=escape_cell(conclusion),
)
)
lines.extend(
[
"",
"## 4. 邮件清单(60/60)",
"",
"| 邮件编号 | 邮件时间 | 评审状态 | 邮件文件名 | PRD 证据编号 |",
"|---|---|---|---|---|",
]
)
for mail in mails:
evidence_ids = [evidence_by_hash[digest] for digest in mail.attachment_hashes]
lines.append(
"| {mail_id} | {date} | {status} | {filename} | {evidence} |".format(
mail_id=mail.mail_id,
date=mail.date.strftime("%Y-%m-%d %H:%M") if mail.date else "未知",
status=escape_cell(mail.status),
filename=escape_cell(mail.path.name),
evidence=join_cell(evidence_ids or ["无 DOC/DOCX/PDF 附件"]),
)
)
lines.extend(
[
"",
"## 5. 附件哈希(58/58)",
"",
"| 证据编号 | SHA-256 | 大小(字节) | 来源邮件 |",
"|---|---|---:|---|",
]
)
for attachment in ordered_attachments:
lines.append(
f"| {attachment.evidence_id} | `{attachment.sha256}` | "
f"{attachment.size} | {join_cell(attachment.mail_ids)} |"
)
lines.extend(
[
"",
"## 6. 维护约定",
"",
"- 新增 PRD 时先运行本目录 `tools/build_prd_traceability.py`,确认邮件数、附件实例数和唯一哈希数,再人工复核采用结论。",
"- 同一文件名出现不同哈希时视为修订版;同一哈希出现在多封邮件时只建立一个证据编号。",
"- 不删除历史证据编号。若文件更新,新增编号并在“版本关系”中指向前一版。",
"- 订单流程结论必须同时标注代码符号或本文证据编号;无法由当前仓库证明的后端动作应写为外部依赖。",
"",
]
)
output.parent.mkdir(parents=True, exist_ok=True)
output.write_text("\n".join(lines), encoding="utf-8")
def main() -> int:
parser = argparse.ArgumentParser()
parser.add_argument(
"--mail-dir",
type=Path,
default=Path.home() / "Downloads",
help="Directory containing the scoped EML files.",
)
parser.add_argument(
"--output",
type=Path,
default=Path(__file__).resolve().parents[1] / "prd-traceability.md",
)
args = parser.parse_args()
mails, attachments = build_inventory(args.mail_dir)
if len(mails) != 60:
raise SystemExit(f"Expected 60 scoped mails, found {len(mails)}")
attachment_instances = sum(len(mail.attachment_hashes) for mail in mails)
if attachment_instances != 62:
raise SystemExit(
f"Expected 62 PRD attachment instances, found {attachment_instances}"
)
if len(attachments) != 58:
raise SystemExit(
f"Expected 58 unique PRD attachment hashes, found {len(attachments)}"
)
render_markdown(mails, attachments, args.output)
print(
f"Wrote {args.output}: {len(mails)} mails, "
f"{attachment_instances} attachment instances, "
f"{len(attachments)} unique hashes"
)
return 0
if __name__ == "__main__":
raise SystemExit(main())