from email.message import EmailMessage from pathlib import Path from unittest.mock import patch import pytest 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, ) from app.services.shipping_notice.order_schema.table_contract import compile_table_header_contract def _table_schema_definition() -> dict: """构造本文件表格样本使用的显式动态 Schema,禁止依赖生产硬编码别名。""" aliases = { 'line_no': ['Line No'], 'part_number': ['Part Number', 'MPN', 'Vendor Part Number'], 'qty': ['Qty', 'Quantity', 'Order Qty', 'Allocated QTY'], 'unit_price': ['Unit Price'], 'line_amount_with_tax': ['Amount'], 'currency': ['Currency'], 'reservation_id': ['Reservation ID', 'Reservation Order', 'Reservation N.r', 'External reservation ID'], 'required_date': ['ETA'], 'customer_part_number': ['Allocated HHPN'], 'aws_part_number': ['Allocated APN', 'Material', 'AWS Sku'], 'inventory_source_hint': ['source type'], 'po_number': ['PO'], } decimal_fields = {'qty', 'unit_price', 'line_amount_with_tax'} return {'fields': [{ 'field_id': f'test-{code}', 'field_code': code, 'scope': 'header' if code == 'po_number' else 'line', 'value_type': 'decimal' if code in decimal_fields else 'date' if code == 'required_date' else 'string', 'enabled': True, 'display_name': code, 'aliases': values, 'normalizer_key': 'trim', 'validator_keys': ['positive_decimal'] if code == 'qty' else ['reservation_id'] if code == 'reservation_id' else [], } for code, values in aliases.items()]} def _table_contract(): """编译测试共享的冻结表头契约。""" return compile_table_header_contract(_table_schema_definition()) 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) def test_extract_notice_text_preview_only_skips_pdf_loader_and_ocr(tmp_path): """上传快览只返回普通文件元信息,绝不能同步调用 PDF Loader 或 OCR。""" from app.services.shipping_notice.notice_upload import extract_notice_text path = tmp_path / "order.pdf" path.write_bytes(_minimal_pdf_bytes("PREVIEW-ONLY")) with patch('app.services.shipping_notice.notice_upload.loader_pdf.run') as pdf_loader, patch( 'app.services.shipping_notice.notice_upload.ocr.run', ) as ocr_loader: text, meta = extract_notice_text(path, preview_only=True) assert text == "" assert meta == { 'warnings': [], 'file_type': 'pdf', 'content_mode': 'preview', } pdf_loader.assert_not_called() ocr_loader.assert_not_called() def test_extract_notice_text_preview_only_skips_plain_text_read(tmp_path): """快览对文本文件也只返回目录元信息,不能读取或持久化正文。""" from app.services.shipping_notice.notice_upload import extract_notice_text path = tmp_path / "order.txt" path.write_text("PO Number: 4510039227", encoding="utf-8") with patch.object(Path, "read_bytes", side_effect=AssertionError("preview must not read content")): text, meta = extract_notice_text(path, preview_only=True) assert text == "" assert meta == { 'warnings': [], 'file_type': 'txt', 'content_mode': 'preview', } _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 = "", ) -> 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" if not pdf_path.exists(): pytest.skip("XFA PDF fixture docs/prototype/4510038672.pdf is not present") 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, schema_definition=_table_schema_definition()) assert len(rows) == 3 assert rows[0]['po_number'] == '4510039227' assert rows[0]['reservation_id'] == '2000485916' assert rows[0]['part_number'] == 'D4-A08AR12000001' assert rows[0]['qty'] == 30 assert rows[0]['inventory_source_hint'] == 'VMI-FRA01' assert rows[0]['customer_part_number'] == 'TEMP-S000218922' assert rows[0]['aws_part_number'] == '504-006043-001' assert rows[2]['inventory_source_hint'] == 'DBS DUB' fused = merge_attachment_candidate( attachment_summary={ 'po_number': '4510039227', 'reservation_ids': ['2000485916'], 'lines': [{'reservation_id': '2000485916', 'part_number': 'D4-A08AR12000001', '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['inventory_source_hint'] == 'VMI-FRA01' assert line['customer_part_number'] == 'TEMP-S000218922' assert line['aws_part_number'] == '504-006043-001' conflict = merge_attachment_candidate( attachment_summary={ 'po_number': '4510039227', 'reservation_ids': ['2000485916'], 'lines': [{'reservation_id': '2000485916', 'part_number': 'D4-A08AR12000001', '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', 'part_number': 'OTHER-SKU', 'qty': 5}, {'reservation_id': '2000485916', 'part_number': 'D4-A08AR12000001', 'qty': 30}, ], }, filename='4510039227.pdf', body_rows=rows, ) assert multi_line['validation_status'] == 'ready' assert 'inventory_source_hint' not in multi_line['business_summary']['lines'][0] assert multi_line['business_summary']['lines'][1]['inventory_source_hint'] == '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"] == "" 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", "", _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_preview_eml_skips_signature_inline_image_from_attachment_count(tmp_path): """签名图不计数,但快览和深度解析必须保留一致的业务附件键。""" from app.services.shipping_notice.notice_upload import extract_notice_text raw = _build_eml( subject="Two POs", body="Body with two PO attachments.", attachments=[ ("order-1.pdf", "application/pdf", _minimal_pdf_bytes("PO-ONE")), ("order-2.pdf", "application/pdf", _minimal_pdf_bytes("PO-TWO")), ], inline_images=[("signature.png", "", _TINY_PNG)], ) path = tmp_path / "preview-with-signature.eml" path.write_bytes(raw) _, preview_meta = extract_notice_text(path, eml_attachment_mode="preview") _, deep_meta = extract_notice_text(path) assert preview_meta["attachment_count"] == 2 assert preview_meta["attachment_registered_count"] == 2 assert [item["filename"] for item in preview_meta["attachments"]] == ["order-1.pdf", "order-2.pdf"] assert [item["attachment_key"] for item in preview_meta["attachments"]] == ["att-002", "att-003"] assert [item["attachment_key"] for item in deep_meta["attachments"]] == ["att-002", "att-003"] assert any(str(w).startswith("eml_inline_resources_skipped:") for w in preview_meta["warnings"]) 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("

HTML-PO-202 please ship

", "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("ALT-PO-HTML-303", "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("

ROOT-ALT-HTML-404

", "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 = ( "" "" "" "" "" "
POQty
451003922730
45100392282
A&B3
" ) 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 = ( "" "" "" "
SKUParent allocation IDExternal reservation ID
A001AWS-311
" ) 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_at_delimited_pr_number(): """PR Number 中以 ``@`` 明确分隔的完整数字可作为 Reservation ID。""" 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 = [ { "part_number": "D4-A08AR12000002", "customer_part_number": "TEMP-S000218929", "qty": 10, "uom": "EA", "reservation_id": "1f1a682dfdc446a393415dee93eb36ce", } ] adjudicated, issues, status = adjudicate_notice_lines( lines, raw_text=raw_text, schema_definition=_table_schema_definition(), ) assert status == "ready" assert adjudicated[0]["reservation_id"] == "3000092917" assert issues == [ { "line_index": 0, "part_number": "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 = [ { "part_number": "D4-A08AR12000002", "qty": 10, "uom": "EA", "reservation_id": "1f1a682dfdc446a393415dee93eb36ce", } ] adjudicated, issues, status = adjudicate_notice_lines( lines, raw_text=raw_text, schema_definition=_table_schema_definition(), ) 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_five_digit_reservation_templates(): """不同来源模板可使用 5 位数字 Reservation ID,并保留明确列证据。""" raw_text = "Part Number\tReservation Order\tQty\nA001\t12345\t2" lines = [{"part_number": "A001", "reservation_id": "", "qty": 2, "uom": "EA"}] adjudicated, issues, status = adjudicate_notice_lines( lines, raw_text=raw_text, schema_definition=_table_schema_definition(), ) assert status == "ready" assert adjudicated[0]["reservation_id"] == "12345" assert issues[0]["reason"] == "value_corrected" def test_wistron_po_table_does_not_broadcast_document_reservation_to_every_line(): 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, contract=_table_contract()) assert len(lines) == 1 assert lines[0]["part_number"] == "B3-A08AR11000001" assert lines[0]["qty"] == 9.0 assert lines[0]["unit_price"] == 1607.72 assert lines[0]["amount"] == 14469.48 assert "reservation_id" not in lines[0] assert lines[0]["required_date"] == "2026-06-15" 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 = """ Part Number\tReservation ID\tQty\tUnit Price\tAmount 10-40594-001\t1000140351\t2\t15.5\t31.0 """ lines = parse_notice_table_text(text, contract=_table_contract()) assert lines[0]["reservation_id"] == "1000140351" def test_extract_notice_supports_five_digit_reservation_free_text(): """自由文本回退路径应识别 5 位 Reservation ID、内部料号和数量。""" parsed, _confidence, _warnings = _heuristic_extract("12345 10-40594-001 2") assert parsed["lines"] == [{ "reservation_id": "12345", "part_number": "10-40594-001", "qty": 2.0, }] def test_does_not_infer_reservation_id_without_configured_header(): headers = ["Part Number", "Ref", "Qty"] rows = [["10-40594-001", 1000140351, 2]] lines = parse_notice_table_rows(headers, rows, contract=_table_contract()) assert "reservation_id" not in lines[0] def test_parse_notice_table_with_all_fields(): text = """ Part Number\tReservation ID\tQty\tUnit Price\tAmount 10-40594-001\t1000140351\t2\t15.5\t31.0 10-40594-002\t1000140352\t1\t20\t20 """ lines = parse_notice_table_text(text, contract=_table_contract()) assert len(lines) == 2 assert lines[0]["part_number"] == "10-40594-001" assert lines[0]["reservation_id"] == "1000140351" assert lines[0]["qty"] == 2 assert lines[0]["unit_price"] == 15.5 assert lines[0]["amount"] == 31.0 def test_normalize_notice_line_aliases(): # 表头业务别名不再内置于代码;只经本次冻结 Schema 解析(见 notice_lines 迁移说明)。 # line_no 为系统生成项次,不参与 normalize 派生,故从结果中移除。 schema_definition = { 'fields': [ {'field_id': 't-line_no', 'field_code': 'line_no', 'scope': 'line', 'enabled': True, 'aliases': ['Line No']}, {'field_id': 't-part', 'field_code': 'part_number', 'scope': 'line', 'enabled': True, 'aliases': []}, {'field_id': 't-qty', 'field_code': 'qty', 'scope': 'line', 'value_type': 'decimal', 'enabled': True, 'aliases': ['quantity']}, {'field_id': 't-rid', 'field_code': 'reservation_id', 'scope': 'line', 'enabled': True, 'aliases': ['com_id']}, {'field_id': 't-price', 'field_code': 'unit_price', 'scope': 'line', 'value_type': 'decimal', 'enabled': True, 'aliases': ['price']}, {'field_id': 't-amount', 'field_code': 'line_amount_with_tax', 'scope': 'line', 'value_type': 'decimal', 'enabled': True, 'aliases': []}, {'field_id': 't-currency', 'field_code': 'currency', 'scope': 'line', 'enabled': True, 'aliases': []}, {'field_id': 't-date', 'field_code': 'required_date', 'scope': 'line', 'value_type': 'date', 'enabled': True, 'aliases': ['delivery_date']}, {'field_id': 't-cust', 'field_code': 'customer_part_number', 'scope': 'line', 'enabled': True, 'aliases': []}, {'field_id': 't-aws', 'field_code': 'aws_part_number', 'scope': 'line', 'enabled': True, 'aliases': []}, ] } line = normalize_notice_line( { "part_number": "A-001", "quantity": "3", "com_id": "1000140351", "price": "12.5", "delivery_date": "2026/06/15", "customer_part_number": "CUST-001", "aws_part_number": "AWS-001", "currency": "USD", "line_no": "10", }, schema_definition=schema_definition, ) assert line == { "part_number": "A-001", "qty": 3.0, "reservation_id": "1000140351", "unit_price": 12.5, "amount": 37.5, "currency": "USD", "required_date": "2026-06-15", "customer_part_number": "CUST-001", "aws_part_number": "AWS-001", } def test_normalize_notice_line_uses_frozen_schema_aliases_for_inventory_source_hint(): """邮件列名只有在本次冻结 Schema 配置后才可映射库存源线索,禁止代码内置业务别名。""" schema_definition = { 'fields': [ { 'field_id': 'part', 'field_code': 'part_number', 'scope': 'line', 'enabled': True, 'display_name': '内部料号', 'aliases': ['Custom MPN'], }, { 'field_id': 'qty', 'field_code': 'qty', 'scope': 'line', 'enabled': True, 'display_name': '数量', 'aliases': ['Custom Qty'], }, { 'field_id': 'source', 'field_code': 'inventory_source_hint', 'scope': 'line', 'enabled': True, 'display_name': '库存源线索', 'aliases': ['VMI HUB'], }, ], } line = normalize_notice_line( {'Custom MPN': 'A-001', 'Custom Qty': '3', 'VMI HUB': 'CMH01'}, schema_definition=schema_definition, ) assert line == { 'part_number': 'A-001', 'qty': 3.0, 'inventory_source_hint': 'CMH01', } def test_normalize_notice_line_uses_schema_alias_for_line_remark(): """行备注只能通过冻结 Schema 的正式字段和别名进入订单行。""" schema_definition = { 'fields': [ { 'field_id': 'part', 'field_code': 'part_number', 'scope': 'line', 'enabled': True, 'display_name': '内部料号', 'aliases': ['Custom MPN'], }, { 'field_id': 'qty', 'field_code': 'qty', 'scope': 'line', 'enabled': True, 'display_name': '数量', 'aliases': ['Custom Qty'], }, { 'field_id': 'remark', 'field_code': 'line_remark', 'scope': 'line', 'enabled': True, 'display_name': '行备注', 'aliases': ['Customer Note'], }, ], } line = normalize_notice_line( {'Custom MPN': 'A-001', 'Custom Qty': '3', 'Customer Note': 'Ship together'}, schema_definition=schema_definition, ) assert line == { 'part_number': 'A-001', 'qty': 3.0, 'line_remark': 'Ship together', } def test_parse_notice_table_keeps_configured_line_remark(): """表格中的行备注仅在冻结 Schema 声明其别名后进入解析结果。""" schema_definition = _table_schema_definition() schema_definition['fields'].append({ 'field_id': 'line-remark', 'field_code': 'line_remark', 'scope': 'line', 'value_type': 'string', 'enabled': True, 'display_name': '行备注', 'aliases': ['Customer Note'], 'normalizer_key': 'trim', 'validator_keys': [], }) lines = parse_notice_table_rows( ['MPN', 'Allocated QTY', 'Customer Note'], [['D4-A08AR12000002', 10, 'Ship together']], contract=compile_table_header_contract(schema_definition), ) assert lines == [{ 'part_number': 'D4-A08AR12000002', 'qty': 10.0, 'line_remark': 'Ship together', }] def test_schema_disables_free_text_field_guessing_after_table_parse_miss(): """存在冻结 Schema 时,表格未命中不得用固定 SKU x Qty 正则生成订单行。""" parsed, confidence, warnings = extract_notice_fields( raw_text='D4-A08AR12000002 x 10', schema_definition=_table_schema_definition(), ) assert parsed['lines'] == [] assert confidence == 0.0 assert 'schema_table_no_lines' in warnings def test_normalize_notice_line_splits_frozen_temp_composite(): """TEMP 二段复合文本应拆为客户料号和内部料号,禁止把组合值持久化。""" line = normalize_notice_line({ "part_number": "TEMP-S000218929/D4-A08AR12000002", "qty": 10, }) assert line is not None assert line["part_number"] == "D4-A08AR12000002" assert line["customer_part_number"] == "TEMP-S000218929" @pytest.mark.parametrize( "value", ["LEFT/RIGHT", "TEMP-A/D4-B/THIRD", "TEMP-A/TEMP-B"], ) def test_normalize_notice_line_rejects_ambiguous_composite(value): """未命中冻结规则的复合料号不得猜测角色或生成有效订单行。""" assert normalize_notice_line({"part_number": value, "qty": 1}) is None def test_parse_notice_table_maps_three_part_number_roles(): """MPN 与 Allocated HHPN 进入内部料号与客户料号;Allocated APN 已移出表格字段目录,不再按行解析。""" lines = parse_notice_table_rows( ["MPN", "Allocated HHPN", "Allocated APN", "Allocated QTY"], [["D4-A08AR12000002", "TEMP-S000218929", "504-006055-001", 10]], contract=_table_contract(), ) assert lines == [{ "part_number": "D4-A08AR12000002", "customer_part_number": "TEMP-S000218929", "qty": 10.0, }] def test_parse_notice_table_rejects_aws_only_as_internal_part_number(): """只有 AWS Sku 的表格缺少内部料号,不能生成可建单订单行。""" assert parse_notice_table_rows( ["AWS Sku", "Reservation ID", "Qty"], [["504-006055-001", "3000092917", 10]], contract=_table_contract(), ) == [] 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": [{"part_number": "A-001", "qty": 1, "uom": "EA"}, {"part_number": "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": [{"part_number": "A-001", "qty": 1, "uom": "EA"}, {"part_number": "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": [ { "part_number": "10-40594-001", "qty": 2, "reservation_id": "1000140351", "unit_price": 10, "amount": 20, } ], "confidence": 0.9, } parsed, confidence, warnings = extract_notice_fields(raw_text="", structured=structured) assert parsed["lines"][0]["reservation_id"] == "1000140351" 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([{"part_number": "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 Part Number\tReservation Order\tOrder Qty\tUnit Price\tLine Amount 10-40594-001\t1000140351\t4\t5\t20 """ parsed, confidence, _ = _heuristic_extract(text, schema_definition=_table_schema_definition()) assert len(parsed["lines"]) == 1 assert parsed["lines"][0]["part_number"] == "10-40594-001" assert parsed["lines"][0]["reservation_id"] == "1000140351" 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": [{"part_number": "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]["part_number"] == "SKU-DIFY" assert confidence > 0.8 assert "parse_fallback_heuristic" not in warnings def test_extract_notice_fields_heuristic_fallback(): """无 structured 时走后端启发式兜底。""" text = "Part Number\tReservation Order\tOrder Qty\n10-40594-001\t1000140351\t4" parsed, _, warnings = extract_notice_fields( raw_text=text, schema_definition=_table_schema_definition(), ) assert parsed["parse_source"] == "heuristic" assert parsed["lines"][0]["part_number"] == "10-40594-001" assert "parse_fallback_heuristic" in warnings