Files
syops/backend/app/services/shipping_notice/business_fingerprint.py
T
hugo 1f3ecb87b7 feat(shipping_notice): 新增货代订单全流程业务模块及配套基建
本次提交新增货代订单处理全流程的完整业务能力、数据库迁移与测试用例:
1.  统一追加式审计事件体系,支持全链路不可篡改的业务追溯
2.  货代任务撤销、版本替代管控逻辑,规范已上传订单的合规版本更替
3.  订单抽取路由审计、模板自动冻结资格、路由计数等核心业务基建
4.  EML订单补充表解析契约与合并逻辑,完善订单补全能力
5.  Chatflow只读能力令牌校验机制,保障工具调用安全
6.  人工复核证据校验服务,规范人工审核的证据留存
所有变更均配套完整的单元测试与迁移契约测试,支持受控回退
2026-07-28 08:56:58 +08:00

225 lines
8.2 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.
"""
backend/app/services/shipping_notice/business_fingerprint.py
用途:基于业务摘要生成稳定业务指纹与强度判定(货代域,不含文件哈希)。
依赖:po_number / reservation_id 标准化函数。
逻辑:intake_parse_workflow / Candidate 级 duplicate_detection / 建单门闩共用;
身份算法版本 shipping-v2,内容算法版本 shipping-content-v4。
"""
from __future__ import annotations
import hashlib
import json
from decimal import Decimal, InvalidOperation
from typing import Any
from app.services.shipping_notice.po_number import normalize_po_number
from app.services.shipping_notice.reservation_id import validated_reservation_id
FINGERPRINT_VERSION = 'shipping-v2'
CONTENT_FINGERPRINT_VERSION = 'shipping-content-v4'
def _norm_text(value: Any) -> str:
return str(value or '').strip().upper()
def _norm_qty(value: Any) -> str:
if value is None or value == '':
return ''
try:
return format(Decimal(str(value)).quantize(Decimal('0.0001')), 'f')
except (InvalidOperation, ValueError, TypeError):
return _norm_text(value)
def _line_digest(lines: list[dict[str, Any]]) -> str:
parts: list[str] = []
for line in lines:
if not isinstance(line, dict):
continue
part_number = _norm_text(line.get('part_number'))
rid = validated_reservation_id(str(line.get('reservation_id') or '')) or ''
qty = _norm_qty(line.get('qty'))
if not part_number and not rid and not qty:
continue
parts.append(f'{part_number}|{rid}|{qty}')
parts.sort()
return '\n'.join(parts)
def _customer_identity(summary: dict[str, Any]) -> tuple[str, str]:
"""
解析客户身份键。
核心逻辑:优先 customer_code;启发式预解析常只有 customer_name,须回退到名称,
否则强业务单号(PO/Reservation)也无法生成 usable 指纹。
Returns:
(identity_value, identity_field) 如 ('ACME', 'customer_name');无则 ('', '')。
"""
code = _norm_text(summary.get('customer_code'))
if code:
return code, 'customer_code'
name = _norm_text(summary.get('customer_name'))
if name:
return name, 'customer_name'
return '', ''
def build_business_fingerprint(business_summary: dict[str, Any] | None) -> dict[str, Any]:
"""
由业务摘要生成指纹、强度与组成依据。
核心逻辑(shipping-v2):
- strong:客户身份(code 或 name)+ PO;Reservation、料号与数量只属于内容版本。
- medium:客户身份 + 目的地 + required_date + 行 digest
- weak:ship_to 或 仅行 digest(SKU+qty)
- unavailable:不足以可靠去重
Args:
business_summary: intake_business_parser 产出。
Returns:
{fingerprint, version, strength, components}
"""
summary = business_summary if isinstance(business_summary, dict) else {}
customer_id, customer_field = _customer_identity(summary)
po_number = normalize_po_number(str(summary.get('po_number') or '')) or ''
dest = summary.get('destination') if isinstance(summary.get('destination'), dict) else {}
destination_key = '|'.join(
[
_norm_text(dest.get('code')),
_norm_text(dest.get('city')),
_norm_text(dest.get('country')),
]
).strip('|')
required_date = _norm_text(summary.get('required_date'))
ship_to = _norm_text(summary.get('ship_to'))
lines = summary.get('lines') if isinstance(summary.get('lines'), list) else []
line_digest = _line_digest([item for item in lines if isinstance(item, dict)])
strength = 'unavailable'
components: dict[str, Any] = {}
# [STEP 1] 订单身份只由客户 + PO 决定;可变订单内容必须转入 content_fingerprint。
if customer_id and po_number:
strength = 'strong'
components = {
customer_field: customer_id,
'po_number': po_number,
}
elif customer_id and destination_key and required_date and line_digest:
strength = 'medium'
components = {
customer_field: customer_id,
'destination': destination_key,
'required_date': required_date,
'line_digest': hashlib.sha256(line_digest.encode('utf-8')).hexdigest()[:16],
}
elif ship_to and line_digest:
strength = 'weak'
components = {
'ship_to': ship_to,
'line_digest': hashlib.sha256(line_digest.encode('utf-8')).hexdigest()[:16],
}
elif line_digest and (po_number or customer_id):
# 有行 digest 且至少一项单头标识:弱指纹,可标记 possible
strength = 'weak'
components = {
'line_digest': hashlib.sha256(line_digest.encode('utf-8')).hexdigest()[:16],
}
if customer_id:
components[customer_field] = customer_id
if po_number:
components['po_number'] = po_number
else:
return {
'fingerprint': None,
'version': FINGERPRINT_VERSION,
'strength': 'unavailable',
'components': {},
}
payload = {
'version': FINGERPRINT_VERSION,
'strength': strength,
'components': components,
}
digest = hashlib.sha256(
json.dumps(payload, ensure_ascii=False, sort_keys=True, separators=(',', ':')).encode('utf-8')
).hexdigest()
return {
'fingerprint': digest,
'version': FINGERPRINT_VERSION,
'strength': strength,
'components': components,
}
def build_content_fingerprint(business_summary: dict[str, Any] | None) -> dict[str, Any]:
"""
生成订单内容版本指纹,用于区分完全重复与同一订单修订。
核心逻辑:标准化并排序订单行,纳入 Reservation、SKU、数量、单位、交期及邮件分配字段;
单头目的地和 PO 仅用于增强内容比较,不替代身份指纹。
Args:
business_summary: Candidate 融合后的业务摘要。
Returns:
包含 fingerprint、version 和 components 的字典;无有效订单行时 fingerprint 为空。
"""
summary = business_summary if isinstance(business_summary, dict) else {}
parts: list[str] = []
for line in summary.get('lines') or []:
if not isinstance(line, dict):
continue
values = [
_norm_text(line.get('line_no')),
validated_reservation_id(line.get('reservation_id')) or '',
_norm_text(line.get('part_number')),
_norm_qty(line.get('qty')),
_norm_text(line.get('uom')),
_norm_qty(line.get('unit_price')),
_norm_qty(line.get('amount')),
_norm_text(line.get('currency')),
_norm_text(line.get('required_date')),
normalize_po_number(line.get('po_number')) or '',
_norm_text(line.get('allocation_id')),
_norm_text(line.get('inventory_source_hint')),
_norm_text(line.get('customer_part_number')),
_norm_text(line.get('aws_part_number')),
]
if any(values):
parts.append('|'.join(values))
if not parts:
return {
'fingerprint': None,
'version': CONTENT_FINGERPRINT_VERSION,
'components': {},
}
parts.sort()
destination = summary.get('destination') if isinstance(summary.get('destination'), dict) else {}
components = {
'po_number': normalize_po_number(summary.get('po_number')) or None,
'destination': '|'.join(
_norm_text(destination.get(key)) for key in ('code', 'city', 'country')
).strip('|') or None,
'ship_to': _norm_text(summary.get('ship_to')) or None,
'required_date': _norm_text(summary.get('required_date')) or None,
'warehouse_hint': _norm_text(summary.get('warehouse_hint')) or None,
'lines': parts,
}
digest = hashlib.sha256(
json.dumps(
{'version': CONTENT_FINGERPRINT_VERSION, 'components': components},
ensure_ascii=False,
sort_keys=True,
separators=(',', ':'),
).encode('utf-8')
).hexdigest()
return {
'fingerprint': digest,
'version': CONTENT_FINGERPRINT_VERSION,
'components': components,
}