Files
syops/backend/tests/test_shipping_notice_extract.py
T

1487 lines
55 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
from email.message import EmailMessage
from pathlib import Path
from app.services.shipping_notice.extract import extract_notice_fields, _heuristic_extract
from app.services.shipping_notice.order_candidate_builder import (
build_email_order_index,
merge_attachment_candidate,
)
from app.services.shipping_notice.notice_lines import (
adjudicate_notice_lines,
normalize_notice_line,
parse_notice_table_rows,
parse_notice_table_text,
validate_notice_lines,
)
from app.services.shipping_notice.reservation_id import (
extract_reservation_id,
find_reservation_id_in_document,
looks_like_reservation_id,
normalize_reservation_id,
)
def _minimal_pdf_bytes(marker: str) -> bytes:
"""
构造含可见文本的最小 PDF,供 EML 附件抽取测试使用。
核心逻辑:手写 PDF 对象流并嵌入 Helvetica 文本;extract_notice_text 应能读出 marker。
"""
safe = (
str(marker)
.replace("\\", "\\\\")
.replace("(", "\\(")
.replace(")", "\\)")
)
stream = f"BT /F1 24 Tf 72 720 Td ({safe}) Tj ET".encode("latin-1")
objects = [
b"1 0 obj<< /Type /Catalog /Pages 2 0 R >>endobj\n",
b"2 0 obj<< /Type /Pages /Kids [3 0 R] /Count 1 >>endobj\n",
(
b"3 0 obj<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] "
b"/Contents 4 0 R /Resources<< /Font<< /F1 5 0 R >> >> >>endobj\n"
),
f"4 0 obj<< /Length {len(stream)} >>stream\n".encode("latin-1")
+ stream
+ b"\nendstream\nendobj\n",
b"5 0 obj<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>endobj\n",
]
out = bytearray(b"%PDF-1.4\n")
offsets = [0]
for obj in objects:
offsets.append(len(out))
out.extend(obj)
xref_pos = len(out)
out.extend(f"xref\n0 {len(offsets)}\n".encode("latin-1"))
out.extend(b"0000000000 65535 f \n")
for off in offsets[1:]:
out.extend(f"{off:010d} 00000 n \n".encode("latin-1"))
out.extend(
f"trailer<< /Size {len(offsets)} /Root 1 0 R >>\nstartxref\n{xref_pos}\n%%EOF\n".encode(
"latin-1"
)
)
return bytes(out)
_TINY_PNG = (
b"\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x01\x00\x00\x00\x01"
b"\x08\x02\x00\x00\x00\x90wS\xde\x00\x00\x00\x0cIDATx\x9cc\xf8\x0f\x00"
b"\x00\x01\x01\x00\x05\x18\xd8N\x00\x00\x00\x00IEND\xaeB`\x82"
)
def _build_eml(
*,
subject: str,
body: str,
attachments: list[tuple[str, str, bytes]],
inline_images: list[tuple[str, str, bytes]] | None = None,
message_id: str = "<sn-eml-test@example.com>",
) -> bytes:
"""
组装 multipart/mixed 测试邮件。
Args:
subject: 邮件主题。
body: text/plain 正文。
attachments: (filename, mime, payload) 真实附件列表。
inline_images: (filename, content_id, payload) 内嵌签名图。
message_id: Message-ID 头。
"""
msg = EmailMessage()
msg["Subject"] = subject
msg["From"] = "laszlo.fussy@example.com"
msg["To"] = "freight@example.com"
msg["Date"] = "Mon, 13 Jul 2026 10:00:00 +0800"
msg["Message-ID"] = message_id
msg.set_content(body)
for filename, content_id, payload in inline_images or []:
msg.add_attachment(
payload,
maintype="image",
subtype="png",
filename=filename,
cid=content_id,
disposition="inline",
)
for filename, mime, payload in attachments:
maintype, _, subtype = mime.partition("/")
msg.add_attachment(
payload,
maintype=maintype or "application",
subtype=subtype or "octet-stream",
filename=filename,
)
return msg.as_bytes()
def test_extract_notice_text_reads_xfa_pdf_datasets():
"""XFA 表单型 PO 的订单字段应进入 raw_text,避免只抽页面文本漏明细。"""
from app.services.shipping_notice.notice_upload import extract_notice_text
pdf_path = Path(__file__).resolve().parents[2] / "docs" / "prototype" / "4510038672.pdf"
text, meta = extract_notice_text(pdf_path)
assert meta["file_type"] == "pdf"
assert "pdf xfa datasets extracted" in meta["warnings"]
assert "HEADER/EBELN: 4510038672" in text
assert "HEADER/SHIPMENT_TEXT: 1000144510" in text
assert "TEMP-S000218922" in text
assert "MPN:D4-A08AR12000001" in text
assert "EINDT=2026-06-23" in text
def test_email_body_order_index_and_attachment_fusion_by_po():
"""截图型邮件正文应解析三条订单,并按 PO 将正文分配字段融合到对应附件候选。"""
body = """
allocation_id\tReservation N.r\tsource type\tAllocated HHPN\tAllocated APN\tAllocated QTY\tMPN\tHub Code\tPO
S-ENC-FOBU260702-286\t2000485916\tVMI-FRA01\tTEMP-S000218922\t504-006043-001\t30\tD4-A08AR12000001\tFRA01\t4510039227
S-BRA-FOBU260702-187\t2000485915\tVMI-FRA01\tTEMP-S000196207\t504-006076-001\t60\tD4-AR1200115A1\tFRA01\t4510039228
S-ENCFOX260705BG977W\t1000148820\tDBS DUB\tTEMP-S000218922\t504-006043-001\t1\tD4-A08AR12000001\tDUB\t4510039229
"""
rows = build_email_order_index(body)
assert len(rows) == 3
assert rows[0]['po_number'] == '4510039227'
assert rows[0]['reservation_id'] == '2000485916'
assert rows[0]['sku'] == '504-006043-001'
assert rows[0]['qty'] == 30
assert rows[0]['source_type'] == 'VMI-FRA01'
assert rows[0]['customer_sku'] == 'TEMP-S000218922'
assert rows[0]['vendor_part_number'] == 'D4-A08AR12000001'
assert rows[0]['hub_code'] == 'FRA01'
assert rows[2]['hub_code'] == 'DUB'
fused = merge_attachment_candidate(
attachment_summary={
'po_number': '4510039227',
'reservation_ids': ['2000485916'],
'lines': [{'reservation_id': '2000485916', 'sku': '504-006043-001', 'qty': 30, 'uom': 'EA'}],
},
filename='4510039227.pdf',
body_rows=rows,
)
line = fused['business_summary']['lines'][0]
assert fused['validation_status'] == 'ready'
assert not fused['conflicts']
assert line['source_type'] == 'VMI-FRA01'
assert line['customer_sku'] == 'TEMP-S000218922'
assert line['hub_code'] == 'FRA01'
conflict = merge_attachment_candidate(
attachment_summary={
'po_number': '4510039227',
'reservation_ids': ['2000485916'],
'lines': [{'reservation_id': '2000485916', 'sku': '504-006043-001', 'qty': 20, 'uom': 'EA'}],
},
filename='4510039227.pdf',
body_rows=rows,
)
assert conflict['validation_status'] == 'needs_review'
assert conflict['conflicts'][0]['field'] == 'qty'
multi_line = merge_attachment_candidate(
attachment_summary={
'po_number': '4510039227',
'reservation_ids': ['OTHER', '2000485916'],
'lines': [
{'reservation_id': 'OTHER', 'sku': 'OTHER-SKU', 'qty': 5},
{'reservation_id': '2000485916', 'sku': '504-006043-001', 'qty': 30},
],
},
filename='4510039227.pdf',
body_rows=rows,
)
assert multi_line['validation_status'] == 'ready'
assert 'source_type' not in multi_line['business_summary']['lines'][0]
assert multi_line['business_summary']['lines'][1]['source_type'] == 'VMI-FRA01'
def test_extract_eml_with_three_pdf_attachments(tmp_path):
"""带 3 个 PDF 附件的 EML:attachment_count=3,且各附件独立抽到文本。"""
from app.services.shipping_notice.notice_upload import extract_notice_text
markers = ("PO-MARKER-AAA", "PO-MARKER-BBB", "PO-MARKER-CCC")
attachments = [
(f"{marker}.pdf", "application/pdf", _minimal_pdf_bytes(marker)) for marker in markers
]
raw = _build_eml(
subject="PO 4510039227, 4510039228, 4510039229",
body="Please find POs attached.",
attachments=attachments,
)
path = tmp_path / "multi-po.eml"
path.write_bytes(raw)
text, meta = extract_notice_text(path)
assert meta["file_type"] == "eml"
assert meta["attachment_count"] == 3
assert meta["email"]["subject"] == "PO 4510039227, 4510039228, 4510039229"
assert meta["email"]["from"] == "laszlo.fussy@example.com"
assert meta["email"]["message_id"] == "<sn-eml-test@example.com>"
assert "Please find POs attached." in meta["email"]["body_text"]
parsed_atts = meta["attachments"]
assert len(parsed_atts) == 3
for marker, item in zip(markers, parsed_atts):
assert item["filename"] == f"{marker}.pdf"
assert item["mime_type"] == "application/pdf"
assert item["parse_status"] == "parsed"
assert len(item["content_hash"]) == 64
assert marker in item["extracted_text"]
assert marker in text
def test_extract_eml_skips_signature_inline_image(tmp_path):
"""邮件签名图片(inline + Content-ID)不得进入 attachments,也不进入订单文本。"""
from app.services.shipping_notice.notice_upload import extract_notice_text
pdf = _minimal_pdf_bytes("PO-ONLY-ORDER")
raw = _build_eml(
subject="Single PO",
body="Body with one PO attachment.",
attachments=[("order.pdf", "application/pdf", pdf)],
inline_images=[("signature.png", "<sig001@example.com>", _TINY_PNG)],
)
path = tmp_path / "with-signature.eml"
path.write_bytes(raw)
text, meta = extract_notice_text(path)
assert meta["attachment_count"] == 1
assert meta["attachments"][0]["filename"] == "order.pdf"
assert all(item["filename"] != "signature.png" for item in meta["attachments"])
assert any(str(w).startswith("eml_inline_resources_skipped:") for w in meta["warnings"])
assert "PO-ONLY-ORDER" in text
# 签名图文件名不应出现在扁平正文附件区
assert "--- attachment: signature.png ---" not in text
def test_extract_eml_duplicate_attachments(tmp_path):
"""同信内重复内容哈希的附件标记 duplicate,不重复抽取。"""
from app.services.shipping_notice.notice_upload import extract_notice_text
pdf = _minimal_pdf_bytes("PO-DUP-SAME")
raw = _build_eml(
subject="Dup attachments",
body="Two copies of the same PDF.",
attachments=[
("a.pdf", "application/pdf", pdf),
("a-copy.pdf", "application/pdf", pdf),
],
)
path = tmp_path / "dup.eml"
path.write_bytes(raw)
_, meta = extract_notice_text(path)
assert meta["attachment_count"] == 2
assert meta["attachments"][0]["parse_status"] == "parsed"
assert meta["attachments"][1]["parse_status"] == "duplicate"
assert any(str(w).startswith("eml_attachment_duplicate:") for w in meta["warnings"])
def test_extract_eml_corrupt_attachment_does_not_block_others(tmp_path):
"""某一个附件损坏时,其他附件仍正常解析。"""
from app.services.shipping_notice.notice_upload import extract_notice_text
good = _minimal_pdf_bytes("PO-GOOD-OK")
bad = b"%PDF-1.4\nthis is not a valid pdf stream{{{{"
raw = _build_eml(
subject="One bad attachment",
body="Mixed attachments.",
attachments=[
("good.pdf", "application/pdf", good),
("broken.pdf", "application/pdf", bad),
("also-good.pdf", "application/pdf", _minimal_pdf_bytes("PO-ALSO-GOOD")),
],
)
path = tmp_path / "partial-fail.eml"
path.write_bytes(raw)
text, meta = extract_notice_text(path)
assert meta["attachment_count"] == 3
statuses = {item["filename"]: item["parse_status"] for item in meta["attachments"]}
assert statuses["good.pdf"] == "parsed"
assert statuses["also-good.pdf"] == "parsed"
# 损坏附件:extract 可能 empty 或 failed,均不得拖垮其余
assert statuses["broken.pdf"] in {"failed", "empty"}
assert "PO-GOOD-OK" in text
assert "PO-ALSO-GOOD" in text
def test_intake_structured_summary_includes_eml_fields(tmp_path):
"""EML 预解析摘要应带上 email / attachment_count / attachments(含独立 extracted_text)。"""
from app.services.shipping_notice.intake_parse_workflow import intake_result_to_structured_summary
from app.services.shipping_notice.notice_upload import extract_notice_text, NoticeIntakeResult
raw = _build_eml(
subject="Summary PO",
body="Summary body.",
attachments=[("one.pdf", "application/pdf", _minimal_pdf_bytes("PO-SUM-1"))],
)
path = tmp_path / "summary.eml"
path.write_bytes(raw)
text, meta = extract_notice_text(path)
result = NoticeIntakeResult(
filename="summary.eml",
source_type="email",
source_file_type="message/rfc822",
text=text,
warnings=list(meta.get("warnings") or []),
meta=meta,
content_hash="abc",
file_size=len(raw),
status="accepted",
)
summary = intake_result_to_structured_summary(result)
assert summary["attachment_count"] == 1
assert summary["email"]["subject"] == "Summary PO"
assert summary["attachments"][0]["filename"] == "one.pdf"
assert summary["attachments"][0]["parse_status"] == "parsed"
assert "PO-SUM-1" in str(summary["attachments"][0].get("extracted_text") or "")
assert summary["attachments"][0]["text_length"] > 0
def test_extract_eml_named_text_part_is_attachment(tmp_path):
"""带 filename 的 text/plain 不得当正文丢弃,应进入 attachments。"""
from email.message import EmailMessage
from app.services.shipping_notice.notice_upload import extract_notice_text
msg = EmailMessage()
msg["Subject"] = "Named text attach"
msg["From"] = "a@example.com"
msg["To"] = "b@example.com"
msg.set_content("Cover note only.")
msg.add_attachment(
b"PO-LINE-TXT-001 qty 2",
maintype="text",
subtype="plain",
filename="order.txt",
)
path = tmp_path / "named-text.eml"
path.write_bytes(msg.as_bytes())
text, meta = extract_notice_text(path)
assert meta["attachment_count"] == 1
assert meta["attachments"][0]["filename"] == "order.txt"
assert meta["attachments"][0]["parse_status"] == "parsed"
assert "PO-LINE-TXT-001" in meta["attachments"][0]["extracted_text"]
assert "PO-LINE-TXT-001" in text
def test_extract_eml_respects_declared_charset(tmp_path):
"""正文解码须尊重 Content-Type charset(ISO-8859-1 café résumé)。"""
from email.message import EmailMessage
from app.services.shipping_notice.notice_upload import extract_notice_text
body = "Please ship café résumé to Lille"
msg = EmailMessage()
msg["Subject"] = "Charset test"
msg["From"] = "eu@example.com"
msg["To"] = "freight@example.com"
msg.set_content(body, charset="iso-8859-1")
path = tmp_path / "charset.eml"
path.write_bytes(msg.as_bytes())
_, meta = extract_notice_text(path)
assert "café" in meta["email"]["body_text"]
assert "résumé" in meta["email"]["body_text"]
def test_extract_eml_nested_rfc822_registers_independent_attachment(tmp_path):
"""成功 message/rfc822 须登记独立附件行(含正文文本)并计入 attachment_count。"""
from email.message import EmailMessage
from app.services.shipping_notice.notice_upload import extract_notice_text
inner = EmailMessage()
inner["Subject"] = "Inner PO Only In Body"
inner["From"] = "buyer@example.com"
inner["To"] = "vendor@example.com"
inner.set_content("INNER-ORDER-PO-4510039999 please ship")
outer = EmailMessage()
outer["Subject"] = "FW: order"
outer["From"] = "relay@example.com"
outer["To"] = "freight@example.com"
outer.set_content("Please see forwarded message.")
# set_content(EmailMessage) → message/rfc822 部件
outer.add_attachment(inner)
path = tmp_path / "forwarded.eml"
path.write_bytes(outer.as_bytes())
text, meta = extract_notice_text(path)
assert meta["attachment_count"] == 1
assert meta["attachment_registered_count"] == 1
assert len(meta["attachments"]) == 1
rfc822_rows = [
row
for row in meta["attachments"]
if str(row.get("mime_type") or "") == "message/rfc822"
or str(row.get("filename") or "").endswith(".eml")
]
assert rfc822_rows, "native message/rfc822 must appear as an attachment row"
row = rfc822_rows[0]
assert row["filename"] == "forwarded-message.eml" or row["mime_type"] == "message/rfc822"
assert row["parse_status"] == "parsed"
assert "INNER-ORDER-PO-4510039999" in str(row.get("extracted_text") or "")
assert "Inner PO Only In Body" in str(row.get("extracted_text") or "")
# 扁平正文经 attachment 段拼接仍可下游解析
assert "INNER-ORDER-PO-4510039999" in text
assert "Inner PO Only In Body" in text
# 不得只剩封面正文(attachment_count=0)却把订单塞进合并正文
assert "Please see forwarded message." in text or "Please see forwarded message" in meta.get("email", {}).get("body_text", "")
# 有外层正文时,内层订单只应在扁平文本中出现一次(封面 + 附件段各一处主题/订单不重复计数订单号)
assert text.count("INNER-ORDER-PO-4510039999") == 1
def test_extract_eml_forward_only_no_outer_body_dedupes_inner_order(tmp_path):
"""无外层正文、仅含 message/rfc822 附件时,内层订单不得在扁平文本出现两次。"""
from email.message import EmailMessage
from app.services.shipping_notice.notice_upload import extract_notice_text
inner = EmailMessage()
inner["Subject"] = "Forward Only PO"
inner["From"] = "buyer@example.com"
inner["To"] = "vendor@example.com"
inner.set_content("INNER-PO-777 please ship")
outer = EmailMessage()
outer["Subject"] = "FW: bare forward"
outer["From"] = "relay@example.com"
outer["To"] = "freight@example.com"
# 常见场景:外层无 set_content,仅挂载转发附件
outer.add_attachment(inner)
path = tmp_path / "forward-only.eml"
path.write_bytes(outer.as_bytes())
text, meta = extract_notice_text(path)
body = str((meta.get("email") or {}).get("body_text") or "")
assert "INNER-PO-777" not in body, "outer body must not absorb inner rfc822 text"
assert meta["attachment_count"] == 1
assert meta["attachments"][0]["parse_status"] == "parsed"
assert "INNER-PO-777" in str(meta["attachments"][0].get("extracted_text") or "")
assert text.count("INNER-PO-777") == 1
def test_extract_eml_attached_multipart_registers_independent_attachment(tmp_path):
"""disposition=attachment 的 multipart/* 须登记为独立附件,不得把订单吞进外层 body。"""
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from app.services.shipping_notice.notice_upload import extract_notice_text
bundle = MIMEMultipart("mixed")
bundle.set_param("name", "bundle.mime")
bundle.add_header("Content-Disposition", "attachment", filename="bundle.mime")
bundle.attach(MIMEText("BUNDLE-PO-888 please ship", "plain", "utf-8"))
outer = MIMEMultipart("mixed")
outer["Subject"] = "Has MIME bundle"
outer["From"] = "a@example.com"
outer["To"] = "b@example.com"
outer.attach(MIMEText("Outer cover only.", "plain", "utf-8"))
outer.attach(bundle)
path = tmp_path / "attached-multipart.eml"
path.write_bytes(outer.as_bytes())
text, meta = extract_notice_text(path)
body = str((meta.get("email") or {}).get("body_text") or "")
assert "BUNDLE-PO-888" not in body
assert "Outer cover only." in body
assert meta["attachment_count"] >= 1
bundles = [
row
for row in meta["attachments"]
if str(row.get("filename") or "") == "bundle.mime"
or str(row.get("mime_type") or "").startswith("multipart/")
]
assert bundles, "attached multipart must appear as an attachment row"
assert bundles[0]["parse_status"] == "parsed"
assert "BUNDLE-PO-888" in str(bundles[0].get("extracted_text") or "")
assert text.count("BUNDLE-PO-888") == 1
def test_extract_eml_attached_multipart_keeps_all_plain_parts(tmp_path):
"""附件型 multipart 内多个 text/plain 须全部拼入 extracted_text,不得只留第一段。"""
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from app.services.shipping_notice.notice_upload import extract_notice_text
bundle = MIMEMultipart("mixed")
bundle.add_header("Content-Disposition", "attachment", filename="multi-po.mime")
bundle.attach(MIMEText("PO-A-111 please ship", "plain", "utf-8"))
bundle.attach(MIMEText("PO-B-222 please ship", "plain", "utf-8"))
outer = MIMEMultipart("mixed")
outer["Subject"] = "Multi plain bundle"
outer["From"] = "a@example.com"
outer["To"] = "b@example.com"
outer.attach(MIMEText("cover", "plain", "utf-8"))
outer.attach(bundle)
path = tmp_path / "multi-plain-bundle.eml"
path.write_bytes(outer.as_bytes())
text, meta = extract_notice_text(path)
row = next(r for r in meta["attachments"] if r.get("filename") == "multi-po.mime")
extracted = str(row.get("extracted_text") or "")
assert "PO-A-111" in extracted
assert "PO-B-222" in extracted
assert text.count("PO-A-111") == 1
assert text.count("PO-B-222") == 1
def test_extract_eml_attached_multipart_mixed_keeps_plain_and_html(tmp_path):
"""multipart/mixed 附件内独立 plain 与 HTML 订单段须全部保留(非 alternative 的 plain 优先)。"""
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from app.services.shipping_notice.notice_upload import extract_notice_text
bundle = MIMEMultipart("mixed")
bundle.add_header("Content-Disposition", "attachment", filename="plain-html.mime")
bundle.attach(MIMEText("PLAIN-PO-101 please ship", "plain", "utf-8"))
bundle.attach(MIMEText("<p>HTML-PO-202 please ship</p>", "html", "utf-8"))
outer = MIMEMultipart("mixed")
outer["Subject"] = "Plain+HTML mixed bundle"
outer["From"] = "a@example.com"
outer["To"] = "b@example.com"
outer.attach(MIMEText("cover", "plain", "utf-8"))
outer.attach(bundle)
path = tmp_path / "plain-html-mixed.eml"
path.write_bytes(outer.as_bytes())
text, meta = extract_notice_text(path)
row = next(r for r in meta["attachments"] if r.get("filename") == "plain-html.mime")
extracted = str(row.get("extracted_text") or "")
assert "PLAIN-PO-101" in extracted
assert "HTML-PO-202" in extracted
assert text.count("PLAIN-PO-101") == 1
assert text.count("HTML-PO-202") == 1
def test_extract_eml_attached_multipart_alternative_prefers_plain(tmp_path):
"""multipart/alternative 附件内仍 plain 优先,避免同一订单 plain/html 双份。"""
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from app.services.shipping_notice.notice_upload import extract_notice_text
alt = MIMEMultipart("alternative")
alt.attach(MIMEText("ALT-PO-PLAIN-303", "plain", "utf-8"))
alt.attach(MIMEText("<b>ALT-PO-HTML-303</b>", "html", "utf-8"))
bundle = MIMEMultipart("mixed")
bundle.add_header("Content-Disposition", "attachment", filename="alt.mime")
bundle.attach(alt)
outer = MIMEMultipart("mixed")
outer["Subject"] = "Alternative bundle"
outer["From"] = "a@example.com"
outer.attach(MIMEText("cover", "plain", "utf-8"))
outer.attach(bundle)
path = tmp_path / "alt-bundle.eml"
path.write_bytes(outer.as_bytes())
text, meta = extract_notice_text(path)
row = next(r for r in meta["attachments"] if r.get("filename") == "alt.mime")
extracted = str(row.get("extracted_text") or "")
assert "ALT-PO-PLAIN-303" in extracted
assert "ALT-PO-HTML-303" not in extracted
assert text.count("ALT-PO-PLAIN-303") == 1
def test_extract_eml_attached_alternative_root_extracts_plain(tmp_path):
"""根部件即为 disposition=attachment 的 multipart/alternative 时须提取 plain,不得 empty。"""
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from app.services.shipping_notice.notice_upload import extract_notice_text
alt = MIMEMultipart("alternative")
alt.add_header("Content-Disposition", "attachment", filename="order-alt.mime")
alt.attach(MIMEText("ROOT-ALT-PO-404 please ship", "plain", "utf-8"))
alt.attach(MIMEText("<p>ROOT-ALT-HTML-404</p>", "html", "utf-8"))
outer = MIMEMultipart("mixed")
outer["Subject"] = "Attached alternative root"
outer["From"] = "a@example.com"
outer["To"] = "b@example.com"
outer.attach(MIMEText("cover", "plain", "utf-8"))
outer.attach(alt)
path = tmp_path / "alt-root-attached.eml"
path.write_bytes(outer.as_bytes())
text, meta = extract_notice_text(path)
row = next(r for r in meta["attachments"] if r.get("filename") == "order-alt.mime")
assert row["parse_status"] == "parsed"
extracted = str(row.get("extracted_text") or "")
assert "ROOT-ALT-PO-404" in extracted
assert "ROOT-ALT-HTML-404" not in extracted
assert text.count("ROOT-ALT-PO-404") == 1
assert "ROOT-ALT-PO-404" not in str((meta.get("email") or {}).get("body_text") or "")
def test_extract_eml_nested_attached_multipart_respects_depth(tmp_path):
"""嵌套附件型 multipart 须累加 depth,超限时 skipped 并打 eml_nesting_depth_exceeded。"""
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from app.services.shipping_notice.eml_parse import EmlLimits, parse_eml_bytes
from app.services.shipping_notice.notice_upload import extract_notice_text
inner = MIMEMultipart("mixed")
inner.add_header("Content-Disposition", "attachment", filename="inner.mime")
inner.attach(MIMEText("INNER-NESTED-PO-999", "plain", "utf-8"))
outer_bundle = MIMEMultipart("mixed")
outer_bundle.add_header("Content-Disposition", "attachment", filename="outer.mime")
outer_bundle.attach(MIMEText("OUTER-BUNDLE-PO", "plain", "utf-8"))
outer_bundle.attach(inner)
root = MIMEMultipart("mixed")
root["Subject"] = "Nested attached multipart"
root["From"] = "a@example.com"
root.attach(MIMEText("cover", "plain", "utf-8"))
root.attach(outer_bundle)
_, meta = parse_eml_bytes(
root.as_bytes(),
extract_text=extract_notice_text,
limits=EmlLimits(max_attachments=10, max_nesting_depth=1),
depth=0,
)
by_name = {row["filename"]: row for row in meta["attachments"]}
assert by_name["outer.mime"]["parse_status"] == "parsed"
assert "OUTER-BUNDLE-PO" in str(by_name["outer.mime"].get("extracted_text") or "")
assert by_name["inner.mime"]["parse_status"] == "skipped"
assert any(str(w).startswith("eml_nesting_depth_exceeded:") for w in meta["warnings"])
assert "INNER-NESTED-PO-999" not in str(by_name["inner.mime"].get("extracted_text") or "")
def test_extract_eml_html_table_keeps_row_boundaries(tmp_path):
"""HTML-only 邮件表格应保留行列边界(换行+制表符),且解码 HTML 实体。"""
from email.message import EmailMessage
from app.services.shipping_notice.notice_upload import extract_notice_text
html = (
"<html><body><table>"
"<tr><th>PO</th><th>Qty</th></tr>"
"<tr><td>4510039227</td><td>30</td></tr>"
"<tr><td>4510039228</td><td>2</td></tr>"
"<tr><td>A&amp;B</td><td>3</td></tr>"
"</table></body></html>"
)
msg = EmailMessage()
msg["Subject"] = "HTML table"
msg["From"] = "a@example.com"
msg["To"] = "b@example.com"
msg.set_content(html, subtype="html")
path = tmp_path / "html-table.eml"
path.write_bytes(msg.as_bytes())
_, meta = extract_notice_text(path)
body = meta["email"]["body_text"]
assert "4510039227" in body
assert "4510039228" in body
assert "A&B" in body
assert body.count("\n") >= 2
assert "\t" in body
assert "4510039227\t30" in body.replace(" ", "")
def test_extract_eml_html_table_preserves_empty_cells(tmp_path):
"""HTML 表格空单元格必须保留列占位,避免不同邮件模板的尾部业务字段整体错位。"""
from email.message import EmailMessage
from app.services.shipping_notice.notice_upload import extract_notice_text
html = (
"<table>"
"<tr><th>SKU</th><th>Parent allocation ID</th><th>External reservation ID</th></tr>"
"<tr><td>A001</td><td></td><td>AWS-311</td></tr>"
"</table>"
)
msg = EmailMessage()
msg.set_content(html, subtype="html")
path = tmp_path / "html-empty-cell.eml"
path.write_bytes(msg.as_bytes())
_, meta = extract_notice_text(path)
body = meta["email"]["body_text"].replace(" ", "")
assert "A001\t\tAWS-311" in body
def test_extract_eml_nested_eml_file_respects_depth(tmp_path):
"""嵌套 .eml 文件附件须共享深度/限额,不得重置 depth=0 无限展开。"""
from email.message import EmailMessage
from app.services.shipping_notice.eml_parse import EmlLimits, parse_eml_bytes
from app.services.shipping_notice.notice_upload import extract_notice_text
leaf = EmailMessage()
leaf["Subject"] = "Leaf"
leaf["From"] = "leaf@example.com"
leaf.set_content("LEAF-MARKER-DEPTH")
leaf_bytes = leaf.as_bytes()
def wrap_as_eml_file(payload: bytes, filename: str, subject: str) -> bytes:
msg = EmailMessage()
msg["Subject"] = subject
msg["From"] = "a@example.com"
msg["To"] = "b@example.com"
msg.set_content(f"see {filename}")
msg.add_attachment(
payload,
maintype="application",
subtype="octet-stream",
filename=filename,
)
return msg.as_bytes()
l1 = wrap_as_eml_file(leaf_bytes, "l1.eml", "L1")
l2 = wrap_as_eml_file(l1, "l2.eml", "L2")
root = wrap_as_eml_file(l2, "l3.eml", "Root")
text, meta = parse_eml_bytes(
root,
extract_text=extract_notice_text,
limits=EmlLimits(max_attachments=20, max_nesting_depth=1),
depth=0,
)
assert any(str(w).startswith("eml_nesting_depth_exceeded:") for w in meta["warnings"])
# depth=1 只允许再展开一层;更深的 LEAF 不应进入正文
assert "LEAF-MARKER-DEPTH" not in text
assert "LEAF-MARKER-DEPTH" not in str(meta.get("email", {}).get("body_text") or "")
def test_extract_eml_attachment_count_includes_overflow(tmp_path):
"""超限未登记的附件仍计入 attachment_count。"""
from email.message import EmailMessage
from app.services.shipping_notice.eml_parse import EmlLimits, parse_eml_bytes
from app.services.shipping_notice.notice_upload import extract_notice_text
msg = EmailMessage()
msg["Subject"] = "Three attaches"
msg["From"] = "a@example.com"
msg["To"] = "b@example.com"
msg.set_content("cover")
for idx in range(3):
msg.add_attachment(
f"PO-LINE-{idx}".encode("utf-8"),
maintype="text",
subtype="plain",
filename=f"order-{idx}.txt",
)
_, meta = parse_eml_bytes(
msg.as_bytes(),
extract_text=extract_notice_text,
limits=EmlLimits(max_attachments=2, max_nesting_depth=3),
)
assert meta["attachment_count"] == 3
assert meta["attachment_registered_count"] == 2
assert len(meta["attachments"]) == 2
assert any("eml_attachment_limit_exceeded:2:discovered=3" in str(w) for w in meta["warnings"])
def test_extract_eml_container_does_not_double_count_total_bytes(tmp_path):
"""嵌套 .eml 容器计费后,内层子附件不得再计,避免双重计费导致误 skip。"""
from email.message import EmailMessage
from app.services.shipping_notice.eml_parse import EmlLimits, parse_eml_bytes
from app.services.shipping_notice.notice_upload import extract_notice_text
inner = EmailMessage()
inner["Subject"] = "Inner"
inner["From"] = "inner@example.com"
inner.set_content("cover")
inner.add_attachment(
b"INNER-PO-TINY",
maintype="text",
subtype="plain",
filename="inner.txt",
)
inner_bytes = inner.as_bytes()
outer = EmailMessage()
outer["Subject"] = "Outer"
outer["From"] = "outer@example.com"
outer.set_content("see nested")
outer.add_attachment(
inner_bytes,
maintype="application",
subtype="octet-stream",
filename="nested.eml",
)
outer_bytes = outer.as_bytes()
# 上限略大于容器;若对子内容再计一次,则可能误 skip
tight_total = len(inner_bytes) + 10
assert tight_total < len(outer_bytes) + len(b"INNER-PO-TINY")
_, meta = parse_eml_bytes(
outer_bytes,
extract_text=extract_notice_text,
limits=EmlLimits(
max_attachments=10,
max_attachment_bytes=10 * 1024 * 1024,
max_total_attachment_bytes=tight_total,
max_nesting_depth=3,
),
)
by_name = {row["filename"]: row for row in meta["attachments"]}
assert "nested.eml" in by_name
assert by_name["inner.txt"]["parse_status"] == "parsed"
assert "INNER-PO-TINY" in by_name["inner.txt"]["extracted_text"]
def test_extract_eml_large_containers_count_toward_total():
"""多个近似空壳大 .eml 容器须计入总量,不能仅靠跳过叶子附件绕过。"""
from email.message import EmailMessage
from app.services.shipping_notice.eml_parse import EmlLimits, parse_eml_bytes
from app.services.shipping_notice.notice_upload import extract_notice_text
def _shell_eml(name: str, pad: bytes) -> bytes:
msg = EmailMessage()
msg["Subject"] = name
msg["From"] = "shell@example.com"
msg.set_content("pad-only")
# 用文本附件撑大容器体积(容器整体计费)
msg.add_attachment(pad, maintype="text", subtype="plain", filename=f"{name}-pad.txt")
return msg.as_bytes()
pad = b"X" * 8000
shell_a = _shell_eml("A", pad)
shell_b = _shell_eml("B", pad)
shell_c = _shell_eml("C", pad)
root = EmailMessage()
root["Subject"] = "Many shells"
root["From"] = "root@example.com"
root.set_content("holders")
for name, payload in (("a.eml", shell_a), ("b.eml", shell_b), ("c.eml", shell_c)):
root.add_attachment(
payload,
maintype="application",
subtype="octet-stream",
filename=name,
)
# 只够放两个容器;第三个须 skipped 并打总量警告
two_shells = len(shell_a) + len(shell_b)
_, meta = parse_eml_bytes(
root.as_bytes(),
extract_text=extract_notice_text,
limits=EmlLimits(
max_attachments=20,
max_attachment_bytes=10 * 1024 * 1024,
max_total_attachment_bytes=two_shells + 50,
max_nesting_depth=3,
),
)
by_name = {row["filename"]: row for row in meta["attachments"]}
assert by_name["a.eml"]["parse_status"] in {"parsed", "empty"}
assert by_name["b.eml"]["parse_status"] in {"parsed", "empty"}
assert by_name["c.eml"]["parse_status"] == "skipped"
assert any(str(w).startswith("eml_total_attachment_size_exceeded:") for w in meta["warnings"])
def test_attachment_integrity_flags_budget_and_failed_status():
"""完整性助手须覆盖预算耗尽、文本截断与 failed/empty/skipped。"""
from app.services.shipping_notice.attachment_integrity import (
BLOCKING_WARNING_PREFIXES,
is_attachment_parse_incomplete,
)
assert not is_attachment_parse_incomplete(
{
"attachment_count": 1,
"attachments": [{"parse_status": "parsed", "warnings": []}],
"warnings": [],
}
)
assert is_attachment_parse_incomplete(
{
"attachment_count": 1,
"attachments": [{"parse_status": "failed", "warnings": []}],
"warnings": [],
}
)
assert is_attachment_parse_incomplete(
{
"attachment_count": 2,
"attachments": [{"parse_status": "parsed", "warnings": []}],
"warnings": [],
}
)
assert is_attachment_parse_incomplete(
{
"attachment_count": 1,
"attachments": [
{
"parse_status": "parsed",
"warnings": ["eml_attachment_text_budget_exhausted:100"],
}
],
"warnings": [],
}
)
assert is_attachment_parse_incomplete(
{
"attachment_count": 1,
"attachments": [{"parse_status": "parsed", "warnings": []}],
"warnings": ["eml_attachment_text_budget_exhausted:100"],
}
)
assert is_attachment_parse_incomplete(
{
"attachment_count": 1,
"attachments": [
{
"parse_status": "parsed",
"warnings": ["eml_attachment_text_truncated:10"],
}
],
"warnings": [],
}
)
assert is_attachment_parse_incomplete(
{
"attachment_count": 0,
"attachments": [],
"warnings": ["notice_text_truncated:100"],
}
)
# 契约:每个阻断前缀都须能触发 incomplete
for prefix in BLOCKING_WARNING_PREFIXES:
assert is_attachment_parse_incomplete({"warnings": [f"{prefix}demo"], "attachments": []})
def test_frontend_blocking_warning_prefixes_match_backend():
"""前后端阻断 warning 前缀契约须一致,防止再漏截断类码。"""
import ast
import re
from pathlib import Path
from app.services.shipping_notice.attachment_integrity import BLOCKING_WARNING_PREFIXES
ts_path = (
Path(__file__).resolve().parents[2]
/ "frontend"
/ "src"
/ "features"
/ "chat"
/ "shipping"
/ "shippingNoticeAttachmentIntegrity.ts"
)
assert ts_path.is_file(), f"missing frontend contract file: {ts_path}"
text = ts_path.read_text(encoding="utf-8")
match = re.search(
r"export const BLOCKING_WARNING_PREFIXES\s*=\s*\[(.*?)]\s*as const",
text,
flags=re.S,
)
assert match, "frontend BLOCKING_WARNING_PREFIXES array not found"
literal = "[" + match.group(1) + "]"
literal = literal.replace("'", '"')
fe_prefixes = ast.literal_eval(literal)
assert sorted(fe_prefixes) == sorted(BLOCKING_WARNING_PREFIXES)
def test_intake_structured_summary_per_attachment_text_truncated(app):
"""单附件文本超 NOTICE_TEXT_MAX_CHARS 须投影 truncated warning 并阻断完整性。"""
from app.services.shipping_notice.attachment_integrity import is_attachment_parse_incomplete
from app.services.shipping_notice.intake_parse_workflow import intake_result_to_structured_summary
from app.services.shipping_notice.notice_upload import NoticeIntakeResult
with app.app_context():
app.config["SHIPPING_NOTICE_NOTICE_TEXT_MAX_CHARS"] = 10
app.config["SHIPPING_NOTICE_EML_MAX_STORED_ATTACHMENT_CHARS"] = 1_000_000
result = NoticeIntakeResult(
filename="trunc.eml",
source_type="email",
source_file_type="message/rfc822",
text="cover",
warnings=[],
meta={
"email": {"subject": "Trunc", "body_text": "cover"},
"attachment_count": 1,
"attachments": [
{
"attachment_key": "att-001",
"filename": "long.txt",
"mime_type": "text/plain",
"size": 20,
"content_hash": "h1",
"parse_status": "parsed",
"extracted_text": "ABCDEFGHIJKLMNOP", # 16 chars → 截断为 10
"warnings": [],
}
],
},
content_hash="trunc-hash",
file_size=100,
status="accepted",
)
summary = intake_result_to_structured_summary(result)
row = summary["attachments"][0]
assert row["parse_status"] == "parsed"
assert row["stored_text_length"] == 10
assert any(str(w).startswith("eml_attachment_text_truncated:") for w in row["warnings"])
assert is_attachment_parse_incomplete(summary)
def test_notice_text_truncated_blocks_integrity(app):
"""扁平正文 notice_text_truncated 须进入完整性门禁。"""
from app.services.shipping_notice.attachment_integrity import is_attachment_parse_incomplete
from app.services.shipping_notice.notice_upload import truncate_notice_text
with app.app_context():
app.config["SHIPPING_NOTICE_NOTICE_TEXT_MAX_CHARS"] = 20
text, warnings = truncate_notice_text("X" * 50, [])
assert len(text) == 20
assert any(str(w).startswith("notice_text_truncated:") for w in warnings)
assert is_attachment_parse_incomplete(
{
"warnings": warnings,
"attachment_count": 0,
"attachments": [],
}
)
def test_extract_eml_rfc822_forward_respects_size_limits():
"""原生 message/rfc822 转发须受单附件/总量上限约束,不可静默完整展开。"""
from email.message import EmailMessage
from app.services.shipping_notice.eml_parse import EmlLimits, parse_eml_bytes
from app.services.shipping_notice.notice_upload import extract_notice_text
forwarded = EmailMessage()
forwarded["Subject"] = "Huge forward"
forwarded["From"] = "inner@example.com"
forwarded.set_content("Y" * 5000)
root = EmailMessage()
root["Subject"] = "Wrapper"
root["From"] = "outer@example.com"
root.set_content("see forward")
root.add_attachment(forwarded)
_, meta = parse_eml_bytes(
root.as_bytes(),
extract_text=extract_notice_text,
limits=EmlLimits(
max_attachments=10,
max_attachment_bytes=100,
max_total_attachment_bytes=100,
max_nesting_depth=3,
),
)
assert any(
str(w).startswith("eml_attachment_too_large:")
or str(w).startswith("eml_total_attachment_size_exceeded:")
for w in meta["warnings"]
)
assert any(row.get("parse_status") == "skipped" for row in meta["attachments"])
flat_body = str((meta.get("email") or {}).get("body_text") or "")
assert ("Y" * 200) not in flat_body
def test_intake_structured_summary_attachment_text_budget(app):
"""附件文本总预算部分/完全耗尽时须投影 warning,且第二附件文本可被截断或清空。"""
from app.services.shipping_notice.intake_parse_workflow import intake_result_to_structured_summary
from app.services.shipping_notice.notice_upload import NoticeIntakeResult
from app.services.shipping_notice.attachment_integrity import is_attachment_parse_incomplete
with app.app_context():
app.config["SHIPPING_NOTICE_EML_MAX_STORED_ATTACHMENT_CHARS"] = 30
result = NoticeIntakeResult(
filename="budget.eml",
source_type="email",
source_file_type="message/rfc822",
text="cover",
warnings=[],
meta={
"email": {"subject": "Budget", "body_text": "cover"},
"attachment_count": 2,
"attachments": [
{
"attachment_key": "att-001",
"filename": "a.txt",
"mime_type": "text/plain",
"size": 20,
"content_hash": "h1",
"parse_status": "parsed",
"extracted_text": "AAAAAAAAAA" * 3, # 30 chars
"warnings": [],
},
{
"attachment_key": "att-002",
"filename": "b.txt",
"mime_type": "text/plain",
"size": 20,
"content_hash": "h2",
"parse_status": "parsed",
"extracted_text": "BBBBBBBBBB" * 3,
"warnings": [],
},
],
},
content_hash="budget-hash",
file_size=100,
status="accepted",
)
summary = intake_result_to_structured_summary(result)
assert any(
str(w).startswith("eml_attachment_text_budget_exhausted:") for w in summary["warnings"]
)
assert summary["attachments"][0]["stored_text_length"] == 30
assert summary["attachments"][1]["stored_text_length"] == 0
assert is_attachment_parse_incomplete(summary)
def test_extract_eml_rfc822_depth_registers_skipped_row(tmp_path):
"""超深 message/rfc822 应登记 skipped 附件行,便于前端感知不完整。"""
from email.message import EmailMessage
from app.services.shipping_notice.eml_parse import EmlLimits, parse_eml_bytes
from app.services.shipping_notice.notice_upload import extract_notice_text
deepest = EmailMessage()
deepest["Subject"] = "Deep"
deepest.set_content("DEEP-ORDER-SHOULD-SKIP")
mid = EmailMessage()
mid["Subject"] = "Mid"
mid.set_content("mid")
mid.add_attachment(deepest)
root = EmailMessage()
root["Subject"] = "Root"
root["From"] = "a@example.com"
root.set_content("root")
root.add_attachment(mid)
_, meta = parse_eml_bytes(
root.as_bytes(),
extract_text=extract_notice_text,
limits=EmlLimits(max_attachments=10, max_nesting_depth=0),
depth=0,
)
assert any(str(w).startswith("eml_nesting_depth_exceeded:") for w in meta["warnings"])
skipped = [row for row in meta["attachments"] if row.get("parse_status") == "skipped"]
assert skipped
assert any(
any(str(w).startswith("eml_nesting_depth_exceeded:") for w in (row.get("warnings") or []))
for row in skipped
)
def test_extract_eml_keeps_inline_pdf_attachment(tmp_path):
"""Content-Disposition: inline 的 PDF 不得被当成签名图丢弃。"""
from email.message import EmailMessage
from app.services.shipping_notice.notice_upload import extract_notice_text
msg = EmailMessage()
msg["Subject"] = "Inline PDF"
msg["From"] = "a@example.com"
msg["To"] = "b@example.com"
msg.set_content("See PDF.")
msg.add_attachment(
_minimal_pdf_bytes("PO-INLINE-PDF"),
maintype="application",
subtype="pdf",
filename="inline-order.pdf",
disposition="inline",
)
path = tmp_path / "inline-pdf.eml"
path.write_bytes(msg.as_bytes())
text, meta = extract_notice_text(path)
assert meta["attachment_count"] == 1
assert meta["attachments"][0]["filename"] == "inline-order.pdf"
assert meta["attachments"][0]["parse_status"] == "parsed"
assert "PO-INLINE-PDF" in text
def test_extract_reservation_id_from_pr_number():
assert extract_reservation_id("ADU_S-ENCWIW260528126265@1000140351") == "1000140351"
assert find_reservation_id_in_document("PR Number: ADU_S-ENCWIW260528126265@1000140351") == "1000140351"
def test_external_reservation_id_corrects_invalid_llm_candidate_with_column_evidence():
"""明确 TSV 列关系与唯一 MPN 关联时,应把 32 位内部 ID 纠正为 External Reservation ID。"""
raw_text = (
"Allocated APN\tMPN\tAllocated QTY\tCommodity group ID\tExternal reservation ID\n"
"504-006055-001\tD4-A08AR12000002\t10\t"
"1f1a682dfdc446a393415dee93eb36ce\t3000092917"
)
lines = [
{
"sku": "TEMP-S000218929/D4-A08AR12000002",
"vendor_part_number": "D4-A08AR12000002",
"qty": 10,
"uom": "EA",
"reservation_id": "1f1a682dfdc446a393415dee93eb36ce",
}
]
adjudicated, issues, status = adjudicate_notice_lines(lines, raw_text=raw_text)
assert status == "ready"
assert adjudicated[0]["reservation_id"] == "3000092917"
assert issues == [
{
"line_index": 0,
"sku": "TEMP-S000218929/D4-A08AR12000002",
"field": "reservation_id",
"reason": "value_corrected",
"severity": "info",
"raw_value": "1f1a682dfdc446a393415dee93eb36ce",
"resolved_value": "3000092917",
"resolution_basis": "email_table.External reservation ID",
}
]
def test_flattened_text_does_not_guess_external_reservation_id():
"""纯文本缺少列边界时不得因附近存在数字而自动修正 Reservation ID。"""
raw_text = (
"Commodity group ID External reservation ID "
"1f1a682dfdc446a393415dee93eb36ce 3000092917"
)
lines = [
{
"sku": "TEMP-S000218929/D4-A08AR12000002",
"qty": 10,
"uom": "EA",
"reservation_id": "1f1a682dfdc446a393415dee93eb36ce",
}
]
adjudicated, issues, status = adjudicate_notice_lines(lines, raw_text=raw_text)
assert status == "needs_review"
assert "reservation_id" not in adjudicated[0]
assert issues[0]["reason"] == "invalid_format"
assert issues[0]["severity"] == "blocking"
def test_adjudication_supports_non_numeric_reservation_templates():
"""不同来源模板可使用字母型 Reservation ID,后端只排除内部 ID,不绑定单一数字模板。"""
raw_text = "AWS Sku\tReservation Order\tQty\nA001\tAWS-311\t2"
lines = [{"sku": "A001", "reservation_id": "", "qty": 2, "uom": "EA"}]
adjudicated, issues, status = adjudicate_notice_lines(lines, raw_text=raw_text)
assert status == "ready"
assert adjudicated[0]["reservation_id"] == "AWS-311"
assert issues[0]["reason"] == "value_corrected"
def test_wistron_po_table_with_pr_number_in_document():
text = """
Vendor: HOXIN
PR Number: ADU_S-ENCWIW260528126265@1000140351
Line No\tMaterial\tVendor Part Number\tDescription\tQuantity\tETA\tUnit Price\tAmount
10\t504-010213-001\tB3-A08AR11000001\tENCLOSURE\t9.000 PCS\t2026/06/15\t1,607.72 USD\t14,469.48 USD
"""
lines = parse_notice_table_text(text)
assert len(lines) == 1
assert lines[0]["sku"] == "504-010213-001"
assert lines[0]["line_no"] == "10"
assert lines[0]["qty"] == 9.0
assert lines[0]["unit_price"] == 1607.72
assert lines[0]["amount"] == 14469.48
assert lines[0]["reservation_id"] == "1000140351"
assert lines[0]["required_date"] == "2026-06-15"
assert lines[0]["vendor_part_number"] == "B3-A08AR11000001"
assert lines[0]["currency"] == "USD"
def test_normalize_reservation_id_from_excel_float():
assert normalize_reservation_id(1000140351.0) == "1000140351"
assert normalize_reservation_id("1000140351.0") == "1000140351"
assert looks_like_reservation_id("1000140351")
def test_parse_notice_table_numeric_reservation_id():
text = """
AWS Sku\tReservation ID\tQty\tUnit Price\tAmount
10-40594-001\t1000140351\t2\t15.5\t31.0
"""
lines = parse_notice_table_text(text)
assert lines[0]["reservation_id"] == "1000140351"
def test_infer_reservation_id_without_header():
headers = ["AWS Sku", "Ref", "Qty"]
rows = [["10-40594-001", 1000140351, 2]]
lines = parse_notice_table_rows(headers, rows)
assert lines[0]["reservation_id"] == "1000140351"
def test_parse_notice_table_with_all_fields():
text = """
AWS Sku\tReservation ID\tQty\tUnit Price\tAmount
10-40594-001\tAWS-311\t2\t15.5\t31.0
10-40594-002\tORD-3002\t1\t20\t20
"""
lines = parse_notice_table_text(text)
assert len(lines) == 2
assert lines[0]["sku"] == "10-40594-001"
assert lines[0]["reservation_id"] == "AWS-311"
assert lines[0]["qty"] == 2
assert lines[0]["unit_price"] == 15.5
assert lines[0]["amount"] == 31.0
def test_normalize_notice_line_aliases():
line = normalize_notice_line(
{
"part_number": "A-001",
"quantity": "3",
"com_id": "COM-99",
"price": "12.5",
"delivery_date": "2026/06/15",
"vendorPartNumber": "VND-001",
"currency": "USD",
"line_no": "10",
}
)
assert line == {
"line_no": "10",
"sku": "A-001",
"qty": 3.0,
"uom": "EA",
"reservation_id": "COM-99",
"unit_price": 12.5,
"amount": 37.5,
"currency": "USD",
"required_date": "2026-06-15",
"vendor_part_number": "VND-001",
}
def test_enrich_notice_with_document_currency():
from app.services.shipping_notice.notice_lines import enrich_notice_with_document_currency
parsed = enrich_notice_with_document_currency(
{
"currency": "USD",
"lines": [{"sku": "A-001", "qty": 1, "uom": "EA"}, {"sku": "B-002", "qty": 2, "currency": "EUR", "uom": "EA"}],
}
)
assert parsed["lines"][0]["currency"] == "USD"
assert parsed["lines"][1]["currency"] == "EUR"
def test_extract_currency_from_price_string():
from app.services.shipping_notice.notice_lines import _extract_currency
assert _extract_currency("1,607.72 USD") == "USD"
assert _extract_currency("$15.5") == "USD"
assert _extract_currency("¥100") == "CNY"
def test_enrich_notice_with_document_required_date():
from app.services.shipping_notice.notice_lines import enrich_notice_with_document_required_date
parsed = enrich_notice_with_document_required_date(
{
"required_date": "2026-06-20",
"lines": [{"sku": "A-001", "qty": 1, "uom": "EA"}, {"sku": "B-002", "qty": 2, "required_date": "2026-06-18", "uom": "EA"}],
}
)
assert parsed["lines"][0]["required_date"] == "2026-06-20"
assert parsed["lines"][1]["required_date"] == "2026-06-18"
def test_extract_notice_fields_structured():
structured = {
"customer_name": "ACME",
"lines": [
{
"sku": "10-40594-001",
"qty": 2,
"reservation_id": "AWS-311",
"unit_price": 10,
"amount": 20,
}
],
"confidence": 0.9,
}
parsed, confidence, warnings = extract_notice_fields(raw_text="", structured=structured)
assert parsed["lines"][0]["reservation_id"] == "AWS-311"
assert parsed["lines"][0]["amount"] == 20
assert confidence >= 0.8
assert not any("未解析到有效订单行" in w for w in warnings)
def test_validate_notice_lines_missing_reservation():
warnings = validate_notice_lines([{"sku": "A001", "qty": 1, "uom": "EA"}])
assert any("Reservation ID" in w for w in warnings)
assert any("阻断后续库存匹配" in w for w in warnings)
def test_heuristic_table_skips_title_row():
from app.services.shipping_notice.extract import _heuristic_extract
text = """
Shipping Notice
AWS Sku\tReservation Order\tOrder Qty\tUnit Price\tLine Amount
10-40594-001\tORD-3002\t4\t5\t20
"""
parsed, confidence, _ = _heuristic_extract(text)
assert len(parsed["lines"]) == 1
assert parsed["lines"][0]["sku"] == "10-40594-001"
assert parsed["lines"][0]["reservation_id"] == "ORD-3002"
assert parsed["lines"][0]["qty"] == 4
assert parsed["lines"][0]["unit_price"] == 5
assert parsed["lines"][0]["amount"] == 20
assert confidence >= 0.5
def test_extract_notice_fields_structured_over_heuristic():
"""Dify 传入 structured 时应直接使用,不走启发式。"""
structured = {
"customer_name": "ACME",
"lines": [{"sku": "SKU-DIFY", "qty": 3, "uom": "EA"}],
"confidence": 0.95,
}
parsed, confidence, warnings = extract_notice_fields(
raw_text="ignored SKU x 99",
structured=structured,
)
assert parsed["parse_source"] == "dify"
assert parsed["lines"][0]["sku"] == "SKU-DIFY"
assert confidence > 0.8
assert "parse_fallback_heuristic" not in warnings
def test_extract_notice_fields_heuristic_fallback():
"""无 structured 时走后端启发式兜底。"""
text = "AWS Sku\tReservation Order\tOrder Qty\n10-40594-001\tORD-3002\t4"
parsed, _, warnings = extract_notice_fields(raw_text=text)
assert parsed["parse_source"] == "heuristic"
assert parsed["lines"][0]["sku"] == "10-40594-001"
assert "parse_fallback_heuristic" in warnings