feat(shipping-notice): 新增货代客户管理功能,支持客户导入、识别证据管理与客户确认
This commit is contained in:
1 parent
b595e157e9
commit
4fbaed2b4c
176 files changed
+14011
-994
No files matched your search
@@ -14,6 +14,8 @@ from . import (
|
||||
guide_service,
|
||||
permission_service,
|
||||
report_service,
|
||||
shipping_customer_import_service,
|
||||
shipping_customer_service,
|
||||
user_service,
|
||||
wecom_admin_service,
|
||||
)
|
||||
@@ -28,6 +30,8 @@ __all__ = [
|
||||
'guide_service',
|
||||
'permission_service',
|
||||
'report_service',
|
||||
'shipping_customer_import_service',
|
||||
'shipping_customer_service',
|
||||
'user_service',
|
||||
'wecom_admin_service',
|
||||
]
|
||||
@@ -0,0 +1,706 @@
|
||||
"""
|
||||
services/admin/shipping_customer_import_service.py
|
||||
|
||||
用途:货代期初客户 Excel 模板、上传预检、行级决策、单事务发布与对账。
|
||||
依赖:openpyxl、客户/导入模型、shipping_customer_service、customer_normalization。
|
||||
逻辑:上传仅落暂存;发布前阻断错误与未决警告,正式客户及识别证据在一个事务内写入。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import csv
|
||||
import hashlib
|
||||
import io
|
||||
import uuid
|
||||
from datetime import date, datetime, time
|
||||
from typing import Any
|
||||
|
||||
from openpyxl import Workbook, load_workbook
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
|
||||
from app import db
|
||||
from app.core.errors import AppError, ConflictError, NotFoundError, ValidationError
|
||||
from app.models import (
|
||||
ShippingCustomer,
|
||||
ShippingCustomerExternalRef,
|
||||
ShippingCustomerIdentifier,
|
||||
ShippingCustomerImportBatch,
|
||||
ShippingCustomerImportRow,
|
||||
)
|
||||
from app.services.admin.shipping_customer_service import serialize_customer
|
||||
from app.services.shipping_notice.customer_normalization import (
|
||||
clean_text,
|
||||
is_public_email_domain,
|
||||
normalize_customer_name,
|
||||
normalize_identifier,
|
||||
normalize_short_code,
|
||||
)
|
||||
|
||||
MAX_IMPORT_BYTES = 5 * 1024 * 1024
|
||||
MAX_IMPORT_ROWS = 10_000
|
||||
CUSTOMER_HEADERS = ('legacy_customer_key', 'standard_name', 'short_code', 'status', 'source_system', 'remark')
|
||||
IDENTIFIER_HEADERS = (
|
||||
'legacy_customer_key',
|
||||
'source_system',
|
||||
'identifier_type',
|
||||
'identifier_value',
|
||||
'auto_match_allowed',
|
||||
'remark',
|
||||
)
|
||||
ROW_DECISIONS = frozenset({'create', 'update', 'merge', 'skip'})
|
||||
|
||||
|
||||
def generate_import_batch_no() -> str:
|
||||
"""生成客户导入批次号。"""
|
||||
return f"SCI-{datetime.utcnow().strftime('%Y%m%d')}-{uuid.uuid4().hex[:8].upper()}"
|
||||
|
||||
|
||||
def build_import_template() -> bytes:
|
||||
"""生成包含 customers/identifiers 两个 Sheet 的标准期初导入模板。"""
|
||||
wb = Workbook()
|
||||
customers = wb.active
|
||||
customers.title = 'customers'
|
||||
customers.append(CUSTOMER_HEADERS)
|
||||
customers.append(('INIT-000001', '无锡宇辰有限公司', 'WYC', 'active', 'INITIAL_EXCEL', '示例行,可删除'))
|
||||
identifiers = wb.create_sheet('identifiers')
|
||||
identifiers.append(IDENTIFIER_HEADERS)
|
||||
identifiers.append(('INIT-000001', 'INITIAL_EXCEL', 'name_alias', 'WUXI YUCHEN', False, '历史英文名称'))
|
||||
output = io.BytesIO()
|
||||
wb.save(output)
|
||||
return output.getvalue()
|
||||
|
||||
|
||||
def _cell_bool(value: Any) -> bool:
|
||||
"""将 Excel 常见真假写法转换为 bool。"""
|
||||
if isinstance(value, bool):
|
||||
return value
|
||||
return clean_text(value).lower() in {'1', 'true', 'yes', 'y', '是'}
|
||||
|
||||
|
||||
def _json_safe_cell(value: Any) -> Any:
|
||||
"""将 Excel 单元格转换为 JSON 可持久化值,日期时间使用 ISO 8601。"""
|
||||
if value is None or isinstance(value, (str, int, float, bool)):
|
||||
return value
|
||||
if isinstance(value, (datetime, date, time)):
|
||||
return value.isoformat()
|
||||
return str(value)
|
||||
|
||||
|
||||
def _sheet_rows(workbook, sheet_name: str, headers: tuple[str, ...]) -> list[tuple[int, dict[str, Any]]]:
|
||||
"""校验 Sheet 表头并返回非空数据行。"""
|
||||
if sheet_name not in workbook.sheetnames:
|
||||
raise ValidationError(
|
||||
f'Missing sheet: {sheet_name}',
|
||||
code='SHIPPING.CUSTOMER_IMPORT_SHEET_MISSING',
|
||||
details={'sheet': sheet_name},
|
||||
)
|
||||
sheet = workbook[sheet_name]
|
||||
actual = tuple(clean_text(cell.value) for cell in sheet[1])
|
||||
missing = [header for header in headers if header not in actual]
|
||||
if missing:
|
||||
raise ValidationError(
|
||||
'Customer import columns missing',
|
||||
code='SHIPPING.CUSTOMER_IMPORT_COLUMNS_MISSING',
|
||||
details={'sheet': sheet_name, 'missing': missing},
|
||||
)
|
||||
positions = {header: actual.index(header) for header in headers}
|
||||
result: list[tuple[int, dict[str, Any]]] = []
|
||||
for row_no, values in enumerate(sheet.iter_rows(min_row=2, values_only=True), start=2):
|
||||
if not any(value not in (None, '') for value in values):
|
||||
continue
|
||||
result.append((row_no, {header: values[index] if index < len(values) else None for header, index in positions.items()}))
|
||||
if len(result) > MAX_IMPORT_ROWS:
|
||||
raise ValidationError(
|
||||
'Customer import contains too many rows',
|
||||
code='SHIPPING.CUSTOMER_IMPORT_TOO_MANY_ROWS',
|
||||
details={'sheet': sheet_name, 'max_rows': MAX_IMPORT_ROWS},
|
||||
)
|
||||
return result
|
||||
|
||||
|
||||
def _existing_customer_by_ref(source_system: str, legacy_key: str) -> ShippingCustomer | None:
|
||||
"""按外部来源稳定键查找已导入客户。"""
|
||||
ref = db.session.query(ShippingCustomerExternalRef).filter_by(
|
||||
source_system=source_system,
|
||||
legacy_customer_key=legacy_key,
|
||||
).first()
|
||||
return db.session.get(ShippingCustomer, ref.customer_id) if ref else None
|
||||
|
||||
|
||||
def _customer_row_validation(raw: dict[str, Any], *, default_source_system: str) -> dict[str, Any]:
|
||||
"""预检单条 customers 行,返回标准化字段、错误、警告和建议动作。"""
|
||||
errors: list[dict[str, Any]] = []
|
||||
warnings: list[dict[str, Any]] = []
|
||||
legacy_key = clean_text(raw.get('legacy_customer_key'))
|
||||
name = clean_text(raw.get('standard_name'))
|
||||
source_system = clean_text(raw.get('source_system') or default_source_system).upper()
|
||||
status = clean_text(raw.get('status') or 'active').lower()
|
||||
short_code = ''
|
||||
if not legacy_key:
|
||||
errors.append({'code': 'SHIPPING.CUSTOMER_IMPORT_KEY_REQUIRED', 'field': 'legacy_customer_key'})
|
||||
elif len(legacy_key) > 128:
|
||||
errors.append({'code': 'SHIPPING.CUSTOMER_IMPORT_KEY_INVALID', 'field': 'legacy_customer_key'})
|
||||
if not name:
|
||||
errors.append({'code': 'SHIPPING.CUSTOMER_NAME_REQUIRED', 'field': 'standard_name'})
|
||||
elif len(name) > 200:
|
||||
errors.append({'code': 'SHIPPING.CUSTOMER_IMPORT_NAME_TOO_LONG', 'field': 'standard_name'})
|
||||
if not source_system or len(source_system) > 64:
|
||||
errors.append({'code': 'SHIPPING.CUSTOMER_IMPORT_SOURCE_INVALID', 'field': 'source_system'})
|
||||
try:
|
||||
short_code = normalize_short_code(raw.get('short_code'))
|
||||
except ValidationError as exc:
|
||||
errors.append({'code': exc.code, 'field': 'short_code'})
|
||||
if status not in {'active', 'inactive'}:
|
||||
errors.append({'code': 'SHIPPING.CUSTOMER_STATUS_INVALID', 'field': 'status'})
|
||||
existing_ref = _existing_customer_by_ref(source_system, legacy_key) if legacy_key and source_system else None
|
||||
code_owner = db.session.query(ShippingCustomer).filter_by(short_code=short_code).first() if short_code else None
|
||||
if code_owner and (not existing_ref or code_owner.id != existing_ref.id):
|
||||
warnings.append({
|
||||
'code': 'SHIPPING.CUSTOMER_IMPORT_SHORT_CODE_CONFLICT',
|
||||
'customer_id': code_owner.id,
|
||||
'short_code': short_code,
|
||||
})
|
||||
normalized_name = normalize_customer_name(name)
|
||||
similar = [
|
||||
item for item in db.session.query(ShippingCustomer).all()
|
||||
if normalize_customer_name(item.standard_name) == normalized_name and (not existing_ref or item.id != existing_ref.id)
|
||||
] if normalized_name else []
|
||||
if similar:
|
||||
warnings.append({
|
||||
'code': 'SHIPPING.CUSTOMER_IMPORT_NAME_MATCH',
|
||||
'candidate_customer_ids': [item.id for item in similar],
|
||||
})
|
||||
suggested_action = 'update' if existing_ref else 'create'
|
||||
target_customer_id = existing_ref.id if existing_ref else None
|
||||
validation_status = 'error' if errors else 'warning' if warnings else 'valid'
|
||||
return {
|
||||
'legacy_customer_key': legacy_key or None,
|
||||
'normalized': {
|
||||
'legacy_customer_key': legacy_key,
|
||||
'standard_name': name,
|
||||
'short_code': short_code,
|
||||
'status': status,
|
||||
'source_system': source_system,
|
||||
'remark': clean_text(raw.get('remark')),
|
||||
},
|
||||
'errors': errors,
|
||||
'warnings': warnings,
|
||||
'validation_status': validation_status,
|
||||
'suggested_action': suggested_action,
|
||||
'target_customer_id': target_customer_id,
|
||||
}
|
||||
|
||||
|
||||
def _identifier_row_validation(raw: dict[str, Any], *, default_source_system: str) -> dict[str, Any]:
|
||||
"""预检单条 identifiers 行,补齐来源系统并将公共邮箱证据降级为人工匹配。"""
|
||||
errors: list[dict[str, Any]] = []
|
||||
warnings: list[dict[str, Any]] = []
|
||||
legacy_key = clean_text(raw.get('legacy_customer_key'))
|
||||
source_system = clean_text(raw.get('source_system') or default_source_system).upper()
|
||||
kind = clean_text(raw.get('identifier_type')).lower()
|
||||
value = clean_text(raw.get('identifier_value'))
|
||||
auto_allowed = _cell_bool(raw.get('auto_match_allowed'))
|
||||
normalized = ''
|
||||
if not legacy_key:
|
||||
errors.append({'code': 'SHIPPING.CUSTOMER_IMPORT_KEY_REQUIRED', 'field': 'legacy_customer_key'})
|
||||
elif len(legacy_key) > 128:
|
||||
errors.append({'code': 'SHIPPING.CUSTOMER_IMPORT_KEY_INVALID', 'field': 'legacy_customer_key'})
|
||||
if not source_system or len(source_system) > 64:
|
||||
errors.append({'code': 'SHIPPING.CUSTOMER_IMPORT_SOURCE_INVALID', 'field': 'source_system'})
|
||||
try:
|
||||
normalized = normalize_identifier(kind, value)
|
||||
except ValidationError as exc:
|
||||
errors.append({'code': exc.code, 'field': 'identifier_value'})
|
||||
if kind in {'domain', 'email'} and normalized and is_public_email_domain(normalized):
|
||||
if auto_allowed:
|
||||
warnings.append({'code': 'SHIPPING.CUSTOMER_PUBLIC_DOMAIN_AUTO_MATCH_FORBIDDEN'})
|
||||
auto_allowed = False
|
||||
validation_status = 'error' if errors else 'warning' if warnings else 'valid'
|
||||
return {
|
||||
'legacy_customer_key': legacy_key or None,
|
||||
'normalized': {
|
||||
'legacy_customer_key': legacy_key,
|
||||
'source_system': source_system,
|
||||
'identifier_type': kind,
|
||||
'identifier_value': value,
|
||||
'normalized_value': normalized,
|
||||
'auto_match_allowed': auto_allowed,
|
||||
'remark': clean_text(raw.get('remark')),
|
||||
},
|
||||
'errors': errors,
|
||||
'warnings': warnings,
|
||||
'validation_status': validation_status,
|
||||
'suggested_action': 'create',
|
||||
'target_customer_id': None,
|
||||
}
|
||||
|
||||
|
||||
def serialize_import_row(row: ShippingCustomerImportRow) -> dict[str, Any]:
|
||||
"""序列化导入暂存行。"""
|
||||
return {
|
||||
'id': row.id,
|
||||
'sheet_name': row.sheet_name,
|
||||
'row_no': row.row_no,
|
||||
'row_type': row.row_type,
|
||||
'legacy_customer_key': row.legacy_customer_key,
|
||||
'raw': row.raw_json or {},
|
||||
'normalized': row.normalized_json or {},
|
||||
'validation_status': row.validation_status,
|
||||
'errors': row.errors_json or [],
|
||||
'warnings': row.warnings_json or [],
|
||||
'suggested_action': row.suggested_action,
|
||||
'decision_action': row.decision_action,
|
||||
'target_customer_id': row.target_customer_id,
|
||||
'decision_note': row.decision_note,
|
||||
'result_customer_id': row.result_customer_id,
|
||||
'result_status': row.result_status,
|
||||
'result_message': row.result_message,
|
||||
}
|
||||
|
||||
|
||||
def serialize_import_batch(batch: ShippingCustomerImportBatch, *, include_rows: bool = True) -> dict[str, Any]:
|
||||
"""序列化导入批次及统计。"""
|
||||
payload: dict[str, Any] = {
|
||||
'id': batch.id,
|
||||
'batch_no': batch.batch_no,
|
||||
'file_name': batch.file_name,
|
||||
'file_hash': batch.file_hash,
|
||||
'file_size': batch.file_size,
|
||||
'source_system': batch.source_system,
|
||||
'status': batch.status,
|
||||
'total_rows': batch.total_rows,
|
||||
'valid_rows': batch.valid_rows,
|
||||
'warning_rows': batch.warning_rows,
|
||||
'error_rows': batch.error_rows,
|
||||
'published_rows': batch.published_rows,
|
||||
'uploaded_by_id': batch.uploaded_by_id,
|
||||
'published_by_id': batch.published_by_id,
|
||||
'published_at': batch.published_at.isoformat() if batch.published_at else None,
|
||||
'created_at': batch.created_at.isoformat() if batch.created_at else None,
|
||||
}
|
||||
if include_rows:
|
||||
payload['rows'] = [serialize_import_row(row) for row in batch.rows]
|
||||
return payload
|
||||
|
||||
|
||||
def create_import_batch(upload: Any, *, source_system: str, actor_id: int | None) -> dict[str, Any]:
|
||||
"""
|
||||
上传并预检客户期初 Excel。
|
||||
|
||||
Args:
|
||||
upload: Flask FileStorage,仅支持 .xlsx,最大 5 MB。
|
||||
source_system: 默认来源系统;行内可覆盖。
|
||||
actor_id: 上传管理员 ID。
|
||||
Returns:
|
||||
导入批次详情;同文件哈希重复上传返回原批次并标记 idempotent_replay。
|
||||
"""
|
||||
filename = clean_text(getattr(upload, 'filename', ''))
|
||||
if not filename.lower().endswith('.xlsx'):
|
||||
raise ValidationError('Only .xlsx customer import files are supported', code='SHIPPING.CUSTOMER_IMPORT_FILE_TYPE_INVALID')
|
||||
content = upload.read() if hasattr(upload, 'read') else b''
|
||||
if not content:
|
||||
raise ValidationError('Customer import file is empty', code='SHIPPING.CUSTOMER_IMPORT_FILE_EMPTY')
|
||||
if len(content) > MAX_IMPORT_BYTES:
|
||||
raise ValidationError(
|
||||
'Customer import file is too large',
|
||||
code='SHIPPING.CUSTOMER_IMPORT_FILE_TOO_LARGE',
|
||||
details={'max_bytes': MAX_IMPORT_BYTES},
|
||||
)
|
||||
normalized_source = clean_text(source_system).upper() or 'INITIAL_EXCEL'
|
||||
if len(normalized_source) > 64:
|
||||
raise ValidationError(
|
||||
'Customer import source system is too long',
|
||||
code='SHIPPING.CUSTOMER_IMPORT_SOURCE_INVALID',
|
||||
details={'field': 'source_system', 'max_length': 64},
|
||||
)
|
||||
file_hash = hashlib.sha256(content).hexdigest()
|
||||
existing = db.session.query(ShippingCustomerImportBatch).filter_by(
|
||||
file_hash=file_hash,
|
||||
source_system=normalized_source,
|
||||
).first()
|
||||
if existing:
|
||||
result = serialize_import_batch(existing)
|
||||
result['idempotent_replay'] = True
|
||||
return result
|
||||
try:
|
||||
workbook = load_workbook(io.BytesIO(content), data_only=True, read_only=True)
|
||||
except Exception as exc:
|
||||
raise ValidationError(
|
||||
'Invalid customer import Excel file',
|
||||
code='SHIPPING.CUSTOMER_IMPORT_FILE_INVALID',
|
||||
details={'error_type': type(exc).__name__},
|
||||
) from exc
|
||||
try:
|
||||
customer_rows = _sheet_rows(workbook, 'customers', CUSTOMER_HEADERS)
|
||||
identifier_rows = _sheet_rows(workbook, 'identifiers', IDENTIFIER_HEADERS)
|
||||
finally:
|
||||
workbook.close()
|
||||
batch = ShippingCustomerImportBatch(
|
||||
batch_no=generate_import_batch_no(),
|
||||
file_name=filename,
|
||||
file_hash=file_hash,
|
||||
file_size=len(content),
|
||||
source_system=normalized_source,
|
||||
uploaded_by_id=actor_id,
|
||||
status='validated',
|
||||
)
|
||||
db.session.add(batch)
|
||||
staged: list[ShippingCustomerImportRow] = []
|
||||
try:
|
||||
db.session.flush()
|
||||
seen_keys: set[tuple[str, str]] = set()
|
||||
order = 0
|
||||
for sheet_name, row_type, rows, validator in (
|
||||
(
|
||||
'customers',
|
||||
'customer',
|
||||
customer_rows,
|
||||
lambda raw: _customer_row_validation(raw, default_source_system=normalized_source),
|
||||
),
|
||||
(
|
||||
'identifiers',
|
||||
'identifier',
|
||||
identifier_rows,
|
||||
lambda raw: _identifier_row_validation(raw, default_source_system=normalized_source),
|
||||
),
|
||||
):
|
||||
for row_no, raw in rows:
|
||||
order += 1
|
||||
result = validator(raw)
|
||||
errors = list(result['errors'])
|
||||
normalized = result['normalized']
|
||||
if row_type == 'customer':
|
||||
key = (normalized.get('source_system') or '', normalized.get('legacy_customer_key') or '')
|
||||
if key in seen_keys:
|
||||
errors.append({'code': 'SHIPPING.CUSTOMER_IMPORT_DUPLICATE_KEY'})
|
||||
result['validation_status'] = 'error'
|
||||
seen_keys.add(key)
|
||||
staged.append(ShippingCustomerImportRow(
|
||||
batch_id=batch.id,
|
||||
sheet_name=sheet_name,
|
||||
row_no=row_no,
|
||||
row_order=order,
|
||||
row_type=row_type,
|
||||
legacy_customer_key=result['legacy_customer_key'],
|
||||
raw_json={key: _json_safe_cell(value) for key, value in raw.items()},
|
||||
normalized_json=normalized,
|
||||
validation_status=result['validation_status'],
|
||||
errors_json=errors,
|
||||
warnings_json=result['warnings'],
|
||||
suggested_action=result['suggested_action'],
|
||||
target_customer_id=result['target_customer_id'],
|
||||
))
|
||||
|
||||
customer_sources_by_key: dict[str, set[str]] = {}
|
||||
for row in staged:
|
||||
if row.row_type != 'customer' or not row.legacy_customer_key or row.validation_status == 'error':
|
||||
continue
|
||||
customer_sources_by_key.setdefault(row.legacy_customer_key, set()).add(
|
||||
clean_text((row.normalized_json or {}).get('source_system')).upper()
|
||||
)
|
||||
for row in staged:
|
||||
if row.row_type != 'identifier' or not row.legacy_customer_key:
|
||||
continue
|
||||
raw_source = clean_text((row.raw_json or {}).get('source_system')).upper()
|
||||
candidate_sources = customer_sources_by_key.get(row.legacy_customer_key) or set()
|
||||
if not raw_source and len(candidate_sources) == 1:
|
||||
row.normalized_json = {
|
||||
**(row.normalized_json or {}),
|
||||
'source_system': next(iter(candidate_sources)),
|
||||
}
|
||||
|
||||
customer_keys = {
|
||||
(
|
||||
clean_text((row.normalized_json or {}).get('source_system')).upper(),
|
||||
row.legacy_customer_key,
|
||||
)
|
||||
for row in staged
|
||||
if row.row_type == 'customer' and row.legacy_customer_key and row.validation_status != 'error'
|
||||
}
|
||||
for row in staged:
|
||||
if row.row_type != 'identifier' or not row.legacy_customer_key:
|
||||
continue
|
||||
source_system = clean_text((row.normalized_json or {}).get('source_system')).upper()
|
||||
if (source_system, row.legacy_customer_key) not in customer_keys:
|
||||
existing_ref = db.session.query(ShippingCustomerExternalRef.id).filter_by(
|
||||
source_system=source_system,
|
||||
legacy_customer_key=row.legacy_customer_key,
|
||||
).first()
|
||||
if not existing_ref:
|
||||
row.errors_json = [
|
||||
*(row.errors_json or []),
|
||||
{'code': 'SHIPPING.CUSTOMER_IMPORT_IDENTIFIER_CUSTOMER_MISSING'},
|
||||
]
|
||||
row.validation_status = 'error'
|
||||
|
||||
db.session.add_all(staged)
|
||||
batch.total_rows = len(staged)
|
||||
batch.valid_rows = sum(row.validation_status == 'valid' for row in staged)
|
||||
batch.warning_rows = sum(row.validation_status == 'warning' for row in staged)
|
||||
batch.error_rows = sum(row.validation_status == 'error' for row in staged)
|
||||
db.session.commit()
|
||||
except ValidationError:
|
||||
db.session.rollback()
|
||||
raise
|
||||
except IntegrityError as exc:
|
||||
db.session.rollback()
|
||||
existing = db.session.query(ShippingCustomerImportBatch).filter_by(
|
||||
file_hash=file_hash,
|
||||
source_system=normalized_source,
|
||||
).first()
|
||||
if existing is not None:
|
||||
result = serialize_import_batch(existing)
|
||||
result['idempotent_replay'] = True
|
||||
return result
|
||||
raise ConflictError(
|
||||
'Customer import upload conflict',
|
||||
code='SHIPPING.CUSTOMER_IMPORT_UPLOAD_CONFLICT',
|
||||
) from exc
|
||||
except Exception:
|
||||
db.session.rollback()
|
||||
raise
|
||||
return serialize_import_batch(batch)
|
||||
|
||||
|
||||
def get_import_batch(batch_id: int) -> dict[str, Any]:
|
||||
"""读取导入批次详情。"""
|
||||
batch = db.session.get(ShippingCustomerImportBatch, batch_id)
|
||||
if batch is None:
|
||||
raise NotFoundError('Customer import batch not found', code='SHIPPING.CUSTOMER_IMPORT_NOT_FOUND')
|
||||
return serialize_import_batch(batch)
|
||||
|
||||
|
||||
def decide_import_row(row_id: int, data: dict[str, Any]) -> dict[str, Any]:
|
||||
"""保存警告行的新增、更新/合并或跳过决定。"""
|
||||
row = db.session.get(ShippingCustomerImportRow, row_id)
|
||||
if row is None:
|
||||
raise NotFoundError('Customer import row not found', code='SHIPPING.CUSTOMER_IMPORT_ROW_NOT_FOUND')
|
||||
if row.batch.status == 'published':
|
||||
raise ConflictError('Published import rows cannot be changed', code='SHIPPING.CUSTOMER_IMPORT_ALREADY_PUBLISHED')
|
||||
if row.validation_status == 'error':
|
||||
raise ValidationError(
|
||||
'Rows with validation errors cannot be decided',
|
||||
code='SHIPPING.CUSTOMER_IMPORT_HAS_ERRORS',
|
||||
details={'row_id': row.id},
|
||||
)
|
||||
action = clean_text(data.get('action')).lower()
|
||||
if action not in ROW_DECISIONS:
|
||||
raise ValidationError('Invalid import row decision', code='SHIPPING.CUSTOMER_IMPORT_DECISION_INVALID')
|
||||
target_id = data.get('target_customer_id')
|
||||
if row.row_type == 'identifier' and action not in {'create', 'skip'}:
|
||||
raise ValidationError(
|
||||
'Identifier warning rows only support create or skip',
|
||||
code='SHIPPING.CUSTOMER_IMPORT_DECISION_INVALID',
|
||||
)
|
||||
if row.row_type == 'customer' and action in {'update', 'merge'}:
|
||||
try:
|
||||
target_id = int(target_id)
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise ValidationError('Target customer is required', code='SHIPPING.CUSTOMER_IMPORT_TARGET_REQUIRED') from exc
|
||||
if db.session.get(ShippingCustomer, target_id) is None:
|
||||
raise NotFoundError('Target customer not found', code='SHIPPING.CUSTOMER_NOT_FOUND')
|
||||
else:
|
||||
target_id = None
|
||||
row.decision_action = action
|
||||
row.target_customer_id = target_id
|
||||
row.decision_note = clean_text(data.get('note')) or None
|
||||
db.session.commit()
|
||||
return serialize_import_row(row)
|
||||
|
||||
|
||||
def _effective_action(row: ShippingCustomerImportRow) -> str:
|
||||
"""返回发布时实际动作;警告行必须显式决策。"""
|
||||
if row.validation_status == 'error':
|
||||
return ''
|
||||
if row.validation_status == 'warning':
|
||||
return clean_text(row.decision_action).lower()
|
||||
return clean_text(row.decision_action or row.suggested_action).lower()
|
||||
|
||||
|
||||
def _upsert_external_ref(customer_id: int, *, source_system: str, legacy_key: str) -> None:
|
||||
"""创建或校验客户外部来源键;禁止同一来源键静默改绑。"""
|
||||
existing = db.session.query(ShippingCustomerExternalRef).filter_by(
|
||||
source_system=source_system,
|
||||
legacy_customer_key=legacy_key,
|
||||
).first()
|
||||
if existing:
|
||||
if existing.customer_id != customer_id:
|
||||
raise ConflictError(
|
||||
'Customer external reference is already bound',
|
||||
code='SHIPPING.CUSTOMER_EXTERNAL_REF_CONFLICT',
|
||||
)
|
||||
return
|
||||
db.session.add(ShippingCustomerExternalRef(
|
||||
customer_id=customer_id,
|
||||
source_system=source_system,
|
||||
legacy_customer_key=legacy_key,
|
||||
))
|
||||
|
||||
|
||||
def publish_import_batch(batch_id: int, *, actor_id: int | None) -> dict[str, Any]:
|
||||
"""
|
||||
单事务发布已预检的客户导入批次。
|
||||
|
||||
Raises:
|
||||
ValidationError: 存在错误行或未决警告。
|
||||
ConflictError: 批次已发布或发布时唯一约束冲突。
|
||||
"""
|
||||
batch = (
|
||||
db.session.query(ShippingCustomerImportBatch)
|
||||
.filter(ShippingCustomerImportBatch.id == batch_id)
|
||||
.with_for_update()
|
||||
.one_or_none()
|
||||
)
|
||||
if batch is None:
|
||||
raise NotFoundError('Customer import batch not found', code='SHIPPING.CUSTOMER_IMPORT_NOT_FOUND')
|
||||
if batch.status == 'published':
|
||||
result = serialize_import_batch(batch)
|
||||
result['idempotent_replay'] = True
|
||||
return result
|
||||
if any(row.validation_status == 'error' for row in batch.rows):
|
||||
raise ValidationError(
|
||||
'Customer import contains blocking errors',
|
||||
code='SHIPPING.CUSTOMER_IMPORT_HAS_ERRORS',
|
||||
details={'error_rows': batch.error_rows},
|
||||
)
|
||||
unresolved = [row.id for row in batch.rows if row.validation_status == 'warning' and not row.decision_action]
|
||||
if unresolved:
|
||||
raise ValidationError(
|
||||
'Customer import warnings require decisions',
|
||||
code='SHIPPING.CUSTOMER_IMPORT_DECISIONS_REQUIRED',
|
||||
details={'row_ids': unresolved},
|
||||
)
|
||||
customer_by_key: dict[tuple[str, str], ShippingCustomer] = {}
|
||||
published = 0
|
||||
try:
|
||||
# [STEP 1] 先发布客户行并建立外部来源键,供 identifiers Sheet 稳定关联。
|
||||
for row in [item for item in batch.rows if item.row_type == 'customer']:
|
||||
action = _effective_action(row)
|
||||
if action == 'skip':
|
||||
row.result_status = 'skipped'
|
||||
row.result_message = 'Skipped by administrator'
|
||||
continue
|
||||
data = row.normalized_json or {}
|
||||
target: ShippingCustomer | None = None
|
||||
if action in {'update', 'merge'}:
|
||||
target = db.session.get(ShippingCustomer, row.target_customer_id)
|
||||
if target is None:
|
||||
raise NotFoundError('Target customer not found', code='SHIPPING.CUSTOMER_NOT_FOUND')
|
||||
if action == 'update':
|
||||
target.standard_name = data['standard_name']
|
||||
target.short_code = data['short_code']
|
||||
target.status = data['status']
|
||||
target.remark = data.get('remark') or None
|
||||
target.updated_by_id = actor_id
|
||||
elif action == 'create':
|
||||
target = ShippingCustomer(
|
||||
standard_name=data['standard_name'],
|
||||
short_code=data['short_code'],
|
||||
status=data['status'],
|
||||
remark=data.get('remark') or None,
|
||||
created_by_id=actor_id,
|
||||
updated_by_id=actor_id,
|
||||
)
|
||||
db.session.add(target)
|
||||
db.session.flush()
|
||||
else:
|
||||
raise ValidationError('Invalid import action', code='SHIPPING.CUSTOMER_IMPORT_DECISION_INVALID')
|
||||
_upsert_external_ref(
|
||||
target.id,
|
||||
source_system=data['source_system'],
|
||||
legacy_key=data['legacy_customer_key'],
|
||||
)
|
||||
customer_by_key[(data['source_system'], data['legacy_customer_key'])] = target
|
||||
row.result_customer_id = target.id
|
||||
row.result_status = 'published'
|
||||
row.result_message = action
|
||||
published += 1
|
||||
|
||||
# [STEP 2] 标识行只绑定已发布/既有客户;导入标识默认 approved,保留 source=imported。
|
||||
for row in [item for item in batch.rows if item.row_type == 'identifier']:
|
||||
action = _effective_action(row)
|
||||
if action == 'skip':
|
||||
row.result_status = 'skipped'
|
||||
row.result_message = 'Skipped by administrator'
|
||||
continue
|
||||
data = row.normalized_json or {}
|
||||
source_system = data.get('source_system') or batch.source_system
|
||||
customer = customer_by_key.get((source_system, data.get('legacy_customer_key')))
|
||||
if customer is None:
|
||||
ref = db.session.query(ShippingCustomerExternalRef).filter_by(
|
||||
source_system=source_system,
|
||||
legacy_customer_key=data.get('legacy_customer_key'),
|
||||
).first()
|
||||
customer = db.session.get(ShippingCustomer, ref.customer_id) if ref else None
|
||||
if customer is None:
|
||||
raise ConflictError(
|
||||
'Identifier customer mapping is missing',
|
||||
code='SHIPPING.CUSTOMER_IMPORT_IDENTIFIER_CUSTOMER_MISSING',
|
||||
)
|
||||
existing_identifier = db.session.query(ShippingCustomerIdentifier).filter_by(
|
||||
customer_id=customer.id,
|
||||
identifier_type=data['identifier_type'],
|
||||
normalized_value=data['normalized_value'],
|
||||
).first()
|
||||
if existing_identifier is None:
|
||||
db.session.add(ShippingCustomerIdentifier(
|
||||
customer_id=customer.id,
|
||||
identifier_type=data['identifier_type'],
|
||||
raw_value=data['identifier_value'],
|
||||
normalized_value=data['normalized_value'],
|
||||
auto_match_allowed=bool(data.get('auto_match_allowed')),
|
||||
status='approved',
|
||||
source='imported',
|
||||
remark=data.get('remark') or None,
|
||||
confirmed_by_id=actor_id,
|
||||
confirmed_at=datetime.utcnow(),
|
||||
))
|
||||
row.result_customer_id = customer.id
|
||||
row.result_status = 'published'
|
||||
row.result_message = 'identifier_created' if existing_identifier is None else 'identifier_exists'
|
||||
published += 1
|
||||
batch.status = 'published'
|
||||
batch.published_rows = published
|
||||
batch.published_by_id = actor_id
|
||||
batch.published_at = datetime.utcnow()
|
||||
db.session.commit()
|
||||
except AppError:
|
||||
db.session.rollback()
|
||||
raise
|
||||
except (IntegrityError, ValueError) as exc:
|
||||
db.session.rollback()
|
||||
raise ConflictError(
|
||||
'Customer import publish conflict',
|
||||
code='SHIPPING.CUSTOMER_IMPORT_PUBLISH_CONFLICT',
|
||||
) from exc
|
||||
except Exception:
|
||||
db.session.rollback()
|
||||
raise
|
||||
return serialize_import_batch(batch)
|
||||
|
||||
|
||||
def build_reconciliation_csv(batch_id: int) -> tuple[bytes, str]:
|
||||
"""从持久化导入行生成可重复下载的 UTF-8 BOM 对账 CSV。"""
|
||||
batch = db.session.get(ShippingCustomerImportBatch, batch_id)
|
||||
if batch is None:
|
||||
raise NotFoundError('Customer import batch not found', code='SHIPPING.CUSTOMER_IMPORT_NOT_FOUND')
|
||||
output = io.StringIO(newline='')
|
||||
writer = csv.writer(output)
|
||||
writer.writerow([
|
||||
'sheet_name', 'row_no', 'legacy_customer_key', 'validation_status', 'decision_action',
|
||||
'result_status', 'result_customer_id', 'result_message', 'errors', 'warnings',
|
||||
])
|
||||
for row in batch.rows:
|
||||
writer.writerow([
|
||||
row.sheet_name,
|
||||
row.row_no,
|
||||
row.legacy_customer_key or '',
|
||||
row.validation_status,
|
||||
row.decision_action or row.suggested_action or '',
|
||||
row.result_status or '',
|
||||
row.result_customer_id or '',
|
||||
row.result_message or '',
|
||||
';'.join(str(item.get('code') or item) for item in (row.errors_json or [])),
|
||||
';'.join(str(item.get('code') or item) for item in (row.warnings_json or [])),
|
||||
])
|
||||
return ('\ufeff' + output.getvalue()).encode('utf-8'), f'{batch.batch_no}_reconciliation.csv'
|
||||
@@ -0,0 +1,342 @@
|
||||
"""
|
||||
services/admin/shipping_customer_service.py
|
||||
|
||||
用途:管理货代标准客户与已审核识别证据。
|
||||
依赖:db、ShippingCustomer* 模型、customer_normalization、统一 AppError。
|
||||
逻辑:管理 API 委托本服务完成校验、唯一性检查、停用与序列化;不承载运行期客户裁决。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
|
||||
from sqlalchemy import asc, desc, func, or_
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
|
||||
from app import db
|
||||
from app.core.errors import ConflictError, NotFoundError, ValidationError
|
||||
from app.models import ShippingCase, ShippingCustomer, ShippingCustomerIdentifier
|
||||
from app.services.shipping_notice.customer_normalization import (
|
||||
clean_text,
|
||||
is_public_email_domain,
|
||||
normalize_identifier,
|
||||
normalize_short_code,
|
||||
)
|
||||
|
||||
CUSTOMER_STATUSES = frozenset({'active', 'inactive'})
|
||||
IDENTIFIER_STATUSES = frozenset({'pending', 'approved', 'disabled'})
|
||||
|
||||
|
||||
def _strict_bool(value: Any, *, field: str) -> bool:
|
||||
"""只接受 JSON 布尔值,避免字符串 ``false`` 被 Python 判定为真。"""
|
||||
if isinstance(value, bool):
|
||||
return value
|
||||
if value is None:
|
||||
return False
|
||||
raise ValidationError(
|
||||
f'{field} must be a boolean',
|
||||
code='VALIDATION.INVALID_PARAM',
|
||||
details={'field': field},
|
||||
)
|
||||
|
||||
|
||||
def serialize_identifier(record: ShippingCustomerIdentifier) -> dict[str, Any]:
|
||||
"""序列化客户识别证据,供管理后台列表与详情共用。"""
|
||||
return {
|
||||
'id': record.id,
|
||||
'customer_id': record.customer_id,
|
||||
'identifier_type': record.identifier_type,
|
||||
'raw_value': record.raw_value,
|
||||
'normalized_value': record.normalized_value,
|
||||
'auto_match_allowed': bool(record.auto_match_allowed),
|
||||
'status': record.status,
|
||||
'source': record.source,
|
||||
'remark': record.remark,
|
||||
'confirmed_by_id': record.confirmed_by_id,
|
||||
'confirmed_at': record.confirmed_at.isoformat() if record.confirmed_at else None,
|
||||
'created_at': record.created_at.isoformat() if record.created_at else None,
|
||||
'updated_at': record.updated_at.isoformat() if record.updated_at else None,
|
||||
}
|
||||
|
||||
|
||||
def serialize_customer(
|
||||
record: ShippingCustomer,
|
||||
*,
|
||||
include_identifiers: bool = False,
|
||||
case_count: int | None = None,
|
||||
identifier_count: int | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
序列化标准客户,并可选附带识别证据和业务引用数量。
|
||||
|
||||
Args:
|
||||
record: 标准客户 ORM 记录。
|
||||
include_identifiers: 是否附带识别证据明细。
|
||||
case_count: 列表查询预聚合的业务单数量;为空时现场查询。
|
||||
identifier_count: 列表查询预聚合的识别证据数量;为空时现场查询。
|
||||
Returns:
|
||||
管理端客户 JSON 字典。
|
||||
"""
|
||||
payload: dict[str, Any] = {
|
||||
'id': record.id,
|
||||
'standard_name': record.standard_name,
|
||||
'short_code': record.short_code,
|
||||
'status': record.status,
|
||||
'remark': record.remark,
|
||||
'created_by_id': record.created_by_id,
|
||||
'updated_by_id': record.updated_by_id,
|
||||
'created_at': record.created_at.isoformat() if record.created_at else None,
|
||||
'updated_at': record.updated_at.isoformat() if record.updated_at else None,
|
||||
'case_count': case_count if case_count is not None else db.session.query(ShippingCase.id).filter_by(customer_id=record.id).count(),
|
||||
'identifier_count': identifier_count if identifier_count is not None else db.session.query(ShippingCustomerIdentifier.id).filter_by(customer_id=record.id).count(),
|
||||
}
|
||||
if include_identifiers:
|
||||
payload['identifiers'] = [serialize_identifier(item) for item in record.identifiers]
|
||||
return payload
|
||||
|
||||
|
||||
def list_customers(params: dict[str, Any]) -> dict[str, Any]:
|
||||
"""
|
||||
分页列出标准客户。
|
||||
|
||||
Args:
|
||||
params: 支持 q/status/page/page_size/sort/order。
|
||||
Returns:
|
||||
items、total、page、page_size、pages。
|
||||
"""
|
||||
case_counts = (
|
||||
db.session.query(ShippingCase.customer_id.label('customer_id'), func.count(ShippingCase.id).label('case_count'))
|
||||
.group_by(ShippingCase.customer_id)
|
||||
.subquery()
|
||||
)
|
||||
identifier_counts = (
|
||||
db.session.query(
|
||||
ShippingCustomerIdentifier.customer_id.label('customer_id'),
|
||||
func.count(ShippingCustomerIdentifier.id).label('identifier_count'),
|
||||
)
|
||||
.group_by(ShippingCustomerIdentifier.customer_id)
|
||||
.subquery()
|
||||
)
|
||||
query = (
|
||||
db.session.query(
|
||||
ShippingCustomer,
|
||||
func.coalesce(case_counts.c.case_count, 0),
|
||||
func.coalesce(identifier_counts.c.identifier_count, 0),
|
||||
)
|
||||
.outerjoin(case_counts, case_counts.c.customer_id == ShippingCustomer.id)
|
||||
.outerjoin(identifier_counts, identifier_counts.c.customer_id == ShippingCustomer.id)
|
||||
)
|
||||
keyword = clean_text(params.get('q'))
|
||||
status = clean_text(params.get('status')).lower()
|
||||
if keyword:
|
||||
like = f'%{keyword}%'
|
||||
query = query.filter(or_(ShippingCustomer.standard_name.ilike(like), ShippingCustomer.short_code.ilike(like)))
|
||||
if status:
|
||||
if status not in CUSTOMER_STATUSES:
|
||||
raise ValidationError('Invalid customer status', code='SHIPPING.CUSTOMER_STATUS_INVALID')
|
||||
query = query.filter(ShippingCustomer.status == status)
|
||||
try:
|
||||
page = max(1, int(params.get('page') or 1))
|
||||
page_size = min(100, max(1, int(params.get('page_size') or 20)))
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise ValidationError('Invalid pagination') from exc
|
||||
sort_map = {
|
||||
'standard_name': ShippingCustomer.standard_name,
|
||||
'short_code': ShippingCustomer.short_code,
|
||||
'created_at': ShippingCustomer.created_at,
|
||||
'updated_at': ShippingCustomer.updated_at,
|
||||
}
|
||||
sort_col = sort_map.get(clean_text(params.get('sort')).lower(), ShippingCustomer.updated_at)
|
||||
order = asc if clean_text(params.get('order')).lower() == 'asc' else desc
|
||||
total = query.count()
|
||||
items = query.order_by(order(sort_col), ShippingCustomer.id.desc()).offset((page - 1) * page_size).limit(page_size).all()
|
||||
return {
|
||||
'items': [
|
||||
serialize_customer(customer, case_count=int(case_count), identifier_count=int(identifier_count))
|
||||
for customer, case_count, identifier_count in items
|
||||
],
|
||||
'total': total,
|
||||
'page': page,
|
||||
'page_size': page_size,
|
||||
'pages': max(1, (total + page_size - 1) // page_size),
|
||||
}
|
||||
|
||||
|
||||
def get_customer(customer_id: int) -> dict[str, Any]:
|
||||
"""读取客户详情;不存在时抛出统一 NotFoundError。"""
|
||||
record = db.session.get(ShippingCustomer, customer_id)
|
||||
if record is None:
|
||||
raise NotFoundError('Customer not found', code='SHIPPING.CUSTOMER_NOT_FOUND')
|
||||
return serialize_customer(record, include_identifiers=True)
|
||||
|
||||
|
||||
def _assert_short_code_available(short_code: str, *, exclude_customer_id: int | None = None) -> None:
|
||||
"""校验客户简码全局唯一。"""
|
||||
query = db.session.query(ShippingCustomer.id).filter(ShippingCustomer.short_code == short_code)
|
||||
if exclude_customer_id is not None:
|
||||
query = query.filter(ShippingCustomer.id != exclude_customer_id)
|
||||
if query.first():
|
||||
raise ConflictError(
|
||||
'Customer short code already exists',
|
||||
code='SHIPPING.CUSTOMER_SHORT_CODE_EXISTS',
|
||||
details={'short_code': short_code},
|
||||
)
|
||||
|
||||
|
||||
def create_customer(data: dict[str, Any], *, actor_id: int | None) -> dict[str, Any]:
|
||||
"""
|
||||
创建标准客户。
|
||||
|
||||
Args:
|
||||
data: standard_name、short_code、status、remark。
|
||||
actor_id: 当前管理员 ID。
|
||||
Returns:
|
||||
新客户详情。
|
||||
"""
|
||||
standard_name = clean_text(data.get('standard_name'))
|
||||
if not standard_name:
|
||||
raise ValidationError(
|
||||
'Customer standard name is required',
|
||||
code='SHIPPING.CUSTOMER_NAME_REQUIRED',
|
||||
details={'field': 'standard_name'},
|
||||
)
|
||||
short_code = normalize_short_code(data.get('short_code'))
|
||||
_assert_short_code_available(short_code)
|
||||
status = clean_text(data.get('status') or 'active').lower()
|
||||
if status not in CUSTOMER_STATUSES:
|
||||
raise ValidationError('Invalid customer status', code='SHIPPING.CUSTOMER_STATUS_INVALID')
|
||||
record = ShippingCustomer(
|
||||
standard_name=standard_name,
|
||||
short_code=short_code,
|
||||
status=status,
|
||||
remark=clean_text(data.get('remark')) or None,
|
||||
created_by_id=actor_id,
|
||||
updated_by_id=actor_id,
|
||||
)
|
||||
db.session.add(record)
|
||||
try:
|
||||
db.session.commit()
|
||||
except IntegrityError as exc:
|
||||
db.session.rollback()
|
||||
raise ConflictError('Customer already exists', code='SHIPPING.CUSTOMER_CONFLICT') from exc
|
||||
return serialize_customer(record, include_identifiers=True)
|
||||
|
||||
|
||||
def update_customer(customer_id: int, data: dict[str, Any], *, actor_id: int | None) -> dict[str, Any]:
|
||||
"""更新标准客户;历史业务号使用快照,不受简码修改影响。"""
|
||||
record = db.session.get(ShippingCustomer, customer_id)
|
||||
if record is None:
|
||||
raise NotFoundError('Customer not found', code='SHIPPING.CUSTOMER_NOT_FOUND')
|
||||
if 'standard_name' in data:
|
||||
name = clean_text(data.get('standard_name'))
|
||||
if not name:
|
||||
raise ValidationError('Customer standard name is required', code='SHIPPING.CUSTOMER_NAME_REQUIRED')
|
||||
record.standard_name = name
|
||||
if 'short_code' in data:
|
||||
short_code = normalize_short_code(data.get('short_code'))
|
||||
_assert_short_code_available(short_code, exclude_customer_id=customer_id)
|
||||
record.short_code = short_code
|
||||
if 'status' in data:
|
||||
status = clean_text(data.get('status')).lower()
|
||||
if status not in CUSTOMER_STATUSES:
|
||||
raise ValidationError('Invalid customer status', code='SHIPPING.CUSTOMER_STATUS_INVALID')
|
||||
record.status = status
|
||||
if 'remark' in data:
|
||||
record.remark = clean_text(data.get('remark')) or None
|
||||
record.updated_by_id = actor_id
|
||||
try:
|
||||
db.session.commit()
|
||||
except IntegrityError as exc:
|
||||
db.session.rollback()
|
||||
raise ConflictError('Customer update conflict', code='SHIPPING.CUSTOMER_CONFLICT') from exc
|
||||
return serialize_customer(record, include_identifiers=True)
|
||||
|
||||
|
||||
def deactivate_customer(customer_id: int, *, actor_id: int | None) -> dict[str, Any]:
|
||||
"""停用客户;不物理删除,以保留业务单和识别审计。"""
|
||||
return update_customer(customer_id, {'status': 'inactive'}, actor_id=actor_id)
|
||||
|
||||
|
||||
def create_identifier(customer_id: int, data: dict[str, Any], *, actor_id: int | None) -> dict[str, Any]:
|
||||
"""
|
||||
新增客户识别证据。
|
||||
|
||||
核心逻辑:公共邮箱域名不得开启自动匹配;approved 状态写入审核人和时间。
|
||||
"""
|
||||
customer = db.session.get(ShippingCustomer, customer_id)
|
||||
if customer is None:
|
||||
raise NotFoundError('Customer not found', code='SHIPPING.CUSTOMER_NOT_FOUND')
|
||||
identifier_type = clean_text(data.get('identifier_type')).lower()
|
||||
raw_value = clean_text(data.get('raw_value') or data.get('identifier_value'))
|
||||
normalized_value = normalize_identifier(identifier_type, raw_value)
|
||||
status = clean_text(data.get('status') or 'pending').lower()
|
||||
if status not in IDENTIFIER_STATUSES:
|
||||
raise ValidationError('Invalid identifier status', code='SHIPPING.CUSTOMER_IDENTIFIER_STATUS_INVALID')
|
||||
auto_match_allowed = _strict_bool(data.get('auto_match_allowed'), field='auto_match_allowed')
|
||||
if identifier_type in {'domain', 'email'} and is_public_email_domain(normalized_value) and auto_match_allowed:
|
||||
raise ValidationError(
|
||||
'Public email domains cannot be used for automatic matching',
|
||||
code='SHIPPING.CUSTOMER_PUBLIC_DOMAIN_AUTO_MATCH_FORBIDDEN',
|
||||
)
|
||||
if status != 'approved' and auto_match_allowed:
|
||||
raise ValidationError(
|
||||
'Only approved identifiers can enable automatic matching',
|
||||
code='SHIPPING.CUSTOMER_IDENTIFIER_NOT_APPROVED',
|
||||
)
|
||||
record = ShippingCustomerIdentifier(
|
||||
customer_id=customer.id,
|
||||
identifier_type=identifier_type,
|
||||
raw_value=raw_value,
|
||||
normalized_value=normalized_value,
|
||||
auto_match_allowed=auto_match_allowed,
|
||||
status=status,
|
||||
source=clean_text(data.get('source') or 'manual').lower(),
|
||||
remark=clean_text(data.get('remark')) or None,
|
||||
confirmed_by_id=actor_id if status == 'approved' else None,
|
||||
confirmed_at=datetime.utcnow() if status == 'approved' else None,
|
||||
)
|
||||
db.session.add(record)
|
||||
try:
|
||||
db.session.commit()
|
||||
except IntegrityError as exc:
|
||||
db.session.rollback()
|
||||
raise ConflictError(
|
||||
'Customer identifier already exists',
|
||||
code='SHIPPING.CUSTOMER_IDENTIFIER_EXISTS',
|
||||
) from exc
|
||||
return serialize_identifier(record)
|
||||
|
||||
|
||||
def update_identifier(identifier_id: int, data: dict[str, Any], *, actor_id: int | None) -> dict[str, Any]:
|
||||
"""更新识别证据;先校验最终状态,再一次性修改 ORM,避免失败后残留脏状态。"""
|
||||
record = db.session.get(ShippingCustomerIdentifier, identifier_id)
|
||||
if record is None:
|
||||
raise NotFoundError('Customer identifier not found', code='SHIPPING.CUSTOMER_IDENTIFIER_NOT_FOUND')
|
||||
next_status = record.status
|
||||
if 'status' in data:
|
||||
next_status = clean_text(data.get('status')).lower()
|
||||
if next_status not in IDENTIFIER_STATUSES:
|
||||
raise ValidationError('Invalid identifier status', code='SHIPPING.CUSTOMER_IDENTIFIER_STATUS_INVALID')
|
||||
next_allowed = record.auto_match_allowed if next_status == 'approved' else False
|
||||
if 'auto_match_allowed' in data:
|
||||
next_allowed = _strict_bool(data.get('auto_match_allowed'), field='auto_match_allowed')
|
||||
if record.identifier_type in {'domain', 'email'} and is_public_email_domain(record.normalized_value) and next_allowed:
|
||||
raise ValidationError(
|
||||
'Public email domains cannot be used for automatic matching',
|
||||
code='SHIPPING.CUSTOMER_PUBLIC_DOMAIN_AUTO_MATCH_FORBIDDEN',
|
||||
)
|
||||
if next_status != 'approved' and next_allowed:
|
||||
raise ValidationError(
|
||||
'Only approved identifiers can enable automatic matching',
|
||||
code='SHIPPING.CUSTOMER_IDENTIFIER_NOT_APPROVED',
|
||||
)
|
||||
record.status = next_status
|
||||
record.auto_match_allowed = next_allowed
|
||||
if next_status == 'approved' and record.confirmed_at is None:
|
||||
record.confirmed_by_id = actor_id
|
||||
record.confirmed_at = datetime.utcnow()
|
||||
if 'remark' in data:
|
||||
record.remark = clean_text(data.get('remark')) or None
|
||||
db.session.commit()
|
||||
return serialize_identifier(record)
|
||||
@@ -70,5 +70,5 @@ class AgentHandler:
|
||||
ctx: ChatStreamContext,
|
||||
event_data: dict[str, Any],
|
||||
) -> Iterator[str]:
|
||||
"""上游 message_end/workflow_finished 后追加的 SSE 行。"""
|
||||
"""上游 error/message_end/workflow_finished 后执行领域收口并追加 SSE 行。"""
|
||||
return iter(())
|
||||
@@ -1,9 +1,10 @@
|
||||
"""
|
||||
backend/app/services/agent_registry/handlers/shipping_notice.py
|
||||
|
||||
用途:货代发货通知 Hybrid Handler — 聊天流 UI State 与上下文准备。
|
||||
依赖:shipping_notice.query_service、ui_state、agent_registry.handlers.registry。
|
||||
逻辑:SSE relay 调用 build_ui_state_event;不替代 Dify 正文生成。
|
||||
用途:货代发货通知 Hybrid Handler — 聊天流订单抽取生命周期、UI State 与上下文准备。
|
||||
依赖:shipping_notice.order_extraction/query_service、chat.log_service、ui_state、agent_registry.handlers.registry。
|
||||
逻辑:Dify 请求前登记并推送订单抽取状态,terminal/error 后收口、持久化结果并补发 Batch UI State;
|
||||
不替代 Dify 正文生成。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -38,41 +39,148 @@ class ShippingNoticeHandler(AgentHandler):
|
||||
"""
|
||||
货代发货通知业务 Handler。
|
||||
|
||||
核心逻辑:按 adapter_hints / 请求 task_id、batch_no 构造 shipping_ui_state 事件供前端渲染步骤与按钮。
|
||||
核心逻辑:订单抽取请求进入 Dify 前登记 request/intakes 并推送 extracting;终态时先落失败、
|
||||
推送并持久化抽取结果,再按 adapter_hints / task_id / batch_no 构造 shipping_ui_state。
|
||||
阶段约束:`open_existing` 终态必须能为前端提供恢复锚点;最小字段是 `task_no`,若已知批次则补
|
||||
`batch_no`,若已构造快照则补 `ui_state / batch_ui_state`,供实时消息与历史回放共用。
|
||||
"""
|
||||
|
||||
def build_ui_state_event(self, ctx: ChatStreamContext) -> dict[str, Any] | None:
|
||||
@staticmethod
|
||||
def _shipping_hints(ctx: ChatStreamContext) -> dict[str, Any]:
|
||||
"""读取 shipping adapter_hints,非法或缺失时返回空字典。"""
|
||||
hints = ctx.adapter_hints if isinstance(ctx.adapter_hints, dict) else {}
|
||||
shipping_hints = hints.get('shipping_notice')
|
||||
return shipping_hints if isinstance(shipping_hints, dict) else {}
|
||||
|
||||
@classmethod
|
||||
def _order_extraction_intake_nos(cls, ctx: ChatStreamContext) -> list[str]:
|
||||
"""仅在能力与契约均匹配时返回本轮 Intake 集合,避免普通续办误触抽取收口。"""
|
||||
hints = cls._shipping_hints(ctx)
|
||||
if (
|
||||
str(hints.get('capability') or '') != 'order_extraction'
|
||||
or str(hints.get('contract_version') or '') != 'shipping-order-extraction-v1'
|
||||
or not isinstance(hints.get('intake_nos'), list)
|
||||
):
|
||||
return []
|
||||
return sorted({
|
||||
str(item or '').strip().upper()
|
||||
for item in hints.get('intake_nos') or []
|
||||
if str(item or '').strip()
|
||||
})
|
||||
|
||||
@staticmethod
|
||||
def _workflow_failure_message(event_data: dict[str, Any]) -> str:
|
||||
"""从 Dify terminal/error 事件提取已友好化的错误文本,缺失时返回空字符串。"""
|
||||
event_name = str(event_data.get('event') or '').strip()
|
||||
data = event_data.get('data') if isinstance(event_data.get('data'), dict) else {}
|
||||
failed = event_name == 'error' or (
|
||||
event_name == 'workflow_finished'
|
||||
and str(data.get('status') or '').strip().lower() == 'failed'
|
||||
)
|
||||
if not failed:
|
||||
return ''
|
||||
for value in (
|
||||
event_data.get('message'),
|
||||
event_data.get('error'),
|
||||
event_data.get('description'),
|
||||
data.get('message'),
|
||||
data.get('error'),
|
||||
data.get('description'),
|
||||
):
|
||||
text = str(value or '').strip()
|
||||
if text:
|
||||
return text
|
||||
return '订单识别失败,请重新发送当前邮件。'
|
||||
|
||||
def prepare_stream(self, ctx: ChatStreamContext) -> ChatStreamContext:
|
||||
"""
|
||||
在订单抽取请求进入 Dify 前登记权威 extracting 状态。
|
||||
|
||||
核心逻辑:仅消费平台 adapter_hints 中的固定能力契约,并把 HXOPS request_id 绑定到完整 Intake 集合;
|
||||
失败直接阻止上游调用,避免前端显示本地 extracting 而后端仍为 not_started。
|
||||
"""
|
||||
intake_nos = self._order_extraction_intake_nos(ctx)
|
||||
if not intake_nos:
|
||||
return ctx
|
||||
from app.services.shipping_notice.order_extraction import start_order_extraction
|
||||
|
||||
start_order_extraction(
|
||||
user_id=int(getattr(ctx.user, 'id', 0) or 0),
|
||||
session_id=str(getattr(ctx.session, 'session_id', '') or ''),
|
||||
intake_nos=intake_nos,
|
||||
request_id=ctx.request_id,
|
||||
)
|
||||
return ctx
|
||||
|
||||
def build_ui_state_event(
|
||||
self,
|
||||
ctx: ChatStreamContext,
|
||||
*,
|
||||
resolve_order_extraction: bool = False,
|
||||
) -> dict[str, Any] | None:
|
||||
"""
|
||||
构造 shipping_ui_state SSE 事件。
|
||||
|
||||
核心逻辑:优先显式 task_id,其次 batch 焦点任务;失败时记录日志并返回 None。
|
||||
用途:为聊天页当前消息与历史回放提供任务/批次恢复锚点。
|
||||
核心逻辑:优先显式 task_id,其次 batch 焦点任务;订单抽取终态可按 intake 反查新建批次或
|
||||
`open_existing` 命中的既有任务。`open_existing` 场景下即使没有新建批次,也必须至少返回
|
||||
`task_no`;失败时记录日志并返回 None。
|
||||
"""
|
||||
if not _uses_shipping_ui_state_progress(ctx.agent):
|
||||
return None
|
||||
|
||||
task_id = str(ctx.shipping_task_id or '').strip()
|
||||
batch_no = str(ctx.shipping_batch_no or '').strip()
|
||||
shipping_hints = self._shipping_hints(ctx)
|
||||
if not task_id and not batch_no:
|
||||
hints = ctx.adapter_hints if isinstance(ctx.adapter_hints, dict) else {}
|
||||
shipping_hints = hints.get('shipping_notice') if isinstance(hints.get('shipping_notice'), dict) else {}
|
||||
task_id = str(shipping_hints.get('task_id') or '').strip()
|
||||
batch_no = str(shipping_hints.get('batch_no') or '').strip()
|
||||
if not task_id and not batch_no:
|
||||
intake_nos = self._order_extraction_intake_nos(ctx)
|
||||
if not task_id and not batch_no and not (resolve_order_extraction and intake_nos):
|
||||
return None
|
||||
|
||||
try:
|
||||
from app.services.shipping_notice.query_service import get_batch_by_no, get_task_by_ref
|
||||
from app.services.shipping_notice.query_service import (
|
||||
get_batch_by_no,
|
||||
get_task_by_ref,
|
||||
resolve_order_extraction_ui_target,
|
||||
)
|
||||
from app.services.shipping_notice.ui_state import build_batch_ui_state, build_task_ui_state
|
||||
|
||||
task = get_task_by_ref(task_id) if task_id else None
|
||||
batch = get_batch_by_no(batch_no) if batch_no else None
|
||||
resolved_from_order_extraction = False
|
||||
if task is None and batch is None and resolve_order_extraction and intake_nos:
|
||||
batch, task = resolve_order_extraction_ui_target(
|
||||
user_id=int(getattr(ctx.user, 'id', 0) or 0),
|
||||
conversation_id=str(getattr(ctx.session, 'session_id', '') or ''),
|
||||
intake_nos=intake_nos,
|
||||
)
|
||||
resolved_from_order_extraction = batch is not None or task is not None
|
||||
session_id = str(getattr(ctx.session, 'session_id', '') or '')
|
||||
if resolved_from_order_extraction and batch is not None:
|
||||
batch_ui_state = build_batch_ui_state(batch)
|
||||
focus_task = batch_ui_state.get('focus_task') if isinstance(batch_ui_state.get('focus_task'), dict) else {}
|
||||
focus_ui_state = (
|
||||
batch_ui_state.get('focus_task_ui_state')
|
||||
if isinstance(batch_ui_state.get('focus_task_ui_state'), dict)
|
||||
else None
|
||||
)
|
||||
return {
|
||||
'event': 'shipping_ui_state',
|
||||
'conversation_id': session_id,
|
||||
'batch_no': batch.batch_no,
|
||||
'task_no': focus_task.get('task_no'),
|
||||
'batch_ui_state': batch_ui_state,
|
||||
**({'ui_state': focus_ui_state} if focus_ui_state is not None else {}),
|
||||
'source': 'order_extraction',
|
||||
}
|
||||
if task is None and batch is not None:
|
||||
focus_task_no = str(batch.current_focus_task_no or '').strip()
|
||||
if focus_task_no:
|
||||
candidate = get_task_by_ref(focus_task_no)
|
||||
if candidate is not None and candidate.batch_id == batch.id:
|
||||
task = candidate
|
||||
session_id = str(getattr(ctx.session, 'session_id', '') or '')
|
||||
if task is not None:
|
||||
return {
|
||||
'event': 'shipping_ui_state',
|
||||
@@ -80,13 +188,23 @@ class ShippingNoticeHandler(AgentHandler):
|
||||
'task_no': task.task_no,
|
||||
'batch_no': task.batch.batch_no if task.batch is not None else None,
|
||||
'ui_state': build_task_ui_state(task),
|
||||
**({'source': 'order_extraction'} if resolved_from_order_extraction else {}),
|
||||
}
|
||||
if batch is not None:
|
||||
batch_ui_state = build_batch_ui_state(batch)
|
||||
focus_task = batch_ui_state.get('focus_task') if isinstance(batch_ui_state.get('focus_task'), dict) else {}
|
||||
focus_ui_state = (
|
||||
batch_ui_state.get('focus_task_ui_state')
|
||||
if isinstance(batch_ui_state.get('focus_task_ui_state'), dict)
|
||||
else None
|
||||
)
|
||||
return {
|
||||
'event': 'shipping_ui_state',
|
||||
'conversation_id': session_id,
|
||||
'batch_no': batch.batch_no,
|
||||
'batch_ui_state': build_batch_ui_state(batch),
|
||||
'task_no': focus_task.get('task_no'),
|
||||
'batch_ui_state': batch_ui_state,
|
||||
**({'ui_state': focus_ui_state} if focus_ui_state is not None else {}),
|
||||
}
|
||||
except Exception:
|
||||
if current_app:
|
||||
@@ -98,7 +216,129 @@ class ShippingNoticeHandler(AgentHandler):
|
||||
)
|
||||
return None
|
||||
|
||||
def build_order_extraction_state_event(
|
||||
self,
|
||||
ctx: ChatStreamContext,
|
||||
) -> dict[str, Any] | None:
|
||||
"""
|
||||
构造当前请求的 shipping_order_extraction_state SSE 事件。
|
||||
|
||||
核心逻辑:只为固定订单抽取能力契约读取权威 Intake 状态;身份围栏失败时记录日志并跳过,
|
||||
避免把旧请求或其他会话结果推送到当前消息。
|
||||
|
||||
Args:
|
||||
ctx: 当前聊天流上下文,必须包含用户、会话、request_id 与 Intake 集合。
|
||||
|
||||
Returns:
|
||||
可直接格式化为 SSE 的事件字典;非订单抽取回合或读取失败时返回 None。
|
||||
"""
|
||||
intake_nos = self._order_extraction_intake_nos(ctx)
|
||||
if not intake_nos:
|
||||
return None
|
||||
try:
|
||||
from app.services.shipping_notice.order_extraction import get_order_extraction_state
|
||||
|
||||
state = get_order_extraction_state(
|
||||
user_id=int(getattr(ctx.user, 'id', 0) or 0),
|
||||
session_id=str(getattr(ctx.session, 'session_id', '') or ''),
|
||||
intake_nos=intake_nos,
|
||||
request_id=ctx.request_id,
|
||||
)
|
||||
return {
|
||||
'event': 'shipping_order_extraction_state',
|
||||
'conversation_id': str(getattr(ctx.session, 'session_id', '') or ''),
|
||||
**state,
|
||||
}
|
||||
except Exception:
|
||||
if current_app:
|
||||
current_app.logger.exception(
|
||||
'[shipping-handler] build order extraction state failed request_id=%s intakes=%s',
|
||||
ctx.request_id,
|
||||
intake_nos,
|
||||
)
|
||||
return None
|
||||
|
||||
@staticmethod
|
||||
def _build_history_recovery_payload_patch(
|
||||
*,
|
||||
state_event: dict[str, Any] | None,
|
||||
ui_event: dict[str, Any] | None,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
提取历史回放所需的最小恢复载荷。
|
||||
|
||||
核心逻辑:抽取终态负责统计摘要,UI State 负责任务/批次锚点;两者都存在时合并为同一条
|
||||
ChatLog.payload patch,保证历史消息可直接恢复工作台。
|
||||
"""
|
||||
payload_patch: dict[str, Any] = {}
|
||||
if isinstance(state_event, dict) and state_event.get('terminal') is True:
|
||||
payload_patch['shipping_order_extraction_state'] = {
|
||||
key: value
|
||||
for key, value in state_event.items()
|
||||
if key not in {'event', 'conversation_id'}
|
||||
}
|
||||
if isinstance(ui_event, dict) and str(ui_event.get('event') or '') == 'shipping_ui_state':
|
||||
task_no = str(ui_event.get('task_no') or '').strip()
|
||||
if task_no:
|
||||
payload_patch['task_no'] = task_no
|
||||
if 'batch_no' in ui_event:
|
||||
batch_no = str(ui_event.get('batch_no') or '').strip()
|
||||
payload_patch['batch_no'] = batch_no or None
|
||||
ui_state = ui_event.get('ui_state')
|
||||
if isinstance(ui_state, dict):
|
||||
payload_patch['shipping_ui_state'] = ui_state
|
||||
batch_ui_state = ui_event.get('batch_ui_state')
|
||||
if isinstance(batch_ui_state, dict):
|
||||
payload_patch['shipping_batch_ui_state'] = batch_ui_state
|
||||
return payload_patch
|
||||
|
||||
def _persist_history_recovery_payload(
|
||||
self,
|
||||
ctx: ChatStreamContext,
|
||||
event_data: dict[str, Any],
|
||||
*,
|
||||
state_event: dict[str, Any] | None = None,
|
||||
ui_event: dict[str, Any] | None = None,
|
||||
) -> None:
|
||||
"""
|
||||
把订单抽取终态与 UI 锚点合并到本轮已落库 ChatLog,供历史消息恢复。
|
||||
|
||||
核心逻辑:使用上游终态附带的 chat_log_id 与当前身份做归属校验;缺少日志主键时保留实时 SSE,
|
||||
不创建额外聊天记录。阶段 1 要求 `open_existing` 至少补齐 `task_no`,有批次或快照时继续补齐
|
||||
`batch_no / shipping_ui_state / shipping_batch_ui_state`。
|
||||
|
||||
Args:
|
||||
ctx: 当前聊天流上下文。
|
||||
event_data: Dify terminal/error 原始事件。
|
||||
state_event: 已构造的订单抽取状态事件。
|
||||
ui_event: 已构造的 shipping_ui_state 事件。
|
||||
"""
|
||||
payload_patch = self._build_history_recovery_payload_patch(
|
||||
state_event=state_event,
|
||||
ui_event=ui_event,
|
||||
)
|
||||
if not payload_patch:
|
||||
return
|
||||
try:
|
||||
chat_log_id = int(event_data.get('chat_log_id') or 0)
|
||||
except (TypeError, ValueError):
|
||||
chat_log_id = 0
|
||||
if chat_log_id <= 0:
|
||||
return
|
||||
from app.services.chat.log_service import merge_chat_log_payload
|
||||
|
||||
merge_chat_log_payload(
|
||||
chat_log_id=chat_log_id,
|
||||
user_id=int(getattr(ctx.user, 'id', 0) or 0),
|
||||
agent_id=int(getattr(ctx.agent, 'id', 0) or 0),
|
||||
session_id=str(getattr(ctx.session, 'session_id', '') or ''),
|
||||
payload_patch=payload_patch,
|
||||
)
|
||||
|
||||
def iter_ui_state_dedupe_key(self, event: dict[str, Any]) -> str | None:
|
||||
"""仅为 shipping_ui_state 构造去重键,其他领域事件保持独立生命周期。"""
|
||||
if str(event.get('event') or '') != 'shipping_ui_state':
|
||||
return None
|
||||
ui_state = event.get('ui_state') if isinstance(event.get('ui_state'), dict) else {}
|
||||
batch_ui_state = event.get('batch_ui_state') if isinstance(event.get('batch_ui_state'), dict) else {}
|
||||
focus_state = (
|
||||
@@ -115,9 +355,14 @@ class ShippingNoticeHandler(AgentHandler):
|
||||
}, ensure_ascii=False, sort_keys=True)
|
||||
|
||||
def _format_sse(self, event: dict[str, Any]) -> str:
|
||||
"""把领域事件编码为单条 SSE data frame。"""
|
||||
return f"data: {json.dumps(event, ensure_ascii=False)}\n\n"
|
||||
|
||||
def iter_preface_sse_lines(self, ctx: ChatStreamContext) -> Iterator[str]:
|
||||
"""上游调用前先推送订单抽取进行态,再补充已有任务 UI State。"""
|
||||
extraction_event = self.build_order_extraction_state_event(ctx)
|
||||
if extraction_event:
|
||||
yield self._format_sse(extraction_event)
|
||||
event = self.build_ui_state_event(ctx)
|
||||
if event:
|
||||
yield self._format_sse(event)
|
||||
@@ -127,9 +372,46 @@ class ShippingNoticeHandler(AgentHandler):
|
||||
ctx: ChatStreamContext,
|
||||
event_data: dict[str, Any],
|
||||
) -> Iterator[str]:
|
||||
"""上游终态后收口抽取状态,依次推送抽取事实和任务 UI State。"""
|
||||
event_name = str(event_data.get('event') or '').strip()
|
||||
if event_name not in {'message_end', 'workflow_finished'}:
|
||||
if event_name not in {'error', 'message_end', 'workflow_finished'}:
|
||||
return iter(())
|
||||
event = self.build_ui_state_event(ctx)
|
||||
intake_nos = self._order_extraction_intake_nos(ctx)
|
||||
if intake_nos:
|
||||
from app.services.shipping_notice.order_extraction import (
|
||||
ORDER_EXTRACTION_INCOMPLETE_MESSAGE,
|
||||
finalize_order_extraction_failure,
|
||||
)
|
||||
|
||||
failure_message = self._workflow_failure_message(event_data)
|
||||
try:
|
||||
finalize_order_extraction_failure(
|
||||
user_id=int(getattr(ctx.user, 'id', 0) or 0),
|
||||
session_id=str(getattr(ctx.session, 'session_id', '') or ''),
|
||||
intake_nos=intake_nos,
|
||||
request_id=ctx.request_id,
|
||||
error_message=failure_message or ORDER_EXTRACTION_INCOMPLETE_MESSAGE,
|
||||
)
|
||||
except Exception:
|
||||
from app import db
|
||||
|
||||
db.session.rollback()
|
||||
if current_app:
|
||||
current_app.logger.exception(
|
||||
'[shipping-handler] finalize order extraction failed request_id=%s intakes=%s',
|
||||
ctx.request_id,
|
||||
intake_nos,
|
||||
)
|
||||
extraction_event = self.build_order_extraction_state_event(ctx)
|
||||
event = self.build_ui_state_event(ctx, resolve_order_extraction=True)
|
||||
if extraction_event or event:
|
||||
self._persist_history_recovery_payload(
|
||||
ctx,
|
||||
event_data,
|
||||
state_event=extraction_event,
|
||||
ui_event=event,
|
||||
)
|
||||
if extraction_event:
|
||||
yield self._format_sse(extraction_event)
|
||||
if event:
|
||||
yield self._format_sse(event)
|
||||
@@ -1,9 +1,9 @@
|
||||
"""
|
||||
backend/app/services/chat/executors/__init__.py
|
||||
|
||||
用途:RUNTIME_PROVIDER_REGISTRY 与聊天 Executor 解析入口。
|
||||
用途:RUNTIME_PROVIDER_REGISTRY、聊天 Executor 解析及同步 Handler 前置准备入口。
|
||||
依赖:dify_chat、hybrid、builtin executors;agent_registry.resolver。
|
||||
逻辑:chat.py completions 默认 Dify 路径调用 stream_chat_via_executor。
|
||||
逻辑:chat.py 先调用 stream_chat_via_executor 同步执行 prepare_stream,再下发 preface 并惰性迭代上游流。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -12,7 +12,11 @@ from typing import Iterator
|
||||
|
||||
from app.core.errors import ValidationError
|
||||
from app.services.agent_registry.handlers.base import ChatStreamContext
|
||||
from app.services.agent_registry.resolver import resolve_runtime_provider
|
||||
from app.services.agent_registry.resolver import (
|
||||
resolve_handler,
|
||||
resolve_handler_for_agent_code,
|
||||
resolve_runtime_provider,
|
||||
)
|
||||
from app.services.chat.executors.base import ChatExecutor
|
||||
from app.services.chat.executors.builtin import BuiltinChatExecutor
|
||||
from app.services.chat.executors.dify_chat import DifyChatExecutor
|
||||
@@ -61,10 +65,19 @@ def stream_chat_via_executor(ctx: ChatStreamContext) -> Iterator[str]:
|
||||
Args:
|
||||
ctx: ChatStreamContext。
|
||||
|
||||
核心逻辑:必须在返回惰性生成器前同步调用 Handler.prepare_stream,确保 chat.py 随后的 preface
|
||||
能读取到已登记的领域状态;Hybrid/Builtin 强制要求 Handler,Dify Chatflow 允许无 Handler。
|
||||
|
||||
Returns:
|
||||
上游 SSE 行迭代器。
|
||||
已完成 Handler 前置准备的上游 SSE 行迭代器。
|
||||
"""
|
||||
executor = resolve_chat_executor(ctx.agent)
|
||||
if executor.provider_key in {'hybrid', 'builtin'}:
|
||||
handler = resolve_handler(ctx.agent)
|
||||
else:
|
||||
handler = resolve_handler_for_agent_code(ctx.agent)
|
||||
if handler is not None:
|
||||
ctx = handler.prepare_stream(ctx)
|
||||
return executor.stream(ctx)
|
||||
|
||||
|
||||
|
||||
@@ -3,7 +3,7 @@ backend/app/services/chat/executors/builtin.py
|
||||
|
||||
用途:runtime_provider=builtin 的聊天 Executor。
|
||||
依赖:agent_registry.resolver.resolve_handler。
|
||||
逻辑:必须存在 Handler;由 Handler 驱动内置流(v1 未实现完整 builtin 流时显式报错)。
|
||||
逻辑:stream_chat_via_executor 已校验并准备 Handler;v1 未实现完整 builtin 流时显式报错。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -21,8 +21,8 @@ class BuiltinChatExecutor(ChatExecutor):
|
||||
provider_key = 'builtin'
|
||||
|
||||
def stream(self, ctx: ChatStreamContext) -> Iterator[str]:
|
||||
"""返回尚未实现的明确错误,并保留 Handler key 便于诊断。"""
|
||||
handler = resolve_handler(ctx.agent)
|
||||
ctx = handler.prepare_stream(ctx)
|
||||
raise AppError(
|
||||
code='AGENT.BUILTIN_NOT_IMPLEMENTED',
|
||||
message='runtime_provider=builtin 的聊天流尚未实现,请使用 hybrid 或 dify',
|
||||
|
||||
@@ -2,15 +2,14 @@
|
||||
backend/app/services/chat/executors/dify_chat.py
|
||||
|
||||
用途:runtime_provider=dify 的 Chatflow 聊天 Executor。
|
||||
依赖:DifyService.stream_chat、executors.base、agent_registry.resolver。
|
||||
逻辑:Handler.prepare_stream → build_chat_dify_inputs → DifyService.stream_chat。
|
||||
依赖:DifyService.stream_chat、executors.base。
|
||||
逻辑:stream_chat_via_executor 已完成 Handler 前置准备;本文件构造 inputs 并惰性转发 Dify SSE。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Iterator
|
||||
|
||||
from app.services.agent_registry.resolver import resolve_handler_for_agent_code
|
||||
from app.services.chat.executors.base import (
|
||||
ChatExecutor,
|
||||
ChatStreamContext,
|
||||
@@ -25,9 +24,7 @@ class DifyChatExecutor(ChatExecutor):
|
||||
provider_key = 'dify'
|
||||
|
||||
def stream(self, ctx: ChatStreamContext) -> Iterator[str]:
|
||||
handler = resolve_handler_for_agent_code(ctx.agent)
|
||||
if handler is not None:
|
||||
ctx = handler.prepare_stream(ctx)
|
||||
"""使用已经完成 Handler 前置准备的上下文调用 Dify Chatflow。"""
|
||||
dify_inputs = build_dify_inputs_for_context(ctx)
|
||||
yield from DifyService.stream_chat(
|
||||
ctx.query,
|
||||
|
||||
@@ -1,16 +1,15 @@
|
||||
"""
|
||||
backend/app/services/chat/executors/hybrid.py
|
||||
|
||||
用途:runtime_provider=hybrid 的聊天 Executor(Handler 前置 + Dify 流)。
|
||||
依赖:resolve_handler、DifyChatExecutor。
|
||||
逻辑:resolve_handler 校验 → handler.prepare_stream → DifyChatExecutor.stream。
|
||||
用途:runtime_provider=hybrid 的聊天 Executor(强制 Handler + Dify 流)。
|
||||
依赖:DifyChatExecutor;Handler 校验与前置准备由 stream_chat_via_executor 统一完成。
|
||||
逻辑:接收已准备上下文并委托 DifyChatExecutor.stream。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Iterator
|
||||
|
||||
from app.services.agent_registry.resolver import resolve_handler
|
||||
from app.services.chat.executors.base import ChatExecutor, ChatStreamContext
|
||||
from app.services.chat.executors.dify_chat import DifyChatExecutor
|
||||
|
||||
@@ -24,6 +23,5 @@ class HybridChatExecutor(ChatExecutor):
|
||||
self._dify = DifyChatExecutor()
|
||||
|
||||
def stream(self, ctx: ChatStreamContext) -> Iterator[str]:
|
||||
handler = resolve_handler(ctx.agent)
|
||||
ctx = handler.prepare_stream(ctx)
|
||||
"""把已完成 Handler 准备的 Hybrid 上下文委托给 Dify Chatflow。"""
|
||||
yield from self._dify.stream(ctx)
|
||||
@@ -1,9 +1,9 @@
|
||||
"""
|
||||
backend/app/services/chat/log_service.py
|
||||
|
||||
用途:Chat Turn 与对话历史的 ChatLog 统一写入。
|
||||
用途:Chat Turn 与对话历史的 ChatLog 统一写入及结构化 payload 合并。
|
||||
依赖:models.ChatLog、SQLAlchemy。
|
||||
逻辑:turn_runtime 在 run.completed 时调用 save_turn_chat_log;api/chat 历史路由可逐步迁入。
|
||||
逻辑:turn_runtime 在 run.completed 时调用 save_turn_chat_log;领域 Handler 可在上游终态后安全合并回放 payload。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -72,3 +72,61 @@ def save_turn_chat_log(
|
||||
current_app.logger.exception("[chat-turn] failed to save chat log: %s", exc)
|
||||
db.session.rollback()
|
||||
return None
|
||||
|
||||
|
||||
def merge_chat_log_payload(
|
||||
*,
|
||||
chat_log_id: int,
|
||||
user_id: int,
|
||||
agent_id: int,
|
||||
session_id: str,
|
||||
payload_patch: dict[str, Any],
|
||||
) -> bool:
|
||||
"""
|
||||
在归属校验通过后幂等合并 ChatLog 结构化 payload。
|
||||
|
||||
核心逻辑:锁定指定消息并同时校验用户、Agent、本地会话,随后以顶层键覆盖方式合并领域终态;
|
||||
该函数不修改正文,适合 SSE terminal 之后补写可回放的状态卡片数据。
|
||||
|
||||
Args:
|
||||
chat_log_id: 已持久化的 ChatLog 主键,必须为正整数。
|
||||
user_id: 当前请求用户主键。
|
||||
agent_id: 当前请求 Agent 主键。
|
||||
session_id: 当前 HXOPS 本地会话号。
|
||||
payload_patch: 要合并的顶层结构化字段,不得为空。
|
||||
|
||||
Returns:
|
||||
找到且成功写入时返回 True;身份不匹配、参数为空或写入失败时返回 False。
|
||||
"""
|
||||
if chat_log_id <= 0 or user_id <= 0 or agent_id <= 0 or not str(session_id or '').strip() or not payload_patch:
|
||||
return False
|
||||
try:
|
||||
chat_log = (
|
||||
db.session.query(ChatLog)
|
||||
.filter(
|
||||
ChatLog.id == int(chat_log_id),
|
||||
ChatLog.user_id == int(user_id),
|
||||
ChatLog.agent_id == int(agent_id),
|
||||
ChatLog.session_id == str(session_id).strip(),
|
||||
)
|
||||
.with_for_update()
|
||||
.one_or_none()
|
||||
)
|
||||
if chat_log is None:
|
||||
db.session.rollback()
|
||||
return False
|
||||
chat_log.payload = {
|
||||
**(chat_log.payload if isinstance(chat_log.payload, dict) else {}),
|
||||
**payload_patch,
|
||||
}
|
||||
db.session.commit()
|
||||
return True
|
||||
except Exception as exc:
|
||||
if current_app:
|
||||
current_app.logger.exception(
|
||||
"[chat-log] failed to merge payload chat_log_id=%s: %s",
|
||||
chat_log_id,
|
||||
exc,
|
||||
)
|
||||
db.session.rollback()
|
||||
return False
|
||||
@@ -42,7 +42,7 @@ def iter_handler_terminal_sse(
|
||||
*,
|
||||
emitted_keys: set[str],
|
||||
) -> Iterator[str]:
|
||||
"""上游终态事件后追加 Handler SSE(如 shipping_ui_state 刷新)。"""
|
||||
"""上游终态/error 事件后追加 Handler SSE(如订单抽取收口与 shipping_ui_state 刷新)。"""
|
||||
handler = resolve_handler_for_agent_code(ctx.agent)
|
||||
if handler is None:
|
||||
return
|
||||
|
||||
@@ -862,7 +862,7 @@ class DifyService:
|
||||
base_url = agent.api_base_url if agent.api_base_url else Config.DIFY_API_BASE
|
||||
url = DifyService._build_chat_messages_url(base_url)
|
||||
normalized_conversation_id = DifyService._normalize_dify_conversation_id(conversation_id)
|
||||
visible_query = str(display_query or query or '').strip()
|
||||
visible_query = str(query if display_query is None else display_query).strip()
|
||||
|
||||
headers = {
|
||||
'Authorization': f'Bearer {agent.dify_api_key}',
|
||||
@@ -1128,19 +1128,20 @@ class DifyService:
|
||||
if isinstance(e, requests.exceptions.ReadTimeout) and has_sent_answer:
|
||||
if current_app:
|
||||
current_app.logger.warning(
|
||||
"[chat-stream] read timeout after answer request_id=%s attempt=%s; finish stream silently",
|
||||
"[chat-stream] read timeout after answer request_id=%s attempt=%s; emit synthetic terminal",
|
||||
request_id,
|
||||
attempt,
|
||||
)
|
||||
persist_stream_chat(
|
||||
{
|
||||
'event': 'message_end',
|
||||
'conversation_id': normalized_conversation_id,
|
||||
'answer': ''.join(full_answer).strip(),
|
||||
'metadata': {},
|
||||
},
|
||||
'message_end',
|
||||
)
|
||||
# [STEP 3] 已有正文时用合成 message_end 正常收口;persist 会把 chat_log_id 回写到同一事件,
|
||||
# 领域 Handler 仍能在网络超时后完成状态持久化,而前端不会把本轮误判为永久处理中。
|
||||
timeout_end_event = {
|
||||
'event': 'message_end',
|
||||
'conversation_id': normalized_conversation_id,
|
||||
'answer': ''.join(full_answer).strip(),
|
||||
'metadata': {},
|
||||
}
|
||||
persist_stream_chat(timeout_end_event, 'message_end')
|
||||
yield f"data: {json.dumps(timeout_end_event, ensure_ascii=False)}\n\n"
|
||||
break
|
||||
if not is_timeout and attempt < max_retries:
|
||||
time.sleep(attempt * 2)
|
||||
@@ -1154,17 +1155,16 @@ class DifyService:
|
||||
message = "连接 Dify 超时,请检查 Dify API Base URL 和网络连通性。"
|
||||
else:
|
||||
message = str(e)
|
||||
persist_stream_chat(
|
||||
{
|
||||
'event': 'error',
|
||||
'conversation_id': normalized_conversation_id,
|
||||
'answer': f"[Error: {message}]",
|
||||
'metadata': {},
|
||||
},
|
||||
'error',
|
||||
)
|
||||
error_msg = json.dumps({'event': 'error', 'message': message})
|
||||
yield f"data: {error_msg}\n\n"
|
||||
# [STEP 4] 错误事件与持久化对象必须是同一个 dict,确保 chat_log_id 能继续传给 relay/领域 Handler。
|
||||
error_event = {
|
||||
'event': 'error',
|
||||
'conversation_id': normalized_conversation_id,
|
||||
'answer': f"[Error: {message}]",
|
||||
'message': message,
|
||||
'metadata': {},
|
||||
}
|
||||
persist_stream_chat(error_event, 'error')
|
||||
yield f"data: {json.dumps(error_event, ensure_ascii=False)}\n\n"
|
||||
|
||||
@staticmethod
|
||||
def _log_chat(
|
||||
|
||||
@@ -40,7 +40,7 @@ def _shipping_inventory_sources_options() -> list[dict[str, Any]]:
|
||||
"label": source.get("display_name") or source.get("source_code"),
|
||||
"value": source.get("source_code"),
|
||||
"description": (
|
||||
f"{source.get('source_type')} · "
|
||||
f"{source.get('connector_type')} · "
|
||||
f"{source.get('site_id') or '-'} · "
|
||||
f"{source.get('warehouse_id')}"
|
||||
),
|
||||
|
||||
@@ -2,8 +2,8 @@
|
||||
backend/app/services/shipping_notice/batch_from_intakes.py
|
||||
|
||||
用途:从已解析 ShippingNoticeIntake 确认建批的共享编排。
|
||||
依赖:batch_from_notices、intake_service、intake_parse_workflow、batch_create_idempotency、
|
||||
attachment_integrity。
|
||||
依赖:batch_from_notices、customer_auto_resolution、intake_service、intake_parse_workflow、batch_create_idempotency、
|
||||
attachment_integrity、open_existing_reservation_backfill。
|
||||
逻辑:workspace API 与 chat action shipping.create_batch_from_intakes 共用本模块。
|
||||
幂等以 intake.create_idempotency_key 为准(覆盖混合批次 / 纯 open_existing);
|
||||
批次 create_idempotency_key + process_summary.request_intake_nos 为兼容回退。
|
||||
@@ -45,7 +45,11 @@ from app.services.shipping_notice.duplicate_detection import (
|
||||
from app.services.shipping_notice.candidate_validation import normalize_candidate_business_summary
|
||||
from app.services.shipping_notice.intake_parse_workflow import candidate_to_notice_item, intake_to_notice_item
|
||||
from app.services.shipping_notice.intake_service import mark_intakes_consumed
|
||||
from app.services.shipping_notice.open_existing_reservation_backfill import (
|
||||
backfill_exact_file_open_existing_reservations,
|
||||
)
|
||||
from app.services.shipping_notice.tool_common import log_task_event
|
||||
from app.services.shipping_notice.customer_auto_resolution import try_auto_confirm_task_customer
|
||||
|
||||
|
||||
def _batch_intake_nos(batch_id: int) -> set[str]:
|
||||
@@ -667,9 +671,21 @@ def create_shipping_batch_from_candidates(
|
||||
message='强制新建必须填写原因',
|
||||
)
|
||||
if resolution == 'open_existing':
|
||||
target = db.session.query(ShippingTask).filter_by(task_no=target_no, user_id=int(user_id)).first()
|
||||
target = (
|
||||
db.session.query(ShippingTask)
|
||||
.filter_by(task_no=target_no, user_id=int(user_id))
|
||||
.with_for_update()
|
||||
.first()
|
||||
)
|
||||
if target is None:
|
||||
raise ConflictError(code='SHIPPING_NOTICE.DUPLICATE_TARGET_NOT_FOUND', message='重复目标任务不存在')
|
||||
backfill_exact_file_open_existing_reservations(
|
||||
task=target,
|
||||
candidate=candidate,
|
||||
candidate_summary=summary,
|
||||
duplicate_status=str(fresh.get('status') or ''),
|
||||
duplicate_matches=matches,
|
||||
)
|
||||
candidate.consumed_task_id = int(target.id)
|
||||
candidate.updated_at = now
|
||||
opened.append({'candidate_no': candidate.candidate_no, 'task_no': target.task_no, 'batch_no': None})
|
||||
@@ -705,6 +721,7 @@ def create_shipping_batch_from_candidates(
|
||||
raise ConflictError(code='SHIPPING.BATCH_CREATE_INCOMPLETE', message='候选任务关联不完整')
|
||||
candidate.consumed_task_id = int(task.id)
|
||||
candidate.updated_at = now
|
||||
try_auto_confirm_task_customer(task)
|
||||
_attach_request_intake_summary(
|
||||
batch_obj,
|
||||
request_intake_nos=intake_nos,
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
"""
|
||||
services/shipping_notice/business_case_service.py
|
||||
|
||||
用途:为新建货代任务创建或继承业务单聚合。
|
||||
依赖:db、ShippingCase、ShippingTask、uuid/datetime。
|
||||
逻辑:普通任务和强制新建任务创建新业务单;修订任务继承父任务业务单,必要时为历史父任务补建。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import uuid
|
||||
from datetime import datetime
|
||||
|
||||
from app import db
|
||||
from app.core.errors import ConflictError
|
||||
from app.models import ShippingCase, ShippingTask
|
||||
|
||||
|
||||
def generate_shipping_case_no() -> str:
|
||||
"""生成内部业务单聚合编号;仅用于系统关联,不对外替代 business_no。"""
|
||||
return f"SC-{datetime.utcnow().strftime('%Y%m%d')}-{uuid.uuid4().hex[:8].upper()}"
|
||||
|
||||
|
||||
def create_shipping_case(*, created_by_id: int | None = None) -> ShippingCase:
|
||||
"""
|
||||
创建未绑定客户、未编号的业务单聚合。
|
||||
|
||||
Args:
|
||||
created_by_id: 创建任务的用户 ID,可为空。
|
||||
Returns:
|
||||
尚未提交事务的 ShippingCase。
|
||||
"""
|
||||
case = ShippingCase(
|
||||
case_no=generate_shipping_case_no(),
|
||||
created_by_id=created_by_id,
|
||||
numbering_status='pending',
|
||||
status='open',
|
||||
)
|
||||
db.session.add(case)
|
||||
db.session.flush()
|
||||
return case
|
||||
|
||||
|
||||
def resolve_shipping_case_for_new_task(
|
||||
*,
|
||||
supersedes_task_id: int | None = None,
|
||||
duplicate_resolution_type: str | None = None,
|
||||
created_by_id: int | None = None,
|
||||
) -> ShippingCase:
|
||||
"""
|
||||
为即将创建的任务解析业务单归属。
|
||||
|
||||
核心逻辑:revision 继承父任务业务单;历史父任务未关联时在同一事务补建;
|
||||
normal/force_create 均创建独立业务单,保证强制新建重新占用未来流水。
|
||||
|
||||
Args:
|
||||
supersedes_task_id: 修订目标任务主键,仅 revision 使用。
|
||||
duplicate_resolution_type: normal/revision/force_create。
|
||||
created_by_id: 新任务创建人。
|
||||
Returns:
|
||||
新任务应关联的 ShippingCase。
|
||||
Raises:
|
||||
ConflictError: revision 缺少或找不到父任务。
|
||||
"""
|
||||
resolution_type = str(duplicate_resolution_type or 'normal').strip().lower()
|
||||
if resolution_type != 'revision':
|
||||
return create_shipping_case(created_by_id=created_by_id)
|
||||
|
||||
if not supersedes_task_id:
|
||||
raise ConflictError(
|
||||
'修订任务缺少父任务',
|
||||
code='SHIPPING_NOTICE.REVISION_TARGET_INVALID',
|
||||
)
|
||||
parent = db.session.get(ShippingTask, int(supersedes_task_id))
|
||||
if parent is None:
|
||||
raise ConflictError(
|
||||
'修订目标任务不存在',
|
||||
code='SHIPPING_NOTICE.REVISION_TARGET_INVALID',
|
||||
details={'supersedes_task_id': supersedes_task_id},
|
||||
)
|
||||
if parent.shipping_case is not None:
|
||||
return parent.shipping_case
|
||||
|
||||
case = create_shipping_case(created_by_id=parent.user_id or created_by_id)
|
||||
parent.shipping_case = case
|
||||
db.session.flush()
|
||||
return case
|
||||
|
||||
@@ -3,7 +3,8 @@ backend/app/services/shipping_notice/business_fingerprint.py
|
||||
|
||||
用途:基于业务摘要生成稳定业务指纹与强度判定(货代域,不含文件哈希)。
|
||||
依赖:po_number / reservation_id 标准化函数。
|
||||
逻辑:intake_parse_workflow / Candidate 级 duplicate_detection / 建单门闩共用;算法版本 shipping-v1。
|
||||
逻辑:intake_parse_workflow / Candidate 级 duplicate_detection / 建单门闩共用;
|
||||
身份算法版本 shipping-v1,内容算法版本 shipping-content-v3。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -17,7 +18,7 @@ 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-v1'
|
||||
CONTENT_FINGERPRINT_VERSION = 'shipping-content-v2'
|
||||
CONTENT_FINGERPRINT_VERSION = 'shipping-content-v3'
|
||||
|
||||
|
||||
def _norm_text(value: Any) -> str:
|
||||
@@ -205,7 +206,6 @@ def build_content_fingerprint(business_summary: dict[str, Any] | None) -> dict[s
|
||||
_norm_text(line.get('source_type')),
|
||||
_norm_text(line.get('customer_sku')),
|
||||
_norm_text(line.get('vendor_part_number')),
|
||||
_norm_text(line.get('hub_code')),
|
||||
]
|
||||
if any(values):
|
||||
parts.append('|'.join(values))
|
||||
|
||||
@@ -0,0 +1,170 @@
|
||||
"""
|
||||
services/shipping_notice/business_numbering_service.py
|
||||
|
||||
用途:为已确认客户的货代业务单分配不可变业务编号。
|
||||
依赖:ShippingCase/Customer/BusinessSequence、Asia/Shanghai 时区、SQLAlchemy 方言能力。
|
||||
逻辑:锁定业务单后按客户与上海业务日期原子递增流水;编号写入业务单快照,事务由调用方提交。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import date, datetime
|
||||
from zoneinfo import ZoneInfo
|
||||
|
||||
from sqlalchemy import update
|
||||
|
||||
from app import db
|
||||
from app.core.errors import ConflictError
|
||||
from app.models import ShippingBusinessSequence, ShippingCase, ShippingCustomer
|
||||
from app.services.shipping_notice.customer_normalization import SHORT_CODE_RE
|
||||
|
||||
BUSINESS_TYPE = "shipping_notice"
|
||||
NUMBERING_RULE_VERSION = "shipping-customer-date-seq-v1"
|
||||
SHANGHAI_TZ = ZoneInfo("Asia/Shanghai")
|
||||
MAX_DAILY_SEQUENCE = 99
|
||||
|
||||
|
||||
def shanghai_business_date(moment: datetime | None = None) -> date:
|
||||
"""
|
||||
计算编号使用的上海业务日期。
|
||||
|
||||
Args:
|
||||
moment: 可选时刻;有时区则转换到上海,无时区按 UTC 兼容处理。
|
||||
Returns:
|
||||
Asia/Shanghai 口径的日期。
|
||||
"""
|
||||
if moment is None:
|
||||
return datetime.now(SHANGHAI_TZ).date()
|
||||
if moment.tzinfo is None:
|
||||
moment = moment.replace(tzinfo=ZoneInfo("UTC"))
|
||||
return moment.astimezone(SHANGHAI_TZ).date()
|
||||
|
||||
|
||||
def format_business_no(short_code: str, business_date: date, sequence_value: int) -> str:
|
||||
"""
|
||||
按固定规则格式化业务编号。
|
||||
|
||||
Args:
|
||||
short_code: 2-6 位大写客户简码。
|
||||
business_date: 上海业务日期。
|
||||
sequence_value: 当日客户流水,范围 1-99。
|
||||
Returns:
|
||||
无分隔符编号,例如 WYC26071501。
|
||||
"""
|
||||
return f"{short_code}{business_date.strftime('%y%m%d')}{sequence_value:02d}"
|
||||
|
||||
|
||||
def _next_sequence_value(customer_id: int, business_date: date) -> int:
|
||||
"""
|
||||
原子取得客户当日下一流水。
|
||||
|
||||
核心逻辑:PostgreSQL 使用 INSERT ON CONFLICT DO UPDATE RETURNING;测试 SQLite 使用条件 UPDATE,
|
||||
两条路径都只允许 1-99,避免“查询最大值 + 1”的竞态。
|
||||
"""
|
||||
bind = db.session.get_bind()
|
||||
dialect_name = bind.dialect.name
|
||||
if dialect_name == "postgresql":
|
||||
from sqlalchemy.dialects.postgresql import insert
|
||||
|
||||
stmt = insert(ShippingBusinessSequence).values(
|
||||
business_type=BUSINESS_TYPE,
|
||||
customer_id=customer_id,
|
||||
business_date=business_date,
|
||||
current_value=1,
|
||||
)
|
||||
stmt = stmt.on_conflict_do_update(
|
||||
index_elements=["business_type", "customer_id", "business_date"],
|
||||
set_={"current_value": ShippingBusinessSequence.current_value + 1},
|
||||
where=ShippingBusinessSequence.current_value < MAX_DAILY_SEQUENCE,
|
||||
).returning(ShippingBusinessSequence.current_value)
|
||||
value = db.session.execute(stmt).scalar_one_or_none()
|
||||
else:
|
||||
stmt = (
|
||||
update(ShippingBusinessSequence)
|
||||
.where(
|
||||
ShippingBusinessSequence.business_type == BUSINESS_TYPE,
|
||||
ShippingBusinessSequence.customer_id == customer_id,
|
||||
ShippingBusinessSequence.business_date == business_date,
|
||||
ShippingBusinessSequence.current_value < MAX_DAILY_SEQUENCE,
|
||||
)
|
||||
.values(current_value=ShippingBusinessSequence.current_value + 1)
|
||||
.returning(ShippingBusinessSequence.current_value)
|
||||
)
|
||||
value = db.session.execute(stmt).scalar_one_or_none()
|
||||
if value is None:
|
||||
existing = db.session.query(ShippingBusinessSequence.id).filter_by(
|
||||
business_type=BUSINESS_TYPE,
|
||||
customer_id=customer_id,
|
||||
business_date=business_date,
|
||||
).first()
|
||||
if existing is None:
|
||||
sequence = ShippingBusinessSequence(
|
||||
business_type=BUSINESS_TYPE,
|
||||
customer_id=customer_id,
|
||||
business_date=business_date,
|
||||
current_value=1,
|
||||
)
|
||||
db.session.add(sequence)
|
||||
db.session.flush()
|
||||
value = 1
|
||||
|
||||
if value is None or int(value) > MAX_DAILY_SEQUENCE:
|
||||
raise ConflictError(
|
||||
"Customer daily business number capacity exhausted",
|
||||
code="SHIPPING.BUSINESS_NUMBER_DAILY_LIMIT_REACHED",
|
||||
details={
|
||||
"customer_id": customer_id,
|
||||
"business_date": business_date.isoformat(),
|
||||
"max_sequence": MAX_DAILY_SEQUENCE,
|
||||
},
|
||||
)
|
||||
return int(value)
|
||||
|
||||
|
||||
def assign_business_number(case: ShippingCase, *, moment: datetime | None = None) -> str:
|
||||
"""
|
||||
为业务单幂等分配业务编号,调用方负责同事务提交。
|
||||
|
||||
核心逻辑:已有编号直接返回;否则校验启用客户与简码快照,取得上海日期流水并写入不可变编号字段。
|
||||
|
||||
Args:
|
||||
case: 已加锁且已绑定标准客户的业务单。
|
||||
moment: 可选测试时刻。
|
||||
Returns:
|
||||
分配或已存在的业务编号。
|
||||
Raises:
|
||||
ConflictError: 客户无效、简码缺失或当日两位流水耗尽。
|
||||
"""
|
||||
if case.business_no:
|
||||
return str(case.business_no)
|
||||
if case.customer_id is None:
|
||||
raise ConflictError(
|
||||
"Shipping case customer must be confirmed before numbering",
|
||||
code="SHIPPING.BUSINESS_NUMBER_CUSTOMER_REQUIRED",
|
||||
)
|
||||
customer = db.session.get(ShippingCustomer, int(case.customer_id))
|
||||
if customer is None or customer.status != "active":
|
||||
raise ConflictError(
|
||||
"Active customer is required before numbering",
|
||||
code="SHIPPING.BUSINESS_NUMBER_CUSTOMER_INVALID",
|
||||
)
|
||||
|
||||
short_code = str(customer.short_code or "").strip().upper()
|
||||
if not SHORT_CODE_RE.fullmatch(short_code):
|
||||
raise ConflictError(
|
||||
"Customer short code is invalid for business numbering",
|
||||
code="SHIPPING.BUSINESS_NUMBER_SHORT_CODE_INVALID",
|
||||
details={"customer_id": customer.id, "short_code": short_code},
|
||||
)
|
||||
business_date = shanghai_business_date(moment)
|
||||
sequence_value = _next_sequence_value(customer.id, business_date)
|
||||
business_no = format_business_no(short_code, business_date, sequence_value)
|
||||
case.customer_name_snapshot = customer.standard_name
|
||||
case.customer_short_code_snapshot = short_code
|
||||
case.business_date = business_date
|
||||
case.sequence_value = sequence_value
|
||||
case.numbering_rule_version = NUMBERING_RULE_VERSION
|
||||
case.numbering_status = "assigned"
|
||||
case.business_no = business_no
|
||||
db.session.flush()
|
||||
return business_no
|
||||
@@ -16,15 +16,15 @@ from app.services.shipping_notice.po_number import normalize_po_number
|
||||
from app.services.shipping_notice.reservation_id import validated_reservation_id
|
||||
|
||||
BUILD_REQUIRED_FIELDS = ('sku', 'qty')
|
||||
PROCESS_FIELDS = ('reservation_id', 'hub_code', 'source_type')
|
||||
PROCESS_FIELDS = ('reservation_id',)
|
||||
|
||||
|
||||
def assess_candidate_business_summary(summary: dict[str, Any] | None) -> dict[str, Any]:
|
||||
"""
|
||||
评估规则/LLM订单结果是否达到自动建单最低条件,同时保留不完整内容供自然对话修订。
|
||||
|
||||
核心逻辑:SKU + 正数 Qty 是建单硬条件;Reservation/Hub/Source Type 属于流程字段,
|
||||
缺失或格式异常时允许创建 Task,但必须进入后续字段补充门禁。
|
||||
核心逻辑:SKU + 正数 Qty 是建单硬条件;Reservation ID 是唯一流程门禁字段。
|
||||
行级 source_type 仅保留为可选库存源路由线索,缺失时不阻断建单或后续流程。
|
||||
|
||||
Args:
|
||||
summary: 单个订单的业务摘要。
|
||||
|
||||
@@ -27,6 +27,7 @@ CP_UPLOAD_REQ = "upload_req"
|
||||
CP_MAP_OK = "map_ok"
|
||||
CP_PARSE_OK = "parse_ok"
|
||||
CP_PARSE_REVIEW = "parse_review"
|
||||
CP_CUSTOMER_REVIEW = "customer_review"
|
||||
CP_TASK_EXISTS = "task_exists"
|
||||
CP_RSV_REQ = "rsv_req"
|
||||
CP_UPLOAD_FAILED = "upload_failed"
|
||||
|
||||
@@ -0,0 +1,425 @@
|
||||
"""
|
||||
services/shipping_notice/customer_auto_resolution.py
|
||||
|
||||
用途:基于管理员审核的强证据受控自动确认客户,并支持历史回填与编号后客户纠错。
|
||||
依赖:ShippingCustomerIdentifier/ShadowResolution/Task、customer_identity_gate、business_numbering_service、Flask 配置。
|
||||
逻辑:Candidate 建单后仅以已审核强证据自动确认;管理员纠错时保留原号作废并创建替代业务单。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
|
||||
from app import db
|
||||
from app.core.errors import ConflictError, NotFoundError, ValidationError
|
||||
from app.models import (
|
||||
ShippingCase,
|
||||
ShippingCustomer,
|
||||
ShippingCustomerIdentifier,
|
||||
ShippingCustomerShadowResolution,
|
||||
ShippingNoticeCandidate,
|
||||
ShippingTask,
|
||||
ShippingTaskEvent,
|
||||
)
|
||||
from app.services.shipping_notice.customer_identity_gate import confirm_task_customer
|
||||
from app.services.shipping_notice.customer_normalization import is_public_email_domain
|
||||
from app.services.shipping_notice.tool_common import cfg_bool
|
||||
from app.services.shipping_notice.business_case_service import generate_shipping_case_no
|
||||
from app.services.shipping_notice.business_numbering_service import assign_business_number
|
||||
|
||||
AUTO_RESOLUTION_VERSION = "customer-auto-v1"
|
||||
AUTO_IDENTIFIER_TYPES = frozenset({"email", "domain", "template_fingerprint"})
|
||||
CUSTOMER_AUDIT_EVENT_TYPES = (
|
||||
"customer_auto_resolution_evaluated",
|
||||
"customer_auto_confirmed",
|
||||
"customer_correction_applied",
|
||||
"customer_historical_backfilled",
|
||||
)
|
||||
|
||||
|
||||
def auto_customer_resolution_enabled() -> bool:
|
||||
"""读取自动客户确认总开关;默认关闭以支持安全降级。"""
|
||||
return cfg_bool("SHIPPING_NOTICE_AUTO_CUSTOMER_CONFIRM_ENABLED", False)
|
||||
|
||||
|
||||
def _eligible_identifier(identifier: ShippingCustomerIdentifier) -> bool:
|
||||
"""判断识别证据是否达到自动确认门槛。"""
|
||||
if identifier.status != "approved" or not identifier.auto_match_allowed:
|
||||
return False
|
||||
if identifier.identifier_type not in AUTO_IDENTIFIER_TYPES:
|
||||
return False
|
||||
if identifier.identifier_type == "domain" and is_public_email_domain(identifier.normalized_value):
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def resolve_auto_customer_from_shadow(task: ShippingTask) -> dict[str, Any]:
|
||||
"""
|
||||
使用任务来源 Candidate 的影子证据执行受控自动裁决。
|
||||
|
||||
Args:
|
||||
task: 已创建但客户仍 pending 的任务。
|
||||
Returns:
|
||||
status、规则版本、唯一 customer_id 与命中证据;歧义/关闭时 customer_id 为空。
|
||||
"""
|
||||
if not auto_customer_resolution_enabled():
|
||||
return {"status": "disabled", "rule_version": AUTO_RESOLUTION_VERSION, "customer_id": None, "evidence": []}
|
||||
if task.source_candidate_id is None:
|
||||
return {"status": "no_candidate", "rule_version": AUTO_RESOLUTION_VERSION, "customer_id": None, "evidence": []}
|
||||
shadow = db.session.query(ShippingCustomerShadowResolution).filter_by(
|
||||
candidate_id=int(task.source_candidate_id),
|
||||
).first()
|
||||
if shadow is None:
|
||||
candidate = db.session.get(ShippingNoticeCandidate, int(task.source_candidate_id))
|
||||
if candidate is not None:
|
||||
from app.services.shipping_notice.customer_shadow_resolution import refresh_candidate_shadow_resolution
|
||||
|
||||
shadow = refresh_candidate_shadow_resolution(candidate)
|
||||
if shadow is None:
|
||||
return {"status": "no_shadow", "rule_version": AUTO_RESOLUTION_VERSION, "customer_id": None, "evidence": []}
|
||||
|
||||
matched: dict[int, list[dict[str, Any]]] = {}
|
||||
for evidence in shadow.evidence_json or []:
|
||||
if not isinstance(evidence, dict):
|
||||
continue
|
||||
kind = str(evidence.get("type") or "").strip()
|
||||
normalized = str(evidence.get("normalized_value") or "").strip()
|
||||
if kind not in AUTO_IDENTIFIER_TYPES or not normalized:
|
||||
continue
|
||||
identifiers = db.session.query(ShippingCustomerIdentifier).filter_by(
|
||||
identifier_type=kind,
|
||||
normalized_value=normalized,
|
||||
).all()
|
||||
for identifier in identifiers:
|
||||
if not _eligible_identifier(identifier):
|
||||
continue
|
||||
customer = db.session.get(ShippingCustomer, int(identifier.customer_id))
|
||||
if customer is None or customer.status != "active":
|
||||
continue
|
||||
matched.setdefault(customer.id, []).append({
|
||||
"identifier_id": identifier.id,
|
||||
"identifier_type": kind,
|
||||
"normalized_value": normalized,
|
||||
})
|
||||
if len(matched) != 1:
|
||||
return {
|
||||
"status": "ambiguous" if matched else "unmatched",
|
||||
"rule_version": AUTO_RESOLUTION_VERSION,
|
||||
"customer_id": None,
|
||||
"evidence": [item for rows in matched.values() for item in rows],
|
||||
"candidate_customer_ids": sorted(matched),
|
||||
}
|
||||
customer_id = next(iter(matched))
|
||||
return {
|
||||
"status": "unique_strong_match",
|
||||
"rule_version": AUTO_RESOLUTION_VERSION,
|
||||
"customer_id": customer_id,
|
||||
"evidence": matched[customer_id],
|
||||
}
|
||||
|
||||
|
||||
def try_auto_confirm_task_customer(task: ShippingTask) -> dict[str, Any]:
|
||||
"""
|
||||
尝试自动确认并生成业务编号;未达门槛时保持 customer_review。
|
||||
|
||||
核心逻辑:先写自动裁决审计,再复用人工确认的锁与编号事务;成功后将确认方法改为 auto_rule。
|
||||
"""
|
||||
if task.customer_resolution_status == "confirmed":
|
||||
return {"status": "already_confirmed", "customer_id": task.shipping_case.customer_id if task.shipping_case else None}
|
||||
decision = resolve_auto_customer_from_shadow(task)
|
||||
db.session.add(ShippingTaskEvent(
|
||||
task_id=task.id,
|
||||
event_type="customer_auto_resolution_evaluated",
|
||||
detail_json=decision,
|
||||
))
|
||||
if decision.get("customer_id") is None:
|
||||
db.session.flush()
|
||||
return decision
|
||||
|
||||
updated = confirm_task_customer(
|
||||
task,
|
||||
customer_id=int(decision["customer_id"]),
|
||||
actor_id=None,
|
||||
resolution_method="auto_rule",
|
||||
commit=False,
|
||||
)
|
||||
db.session.add(ShippingTaskEvent(
|
||||
task_id=updated.id,
|
||||
event_type="customer_auto_confirmed",
|
||||
detail_json={
|
||||
**decision,
|
||||
"business_no": updated.shipping_case.business_no if updated.shipping_case else None,
|
||||
},
|
||||
))
|
||||
db.session.flush()
|
||||
return {**decision, "status": "auto_confirmed", "business_no": updated.shipping_case.business_no}
|
||||
|
||||
|
||||
def backfill_historical_task_customer(
|
||||
task: ShippingTask,
|
||||
*,
|
||||
customer_id: int,
|
||||
actor_id: int | None,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
为历史无业务单任务回填标准客户,但默认不生成历史业务编号。
|
||||
|
||||
Args:
|
||||
task: shipping_case_id 为空且 task_no 为历史技术号的任务。
|
||||
customer_id: 管理员确认的标准客户 ID。
|
||||
actor_id: 管理员审计 ID。
|
||||
Returns:
|
||||
回填后的 task_no、customer_id、business_no(None)。
|
||||
"""
|
||||
customer = db.session.get(ShippingCustomer, int(customer_id))
|
||||
if customer is None or customer.status != "active":
|
||||
raise ValueError("active customer is required")
|
||||
if task.shipping_case_id is not None:
|
||||
raise ValueError("historical backfill only supports tasks without a shipping case")
|
||||
case = ShippingCase(
|
||||
case_no=generate_shipping_case_no(),
|
||||
customer_id=customer.id,
|
||||
customer_name_snapshot=customer.standard_name,
|
||||
customer_short_code_snapshot=customer.short_code,
|
||||
numbering_status="historical_unnumbered",
|
||||
status="open",
|
||||
created_by_id=actor_id,
|
||||
)
|
||||
db.session.add(case)
|
||||
db.session.flush()
|
||||
task.shipping_case_id = case.id
|
||||
task.customer_resolution_status = "confirmed"
|
||||
task.customer_resolution_method = "historical_backfill"
|
||||
task.customer_confirmed_by = actor_id
|
||||
task.customer_confirmed_at = datetime.utcnow()
|
||||
db.session.add(ShippingTaskEvent(
|
||||
task_id=task.id,
|
||||
event_type="customer_historical_backfilled",
|
||||
detail_json={"customer_id": customer.id, "business_no": None},
|
||||
))
|
||||
db.session.commit()
|
||||
return {"task_no": task.task_no, "customer_id": customer.id, "business_no": None}
|
||||
|
||||
|
||||
def correct_numbered_task_customer(
|
||||
task: ShippingTask,
|
||||
*,
|
||||
customer_id: int,
|
||||
reason: str,
|
||||
actor_id: int | None,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
更正已编号业务单的标准客户,同时保留原号作废与替代关系。
|
||||
|
||||
核心逻辑:锁定原业务单并校验未上传 → 创建替代业务单和新号 → 迁移整条任务版本链 →
|
||||
清理当前版本的客户相关下游派生结果 → 写入新旧编号纠错审计;原业务号永不修改。
|
||||
|
||||
Args:
|
||||
task: 原业务号或技术号定位到的当前任务版本。
|
||||
customer_id: 管理员确认的正确启用客户 ID。
|
||||
reason: 必填纠错原因,写入审计事件。
|
||||
actor_id: 管理员审计 ID。
|
||||
Returns:
|
||||
原号、新号、替代业务单和受影响任务信息。
|
||||
Raises:
|
||||
ValidationError: 缺少原因、客户无效或客户未变化。
|
||||
ConflictError: 业务单未编号、已上传或已被替代。
|
||||
"""
|
||||
correction_reason = str(reason or "").strip()
|
||||
if not correction_reason:
|
||||
raise ValidationError(
|
||||
"Customer correction reason is required",
|
||||
code="SHIPPING.CUSTOMER_CORRECTION_REASON_REQUIRED",
|
||||
)
|
||||
if task.shipping_case_id is None:
|
||||
raise ConflictError(
|
||||
"Numbered shipping case is required for customer correction",
|
||||
code="SHIPPING.CUSTOMER_CORRECTION_NUMBER_REQUIRED",
|
||||
)
|
||||
|
||||
original_case = (
|
||||
db.session.query(ShippingCase)
|
||||
.filter(ShippingCase.id == int(task.shipping_case_id))
|
||||
.with_for_update()
|
||||
.one_or_none()
|
||||
)
|
||||
if original_case is None:
|
||||
raise NotFoundError("Shipping case not found", code="SHIPPING.CASE_NOT_FOUND")
|
||||
if not original_case.business_no:
|
||||
raise ConflictError(
|
||||
"Numbered shipping case is required for customer correction",
|
||||
code="SHIPPING.CUSTOMER_CORRECTION_NUMBER_REQUIRED",
|
||||
)
|
||||
existing_replacement = db.session.query(ShippingCase.id).filter_by(
|
||||
replaces_case_id=original_case.id,
|
||||
).first()
|
||||
if existing_replacement is not None or original_case.status == "voided":
|
||||
raise ConflictError(
|
||||
"Shipping case has already been replaced",
|
||||
code="SHIPPING.CUSTOMER_CORRECTION_ALREADY_REPLACED",
|
||||
)
|
||||
|
||||
customer = db.session.get(ShippingCustomer, int(customer_id))
|
||||
if customer is None:
|
||||
raise NotFoundError("Customer not found", code="SHIPPING.CUSTOMER_NOT_FOUND")
|
||||
if customer.status != "active":
|
||||
raise ValidationError("Inactive customer cannot be used", code="SHIPPING.CUSTOMER_INACTIVE")
|
||||
if original_case.customer_id == customer.id:
|
||||
raise ValidationError(
|
||||
"Corrected customer must differ from the current customer",
|
||||
code="SHIPPING.CUSTOMER_CORRECTION_UNCHANGED",
|
||||
)
|
||||
|
||||
versions = (
|
||||
db.session.query(ShippingTask)
|
||||
.filter_by(shipping_case_id=original_case.id)
|
||||
.order_by(ShippingTask.document_version.asc(), ShippingTask.id.asc())
|
||||
.with_for_update()
|
||||
.all()
|
||||
)
|
||||
if not versions:
|
||||
raise ConflictError(
|
||||
"Shipping case has no task versions",
|
||||
code="SHIPPING.CUSTOMER_CORRECTION_TASK_MISSING",
|
||||
)
|
||||
if any(
|
||||
version.process_status == "uploaded"
|
||||
or str(version.upload_status or "").lower() in {"uploaded", "succeeded", "success"}
|
||||
for version in versions
|
||||
):
|
||||
raise ConflictError(
|
||||
"Uploaded shipping cases require an external cancellation workflow before correction",
|
||||
code="SHIPPING.CUSTOMER_CORRECTION_UPLOADED_BLOCKED",
|
||||
)
|
||||
|
||||
old_business_no = str(original_case.business_no)
|
||||
replacement = ShippingCase(
|
||||
case_no=generate_shipping_case_no(),
|
||||
customer_id=customer.id,
|
||||
customer_name_snapshot=customer.standard_name,
|
||||
customer_short_code_snapshot=customer.short_code,
|
||||
numbering_status="pending",
|
||||
status="open",
|
||||
replaces_case_id=original_case.id,
|
||||
created_by_id=actor_id,
|
||||
)
|
||||
db.session.add(replacement)
|
||||
db.session.flush()
|
||||
new_business_no = assign_business_number(replacement)
|
||||
|
||||
original_case.status = "voided"
|
||||
original_case.numbering_status = "voided"
|
||||
now = datetime.utcnow()
|
||||
customer_fingerprint = hashlib.sha256(f"customer:{customer.id}".encode("ascii")).hexdigest()
|
||||
latest = max(versions, key=lambda item: (int(item.document_version or 1), int(item.id)))
|
||||
for version in versions:
|
||||
version.shipping_case_id = replacement.id
|
||||
version.customer_resolution_status = "confirmed"
|
||||
version.customer_resolution_method = "admin_correction"
|
||||
version.customer_identity_fingerprint = customer_fingerprint
|
||||
version.customer_confirmed_by = actor_id
|
||||
version.customer_confirmed_at = now
|
||||
db.session.add(ShippingTaskEvent(
|
||||
task_id=version.id,
|
||||
event_type="customer_correction_applied",
|
||||
detail_json={
|
||||
"old_case_id": original_case.id,
|
||||
"new_case_id": replacement.id,
|
||||
"old_business_no": old_business_no,
|
||||
"new_business_no": new_business_no,
|
||||
"old_customer_id": original_case.customer_id,
|
||||
"new_customer_id": customer.id,
|
||||
"reason": correction_reason,
|
||||
"actor_id": actor_id,
|
||||
},
|
||||
))
|
||||
|
||||
# 客户变化会使库存路由、匹配和导出失效;只重置当前版本,旧版本状态通过事件保留审计语义。
|
||||
latest.inventory_source_code = None
|
||||
latest.inventory_connector_type = None
|
||||
latest.inventory_site_id = None
|
||||
latest.inventory_warehouse_id = None
|
||||
latest.inventory_source_status = None
|
||||
latest.inventory_source_method = None
|
||||
latest.inventory_source_confirmed_by = None
|
||||
latest.inventory_source_confirmed_at = None
|
||||
latest.inventory_source_config_version = None
|
||||
latest.inventory_routing_fingerprint = None
|
||||
latest.inventory_rpa_consumed_run_no = None
|
||||
latest.inventory_snapshot_id = None
|
||||
latest.inventory_lines_json = None
|
||||
latest.match_status = None
|
||||
latest.shortage_json = None
|
||||
latest.line_results_json = None
|
||||
latest.export_file_path = None
|
||||
latest.export_file_name = None
|
||||
latest.freight_ref_no = None
|
||||
latest.upload_status = None
|
||||
latest.upload_mode = None
|
||||
latest.upload_attempt = 0
|
||||
latest.upload_started_at = None
|
||||
latest.upload_finished_at = None
|
||||
latest.upload_error_code = None
|
||||
latest.upload_error_message = None
|
||||
latest.upload_receipt_json = None
|
||||
latest.idempotency_key = None
|
||||
latest.process_status = "parsed"
|
||||
latest.current_step = None
|
||||
latest.review_status = None
|
||||
latest.pending_human_reason = None
|
||||
latest.error_message = None
|
||||
db.session.commit()
|
||||
return {
|
||||
"task_no": latest.task_no,
|
||||
"old_case_id": original_case.id,
|
||||
"new_case_id": replacement.id,
|
||||
"old_business_no": old_business_no,
|
||||
"new_business_no": new_business_no,
|
||||
"customer_id": customer.id,
|
||||
"affected_task_count": len(versions),
|
||||
}
|
||||
|
||||
|
||||
def get_auto_resolution_metrics() -> dict[str, Any]:
|
||||
"""汇总自动裁决、纠错和回填事件,供管理员监控、查询与降级判断。"""
|
||||
evaluated = db.session.query(ShippingTaskEvent.task_id).filter_by(
|
||||
event_type="customer_auto_resolution_evaluated",
|
||||
).distinct().count()
|
||||
confirmed = db.session.query(ShippingTaskEvent.task_id).filter_by(
|
||||
event_type="customer_auto_confirmed",
|
||||
).distinct().count()
|
||||
corrected = db.session.query(ShippingTaskEvent.task_id).filter_by(
|
||||
event_type="customer_correction_applied",
|
||||
).distinct().count()
|
||||
backfilled = db.session.query(ShippingTaskEvent.task_id).filter_by(
|
||||
event_type="customer_historical_backfilled",
|
||||
).distinct().count()
|
||||
recent_events = (
|
||||
db.session.query(ShippingTaskEvent, ShippingTask.task_no)
|
||||
.join(ShippingTask, ShippingTask.id == ShippingTaskEvent.task_id)
|
||||
.filter(ShippingTaskEvent.event_type.in_(CUSTOMER_AUDIT_EVENT_TYPES))
|
||||
.order_by(ShippingTaskEvent.id.desc())
|
||||
.limit(100)
|
||||
.all()
|
||||
)
|
||||
return {
|
||||
"enabled": auto_customer_resolution_enabled(),
|
||||
"rule_version": AUTO_RESOLUTION_VERSION,
|
||||
"evaluated_count": evaluated,
|
||||
"auto_confirmed_count": confirmed,
|
||||
"corrected_task_count": corrected,
|
||||
"historical_backfilled_count": backfilled,
|
||||
"auto_confirmation_rate": (confirmed / evaluated) if evaluated else None,
|
||||
"recent_events": [
|
||||
{
|
||||
"id": event.id,
|
||||
"task_no": task_no,
|
||||
"event_type": event.event_type,
|
||||
"detail": event.detail_json or {},
|
||||
"created_at": event.created_at.isoformat() if event.created_at else None,
|
||||
}
|
||||
for event, task_no in recent_events
|
||||
],
|
||||
}
|
||||
@@ -0,0 +1,231 @@
|
||||
"""
|
||||
backend/app/services/shipping_notice/customer_identity_gate.py
|
||||
|
||||
用途:货代任务标准客户确认、业务编号生成、候选查询与统一下游硬门禁。
|
||||
依赖:ShippingTask/Case/Customer/Event、business_numbering_service、统一 AppError、customer_normalization。
|
||||
逻辑:业务用户只能选择已启用标准客户;确认与业务编号在同一事务完成,并同步业务单全部任务版本。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
|
||||
from sqlalchemy import or_
|
||||
|
||||
from app import db
|
||||
from app.core.errors import AppError, ConflictError, NotFoundError, ValidationError
|
||||
from app.models import ShippingCase, ShippingCustomer, ShippingTask, ShippingTaskEvent
|
||||
from app.services.shipping_notice.customer_normalization import clean_text
|
||||
from app.services.shipping_notice.business_numbering_service import assign_business_number
|
||||
|
||||
CUSTOMER_GATE_ERROR_CODE = 'SHIPPING.CUSTOMER_CONFIRMATION_REQUIRED'
|
||||
|
||||
|
||||
def customer_identity_is_confirmed(task: ShippingTask) -> bool:
|
||||
"""判断任务是否通过客户 Gate;无业务单历史任务兼容放行。"""
|
||||
if task.shipping_case_id is None:
|
||||
return True
|
||||
case = task.shipping_case or db.session.get(ShippingCase, int(task.shipping_case_id))
|
||||
if case is None or case.customer_id is None:
|
||||
return False
|
||||
customer = db.session.get(ShippingCustomer, int(case.customer_id))
|
||||
return bool(customer and customer.status == 'active' and task.customer_resolution_status == 'confirmed')
|
||||
|
||||
|
||||
def assert_customer_identity_gate(task: ShippingTask, *, operation: str = 'continue') -> None:
|
||||
"""
|
||||
标准客户硬门禁;新业务单未确认时阻断库存、RPA、匹配、Excel 与上传。
|
||||
|
||||
Args:
|
||||
task: 当前发货任务;历史无业务单任务兼容放行。
|
||||
operation: 触发门禁的操作名,写入错误详情。
|
||||
Raises:
|
||||
AppError: 客户尚未确认、客户已停用或业务单关联无效。
|
||||
"""
|
||||
if customer_identity_is_confirmed(task):
|
||||
return
|
||||
case = task.shipping_case or (
|
||||
db.session.get(ShippingCase, int(task.shipping_case_id)) if task.shipping_case_id else None
|
||||
)
|
||||
raise AppError(
|
||||
code=CUSTOMER_GATE_ERROR_CODE,
|
||||
message='标准客户尚未确认,无法继续后续流程',
|
||||
http_status=409,
|
||||
details={
|
||||
'operation': operation,
|
||||
'task_no': task.task_no,
|
||||
'shipping_case_id': task.shipping_case_id,
|
||||
'customer_resolution_status': task.customer_resolution_status or 'pending',
|
||||
'customer_id': case.customer_id if case else None,
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
def list_customer_options(*, query: str = '', limit: int = 100) -> list[dict[str, Any]]:
|
||||
"""列出启用标准客户,供业务用户人工确认;不暴露识别证据和管理字段。"""
|
||||
customer_query = db.session.query(ShippingCustomer).filter_by(status='active')
|
||||
keyword = clean_text(query)
|
||||
if keyword:
|
||||
like = f'%{keyword}%'
|
||||
customer_query = customer_query.filter(
|
||||
or_(ShippingCustomer.standard_name.ilike(like), ShippingCustomer.short_code.ilike(like))
|
||||
)
|
||||
rows = customer_query.order_by(ShippingCustomer.standard_name.asc(), ShippingCustomer.id.asc()).limit(
|
||||
max(1, min(int(limit or 100), 200))
|
||||
).all()
|
||||
return [{'id': row.id, 'standard_name': row.standard_name, 'short_code': row.short_code} for row in rows]
|
||||
|
||||
|
||||
def confirm_task_customer(
|
||||
task: ShippingTask,
|
||||
*,
|
||||
customer_id: int,
|
||||
actor_id: int | None,
|
||||
resolution_method: str = 'manual',
|
||||
commit: bool = True,
|
||||
) -> ShippingTask:
|
||||
"""
|
||||
人工确认任务所属标准客户,并同步共享业务单下所有任务版本。
|
||||
|
||||
核心逻辑:锁定业务单 → 校验启用客户 → 原子分配业务号 → 同步 revision 任务确认状态和事件。
|
||||
客户确认与编号同事务提交,任何一步失败都不留下半确认状态。
|
||||
|
||||
Args:
|
||||
task: 待确认客户的任务。
|
||||
customer_id: 启用标准客户主键。
|
||||
actor_id: 人工操作人;自动规则可为空。
|
||||
resolution_method: manual/auto_rule 等审计方法。
|
||||
commit: 是否提交事务;批次编排传 False 由外层统一提交。
|
||||
"""
|
||||
if task.shipping_case_id is None:
|
||||
raise ConflictError(
|
||||
'Legacy tasks without a shipping case cannot confirm customer in this workflow',
|
||||
code='SHIPPING.CUSTOMER_CONFIRMATION_LEGACY_UNSUPPORTED',
|
||||
)
|
||||
case = (
|
||||
db.session.query(ShippingCase)
|
||||
.filter(ShippingCase.id == int(task.shipping_case_id))
|
||||
.with_for_update()
|
||||
.one_or_none()
|
||||
)
|
||||
if case is None:
|
||||
raise NotFoundError('Shipping case not found', code='SHIPPING.CASE_NOT_FOUND')
|
||||
customer = db.session.get(ShippingCustomer, int(customer_id))
|
||||
if customer is None:
|
||||
raise NotFoundError('Customer not found', code='SHIPPING.CUSTOMER_NOT_FOUND')
|
||||
if customer.status != 'active':
|
||||
raise ValidationError('Inactive customer cannot be confirmed', code='SHIPPING.CUSTOMER_INACTIVE')
|
||||
if case.business_no and case.customer_id not in {None, customer.id}:
|
||||
raise ConflictError(
|
||||
'Numbered shipping case customer cannot be changed silently',
|
||||
code='SHIPPING.CUSTOMER_NUMBERED_CASE_LOCKED',
|
||||
)
|
||||
|
||||
now = datetime.utcnow()
|
||||
previous_customer_id = case.customer_id
|
||||
number_was_assigned = bool(case.business_no)
|
||||
case.customer_id = customer.id
|
||||
case.customer_name_snapshot = customer.standard_name
|
||||
case.customer_short_code_snapshot = customer.short_code
|
||||
business_no = assign_business_number(case)
|
||||
fingerprint = hashlib.sha256(f'customer:{customer.id}'.encode('ascii')).hexdigest()
|
||||
tasks = db.session.query(ShippingTask).filter_by(shipping_case_id=case.id).all()
|
||||
for version in tasks:
|
||||
version.customer_resolution_status = 'confirmed'
|
||||
version.customer_resolution_method = resolution_method
|
||||
version.customer_identity_fingerprint = fingerprint
|
||||
version.customer_confirmed_by = actor_id
|
||||
version.customer_confirmed_at = now
|
||||
db.session.add(ShippingTaskEvent(
|
||||
task_id=version.id,
|
||||
event_type='customer_confirmed',
|
||||
detail_json={
|
||||
'customer_id': customer.id,
|
||||
'standard_name': customer.standard_name,
|
||||
'short_code': customer.short_code,
|
||||
'previous_customer_id': previous_customer_id,
|
||||
'method': resolution_method,
|
||||
'business_no': business_no,
|
||||
},
|
||||
))
|
||||
if not number_was_assigned:
|
||||
db.session.add(ShippingTaskEvent(
|
||||
task_id=version.id,
|
||||
event_type='business_number_assigned',
|
||||
detail_json={
|
||||
'business_no': business_no,
|
||||
'business_date': case.business_date.isoformat() if case.business_date else None,
|
||||
'sequence_value': case.sequence_value,
|
||||
'numbering_rule_version': case.numbering_rule_version,
|
||||
},
|
||||
))
|
||||
if commit:
|
||||
db.session.commit()
|
||||
return db.session.get(ShippingTask, int(task.id))
|
||||
db.session.flush()
|
||||
return task
|
||||
|
||||
|
||||
def customer_gate_tool_response(task: ShippingTask, *, operation: str) -> dict[str, Any] | None:
|
||||
"""Tool 公共入口将客户 Gate 转为 needs_human 响应,未阻断时返回 None。"""
|
||||
if customer_identity_is_confirmed(task):
|
||||
return None
|
||||
from app.services.shipping_notice.query_service import serialize_task_for_tool
|
||||
from app.services.shipping_notice.tool_response import tool_response
|
||||
|
||||
return tool_response(
|
||||
status='needs_human',
|
||||
task=task,
|
||||
message='标准客户尚未确认,请先选择正式客户后再继续。',
|
||||
data=serialize_task_for_tool(task),
|
||||
human_options=['confirm_customer'],
|
||||
checkpoint='customer_review',
|
||||
stop_agent_turn=True,
|
||||
forbidden_next_tools=[
|
||||
'ensure_inventory', 'parse_inventory', 'match_inventory',
|
||||
'generate_shipment_excel', 'upload_to_freight',
|
||||
],
|
||||
)
|
||||
|
||||
|
||||
def confirm_customer(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
"""
|
||||
Tool 入口确认标准客户。
|
||||
【AI 触发时机】:用户在 customer_review 检查点明确选择标准客户后调用。
|
||||
|
||||
Args:
|
||||
payload: 须含 task_id/customer_id,可含 user_id 作为审计人。
|
||||
Returns:
|
||||
Tool 标准响应;data.business_no 返回正式业务编号。
|
||||
"""
|
||||
from app.services.shipping_notice.query_service import resolve_task_from_payload, serialize_task_for_tool
|
||||
from app.services.shipping_notice.tool_response import tool_response
|
||||
|
||||
task = resolve_task_from_payload(payload)
|
||||
if task is None:
|
||||
return tool_response(status='failed', message='未找到任务编号')
|
||||
try:
|
||||
customer_id = int(payload.get('customer_id'))
|
||||
except (TypeError, ValueError):
|
||||
return tool_response(
|
||||
status='needs_human',
|
||||
task=task,
|
||||
message='请选择标准客户。',
|
||||
data=serialize_task_for_tool(task),
|
||||
human_options=['confirm_customer'],
|
||||
checkpoint='customer_review',
|
||||
stop_agent_turn=True,
|
||||
)
|
||||
updated = confirm_task_customer(
|
||||
task,
|
||||
customer_id=customer_id,
|
||||
actor_id=int(payload.get('user_id')) if payload.get('user_id') is not None else None,
|
||||
)
|
||||
return tool_response(
|
||||
status='ok',
|
||||
task=updated,
|
||||
message='标准客户已确认,可以继续库存与履约流程。',
|
||||
data=serialize_task_for_tool(updated),
|
||||
)
|
||||
@@ -0,0 +1,132 @@
|
||||
"""
|
||||
services/shipping_notice/customer_normalization.py
|
||||
|
||||
用途:统一客户名称、简码、邮箱、域名和识别证据的标准化与基础校验。
|
||||
依赖:re、unicodedata 标准库。
|
||||
逻辑:管理后台导入与运行期客户裁决共用,避免同一证据在不同入口产生不同匹配键。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
import unicodedata
|
||||
from typing import Any
|
||||
|
||||
from app.core.errors import ValidationError
|
||||
|
||||
SHORT_CODE_RE = re.compile(r'^[A-Z]{2,6}$')
|
||||
EMAIL_RE = re.compile(r'^[^@\s]+@[^@\s]+\.[^@\s]+$')
|
||||
PUBLIC_EMAIL_DOMAINS = frozenset({
|
||||
'126.com',
|
||||
'163.com',
|
||||
'gmail.com',
|
||||
'hotmail.com',
|
||||
'icloud.com',
|
||||
'live.com',
|
||||
'outlook.com',
|
||||
'qq.com',
|
||||
'yahoo.com',
|
||||
})
|
||||
IDENTIFIER_TYPES = frozenset({'name_alias', 'email', 'domain', 'template_fingerprint', 'address', 'contact'})
|
||||
|
||||
|
||||
def clean_text(value: Any) -> str:
|
||||
"""将任意输入规范为去首尾空白、合并内部空白的展示文本。"""
|
||||
text = unicodedata.normalize('NFKC', str(value or '')).strip()
|
||||
return re.sub(r'\s+', ' ', text)
|
||||
|
||||
|
||||
def normalize_customer_name(value: Any) -> str:
|
||||
"""生成不区分大小写和常见标点的客户名称匹配键。"""
|
||||
text = clean_text(value).upper()
|
||||
return re.sub(r'[\s\-_,.,。()()]+', '', text)
|
||||
|
||||
|
||||
def normalize_short_code(value: Any) -> str:
|
||||
"""
|
||||
校验并返回客户简码。
|
||||
|
||||
Args:
|
||||
value: 管理员输入的客户简码。
|
||||
Returns:
|
||||
2-6 位大写英文字母。
|
||||
Raises:
|
||||
ValidationError: 简码为空或格式不合法。
|
||||
"""
|
||||
code = clean_text(value).upper()
|
||||
if not SHORT_CODE_RE.fullmatch(code):
|
||||
raise ValidationError(
|
||||
'Customer short code must contain 2-6 uppercase letters',
|
||||
code='SHIPPING.CUSTOMER_SHORT_CODE_INVALID',
|
||||
details={'field': 'short_code'},
|
||||
)
|
||||
return code
|
||||
|
||||
|
||||
def normalize_email(value: Any) -> str:
|
||||
"""校验并返回小写完整邮箱地址。"""
|
||||
email = clean_text(value).lower()
|
||||
if not EMAIL_RE.fullmatch(email):
|
||||
raise ValidationError(
|
||||
'Invalid customer email',
|
||||
code='SHIPPING.CUSTOMER_EMAIL_INVALID',
|
||||
details={'field': 'identifier_value'},
|
||||
)
|
||||
return email
|
||||
|
||||
|
||||
def normalize_domain(value: Any) -> str:
|
||||
"""移除协议、路径与前导 www,返回小写邮箱/网站域名。"""
|
||||
domain = clean_text(value).lower()
|
||||
domain = re.sub(r'^https?://', '', domain).split('/', 1)[0].split('@')[-1].strip('.')
|
||||
if not domain or '.' not in domain or re.search(r'[^a-z0-9.-]', domain):
|
||||
raise ValidationError(
|
||||
'Invalid customer domain',
|
||||
code='SHIPPING.CUSTOMER_DOMAIN_INVALID',
|
||||
details={'field': 'identifier_value'},
|
||||
)
|
||||
return domain
|
||||
|
||||
|
||||
def is_public_email_domain(value: Any) -> bool:
|
||||
"""判断域名是否属于不可用于客户自动确认的公共邮箱。"""
|
||||
try:
|
||||
return normalize_domain(value) in PUBLIC_EMAIL_DOMAINS
|
||||
except ValidationError:
|
||||
return False
|
||||
|
||||
|
||||
def normalize_identifier(identifier_type: Any, value: Any) -> str:
|
||||
"""
|
||||
按证据类型生成稳定匹配键。
|
||||
|
||||
Args:
|
||||
identifier_type: name_alias/email/domain/template_fingerprint/address/contact。
|
||||
value: 原始识别证据。
|
||||
Returns:
|
||||
标准化匹配值。
|
||||
Raises:
|
||||
ValidationError: 类型或值不合法。
|
||||
"""
|
||||
kind = clean_text(identifier_type).lower()
|
||||
if kind not in IDENTIFIER_TYPES:
|
||||
raise ValidationError(
|
||||
'Unsupported customer identifier type',
|
||||
code='SHIPPING.CUSTOMER_IDENTIFIER_TYPE_INVALID',
|
||||
details={'identifier_type': kind},
|
||||
)
|
||||
if kind == 'email':
|
||||
return normalize_email(value)
|
||||
if kind == 'domain':
|
||||
return normalize_domain(value)
|
||||
if kind == 'name_alias':
|
||||
normalized = normalize_customer_name(value)
|
||||
else:
|
||||
normalized = clean_text(value).upper()
|
||||
if not normalized:
|
||||
raise ValidationError(
|
||||
'Customer identifier value is required',
|
||||
code='SHIPPING.CUSTOMER_IDENTIFIER_VALUE_REQUIRED',
|
||||
details={'field': 'identifier_value'},
|
||||
)
|
||||
return normalized
|
||||
@@ -0,0 +1,274 @@
|
||||
"""
|
||||
backend/app/services/shipping_notice/customer_shadow_resolution.py
|
||||
|
||||
用途:对订单 Candidate 执行只读客户影子识别,并提供质量报告与人工标签。
|
||||
依赖:客户主数据/识别证据、Candidate/Intake、customer_normalization。
|
||||
逻辑:确定性证据打分后只写 ShadowResolution;严禁修改 ShippingCase、ShippingTask 或业务编号。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections import defaultdict
|
||||
from datetime import datetime
|
||||
from email.utils import parseaddr
|
||||
import logging
|
||||
from typing import Any
|
||||
|
||||
from sqlalchemy import func
|
||||
|
||||
from app import db
|
||||
from app.core.errors import NotFoundError, ValidationError
|
||||
from app.models import (
|
||||
ShippingCustomer,
|
||||
ShippingCustomerIdentifier,
|
||||
ShippingCustomerShadowResolution,
|
||||
ShippingNoticeCandidate,
|
||||
ShippingNoticeIntake,
|
||||
)
|
||||
from app.services.shipping_notice.customer_normalization import (
|
||||
is_public_email_domain,
|
||||
normalize_customer_name,
|
||||
normalize_domain,
|
||||
normalize_email,
|
||||
normalize_identifier,
|
||||
)
|
||||
|
||||
RESOLUTION_VERSION = 'shadow-v1'
|
||||
EVIDENCE_WEIGHTS = {'email': 100.0, 'domain': 80.0, 'name_alias': 70.0, 'standard_name': 60.0}
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def _extract_evidence(candidate: ShippingNoticeCandidate, intake: ShippingNoticeIntake) -> list[dict[str, Any]]:
|
||||
"""从业务摘要和邮件元数据提取可审计证据,不把解析客户码当稳定客户键。"""
|
||||
structured = candidate.structured_result_json if isinstance(candidate.structured_result_json, dict) else {}
|
||||
summary = structured.get('business_summary') if isinstance(structured.get('business_summary'), dict) else {}
|
||||
intake_structured = intake.structured_result_json if isinstance(intake.structured_result_json, dict) else {}
|
||||
email_meta = intake_structured.get('email') if isinstance(intake_structured.get('email'), dict) else {}
|
||||
evidence: list[dict[str, Any]] = []
|
||||
customer_name = str(summary.get('customer_name') or '').strip()
|
||||
if customer_name:
|
||||
evidence.append({'type': 'name_alias', 'raw_value': customer_name, 'normalized_value': normalize_customer_name(customer_name)})
|
||||
template_fingerprint = str(
|
||||
structured.get('template_fingerprint')
|
||||
or intake_structured.get('template_fingerprint')
|
||||
or ''
|
||||
).strip()
|
||||
if template_fingerprint:
|
||||
evidence.append({
|
||||
'type': 'template_fingerprint',
|
||||
'raw_value': template_fingerprint,
|
||||
'normalized_value': normalize_identifier('template_fingerprint', template_fingerprint),
|
||||
})
|
||||
sender = parseaddr(str(email_meta.get('from') or ''))[1].strip().lower()
|
||||
if sender:
|
||||
try:
|
||||
normalized_email = normalize_email(sender)
|
||||
evidence.append({'type': 'email', 'raw_value': sender, 'normalized_value': normalized_email})
|
||||
domain = normalize_domain(normalized_email)
|
||||
if not is_public_email_domain(domain):
|
||||
evidence.append({'type': 'domain', 'raw_value': domain, 'normalized_value': domain})
|
||||
except ValidationError:
|
||||
pass
|
||||
return evidence
|
||||
|
||||
|
||||
def _rank_matches(evidence: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
||||
"""仅用启用客户和 approved 标识聚合确定性分数,返回稳定排序候选。"""
|
||||
scores: dict[int, float] = defaultdict(float)
|
||||
reasons: dict[int, list[dict[str, Any]]] = defaultdict(list)
|
||||
active_customers = db.session.query(ShippingCustomer).filter_by(status='active').all()
|
||||
active_ids = {int(item.id) for item in active_customers}
|
||||
by_name: dict[str, list[ShippingCustomer]] = defaultdict(list)
|
||||
for customer in active_customers:
|
||||
by_name[normalize_customer_name(customer.standard_name)].append(customer)
|
||||
for item in evidence:
|
||||
kind = str(item.get('type') or '')
|
||||
normalized = str(item.get('normalized_value') or '')
|
||||
if kind == 'name_alias' and normalized in by_name:
|
||||
for customer in by_name[normalized]:
|
||||
scores[customer.id] += EVIDENCE_WEIGHTS['standard_name']
|
||||
reasons[customer.id].append({'type': 'standard_name', 'value': normalized})
|
||||
identifiers = db.session.query(ShippingCustomerIdentifier).filter_by(
|
||||
identifier_type=kind,
|
||||
normalized_value=normalized,
|
||||
status='approved',
|
||||
).all()
|
||||
for identifier in identifiers:
|
||||
if int(identifier.customer_id) not in active_ids:
|
||||
continue
|
||||
scores[identifier.customer_id] += EVIDENCE_WEIGHTS.get(kind, 0.0)
|
||||
reasons[identifier.customer_id].append({'type': kind, 'identifier_id': identifier.id, 'value': normalized})
|
||||
customers = {item.id: item for item in active_customers}
|
||||
return sorted(
|
||||
[
|
||||
{
|
||||
'customer_id': customer_id,
|
||||
'standard_name': customers[customer_id].standard_name,
|
||||
'short_code': customers[customer_id].short_code,
|
||||
'score': score,
|
||||
'reasons': reasons[customer_id],
|
||||
}
|
||||
for customer_id, score in scores.items()
|
||||
],
|
||||
key=lambda item: (-float(item['score']), int(item['customer_id'])),
|
||||
)
|
||||
|
||||
|
||||
def refresh_candidate_shadow_resolution(candidate: ShippingNoticeCandidate) -> ShippingCustomerShadowResolution:
|
||||
"""幂等刷新 Candidate 影子识别;只写审计结果,不执行客户绑定或自动确认。"""
|
||||
intake = db.session.get(ShippingNoticeIntake, int(candidate.intake_id))
|
||||
if intake is None:
|
||||
raise NotFoundError('Shipping intake not found', code='SHIPPING_NOTICE.INTAKE_NOT_FOUND')
|
||||
evidence = _extract_evidence(candidate, intake)
|
||||
matches = _rank_matches(evidence)
|
||||
top_score = float(matches[0]['score']) if matches else None
|
||||
tied = [item for item in matches if float(item['score']) == top_score] if top_score is not None else []
|
||||
status = 'unmatched' if not matches else 'unique_candidate' if len(tied) == 1 else 'ambiguous'
|
||||
row = db.session.query(ShippingCustomerShadowResolution).filter_by(candidate_id=int(candidate.id)).first()
|
||||
if row is None:
|
||||
row = ShippingCustomerShadowResolution(candidate_id=int(candidate.id), intake_id=int(candidate.intake_id))
|
||||
db.session.add(row)
|
||||
row.intake_id = int(candidate.intake_id)
|
||||
row.resolution_version = RESOLUTION_VERSION
|
||||
row.status = status
|
||||
row.evidence_json = evidence
|
||||
row.candidate_matches_json = matches
|
||||
row.top_customer_id = int(matches[0]['customer_id']) if status == 'unique_candidate' else None
|
||||
row.top_score = top_score
|
||||
row.updated_at = datetime.utcnow()
|
||||
db.session.flush()
|
||||
return row
|
||||
|
||||
|
||||
def refresh_candidate_shadow_resolution_safely(candidate: ShippingNoticeCandidate) -> None:
|
||||
"""用 SAVEPOINT 隔离影子识别异常;任何失败均不得中断 Candidate 主流程。"""
|
||||
try:
|
||||
with db.session.begin_nested():
|
||||
refresh_candidate_shadow_resolution(candidate)
|
||||
except Exception as exc:
|
||||
logger.warning(
|
||||
'Customer shadow resolution failed candidate_id=%s error_type=%s',
|
||||
candidate.id,
|
||||
type(exc).__name__,
|
||||
)
|
||||
try:
|
||||
with db.session.begin_nested():
|
||||
row = db.session.query(ShippingCustomerShadowResolution).filter_by(
|
||||
candidate_id=int(candidate.id),
|
||||
).first()
|
||||
if row is None:
|
||||
row = ShippingCustomerShadowResolution(
|
||||
candidate_id=int(candidate.id),
|
||||
intake_id=int(candidate.intake_id),
|
||||
)
|
||||
db.session.add(row)
|
||||
row.resolution_version = RESOLUTION_VERSION
|
||||
row.status = 'failed'
|
||||
row.evidence_json = []
|
||||
row.candidate_matches_json = []
|
||||
row.top_customer_id = None
|
||||
row.top_score = None
|
||||
row.updated_at = datetime.utcnow()
|
||||
db.session.flush()
|
||||
except Exception:
|
||||
logger.warning(
|
||||
'Customer shadow failure audit could not be persisted candidate_id=%s',
|
||||
candidate.id,
|
||||
exc_info=True,
|
||||
)
|
||||
|
||||
|
||||
def label_shadow_resolution(resolution_id: int, *, customer_id: int, actor_id: int | None) -> dict[str, Any]:
|
||||
"""管理员为历史样本写入标准客户真值标签,供准确率计算,不触发业务绑定。"""
|
||||
row = db.session.get(ShippingCustomerShadowResolution, resolution_id)
|
||||
customer = db.session.get(ShippingCustomer, customer_id)
|
||||
if row is None:
|
||||
raise NotFoundError('Shadow resolution not found', code='SHIPPING.CUSTOMER_SHADOW_NOT_FOUND')
|
||||
if customer is None:
|
||||
raise NotFoundError('Customer not found', code='SHIPPING.CUSTOMER_NOT_FOUND')
|
||||
row.manual_customer_id = customer.id
|
||||
row.labeled_by_id = actor_id
|
||||
row.labeled_at = datetime.utcnow()
|
||||
db.session.commit()
|
||||
return serialize_shadow_resolution(row)
|
||||
|
||||
|
||||
def serialize_shadow_resolution(
|
||||
row: ShippingCustomerShadowResolution,
|
||||
*,
|
||||
candidate: ShippingNoticeCandidate | None = None,
|
||||
intake: ShippingNoticeIntake | None = None,
|
||||
manual_customer: ShippingCustomer | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""序列化影子识别结果;报告可传入批量预加载对象以避免 N+1。"""
|
||||
candidate = candidate or db.session.get(ShippingNoticeCandidate, int(row.candidate_id))
|
||||
intake = intake or db.session.get(ShippingNoticeIntake, int(row.intake_id))
|
||||
if manual_customer is None and row.manual_customer_id is not None:
|
||||
manual_customer = db.session.get(ShippingCustomer, int(row.manual_customer_id))
|
||||
return {
|
||||
'id': row.id,
|
||||
'candidate_id': row.candidate_id,
|
||||
'intake_id': row.intake_id,
|
||||
'candidate_no': candidate.candidate_no if candidate else None,
|
||||
'intake_no': intake.intake_no if intake else None,
|
||||
'resolution_version': row.resolution_version,
|
||||
'status': row.status,
|
||||
'evidence': row.evidence_json or [],
|
||||
'matches': row.candidate_matches_json or [],
|
||||
'top_customer_id': row.top_customer_id,
|
||||
'top_score': row.top_score,
|
||||
'manual_customer_id': row.manual_customer_id,
|
||||
'manual_customer_name': manual_customer.standard_name if manual_customer else None,
|
||||
'manual_customer_short_code': manual_customer.short_code if manual_customer else None,
|
||||
'is_correct': row.top_customer_id == row.manual_customer_id if row.manual_customer_id is not None else None,
|
||||
'labeled_at': row.labeled_at.isoformat() if row.labeled_at else None,
|
||||
}
|
||||
|
||||
|
||||
def get_shadow_quality_report(*, limit: int = 100) -> dict[str, Any]:
|
||||
"""返回影子识别分布和最近样本;准确率只以已人工标注样本为分母。"""
|
||||
query = db.session.query(ShippingCustomerShadowResolution)
|
||||
total = query.count()
|
||||
status_counts = dict(
|
||||
query.with_entities(ShippingCustomerShadowResolution.status, func.count())
|
||||
.group_by(ShippingCustomerShadowResolution.status)
|
||||
.all()
|
||||
)
|
||||
labeled = query.filter(ShippingCustomerShadowResolution.manual_customer_id.isnot(None)).all()
|
||||
correct = sum(item.top_customer_id == item.manual_customer_id for item in labeled)
|
||||
rows = query.order_by(ShippingCustomerShadowResolution.updated_at.desc()).limit(max(1, min(limit, 500))).all()
|
||||
candidate_ids = [int(item.candidate_id) for item in rows]
|
||||
intake_ids = [int(item.intake_id) for item in rows]
|
||||
manual_customer_ids = [int(item.manual_customer_id) for item in rows if item.manual_customer_id is not None]
|
||||
candidates = {
|
||||
item.id: item
|
||||
for item in db.session.query(ShippingNoticeCandidate).filter(ShippingNoticeCandidate.id.in_(candidate_ids)).all()
|
||||
} if candidate_ids else {}
|
||||
intakes = {
|
||||
item.id: item
|
||||
for item in db.session.query(ShippingNoticeIntake).filter(ShippingNoticeIntake.id.in_(intake_ids)).all()
|
||||
} if intake_ids else {}
|
||||
manual_customers = {
|
||||
item.id: item
|
||||
for item in db.session.query(ShippingCustomer).filter(ShippingCustomer.id.in_(manual_customer_ids)).all()
|
||||
} if manual_customer_ids else {}
|
||||
from app.services.shipping_notice.customer_auto_resolution import get_auto_resolution_metrics
|
||||
|
||||
auto_metrics = get_auto_resolution_metrics()
|
||||
return {
|
||||
'total': total,
|
||||
'status_counts': status_counts,
|
||||
'labeled_count': len(labeled),
|
||||
'correct_count': correct,
|
||||
'accuracy': (correct / len(labeled)) if labeled else None,
|
||||
'auto_bound_count': auto_metrics['auto_confirmed_count'],
|
||||
'items': [
|
||||
serialize_shadow_resolution(
|
||||
item,
|
||||
candidate=candidates.get(item.candidate_id),
|
||||
intake=intakes.get(item.intake_id),
|
||||
manual_customer=manual_customers.get(item.manual_customer_id),
|
||||
)
|
||||
for item in rows
|
||||
],
|
||||
}
|
||||
@@ -2,7 +2,7 @@
|
||||
backend/app/services/shipping_notice/document_candidate_persist.py
|
||||
|
||||
用途:阶段二——EML 附件派生 FileAsset、ShippingNoticeDocument / Candidate 幂等落库。
|
||||
依赖:file_assets.service、intake_business_parser、business_fingerprint、duplicate_detection、eml_parse。
|
||||
依赖:file_assets.service、intake_business_parser、business_fingerprint、duplicate_detection、客户影子识别、eml_parse。
|
||||
逻辑:由 intake_parse_workflow.run_intake_parse 在文本落库成功后调用;重试按
|
||||
(parent, content_hash)、(intake, attachment_key)、(intake, primary_document_id) 复用,不重复创建。
|
||||
Document↔派生资产的引用计数仅在 asset_id 变更时 +1/-1;
|
||||
@@ -270,6 +270,11 @@ def _upsert_candidate(
|
||||
row.duplicate_resolved_at = None
|
||||
row.updated_at = datetime.utcnow()
|
||||
db.session.flush()
|
||||
from app.services.shipping_notice.customer_shadow_resolution import (
|
||||
refresh_candidate_shadow_resolution_safely,
|
||||
)
|
||||
|
||||
refresh_candidate_shadow_resolution_safely(row)
|
||||
return row
|
||||
|
||||
|
||||
|
||||
@@ -169,6 +169,7 @@ def _clear_sheet_data_rows(ws, *, from_row: int = DATA_START_ROW) -> None:
|
||||
|
||||
|
||||
def _fill_pvmi_template(task: ShippingTask, path: Path) -> None:
|
||||
"""将业务号作为货代主引用写入 PVMI 模板,技术任务号仍用于系统追踪和文件名。"""
|
||||
wb = load_workbook(filename=str(path))
|
||||
header_ws = wb[HEADER_SHEET]
|
||||
detail_ws = wb[DETAIL_SHEET]
|
||||
@@ -186,7 +187,8 @@ def _fill_pvmi_template(task: ShippingTask, path: Path) -> None:
|
||||
|
||||
header_ws.cell(DATA_START_ROW, 5).value = _delivery_date_for_task(task)
|
||||
header_ws.cell(DATA_START_ROW, 6).value = _resolve_odm_id(task)
|
||||
header_ws.cell(DATA_START_ROW, 7).value = task.task_no
|
||||
business_ref = task.shipping_case.business_no if task.shipping_case and task.shipping_case.business_no else task.task_no
|
||||
header_ws.cell(DATA_START_ROW, 7).value = business_ref
|
||||
|
||||
notice_lines = [line for line in (task.lines_json or []) if isinstance(line, dict)]
|
||||
if not notice_lines:
|
||||
@@ -198,7 +200,7 @@ def _fill_pvmi_template(task: ShippingTask, path: Path) -> None:
|
||||
qty = line.get("qty")
|
||||
amount = line.get("amount")
|
||||
|
||||
detail_ws.cell(row_idx, 1).value = task.task_no
|
||||
detail_ws.cell(row_idx, 1).value = business_ref
|
||||
detail_ws.cell(row_idx, 2).value = line_no
|
||||
detail_ws.cell(row_idx, 4).value = _line_vendor_part_number(line)
|
||||
detail_ws.cell(row_idx, 5).value = qty if qty is not None else ""
|
||||
@@ -224,6 +226,7 @@ def _row_values(task: ShippingTask, line: dict | None) -> list:
|
||||
|
||||
|
||||
def _fill_legacy_template(task: ShippingTask, path: Path) -> None:
|
||||
"""填充 legacy 模板;技术任务号继续保留在导出文件名与系统记录中。"""
|
||||
wb = load_workbook(filename=str(path))
|
||||
ws = wb.active
|
||||
lines = task.lines_json or [None]
|
||||
@@ -235,6 +238,7 @@ def _fill_legacy_template(task: ShippingTask, path: Path) -> None:
|
||||
|
||||
|
||||
def _fill_blank_workbook(task: ShippingTask, path: Path) -> None:
|
||||
"""生成无模板工作簿;技术任务号继续保留在导出文件名与系统记录中。"""
|
||||
wb = Workbook()
|
||||
ws = wb.active
|
||||
ws.title = "Shipment"
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
services/shipping_notice/fulfillment_workflow.py
|
||||
|
||||
用途:发货通知履约阶段 — 库存匹配、Excel 导出、货代上传/RPA 与自动串联编排。
|
||||
依赖:match、export、rpa、query_service、inventory_workflow、inventory_mapping_workflow、tool_common、tool_response。
|
||||
依赖:customer_identity_gate、match、export、rpa、query_service、inventory_workflow、inventory_mapping_workflow、tool_common、tool_response。
|
||||
逻辑:tools.py 门面 re-export;库存就绪后由 inventory_workflow 委托 try_auto_chain_after_match。
|
||||
"""
|
||||
|
||||
@@ -40,6 +40,7 @@ from app.services.shipping_notice.rpa_attempts import (
|
||||
upload_rpa_attempts,
|
||||
)
|
||||
from app.services.shipping_notice.inventory_source_gate import assert_inventory_source_gate, is_inventory_source_stable
|
||||
from app.services.shipping_notice.customer_identity_gate import customer_gate_tool_response
|
||||
from app.services.shipping_notice.state_machine import TaskTransition, apply_task_transition
|
||||
from app.services.shipping_notice.tool_common import prepend_tool_message, set_task_step_progress
|
||||
from app.services.shipping_notice.tool_response import tool_response
|
||||
@@ -207,6 +208,10 @@ def match_inventory(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
if not task:
|
||||
return tool_response(status="failed", message=t("workflow.fulfillment.task_not_found", lang=lang))
|
||||
|
||||
customer_gate = customer_gate_tool_response(task, operation='match_inventory')
|
||||
if customer_gate is not None:
|
||||
return customer_gate
|
||||
|
||||
# [STEP 1] 先确认字段对齐与库存快照是否已经就绪。
|
||||
# 若还停在映射确认阶段或完全没有库存,就不能直接进入匹配计算。
|
||||
if awaiting_inventory_mapping_confirm(task):
|
||||
@@ -374,6 +379,10 @@ def generate_excel(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
if not task:
|
||||
return tool_response(status="failed", message=t("workflow.fulfillment.task_not_found", lang=lang))
|
||||
|
||||
customer_gate = customer_gate_tool_response(task, operation='generate_excel')
|
||||
if customer_gate is not None:
|
||||
return customer_gate
|
||||
|
||||
if not is_inventory_source_stable(task):
|
||||
return tool_response(
|
||||
status="failed",
|
||||
@@ -460,6 +469,10 @@ def upload_to_freight(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
if not task:
|
||||
return tool_response(status="failed", message=t("workflow.fulfillment.task_not_found", lang=lang))
|
||||
|
||||
customer_gate = customer_gate_tool_response(task, operation='upload_to_freight')
|
||||
if customer_gate is not None:
|
||||
return customer_gate
|
||||
|
||||
if not is_inventory_source_stable(task):
|
||||
return tool_response(
|
||||
status="failed",
|
||||
|
||||
@@ -71,7 +71,6 @@ def parse_intake_business_summary(
|
||||
'source_type': str(line.get('source_type') or '').strip() or None,
|
||||
'customer_sku': str(line.get('customer_sku') or '').strip() or None,
|
||||
'vendor_part_number': str(line.get('vendor_part_number') or '').strip() or None,
|
||||
'hub_code': str(line.get('hub_code') or '').strip() or None,
|
||||
}
|
||||
for line in lines
|
||||
if isinstance(line, dict)
|
||||
|
||||
@@ -2,8 +2,8 @@
|
||||
backend/app/services/shipping_notice/intake_service.py
|
||||
|
||||
用途:发货通知接入记录(ShippingNoticeIntake)业务编排(含重复决策投影与权限)。
|
||||
依赖:file_assets.service、intake_parse_workflow、jobs.queue、models、duplicate_detection、
|
||||
attachment_integrity。
|
||||
依赖:file_assets.service、intake_parse_workflow、order_extraction、jobs.queue、models、
|
||||
duplicate_detection、attachment_integrity。
|
||||
逻辑:由 workspace API 与 chat action 调用;解析 Job 由 intake_parse_workflow 执行;
|
||||
创建 Intake:SAVEPOINT 插入 + IntegrityError 回落,mutate/enqueue 前 FOR UPDATE;
|
||||
cancelled/expired 拒绝复活;重投仅复用 queued Job(与 retry 同口径);
|
||||
@@ -54,6 +54,30 @@ def _intake_ttl_hours() -> int:
|
||||
return max(int(current_app.config.get('SHIPPING_NOTICE_INTAKE_TTL_HOURS', 72) or 72), 1)
|
||||
|
||||
|
||||
def _expire_order_extractions_for_read(
|
||||
*,
|
||||
user_id: int,
|
||||
intake_nos: list[str] | None = None,
|
||||
conversation_id: str | None = None,
|
||||
) -> int:
|
||||
"""
|
||||
在 Intake 读取入口惰性回收订单识别超时状态。
|
||||
|
||||
核心逻辑:委托 order_extraction 使用数据库快照和配置超时值完成带锁收口;
|
||||
读取接口无需依赖进程内定时器,服务重启后仍可恢复失败终态。
|
||||
|
||||
Returns:
|
||||
本次由 extracting 收口为 failed 的 Intake 数量。
|
||||
"""
|
||||
from app.services.shipping_notice.order_extraction import expire_stale_order_extractions
|
||||
|
||||
return expire_stale_order_extractions(
|
||||
user_id=user_id,
|
||||
intake_nos=intake_nos,
|
||||
conversation_id=conversation_id,
|
||||
)
|
||||
|
||||
|
||||
def generate_intake_no() -> str:
|
||||
"""生成 SNI-YYYYMMDD-XXXXXXXX 格式接入编号。"""
|
||||
return f"SNI-{datetime.utcnow().strftime('%Y%m%d')}-{uuid.uuid4().hex[:8].upper()}"
|
||||
@@ -230,6 +254,7 @@ def get_intake_for_user(intake_no: str, user_id: int) -> ShippingNoticeIntake:
|
||||
|
||||
def get_intake_detail(*, user_id: int, intake_no: str) -> dict[str, Any]:
|
||||
"""查询单个接入记录详情(含资产摘要与附件全文)。"""
|
||||
_expire_order_extractions_for_read(user_id=user_id, intake_nos=[intake_no])
|
||||
intake = get_intake_for_user(intake_no, user_id)
|
||||
asset = db.session.get(FileAsset, intake.asset_id)
|
||||
if not asset:
|
||||
@@ -387,6 +412,8 @@ def create_shipping_notice_intake(
|
||||
|
||||
def list_active_intakes_for_conversation(*, user_id: int, conversation_id: str | None) -> list[dict[str, Any]]:
|
||||
"""列出会话下未消费的活跃接入记录,供页面恢复。"""
|
||||
conv = str(conversation_id or '').strip()
|
||||
_expire_order_extractions_for_read(user_id=user_id, conversation_id=conv or None)
|
||||
query = db.session.query(ShippingNoticeIntake, FileAsset).join(
|
||||
FileAsset, FileAsset.id == ShippingNoticeIntake.asset_id
|
||||
).filter(
|
||||
@@ -394,7 +421,6 @@ def list_active_intakes_for_conversation(*, user_id: int, conversation_id: str |
|
||||
ShippingNoticeIntake.parse_status.in_(tuple(ACTIVE_INTAKE_STATUSES - {'consumed', 'expired', 'cancelled'})),
|
||||
ShippingNoticeIntake.consumed_at.is_(None),
|
||||
)
|
||||
conv = str(conversation_id or '').strip()
|
||||
if conv:
|
||||
query = query.filter(ShippingNoticeIntake.conversation_id == conv)
|
||||
rows = query.order_by(ShippingNoticeIntake.created_at.desc()).limit(50).all()
|
||||
@@ -406,6 +432,7 @@ def get_intake_statuses(*, user_id: int, intake_nos: list[str]) -> list[dict[str
|
||||
normalized = [str(item or '').strip().upper() for item in intake_nos if str(item or '').strip()]
|
||||
if not normalized:
|
||||
return []
|
||||
_expire_order_extractions_for_read(user_id=user_id, intake_nos=normalized)
|
||||
rows = (
|
||||
db.session.query(ShippingNoticeIntake, FileAsset)
|
||||
.join(FileAsset, FileAsset.id == ShippingNoticeIntake.asset_id)
|
||||
|
||||
@@ -232,7 +232,7 @@ def save_batch_inventory_upload(task: ShippingTask, upload: FileStorage) -> Ship
|
||||
share_mode="task_only",
|
||||
line_count=0,
|
||||
source_code=source_code,
|
||||
source_type=str(task.inventory_source_type or "").strip() or None,
|
||||
source_type=str(task.inventory_connector_type or "").strip() or None,
|
||||
site_id=site_id,
|
||||
warehouse_id=warehouse_id,
|
||||
source_config_version=task.inventory_source_config_version or get_inventory_sources_config_version(),
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
services/shipping_notice/inventory_rpa_workflow.py
|
||||
|
||||
用途:发货通知库存 RPA 编排(触发导出、等待/超时、回调落盘)。
|
||||
依赖:rpa、rpa_attempts、inventory_snapshot、inventory_mapping_workflow、query_service、tool_common、state_machine、tool_response。
|
||||
依赖:customer_identity_gate、rpa、rpa_attempts、inventory_snapshot、inventory_mapping_workflow、query_service、tool_common、state_machine、tool_response。
|
||||
逻辑:inventory_workflow.ensure_inventory 在 mode=auto/retry_rpa 时委托本模块;tools 门面 re-export rpa_report_inventory。
|
||||
"""
|
||||
|
||||
@@ -55,6 +55,10 @@ from app.services.shipping_notice.inventory_source_gate import (
|
||||
task_needs_parse_review,
|
||||
)
|
||||
from app.services.shipping_notice.inventory_source_rules import task_rpa_inventory_source
|
||||
from app.services.shipping_notice.customer_identity_gate import (
|
||||
assert_customer_identity_gate,
|
||||
customer_gate_tool_response,
|
||||
)
|
||||
from app.services.shipping_notice.inventory_sources import build_rpa_inventory_source
|
||||
from app.services.shipping_notice.query_service import (
|
||||
resolve_task_from_payload,
|
||||
@@ -157,7 +161,7 @@ def _try_reuse_inventory_snapshot(
|
||||
task,
|
||||
snapshot,
|
||||
reason="reuse_latest",
|
||||
audit_payload={"mode": mode, "source_type": rpa_source.get("source_type")},
|
||||
audit_payload={"mode": mode, "connector_type": rpa_source.get("connector_type")},
|
||||
)
|
||||
if not link:
|
||||
return None
|
||||
@@ -695,8 +699,9 @@ def _validate_rpa_callback_round(task: ShippingTask, payload: dict[str, Any]) ->
|
||||
|
||||
|
||||
def _validate_rpa_callback_gate(task: ShippingTask) -> dict[str, Any] | None:
|
||||
"""校验库存源门禁(skipped/failed/success 共用)。"""
|
||||
"""校验客户与库存源门禁(skipped/failed/success 共用)。"""
|
||||
try:
|
||||
assert_customer_identity_gate(task, operation='rpa_inventory_callback')
|
||||
assert_inventory_source_gate(task, operation="rpa_inventory_callback")
|
||||
except AppError as exc:
|
||||
return tool_response(
|
||||
@@ -924,7 +929,7 @@ def confirm_inventory_source(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
"inventory_source_confirmed",
|
||||
{
|
||||
"source_code": task.inventory_source_code,
|
||||
"source_type": task.inventory_source_type,
|
||||
"connector_type": task.inventory_connector_type,
|
||||
"site_id": task.inventory_site_id,
|
||||
"warehouse_id": task.inventory_warehouse_id,
|
||||
"confirmed_by": confirmed_by or "integration_tool",
|
||||
@@ -989,6 +994,10 @@ def ensure_inventory_via_rpa(task: ShippingTask, *, mode: str) -> dict[str, Any]
|
||||
from app.services.shipping_notice.inventory_mapping_workflow import inventory_loaded_response
|
||||
manual_retry_round = mode == "retry_rpa"
|
||||
|
||||
customer_gate = customer_gate_tool_response(task, operation='ensure_inventory_via_rpa')
|
||||
if customer_gate is not None:
|
||||
return customer_gate
|
||||
|
||||
# [STEP 0] 库存源须在订单解析阶段已确定;RPA 只读取独立字段。
|
||||
try:
|
||||
assert_inventory_source_gate(task, operation="ensure_inventory_via_rpa")
|
||||
|
||||
@@ -351,7 +351,7 @@ def create_inventory_snapshot_from_rpa(
|
||||
source_config_version=get_inventory_sources_config_version(),
|
||||
identity_status="pending" if success else "unknown",
|
||||
source_code=source_code or None,
|
||||
source_type=str(source.get("source_type") or "").strip() or None,
|
||||
source_type=str(source.get("connector_type") or "").strip() or None,
|
||||
snapshot_status=snapshot_status,
|
||||
exported_at=exported_at,
|
||||
expires_at=snapshot_expires_at(exported_at) if success else None,
|
||||
|
||||
@@ -61,13 +61,13 @@ def is_inventory_source_stable(task: ShippingTask) -> bool:
|
||||
code = str(task.inventory_source_code or "").strip().upper()
|
||||
if not code:
|
||||
return False
|
||||
source_type = str(task.inventory_source_type or "").strip()
|
||||
if not source_type:
|
||||
connector_type = str(task.inventory_connector_type or "").strip()
|
||||
if not connector_type:
|
||||
return False
|
||||
source = get_inventory_source(code)
|
||||
if not source:
|
||||
return False
|
||||
if source_type != str(source.get("source_type") or "").strip():
|
||||
if connector_type != str(source.get("connector_type") or "").strip():
|
||||
return False
|
||||
|
||||
site_id = str(task.inventory_site_id or "").strip().upper()
|
||||
@@ -135,7 +135,7 @@ def _adjudication_from_stable_task(task: ShippingTask) -> InventorySourceAdjudic
|
||||
status=str(task.inventory_source_status or "").strip(),
|
||||
method=str(task.inventory_source_method or "").strip() or None,
|
||||
source_code=str(task.inventory_source_code or "").strip().upper() or None,
|
||||
source_type=str(task.inventory_source_type or "").strip() or None,
|
||||
connector_type=str(task.inventory_connector_type or "").strip() or None,
|
||||
site_id=str(task.inventory_site_id or "").strip().upper() or None,
|
||||
warehouse_id=str(task.inventory_warehouse_id or "").strip().upper() or None,
|
||||
config_version=str(task.inventory_source_config_version or "").strip() or None,
|
||||
@@ -166,7 +166,7 @@ def apply_inventory_source_adjudication(
|
||||
|
||||
if adjudication.status in STABLE_INVENTORY_SOURCE_STATUSES and adjudication.source_code:
|
||||
task.inventory_source_code = adjudication.source_code
|
||||
task.inventory_source_type = adjudication.source_type
|
||||
task.inventory_connector_type = adjudication.connector_type
|
||||
task.inventory_site_id = adjudication.site_id
|
||||
task.inventory_warehouse_id = adjudication.warehouse_id or None
|
||||
if adjudication.status == "user_confirmed" and confirmed_by_user_id:
|
||||
@@ -174,7 +174,7 @@ def apply_inventory_source_adjudication(
|
||||
task.inventory_source_confirmed_at = datetime.utcnow()
|
||||
elif adjudication.status not in STABLE_INVENTORY_SOURCE_STATUSES:
|
||||
task.inventory_source_code = None
|
||||
task.inventory_source_type = None
|
||||
task.inventory_connector_type = None
|
||||
task.inventory_site_id = None
|
||||
task.inventory_warehouse_id = None
|
||||
payload = dict(task.step_payload_json or {})
|
||||
@@ -233,7 +233,7 @@ def adjudicate_and_apply_inventory_source(task: ShippingTask) -> InventorySource
|
||||
status="user_confirmed",
|
||||
method="user_confirmed",
|
||||
source_code=adjudication.source_code,
|
||||
source_type=adjudication.source_type,
|
||||
connector_type=adjudication.connector_type,
|
||||
site_id=adjudication.site_id,
|
||||
warehouse_id=adjudication.warehouse_id,
|
||||
config_version=adjudication.config_version,
|
||||
|
||||
@@ -31,7 +31,7 @@ class ResolvedInventoryIdentity:
|
||||
"""稳定库存源四元组中的站点/库位解析结果。"""
|
||||
|
||||
source_code: str
|
||||
source_type: str
|
||||
connector_type: str
|
||||
site_id: str
|
||||
warehouse_id: str
|
||||
|
||||
@@ -84,7 +84,7 @@ def _resolve_crane_warehouse_id(source: dict[str, Any], context: dict[str, Any])
|
||||
ok=True,
|
||||
identity=ResolvedInventoryIdentity(
|
||||
source_code=str(source.get("source_code") or "").strip().upper(),
|
||||
source_type=str(source.get("source_type") or "").strip(),
|
||||
connector_type=str(source.get("connector_type") or "").strip(),
|
||||
site_id=site_id,
|
||||
warehouse_id=matched[0],
|
||||
),
|
||||
@@ -107,11 +107,11 @@ def resolve_inventory_source_identity(
|
||||
核心逻辑:DSV 使用配置显式声明;Crane 通过别名唯一命中推导库位。
|
||||
"""
|
||||
source_code = str(source.get("source_code") or "").strip().upper()
|
||||
source_type = str(source.get("source_type") or "").strip()
|
||||
if not source_code or not source_type:
|
||||
connector_type = str(source.get("connector_type") or "").strip()
|
||||
if not source_code or not connector_type:
|
||||
return InventoryIdentityResolution(ok=False, reason="source_incomplete")
|
||||
|
||||
if source_type == "crane_footprint":
|
||||
if connector_type == "crane_footprint":
|
||||
return _resolve_crane_warehouse_id(source, context)
|
||||
|
||||
site_id = str(source.get("site_id") or "").strip().upper()
|
||||
@@ -122,7 +122,7 @@ def resolve_inventory_source_identity(
|
||||
ok=True,
|
||||
identity=ResolvedInventoryIdentity(
|
||||
source_code=source_code,
|
||||
source_type=source_type,
|
||||
connector_type=connector_type,
|
||||
site_id=site_id,
|
||||
warehouse_id=warehouse_id,
|
||||
),
|
||||
@@ -145,8 +145,8 @@ def identity_matches_config(
|
||||
return False
|
||||
if cfg_site and task_site != cfg_site:
|
||||
return False
|
||||
source_type = str(source.get("source_type") or "").strip()
|
||||
if source_type == "crane_footprint":
|
||||
connector_type = str(source.get("connector_type") or "").strip()
|
||||
if connector_type == "crane_footprint":
|
||||
if context is None:
|
||||
return False
|
||||
resolution = resolve_inventory_source_identity(source, context)
|
||||
|
||||
@@ -2,8 +2,8 @@
|
||||
services/shipping_notice/inventory_source_rules.py
|
||||
|
||||
用途:根据发货通知路由线索对库存源做确定性裁决。
|
||||
依赖:inventory_sources、ShippingTask 独立字段与 step_payload_json。
|
||||
逻辑:Dify/LLM 只提供路由线索;本模块负责唯一性判断、冲突检测与人工确认复核。
|
||||
依赖:inventory_sources、ShippingTask 目的地字段、订单行 source_type 与 step_payload_json。
|
||||
逻辑:Dify/LLM 只提供行级可选路由线索;本模块负责唯一性判断、冲突检测与人工确认复核。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -33,7 +33,7 @@ class InventorySourceAdjudication:
|
||||
status: str
|
||||
method: str | None = None
|
||||
source_code: str | None = None
|
||||
source_type: str | None = None
|
||||
connector_type: str | None = None
|
||||
site_id: str | None = None
|
||||
warehouse_id: str | None = None
|
||||
config_version: str | None = None
|
||||
@@ -103,7 +103,14 @@ def _extract_destination_object(candidates: list[str], value: Any) -> None:
|
||||
def extract_destination_candidates(task: ShippingTask) -> list[str]:
|
||||
"""
|
||||
从任务解析结果提取目的地/港口/仓库候选。
|
||||
【AI 触发时机】:订单解析后由裁决服务调用,Dify 输出与后端字段都作为候选证据。
|
||||
【AI 触发时机】:订单解析后由裁决服务调用,Dify 行级 source_type 与目的地字段都作为候选证据。
|
||||
|
||||
核心逻辑:只读取 orders[].lines[].source_type,禁止使用 Task.source_type;
|
||||
Task.source_type 表示 PDF/manual 等接入来源,不是库存源路由证据。
|
||||
Args:
|
||||
task: 待裁决库存源的发货任务。
|
||||
Returns:
|
||||
去重并标准化后的 match_aliases 候选。
|
||||
"""
|
||||
candidates: list[str] = []
|
||||
payload = task.step_payload_json if isinstance(task.step_payload_json, dict) else {}
|
||||
@@ -121,6 +128,7 @@ def extract_destination_candidates(task: ShippingTask) -> list[str]:
|
||||
_extract_destination_object(candidates, line.get("destination"))
|
||||
for key in ("destination_port", "destination_city", "destination_country", "warehouse_hint", "ship_to", "raw_text"):
|
||||
_append_candidate(candidates, line.get(key))
|
||||
_append_candidate(candidates, line.get("source_type"))
|
||||
return candidates
|
||||
|
||||
|
||||
@@ -147,7 +155,7 @@ def _candidate_summary(source: dict[str, Any], *, score: int = 0, matched_by: st
|
||||
"display_name": source.get("display_name"),
|
||||
"site_id": source.get("site_id"),
|
||||
"warehouse_id": source.get("warehouse_id"),
|
||||
"source_type": source.get("source_type"),
|
||||
"connector_type": source.get("connector_type"),
|
||||
"match_score": score,
|
||||
"matched_by": matched_by,
|
||||
}
|
||||
@@ -304,7 +312,7 @@ def _stable_from_source(
|
||||
status="resolved",
|
||||
method=method,
|
||||
source_code=identity.source_code,
|
||||
source_type=identity.source_type,
|
||||
connector_type=identity.connector_type,
|
||||
site_id=identity.site_id,
|
||||
warehouse_id=identity.warehouse_id,
|
||||
config_version=config_version,
|
||||
@@ -328,8 +336,8 @@ def adjudicate_inventory_source(task: ShippingTask) -> InventorySourceAdjudicati
|
||||
for source in list_inventory_sources():
|
||||
if _source_field_excluded(source, context):
|
||||
continue
|
||||
source_type = str(source.get("source_type") or "").strip()
|
||||
if source_type == "dsv360" and (
|
||||
connector_type = str(source.get("connector_type") or "").strip()
|
||||
if connector_type == "dsv360" and (
|
||||
not str(source.get("site_id") or "").strip()
|
||||
or not str(source.get("warehouse_id") or "").strip()
|
||||
):
|
||||
@@ -440,7 +448,7 @@ def confirm_inventory_source_by_code(task: ShippingTask, source_code: str) -> In
|
||||
conflicts=["source_code_not_found"],
|
||||
reason="source_code_not_found",
|
||||
)
|
||||
if str(source.get("source_type") or "").strip() == "dsv360" and (
|
||||
if str(source.get("connector_type") or "").strip() == "dsv360" and (
|
||||
not str(source.get("site_id") or "").strip() or not str(source.get("warehouse_id") or "").strip()
|
||||
):
|
||||
return InventorySourceAdjudication(
|
||||
@@ -471,7 +479,7 @@ def confirm_inventory_source_by_code(task: ShippingTask, source_code: str) -> In
|
||||
status="user_confirmed",
|
||||
method="user_confirmed",
|
||||
source_code=identity.source_code,
|
||||
source_type=identity.source_type,
|
||||
connector_type=identity.connector_type,
|
||||
site_id=identity.site_id,
|
||||
warehouse_id=identity.warehouse_id,
|
||||
config_version=get_inventory_sources_config_version(),
|
||||
@@ -520,7 +528,7 @@ def save_task_rpa_inventory_source(
|
||||
status="user_confirmed",
|
||||
method="user_confirmed",
|
||||
source_code=identity.source_code,
|
||||
source_type=identity.source_type,
|
||||
connector_type=identity.connector_type,
|
||||
site_id=identity.site_id,
|
||||
warehouse_id=identity.warehouse_id,
|
||||
config_version=get_inventory_sources_config_version(),
|
||||
|
||||
@@ -16,7 +16,7 @@ from typing import Any
|
||||
import yaml
|
||||
from flask import current_app
|
||||
|
||||
_VALID_SOURCE_TYPES = {
|
||||
_VALID_CONNECTOR_TYPES = {
|
||||
"dsv360": "dsv360",
|
||||
"crane_footprint": "crane_footprint",
|
||||
}
|
||||
@@ -31,7 +31,7 @@ def _canonical_source_for_digest(source: dict[str, Any]) -> dict[str, Any]:
|
||||
match_cfg = source.get("match") if isinstance(source.get("match"), dict) else {}
|
||||
return {
|
||||
"source_code": source.get("source_code"),
|
||||
"source_type": source.get("source_type"),
|
||||
"connector_type": source.get("connector_type"),
|
||||
"site_id": source.get("site_id"),
|
||||
"warehouse_id": source.get("warehouse_id"),
|
||||
"warehouse_resolution": source.get("warehouse_resolution"),
|
||||
@@ -127,13 +127,13 @@ def _build_legacy_query(source: dict[str, Any]) -> dict[str, Any]:
|
||||
"""
|
||||
navigation = dict(source.get("navigation") or {})
|
||||
query: dict[str, Any] = {}
|
||||
source_type = str(source.get("source_type") or "").strip().lower()
|
||||
connector_type = str(source.get("connector_type") or "").strip().lower()
|
||||
|
||||
if source_type == "dsv360":
|
||||
if connector_type == "dsv360":
|
||||
for key in ("program_group", "program_label", "report_group", "report_name"):
|
||||
if navigation.get(key):
|
||||
query[key] = navigation[key]
|
||||
elif source_type == "crane_footprint":
|
||||
elif connector_type == "crane_footprint":
|
||||
if navigation.get("report_name"):
|
||||
query["report_name"] = navigation["report_name"]
|
||||
query["project_code"] = navigation.get("project_code")
|
||||
@@ -188,18 +188,20 @@ def _validate_source(raw: dict[str, Any], *, seen_codes: set[str]) -> dict[str,
|
||||
raise InventorySourceConfigError(f"duplicate source_code: {source_code}")
|
||||
seen_codes.add(source_code)
|
||||
|
||||
source_type = str(raw.get("source_type") or "").strip().lower()
|
||||
if source_type not in _VALID_SOURCE_TYPES:
|
||||
raise InventorySourceConfigError(f"{source_code}: source_type must be dsv360 or crane_footprint")
|
||||
connector_type = str(raw.get("connector_type") or "").strip().lower()
|
||||
if connector_type not in _VALID_CONNECTOR_TYPES:
|
||||
raise InventorySourceConfigError(
|
||||
f"{source_code}: connector_type must be dsv360 or crane_footprint"
|
||||
)
|
||||
|
||||
warehouse_id = str(raw.get("warehouse_id") or "").strip().upper()
|
||||
site_id = str(raw.get("site_id") or "").strip().upper()
|
||||
if source_type == "dsv360":
|
||||
if connector_type == "dsv360":
|
||||
if not site_id:
|
||||
raise InventorySourceConfigError(f"{source_code}: site_id is required for dsv360")
|
||||
if not warehouse_id:
|
||||
raise InventorySourceConfigError(f"{source_code}: warehouse_id is required for dsv360")
|
||||
elif source_type == "crane_footprint":
|
||||
elif connector_type == "crane_footprint":
|
||||
if not site_id:
|
||||
raise InventorySourceConfigError(f"{source_code}: site_id is required for crane_footprint")
|
||||
aliases = [str(alias).strip() for alias in (raw.get("match_aliases") or []) if str(alias).strip()]
|
||||
@@ -234,7 +236,7 @@ def _validate_source(raw: dict[str, Any], *, seen_codes: set[str]) -> dict[str,
|
||||
|
||||
normalized = {
|
||||
"source_code": source_code,
|
||||
"source_type": _VALID_SOURCE_TYPES[source_type],
|
||||
"connector_type": _VALID_CONNECTOR_TYPES[connector_type],
|
||||
"site_id": site_id,
|
||||
"display_name": str(raw.get("display_name") or source_code).strip(),
|
||||
"enabled": bool(raw.get("enabled", True)),
|
||||
@@ -249,7 +251,7 @@ def _validate_source(raw: dict[str, Any], *, seen_codes: set[str]) -> dict[str,
|
||||
if str(alias).strip()
|
||||
],
|
||||
}
|
||||
if source_type == "crane_footprint":
|
||||
if connector_type == "crane_footprint":
|
||||
normalized["warehouse_resolution"] = str(raw.get("warehouse_resolution") or "alias_match").strip().lower()
|
||||
normalized["allowed_warehouse_ids"] = allowed_warehouse_ids
|
||||
match_cfg = raw.get("match")
|
||||
@@ -261,7 +263,7 @@ def _validate_source(raw: dict[str, Any], *, seen_codes: set[str]) -> dict[str,
|
||||
"warehouse_hints": [str(v).strip() for v in (match_cfg.get("warehouse_hints") or []) if str(v).strip()],
|
||||
"aliases": [str(v).strip() for v in (match_cfg.get("aliases") or []) if str(v).strip()],
|
||||
}
|
||||
if source_type == "crane_footprint" and raw.get("export"):
|
||||
if connector_type == "crane_footprint" and raw.get("export"):
|
||||
normalized["export"] = dict(raw.get("export") or {})
|
||||
normalized["query"] = _build_legacy_query(normalized)
|
||||
return normalized
|
||||
@@ -421,8 +423,8 @@ def merge_runtime_inventory_identity(
|
||||
query = dict(merged.get("query") or {})
|
||||
query["warehouse_code"] = warehouse
|
||||
merged["query"] = query
|
||||
source_type = str(merged.get("source_type") or "").strip()
|
||||
if source_type == "crane_footprint":
|
||||
connector_type = str(merged.get("connector_type") or "").strip()
|
||||
if connector_type == "crane_footprint":
|
||||
navigation = dict(merged.get("navigation") or {})
|
||||
navigation["project_code"] = warehouse
|
||||
merged["navigation"] = navigation
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
services/shipping_notice/inventory_workflow.py
|
||||
|
||||
用途:发货通知库存阶段编排(解析、上传、ensure_inventory);RPA 见 inventory_rpa_workflow。
|
||||
依赖:inventory_*、inventory_mapping_workflow、inventory_rpa_workflow、query_service、state_machine。
|
||||
依赖:customer_identity_gate、inventory_*、inventory_mapping_workflow、inventory_rpa_workflow、query_service、state_machine。
|
||||
逻辑:tools.py 门面 re-export;解析/上传完成后委托 inventory_mapping_workflow 做对齐与 auto-chain。
|
||||
"""
|
||||
|
||||
@@ -60,6 +60,7 @@ from app.services.shipping_notice.query_service import (
|
||||
)
|
||||
from app.services.shipping_notice.i18n import resolve_lang, t
|
||||
from app.services.shipping_notice.inventory_source_gate import assert_inventory_source_gate, is_inventory_source_stable
|
||||
from app.services.shipping_notice.customer_identity_gate import customer_gate_tool_response
|
||||
from app.services.shipping_notice.state_machine import resolve_task_ui_state
|
||||
from app.services.shipping_notice.state_machine import TaskTransition, apply_task_transition
|
||||
from app.services.shipping_notice.tool_common import log_task_event, set_task_step_progress
|
||||
@@ -126,6 +127,9 @@ def _inventory_source_gate_response(task: ShippingTask, *, operation: str, lang:
|
||||
库存相关 Tool 入口统一门禁;未稳定时返回 needs_human 响应。
|
||||
核心逻辑:仅捕获预期 AppError,其它异常继续向上抛出。
|
||||
"""
|
||||
customer_gate = customer_gate_tool_response(task, operation=operation)
|
||||
if customer_gate is not None:
|
||||
return customer_gate
|
||||
if is_inventory_source_stable(task):
|
||||
return None
|
||||
try:
|
||||
@@ -590,6 +594,10 @@ def ensure_inventory(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
if not task:
|
||||
return tool_response(status="failed", message=t("workflow.inventory.task_not_found", lang=lang))
|
||||
|
||||
customer_gate = customer_gate_tool_response(task, operation='ensure_inventory')
|
||||
if customer_gate is not None:
|
||||
return customer_gate
|
||||
|
||||
if not is_inventory_source_stable(task):
|
||||
try:
|
||||
assert_inventory_source_gate(task, operation="ensure_inventory")
|
||||
|
||||
@@ -24,7 +24,6 @@ NOTICE_LINE_FIELDS = (
|
||||
"allocation_id",
|
||||
"source_type",
|
||||
"customer_sku",
|
||||
"hub_code",
|
||||
)
|
||||
|
||||
# 订单行表头 → 系统字段(发货通知 PDF/Excel/邮件表格)
|
||||
@@ -126,10 +125,11 @@ NOTICE_COLUMN_MAP: dict[str, str] = {
|
||||
"Allocation ID": "allocation_id",
|
||||
"source type": "source_type",
|
||||
"Source Type": "source_type",
|
||||
"Hub Code": "hub_code",
|
||||
"Hub": "hub_code",
|
||||
"HUB": "hub_code",
|
||||
"hub_code": "hub_code",
|
||||
# Hub Code 与 Source Type 在当前业务中是同一库存路由线索,统一归入 source_type。
|
||||
"Hub Code": "source_type",
|
||||
"Hub": "source_type",
|
||||
"HUB": "source_type",
|
||||
"hub_code": "source_type",
|
||||
# 单位
|
||||
"单位": "uom",
|
||||
"UOM": "uom",
|
||||
@@ -162,7 +162,6 @@ NOTICE_FIELD_LABELS = {
|
||||
"allocation_id": "Allocation ID",
|
||||
"source_type": "库存来源提示",
|
||||
"customer_sku": "客户料号 / HHPN",
|
||||
"hub_code": "Hub Code / 枢纽代码",
|
||||
}
|
||||
|
||||
HEADER_SKIP_TOKENS = {
|
||||
|
||||
@@ -27,15 +27,6 @@ from app.services.shipping_notice.reservation_id import (
|
||||
)
|
||||
|
||||
|
||||
def _derive_hub_code(source_type: Any) -> str:
|
||||
"""避免循环依赖,在表格解析层从 VMI/DBS source type 提取 Hub Code。"""
|
||||
import re
|
||||
|
||||
text = re.sub(r"\s+", " ", str(source_type or "").strip().upper())
|
||||
match = re.fullmatch(r"(?:VMI|DBS)[\s_-]+([A-Z0-9]+)", text)
|
||||
return match.group(1) if match else ""
|
||||
|
||||
|
||||
def parse_notice_row(
|
||||
row: list[Any] | tuple[Any, ...],
|
||||
columns: dict[str, int | None],
|
||||
@@ -138,17 +129,13 @@ def parse_notice_row(
|
||||
if vendor_part_number:
|
||||
parsed["vendor_part_number"] = vendor_part_number
|
||||
|
||||
for field in ("po_number", "allocation_id", "source_type", "customer_sku", "hub_code"):
|
||||
for field in ("po_number", "allocation_id", "source_type", "customer_sku"):
|
||||
idx = columns.get(field)
|
||||
if idx is None:
|
||||
continue
|
||||
value = str(cell(row, idx) or "").strip()
|
||||
if value:
|
||||
parsed[field] = value
|
||||
if not parsed.get("hub_code"):
|
||||
hub_code = _derive_hub_code(parsed.get("source_type"))
|
||||
if hub_code:
|
||||
parsed["hub_code"] = hub_code
|
||||
|
||||
if "amount" not in parsed and "unit_price" in parsed:
|
||||
computed = round(parsed["unit_price"] * qty, 4)
|
||||
|
||||
@@ -8,7 +8,6 @@ services/shipping_notice/notice_lines.py
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from typing import Any
|
||||
|
||||
from app.services.shipping_notice.notice_line_constants import (
|
||||
@@ -46,13 +45,6 @@ _map_notice_header = map_notice_header
|
||||
_parse_number = parse_number
|
||||
|
||||
|
||||
def derive_hub_code(source_type: Any) -> str:
|
||||
"""从已知库存来源提示中派生 Hub Code,如 VMI-FRA01→FRA01、DBS DUB→DUB。"""
|
||||
text = re.sub(r"\s+", " ", str(source_type or "").strip().upper())
|
||||
match = re.fullmatch(r"(?:VMI|DBS)[\s_-]+([A-Z0-9]+)", text)
|
||||
return match.group(1) if match else ""
|
||||
|
||||
|
||||
def normalize_notice_line(raw: dict[str, Any] | None) -> dict[str, Any] | None:
|
||||
"""
|
||||
标准化单条发货通知订单行。
|
||||
@@ -153,20 +145,23 @@ def normalize_notice_line(raw: dict[str, Any] | None) -> dict[str, Any] | None:
|
||||
optional_aliases = {
|
||||
"po_number": ("po_number", "poNumber", "PO", "PO Number"),
|
||||
"allocation_id": ("allocation_id", "allocationId", "Allocation ID"),
|
||||
"source_type": ("source_type", "sourceType", "Source Type"),
|
||||
"source_type": (
|
||||
"source_type",
|
||||
"sourceType",
|
||||
"Source Type",
|
||||
"hub_code",
|
||||
"hubCode",
|
||||
"Hub Code",
|
||||
"Hub",
|
||||
"HUB",
|
||||
),
|
||||
"customer_sku": ("customer_sku", "customerSku", "allocated_hhpn", "Allocated HHPN"),
|
||||
"hub_code": ("hub_code", "hubCode", "Hub Code", "Hub", "HUB"),
|
||||
}
|
||||
for field, aliases in optional_aliases.items():
|
||||
value = next((str(raw.get(alias) or "").strip() for alias in aliases if raw.get(alias)), "")
|
||||
if value:
|
||||
line[field] = value
|
||||
|
||||
if not line.get("hub_code"):
|
||||
hub_code = derive_hub_code(line.get("source_type"))
|
||||
if hub_code:
|
||||
line["hub_code"] = hub_code
|
||||
|
||||
remark = str(raw.get("remark") or raw.get("note") or "").strip()
|
||||
if remark:
|
||||
line["remark"] = remark
|
||||
@@ -466,7 +461,6 @@ __all__ = [
|
||||
"enrich_notice_with_document_currency",
|
||||
"enrich_notice_with_document_required_date",
|
||||
"enrich_notice_with_document_reservation",
|
||||
"derive_hub_code",
|
||||
"adjudicate_notice_lines",
|
||||
"normalize_notice_line",
|
||||
"normalize_notice_lines",
|
||||
|
||||
@@ -0,0 +1,216 @@
|
||||
"""
|
||||
backend/app/services/shipping_notice/open_existing_reservation_backfill.py
|
||||
|
||||
用途:在 exact_file/open_existing 场景下,将最新订单 Candidate 的合法 Reservation ID 安全回填旧任务。
|
||||
依赖:ShippingNoticeCandidate/ShippingTask、po_number、reservation_id、state_machine、tool_common。
|
||||
逻辑:batch_from_intakes 在消费 open_existing Candidate 前调用;本模块只处理尚未进入库存链的 rsv_req 任务,
|
||||
按 PO + SKU + Qty 唯一匹配空值订单行,重算 Reservation 门禁并写入任务审计。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections import Counter
|
||||
from decimal import Decimal, InvalidOperation
|
||||
from typing import Any
|
||||
|
||||
from app.models import ShippingNoticeCandidate, ShippingTask
|
||||
from app.services.shipping_notice.constants import PH_RSV_REQ
|
||||
from app.services.shipping_notice.po_number import normalize_po_number
|
||||
from app.services.shipping_notice.reservation_id import (
|
||||
is_valid_reservation_id,
|
||||
validated_reservation_id,
|
||||
)
|
||||
from app.services.shipping_notice.state_machine import TaskTransition, apply_task_transition
|
||||
from app.services.shipping_notice.tool_common import log_task_event
|
||||
|
||||
|
||||
def _normalized_qty(value: Any) -> str:
|
||||
"""
|
||||
将订单数量转换为稳定比较值。
|
||||
|
||||
Args:
|
||||
value: Candidate 或 Task 订单行中的数量。
|
||||
Returns:
|
||||
去除无意义小数尾零后的十进制字符串;非法值返回空字符串。
|
||||
"""
|
||||
try:
|
||||
quantity = Decimal(str(value).strip())
|
||||
except (InvalidOperation, ValueError):
|
||||
return ""
|
||||
if quantity <= 0:
|
||||
return ""
|
||||
return format(quantity.normalize(), "f")
|
||||
|
||||
|
||||
def _line_match_key(line: dict[str, Any]) -> tuple[str, str] | None:
|
||||
"""
|
||||
生成 SKU + Qty 唯一匹配键。
|
||||
|
||||
Args:
|
||||
line: 已标准化或历史任务订单行。
|
||||
Returns:
|
||||
大写 SKU 与规范数量组成的键;缺少任一字段时返回 None。
|
||||
"""
|
||||
sku = str(line.get("sku") or "").strip().upper()
|
||||
quantity = _normalized_qty(line.get("qty") if line.get("qty") is not None else line.get("quantity"))
|
||||
return (sku, quantity) if sku and quantity else None
|
||||
|
||||
|
||||
def _target_is_safe(task: ShippingTask) -> bool:
|
||||
"""
|
||||
判断旧任务是否仍允许补充 Reservation。
|
||||
|
||||
核心逻辑:只允许 pending_review + rsv_req,且库存、匹配、导出任一真相均未产生。
|
||||
Args:
|
||||
task: exact_file 命中的旧任务。
|
||||
Returns:
|
||||
是否允许执行只补空值的回填。
|
||||
"""
|
||||
return (
|
||||
str(task.process_status or "").strip() == "pending_review"
|
||||
and str(task.pending_human_reason or "").strip() == PH_RSV_REQ
|
||||
and not task.inventory_lines_json
|
||||
and not task.inventory_snapshot_id
|
||||
and not str(task.match_status or "").strip()
|
||||
and not task.line_results_json
|
||||
and not str(task.export_file_path or "").strip()
|
||||
and not str(task.export_file_name or "").strip()
|
||||
)
|
||||
|
||||
|
||||
def _reservation_gate_issues(lines: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
||||
"""
|
||||
重算订单行 Reservation ID 门禁。
|
||||
|
||||
Args:
|
||||
lines: 回填后的旧任务订单行。
|
||||
Returns:
|
||||
缺失或格式非法的 Reservation 行级问题。
|
||||
"""
|
||||
issues: list[dict[str, Any]] = []
|
||||
for index, line in enumerate(lines):
|
||||
raw_value = str(line.get("reservation_id") or "").strip()
|
||||
if is_valid_reservation_id(raw_value):
|
||||
continue
|
||||
issues.append(
|
||||
{
|
||||
"line_index": index,
|
||||
"sku": str(line.get("sku") or "").strip(),
|
||||
"field": "reservation_id",
|
||||
"reason": "invalid_format" if raw_value else "missing",
|
||||
"severity": "blocking",
|
||||
"raw_value": raw_value,
|
||||
}
|
||||
)
|
||||
return issues
|
||||
|
||||
|
||||
def backfill_exact_file_open_existing_reservations(
|
||||
*,
|
||||
task: ShippingTask,
|
||||
candidate: ShippingNoticeCandidate,
|
||||
candidate_summary: dict[str, Any],
|
||||
duplicate_status: str,
|
||||
duplicate_matches: list[dict[str, Any]],
|
||||
) -> bool:
|
||||
"""
|
||||
从 exact_file Candidate 安全补齐 open_existing 旧任务的 Reservation ID。
|
||||
|
||||
核心逻辑:要求重复目标唯一、旧任务尚处 rsv_req 且未进入下游;PO 必须一致,
|
||||
SKU + Qty 在新旧两侧都唯一且旧值为空时才回填。成功后仅重算 Reservation 门禁,
|
||||
即使门禁清除也继续停留在 parse_review,等待人工确认。
|
||||
Args:
|
||||
task: open_existing 指向的旧任务。
|
||||
candidate: 当前最新订单 Candidate,用于审计定位。
|
||||
candidate_summary: 已通过 Candidate 校验的业务摘要。
|
||||
duplicate_status: 本次实时重复检测状态,必须为 exact_file。
|
||||
duplicate_matches: 本次实时重复目标列表,必须唯一命中当前 task。
|
||||
Returns:
|
||||
是否至少安全回填一条订单行。
|
||||
"""
|
||||
matched_task_nos = {
|
||||
str(item.get("task_no") or "").strip().upper()
|
||||
for item in duplicate_matches
|
||||
if str(item.get("task_no") or "").strip()
|
||||
}
|
||||
if (
|
||||
str(duplicate_status or "").strip() != "exact_file"
|
||||
or matched_task_nos != {str(task.task_no or "").strip().upper()}
|
||||
or not _target_is_safe(task)
|
||||
):
|
||||
return False
|
||||
|
||||
candidate_po = normalize_po_number(candidate_summary.get("po_number"))
|
||||
task_po = normalize_po_number(task.po_number)
|
||||
if not candidate_po or not task_po or candidate_po != task_po:
|
||||
return False
|
||||
|
||||
target_lines = [dict(item) for item in (task.lines_json or []) if isinstance(item, dict)]
|
||||
candidate_lines = [
|
||||
dict(item)
|
||||
for item in (candidate_summary.get("lines") or [])
|
||||
if isinstance(item, dict)
|
||||
]
|
||||
target_keys = [_line_match_key(line) for line in target_lines]
|
||||
candidate_keys = [_line_match_key(line) for line in candidate_lines]
|
||||
target_counts = Counter(key for key in target_keys if key is not None)
|
||||
candidate_counts = Counter(key for key in candidate_keys if key is not None)
|
||||
|
||||
updated_indexes: list[int] = []
|
||||
reservation_by_key: dict[tuple[str, str], str] = {}
|
||||
for line, key in zip(candidate_lines, candidate_keys, strict=True):
|
||||
reservation_id = validated_reservation_id(line.get("reservation_id"))
|
||||
if (
|
||||
key is not None
|
||||
and reservation_id
|
||||
and candidate_counts[key] == 1
|
||||
and target_counts[key] == 1
|
||||
):
|
||||
reservation_by_key[key] = reservation_id
|
||||
|
||||
for index, (line, key) in enumerate(zip(target_lines, target_keys, strict=True)):
|
||||
if key not in reservation_by_key or str(line.get("reservation_id") or "").strip():
|
||||
continue
|
||||
line["reservation_id"] = reservation_by_key[key]
|
||||
updated_indexes.append(index)
|
||||
|
||||
if not updated_indexes:
|
||||
return False
|
||||
|
||||
# [STEP 1] 回填只写空 Reservation,不改变 PO/SKU/Qty 或库存源路由线索。
|
||||
task.lines_json = target_lines
|
||||
issues = _reservation_gate_issues(target_lines)
|
||||
step_payload = dict(task.step_payload_json or {})
|
||||
step_payload["parse_validation"] = {
|
||||
"status": "needs_review" if issues else "ready",
|
||||
"issues": issues,
|
||||
"contract_version": "shipping-line-v1",
|
||||
"resolution_source": "exact_file_candidate_backfill",
|
||||
}
|
||||
if issues:
|
||||
step_payload["process_field_gate"] = {
|
||||
"status": "needs_enrichment",
|
||||
"missing_fields": ["reservation_id"],
|
||||
"issues": issues,
|
||||
"contract_version": "shipping-order-extraction-v1",
|
||||
}
|
||||
apply_task_transition(task, TaskTransition.RSV_REQUIRED)
|
||||
else:
|
||||
step_payload.pop("process_field_gate", None)
|
||||
apply_task_transition(task, TaskTransition.PARSE_NEEDS_REVIEW)
|
||||
task.error_message = None
|
||||
task.step_payload_json = step_payload
|
||||
|
||||
# [STEP 2] 保留人工复核,并记录可追溯的 Candidate 与订单行索引。
|
||||
log_task_event(
|
||||
task,
|
||||
"reservation_backfilled_from_exact_file_candidate",
|
||||
{
|
||||
"candidate_no": candidate.candidate_no,
|
||||
"duplicate_status": duplicate_status,
|
||||
"updated_line_indexes": updated_indexes,
|
||||
"remaining_issue_count": len(issues),
|
||||
"review_preserved": True,
|
||||
},
|
||||
)
|
||||
return True
|
||||
@@ -72,7 +72,7 @@ def build_dify_openapi_spec(base_url: str) -> dict[str, Any]:
|
||||
if not server.endswith("/api/shipping-notice"):
|
||||
server = f"{server}/api/shipping-notice" if server else "/api/shipping-notice"
|
||||
|
||||
task_id = _str_prop("发货任务编号(task id),如 SN-20260529-ABCD1234")
|
||||
task_id = _str_prop("发货任务引用:技术任务号 SN-20260529-ABCD1234 或业务号 WYC26071501")
|
||||
batch_id = _str_prop("发货批次编号(batch id),如 SB-20260617-ABCD1234")
|
||||
runtime_context = _str_prop(
|
||||
"HXOPS 注入的完整 agent_runtime_context JSON 字符串;必须原样透传,禁止由 LLM 构造或修改"
|
||||
@@ -89,7 +89,7 @@ def build_dify_openapi_spec(base_url: str) -> dict[str, Any]:
|
||||
"不包含由后台任务统一续跑的主推进工具,也不包含 RPA 回调。"
|
||||
"推进类 Tool 的统一约束如下:必须依赖 HXOPS 状态机校验,必须基于唯一 task_id 推进;"
|
||||
"模糊指代不能直接推进,必须先通过 reference_context、get_task_status 或其他 HXOPS Tool 解析到唯一任务。"
|
||||
"submit_decision、match_inventory、generate_shipment_excel、upload_to_freight、retry_task、confirm_inventory_source"
|
||||
"submit_decision、match_inventory、generate_shipment_excel、upload_to_freight、retry_task、confirm_inventory_source、confirm_customer"
|
||||
" 这类推进动作都必须根据 HXOPS Tool 返回结果解释,不能脱离 Tool 返回自行编造状态。"
|
||||
"若 Tool 返回 needs_human 或 failed,不得自行改写成完成、成功上传或已处理完毕。"
|
||||
"如果响应包含 action_buttons,Dify 只解释当前状态、业务原因和影响,"
|
||||
@@ -159,8 +159,10 @@ def build_dify_openapi_spec(base_url: str) -> dict[str, Any]:
|
||||
"sku": _str_prop("SKU/料号"),
|
||||
"qty": {"type": "number", "exclusiveMinimum": 0},
|
||||
"reservation_id": _str_prop("可为空,缺失时 Task 停在补字段门禁"),
|
||||
"hub_code": _str_prop("可为空,缺失时 Task 停在补字段门禁"),
|
||||
"source_type": _str_prop("可为空,缺失时 Task 停在补字段门禁"),
|
||||
"source_type": _str_prop(
|
||||
"可选订单路由线索;仅在原文有可靠证据时填写,"
|
||||
"不代表任务通知来源或已确认的库存连接器类型"
|
||||
),
|
||||
},
|
||||
"additionalProperties": True,
|
||||
},
|
||||
@@ -190,7 +192,10 @@ def build_dify_openapi_spec(base_url: str) -> dict[str, Any]:
|
||||
required=["agent_runtime_context", "input_snapshot_hash", "schema_version", "orders"],
|
||||
description=(
|
||||
"只接受 get_order_extraction_context 的同一快照。HXOPS 仅在分类、SKU/Qty 置信度及原文证据均达标,"
|
||||
"且无阻断冲突/修订决策时自动建单;Reservation ID、Hub Code、Source Type 允许缺失。"
|
||||
"且无阻断冲突/修订决策时自动建单;Reservation ID 允许缺失,"
|
||||
"订单行 Source Type 是可选路由线索。"
|
||||
"响应以持久化结果分别返回 created_count、opened_existing_count、pending_count、"
|
||||
"non_shipping_count;auto_created_count 仅为兼容字段且等于 created_count。"
|
||||
),
|
||||
),
|
||||
"/tools/parse_notice": _post_op(
|
||||
@@ -230,7 +235,10 @@ def build_dify_openapi_spec(base_url: str) -> dict[str, Any]:
|
||||
"line_index": _int_prop("行下标,从 0 开始"),
|
||||
"patch": {
|
||||
"type": "object",
|
||||
"description": "可更新字段:sku/reservation_id/quantity/qty/required_date/uom/hub_code/source_type",
|
||||
"description": (
|
||||
"可更新字段:sku/reservation_id/quantity/qty/required_date/uom/source_type;"
|
||||
"source_type 仅作为可选订单路由线索"
|
||||
),
|
||||
"additionalProperties": True,
|
||||
},
|
||||
"comment": _str_prop("修改备注(可选)"),
|
||||
@@ -291,12 +299,25 @@ def build_dify_openapi_spec(base_url: str) -> dict[str, Any]:
|
||||
},
|
||||
required=["task_id", "source_code"],
|
||||
description=(
|
||||
"库存源门禁:稳定身份须同时具备 source_code、source_type、site_id、warehouse_id,"
|
||||
"库存连接器门禁:稳定身份须同时具备 source_code、connector_type、site_id、warehouse_id,"
|
||||
"且 routing_fingerprint 与当前配置版本一致。"
|
||||
"Tool API 使用集成密钥鉴权,确认人审计由宿主会话内部链路写入,不接受外部 user_id。"
|
||||
"若返回 needs_human,说明身份未完整解析或需先完成解析确认。"
|
||||
),
|
||||
),
|
||||
"/tools/confirm_customer": _post_op(
|
||||
"confirm_customer",
|
||||
"在客户人工检查点确认标准客户(仅提交 customer_id)",
|
||||
{
|
||||
"task_id": task_id,
|
||||
"customer_id": _int_prop("用户从 HXOPS 标准客户列表中明确选择的客户 ID"),
|
||||
},
|
||||
required=["task_id", "customer_id"],
|
||||
description=(
|
||||
"仅在 customer_review 检查点且用户已经明确选择标准客户后调用。"
|
||||
"禁止根据邮件中的不稳定客户名称自行猜测 customer_id;客户确认成功后由 HXOPS 决定后续流程。"
|
||||
),
|
||||
),
|
||||
"/tools/submit_decision": _post_op(
|
||||
"submit_decision",
|
||||
"人工复核决策。task_id 与 conversation_id 至少传一个;用户确认时禁止 create_task。决策提交后由后台任务统一续跑。",
|
||||
@@ -332,13 +353,13 @@ def build_dify_openapi_spec(base_url: str) -> dict[str, Any]:
|
||||
),
|
||||
"/tools/get_task_status": _post_op(
|
||||
"get_task_status",
|
||||
"查询任务当前状态与 human_options;响应含 inventory_source_* 独立字段与候选结构",
|
||||
"查询任务当前状态与 human_options;响应含库存连接器独立字段与候选结构",
|
||||
{
|
||||
"task_id": task_id,
|
||||
"conversation_id": _str_prop("Dify 会话 ID"),
|
||||
},
|
||||
description=(
|
||||
"返回 inventory_source_code、inventory_source_type、inventory_site_id、"
|
||||
"返回 inventory_source_code、inventory_connector_type、inventory_site_id、"
|
||||
"inventory_warehouse_id、inventory_source_status(unresolved|ambiguous|resolved|"
|
||||
"user_confirmed|invalid|conflicted)、inventory_source_method、"
|
||||
"inventory_source_config_version、inventory_routing_fingerprint、"
|
||||
|
||||
@@ -17,7 +17,7 @@ from app.services.shipping_notice.po_number import normalize_po_number
|
||||
from app.services.shipping_notice.reservation_id import validated_reservation_id
|
||||
|
||||
_PO_IN_FILENAME = re.compile(r"(?<!\d)(\d{7,12})(?!\d)")
|
||||
_KEY_FIELDS = ("reservation_id", "sku", "qty", "hub_code")
|
||||
_KEY_FIELDS = ("reservation_id", "sku", "qty", "source_type")
|
||||
|
||||
|
||||
def _comparable_value(field: str, value: Any) -> str:
|
||||
|
||||
@@ -1,17 +1,18 @@
|
||||
"""
|
||||
backend/app/services/shipping_notice/order_extraction.py
|
||||
|
||||
用途:为现有货代 Chatflow 提供建单前订单抽取上下文,并接收 LLM orders[] 完成校验、判重与自动建单。
|
||||
用途:为现有货代 Chatflow 提供建单前订单抽取上下文,并接收 LLM orders[] 完成校验、判重、自动建单与失败收口。
|
||||
依赖:agent_runtime_context、ChatSession、ShippingNoticeIntake/Document/Candidate、batch_from_intakes。
|
||||
逻辑:点击发送后 Dify 先读取不可变输入快照,再提交结构化订单;HXOPS 以会话用户为权限边界,
|
||||
逐订单落 Candidate,高置信度 SKU/Qty 订单自动消费建 Task,其余保留供自然对话修订。
|
||||
逻辑:聊天请求进入 Dify 前先登记本轮抽取身份,Dify 再读取不可变输入快照并提交结构化订单;
|
||||
HXOPS 逐订单落 Candidate,高置信度 SKU/Qty 订单自动消费建 Task,其余保留供自然对话修订;
|
||||
Dify 终态或状态读取负责把未提交和超时请求收口为失败。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
from datetime import datetime
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from typing import Any
|
||||
|
||||
from flask import current_app
|
||||
@@ -20,6 +21,7 @@ from sqlalchemy.orm.attributes import flag_modified
|
||||
from app import db
|
||||
from app.core.errors import ConflictError, ForbiddenError, NotFoundError, ValidationError
|
||||
from app.models import (
|
||||
Agent,
|
||||
ChatSession,
|
||||
FileAsset,
|
||||
ShippingNoticeCandidate,
|
||||
@@ -50,6 +52,9 @@ _CONTEXT_PATHS = [
|
||||
'refs.contract_version',
|
||||
'refs.intake_nos',
|
||||
]
|
||||
ORDER_EXTRACTION_FAILED_CODE = 'SHIPPING_NOTICE.ORDER_EXTRACTION_FAILED'
|
||||
ORDER_EXTRACTION_INCOMPLETE_MESSAGE = '订单识别流程未提交有效结果,请重新发送当前邮件。'
|
||||
ORDER_EXTRACTION_TIMEOUT_MESSAGE = '订单识别超时,请重新发送当前邮件。'
|
||||
|
||||
|
||||
def _runtime_identity(raw_context: str | dict[str, Any]) -> tuple[ChatSession, list[str], str]:
|
||||
@@ -64,7 +69,18 @@ def _runtime_identity(raw_context: str | dict[str, Any]) -> tuple[ChatSession, l
|
||||
raise ValidationError(code='SHIPPING_NOTICE.ORDER_EXTRACTION_CONTEXT_INVALID', message='订单抽取契约版本不匹配')
|
||||
|
||||
session_id = str(values.get('platform.session_id') or '').strip()
|
||||
session = ChatSession.query.filter_by(session_id=session_id).first()
|
||||
request_id = str(values.get('platform.request_id') or '').strip()
|
||||
if not session_id or not request_id:
|
||||
raise ValidationError(code='SHIPPING_NOTICE.ORDER_EXTRACTION_CONTEXT_INVALID', message='订单抽取请求缺少会话或请求标识')
|
||||
session = (
|
||||
db.session.query(ChatSession)
|
||||
.join(Agent, Agent.id == ChatSession.agent_id)
|
||||
.filter(
|
||||
ChatSession.session_id == session_id,
|
||||
Agent.agent_code == 'shipping_notice',
|
||||
)
|
||||
.first()
|
||||
)
|
||||
if session is None:
|
||||
raise NotFoundError(code='SHIPPING_NOTICE.ORDER_EXTRACTION_CONTEXT_INVALID', message='聊天会话不存在')
|
||||
try:
|
||||
@@ -76,7 +92,7 @@ def _runtime_identity(raw_context: str | dict[str, Any]) -> tuple[ChatSession, l
|
||||
intake_nos = sorted({str(item or '').strip().upper() for item in raw_nos if str(item or '').strip()})
|
||||
if not intake_nos:
|
||||
raise ValidationError(code='SHIPPING_NOTICE.ORDER_EXTRACTION_CONTEXT_INVALID', message='未提供待解析 Intake')
|
||||
return session, intake_nos, str(values.get('platform.request_id') or '').strip()
|
||||
return session, intake_nos, request_id
|
||||
|
||||
|
||||
def _load_intakes(
|
||||
@@ -145,6 +161,428 @@ def _snapshot_hash(intakes: list[ShippingNoticeIntake], documents: list[Shipping
|
||||
return hashlib.sha256(raw.encode('utf-8')).hexdigest()
|
||||
|
||||
|
||||
def _normalized_intake_nos(intake_nos: list[str]) -> list[str]:
|
||||
"""规范化并稳定排序 Intake 编号,供请求登记、失败收口和超时回收复用。"""
|
||||
return sorted({str(item or '').strip().upper() for item in intake_nos if str(item or '').strip()})
|
||||
|
||||
|
||||
def _order_extraction_snapshot(intake: ShippingNoticeIntake) -> dict[str, Any]:
|
||||
"""读取 Intake 当前抽取快照;旧数据或非法结构统一视为空快照。"""
|
||||
structured = intake.structured_result_json if isinstance(intake.structured_result_json, dict) else {}
|
||||
snapshot = structured.get('order_extraction_snapshot')
|
||||
return snapshot if isinstance(snapshot, dict) else {}
|
||||
|
||||
|
||||
def _parse_snapshot_time(value: Any) -> datetime | None:
|
||||
"""将抽取快照时间转换为无时区 UTC,兼容 ISO `Z` 与带时区格式。"""
|
||||
text = str(value or '').strip()
|
||||
if not text:
|
||||
return None
|
||||
try:
|
||||
parsed = datetime.fromisoformat(text.replace('Z', '+00:00'))
|
||||
except ValueError:
|
||||
return None
|
||||
if parsed.tzinfo is not None:
|
||||
parsed = parsed.astimezone(timezone.utc).replace(tzinfo=None)
|
||||
return parsed
|
||||
|
||||
|
||||
def _set_documents_extraction_state(
|
||||
*,
|
||||
intake_ids: list[int],
|
||||
status: str,
|
||||
error_code: str | None,
|
||||
error_message: str | None,
|
||||
now: datetime,
|
||||
only_extracting: bool,
|
||||
) -> None:
|
||||
"""
|
||||
同步本轮 Intake 下 Document 的订单抽取状态。
|
||||
|
||||
Args:
|
||||
intake_ids: 已通过用户、会话与请求身份校验的 Intake 主键。
|
||||
status: 目标状态。
|
||||
error_code: 失败错误码;开始抽取时传 None。
|
||||
error_message: 用户可见错误说明;开始抽取时传 None。
|
||||
now: 本次状态更新时间。
|
||||
only_extracting: True 时只收口仍在 extracting 的 Document,禁止覆盖成功终态。
|
||||
"""
|
||||
if not intake_ids:
|
||||
return
|
||||
query = db.session.query(ShippingNoticeDocument).filter(
|
||||
ShippingNoticeDocument.intake_id.in_(intake_ids)
|
||||
)
|
||||
if only_extracting:
|
||||
query = query.filter(ShippingNoticeDocument.order_extraction_status == 'extracting')
|
||||
for document in query.with_for_update().all():
|
||||
document.order_extraction_status = status
|
||||
document.order_extraction_source = 'dify_chatflow'
|
||||
document.order_extraction_version = EXTRACTION_CONTRACT_VERSION
|
||||
document.order_extraction_error_code = error_code
|
||||
document.order_extraction_error_message = error_message
|
||||
document.updated_at = now
|
||||
|
||||
|
||||
def start_order_extraction(
|
||||
*,
|
||||
user_id: int,
|
||||
session_id: str,
|
||||
intake_nos: list[str],
|
||||
request_id: str,
|
||||
) -> int:
|
||||
"""
|
||||
在请求进入 Dify 前登记权威订单抽取状态。
|
||||
|
||||
核心逻辑:锁定当前用户和会话的完整 Intake 集合;同一 request 重入不刷新超时起点,
|
||||
新 request 则覆盖旧快照身份,使旧 terminal 无法把新一轮抽取收口为失败。
|
||||
|
||||
Args:
|
||||
user_id: 当前聊天用户主键。
|
||||
session_id: HXOPS 本地会话号,必须与 Intake 绑定会话一致。
|
||||
intake_nos: 本轮完整 Intake 编号集合。
|
||||
request_id: 本轮 HXOPS 请求号,不得为空。
|
||||
|
||||
Returns:
|
||||
本轮进入 extracting 的 Intake 数量;同一请求重复登记仍返回完整数量。
|
||||
|
||||
Raises:
|
||||
ValidationError: 请求身份或 Intake 集合为空。
|
||||
NotFoundError: Intake 集合不完整。
|
||||
ConflictError: Intake 尚未预处理完成、已消费或绑定其他会话。
|
||||
"""
|
||||
normalized = _normalized_intake_nos(intake_nos)
|
||||
session_value = str(session_id or '').strip()
|
||||
request_value = str(request_id or '').strip()
|
||||
if not normalized or not session_value or not request_value:
|
||||
raise ValidationError(code='SHIPPING_NOTICE.ORDER_EXTRACTION_CONTEXT_INVALID', message='订单识别请求上下文不完整')
|
||||
|
||||
intakes = (
|
||||
db.session.query(ShippingNoticeIntake)
|
||||
.filter(
|
||||
ShippingNoticeIntake.user_id == int(user_id),
|
||||
ShippingNoticeIntake.intake_no.in_(normalized),
|
||||
)
|
||||
.order_by(ShippingNoticeIntake.id.asc())
|
||||
.with_for_update()
|
||||
.all()
|
||||
)
|
||||
if {row.intake_no for row in intakes} != set(normalized):
|
||||
db.session.rollback()
|
||||
raise NotFoundError(code='SHIPPING_NOTICE.INTAKE_NOT_FOUND', message='部分发货通知接入记录不存在')
|
||||
now = datetime.utcnow()
|
||||
intake_ids: list[int] = []
|
||||
for intake in intakes:
|
||||
if intake.parse_status != 'parsed' or intake.consumed_at is not None:
|
||||
db.session.rollback()
|
||||
raise ConflictError(code='SHIPPING_NOTICE.ORDER_EXTRACTION_PENDING', message='邮件或附件尚未完成预处理')
|
||||
if intake.conversation_id and intake.conversation_id != session_value:
|
||||
db.session.rollback()
|
||||
raise ConflictError(code='SHIPPING_NOTICE.ORDER_EXTRACTION_CONTEXT_INVALID', message='发货通知已绑定其他会话')
|
||||
intake.conversation_id = session_value
|
||||
previous = _order_extraction_snapshot(intake)
|
||||
same_request = (
|
||||
intake.order_extraction_status == 'extracting'
|
||||
and str(previous.get('request_id') or '') == request_value
|
||||
and str(previous.get('session_id') or '') == session_value
|
||||
)
|
||||
structured = dict(intake.structured_result_json or {})
|
||||
next_snapshot = dict(previous) if same_request else {}
|
||||
structured['order_extraction_snapshot'] = {
|
||||
**next_snapshot,
|
||||
'request_id': request_value,
|
||||
'session_id': session_value,
|
||||
'created_at': previous.get('created_at') if same_request and previous.get('created_at') else now.isoformat(),
|
||||
}
|
||||
intake.structured_result_json = structured
|
||||
flag_modified(intake, 'structured_result_json')
|
||||
intake.order_extraction_status = 'extracting'
|
||||
intake.order_extraction_version = EXTRACTION_CONTRACT_VERSION
|
||||
intake.order_extraction_error_code = None
|
||||
intake.order_extraction_error_message = None
|
||||
intake.updated_at = now
|
||||
intake_ids.append(int(intake.id))
|
||||
_set_documents_extraction_state(
|
||||
intake_ids=intake_ids,
|
||||
status='extracting',
|
||||
error_code=None,
|
||||
error_message=None,
|
||||
now=now,
|
||||
only_extracting=False,
|
||||
)
|
||||
db.session.commit()
|
||||
return len(intakes)
|
||||
|
||||
|
||||
def finalize_order_extraction_failure(
|
||||
*,
|
||||
user_id: int,
|
||||
session_id: str,
|
||||
intake_nos: list[str],
|
||||
request_id: str,
|
||||
error_code: str = ORDER_EXTRACTION_FAILED_CODE,
|
||||
error_message: str = ORDER_EXTRACTION_INCOMPLETE_MESSAGE,
|
||||
) -> int:
|
||||
"""
|
||||
将当前请求仍未提交的订单抽取幂等收口为失败。
|
||||
|
||||
核心逻辑:先验证用户、会话与完整 Intake 集合,再逐条匹配快照 request/session;
|
||||
只允许 extracting 转 failed,因此成功结果、部分完成结果和新请求均不会被旧 terminal 覆盖。
|
||||
|
||||
Args:
|
||||
user_id: 当前聊天用户主键。
|
||||
session_id: 当前 HXOPS 会话号。
|
||||
intake_nos: 当前请求携带的完整 Intake 集合。
|
||||
request_id: 当前 HXOPS 请求号。
|
||||
error_code: 稳定业务错误码,最长 64 字符。
|
||||
error_message: 用户可见错误说明,不得包含密钥或堆栈。
|
||||
|
||||
Returns:
|
||||
实际由 extracting 更新为 failed 的 Intake 数量;重复调用或旧请求返回 0。
|
||||
"""
|
||||
normalized = _normalized_intake_nos(intake_nos)
|
||||
session_value = str(session_id or '').strip()
|
||||
request_value = str(request_id or '').strip()
|
||||
if not normalized or not session_value or not request_value:
|
||||
return 0
|
||||
intakes = (
|
||||
db.session.query(ShippingNoticeIntake)
|
||||
.filter(
|
||||
ShippingNoticeIntake.user_id == int(user_id),
|
||||
ShippingNoticeIntake.intake_no.in_(normalized),
|
||||
)
|
||||
.order_by(ShippingNoticeIntake.id.asc())
|
||||
.with_for_update()
|
||||
.all()
|
||||
)
|
||||
if {row.intake_no for row in intakes} != set(normalized):
|
||||
db.session.rollback()
|
||||
return 0
|
||||
now = datetime.utcnow()
|
||||
code = str(error_code or ORDER_EXTRACTION_FAILED_CODE).strip()[:64]
|
||||
message = str(error_message or ORDER_EXTRACTION_INCOMPLETE_MESSAGE).strip()[:2000]
|
||||
failed_ids: list[int] = []
|
||||
for intake in intakes:
|
||||
snapshot = _order_extraction_snapshot(intake)
|
||||
if (
|
||||
intake.order_extraction_status != 'extracting'
|
||||
or intake.conversation_id != session_value
|
||||
or str(snapshot.get('request_id') or '') != request_value
|
||||
or str(snapshot.get('session_id') or '') != session_value
|
||||
):
|
||||
continue
|
||||
intake.order_extraction_status = 'failed'
|
||||
intake.order_extraction_version = EXTRACTION_CONTRACT_VERSION
|
||||
intake.order_extraction_error_code = code
|
||||
intake.order_extraction_error_message = message
|
||||
intake.updated_at = now
|
||||
failed_ids.append(int(intake.id))
|
||||
_set_documents_extraction_state(
|
||||
intake_ids=failed_ids,
|
||||
status='failed',
|
||||
error_code=code,
|
||||
error_message=message,
|
||||
now=now,
|
||||
only_extracting=True,
|
||||
)
|
||||
db.session.commit()
|
||||
return len(failed_ids)
|
||||
|
||||
|
||||
def expire_stale_order_extractions(
|
||||
*,
|
||||
user_id: int,
|
||||
intake_nos: list[str] | None = None,
|
||||
conversation_id: str | None = None,
|
||||
timeout_seconds: int | None = None,
|
||||
now: datetime | None = None,
|
||||
) -> int:
|
||||
"""
|
||||
在 Intake 状态读取时惰性回收超时订单抽取。
|
||||
|
||||
核心逻辑:锁定当前用户仍为 extracting 的记录,优先使用快照 created_at,旧数据回退 updated_at;
|
||||
只更新超时记录及其仍在 extracting 的 Documents,不依赖进程内定时器。
|
||||
|
||||
Args:
|
||||
user_id: 当前用户主键。
|
||||
intake_nos: 可选 Intake 范围;批量状态接口应传入请求集合。
|
||||
conversation_id: 可选会话范围;会话恢复接口应传入当前会话。
|
||||
timeout_seconds: 可选覆盖值,默认读取应用配置,最小为 1 秒。
|
||||
now: 测试使用的 UTC 当前时间;生产不传。
|
||||
|
||||
Returns:
|
||||
实际回收为 failed 的 Intake 数量。
|
||||
"""
|
||||
configured = timeout_seconds
|
||||
if configured is None:
|
||||
configured = int(current_app.config.get('SHIPPING_NOTICE_ORDER_EXTRACTION_TIMEOUT_SECONDS') or 300)
|
||||
timeout = max(int(configured), 1)
|
||||
current_time = now or datetime.utcnow()
|
||||
if current_time.tzinfo is not None:
|
||||
current_time = current_time.astimezone(timezone.utc).replace(tzinfo=None)
|
||||
query = db.session.query(ShippingNoticeIntake).filter(
|
||||
ShippingNoticeIntake.user_id == int(user_id),
|
||||
ShippingNoticeIntake.order_extraction_status == 'extracting',
|
||||
)
|
||||
normalized = _normalized_intake_nos(intake_nos or [])
|
||||
if intake_nos is not None:
|
||||
if not normalized:
|
||||
return 0
|
||||
query = query.filter(ShippingNoticeIntake.intake_no.in_(normalized))
|
||||
conversation_value = str(conversation_id or '').strip()
|
||||
if conversation_value:
|
||||
query = query.filter(ShippingNoticeIntake.conversation_id == conversation_value)
|
||||
|
||||
expired_ids: list[int] = []
|
||||
for intake in query.order_by(ShippingNoticeIntake.id.asc()).with_for_update().all():
|
||||
snapshot = _order_extraction_snapshot(intake)
|
||||
started_at = _parse_snapshot_time(snapshot.get('created_at')) or intake.updated_at
|
||||
if started_at is None or current_time - started_at < timedelta(seconds=timeout):
|
||||
continue
|
||||
intake.order_extraction_status = 'failed'
|
||||
intake.order_extraction_version = EXTRACTION_CONTRACT_VERSION
|
||||
intake.order_extraction_error_code = ORDER_EXTRACTION_FAILED_CODE
|
||||
intake.order_extraction_error_message = ORDER_EXTRACTION_TIMEOUT_MESSAGE
|
||||
intake.updated_at = current_time
|
||||
expired_ids.append(int(intake.id))
|
||||
_set_documents_extraction_state(
|
||||
intake_ids=expired_ids,
|
||||
status='failed',
|
||||
error_code=ORDER_EXTRACTION_FAILED_CODE,
|
||||
error_message=ORDER_EXTRACTION_TIMEOUT_MESSAGE,
|
||||
now=current_time,
|
||||
only_extracting=True,
|
||||
)
|
||||
# 查询使用 FOR UPDATE;即使没有超时记录也提交只读事务,避免状态接口序列化期间继续持锁。
|
||||
db.session.commit()
|
||||
return len(expired_ids)
|
||||
|
||||
|
||||
def get_order_extraction_state(
|
||||
*,
|
||||
user_id: int,
|
||||
session_id: str,
|
||||
intake_nos: list[str],
|
||||
request_id: str,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
读取当前订单抽取请求可用于聊天展示的权威聚合状态。
|
||||
|
||||
核心逻辑:按用户、会话、完整 Intake 集合和 snapshot request_id 做四重围栏;
|
||||
处理中只返回不确定进度,终态从已持久化的 submission.result 读取真实建单计数。
|
||||
|
||||
Args:
|
||||
user_id: 当前聊天用户主键。
|
||||
session_id: HXOPS 本地会话号。
|
||||
intake_nos: 本轮完整 Intake 编号集合。
|
||||
request_id: 本轮 HXOPS 请求号。
|
||||
|
||||
Returns:
|
||||
包含 status、phase、message、真实结果计数、batch_no 与 terminal 的状态字典。
|
||||
|
||||
Raises:
|
||||
ValidationError: 请求身份不完整。
|
||||
NotFoundError: Intake 集合不存在或不完整。
|
||||
ConflictError: Intake 不属于当前会话或已被更新请求取代。
|
||||
"""
|
||||
normalized = _normalized_intake_nos(intake_nos)
|
||||
session_value = str(session_id or '').strip()
|
||||
request_value = str(request_id or '').strip()
|
||||
if int(user_id or 0) <= 0 or not normalized or not session_value or not request_value:
|
||||
raise ValidationError(
|
||||
code='SHIPPING_NOTICE.ORDER_EXTRACTION_CONTEXT_INVALID',
|
||||
message='订单识别请求上下文不完整',
|
||||
)
|
||||
|
||||
intakes = (
|
||||
db.session.query(ShippingNoticeIntake)
|
||||
.filter(
|
||||
ShippingNoticeIntake.user_id == int(user_id),
|
||||
ShippingNoticeIntake.intake_no.in_(normalized),
|
||||
)
|
||||
.order_by(ShippingNoticeIntake.id.asc())
|
||||
.all()
|
||||
)
|
||||
if {row.intake_no for row in intakes} != set(normalized):
|
||||
raise NotFoundError(code='SHIPPING_NOTICE.INTAKE_NOT_FOUND', message='部分发货通知接入记录不存在')
|
||||
|
||||
for intake in intakes:
|
||||
snapshot = _order_extraction_snapshot(intake)
|
||||
if (
|
||||
intake.conversation_id != session_value
|
||||
or str(snapshot.get('session_id') or '') != session_value
|
||||
or str(snapshot.get('request_id') or '') != request_value
|
||||
):
|
||||
raise ConflictError(
|
||||
code='SHIPPING_NOTICE.ORDER_EXTRACTION_PENDING',
|
||||
message='订单识别请求已失效或已被更新请求取代',
|
||||
)
|
||||
|
||||
statuses = {str(row.order_extraction_status or '').strip() for row in intakes}
|
||||
if 'extracting' in statuses:
|
||||
status = 'extracting'
|
||||
elif statuses == {'failed'}:
|
||||
status = 'failed'
|
||||
elif 'partially_completed' in statuses or 'failed' in statuses:
|
||||
status = 'partially_completed'
|
||||
elif statuses == {'completed'}:
|
||||
status = 'completed'
|
||||
else:
|
||||
raise ConflictError(
|
||||
code='SHIPPING_NOTICE.ORDER_EXTRACTION_PENDING',
|
||||
message='订单识别尚未进入可展示状态',
|
||||
)
|
||||
|
||||
result: dict[str, Any] = {}
|
||||
for intake in intakes:
|
||||
structured = intake.structured_result_json if isinstance(intake.structured_result_json, dict) else {}
|
||||
submission = structured.get('order_extraction_submission')
|
||||
if not isinstance(submission, dict) or str(submission.get('request_id') or '') != request_value:
|
||||
continue
|
||||
candidate = submission.get('result')
|
||||
if isinstance(candidate, dict):
|
||||
result = candidate
|
||||
break
|
||||
|
||||
if status == 'extracting':
|
||||
message = '正在识别邮件及附件中的订单'
|
||||
phase = 'llm_extraction'
|
||||
elif status == 'failed':
|
||||
message = next(
|
||||
(
|
||||
str(row.order_extraction_error_message or '').strip()
|
||||
for row in intakes
|
||||
if str(row.order_extraction_error_message or '').strip()
|
||||
),
|
||||
'订单识别失败,请重新发送当前邮件。',
|
||||
)
|
||||
phase = 'failed'
|
||||
else:
|
||||
message = str(result.get('message') or '').strip()
|
||||
if not message:
|
||||
message = '部分订单已处理,仍需补充或确认。' if status == 'partially_completed' else '订单识别完成。'
|
||||
phase = 'result_persisted'
|
||||
|
||||
def _count(key: str) -> int:
|
||||
"""将 Tool 结果计数约束为非负整数,异常值按 0 展示。"""
|
||||
try:
|
||||
return max(int(result.get(key) or 0), 0)
|
||||
except (TypeError, ValueError):
|
||||
return 0
|
||||
|
||||
return {
|
||||
'status': status,
|
||||
'phase': phase,
|
||||
'message': message,
|
||||
'created_count': _count('created_count'),
|
||||
'opened_existing_count': _count('opened_existing_count'),
|
||||
'pending_count': _count('pending_count'),
|
||||
'non_shipping_count': _count('non_shipping_count'),
|
||||
'created_with_missing_fields_count': _count('created_with_missing_fields_count'),
|
||||
'batch_no': str(result.get('batch_no') or '').strip() or None,
|
||||
'terminal': status != 'extracting',
|
||||
}
|
||||
|
||||
|
||||
def get_order_extraction_context(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
"""
|
||||
返回现有 Chatflow 完整理解邮件所需的 Intake/Document 上下文。
|
||||
@@ -160,6 +598,21 @@ def get_order_extraction_context(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
"""
|
||||
session, intake_nos, request_id = _runtime_identity(payload.get('agent_runtime_context'))
|
||||
intakes = _load_intakes(session=session, intake_nos=intake_nos, lock=True)
|
||||
for intake in intakes:
|
||||
previous_snapshot = _order_extraction_snapshot(intake)
|
||||
if (
|
||||
intake.order_extraction_status == 'extracting'
|
||||
and previous_snapshot.get('request_id')
|
||||
and (
|
||||
str(previous_snapshot.get('request_id') or '') != request_id
|
||||
or str(previous_snapshot.get('session_id') or '') != session.session_id
|
||||
)
|
||||
):
|
||||
db.session.rollback()
|
||||
raise ConflictError(
|
||||
code='SHIPPING_NOTICE.ORDER_EXTRACTION_PENDING',
|
||||
message='已有更新的订单识别请求正在处理,当前旧请求已失效',
|
||||
)
|
||||
documents = _load_documents(intakes, lock=False)
|
||||
if not documents:
|
||||
raise ConflictError(code='SHIPPING_NOTICE.INTAKE_ATTACHMENTS_INCOMPLETE', message='未找到可供订单抽取的邮件正文或附件')
|
||||
@@ -193,11 +646,19 @@ def get_order_extraction_context(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
now = datetime.utcnow()
|
||||
for intake in intakes:
|
||||
structured = dict(intake.structured_result_json or {})
|
||||
previous_snapshot = _order_extraction_snapshot(intake)
|
||||
structured['order_extraction_snapshot'] = {
|
||||
**previous_snapshot,
|
||||
'hash': snapshot,
|
||||
'request_id': request_id,
|
||||
'session_id': session.session_id,
|
||||
'created_at': now.isoformat(),
|
||||
'created_at': (
|
||||
previous_snapshot.get('created_at')
|
||||
if str(previous_snapshot.get('request_id') or '') == request_id
|
||||
and str(previous_snapshot.get('session_id') or '') == session.session_id
|
||||
and previous_snapshot.get('created_at')
|
||||
else now.isoformat()
|
||||
),
|
||||
}
|
||||
intake.structured_result_json = structured
|
||||
flag_modified(intake, 'structured_result_json')
|
||||
@@ -206,6 +667,14 @@ def get_order_extraction_context(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
intake.order_extraction_error_code = None
|
||||
intake.order_extraction_error_message = None
|
||||
intake.updated_at = now
|
||||
_set_documents_extraction_state(
|
||||
intake_ids=[int(row.id) for row in intakes],
|
||||
status='extracting',
|
||||
error_code=None,
|
||||
error_message=None,
|
||||
now=now,
|
||||
only_extracting=False,
|
||||
)
|
||||
db.session.commit()
|
||||
return {
|
||||
'status': 'ok',
|
||||
@@ -221,7 +690,9 @@ def get_order_extraction_context(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
'schema_version': EXTRACTION_CONTRACT_VERSION,
|
||||
'required_order_fields': ['source_intake_no', 'primary_document_id', 'classification', 'lines'],
|
||||
'auto_create_required_line_fields': ['sku', 'qty'],
|
||||
'allowed_missing_process_fields': ['reservation_id', 'hub_code', 'source_type'],
|
||||
'required_process_line_fields': ['reservation_id'],
|
||||
'optional_routing_line_fields': ['source_type'],
|
||||
'allowed_missing_process_fields': ['reservation_id'],
|
||||
},
|
||||
}
|
||||
|
||||
@@ -265,6 +736,39 @@ def _evidence_has_sku_qty(order: dict[str, Any]) -> bool:
|
||||
return any('sku' in field for field in fields) and any('qty' in field or 'quantity' in field for field in fields)
|
||||
|
||||
|
||||
def _build_submission_message(
|
||||
*,
|
||||
created_count: int,
|
||||
opened_existing_count: int,
|
||||
pending_count: int,
|
||||
non_shipping_count: int,
|
||||
created_with_missing_fields_count: int,
|
||||
) -> str:
|
||||
"""按持久化结果生成确定性摘要,禁止把 Candidate 数量描述为已建任务数量。"""
|
||||
if not created_count and not opened_existing_count and not pending_count:
|
||||
if non_shipping_count:
|
||||
return f'未识别到需要处理的发货订单,已忽略 {non_shipping_count} 项非发货内容;本次未创建任务。'
|
||||
return '未识别到发货订单,本次未创建任务。'
|
||||
|
||||
parts: list[str] = []
|
||||
if created_count:
|
||||
parts.append(f'已创建 {created_count} 个发货任务')
|
||||
if opened_existing_count:
|
||||
parts.append(f'已打开 {opened_existing_count} 个已有任务')
|
||||
if pending_count:
|
||||
prefix = '另有' if parts else '有'
|
||||
parts.append(f'{prefix} {pending_count} 个订单需要补充信息或处理冲突')
|
||||
if non_shipping_count:
|
||||
parts.append(f'已忽略 {non_shipping_count} 项非发货内容')
|
||||
message = ';'.join(parts) + '。'
|
||||
if created_with_missing_fields_count:
|
||||
message += (
|
||||
f'其中 {created_with_missing_fields_count} 个新建任务仍缺少 Reservation ID,'
|
||||
'可通过自然对话补充。'
|
||||
)
|
||||
return message
|
||||
|
||||
|
||||
def submit_order_extraction(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
"""
|
||||
提交 Chatflow 的 orders[],执行后端强校验、订单级判重与自动建单。
|
||||
@@ -290,6 +794,16 @@ def submit_order_extraction(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
raise ValidationError(code='SHIPPING_NOTICE.ORDER_EXTRACTION_INVALID_RESULT', message='订单数量超过限制')
|
||||
|
||||
intakes = _load_intakes(session=session, intake_nos=intake_nos, lock=True, allow_consumed=True)
|
||||
if any(
|
||||
str(_order_extraction_snapshot(intake).get('request_id') or '') != request_id
|
||||
or str(_order_extraction_snapshot(intake).get('session_id') or '') != session.session_id
|
||||
for intake in intakes
|
||||
):
|
||||
db.session.rollback()
|
||||
raise ConflictError(
|
||||
code='SHIPPING_NOTICE.ORDER_EXTRACTION_CONTEXT_INVALID',
|
||||
message='订单识别请求已被更新请求替代,请重新读取上下文',
|
||||
)
|
||||
documents = _load_documents(intakes, lock=True)
|
||||
current_snapshot = _snapshot_hash(intakes, documents)
|
||||
supplied_snapshot = str(payload.get('input_snapshot_hash') or '').strip().lower()
|
||||
@@ -303,6 +817,12 @@ def submit_order_extraction(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
replay_results = []
|
||||
break
|
||||
stored_result = submission.get('result')
|
||||
submission_request_id = submission.get('request_id')
|
||||
if not submission_request_id and isinstance(stored_result, dict):
|
||||
submission_request_id = stored_result.get('request_id')
|
||||
if str(submission_request_id or '') != request_id:
|
||||
replay_results = []
|
||||
break
|
||||
if isinstance(stored_result, dict):
|
||||
replay_results.append(stored_result)
|
||||
if len(replay_results) == len(intakes):
|
||||
@@ -324,11 +844,13 @@ def submit_order_extraction(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
field_threshold = float(current_app.config.get('SHIPPING_NOTICE_ORDER_FIELD_CONFIDENCE') or 0.90)
|
||||
auto_candidates: list[ShippingNoticeCandidate] = []
|
||||
pending: list[dict[str, Any]] = []
|
||||
non_shipping: list[dict[str, Any]] = []
|
||||
duplicate_results_by_intake: dict[int, list[dict[str, Any]]] = {}
|
||||
active_keys_by_intake: dict[int, set[str]] = {int(row.id): set() for row in intakes}
|
||||
pending_by_intake: dict[int, list[dict[str, Any]]] = {int(row.id): [] for row in intakes}
|
||||
document_candidate_keys: dict[int, list[str]] = {int(row.id): [] for row in documents}
|
||||
document_has_pending: dict[int, bool] = {int(row.id): False for row in documents}
|
||||
document_non_shipping_indexes: dict[int, list[int]] = {int(row.id): [] for row in documents}
|
||||
|
||||
# [STEP 1] 本轮选择状态完全由最新 LLM 结果决定,避免旧的 selected Candidate 混入自动建批集合。
|
||||
db.session.query(ShippingNoticeCandidate).filter(
|
||||
@@ -356,6 +878,28 @@ def submit_order_extraction(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
pending_item = {'order_index': index, 'source_intake_no': intake_no, 'reasons': ['primary_document_not_found']}
|
||||
pending.append(pending_item)
|
||||
pending_by_intake[int(intake.id)].append(pending_item)
|
||||
for owned_document in owned_docs:
|
||||
document_has_pending[int(owned_document.id)] = True
|
||||
continue
|
||||
|
||||
classification_confidence = _float(raw_order.get('classification_confidence'))
|
||||
classification = str(raw_order.get('classification') or '').strip().lower()
|
||||
conflicts = [item for item in (raw_order.get('conflicts') or []) if isinstance(item, dict)]
|
||||
blocking_conflicts = [item for item in conflicts if str(item.get('severity') or 'blocking') == 'blocking']
|
||||
if (
|
||||
classification == 'non_shipping_request'
|
||||
and classification_confidence >= class_threshold
|
||||
and not blocking_conflicts
|
||||
):
|
||||
# [STEP 1A] 明确的非发货内容只保留提交审计,不生成无法被消费的待处理 Candidate。
|
||||
non_shipping_item = {
|
||||
'order_index': index,
|
||||
'source_intake_no': intake_no,
|
||||
'primary_document_id': int(document.id),
|
||||
'classification_confidence': classification_confidence,
|
||||
}
|
||||
non_shipping.append(non_shipping_item)
|
||||
document_non_shipping_indexes[int(document.id)].append(index)
|
||||
continue
|
||||
|
||||
summary = dict(raw_order)
|
||||
@@ -368,13 +912,9 @@ def submit_order_extraction(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
summary.pop('primary_document_id', None)
|
||||
assessment = assess_candidate_business_summary(summary)
|
||||
normalized = assessment['normalized_summary']
|
||||
classification_confidence = _float(raw_order.get('classification_confidence'))
|
||||
field_confidence = raw_order.get('field_confidence') if isinstance(raw_order.get('field_confidence'), dict) else {}
|
||||
sku_conf = _float(field_confidence.get('sku'))
|
||||
qty_conf = _float(field_confidence.get('qty'))
|
||||
classification = str(raw_order.get('classification') or '').strip().lower()
|
||||
conflicts = [item for item in (raw_order.get('conflicts') or []) if isinstance(item, dict)]
|
||||
blocking_conflicts = [item for item in conflicts if str(item.get('severity') or 'blocking') == 'blocking']
|
||||
reasons: list[str] = []
|
||||
if classification != 'shipping_request':
|
||||
reasons.append('not_shipping_request')
|
||||
@@ -481,18 +1021,26 @@ def submit_order_extraction(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
pending.append(pending_item)
|
||||
pending_by_intake[int(intake.id)].append(pending_item)
|
||||
|
||||
# [STEP 2] 聚合 Document 结果,避免同一附件多订单时后一个 Candidate 覆盖前一个审计记录。
|
||||
# [STEP 2] 聚合 Document 结果;无法归属到 Intake 的异常项会使本轮全部 Document 保持部分完成。
|
||||
has_unassigned_pending = any(not item.get('source_intake_no') for item in pending)
|
||||
for document in documents:
|
||||
keys = document_candidate_keys[int(document.id)]
|
||||
document.order_extraction_status = 'partially_completed' if document_has_pending[int(document.id)] else 'completed'
|
||||
document.order_extraction_status = (
|
||||
'partially_completed'
|
||||
if document_has_pending[int(document.id)] or has_unassigned_pending
|
||||
else 'completed'
|
||||
)
|
||||
document.order_extraction_source = 'dify_chatflow'
|
||||
document.order_extraction_version = EXTRACTION_CONTRACT_VERSION
|
||||
document.order_extraction_result_json = {'request_id': request_id, 'candidate_keys': keys}
|
||||
document.order_extraction_result_json = {
|
||||
'request_id': request_id,
|
||||
'candidate_keys': keys,
|
||||
'non_shipping_order_indexes': document_non_shipping_indexes[int(document.id)],
|
||||
}
|
||||
document.order_extraction_error_code = None
|
||||
document.order_extraction_error_message = None
|
||||
|
||||
# [STEP 3] 清理同一抽取版本中消失、且尚未消费的旧 Candidate。
|
||||
has_unassigned_pending = any(not item.get('source_intake_no') for item in pending)
|
||||
for intake in intakes:
|
||||
active_keys = active_keys_by_intake[int(intake.id)]
|
||||
stale = db.session.query(ShippingNoticeCandidate).filter(
|
||||
@@ -531,7 +1079,7 @@ def submit_order_extraction(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
create_idempotency_key=idem,
|
||||
)
|
||||
else:
|
||||
# [STEP 4] 没有待处理订单且 LLM 明确返回 0 单时,本次 Intake 已完成但不会产生 Batch/Task。
|
||||
# [STEP 4] 没有待处理订单时(空数组或仅明确非发货内容),消费 Intake 但不产生 Batch/Task。
|
||||
if not pending:
|
||||
now = datetime.utcnow()
|
||||
for intake in intakes:
|
||||
@@ -543,21 +1091,42 @@ def submit_order_extraction(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
|
||||
create_data = (create_result or {}).get('data')
|
||||
create_data = create_data if isinstance(create_data, dict) else {}
|
||||
created = list(create_data.get('tasks') or [])
|
||||
opened_existing = list(
|
||||
(create_result or {}).get('opened_existing')
|
||||
or create_data.get('opened_existing')
|
||||
or []
|
||||
)
|
||||
created_count = len(created)
|
||||
opened_existing_count = len(opened_existing)
|
||||
created_with_missing_fields_count = sum(
|
||||
1
|
||||
for candidate in auto_candidates
|
||||
if candidate.duplicate_resolution != 'open_existing' and candidate.missing_fields_json
|
||||
)
|
||||
# 下层响应缺失任务明细属于契约异常;摘要只能陈述已持久化并返回的 Task,不能回退到 Candidate 数。
|
||||
created_with_missing_fields_count = min(created_with_missing_fields_count, created_count)
|
||||
result = {
|
||||
'status': 'ok',
|
||||
'request_id': request_id,
|
||||
'batch_no': create_result.get('batch_no') if create_result else None,
|
||||
'created': list(create_data.get('tasks') or []),
|
||||
'opened_existing': list(
|
||||
(create_result or {}).get('opened_existing')
|
||||
or create_data.get('opened_existing')
|
||||
or []
|
||||
),
|
||||
'created': created,
|
||||
'opened_existing': opened_existing,
|
||||
'pending_orders': pending,
|
||||
'auto_created_count': len(auto_candidate_nos),
|
||||
'non_shipping_orders': non_shipping,
|
||||
'created_count': created_count,
|
||||
'opened_existing_count': opened_existing_count,
|
||||
'pending_count': len(pending),
|
||||
'message': (
|
||||
f"已自动处理 {len(auto_candidate_nos)} 份发货订单,另有 {len(pending)} 份需要补充或确认。"
|
||||
'non_shipping_count': len(non_shipping),
|
||||
'created_with_missing_fields_count': created_with_missing_fields_count,
|
||||
# 兼容旧 Dify 节点;新节点应改读 created_count。
|
||||
'auto_created_count': created_count,
|
||||
'message': _build_submission_message(
|
||||
created_count=created_count,
|
||||
opened_existing_count=opened_existing_count,
|
||||
pending_count=len(pending),
|
||||
non_shipping_count=len(non_shipping),
|
||||
created_with_missing_fields_count=created_with_missing_fields_count,
|
||||
),
|
||||
}
|
||||
# [STEP 5] 保存 Tool 级幂等回放结果,防止 Dify 网络重试重复建单。
|
||||
@@ -566,6 +1135,7 @@ def submit_order_extraction(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
structured['order_extraction_submission'] = {
|
||||
'input_snapshot_hash': current_snapshot,
|
||||
'schema_version': EXTRACTION_CONTRACT_VERSION,
|
||||
'request_id': request_id,
|
||||
'result': result,
|
||||
'submitted_at': datetime.utcnow().isoformat(),
|
||||
}
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
services/shipping_notice/progress_workflow.py
|
||||
|
||||
用途:承接发货通知任务的自动推进流程,包括解析确认检查、库存准备、字段映射确认与履约侧串联。
|
||||
依赖:tool_common、query_service、inventory_mapping_workflow、inventory_workflow、fulfillment_workflow、tool_response。
|
||||
依赖:customer_identity_gate、tool_common、query_service、inventory_mapping_workflow、inventory_workflow、fulfillment_workflow、tool_response。
|
||||
逻辑:由 task_workflow 对外转调本文件;本文件按当前任务状态决定继续自动推进、停在人审检查点,或进入履约 workflow。
|
||||
"""
|
||||
|
||||
@@ -37,6 +37,7 @@ from app.services.shipping_notice.query_service import resolve_task_from_payload
|
||||
from app.services.shipping_notice.state_machine import TaskTransition, apply_task_transition, resolve_task_ui_state
|
||||
from app.services.shipping_notice.tool_common import auto_progress_enabled, auto_rpa_inventory_enabled, set_task_step_progress
|
||||
from app.services.shipping_notice.tool_response import tool_response
|
||||
from app.services.shipping_notice.customer_identity_gate import customer_gate_tool_response
|
||||
|
||||
|
||||
def auto_progress(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
@@ -108,6 +109,10 @@ def auto_progress(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
stop_agent_turn=True,
|
||||
)
|
||||
|
||||
customer_gate = customer_gate_tool_response(task, operation='auto_progress')
|
||||
if customer_gate is not None:
|
||||
return customer_gate
|
||||
|
||||
if task.pending_human_reason == PH_INVENTORY_SOURCE_UNRESOLVED or not is_inventory_source_stable(task):
|
||||
adjudication = ensure_inventory_source_review_state(task)
|
||||
db.session.commit()
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
services/shipping_notice/query_service.py
|
||||
|
||||
用途:发货通知读模型 — 任务/批次查询、排序与序列化投影(含版本链与重复决策字段)。
|
||||
依赖:models.ShippingBatch、ShippingTask、ShippingTaskEvent。
|
||||
依赖:models.ShippingBatch、ShippingCase、ShippingTask、ShippingTaskEvent。
|
||||
逻辑:workspace_shipping_notice 与 shipping_notice_tools 的读路径统一经本模块;
|
||||
tools.py 通过 TaskProjection / BatchProjection 委托序列化与任务解析,写路径逐步下沉;
|
||||
SUMMARY/DETAIL 经 _task_version_chain_fields 暴露 document_version / supersedes / duplicate_*。
|
||||
@@ -18,11 +18,18 @@ from typing import Any
|
||||
from sqlalchemy import asc, desc
|
||||
|
||||
from app import db
|
||||
from app.models import ShippingBatch, ShippingTask
|
||||
from app.models import (
|
||||
ShippingBatch,
|
||||
ShippingCase,
|
||||
ShippingNoticeCandidate,
|
||||
ShippingNoticeIntake,
|
||||
ShippingTask,
|
||||
)
|
||||
|
||||
EXPORT_MIME_TYPE = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
|
||||
|
||||
_TASK_NO_RE = re.compile(r"SN-\d{8}-[A-F0-9]{8}", re.IGNORECASE)
|
||||
_BUSINESS_NO_RE = re.compile(r"(?<![A-Z0-9])[A-Z]{2,6}\d{8}(?![A-Z0-9])", re.IGNORECASE)
|
||||
|
||||
|
||||
class TaskProjection(str, Enum):
|
||||
@@ -61,13 +68,33 @@ def sort_batch_tasks(tasks: list[ShippingTask]) -> list[ShippingTask]:
|
||||
|
||||
|
||||
def get_task_by_ref(task_ref: str) -> ShippingTask | None:
|
||||
"""按 task_no 或数字主键查找任务(Tool API / 内部引用解析)。"""
|
||||
"""按 task_no、business_no 或数字主键查找任务;作废原号跟随替代链返回当前最新版本。"""
|
||||
value = str(task_ref or "").strip()
|
||||
if not value:
|
||||
return None
|
||||
task = ShippingTask.query.filter_by(task_no=value).first()
|
||||
if task:
|
||||
return task
|
||||
case = db.session.query(ShippingCase).filter_by(business_no=value.upper()).first()
|
||||
if case is not None:
|
||||
visited: set[int] = set()
|
||||
while case.id not in visited:
|
||||
visited.add(int(case.id))
|
||||
replacement = (
|
||||
db.session.query(ShippingCase)
|
||||
.filter_by(replaces_case_id=case.id)
|
||||
.order_by(ShippingCase.id.desc())
|
||||
.first()
|
||||
)
|
||||
if replacement is None:
|
||||
break
|
||||
case = replacement
|
||||
return (
|
||||
db.session.query(ShippingTask)
|
||||
.filter_by(shipping_case_id=case.id)
|
||||
.order_by(ShippingTask.document_version.desc(), ShippingTask.id.desc())
|
||||
.first()
|
||||
)
|
||||
if value.isdigit():
|
||||
return db.session.get(ShippingTask, int(value))
|
||||
return None
|
||||
@@ -81,6 +108,71 @@ def get_batch_by_no(batch_no: str) -> ShippingBatch | None:
|
||||
return ShippingBatch.query.filter_by(batch_no=value).first()
|
||||
|
||||
|
||||
def resolve_order_extraction_ui_target(
|
||||
*,
|
||||
user_id: int,
|
||||
conversation_id: str,
|
||||
intake_nos: list[str],
|
||||
) -> tuple[ShippingBatch | None, ShippingTask | None]:
|
||||
"""
|
||||
按本轮 Intake 消费关系解析订单抽取完成后的 UI State 目标。
|
||||
|
||||
核心逻辑:先查当前用户、当前会话、指定 Intake 直接消费的新 Batch;没有新 Batch 时,
|
||||
再沿 Candidate.consumed_task_id 查找打开的既有 Task。禁止回退到“用户最近批次”,避免并发会话串单。
|
||||
|
||||
Args:
|
||||
user_id: 当前聊天用户 ID。
|
||||
conversation_id: 当前 HXOPS ChatSession.session_id。
|
||||
intake_nos: 本轮 agent_runtime_context.refs.intake_nos。
|
||||
Returns:
|
||||
`(batch, task)`;新建批次时 batch 非空,只有 open_existing 时 task 非空。
|
||||
"""
|
||||
normalized = sorted({str(item or '').strip().upper() for item in intake_nos if str(item or '').strip()})
|
||||
session_id = str(conversation_id or '').strip()
|
||||
if not normalized or not session_id:
|
||||
return None, None
|
||||
|
||||
intakes = (
|
||||
db.session.query(ShippingNoticeIntake)
|
||||
.filter(
|
||||
ShippingNoticeIntake.user_id == int(user_id),
|
||||
ShippingNoticeIntake.conversation_id == session_id,
|
||||
ShippingNoticeIntake.intake_no.in_(normalized),
|
||||
)
|
||||
.order_by(ShippingNoticeIntake.id.asc())
|
||||
.all()
|
||||
)
|
||||
if {item.intake_no for item in intakes} != set(normalized):
|
||||
return None, None
|
||||
|
||||
batch_ids = [int(item.consumed_batch_id) for item in intakes if item.consumed_batch_id is not None]
|
||||
if batch_ids:
|
||||
batch = (
|
||||
db.session.query(ShippingBatch)
|
||||
.filter(
|
||||
ShippingBatch.id.in_(batch_ids),
|
||||
ShippingBatch.user_id == int(user_id),
|
||||
ShippingBatch.conversation_id == session_id,
|
||||
)
|
||||
.order_by(ShippingBatch.created_at.desc(), ShippingBatch.id.desc())
|
||||
.first()
|
||||
)
|
||||
if batch is not None:
|
||||
return batch, None
|
||||
|
||||
task = (
|
||||
db.session.query(ShippingTask)
|
||||
.join(ShippingNoticeCandidate, ShippingNoticeCandidate.consumed_task_id == ShippingTask.id)
|
||||
.filter(
|
||||
ShippingNoticeCandidate.intake_id.in_([int(item.id) for item in intakes]),
|
||||
ShippingTask.user_id == int(user_id),
|
||||
)
|
||||
.order_by(ShippingNoticeCandidate.id.asc(), ShippingTask.id.asc())
|
||||
.first()
|
||||
)
|
||||
return None, task
|
||||
|
||||
|
||||
def get_task_in_batch(batch_no: str, task_no: str) -> ShippingTask | None:
|
||||
"""查找属于指定批次的任务;批次不存在或任务不在批次内时返回 None。"""
|
||||
batch = get_batch_by_no(batch_no)
|
||||
@@ -197,8 +289,9 @@ def compute_conversation_workspace_summary(batches: list[ShippingBatch]) -> dict
|
||||
|
||||
|
||||
def extract_task_no_from_text(text: str) -> str | None:
|
||||
"""从自然语言文本中提取 SN- 任务编号。"""
|
||||
match = _TASK_NO_RE.search(str(text or ""))
|
||||
"""从自然语言文本中提取 SN 技术号或客户业务号。"""
|
||||
raw = str(text or "")
|
||||
match = _TASK_NO_RE.search(raw) or _BUSINESS_NO_RE.search(raw)
|
||||
return match.group(0).upper() if match else None
|
||||
|
||||
|
||||
@@ -253,6 +346,9 @@ def _task_tool_payload(task: ShippingTask) -> dict[str, Any]:
|
||||
step_payload = task.step_payload_json or {}
|
||||
payload: dict[str, Any] = {
|
||||
"task_no": task.task_no,
|
||||
"shipping_case_id": task.shipping_case_id,
|
||||
"case_no": task.shipping_case.case_no if task.shipping_case else None,
|
||||
"business_no": task.shipping_case.business_no if task.shipping_case else None,
|
||||
"process_status": task.process_status,
|
||||
"current_step": task.current_step,
|
||||
"review_status": task.review_status,
|
||||
@@ -260,6 +356,11 @@ def _task_tool_payload(task: ShippingTask) -> dict[str, Any]:
|
||||
"pending_human_reason": task.pending_human_reason,
|
||||
"customer_name": task.customer_name,
|
||||
"customer_code": task.customer_code,
|
||||
"customer_resolution_status": task.customer_resolution_status,
|
||||
"customer_resolution_method": task.customer_resolution_method,
|
||||
"customer_id": task.shipping_case.customer_id if task.shipping_case else None,
|
||||
"customer_name_snapshot": task.shipping_case.customer_name_snapshot if task.shipping_case else None,
|
||||
"customer_short_code_snapshot": task.shipping_case.customer_short_code_snapshot if task.shipping_case else None,
|
||||
"ship_to": task.ship_to,
|
||||
"po_number": task.po_number,
|
||||
"required_date": task.required_date,
|
||||
@@ -343,6 +444,9 @@ def serialize_task(task: ShippingTask, projection: TaskProjection) -> dict[str,
|
||||
data = {
|
||||
"id": task.id,
|
||||
"task_no": task.task_no,
|
||||
"shipping_case_id": task.shipping_case_id,
|
||||
"case_no": task.shipping_case.case_no if task.shipping_case else None,
|
||||
"business_no": task.shipping_case.business_no if task.shipping_case else None,
|
||||
"batch_no": _task_batch_no(task),
|
||||
"source_type": task.source_type,
|
||||
"source_file_name": task.source_file_name,
|
||||
@@ -350,6 +454,11 @@ def serialize_task(task: ShippingTask, projection: TaskProjection) -> dict[str,
|
||||
"batch_index": task.batch_index,
|
||||
"batch_total": task.batch_total,
|
||||
"customer_name": task.customer_name,
|
||||
"customer_resolution_status": task.customer_resolution_status,
|
||||
"customer_resolution_method": task.customer_resolution_method,
|
||||
"customer_id": task.shipping_case.customer_id if task.shipping_case else None,
|
||||
"customer_name_snapshot": task.shipping_case.customer_name_snapshot if task.shipping_case else None,
|
||||
"customer_short_code_snapshot": task.shipping_case.customer_short_code_snapshot if task.shipping_case else None,
|
||||
"current_step": task.current_step,
|
||||
"process_status": task.process_status,
|
||||
"review_status": task.review_status,
|
||||
@@ -371,7 +480,7 @@ def serialize_task(task: ShippingTask, projection: TaskProjection) -> dict[str,
|
||||
"destination_country": task.destination_country,
|
||||
"warehouse_hint": task.warehouse_hint,
|
||||
"inventory_source_code": task.inventory_source_code,
|
||||
"inventory_source_type": task.inventory_source_type,
|
||||
"inventory_connector_type": task.inventory_connector_type,
|
||||
"inventory_site_id": task.inventory_site_id,
|
||||
"inventory_warehouse_id": task.inventory_warehouse_id,
|
||||
"inventory_source_status": task.inventory_source_status,
|
||||
|
||||
@@ -131,7 +131,7 @@ def write_inventory_export_batch_trigger(
|
||||
continue
|
||||
inventory_sources.append({
|
||||
"source_code": source.get("source_code"),
|
||||
"source_type": source.get("source_type"),
|
||||
"connector_type": source.get("connector_type"),
|
||||
"site_id": source.get("site_id"),
|
||||
"warehouse_id": source.get("warehouse_id"),
|
||||
"entry_url": source.get("entry_url"),
|
||||
|
||||
@@ -24,6 +24,7 @@ from app.services.shipping_notice.constants import (
|
||||
CP_EXPORT_GENERATED,
|
||||
CP_INVENTORY_PENDING,
|
||||
CP_INVENTORY_SOURCE_REVIEW,
|
||||
CP_CUSTOMER_REVIEW,
|
||||
CP_MAP_INFER,
|
||||
CP_PARSE_REVIEW,
|
||||
CP_NOTICE_TEXT_EXTRACTION_FAILED,
|
||||
@@ -75,6 +76,7 @@ ACTION_SPECS: dict[str, dict[str, str]] = {
|
||||
"rematch": {"label": "重新匹配", "message": "重新匹配", "variant": "secondary"},
|
||||
"retry_rpa": {"label": "重新获取库存", "message": "重新获取库存", "variant": "secondary"},
|
||||
"confirm_inventory_source": {"label": "确认库存源", "message": "确认库存查询来源", "variant": "primary"},
|
||||
"confirm_customer": {"label": "确认客户", "message": "选择并确认标准客户", "variant": "primary"},
|
||||
"retry_resolve_inventory_source": {"label": "重新判断", "message": "重新判断库存查询来源", "variant": "secondary"},
|
||||
"refresh": {"label": "刷新", "message": "刷新", "variant": "secondary"},
|
||||
"upload_inventory_file": {
|
||||
@@ -110,6 +112,7 @@ ACTION_SPECS: dict[str, dict[str, str]] = {
|
||||
# checkpoint id → default human option ids (HTTP / Dify before task reload)
|
||||
CHECKPOINT_REGISTRY: dict[str, tuple[str, ...]] = {
|
||||
CP_PARSE_REVIEW: ("confirm", "reject", "reparse"),
|
||||
CP_CUSTOMER_REVIEW: ("confirm_customer",),
|
||||
CP_ALIGN_REVIEW: (
|
||||
"confirm_inventory_mapping",
|
||||
"correct_inventory_mapping",
|
||||
@@ -275,8 +278,32 @@ def resolve_task_ui_state(task: ShippingTask) -> TaskUiState:
|
||||
if task.process_status == "rejected" or task.review_status == "rejected":
|
||||
return TaskUiState(checkpoint=CP_REJECTED, human_options=[])
|
||||
|
||||
# [STEP 2] RPA 库存耗尽与解析后待库存 — 正向流程中的「下一步」节点。
|
||||
if task.pending_human_reason == PH_RPA_EXHAUSTED:
|
||||
# [STEP 2] 先完成订单解析复核,再暴露客户确认节点。
|
||||
reason = task.pending_human_reason
|
||||
if reason == PH_RSV_REQ or task.review_status == RS_RSV_REQ:
|
||||
return TaskUiState(
|
||||
checkpoint=CP_RSV_REQ,
|
||||
human_options=list(CHECKPOINT_REGISTRY[CP_RSV_REQ]),
|
||||
)
|
||||
if reason == PH_LOW_CONF or task.review_status == RS_PARSE_REVIEW:
|
||||
return TaskUiState(
|
||||
checkpoint=CP_PARSE_REVIEW,
|
||||
human_options=list(CHECKPOINT_REGISTRY[CP_PARSE_REVIEW]),
|
||||
)
|
||||
if reason == PH_NOTICE_TEXT_EXTRACTION_FAILED:
|
||||
return TaskUiState(
|
||||
checkpoint=CP_NOTICE_TEXT_EXTRACTION_FAILED,
|
||||
human_options=list(CHECKPOINT_REGISTRY[CP_NOTICE_TEXT_EXTRACTION_FAILED]),
|
||||
)
|
||||
|
||||
if task.shipping_case_id is not None and task.customer_resolution_status != "confirmed":
|
||||
return TaskUiState(
|
||||
checkpoint=CP_CUSTOMER_REVIEW,
|
||||
human_options=list(CHECKPOINT_REGISTRY[CP_CUSTOMER_REVIEW]),
|
||||
)
|
||||
|
||||
# [STEP 3] 客户确认后,才进入库存和履约节点。
|
||||
if reason == PH_RPA_EXHAUSTED:
|
||||
return TaskUiState(
|
||||
checkpoint=CP_UPLOAD_REQ,
|
||||
human_options=upload_req_options_for_task(task),
|
||||
@@ -306,7 +333,7 @@ def resolve_task_ui_state(task: ShippingTask) -> TaskUiState:
|
||||
human_options=list(CHECKPOINT_REGISTRY[CP_READY_MATCH]),
|
||||
)
|
||||
|
||||
# [STEP 3] 匹配/导出阶段 — matched 后区分待生成与已生成 Excel。
|
||||
# [STEP 4] 匹配/导出阶段 — matched 后区分待生成与已生成 Excel。
|
||||
if task.process_status == "matched":
|
||||
if task.export_file_path:
|
||||
return TaskUiState(
|
||||
@@ -318,8 +345,7 @@ def resolve_task_ui_state(task: ShippingTask) -> TaskUiState:
|
||||
human_options=list(CHECKPOINT_REGISTRY[CP_READY_EXPORT]),
|
||||
)
|
||||
|
||||
# [STEP 4] 人审分支 — 按 pending_human_reason / review_status 映射 checkpoint。
|
||||
reason = task.pending_human_reason
|
||||
# [STEP 5] 人审分支 — 按 pending_human_reason / review_status 映射 checkpoint。
|
||||
if reason == PH_ALIGN_REVIEW or task.review_status == RS_ALIGN_REVIEW:
|
||||
return TaskUiState(
|
||||
checkpoint=CP_ALIGN_REVIEW,
|
||||
@@ -330,11 +356,6 @@ def resolve_task_ui_state(task: ShippingTask) -> TaskUiState:
|
||||
checkpoint=CP_MAP_INFER,
|
||||
human_options=list(CHECKPOINT_REGISTRY[CP_MAP_INFER]),
|
||||
)
|
||||
if reason == PH_RSV_REQ or task.review_status == RS_RSV_REQ:
|
||||
return TaskUiState(
|
||||
checkpoint=CP_RSV_REQ,
|
||||
human_options=list(CHECKPOINT_REGISTRY[CP_RSV_REQ]),
|
||||
)
|
||||
if reason == PH_INV_UNAVAIL:
|
||||
return TaskUiState(
|
||||
checkpoint=CP_UPLOAD_REQ,
|
||||
@@ -350,16 +371,6 @@ def resolve_task_ui_state(task: ShippingTask) -> TaskUiState:
|
||||
checkpoint=RS_SHORTAGE_REVIEW,
|
||||
human_options=list(CHECKPOINT_REGISTRY[RS_SHORTAGE_REVIEW]),
|
||||
)
|
||||
if reason == PH_LOW_CONF or task.review_status == RS_PARSE_REVIEW:
|
||||
return TaskUiState(
|
||||
checkpoint=CP_PARSE_REVIEW,
|
||||
human_options=list(CHECKPOINT_REGISTRY[CP_PARSE_REVIEW]),
|
||||
)
|
||||
if reason == PH_NOTICE_TEXT_EXTRACTION_FAILED:
|
||||
return TaskUiState(
|
||||
checkpoint=CP_NOTICE_TEXT_EXTRACTION_FAILED,
|
||||
human_options=list(CHECKPOINT_REGISTRY[CP_NOTICE_TEXT_EXTRACTION_FAILED]),
|
||||
)
|
||||
if reason == PH_UPLOAD_RPA_FAILED or task.process_status == "upload_failed":
|
||||
return TaskUiState(
|
||||
checkpoint=CP_UPLOAD_FAILED,
|
||||
|
||||
@@ -67,6 +67,7 @@ from app.services.shipping_notice.batch_create_idempotency import (
|
||||
handle_batch_create_integrity_error,
|
||||
normalize_create_idempotency_key,
|
||||
)
|
||||
from app.services.shipping_notice.business_case_service import resolve_shipping_case_for_new_task
|
||||
from app.services.shipping_notice.tool_common import (
|
||||
auto_progress_enabled,
|
||||
defer_parse_to_dify_enabled,
|
||||
@@ -83,7 +84,6 @@ EDITABLE_NOTICE_LINE_FIELDS = frozenset({
|
||||
"quantity",
|
||||
"required_date",
|
||||
"uom",
|
||||
"hub_code",
|
||||
"source_type",
|
||||
})
|
||||
|
||||
@@ -167,22 +167,17 @@ def _missing_reservation_lines(lines: list[Any]) -> list[dict[str, Any]]:
|
||||
return missing
|
||||
|
||||
|
||||
def _missing_process_field_issues(
|
||||
lines: list[Any],
|
||||
*,
|
||||
require_order_extraction_routing: bool,
|
||||
) -> list[dict[str, Any]]:
|
||||
def _missing_process_field_issues(lines: list[Any]) -> list[dict[str, Any]]:
|
||||
"""
|
||||
检查 Task 进入库存链前必须补齐的订单行流程字段。
|
||||
|
||||
核心逻辑:所有入口继续检查 Reservation ID;仅本期完整订单抽取契约额外检查 Source Type 与 Hub Code,
|
||||
避免把新协议强行扩散到历史手工 parse_notice 调用。
|
||||
核心逻辑:所有入口只检查 Reservation ID;行级 Source Type 是可选库存源路由线索,
|
||||
Hub Code 不属于新订单抽取契约,也不参与流程门禁。
|
||||
|
||||
Args:
|
||||
lines: 已标准化的订单行。
|
||||
require_order_extraction_routing: 是否启用 v1 订单抽取的 Source Type/Hub Code 门禁。
|
||||
Returns:
|
||||
每个缺失字段对应的结构化 issue,包含行号、SKU、field 与原因。
|
||||
每个缺失或格式非法 Reservation ID 对应的结构化 issue。
|
||||
"""
|
||||
issues: list[dict[str, Any]] = []
|
||||
for index, line in enumerate(lines):
|
||||
@@ -190,29 +185,16 @@ def _missing_process_field_issues(
|
||||
continue
|
||||
sku = str(line.get('sku') or '').strip()
|
||||
raw_reservation = str(line.get('reservation_id') or '').strip()
|
||||
field_values = {
|
||||
'reservation_id': raw_reservation if is_valid_reservation_id(raw_reservation) else None,
|
||||
}
|
||||
if require_order_extraction_routing:
|
||||
field_values.update({
|
||||
'source_type': str(line.get('source_type') or '').strip() or None,
|
||||
'hub_code': str(line.get('hub_code') or '').strip() or None,
|
||||
})
|
||||
for field, value in field_values.items():
|
||||
if value:
|
||||
continue
|
||||
issues.append({
|
||||
'line_index': index,
|
||||
'sku': sku,
|
||||
'field': field,
|
||||
'reason': (
|
||||
'invalid_format'
|
||||
if field == 'reservation_id' and raw_reservation
|
||||
else 'missing'
|
||||
),
|
||||
'severity': 'blocking',
|
||||
'raw_value': str(line.get(field) or '').strip(),
|
||||
})
|
||||
if is_valid_reservation_id(raw_reservation):
|
||||
continue
|
||||
issues.append({
|
||||
'line_index': index,
|
||||
'sku': sku,
|
||||
'field': 'reservation_id',
|
||||
'reason': 'invalid_format' if raw_reservation else 'missing',
|
||||
'severity': 'blocking',
|
||||
'raw_value': raw_reservation,
|
||||
})
|
||||
return issues
|
||||
|
||||
|
||||
@@ -416,8 +398,15 @@ def create_batch_tasks(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
if not isinstance(item, dict):
|
||||
continue
|
||||
content_hash = str(item.get("source_content_hash") or "").strip().lower() or None
|
||||
resolution_type = str(item.get("duplicate_resolution_type") or "normal").strip() or "normal"
|
||||
shipping_case = resolve_shipping_case_for_new_task(
|
||||
supersedes_task_id=item.get("supersedes_task_id"),
|
||||
duplicate_resolution_type=resolution_type,
|
||||
created_by_id=payload.get("user_id"),
|
||||
)
|
||||
task = ShippingTask(
|
||||
task_no=generate_task_no(),
|
||||
shipping_case_id=shipping_case.id,
|
||||
batch_id=batch.id,
|
||||
user_id=payload.get("user_id"),
|
||||
conversation_id=str(payload.get("conversation_id") or "").strip() or None,
|
||||
@@ -436,10 +425,16 @@ def create_batch_tasks(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
supersedes_task_id=item.get("supersedes_task_id"),
|
||||
duplicate_source_task_id=item.get("duplicate_source_task_id"),
|
||||
duplicate_override_reason=str(item.get("duplicate_override_reason") or "").strip() or None,
|
||||
duplicate_resolution_type=str(item.get("duplicate_resolution_type") or "normal").strip() or "normal",
|
||||
duplicate_resolution_type=resolution_type,
|
||||
batch_index=idx,
|
||||
batch_total=total,
|
||||
raw_content=str(item.get("raw_text") or "").strip() or None,
|
||||
customer_resolution_status=(
|
||||
'confirmed' if shipping_case.customer_id is not None else 'pending'
|
||||
),
|
||||
customer_resolution_method=(
|
||||
'inherited' if shipping_case.customer_id is not None else None
|
||||
),
|
||||
process_status="created",
|
||||
)
|
||||
db.session.add(task)
|
||||
@@ -582,8 +577,10 @@ def create_task(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
|
||||
batch = _create_single_task_batch(payload)
|
||||
db.session.flush()
|
||||
shipping_case = resolve_shipping_case_for_new_task(created_by_id=payload.get("user_id"))
|
||||
task = ShippingTask(
|
||||
task_no=generate_task_no(),
|
||||
shipping_case_id=shipping_case.id,
|
||||
batch_id=batch.id,
|
||||
user_id=payload.get("user_id"),
|
||||
conversation_id=str(payload.get("conversation_id") or "").strip() or None,
|
||||
@@ -591,6 +588,12 @@ def create_task(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
batch_index=1,
|
||||
batch_total=1,
|
||||
raw_content=str(payload.get("raw_content") or "").strip() or None,
|
||||
customer_resolution_status=(
|
||||
'confirmed' if shipping_case.customer_id is not None else 'pending'
|
||||
),
|
||||
customer_resolution_method=(
|
||||
'inherited' if shipping_case.customer_id is not None else None
|
||||
),
|
||||
process_status="created",
|
||||
)
|
||||
db.session.add(task)
|
||||
@@ -640,8 +643,10 @@ def parse_notice(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
):
|
||||
batch = _create_single_task_batch(payload)
|
||||
db.session.flush()
|
||||
shipping_case = resolve_shipping_case_for_new_task(created_by_id=payload.get("user_id"))
|
||||
new_task = ShippingTask(
|
||||
task_no=generate_task_no(),
|
||||
shipping_case_id=shipping_case.id,
|
||||
batch_id=batch.id,
|
||||
user_id=payload.get("user_id"),
|
||||
conversation_id=conv_id or None,
|
||||
@@ -649,6 +654,12 @@ def parse_notice(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
batch_index=1,
|
||||
batch_total=1,
|
||||
raw_content=None,
|
||||
customer_resolution_status=(
|
||||
'confirmed' if shipping_case.customer_id is not None else 'pending'
|
||||
),
|
||||
customer_resolution_method=(
|
||||
'inherited' if shipping_case.customer_id is not None else None
|
||||
),
|
||||
process_status="created",
|
||||
)
|
||||
db.session.add(new_task)
|
||||
@@ -739,24 +750,12 @@ def parse_notice(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
}
|
||||
|
||||
# [STEP 3] 流程字段是后续库存匹配硬前置;允许 Task 创建,但缺失时停在字段补充门禁。
|
||||
require_order_extraction_routing = (
|
||||
isinstance(structured, dict)
|
||||
and structured.get('_order_extraction_contract') == 'shipping-order-extraction-v1'
|
||||
)
|
||||
process_field_issues = _missing_process_field_issues(
|
||||
lines,
|
||||
require_order_extraction_routing=require_order_extraction_routing,
|
||||
)
|
||||
process_field_issues = _missing_process_field_issues(lines)
|
||||
if process_field_issues:
|
||||
missing_reservation = [item for item in process_field_issues if item.get('field') == 'reservation_id']
|
||||
missing_fields = sorted({str(item.get('field') or '') for item in process_field_issues if item.get('field')})
|
||||
only_reservation_missing = missing_fields == ['reservation_id']
|
||||
missing_reservation = list(process_field_issues)
|
||||
missing_fields = ['reservation_id']
|
||||
apply_task_transition(task, TaskTransition.RSV_REQUIRED)
|
||||
task.error_message = (
|
||||
"解析失败:未识别到 Reservation ID / COM ID(预定单号)"
|
||||
if only_reservation_missing
|
||||
else f"订单已创建,但缺少后续处理必需字段:{', '.join(missing_fields)}"
|
||||
)
|
||||
task.error_message = "解析失败:未识别到 Reservation ID / COM ID(预定单号)"
|
||||
step_payload = dict(task.step_payload_json or {})
|
||||
step_payload['process_field_gate'] = {
|
||||
'status': 'needs_enrichment',
|
||||
@@ -774,7 +773,7 @@ def parse_notice(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
progress_percent=100,
|
||||
current=max(0, len(lines) - len({int(item['line_index']) for item in process_field_issues})),
|
||||
total=len(lines),
|
||||
detail="可直接通过自然对话补充 Reservation ID、Source Type 或 Hub Code;补齐前不会进入库存流程。",
|
||||
detail="可直接通过自然对话补充 Reservation ID;补齐前不会进入库存流程。",
|
||||
extra={
|
||||
"warnings": warnings,
|
||||
"missing_reservation": missing_reservation[:5],
|
||||
@@ -797,8 +796,6 @@ def parse_notice(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
message=(
|
||||
"解析失败:未识别到 Reservation ID / COM ID(预定单号),"
|
||||
"当前任务无法继续匹配库存。请重新上传包含该字段的通知,或重新解析后补充预定单号。"
|
||||
if only_reservation_missing
|
||||
else f"订单任务已创建,但缺少 {', '.join(missing_fields)};请通过自然对话补齐后继续。"
|
||||
),
|
||||
data={**serialize_task_for_tool(task), "missing_reservation": detail},
|
||||
checkpoint=CP_RSV_REQ,
|
||||
@@ -1158,15 +1155,7 @@ def _commit_notice_edit(
|
||||
) -> dict[str, Any]:
|
||||
# [STEP 1] 人工编辑后的业务值拥有最终优先级,但仍必须通过同一流程字段契约。
|
||||
step_payload = dict(task.step_payload_json or {})
|
||||
existing_gate = step_payload.get('process_field_gate')
|
||||
require_order_extraction_routing = (
|
||||
isinstance(existing_gate, dict)
|
||||
and existing_gate.get('contract_version') == 'shipping-order-extraction-v1'
|
||||
)
|
||||
validation_issues = _missing_process_field_issues(
|
||||
list(task.lines_json or []),
|
||||
require_order_extraction_routing=require_order_extraction_routing,
|
||||
)
|
||||
validation_issues = _missing_process_field_issues(list(task.lines_json or []))
|
||||
step_payload["parse_validation"] = {
|
||||
"status": "needs_review" if validation_issues else "ready",
|
||||
"issues": validation_issues,
|
||||
@@ -1179,11 +1168,7 @@ def _commit_notice_edit(
|
||||
'status': 'needs_enrichment',
|
||||
'missing_fields': missing_fields,
|
||||
'issues': validation_issues,
|
||||
'contract_version': (
|
||||
'shipping-order-extraction-v1'
|
||||
if require_order_extraction_routing
|
||||
else 'shipping-line-v1'
|
||||
),
|
||||
'contract_version': 'shipping-order-extraction-v1',
|
||||
}
|
||||
else:
|
||||
step_payload.pop('process_field_gate', None)
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
services/shipping_notice/tools.py
|
||||
|
||||
用途:发货通知 Agent Tool 统一门面(API 唯一业务入口,无编排实现)。
|
||||
依赖:task_workflow、inventory_workflow、inventory_rpa_workflow、fulfillment_workflow;order_extraction 延迟导入以避免建批循环依赖。
|
||||
依赖:customer_identity_gate、task_workflow、inventory_workflow、inventory_rpa_workflow、fulfillment_workflow;order_extraction 延迟导入以避免建批循环依赖。
|
||||
逻辑:shipping_notice_tools / workspace_shipping_notice 仅 import 本模块公开符号。
|
||||
"""
|
||||
|
||||
@@ -14,6 +14,7 @@ from app.services.shipping_notice import (
|
||||
inventory_workflow,
|
||||
task_workflow,
|
||||
)
|
||||
from app.services.shipping_notice import customer_identity_gate
|
||||
|
||||
|
||||
def get_order_extraction_context(payload: dict):
|
||||
@@ -60,6 +61,7 @@ update_notice_fields = task_workflow.update_notice_fields
|
||||
update_notice_line = task_workflow.update_notice_line
|
||||
add_notice_line = task_workflow.add_notice_line
|
||||
remove_notice_line = task_workflow.remove_notice_line
|
||||
confirm_customer = customer_identity_gate.confirm_customer
|
||||
|
||||
# 库存阶段
|
||||
ensure_inventory = inventory_workflow.ensure_inventory
|
||||
|
||||
Reference in new issue
Block a user