Merge branch 'dev' into snow

# Conflicts:
#	backend/app/api/chat.py
#	backend/app/services/admin/permission_service.py
#	backend/app/services/knowledge_cleaning/dify_sync_service.py
#	backend/app/services/knowledge_cleaning/settings_service.py
#	backend/tests/test_dify_sync_process_rule.py
#	docker-compose.yml
#	docs/funclist.md
#	frontend/package-lock.json
#	frontend/src/config.ts
#	frontend/src/features/admin/components/AdminNav.vue
#	frontend/src/features/admin/constants/modules.ts
#	frontend/src/features/admin/stores/admin-nav.store.ts
#	frontend/src/features/chat/components/messages/ChatMessageBubble.vue
#	frontend/src/features/user/views/UserProfilePage.vue
#	frontend/src/locales/en/admin.json
#	frontend/src/locales/en/auth.json
#	frontend/src/locales/en/errors.json
#	frontend/src/locales/th/admin.json
#	frontend/src/locales/th/auth.json
#	frontend/src/locales/th/errors.json
#	frontend/src/locales/zh-CN/admin.json
#	frontend/src/locales/zh-CN/auth.json
#	frontend/src/locales/zh-CN/errors.json
#	frontend/src/locales/zh-TW/admin.json
#	frontend/src/locales/zh-TW/auth.json
#	frontend/src/locales/zh-TW/errors.json
This commit is contained in:
HTEWJ\26070045 committed 2026-09-11 14:55:20 +08:00
commit ca9c174f29
2050 files changed
+511839 -42320

No files matched your search

+8
View File
@@ -15,6 +15,10 @@ from . import (
linked_service_service,
permission_service,
report_service,
shipping_customer_import_service,
shipping_customer_lifecycle_service,
shipping_customer_merge_service,
shipping_customer_service,
user_service,
wecom_admin_service,
)
@@ -30,6 +34,10 @@ __all__ = [
'linked_service_service',
'permission_service',
'report_service',
'shipping_customer_import_service',
'shipping_customer_lifecycle_service',
'shipping_customer_merge_service',
'shipping_customer_service',
'user_service',
'wecom_admin_service',
]
@@ -189,7 +189,6 @@ def promote_faq_candidate(data: dict[str, Any]) -> dict:
q_norm = normalize_faq_query(str(data.get('q_norm') or ''))
if not agent_id or not q_norm:
raise ValidationError('agent_id and q_norm are required')
candidate = HotFaqCandidateStore.get_candidate(int(agent_id), q_norm)
if not candidate:
raise NotFoundError('FAQ candidate not found')
+19 -3
View File
@@ -20,10 +20,20 @@ from app.services.minio_service import minio_service
GUIDE_USAGE_GENERAL = 'general'
GUIDE_USAGE_TRAINING_VIDEO = 'training_video'
GUIDE_USAGE_TRAINING_EXAM_PDF = 'training_exam_pdf'
GUIDE_USAGE_TRAINING_SAFETY_VIDEO = 'training_safety_video'
GUIDE_USAGE_TRAINING_SAFETY_COMPANY_VIDEO = 'training_safety_company_video'
GUIDE_USAGE_TRAINING_SAFETY_DEPARTMENT_VIDEO = 'training_safety_department_video'
GUIDE_USAGE_TRAINING_SAFETY_TEAM_VIDEO = 'training_safety_team_video'
GUIDE_USAGE_TRAINING_SAFETY_PDF = 'training_safety_pdf'
ALLOWED_GUIDE_USAGES = {
GUIDE_USAGE_GENERAL,
GUIDE_USAGE_TRAINING_VIDEO,
GUIDE_USAGE_TRAINING_EXAM_PDF,
GUIDE_USAGE_TRAINING_SAFETY_VIDEO,
GUIDE_USAGE_TRAINING_SAFETY_COMPANY_VIDEO,
GUIDE_USAGE_TRAINING_SAFETY_DEPARTMENT_VIDEO,
GUIDE_USAGE_TRAINING_SAFETY_TEAM_VIDEO,
GUIDE_USAGE_TRAINING_SAFETY_PDF,
}
@@ -59,14 +69,20 @@ def _normalize_guide_usage(raw_usage: Any, *, file_type: str) -> str:
归一化指南用途并校验与文件类型是否匹配。
用途:给后台上传/编辑指南时统一约束“培训视频”“培训试题 PDF”等资料用途,避免前端再靠排序或文件名猜测。
参数约束:training_video 仅允许 video 文件;training_exam_pdf 仅允许 pdf 文件。
参数约束:所有培训视频用途仅允许 video 文件;培训试题 PDF 用途仅允许 pdf 文件。
"""
usage = str(raw_usage or GUIDE_USAGE_GENERAL).strip() or GUIDE_USAGE_GENERAL
if usage not in ALLOWED_GUIDE_USAGES:
raise ValidationError('Invalid guide usage')
if usage == GUIDE_USAGE_TRAINING_VIDEO and file_type != 'video':
if usage in (
GUIDE_USAGE_TRAINING_VIDEO,
GUIDE_USAGE_TRAINING_SAFETY_VIDEO,
GUIDE_USAGE_TRAINING_SAFETY_COMPANY_VIDEO,
GUIDE_USAGE_TRAINING_SAFETY_DEPARTMENT_VIDEO,
GUIDE_USAGE_TRAINING_SAFETY_TEAM_VIDEO,
) and file_type != 'video':
raise ValidationError('Training video usage requires a video file')
if usage == GUIDE_USAGE_TRAINING_EXAM_PDF and file_type != 'pdf':
if usage in (GUIDE_USAGE_TRAINING_EXAM_PDF, GUIDE_USAGE_TRAINING_SAFETY_PDF) and file_type != 'pdf':
raise ValidationError('Training exam PDF usage requires a PDF file')
return usage
@@ -97,3 +97,65 @@ def update_user_permissions(user_id: int, data: dict[str, Any]) -> dict:
return {'status': 'ok'}
def list_permission_requests() -> list[dict]:
"""返回全部权限申请(按 created_at 降序)。"""
reqs = (
db.session.query(PermissionRequest)
.order_by(PermissionRequest.created_at.desc())
.all()
)
return [serialize_permission_request(r) for r in reqs]
def approve_permission_request(request_id: int) -> dict:
"""
批准权限申请:更新状态并将 Agent 加入用户权限。
Raises:
NotFoundError: 申请不存在。
"""
req = db.session.get(PermissionRequest, request_id)
if not req:
raise NotFoundError('Not found')
user = db.session.get(User, req.user_id)
agent = db.session.get(Agent, req.agent_id)
req.status = 'approved'
req.reviewed_at = datetime.utcnow()
if user and agent and (agent not in user.agents):
user.agents.append(agent)
if user and user.wecom_userid:
send_wecom_event_message(
event_type='permission_request_approved',
user=user,
title='权限申请已通过',
content=f'你申请的应用权限已通过:{(agent.name if agent else req.agent_id)}',
jump_path='/workspace',
)
db.session.commit()
return {'status': 'ok'}
def reject_permission_request(request_id: int) -> dict:
"""
拒绝权限申请并通知用户(若已绑定企微)。
Raises:
NotFoundError: 申请不存在。
"""
req = db.session.get(PermissionRequest, request_id)
if not req:
raise NotFoundError('Not found')
req.status = 'rejected'
req.reviewed_at = datetime.utcnow()
user = db.session.get(User, req.user_id)
agent = db.session.get(Agent, req.agent_id)
if user and user.wecom_userid:
send_wecom_event_message(
event_type='permission_request_rejected',
user=user,
title='权限申请未通过',
content=f'你申请的应用权限未通过:{(agent.name if agent else req.agent_id)}',
jump_path='/workspace',
)
db.session.commit()
return {'status': 'ok'}
@@ -0,0 +1,711 @@
"""
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
target = db.session.get(ShippingCustomer, target_id)
if target is None:
raise NotFoundError('Target customer not found', code='SHIPPING.CUSTOMER_NOT_FOUND')
if target.status != 'active':
raise ValidationError('Target customer must be active', code='SHIPPING.CUSTOMER_MERGE_TARGET_INVALID')
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 target.status != 'active':
raise ValidationError('Target customer must be active', code='SHIPPING.CUSTOMER_MERGE_TARGET_INVALID')
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,262 @@
"""
services/admin/shipping_customer_lifecycle_service.py
用途:统一计算货代客户生命周期影响和永久删除资格。
依赖:客户、业务单、流水、导入、影子识别模型及统一 AppError。
逻辑:所有删除入口先调用本服务;业务和识别审计引用均阻断删除,识别证据仅作为可级联配置数据。
"""
from __future__ import annotations
from typing import Any
from app import db
from sqlalchemy import select
from app.core.errors import ConflictError, NotFoundError, ValidationError
from app.models import (
ShippingBusinessSequence,
ShippingCustomer,
ShippingCustomerExternalRef,
ShippingCustomerIdentifier,
ShippingIdentityEvidence,
ShippingCustomerImportRow,
ShippingCustomerLifecycleEvent,
ShippingCustomerSite,
ShippingOrderTask,
ShippingCustomerShadowMatch,
ShippingCustomerShadowResolution,
ShippingNotice,
)
def _legacy_shadow_json_match_count(customer_id: int, *, matched_resolution_ids: set[int]) -> int:
"""统计规范化迁移前 JSON 中仍未映射的候选,防止现存审计记录漏算。"""
count = 0
rows = db.session.query(
ShippingCustomerShadowResolution.id,
ShippingCustomerShadowResolution.candidate_matches_json,
).all()
for resolution_id, matches in rows:
if int(resolution_id) in matched_resolution_ids:
continue
for item in matches or []:
if not isinstance(item, dict):
continue
try:
if int(item.get('customer_id')) == customer_id:
count += 1
break
except (TypeError, ValueError):
continue
return count
def _build_customer_lifecycle_impact(customer: ShippingCustomer) -> dict[str, Any]:
"""按已锁定或已读取的客户对象统计删除资格,保证各删除入口使用同一口径。"""
matched_resolution_ids = {
int(row[0])
for row in db.session.query(ShippingCustomerShadowMatch.resolution_id)
.filter_by(customer_id=customer.id)
.all()
}
shadow_normalized = len(matched_resolution_ids)
blockers = {
'shipping_notices': (
db.session.query(ShippingNotice.id)
.join(ShippingOrderTask, ShippingOrderTask.id == ShippingNotice.order_task_id)
.join(ShippingCustomerShadowResolution, ShippingCustomerShadowResolution.candidate_id == ShippingOrderTask.candidate_id)
.filter(
ShippingCustomerShadowResolution.confirmed_customer_id == customer.id,
)
.distinct()
.count()
),
'business_sequences': db.session.query(ShippingBusinessSequence.id).filter_by(customer_id=customer.id).count(),
'external_references': db.session.query(ShippingCustomerExternalRef.id).filter_by(customer_id=customer.id).count(),
'confirmed_customer_resolutions': db.session.query(ShippingCustomerShadowResolution.id).filter_by(confirmed_customer_id=customer.id).count(),
'import_target_rows': db.session.query(ShippingCustomerImportRow.id).filter_by(target_customer_id=customer.id).count(),
'import_result_rows': db.session.query(ShippingCustomerImportRow.id).filter_by(result_customer_id=customer.id).count(),
'shadow_top_candidates': db.session.query(ShippingCustomerShadowResolution.id).filter_by(top_customer_id=customer.id).count(),
'shadow_manual_labels': db.session.query(ShippingCustomerShadowResolution.id).filter_by(manual_customer_id=customer.id).count(),
'shadow_candidate_matches': shadow_normalized + _legacy_shadow_json_match_count(
customer.id,
matched_resolution_ids=matched_resolution_ids,
),
'merged_source_customers': db.session.query(ShippingCustomer.id).filter_by(
merged_into_customer_id=customer.id,
).count(),
'merged_into_customer': int(customer.merged_into_customer_id is not None),
}
return {
'customer': {
'id': customer.id,
'standard_name': customer.standard_name,
'short_code': customer.short_code,
'status': customer.status,
},
'can_delete': not any(blockers.values()),
'blockers': blockers,
'cascade': {
'identifiers': db.session.query(ShippingCustomerIdentifier.id).filter_by(customer_id=customer.id).count(),
'identity_evidences': db.session.query(ShippingIdentityEvidence.id).filter_by(customer_id=customer.id).count(),
'sites': db.session.query(ShippingCustomerSite.id).filter_by(customer_id=customer.id).count(),
},
}
def get_customer_lifecycle_impact(customer_id: int) -> dict[str, Any]:
"""
返回客户永久删除前必须检查的全部引用和可级联配置数据。
Args:
customer_id: 标准客户主键。
Returns:
客户快照、can_delete、阻断引用计数和可级联识别证据数。
"""
customer = db.session.get(ShippingCustomer, customer_id)
if customer is None:
raise NotFoundError('Customer not found', code='SHIPPING.CUSTOMER_NOT_FOUND')
return _build_customer_lifecycle_impact(customer)
def get_customer_lifecycle_timeline(customer_id: int, *, limit: int = 100) -> dict[str, Any]:
"""返回客户关键治理操作的倒序时间线,事件只含快照而不依赖客户外键。"""
customer = db.session.get(ShippingCustomer, customer_id)
rows = (
db.session.query(ShippingCustomerLifecycleEvent)
.filter_by(customer_id_snapshot=customer_id)
.order_by(ShippingCustomerLifecycleEvent.id.desc())
.limit(max(1, min(int(limit), 500)))
.all()
)
if customer is None and not rows:
raise NotFoundError('Customer not found', code='SHIPPING.CUSTOMER_NOT_FOUND')
# 受控删除后主表已不存在;以最近生命周期快照继续提供审计回放。
customer_snapshot = _build_customer_lifecycle_impact(customer)['customer'] if customer is not None else {
'id': customer_id,
'standard_name': rows[0].customer_name_snapshot,
'short_code': rows[0].customer_short_code_snapshot,
'status': 'deleted',
}
return {
'customer': customer_snapshot,
'items': [{
'id': row.id,
'event_type': row.event_type,
'actor_id': row.actor_id,
'reason': row.reason,
'detail': row.detail_json or {},
'created_at': row.created_at.isoformat() if row.created_at else None,
} for row in rows],
}
def get_customer_governance_quality(*, limit: int = 100) -> dict[str, Any]:
"""汇总影子识别、自动确认门禁和生命周期事件,供管理端持续治理。"""
from app.services.shipping_notice.customer_shadow_resolution import get_shadow_quality_report
from app.services.shipping_notice.customer_auto_resolution import get_auto_resolution_metrics
report = get_shadow_quality_report(limit=limit)
report['auto_resolution'] = get_auto_resolution_metrics()
event_counts = dict(
db.session.query(ShippingCustomerLifecycleEvent.event_type, db.func.count())
.group_by(ShippingCustomerLifecycleEvent.event_type)
.all()
)
return {
'shadow_quality': report,
'lifecycle_event_counts': event_counts,
}
def delete_customer(
customer_id: int,
*,
confirmation_short_code: object,
reason: object,
actor_id: int | None,
) -> dict[str, Any]:
"""
受控永久删除未进入任何业务或审计链的误建客户。
Args:
customer_id: 待删除的标准客户主键。
confirmation_short_code: 管理员二次输入的客户简码,忽略首尾空格并按大写比对。
reason: 必填删除原因,写入不可反向引用客户的生命周期审计。
actor_id: 当前管理员主键。
Returns:
已删除客户的快照、级联删除证据数与审计事件主键。
Raises:
ValidationError: 删除原因或二次确认简码不合法。
ConflictError: 锁定后发现存在任一阻断引用。
NotFoundError: 客户不存在。
"""
confirmed_code = str(confirmation_short_code or '').strip().upper()
delete_reason = str(reason or '').strip()
if not delete_reason:
raise ValidationError(
'Customer deletion reason is required',
code='SHIPPING.CUSTOMER_DELETE_REASON_REQUIRED',
details={'field': 'reason'},
)
try:
# 锁住客户行后再统计引用,避免预检与提交之间出现可删除的错误判断。
customer = db.session.execute(
select(ShippingCustomer)
.where(ShippingCustomer.id == customer_id)
.with_for_update()
).scalar_one_or_none()
if customer is None:
raise NotFoundError('Customer not found', code='SHIPPING.CUSTOMER_NOT_FOUND')
if confirmed_code != customer.short_code:
raise ValidationError(
'Customer deletion confirmation short code is invalid',
code='SHIPPING.CUSTOMER_DELETE_CONFIRMATION_INVALID',
details={'field': 'confirmation_short_code'},
)
impact = _build_customer_lifecycle_impact(customer)
if not impact['can_delete']:
raise ConflictError(
'Customer deletion is blocked by lifecycle references',
code='SHIPPING.CUSTOMER_DELETE_BLOCKED',
details={'blockers': impact['blockers']},
)
event = ShippingCustomerLifecycleEvent(
event_type='deleted',
customer_id_snapshot=customer.id,
customer_name_snapshot=customer.standard_name,
customer_short_code_snapshot=customer.short_code,
actor_id=actor_id,
reason=delete_reason,
detail_json={
'cascade': impact['cascade'],
},
)
customer_snapshot = impact['customer']
db.session.add(event)
db.session.flush()
# 新模型未在 Customer ORM 上定义 relationship;显式清理可级联配置,避免删除误建客户时外键阻断。
db.session.query(ShippingIdentityEvidence).filter_by(customer_id=customer.id).delete(synchronize_session=False)
site_ids = [item.id for item in db.session.query(ShippingCustomerSite.id).filter_by(customer_id=customer.id).all()]
if site_ids:
db.session.query(ShippingIdentityEvidence).filter(ShippingIdentityEvidence.site_id.in_(site_ids)).delete(
synchronize_session=False,
)
db.session.delete(customer)
db.session.commit()
return {
'deleted_customer': customer_snapshot,
'cascade': impact['cascade'],
'lifecycle_event_id': event.id,
}
except (ConflictError, NotFoundError, ValidationError):
db.session.rollback()
raise
except Exception:
db.session.rollback()
raise
@@ -0,0 +1,257 @@
"""
services/admin/shipping_customer_merge_service.py
用途:执行货代标准客户的受控身份归并。
依赖:客户、识别证据、外部来源键、生命周期审计与统一业务异常。
逻辑:历史业务、编号、导入和影子审计保持指向源客户;仅将未来识别配置归并至目标客户。
"""
from __future__ import annotations
from typing import Any
from sqlalchemy import select
from app import db
from app.core.errors import ConflictError, NotFoundError, ValidationError
from app.models import (
ShippingCustomer,
ShippingCustomerExternalRef,
ShippingCustomerIdentifier,
ShippingIdentityEvidence,
ShippingCustomerLifecycleEvent,
ShippingCustomerMerge,
ShippingCustomerSite,
)
from app.services.admin.shipping_customer_lifecycle_service import get_customer_lifecycle_impact
def _load_customers_for_merge(source_customer_id: int, target_customer_id: int) -> tuple[ShippingCustomer, ShippingCustomer]:
"""按主键固定顺序锁住源和目标客户,避免两个反向合并请求产生死锁。"""
if source_customer_id == target_customer_id:
raise ValidationError('Source and target customer must differ', code='SHIPPING.CUSTOMER_MERGE_SAME_CUSTOMER')
ids = sorted({int(source_customer_id), int(target_customer_id)})
records = db.session.execute(
select(ShippingCustomer)
.where(ShippingCustomer.id.in_(ids))
.order_by(ShippingCustomer.id.asc())
.with_for_update()
).scalars().all()
by_id = {int(record.id): record for record in records}
source = by_id.get(int(source_customer_id))
target = by_id.get(int(target_customer_id))
if source is None or target is None:
raise NotFoundError('Customer not found', code='SHIPPING.CUSTOMER_NOT_FOUND')
return source, target
def _assert_merge_allowed(source: ShippingCustomer, target: ShippingCustomer) -> None:
"""校验合并两端均处于可操作状态,禁止链式或循环归并。"""
if source.status == 'merged' or source.merged_into_customer_id is not None:
raise ConflictError('Source customer has already been merged', code='SHIPPING.CUSTOMER_MERGE_SOURCE_ALREADY_MERGED')
if target.status != 'active' or target.merged_into_customer_id is not None:
raise ValidationError('Target customer must be active', code='SHIPPING.CUSTOMER_MERGE_TARGET_INVALID')
def get_customer_merge_impact(source_customer_id: int, target_customer_id: int) -> dict[str, Any]:
"""预览归并的历史保留引用与可迁移配置,不执行任何数据修改。"""
if source_customer_id == target_customer_id:
raise ValidationError('Source and target customer must differ', code='SHIPPING.CUSTOMER_MERGE_SAME_CUSTOMER')
source = db.session.get(ShippingCustomer, source_customer_id)
target = db.session.get(ShippingCustomer, target_customer_id)
if source is None or target is None:
raise NotFoundError('Customer not found', code='SHIPPING.CUSTOMER_NOT_FOUND')
_assert_merge_allowed(source, target)
target_identifiers = {
(item.identifier_type, item.normalized_value)
for item in db.session.query(ShippingCustomerIdentifier)
.filter_by(customer_id=target.id)
.all()
}
source_identifiers = db.session.query(ShippingCustomerIdentifier).filter_by(customer_id=source.id).all()
duplicate_identifiers = sum(
(item.identifier_type, item.normalized_value) in target_identifiers
for item in source_identifiers
)
target_evidence_keys = {
(item.definition_id, item.normalized_value)
for item in db.session.query(ShippingIdentityEvidence).filter_by(customer_id=target.id).all()
}
source_evidence = db.session.query(ShippingIdentityEvidence).filter_by(customer_id=source.id).all()
duplicate_evidence = sum((item.definition_id, item.normalized_value) in target_evidence_keys for item in source_evidence)
return {
'source': {
'id': source.id,
'standard_name': source.standard_name,
'short_code': source.short_code,
'status': source.status,
},
'target': {
'id': target.id,
'standard_name': target.standard_name,
'short_code': target.short_code,
'status': target.status,
},
'historical_references': get_customer_lifecycle_impact(source.id)['blockers'],
'migrate': {
'identifiers': len(source_identifiers) - duplicate_identifiers,
'duplicate_identifiers': duplicate_identifiers,
'external_references': db.session.query(ShippingCustomerExternalRef.id).filter_by(customer_id=source.id).count(),
'sites': db.session.query(ShippingCustomerSite.id).filter_by(customer_id=source.id).count(),
'identity_evidences': len(source_evidence) - duplicate_evidence,
'duplicate_identity_evidences': duplicate_evidence,
},
}
def merge_customer(
source_customer_id: int,
*,
target_customer_id: int,
confirmation_short_code: object,
reason: object,
actor_id: int | None,
) -> dict[str, Any]:
"""
原子归并重复客户,不改写历史业务号及其引用。
Args:
source_customer_id: 待归并的源客户。
target_customer_id: 承接未来识别配置的启用目标客户。
confirmation_short_code: 必须匹配源客户当前简码。
reason: 必填合并原因。
actor_id: 当前管理员主键。
Returns:
源/目标快照、迁移统计与合并审计主键。
"""
merge_reason = str(reason or '').strip()
confirmation = str(confirmation_short_code or '').strip().upper()
if not merge_reason:
raise ValidationError('Customer merge reason is required', code='SHIPPING.CUSTOMER_MERGE_REASON_REQUIRED')
try:
source, target = _load_customers_for_merge(source_customer_id, target_customer_id)
_assert_merge_allowed(source, target)
if confirmation != source.short_code:
raise ValidationError(
'Customer merge confirmation short code is invalid',
code='SHIPPING.CUSTOMER_MERGE_CONFIRMATION_INVALID',
details={'field': 'confirmation_short_code'},
)
impact = get_customer_merge_impact(source.id, target.id)
target_identifier_keys = {
(item.identifier_type, item.normalized_value)
for item in db.session.query(ShippingCustomerIdentifier)
.filter_by(customer_id=target.id)
.all()
}
moved_identifiers = 0
duplicates: list[ShippingCustomerIdentifier] = []
identifiers_to_move: list[ShippingCustomerIdentifier] = []
for identifier in db.session.query(ShippingCustomerIdentifier).filter_by(customer_id=source.id).all():
key = (identifier.identifier_type, identifier.normalized_value)
if key in target_identifier_keys:
duplicates.append(identifier)
else:
identifiers_to_move.append(identifier)
target_identifier_keys.add(key)
# 先实际删除与目标重复的证据,再更新其余证据的外键,避免唯一约束瞬时冲突。
for identifier in duplicates:
db.session.delete(identifier)
db.session.flush()
for identifier in identifiers_to_move:
identifier.customer_id = target.id
moved_identifiers += 1
removed_duplicate_identifiers = len(duplicates)
target_evidence_keys = {
(item.definition_id, item.normalized_value)
for item in db.session.query(ShippingIdentityEvidence).filter_by(customer_id=target.id).all()
}
duplicate_evidences = []
evidences_to_move = []
for evidence in db.session.query(ShippingIdentityEvidence).filter_by(customer_id=source.id).all():
key = (evidence.definition_id, evidence.normalized_value)
if key in target_evidence_keys:
duplicate_evidences.append(evidence)
else:
evidences_to_move.append(evidence)
target_evidence_keys.add(key)
for evidence in duplicate_evidences:
db.session.delete(evidence)
db.session.flush()
for evidence in evidences_to_move:
evidence.customer_id = target.id
external_refs = db.session.query(ShippingCustomerExternalRef).filter_by(customer_id=source.id).all()
for external_ref in external_refs:
external_ref.customer_id = target.id
target_site_codes = {
item.site_code for item in db.session.query(ShippingCustomerSite).filter_by(customer_id=target.id).all()
}
source_sites = db.session.query(ShippingCustomerSite).filter_by(customer_id=source.id).all()
duplicate_site_codes = sorted({item.site_code for item in source_sites if item.site_code in target_site_codes})
if duplicate_site_codes:
raise ConflictError(
'Customer sites conflict during merge',
code='SHIPPING.CUSTOMER_MERGE_SITE_CONFLICT',
details={'site_codes': duplicate_site_codes},
)
for site in source_sites:
site.customer_id = target.id
source_snapshot = impact['source']
target_snapshot = impact['target']
merge = ShippingCustomerMerge(
source_customer_id_snapshot=source.id,
source_name_snapshot=source.standard_name,
source_short_code_snapshot=source.short_code,
target_customer_id_snapshot=target.id,
target_name_snapshot=target.standard_name,
target_short_code_snapshot=target.short_code,
actor_id=actor_id,
reason=merge_reason,
detail_json={
'historical_references': impact['historical_references'],
'migrate': {
'identifiers': moved_identifiers,
'duplicate_identifiers': removed_duplicate_identifiers,
'external_references': len(external_refs),
'sites': len(source_sites),
'identity_evidences': len(evidences_to_move),
'duplicate_identity_evidences': len(duplicate_evidences),
},
},
)
source.status = 'merged'
source.merged_into_customer_id = target.id
source.updated_by_id = actor_id
db.session.add_all([
merge,
ShippingCustomerLifecycleEvent(
event_type='merged_source', customer_id_snapshot=source.id,
customer_name_snapshot=source.standard_name, customer_short_code_snapshot=source.short_code,
actor_id=actor_id, reason=merge_reason,
detail_json={'target': target_snapshot},
),
ShippingCustomerLifecycleEvent(
event_type='merged_target', customer_id_snapshot=target.id,
customer_name_snapshot=target.standard_name, customer_short_code_snapshot=target.short_code,
actor_id=actor_id, reason=merge_reason,
detail_json={'source': source_snapshot},
),
])
db.session.commit()
return {
'source': source_snapshot,
'target': target_snapshot,
'migrate': merge.detail_json['migrate'],
'merge_id': merge.id,
}
except (ConflictError, NotFoundError, ValidationError):
db.session.rollback()
raise
except Exception:
db.session.rollback()
raise
@@ -0,0 +1,625 @@
"""
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 (
ShippingCustomer,
ShippingCustomerExternalRef,
ShippingCustomerIdentifier,
ShippingCustomerLifecycleEvent,
ShippingCustomerSite,
ShippingCustomerSiteIdentifier,
ShippingIdentityEvidence,
ShippingNotice,
ShippingOrderTask,
ShippingCustomerShadowResolution,
)
from app.services.shipping_notice.customer_normalization import (
clean_text,
is_public_email_domain,
normalize_identifier,
normalize_short_code,
)
CUSTOMER_STATUSES = frozenset({'active', 'inactive', 'merged'})
IDENTIFIER_STATUSES = frozenset({'pending', 'approved', 'disabled'})
def _record_lifecycle_event(
customer: ShippingCustomer,
*,
event_type: str,
actor_id: int | None,
reason: str | None = None,
detail: dict[str, Any] | None = None,
) -> None:
"""写入仅含客户快照的治理审计,避免生命周期日志反向阻断受控删除。"""
db.session.add(ShippingCustomerLifecycleEvent(
event_type=event_type,
customer_id_snapshot=customer.id,
customer_name_snapshot=customer.standard_name,
customer_short_code_snapshot=customer.short_code,
actor_id=actor_id,
reason=reason,
detail_json=detail or {},
))
def _required_change_reason(data: dict[str, Any]) -> str:
"""返回高风险客户变更的必填审计原因,缺失时拒绝提交。"""
reason = clean_text(data.get('reason'))
if not reason:
raise ValidationError(
'Customer change reason is required',
code='SHIPPING.CUSTOMER_CHANGE_REASON_REQUIRED',
details={'field': 'reason'},
)
return reason
def _identifier_snapshot(record: ShippingCustomerIdentifier) -> dict[str, Any]:
"""生成识别证据变更前后对比所需的最小审计快照。"""
return {
'identifier_id': record.id,
'identifier_type': record.identifier_type,
'normalized_value': record.normalized_value,
'status': record.status,
'auto_match_allowed': bool(record.auto_match_allowed),
'remark': record.remark,
}
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,
notice_count: int | None = None,
identifier_count: int | None = None,
identity_evidence_count: int | None = None,
) -> dict[str, Any]:
"""
序列化标准客户,并可选附带识别证据和业务引用数量。
Args:
record: 标准客户 ORM 记录。
include_identifiers: 是否附带识别证据明细。
notice_count: 列表查询预聚合的发货通知数量;为空时现场查询。
identifier_count: 历史固定类型证据数量,仅供存量审计显示。
identity_evidence_count: 配置化客户主体证据数量;为空时现场查询。
Returns:
管理端客户 JSON 字典。
"""
payload: dict[str, Any] = {
'id': record.id,
'standard_name': record.standard_name,
'short_code': record.short_code,
'status': record.status,
'merged_into_customer_id': record.merged_into_customer_id,
'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,
'notice_count': notice_count if notice_count is not None else (
db.session.query(ShippingNotice.id)
.join(ShippingOrderTask, ShippingOrderTask.id == ShippingNotice.order_task_id)
.join(ShippingCustomerShadowResolution, ShippingCustomerShadowResolution.candidate_id == ShippingOrderTask.candidate_id)
.filter(
ShippingCustomerShadowResolution.confirmed_customer_id == record.id,
)
.distinct()
.count()
),
'identifier_count': identifier_count if identifier_count is not None else db.session.query(ShippingCustomerIdentifier.id).filter_by(customer_id=record.id).count(),
'identity_evidence_count': identity_evidence_count if identity_evidence_count is not None else db.session.query(
ShippingIdentityEvidence.id,
).filter_by(customer_id=record.id).count(),
}
if include_identifiers:
payload['identifiers'] = [serialize_identifier(item) for item in record.identifiers]
payload['identity_evidences'] = [
_serialize_identity_evidence(item)
for item in db.session.query(ShippingIdentityEvidence)
.filter_by(customer_id=record.id)
.order_by(ShippingIdentityEvidence.id.desc())
.all()
]
payload['external_refs'] = [serialize_external_ref(item) for item in record.external_refs]
payload['sites'] = [serialize_site(item) for item in record.sites]
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。
"""
notice_counts = (
db.session.query(ShippingCustomerShadowResolution.confirmed_customer_id.label('customer_id'), func.count(ShippingNotice.id).label('notice_count'))
.join(ShippingOrderTask, ShippingOrderTask.candidate_id == ShippingCustomerShadowResolution.candidate_id)
.join(ShippingNotice, ShippingNotice.order_task_id == ShippingOrderTask.id)
.filter(ShippingCustomerShadowResolution.confirmed_customer_id.isnot(None))
.group_by(ShippingCustomerShadowResolution.confirmed_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()
)
identity_evidence_counts = (
db.session.query(
ShippingIdentityEvidence.customer_id.label('customer_id'),
func.count(ShippingIdentityEvidence.id).label('identity_evidence_count'),
)
.filter(ShippingIdentityEvidence.customer_id.isnot(None))
.group_by(ShippingIdentityEvidence.customer_id)
.subquery()
)
site_identity_evidence_counts = (
db.session.query(
ShippingCustomerSite.customer_id.label('customer_id'),
func.count(ShippingIdentityEvidence.id).label('identity_evidence_count'),
)
.join(ShippingIdentityEvidence, ShippingIdentityEvidence.site_id == ShippingCustomerSite.id)
.group_by(ShippingCustomerSite.customer_id)
.subquery()
)
query = (
db.session.query(
ShippingCustomer,
func.coalesce(notice_counts.c.notice_count, 0),
func.coalesce(identifier_counts.c.identifier_count, 0),
func.coalesce(identity_evidence_counts.c.identity_evidence_count, 0)
+ func.coalesce(site_identity_evidence_counts.c.identity_evidence_count, 0),
)
.outerjoin(notice_counts, notice_counts.c.customer_id == ShippingCustomer.id)
.outerjoin(identifier_counts, identifier_counts.c.customer_id == ShippingCustomer.id)
.outerjoin(identity_evidence_counts, identity_evidence_counts.c.customer_id == ShippingCustomer.id)
.outerjoin(site_identity_evidence_counts, site_identity_evidence_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, notice_count=int(notice_count), identifier_count=int(identifier_count),
identity_evidence_count=int(identity_evidence_count),
)
for customer, notice_count, identifier_count, identity_evidence_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 - {'merged'}:
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)
db.session.flush()
_record_lifecycle_event(
record,
event_type='created',
actor_id=actor_id,
detail={'after': {'standard_name': standard_name, 'short_code': short_code, 'status': status}},
)
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 serialize_external_ref(record: ShippingCustomerExternalRef) -> dict[str, Any]:
"""序列化客户在外部系统中的稳定客户编码。"""
return {
'id': record.id, 'customer_id': record.customer_id,
'source_system': record.source_system, 'customer_code': record.legacy_customer_key,
}
def _serialize_identity_evidence(record: ShippingIdentityEvidence) -> dict[str, Any]:
"""序列化配置化身份识别证据及定义快照,供客户主数据页直接渲染。"""
from app.services.shipping_notice.identity_rules.service import serialize_evidence
return serialize_evidence(record)
def serialize_site(record: ShippingCustomerSite) -> dict[str, Any]:
"""序列化送货站点及其名称/外部编码标识。"""
return {
'id': record.id, 'customer_id': record.customer_id, 'site_name': record.site_name,
'site_code': record.site_code, 'address': record.address, 'city': record.city,
'country': record.country, 'status': record.status, 'remark': record.remark,
'identifiers': [{
'id': item.id, 'identifier_type': item.identifier_type,
'source_system': item.source_system, 'raw_value': item.raw_value,
'normalized_value': item.normalized_value, 'status': item.status,
} for item in record.identifiers],
'identity_evidences': [
_serialize_identity_evidence(item)
for item in db.session.query(ShippingIdentityEvidence)
.filter_by(site_id=record.id)
.order_by(ShippingIdentityEvidence.id.desc())
.all()
],
}
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 record.status == 'merged':
raise ConflictError('Merged customer cannot be edited', code='SHIPPING.CUSTOMER_MERGED_LOCKED')
before = {
'standard_name': record.standard_name,
'short_code': record.short_code,
'status': record.status,
'remark': record.remark,
}
next_name = before['standard_name']
next_short_code = before['short_code']
next_status = before['status']
next_remark = before['remark']
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')
next_name = name
if 'short_code' in data:
next_short_code = normalize_short_code(data.get('short_code'))
_assert_short_code_available(next_short_code, exclude_customer_id=customer_id)
if 'status' in data:
next_status = clean_text(data.get('status')).lower()
if next_status not in CUSTOMER_STATUSES - {'merged'}:
raise ValidationError('Invalid customer status', code='SHIPPING.CUSTOMER_STATUS_INVALID')
if 'remark' in data:
next_remark = clean_text(data.get('remark')) or None
after = {
'standard_name': next_name,
'short_code': next_short_code,
'status': next_status,
'remark': next_remark,
}
changes = {key: {'before': before[key], 'after': after[key]} for key in before if before[key] != after[key]}
if changes:
high_risk_change = 'short_code' in changes or 'status' in changes
change_reason = _required_change_reason(data) if high_risk_change else clean_text(data.get('reason')) or None
record.standard_name = next_name
record.short_code = next_short_code
record.status = next_status
record.remark = next_remark
record.updated_by_id = actor_id
_record_lifecycle_event(
record,
event_type='updated',
actor_id=actor_id,
reason=change_reason,
detail={'changes': changes},
)
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, *, reason: object = None, actor_id: int | None) -> dict[str, Any]:
"""停用客户;不物理删除,以保留业务单和识别审计。"""
return update_customer(customer_id, {'status': 'inactive', 'reason': reason}, 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')
if customer.status == 'merged':
raise ConflictError('Merged customer cannot receive identifiers', code='SHIPPING.CUSTOMER_MERGED_LOCKED')
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)
db.session.flush()
_record_lifecycle_event(
customer,
event_type='identifier_created',
actor_id=actor_id,
detail={'identifier': _identifier_snapshot(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')
customer = db.session.get(ShippingCustomer, record.customer_id)
if customer is None or customer.status == 'merged':
raise ConflictError('Merged customer identifier cannot be edited', code='SHIPPING.CUSTOMER_MERGED_LOCKED')
before = _identifier_snapshot(record)
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',
)
next_remark = clean_text(data.get('remark')) or None if 'remark' in data else record.remark
after = {
**before,
'status': next_status,
'auto_match_allowed': bool(next_allowed),
'remark': next_remark,
}
changes = {key: {'before': before[key], 'after': after[key]} for key in before if before[key] != after[key]}
if changes:
requires_reason = 'status' in changes or 'auto_match_allowed' in changes
change_reason = _required_change_reason(data) if requires_reason else clean_text(data.get('reason')) or None
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()
record.remark = next_remark
_record_lifecycle_event(
customer,
event_type='identifier_updated',
actor_id=actor_id,
reason=change_reason,
detail={'identifier_id': record.id, 'changes': changes},
)
db.session.commit()
return serialize_identifier(record)
def create_external_ref(customer_id: int, data: dict[str, Any]) -> dict[str, Any]:
"""新增来源系统客户编码;同一来源和编码只能绑定一个标准客户。"""
customer = db.session.get(ShippingCustomer, customer_id)
if customer is None:
raise NotFoundError('Customer not found', code='SHIPPING.CUSTOMER_NOT_FOUND')
source_system = clean_text(data.get('source_system')).upper()
customer_code = clean_text(data.get('customer_code')).upper()
if not source_system or not customer_code:
raise ValidationError('Source system and customer code are required', code='SHIPPING.CUSTOMER_EXTERNAL_REF_INVALID')
record = ShippingCustomerExternalRef(
customer_id=customer.id, source_system=source_system, legacy_customer_key=customer_code,
)
db.session.add(record)
try:
db.session.commit()
except IntegrityError as exc:
db.session.rollback()
raise ConflictError('Customer external reference already exists', code='SHIPPING.CUSTOMER_EXTERNAL_REF_CONFLICT') from exc
return serialize_external_ref(record)
def create_site(customer_id: int, data: dict[str, Any], *, actor_id: int | None) -> dict[str, Any]:
"""新增客户送货站点,站点编码在同一标准客户内唯一。"""
customer = db.session.get(ShippingCustomer, customer_id)
if customer is None:
raise NotFoundError('Customer not found', code='SHIPPING.CUSTOMER_NOT_FOUND')
site_name = clean_text(data.get('site_name'))
site_code = clean_text(data.get('site_code')).upper()
if not site_name or not site_code:
raise ValidationError('Site name and code are required', code='SHIPPING.CUSTOMER_SITE_INVALID')
record = ShippingCustomerSite(
customer_id=customer.id, site_name=site_name, site_code=site_code,
address=clean_text(data.get('address')) or None, city=clean_text(data.get('city')) or None,
country=clean_text(data.get('country')) or None, status='active',
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 site already exists', code='SHIPPING.CUSTOMER_SITE_CONFLICT') from exc
return serialize_site(record)
def create_site_identifier(site_id: int, data: dict[str, Any]) -> dict[str, Any]:
"""为送货站点新增名称别名、地址或带来源系统的外部站点编码。"""
site = db.session.get(ShippingCustomerSite, site_id)
if site is None:
raise NotFoundError('Customer site not found', code='SHIPPING.CUSTOMER_SITE_NOT_FOUND')
identifier_type = clean_text(data.get('identifier_type')).lower()
if identifier_type not in {'name_alias', 'external_code', 'address'}:
raise ValidationError('Site identifier type is invalid', code='SHIPPING.CUSTOMER_SITE_IDENTIFIER_INVALID')
raw_value = clean_text(data.get('identifier_value'))
source_system = clean_text(data.get('source_system')).upper() if identifier_type == 'external_code' else ''
if not raw_value or (identifier_type == 'external_code' and not source_system):
raise ValidationError('Site identifier is incomplete', code='SHIPPING.CUSTOMER_SITE_IDENTIFIER_INVALID')
normalized = normalize_identifier('name_alias', raw_value) if identifier_type == 'name_alias' else raw_value.upper()
record = ShippingCustomerSiteIdentifier(
site_id=site.id, identifier_type=identifier_type, source_system=source_system,
raw_value=raw_value, normalized_value=normalized, status='approved',
remark=clean_text(data.get('remark')) or None,
)
db.session.add(record)
try:
db.session.commit()
except IntegrityError as exc:
db.session.rollback()
raise ConflictError('Site identifier already exists', code='SHIPPING.CUSTOMER_SITE_IDENTIFIER_CONFLICT') from exc
return serialize_site(site)
File diff suppressed because it is too large. Load diff
@@ -17,8 +17,9 @@ from pypdf import PdfReader
from app import db
from app.core.errors import NotFoundError, ValidationError
from app.models import AgentGuide
from app.models import AgentGuide, KbDocumentVersion
from app.services.admin.guide_service import GUIDE_USAGE_TRAINING_EXAM_PDF
from app.services.kb.storage import resolve_storage_path
from app.services.minio_service import minio_service
from edkb_system.contracts import Block, Context
from edkb_system.skills import loader_pdf, ocr
@@ -26,11 +27,16 @@ from edkb_system.skills import loader_pdf, ocr
_QUESTION_START_PATTERN = re.compile(r'^\s*(\d{1,3})\s*[\.\、\.\)]\s*(.+?)\s*$')
_OPTION_PATTERN = re.compile(r'([A-D])\s*[\.\、\.\)\::]\s*')
_INLINE_ANSWER_PATTERN = re.compile(r'答案\s*[::]?\s*(A|B|C|D|正确|错误|对|错|T|F|√|×)', re.IGNORECASE)
_PARENTHESIZED_ANSWER_PATTERN = re.compile(r'[\((]\s*(A|B|C|D|正确|错误|对|错|T|F|√|×)\s*[\))]', re.IGNORECASE)
_INLINE_EXPLANATION_PATTERN = re.compile(r'解析\s*[::]?\s*(.+)$', re.IGNORECASE)
_ANSWER_PAIR_PATTERN = re.compile(r'(?:^|(?<=[\s,,;;]))(\d{1,3})\s*[\.\、\.\)]?\s*[::]?\s*(A|B|C|D|正确|错误|对|错|T|F|√|×)', re.IGNORECASE)
_SECTION_HEADING_PATTERN = re.compile(r'^[一二三四五六七八九十]+[\.\、\.\)]\s*[^\n]*题')
_FILL_SECTION_PATTERN = re.compile(r'填空(?:题)?|填\s*空')
_ESSAY_SECTION_PATTERN = re.compile(r'问答题|简答题')
_BOOLEAN_SECTION_PATTERN = re.compile(r'判\s*断\s*题?')
_BOOLEAN_SECTION_ANSWER_PATTERN = re.compile(r'判\s*断\s*题\s*[::]?\s*(.*)$')
_BOOLEAN_PROMPT_HINT_PATTERN = re.compile(r'正确还是错误|对还是错|判断题|[\((]\s*[\))]|是否')
_ANSWER_RANGE_PATTERN = re.compile(r'^(\d{1,3})\s*[-~-—至到]\s*(\d{1,3})\s+(.+)$')
_ANSWER_RANGE_PATTERN = re.compile(r'^(\d{1,3})\s*[-~-—至到]\s*(\d{1,3})\s*[、,,.::]?\s*(.+)$')
_BOOLEAN_TOKEN_PATTERN = re.compile(r'正确|错误|对|错|T|F|V|X|√|×', re.IGNORECASE)
@@ -144,7 +150,7 @@ def _is_answer_sheet_line(line: str) -> bool:
if range_match:
token_matches = _BOOLEAN_TOKEN_PATTERN.findall(range_match.group(3))
expected_count = int(range_match.group(2)) - int(range_match.group(1)) + 1
if len(token_matches) >= max(expected_count - 1, 2):
if token_matches:
return True
matches = list(_ANSWER_PAIR_PATTERN.finditer(normalized_line))
return len(matches) >= 2
@@ -175,6 +181,20 @@ def _extract_answer_sequence(lines: list[str]) -> list[str]:
return answers
def _extract_section_answer_sequence(lines: list[str], section_pattern: re.Pattern[str]) -> list[str]:
"""提取带题型标题的答案行,支持“判断题:1-10、√ ×”这类分节答案表。"""
answers: list[str] = []
for line in lines:
if not section_pattern.search(line) or not _is_answer_sheet_line(line):
continue
range_match = re.search(r'\d{1,3}\s*[-~-—至到]\s*\d{1,3}\s*[、,,.::]?\s*(.*)$', line)
token_text = range_match.group(1) if range_match else line
for raw_token in _BOOLEAN_TOKEN_PATTERN.findall(token_text):
answer = _normalize_answer_token(raw_token)
if answer:
answers.append(answer)
return answers
def _extract_answer_map(lines: list[str]) -> dict[int, str]:
"""
从“参考答案”区域提取题号与答案映射。
@@ -195,24 +215,119 @@ def _extract_answer_map(lines: list[str]) -> dict[int, str]:
return answer_map
def _split_question_blocks(lines: list[str]) -> list[tuple[int, str]]:
blocks: list[tuple[int, str]] = []
def _section_type_for_line(line: str) -> str | None:
if _FILL_SECTION_PATTERN.search(line):
return 'fill'
if _ESSAY_SECTION_PATTERN.search(line):
return 'essay'
if _BOOLEAN_SECTION_PATTERN.search(line):
return 'boolean'
if re.search(r'选择题|单选题', line):
return 'single'
return None
def _extract_repeated_section_answers(lines: list[str]) -> dict[str, list[str]]:
"""提取 PDF 后半段按小节重复出现的填空标准答案,避免把答案行当作新题目。"""
occurrences: dict[str, int] = {}
active_type: str | None = None
answers: dict[str, list[str]] = {'fill': []}
in_answer_sheet = False
for line in lines:
if _is_answer_section_heading(line):
in_answer_sheet = True
active_type = None
continue
section_type = _section_type_for_line(line)
if section_type:
occurrences[section_type] = occurrences.get(section_type, 0) + 1
if occurrences[section_type] > 1:
in_answer_sheet = True
active_type = section_type if occurrences[section_type] > 1 or in_answer_sheet else None
continue
if not in_answer_sheet or active_type != 'fill':
continue
match = _QUESTION_START_PATTERN.match(line)
if match:
value = _normalize_spaces(match.group(2))
if value:
answers['fill'].append(value)
return answers
def _format_fill_prompt(prompt: str, standard_answer: str) -> str:
"""把 PDF 中表示填空位置的空白转换为稳定可见的下划线。"""
text = _normalize_spaces(prompt)
if not standard_answer:
return text
answer_parts = [part for part in re.split(r'[、,,;;]+', standard_answer) if part.strip()]
expected = max(1, len(answer_parts))
candidates = list(re.finditer(r'(?<=[\u4e00-\u9fff])\s+(?=[\u4e00-\u9fff、,,;;。])', text))
if not candidates:
return f"{text} {' '.join('______' for _ in range(expected))}"
positions = {match.start() for match in candidates[:expected]}
result: list[str] = []
last = 0
for match in candidates:
result.append(text[last:match.start()])
result.append(' ______ ' if match.start() in positions else ' ')
last = match.end()
result.append(text[last:])
formatted = _normalize_spaces(''.join(result))
missing_count = expected - formatted.count('______')
if missing_count > 0:
# PDF 文本抽取会丢失部分空白字符;补足占位符,确保学员能看到与标准答案数量一致的填空位置。
formatted = f"{formatted} {' '.join('______' for _ in range(missing_count))}"
return formatted
def _split_question_blocks(lines: list[str]) -> list[tuple[int, str, str | None]]:
"""
按题号及所属小节切分题目块。
用途:保留“填空题”“判断题”“问答题”小节语义,避免无选项题被当作解析失败而丢弃。
参数约束:仅识别明确的题目小节;未命中时返回 None,后续继续按单选/判断规则判别。
"""
blocks: list[tuple[int, str, str | None]] = []
current_no: int | None = None
current_lines: list[str] = []
current_section_type: str | None = None
section_occurrences: dict[str, int] = {}
for line in lines:
if _SECTION_HEADING_PATTERN.match(line):
if _is_answer_section_heading(line):
if current_no is not None and current_lines:
blocks.append((current_no, ' '.join(current_lines).strip()))
blocks.append((current_no, ' '.join(current_lines).strip(), current_section_type))
current_no = None
current_lines = []
current_section_type = 'answer_sheet'
continue
section_type = _section_type_for_line(line)
if section_type:
if current_no is not None and current_lines:
blocks.append((current_no, ' '.join(current_lines).strip(), current_section_type))
current_no = None
current_lines = []
section_occurrences[section_type] = section_occurrences.get(section_type, 0) + 1
current_section_type = section_type if section_occurrences[section_type] == 1 else f'answer_{section_type}'
continue
if _is_answer_section_heading(line):
if current_no is not None and current_lines:
blocks.append((current_no, ' '.join(current_lines).strip(), current_section_type))
current_no = None
current_lines = []
current_section_type = 'answer_sheet'
continue
if current_section_type == 'answer_sheet' or (current_section_type and current_section_type.startswith('answer_')):
continue
if _is_answer_sheet_line(line):
continue
question_match = _QUESTION_START_PATTERN.match(line)
if question_match:
if _is_answer_sheet_line(line) and '答案' not in line:
continue
if current_no is not None and current_lines:
blocks.append((current_no, ' '.join(current_lines).strip()))
blocks.append((current_no, ' '.join(current_lines).strip(), current_section_type))
current_no = int(question_match.group(1))
current_lines = [question_match.group(2)]
continue
@@ -222,12 +337,22 @@ def _split_question_blocks(lines: list[str]) -> list[tuple[int, str]]:
current_lines.append(line)
if current_no is not None and current_lines:
blocks.append((current_no, ' '.join(current_lines).strip()))
blocks.append((current_no, ' '.join(current_lines).strip(), current_section_type))
return blocks
def _is_answer_section_heading(line: str) -> bool:
return bool(re.match(r'^(?:参考)?答案(?:解析|及解析)?\s*[::]?$', line))
def _extract_inline_answer(block_text: str) -> str:
match = _INLINE_ANSWER_PATTERN.search(block_text)
"""
从单题文本中提取内联标准答案。
用途:兼容“答案:B”与“(B)”两种常见试卷标注;后者需排除空括号,避免把答题留白误判为答案。
参数约束:仅返回可标准化为单选或判断值的答案,否则返回空字符串。
"""
match = _INLINE_ANSWER_PATTERN.search(block_text) or _PARENTHESIZED_ANSWER_PATTERN.search(block_text)
if not match:
return ''
return _normalize_answer_token(match.group(1))
@@ -256,6 +381,25 @@ def _build_boolean_question(question_no: int, prompt: str, answer: str, explanat
}
def _build_text_question(question_no: int, prompt: str, question_type: str, explanation: str, answer: str = '') -> dict[str, Any] | None:
"""
构造无选项的填空或问答题。
用途:填空题会携带 PDF 答案区提取到的标准答案用于自动判分;问答题没有固定答案时仍按文本长度规则评分。
参数约束:question_type 只能为 fill 或 essay;answer 仅允许来自同一 PDF 的对应填空答案。
"""
prompt_text = _normalize_spaces(prompt)
if not prompt_text or question_type not in {'fill', 'essay'}:
return None
return {
'id': f'q{question_no}',
'type': question_type,
'prompt': prompt_text,
'answer': _normalize_spaces(answer) if question_type == 'fill' else '',
'explanation': explanation,
}
def _build_answer_candidates(
*,
inline_answer: str,
@@ -331,21 +475,59 @@ def parse_training_question_bank_text(text: str) -> dict[str, Any]:
lines = _collect_candidate_lines(text)
answer_map = _extract_answer_map(lines)
answer_sequence = _extract_answer_sequence(lines)
repeated_section_answers = _extract_repeated_section_answers(lines)
question_blocks = _split_question_blocks(lines)
question_bank: list[dict[str, Any]] = []
skipped_questions: list[int] = []
fill_answer_index = 0
# [STEP 1] 先按题号切块,再对每一块做题型、答案和解析判定,避免跨题串行污染。
for index, (question_no, raw_block) in enumerate(question_blocks):
answer_sequence_index = 0
for question_no, raw_block, section_type in question_blocks:
inline_answer = _extract_inline_answer(raw_block)
explanation = _extract_inline_explanation(raw_block)
block_text = _strip_inline_meta(raw_block)
option_matches = list(_OPTION_PATTERN.finditer(block_text))
consumes_answer = section_type not in {'fill', 'essay'}
ordered_answer = answer_sequence[answer_sequence_index] if answer_sequence_index < len(answer_sequence) else ''
if consumes_answer:
answer_sequence_index += 1
answer_candidates = _build_answer_candidates(
inline_answer=inline_answer,
mapped_answer=answer_map.get(question_no, ''),
ordered_answer=answer_sequence[index] if index < len(answer_sequence) else '',
ordered_answer=ordered_answer,
)
if section_type == 'boolean':
for answer in answer_candidates:
question_payload = _build_boolean_question(
question_no=question_no,
prompt=block_text,
answer=answer,
explanation=explanation,
)
if question_payload:
question_payload['id'] = f'q{len(question_bank) + 1}'
question_bank.append(question_payload)
break
else:
question_payload = None
if question_payload:
continue
if section_type in {'fill', 'essay'}:
fill_answer = (
repeated_section_answers['fill'][fill_answer_index]
if section_type == 'fill' and fill_answer_index < len(repeated_section_answers['fill'])
else ''
)
if section_type == 'fill':
fill_answer_index += 1
block_text = _format_fill_prompt(block_text, fill_answer)
question_payload = _build_text_question(question_no, block_text, section_type, explanation, fill_answer)
if question_payload:
question_payload['id'] = f'q{len(question_bank) + 1}'
question_bank.append(question_payload)
continue
if _looks_like_boolean_question(block_text, option_matches, answer_candidates):
for answer in answer_candidates:
@@ -443,3 +625,62 @@ def parse_training_question_bank_from_guide(agent_id: int, guide_id: int | None
parsed['extraction_mode'] = extraction_mode
parsed['extraction_warnings'] = ocr_warnings
return parsed
def parse_training_question_bank_from_kb_version(version_id: int) -> dict[str, Any]:
"""
从员工培训知识库当前 PDF 文档版本解析题库。
用途:培训配置页选择员工培训知识库试题 PDF 后,将原始文件交给现有 PDF/OCR 解析链路。
参数约束:版本必须为当前版本、属于启用的“员工培训”知识库、未删除且扩展名为 PDF。
Returns:
包含题目、解析数量、跳过题号、解析模式和源文件信息的字典。
Raises:
NotFoundError: 文档版本不存在或原始文件不可用。
ValidationError: 文档不符合培训试题 PDF 资源约束,或无法解析题目。
"""
version = db.session.get(KbDocumentVersion, version_id)
document = version.document if version else None
group = document.group if document else None
if not version or not document or document.is_deleted:
raise NotFoundError('Knowledge base document version not found')
if not version.is_current or not group or not group.is_active or group.name != '员工培训':
raise ValidationError('Selected document must be a current document in the employee training knowledge base')
if str(version.source_file_ext or '').lower().lstrip('.') != 'pdf' and not str(version.source_file_name or '').lower().endswith('.pdf'):
raise ValidationError('Selected training exam document must be a PDF')
source_path = resolve_storage_path(version.source_file_path)
if not source_path or not source_path.exists():
raise NotFoundError('Training exam PDF source file not found')
raw_bytes = source_path.read_bytes()
text = _extract_pdf_text(raw_bytes)
ocr_text = ''
ocr_warnings: list[str] = []
extraction_mode = 'pdf_text'
if text:
try:
parsed = parse_training_question_bank_text(text)
except ValidationError as primary_error:
ocr_text, ocr_warnings = _extract_pdf_text_via_ocr(raw_bytes)
if not ocr_text or ocr_text == text:
raise primary_error
parsed = parse_training_question_bank_text(ocr_text)
extraction_mode = 'ocr_fallback'
else:
ocr_text, ocr_warnings = _extract_pdf_text_via_ocr(raw_bytes)
if not ocr_text:
raise ValidationError(
'Training exam PDF has no readable text',
details={'ocr_warnings': ocr_warnings},
)
parsed = parse_training_question_bank_text(ocr_text)
extraction_mode = 'ocr'
parsed.update({
'kb_document_version_id': version.id,
'document_id': version.document_id,
'source_file_name': version.source_file_name,
'version_no': version.version_no,
'extraction_mode': extraction_mode,
'extraction_warnings': ocr_warnings,
})
return parsed
@@ -235,6 +235,22 @@ def create_user(data: dict[str, Any]) -> dict:
def update_user(user_id: int, data: dict[str, Any]) -> dict:
"""
更新管理端用户资料,可选同步 Casdoor 改密。
核心逻辑:先写入本地字段;新密码与当前哈希相同则直接拒绝,避免 Casdoor 返回含 old password 的文案被误判成 401。
Args:
user_id: 目标用户主键。
data: 管理端提交的字段,password 为空表示不改密。
Returns:
{'status': 'ok'}。
Raises:
NotFoundError: 用户不存在。
AppError: 邮箱非法、新密码未变化或 Casdoor 同步失败。
"""
user = db.session.get(User, user_id)
if not user:
raise NotFoundError('User not found')
@@ -259,6 +275,12 @@ def update_user(user_id: int, data: dict[str, Any]) -> dict:
if 'feature_permissions' in data or 'role' in data:
permissions_payload = data.get('feature_permissions', user.feature_permissions)
user.set_feature_permissions(permissions_payload)
if new_password and user.check_password(new_password):
raise AppError(
code='AUTH.PASSWORD_UNCHANGED',
message='New password must differ from the current password',
http_status=400,
)
if new_password:
user.set_password(new_password)
if 'agent_ids' in data:
@@ -12,4 +12,5 @@ from __future__ import annotations
RUNTIME_HANDLER_BINDINGS: dict[str, str] = {
'shipping_notice': 'shipping_notice',
'file_check': 'file_check',
'in_transit_transfer': 'in_transit_transfer',
}
@@ -32,7 +32,6 @@ platform:
dify_required_providers:
- dify
- hybrid
agent_types:
generic:
label: 通用问答 / 知识库
@@ -54,8 +53,8 @@ agent_types:
conversation_mode_default: task_chat
runtime_provider_default: hybrid
models:
- ShippingBatch
- ShippingTask
- ShippingNotice
- ShippingOrderTask
- ShippingTaskEvent
required_fields: []
default_capabilities:
@@ -130,3 +129,35 @@ agent_types:
file_upload: true
human_confirm: false
handler_config_schema: {}
in_transit_transfer:
label: 在途仓自动调拨
conversation_mode_default: task_chat
runtime_provider_default: hybrid
models:
- TransferRun
- TransferPrecheck
- TransferInvoiceItem
required_fields: []
default_capabilities:
task_progress: true
human_confirm: true
forced_capabilities:
human_confirm: true
progress_contract:
enabled: true
data_source:
type: domain_state
domain: in_transit_transfer
update:
transport: sse
event: transfer_ui_state
binding:
type: conversation_context
keys:
- run_no
- precheck_id
requires_schedule_task: false
presentation:
layout: card
visualization: stepper
handler_config_schema: {}
@@ -17,7 +17,7 @@ class ChatStreamContext:
"""
/api/chat/completions 单次流式请求上下文。
核心字段:用户/Agent/会话、Dify 入参、adapter_hints 与领域锚点(task_id/batch_no)。
核心字段:用户/Agent/会话、Dify 入参、adapter_hints 与领域锚点(task_id)。
"""
query: str
@@ -30,7 +30,6 @@ class ChatStreamContext:
normalized_files: list[dict] | None = None
adapter_hints: dict[str, Any] | None = None
shipping_task_id: str = ''
shipping_batch_no: str = ''
kb_type: str = '企业知识库'
hxops_turn_id: str | None = None
@@ -70,5 +69,9 @@ class AgentHandler:
ctx: ChatStreamContext,
event_data: dict[str, Any],
) -> Iterator[str]:
"""上游 message_end/workflow_finished 后追加的 SSE 行。"""
"""上游 error/message_end/workflow_finished 后执行领域收口并追加 SSE 行。"""
return iter(())
def should_recover_upstream_error(self, ctx: ChatStreamContext, event_data: dict[str, Any]) -> bool:
"""业务事实已持久化时,允许把上游 SSE error 收口为正常终态。"""
return False
@@ -30,10 +30,12 @@ def load_handlers() -> None:
import importlib
import app.services.agent_registry.handlers.file_check as file_check_mod
import app.services.agent_registry.handlers.in_transit_transfer as in_transit_transfer_mod
import app.services.agent_registry.handlers.shipping_notice as shipping_mod
importlib.reload(file_check_mod)
importlib.reload(shipping_mod)
importlib.reload(in_transit_transfer_mod)
logger.info('Agent handlers loaded: %s', sorted(HANDLER_REGISTRY.keys()))
_handlers_loaded = True
@@ -0,0 +1,34 @@
"""
用途:在途仓自动调拨 Hybrid Handler。
依赖:agent_registry.handlers.base/registry。
逻辑:在途调拨的进度与结果卡由 Chat Action(transfer.precheck / transfer.execute)
输出结构化 message.completed 卡片,并经 Run API 恢复;本 Handler 负责 hybrid
运行时的上下文钩子与领域 UI State 扩展位(transfer_ui_state),暂不注入
Dify Chatflow 生命周期。
"""
from __future__ import annotations
from typing import Any
from app.services.agent_registry.handlers.base import AgentHandler, ChatStreamContext
from app.services.agent_registry.handlers.registry import register_handler
@register_handler('in_transit_transfer')
class InTransitTransferHandler(AgentHandler):
"""
在途仓自动调拨业务 Handler。
核心逻辑:预检/执行/结果卡不进入普通 Dify 生命周期(后台 Run 持久化 + 卡片消息
+ Run API 恢复);prepare_stream / build_ui_state_event 预留领域扩展位。
"""
def prepare_stream(self, ctx: ChatStreamContext) -> ChatStreamContext:
"""Dify 流开始前:校验领域上下文(预留 run_no/precheck_id 锚点)。"""
return ctx
def build_ui_state_event(self, ctx: ChatStreamContext) -> dict[str, Any] | None:
"""构造 transfer_ui_state SSE 事件(预留;进度由卡片消息 + Run API 提供)。"""
return None
@@ -1,9 +1,7 @@
"""
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.query_service/ui_state、agent_registry.handlers.registry。
逻辑:根据显式 task/batch 上下文构造并推送 UI State;订单抽取由后台 Run/Worker 独立执行。
"""
from __future__ import annotations
@@ -38,86 +36,73 @@ class ShippingNoticeHandler(AgentHandler):
"""
货代发货通知业务 Handler。
核心逻辑:按 adapter_hints / 请求 task_id、batch_no 构造 shipping_ui_state 事件供前端渲染步骤与按钮。
核心逻辑:按 adapter_hints / task_id 构造 shipping_ui_state,供实时消息使用。
订单抽取状态卡由 Run API 和本地消息持久化恢复,不进入普通 Dify Chatflow 生命周期。
"""
@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 {}
def build_ui_state_event(self, ctx: ChatStreamContext) -> dict[str, Any] | None:
"""
构造 shipping_ui_state SSE 事件。
核心逻辑:优先显式 task_id,其次 batch 焦点任务;失败时记录日志并返回 None。
核心逻辑:只接受显式 task_id;失败时记录日志并返回 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()
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 {}
shipping_hints = self._shipping_hints(ctx)
if not task_id:
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:
if not task_id:
return None
try:
from app.services.shipping_notice.query_service import get_batch_by_no, get_task_by_ref
from app.services.shipping_notice.ui_state import build_batch_ui_state, build_task_ui_state
from app.services.shipping_notice.query_service import get_task_by_ref
from app.services.shipping_notice.ui_state import 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
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
task = get_task_by_ref(task_id)
session_id = str(getattr(ctx.session, 'session_id', '') or '')
if task is not None:
return {
'event': 'shipping_ui_state',
'conversation_id': session_id,
'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),
}
if batch is not None:
return {
'event': 'shipping_ui_state',
'conversation_id': session_id,
'batch_no': batch.batch_no,
'batch_ui_state': build_batch_ui_state(batch),
}
except Exception:
if current_app:
current_app.logger.exception(
'[shipping-handler] build_ui_state failed request_id=%s task_id=%s batch_no=%s',
'[shipping-handler] build_ui_state failed request_id=%s task_id=%s',
ctx.request_id,
task_id,
batch_no,
)
return None
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 = (
batch_ui_state.get('focus_task_ui_state')
if isinstance(batch_ui_state.get('focus_task_ui_state'), dict)
else {}
)
checkpoint = ui_state.get('checkpoint') or focus_state.get('checkpoint')
return json.dumps({
'task_no': event.get('task_no'),
'batch_no': event.get('batch_no'),
'checkpoint': checkpoint,
'updated_at': ui_state.get('updated_at') or batch_ui_state.get('updated_at'),
'position': ui_state.get('position'),
'user_mode': ui_state.get('user_mode'),
'updated_at': ui_state.get('updated_at'),
}, ensure_ascii=False, sort_keys=True)
def _format_sse(self, event: dict[str, Any]) -> str:
@staticmethod
def _format_sse(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。"""
event = self.build_ui_state_event(ctx)
if event:
yield self._format_sse(event)
@@ -127,8 +112,9 @@ 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)
if event:
@@ -28,15 +28,17 @@ ALLOWED_PARSE_PATHS: frozenset[str] = frozenset(
"platform.request_id",
"platform.locale",
"platform.trigger_source",
"refs.batch_no",
"refs.task_no",
"refs.run_purpose",
"refs.capability",
"refs.intake_nos",
"refs.file_name",
"refs.temporary_inventory_asset_no",
"refs.temporary_inventory_session_no",
"refs.schedule_task_id",
"refs.hxops_turn_id",
"domain.type",
"domain.summary",
"domain.state_hint.batch_no",
"domain.state_hint.focus_task_no",
"domain.state_hint.schedule_task_id",
"domain.state_hint.hxops_turn_id",
@@ -3,7 +3,7 @@ backend/app/services/auth/hxops/casdoor_user_sync.py
用途:集中实现 HXOPS 用户创建和改密到 Casdoor 的管理端同步。
依赖:Flask 配置、requests、HXOPS User 模型、公共 Casdoor 错误解析。
逻辑:管理端事务调用本模块;HTTP 失败映射为稳定 AppError,由上层决定回滚。
逻辑:管理端事务调用本模块;set-password 失败映射为稳定业务码(相同密码/原密码错误不用 401)。
"""
from __future__ import annotations
@@ -111,13 +111,57 @@ def raise_update_user_error(source) -> None:
)
def is_same_password_error(message: str) -> bool:
"""判断 Casdoor 是否因新密码与当前密码相同而拒绝改密。"""
text = message or ''
lowered = text.lower()
if any(
token in lowered
for token in (
'cannot be the same',
'must be different',
'same as the old',
'same as old password',
'identical to the old',
'identical to old',
'password unchanged',
'new password is the same',
)
):
return True
if 'new password' in lowered and 'old password' in lowered and 'same' in lowered:
return True
return '新密码' in text and '旧密码' in text and ('相同' in text or '一样' in text)
def raise_password_unchanged(source=None) -> None:
"""新密码与当前密码相同按业务校验失败返回,禁止使用 401 以免前端清会话。"""
data = extract_error_payload(source) if source is not None else {}
msg_text = clean_str(data.get('msg') or data.get('error_description') or data.get('message'))
raise AppError(
code='AUTH.PASSWORD_UNCHANGED',
message='New password must differ from the current password',
http_status=400,
details={'technical': msg_text[:300]} if msg_text else {},
)
def raise_set_password_error(source) -> None:
"""将 Casdoor set-password 失败映射为稳定业务错误码。"""
"""将 Casdoor set-password 失败映射为稳定业务错误码,改密业务失败不使用会话 401。"""
data = extract_error_payload(source)
msg_text = clean_str(data.get('msg') or data.get('error_description') or data.get('message'))
lowered = (msg_text or str(source or '')).lower()
raw_text = msg_text or str(source or '')
lowered = raw_text.lower()
# [STEP 1] 先识别“新密码与旧密码相同”。Casdoor 文案含 old password,若后判会被误成原密码错误 401。
if is_same_password_error(raw_text):
raise_password_unchanged(source)
# [STEP 2] 原密码错误:业务 400。401 会被前端全局 fetch 包装当成登录失效并踢回登录页。
if is_password_error(lowered) or 'old password' in lowered or 'current password' in lowered:
raise AppError(code='CASDOOR_INVALID_CREDENTIALS', message='Incorrect current password', http_status=401)
raise AppError(
code='AUTH.INCORRECT_CURRENT_PASSWORD',
message='Incorrect current password',
http_status=400,
)
if any(token in lowered for token in ('too short', 'too weak', 'password policy', 'at least')):
raise AppError(code='CASDOOR_PASSWORD_POLICY', message='New password does not meet security requirements', http_status=400)
if is_user_missing_error(lowered):
+4 -3
View File
@@ -3,7 +3,7 @@ backend/app/services/chat/action_registry.py
用途:Chat Turn Action Handler 注册与解析。
依赖:turn_context.TurnContext、action_schema.TurnEvent、agent_registry.resolver。
逻辑:各领域在 chat_action_handlers / maintenance_chat_actions 等模块注册 handler;turn_runtime 调用 resolve。
逻辑:各领域在各自 action handler 模块注册 handler;turn_runtime 调用 resolve。
"""
from __future__ import annotations
@@ -17,6 +17,7 @@ from app.services.chat.turn_context import TurnContext
# action_type 前缀 → 允许的 agent_code 集合;空集合表示不限制。
ACTION_AGENT_CODES: dict[str, tuple[str, ...]] = {
"shipping.": ("shipping_notice",),
"transfer.": ("in_transit_transfer",),
}
@@ -78,8 +79,8 @@ def resolve_action_handler(ctx: TurnContext) -> ChatActionHandler:
def ensure_handlers_loaded() -> None:
"""延迟导入各领域 handler 模块以完成注册。"""
from app.services.shipping_notice import chat_action_handlers as _shipping_handlers # noqa: F401
from app.services.shipping_notice import chat_action_extended_handlers as _shipping_extended # noqa: F401
from app.services.in_transit_transfer import chat_actions as _transfer_actions # noqa: F401
_ = _shipping_handlers
_ = _shipping_extended
_ = _transfer_actions
+1 -1
View File
@@ -23,7 +23,7 @@ class TurnInput:
Args:
type: 输入类型;第一阶段仅开放 action / form_submit。
display_text: 写入 ChatLog.query 与前端 user 气泡的可见文案。
action_type: action / form_submit 时的全局唯一动作标识,如 shipping.submit_decision。
action_type: action / form_submit 时的全局唯一动作标识,如 shipping.create_order_extraction。
text: type=text 时的原始问题。
payload: 业务动作参数,由各领域 handler 自行解析。
"""
@@ -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)
+60 -2
View File
@@ -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
+7 -1
View File
@@ -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
@@ -58,6 +58,12 @@ def iter_handler_terminal_sse(
emitted_keys.add(dedupe_key)
def should_recover_upstream_error(ctx: ChatStreamContext, event_data: dict) -> bool:
"""委托领域 Handler 判断上游流错误是否可由已持久化业务事实恢复。"""
handler = resolve_handler_for_agent_code(ctx.agent)
return bool(handler and handler.should_recover_upstream_error(ctx, event_data))
def maybe_emit_handler_ui_state(ctx: ChatStreamContext, *, emitted_keys: set[str]) -> str | None:
"""
构造并格式化单次 UI State SSE;已 emit 的 dedupe 键则跳过。
-2
View File
@@ -73,8 +73,6 @@ def emit_ui_state_updated(*, domain: str, conversation_id: str, payload: dict[st
shipping_payload["ui_state"] = payload["ui_state"]
if payload.get("task_no"):
shipping_payload["task_no"] = payload["task_no"]
if payload.get("batch_no"):
shipping_payload["batch_no"] = payload["batch_no"]
return modern + sse_frame(shipping_payload)
@@ -0,0 +1,11 @@
"""
backend/app/services/contract_payment/__init__.py
用途:采购合同付款预警 Agent 服务包入口。
依赖:sync_service、parse_service、alert_service。
逻辑:API 层从此包调用合同同步、解析、付款计划和预警编排能力。
"""
from app.services.contract_payment import alert_service, dms_client, oa_client, parse_service, sync_service
__all__ = ["alert_service", "dms_client", "oa_client", "parse_service", "sync_service"]
@@ -0,0 +1,300 @@
"""
backend/app/services/contract_payment/acceptance_oa_service.py
用途:从 OA ecology SQL Server 读取已归档资产验收单,供合同付款预警计算验收款/质保款锚点。
依赖:OASQLServerService(复用既有 OA_SQLSERVER_* 只读连接,不新增 OA 库凭据)、Flask current_app。
逻辑:formtable_main_324.cgdh 为采购单号,requestId 关联 workflow_requestbase;
currentnodetype='3' 表示验收单已归档(0 创建 / 1 批准 / 2 提交 / 3 归档)。
查询失败 fail-safe 返回空,不打断合同 HTTP 同步。
"""
from __future__ import annotations
import re
from datetime import date, datetime
from typing import Any
from flask import current_app
from app.services.oa_sqlserver import OASQLServerService
# [STEP] 仅允许字母数字下划线作为 SQL 标识符,表名/字段来自配置,禁止拼接任意字符串。
_SAFE_IDENT = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*$")
_DEFAULT_TABLE = "formtable_main_324"
_DEFAULT_PO_FIELD = "cgdh"
_DEFAULT_NODETYPE = "3"
_DEFAULT_REQUEST_ID_FIELD = "requestId"
_PO_IN_BATCH = 100
def source_event_id(request_id: str | int, contract_id: int) -> str:
"""
生成验收归档事件的幂等键。
核心逻辑:同一 OA requestId 在多份合同(相同采购单号)下各写一条事件,避免
`(event_type, source_event_id)` 全局唯一约束把第二份合同挤掉。
Args:
request_id: OA workflow_requestbase.requestid / 表单 requestId。
contract_id: 合同付款台账主键。
Returns:
形如 `oa-acceptance:{requestId}:c{contractId}` 的稳定 ID。
"""
return f"oa-acceptance:{str(request_id).strip()}:c{int(contract_id)}"
def fetch_archived_acceptances(
*,
since: datetime | None = None,
purchase_order_nos: list[str] | None = None,
) -> tuple[list[dict[str, Any]], bool]:
"""
查询已归档资产验收单及其采购单号。
AI 触发时机:合同付款 `sync_notifications` 在合同申请单 HTTP 同步之后调用,
用验收归档日驱动验收款/质保款节点日期。
核心逻辑:JOIN `formtable_main_324` 与 `workflow_requestbase`,过滤
currentnodetype=3(归档)且 cgdh 非空。增量按 lastoperatedate(归档后该字段即为归档日);
同时可用采购单号回补「验收先于合同入库」的漏扫。连接或查询失败返回 `([], False)`。
Args:
since: 增量下限;None 表示全量(管理员 force 或首次断点)。
purchase_order_nos: 台账中尚无验收事件的采购单号,用于回补窗口外历史归档。
Returns:
`(events, ok)`。ok=False 时调用方不得推进验收断点。每条 event 含
request_id、purchase_order_no、archive_at、currentnodetype。
"""
try:
table = _configured_ident("CONTRACT_PAYMENT_OA_ACCEPTANCE_TABLE", _DEFAULT_TABLE)
po_field = _configured_ident("CONTRACT_PAYMENT_OA_ACCEPTANCE_PO_FIELD", _DEFAULT_PO_FIELD)
request_id_field = _configured_ident(
"CONTRACT_PAYMENT_OA_ACCEPTANCE_REQUEST_ID_FIELD",
_DEFAULT_REQUEST_ID_FIELD,
)
node_type = str(
current_app.config.get("CONTRACT_PAYMENT_OA_ACCEPTANCE_NODETYPE") or _DEFAULT_NODETYPE
).strip() or _DEFAULT_NODETYPE
po_nos = _unique_po_list(purchase_order_nos)
sql, params = build_archived_acceptance_sql(
table=table,
po_field=po_field,
request_id_field=request_id_field,
node_type=node_type,
since=since,
purchase_order_nos=po_nos,
)
connection = OASQLServerService._connect()
try:
cursor = connection.cursor()
cursor.execute(sql, params)
rows = cursor.fetchall() or []
finally:
connection.close()
except Exception:
current_app.logger.exception("合同付款预警:读取 OA 验收归档失败")
return [], False
events: list[dict[str, Any]] = []
for row in rows:
event = _row_to_event(row)
if event is not None:
events.append(event)
current_app.logger.info(
"合同付款预警:OA 验收归档 SQL 命中 %d 条 since=%s backfill_po=%d",
len(events),
since.isoformat() if since else None,
len(po_nos),
)
return events, True
def build_archived_acceptance_sql(
*,
table: str,
po_field: str,
request_id_field: str,
node_type: str,
since: datetime | None,
purchase_order_nos: list[str],
) -> tuple[str, list[Any]]:
"""
组装已归档验收单查询 SQL(标识符已校验,业务值全部参数化)。
核心逻辑:固定 JOIN workflow_requestbase;增量日期与采购单号回补用 OR 合并,
避免验收早于合同入库且 lastoperatedate 落在窗口外时永久漏扫。
Args:
table: 资产验收单主表,默认 formtable_main_324。
po_field: 采购单号列,默认 cgdh。
request_id_field: 表单 requestId 列。
node_type: workflow_requestbase.currentnodetype 目标值,默认 '3'(归档)。
since: 增量下限;None 不加日期条件。
purchase_order_nos: 回补采购单号;空列表不加 IN 条件。
Returns:
`(sql, params)` 供 pyodbc execute。
Raises:
ValueError: 标识符未通过安全校验。
"""
table_sql = _bracket_ident(table)
po_sql = _bracket_ident(po_field)
request_sql = _bracket_ident(request_id_field)
# [STEP 1] 验收单主表无状态字段;归档以 currentnodetype 为准(char:0 创建 / 1 批准 / 2 提交 / 3 归档)。
# char 可能带尾随空格,比较前 LTRIM/RTRIM。归档日取 lastoperatedate/lastoperatetime:
# currentnodetype 变为 3 后该对字段即为最后一次操作(归档)时间。
sql = f"""
SELECT
f.{request_sql} AS request_id,
LTRIM(RTRIM(CAST(f.{po_sql} AS nvarchar(200)))) AS purchase_order_no,
LTRIM(RTRIM(CAST(w.[currentnodetype] AS nvarchar(10)))) AS currentnodetype,
w.lastoperatedate AS lastoperatedate,
w.lastoperatetime AS lastoperatetime,
w.createdate AS createdate,
w.createtime AS createtime
FROM {table_sql} f
INNER JOIN [workflow_requestbase] w ON w.[requestid] = f.{request_sql}
WHERE LTRIM(RTRIM(CAST(w.[currentnodetype] AS nvarchar(10)))) = ?
AND f.{po_sql} IS NOT NULL
AND LTRIM(RTRIM(CAST(f.{po_sql} AS nvarchar(200)))) <> N''
"""
params: list[Any] = [str(node_type).strip()]
extra_clauses: list[str] = []
if since is not None:
extra_clauses.append("LTRIM(RTRIM(CAST(w.[lastoperatedate] AS nvarchar(20)))) >= ?")
params.append(since.date().isoformat())
if purchase_order_nos:
placeholders = ", ".join("?" for _ in purchase_order_nos)
extra_clauses.append(
f"LTRIM(RTRIM(CAST(f.{po_sql} AS nvarchar(200)))) IN ({placeholders})"
)
params.extend(purchase_order_nos)
if extra_clauses:
sql += " AND (" + " OR ".join(extra_clauses) + ")"
return sql, params
def parse_oa_archive_at(date_value: Any, time_value: Any = None) -> datetime | None:
"""
将泛微 lastoperatedate + lastoperatetime 拼成 naive datetime。
核心逻辑:兼容 date/datetime、yyyy-MM-dd、yyyy/MM/dd、yyyyMMdd;时间可缺省为 00:00:00。
Args:
date_value: 日期列。
time_value: 可选时间列(HH:mm:ss 或 HHmmss)。
Returns:
解析成功的 datetime;无法解析则 None。
"""
day = _parse_oa_date(date_value)
if day is None:
return None
hour, minute, second = _parse_oa_time(time_value)
return datetime(day.year, day.month, day.day, hour, minute, second)
def _configured_ident(config_key: str, default: str) -> str:
"""读取 Flask 配置中的 SQL 标识符,非法时回退默认值并打日志。"""
raw = str(current_app.config.get(config_key) or default).strip() or default
if not _SAFE_IDENT.match(raw):
current_app.logger.error("合同付款预警:非法 SQL 标识符 %s=%r,回退 %s", config_key, raw, default)
return default
return raw
def _bracket_ident(name: str) -> str:
"""校验并返回 [ident] 形式的 SQL Server 标识符。"""
if not _SAFE_IDENT.match(name):
raise ValueError(f"非法 SQL 标识符: {name!r}")
return f"[{name}]"
def _unique_po_list(purchase_order_nos: list[str] | None) -> list[str]:
"""去空白、去重,并截断单批 IN 参数数量。"""
seen: set[str] = set()
result: list[str] = []
for raw in purchase_order_nos or []:
po = str(raw or "").strip()
if not po or po in seen:
continue
seen.add(po)
result.append(po)
if len(result) >= _PO_IN_BATCH:
break
return result
def _row_to_event(row: Any) -> dict[str, Any] | None:
"""将游标行转为验收事件字典;无 requestId 或采购单号则丢弃。"""
request_id = _row_value(row, 0)
purchase_order_no = str(_row_value(row, 1) or "").strip()
currentnodetype = str(_row_value(row, 2) or "").strip()
if request_id in (None, "") or not purchase_order_no:
return None
archive_at = parse_oa_archive_at(_row_value(row, 3), _row_value(row, 4))
if archive_at is None:
archive_at = parse_oa_archive_at(_row_value(row, 5), _row_value(row, 6))
return {
"event_type": "acceptance_archive",
"source": "oa_sqlserver",
"request_id": str(request_id).strip(),
"purchase_order_no": purchase_order_no,
"currentnodetype": currentnodetype,
"archive_at": archive_at.isoformat(sep=" ") if archive_at else None,
"lastoperatedate": _stringify(_row_value(row, 3)),
"lastoperatetime": _stringify(_row_value(row, 4)),
}
def _row_value(row: Any, index: int) -> Any:
"""按位置取值,兼容 tuple 与 pyodbc.Row。"""
try:
return row[index]
except (IndexError, TypeError, KeyError):
return None
def _stringify(value: Any) -> str | None:
text = str(value).strip() if value is not None else ""
return text or None
def _parse_oa_date(value: Any) -> date | None:
if isinstance(value, datetime):
return value.date()
if isinstance(value, date):
return value
raw = str(value or "").strip()
if not raw:
return None
digits = re.sub(r"[^0-9]", "", raw)
if len(digits) >= 8:
try:
return date(int(digits[0:4]), int(digits[4:6]), int(digits[6:8]))
except ValueError:
return None
return None
def _parse_oa_time(value: Any) -> tuple[int, int, int]:
if value is None or value == "":
return 0, 0, 0
if isinstance(value, datetime):
return value.hour, value.minute, value.second
raw = str(value).strip()
digits = re.sub(r"[^0-9]", "", raw)
if len(digits) >= 6:
try:
return int(digits[0:2]), int(digits[2:4]), int(digits[4:6])
except ValueError:
return 0, 0, 0
if len(digits) == 4:
try:
return int(digits[0:2]), int(digits[2:4]), 0
except ValueError:
return 0, 0, 0
return 0, 0, 0
@@ -0,0 +1,506 @@
"""
services/contract_payment/alert_service.py
用途:按付款阶段生成待发送预警,在每周五按收件人汇总发送企业微信和 Excel 明细,并提供工作台待发送摘要。
依赖:合同付款模型、用户目录、openpyxl、企业微信通知服务、OA 上级矩阵、排程时区工具。
逻辑:每日任务只写入 pending 审计;周汇总任务锁定本周收件人批次,发送一条汇总卡片和一份逐笔 Excel;摘要接口与周五发送使用同一 pending 口径。
第一轮按台账申请人 `real_name` 唯一匹配系统用户;第二、三轮查 OA HrmResource + Matrixtable_3,用 zz/jfl 作为企微 userid,不向第一轮兜底。
"""
from __future__ import annotations
from collections import Counter, defaultdict
from dataclasses import dataclass
from datetime import date, datetime, timedelta, timezone
from io import BytesIO
from uuid import uuid4
from flask import current_app
from openpyxl import Workbook
from openpyxl.styles import Font
from sqlalchemy import func
from app import db
from app.models import (
ContractPaymentAlert,
ContractPaymentAlertBatch,
ContractPaymentContract,
ContractPaymentEvent,
ContractPaymentNode,
User,
)
from app.services.wecom_notify import (
send_wecom_event_message,
send_wecom_file_message,
upload_wecom_temp_media,
)
from app.services.contract_payment.erp_payment_service import fetch_paid_records, resolve_paid_node_dates
from app.services.contract_payment.supervisor_oa_service import SupervisorMatrixCache
from app.services.schedule.timezone_util import compute_next_run_at
@dataclass(frozen=True)
class _AlertRecipient:
"""扫描时解析出的收件人:系统用户 + 可选 OA/企微 userid。"""
user: User
oa_wecom_userid: str | None = None
_ALERT_RULES: dict[str, tuple[tuple[int, str], ...]] = {
"prepayment": ((7, "owner"), (14, "department_head"), (21, "procurement_leader")),
"shipment": ((-7, "owner"), (0, "department_head"), (14, "procurement_leader")),
"acceptance": ((30, "owner"), (40, "department_head"), (60, "procurement_leader")),
"warranty": ((-7, "owner"), (0, "department_head"), (14, "procurement_leader")),
}
def generate_alerts(*, today: date | None = None, send: bool = False) -> dict[str, int]:
"""每日扫描付款节点并生成 pending 预警,不直接发送企微。
AI 触发时机:每日排程或管理员手动执行扫描时调用。
核心逻辑:按阶段计算已到期的三轮提醒,按节点、轮次、收件人幂等;第二、三轮收件人来自 OA 部门矩阵;
ERP `apa_file` 的合格付款记录只停止尚未发送的后续轮次。
Args:
today: 业务日期,未传时使用服务器日期。
send: 保留旧调用兼容参数;最新方案下始终不发送消息。
Returns:
created、pending、skipped、resolved 四项计数。
"""
_ = send
today = today or date.today()
created = skipped = resolved = 0
supervisors = SupervisorMatrixCache()
rows = (
db.session.query(ContractPaymentNode, ContractPaymentContract)
.join(ContractPaymentContract, ContractPaymentContract.id == ContractPaymentNode.contract_id)
.filter(ContractPaymentNode.status == "active", ContractPaymentContract.status == "active")
.all()
)
paid_records = fetch_paid_records(
contract.purchase_order_no
for _node, contract in rows
if _node.node_type in {"prepayment", "shipment"}
)
paid_node_dates: dict[int, str | None] = {}
nodes_by_purchase_order: dict[str, list[ContractPaymentNode]] = defaultdict(list)
for node, contract in rows:
purchase_order_no = str(contract.purchase_order_no or "").strip()
if node.node_type in {"prepayment", "shipment"} and purchase_order_no:
nodes_by_purchase_order[purchase_order_no].append(node)
for purchase_order_no, payment_nodes in nodes_by_purchase_order.items():
paid_node_dates.update(resolve_paid_node_dates(
[(node.id, node.node_type, node.amount) for node in payment_nodes],
paid_records.get(purchase_order_no, []),
))
for node, contract in rows:
anchor = _anchor_date(contract=contract, node=node)
if anchor is None:
skipped += 1
continue
erp_paid = node.id in paid_node_dates
if erp_paid:
node.status = "paid"
# [STEP 1] 记录 ERP 付款日期,供详情页付款计划展示“已付 + 日期”。
node.evidence_json = {**(node.evidence_json or {}), "paid_at": paid_node_dates.get(node.id)}
for alert_round, (offset_days, recipient_role) in enumerate(_ALERT_RULES.get(node.node_type, ()), start=1):
scheduled_date = anchor + timedelta(days=offset_days)
if today < scheduled_date:
continue
# ERP 合格付款先按金额匹配阶段;同金额时预付款优先于出货款。
# 节点被匹配为已付款后,保留历史 sent,仅关闭尚未发送轮次。
if erp_paid:
resolved += _resolve_pending_alerts(node_id=node.id)
break
recipients = _resolve_recipients(
contract=contract, recipient_role=recipient_role, supervisors=supervisors
)
if not recipients:
skipped += 1
continue
for recipient in recipients:
trigger_key = f"round:{alert_round}:date:{scheduled_date.isoformat()}"
exists = db.session.query(ContractPaymentAlert.id).filter_by(
node_id=node.id, trigger_key=trigger_key, recipient_user_id=recipient.user.id
).first()
if exists:
continue
message_json = {"scheduled_date": scheduled_date.isoformat()}
if recipient.oa_wecom_userid:
message_json["oa_wecom_userid"] = recipient.oa_wecom_userid
db.session.add(ContractPaymentAlert(
contract_id=contract.id,
node_id=node.id,
trigger_key=trigger_key,
alert_round=alert_round,
scheduled_at=datetime.combine(scheduled_date, datetime.min.time()),
recipient_user_id=recipient.user.id,
status="pending",
message_json=message_json,
))
created += 1
db.session.commit()
return {"created": created, "pending": created, "sent": 0, "skipped": skipped, "resolved": resolved}
def _resolve_pending_alerts(*, node_id: int) -> int:
"""将某节点未发送的提醒标记为已按 ERP 付款关闭,保留历史发送记录。"""
rows = db.session.query(ContractPaymentAlert).filter_by(node_id=node_id, status="pending").all()
for alert in rows:
alert.status = "resolved"
alert.message_json = {**(alert.message_json or {}), "resolved_reason": "erp_paid"}
return len(rows)
def send_weekly_alerts(*, today: date | None = None) -> dict[str, int]:
"""按收件人发送本周合同付款预警汇总及 Excel 明细。
AI 触发时机:每周五 18:00 的排程或管理员补发时调用。
核心逻辑:每位收件人每周只产生一个批次;企微正文仅发送总笔数和阶段数量,逐笔信息写入附件。
Args:
today: 用于确定 ISO 周标识,测试可显式传入。
Returns:
batches、sent、failed、alerts 四项计数。
"""
today = today or date.today()
week_key = today.strftime("%G-W%V")
rows = (
db.session.query(ContractPaymentAlert, ContractPaymentContract, ContractPaymentNode, User)
.join(ContractPaymentContract, ContractPaymentContract.id == ContractPaymentAlert.contract_id)
.join(ContractPaymentNode, ContractPaymentNode.id == ContractPaymentAlert.node_id)
.join(User, User.id == ContractPaymentAlert.recipient_user_id)
.filter(ContractPaymentAlert.status == "pending", ContractPaymentContract.status == "active")
.order_by(ContractPaymentAlert.recipient_user_id, ContractPaymentAlert.scheduled_at, ContractPaymentAlert.id)
.all()
)
grouped: dict[int, list[tuple[ContractPaymentAlert, ContractPaymentContract, ContractPaymentNode, User]]] = defaultdict(list)
for row in rows:
grouped[row[0].recipient_user_id].append(row)
batches = sent = failed = detail_count = 0
for recipient_id, items in grouped.items():
batch = db.session.query(ContractPaymentAlertBatch).filter_by(week_key=week_key, recipient_user_id=recipient_id).first()
if batch and batch.status == "sent":
continue
if batch is None:
batch = ContractPaymentAlertBatch(
batch_no=f"CPAW-{datetime.utcnow():%Y%m%d%H%M%S}-{uuid4().hex[:8].upper()}",
week_key=week_key,
recipient_user_id=recipient_id,
status="sending",
)
db.session.add(batch)
db.session.flush()
batches += 1
workbook_data, summary = _build_excel(items)
batch.summary_json = summary
batch.excel_file_name = f"合同付款预警明细-{week_key}-{recipient_id}.xlsx"
batch.excel_file_data = workbook_data
batch.excel_file_size = len(workbook_data)
user = items[0][3]
wecom_userid = _batch_wecom_userid(items, user)
result = send_wecom_event_message(
event_type="contract_payment_warning",
user=user,
title=f"合同付款预警汇总({summary['total']}笔)",
content=_build_summary_message(summary),
jump_path="/workspace/contract-payment",
jump_params={"batch_no": batch.batch_no},
wecom_userid=wecom_userid,
)
trace = {"textcard": result}
try:
media_id = upload_wecom_temp_media(workbook_data, batch.excel_file_name)
file_result = (
send_wecom_file_message(wecom_userid, media_id)
if wecom_userid
else {"errcode": -1, "errmsg": "user_unbound"}
)
trace["file"] = file_result
except Exception as exc:
trace["file_error"] = str(exc)
file_result = {"errcode": -1}
batch.wecom_trace_json = trace
if result.get("ok") and file_result.get("errcode") == 0:
batch.status = "sent"
batch.sent_at = datetime.utcnow()
for alert, *_ in items:
alert.status = "sent"
alert.sent_at = datetime.utcnow()
alert.message_json = {**(alert.message_json or {}), "batch_no": batch.batch_no}
detail_count += 1
sent += 1
else:
batch.status = "failed"
batch.error_message = str(trace)[:2000]
failed += 1
db.session.commit()
return {"batches": batches, "sent": sent, "failed": failed, "alerts": detail_count}
def build_weekly_alert_summary(*, now: datetime | None = None) -> dict[str, object]:
"""返回本周待发送笔数和下一次周五汇总发送时间。
核心逻辑:待发送口径与 `send_weekly_alerts` 一致(pending + 合同 active);
下次发送时刻复用排程 Cron `0 18 * * 5` 与上海时区,当前时刻已过本周五 18:00 则指向下周五。
Args:
now: 可选 UTC naive 基准时刻,测试可注入;未传时使用当前时间。
Returns:
pending_count、UTC ISO 的 next_send_at,以及业务时区名称。
"""
pending_count = (
db.session.query(ContractPaymentAlert)
.join(ContractPaymentContract, ContractPaymentContract.id == ContractPaymentAlert.contract_id)
.filter(ContractPaymentAlert.status == "pending", ContractPaymentContract.status == "active")
.count()
)
timezone_name = str(current_app.config.get("CONTRACT_PAYMENT_ALERT_TIMEZONE") or "Asia/Shanghai").strip() or "Asia/Shanghai"
cron = str(current_app.config.get("CONTRACT_PAYMENT_ALERT_WEEKLY_CRON") or "0 18 * * 5").strip() or "0 18 * * 5"
next_utc = compute_next_run_at(cron, base_utc_naive=now, timezone_name=timezone_name)
next_send_at = None
if next_utc is not None:
next_send_at = next_utc.replace(tzinfo=timezone.utc).isoformat().replace("+00:00", "Z")
return {
"pending_count": pending_count,
"next_send_at": next_send_at,
"timezone": timezone_name,
}
def _node_paid_date(node: ContractPaymentNode) -> str | None:
"""返回节点实际付款日期(ERP apa_file 的 paid_at);节点未付时返回 None。
用于 Excel 「付款日期」列:只有已付节点才展示付款日期,未付显示「—」,
避免把「到期日」(due_date)误标为付款日期。
"""
if str(node.status or "").strip().lower() != "paid":
return None
return (node.evidence_json or {}).get("paid_at")
def _build_excel(items) -> tuple[bytes, dict[str, object]]:
"""生成收件人专属逐笔付款预警明细 Excel。
核心逻辑:按合同/节点逐行输出;「收件人」列写该批次实际收件人姓名,「状态」列写中文,不再输出岗位名称或 pending 英文码。
"""
wb = Workbook()
ws = wb.active
ws.title = "付款预警明细"
headers = ["合同编号", "采购编号", "供应商", "合同金额", "付款阶段", "付款金额", "比例", "付款日期", "到期日", "预警轮次", "收件人", "状态"]
ws.append(headers)
for cell in ws[1]:
cell.font = Font(bold=True)
counts = Counter()
for alert, contract, node, user in items:
ws.append([
contract.contract_no or "待解析", contract.purchase_order_no or "—", contract.supplier_name or "—",
str(contract.total_amount or ""), _node_label(node.node_type), str(node.amount or ""),
str(node.percentage or ""), _node_paid_date(node) or "—", (node.due_date or node.anchor_date).isoformat() if (node.due_date or node.anchor_date) else "—",
f"第{alert.alert_round}次", _recipient_display_name(user), _alert_status_label(alert.status),
])
counts[node.node_type] += 1
ws.freeze_panes = "A2"
ws.auto_filter.ref = ws.dimensions
output = BytesIO()
wb.save(output)
return output.getvalue(), {"total": len(items), "stages": {_node_label(k): v for k, v in counts.items()}}
def _recipient_display_name(user: User | None) -> str:
"""
返回 Excel「收件人」列展示的人名。
核心逻辑:优先真实姓名;姓名为空时回退用户名,避免再写出岗位名称。
Args:
user: 本行预警对应的系统用户;缺失时写「—」。
Returns:
去空白后的姓名或用户名;都没有时为「—」。
"""
if user is None:
return "—"
name = str(getattr(user, "real_name", None) or "").strip()
if name:
return name
username = str(getattr(user, "username", None) or "").strip()
return username or "—"
def _build_summary_message(summary: dict[str, object]) -> str:
stages = summary.get("stages") or {}
detail = "、".join(f"{key}{value}笔" for key, value in stages.items()) or "无"
return f"本周需关注付款 {summary.get('total', 0)} 笔\n阶段汇总:{detail}\n详细合同与付款信息请查看随附 Excel。"
def _anchor_date(*, contract: ContractPaymentContract, node: ContractPaymentNode) -> date | None:
"""返回付款节点的提醒规则锚点日期;缺少事实时返回 None。"""
if node.node_type == "prepayment":
return contract.oa_archive_at.date() if contract.oa_archive_at else None
if node.node_type == "shipment":
return node.due_date or contract.delivery_due_date
if node.node_type == "acceptance":
event = db.session.query(ContractPaymentEvent).filter_by(contract_id=contract.id, event_type="acceptance_archive").order_by(ContractPaymentEvent.event_date.asc()).first()
return event.event_date if event else None
if node.node_type == "warranty":
return node.due_date
return None
def bind_contract_owner_from_applicant(contract: ContractPaymentContract) -> User | None:
"""
将合同第一轮收件人绑定为台账申请人对应的系统用户。
核心逻辑:用 OA/台账上的申请人姓名对 `users.real_name` 做去空白后的精确匹配;
仅当且仅有一名 active 用户时写入 `owner_user_id`。匹配失败、姓名为空或重名时清空
`owner_user_id`,禁止继续使用默认管理员或其他兜底账号。
Args:
contract: 已带 applicant_name 的合同主记录。
Returns:
唯一匹配到的系统用户;无法唯一确定时返回 None。
"""
name = str(contract.applicant_name or "").strip()
if not name:
contract.owner_user_id = None
return None
matches = (
db.session.query(User)
.filter(User.status == "active", func.trim(User.real_name) == name)
.order_by(User.id.asc())
.all()
)
if len(matches) != 1:
current_app.logger.warning(
"contract_payment applicant mapping skipped contract_id=%s applicant=%s matches=%s",
getattr(contract, "id", None),
name,
len(matches),
)
contract.owner_user_id = None
return None
user = matches[0]
contract.owner_user_id = user.id
return user
def _batch_wecom_userid(
items: list[tuple[ContractPaymentAlert, ContractPaymentContract, ContractPaymentNode, User]],
user: User,
) -> str | None:
"""
解析本周批次实际发送的企业微信 userid。
核心逻辑:第二、三轮优先用 OA 矩阵写入的 `oa_wecom_userid`(即 HrmResource.id);
没有时回退系统用户已绑定的 wecom_userid。第一轮通常走后者。
"""
for alert, *_rest in items:
raw = (alert.message_json or {}).get("oa_wecom_userid")
text = str(raw or "").strip()
if text:
return text
bound = str(getattr(user, "wecom_userid", None) or "").strip()
return bound or None
def _resolve_recipients(
*,
contract: ContractPaymentContract,
recipient_role: str,
supervisors: SupervisorMatrixCache,
) -> list[_AlertRecipient]:
"""
根据轮次岗位解析有效收件人。
核心逻辑:第一轮按申请人真实姓名唯一匹配系统用户。第二轮用矩阵 zz、第三轮用 jfl,
该 OA id 同时作为企微 userid;再映射到系统用户以便写入 recipient_user_id。
查不到或无法唯一确定时跳过该轮,不向第一轮申请人或其他全局名单兜底。
"""
if recipient_role == "owner":
user = bind_contract_owner_from_applicant(contract)
return [_AlertRecipient(user=user)] if user else []
matrix = supervisors.get(contract.applicant_name)
if matrix is None or not matrix.ok:
return []
oa_id = matrix.round2_oa_id if recipient_role == "department_head" else matrix.round3_oa_id
lastname = matrix.round2_name if recipient_role == "department_head" else matrix.round3_name
user = _user_for_oa_wecom_id(oa_id, lastname)
if user is None:
current_app.logger.warning(
"contract_payment supervisor recipient missing role=%s contract_id=%s oa_id=%s",
recipient_role,
getattr(contract, "id", None),
oa_id,
)
return []
return [_AlertRecipient(user=user, oa_wecom_userid=str(oa_id))]
def _user_for_oa_wecom_id(oa_id: int | None, lastname: str | None) -> User | None:
"""
将 OA/企微 userid 映射为系统用户。
核心逻辑:优先 `users.wecom_userid` 精确等于 OA id;未绑定时再用主管 lastname
对 `users.real_name` 做唯一匹配,以便满足预警表的用户外键。重名或都未命中则放弃。
"""
if oa_id is None:
return None
wecom = str(oa_id)
by_wecom = (
db.session.query(User)
.filter(User.status == "active", User.wecom_userid == wecom)
.order_by(User.id.asc())
.all()
)
if len(by_wecom) == 1:
return by_wecom[0]
if len(by_wecom) > 1:
current_app.logger.warning(
"contract_payment supervisor wecom_userid not unique oa_id=%s matches=%s",
wecom,
len(by_wecom),
)
return None
name = str(lastname or "").strip()
if not name:
return None
by_name = (
db.session.query(User)
.filter(User.status == "active", func.trim(User.real_name) == name)
.order_by(User.id.asc())
.all()
)
if len(by_name) == 1:
return by_name[0]
current_app.logger.warning(
"contract_payment supervisor user mapping skipped oa_id=%s lastname=%s matches=%s",
wecom,
name,
len(by_name),
)
return None
def _node_label(node_type: str) -> str:
"""返回付款阶段中文名称。"""
return {"prepayment": "预付款", "shipment": "出货款", "acceptance": "验收款", "warranty": "质保款"}.get(node_type, node_type)
def _alert_status_label(status: str | None) -> str:
"""返回预警状态的中文名称,供企微 Excel「状态」列使用。
核心逻辑:与工作台 alertStatus 口径一致;未知编码原样回写,避免掩盖新增状态。
Args:
status: 预警记录内部状态码。
Returns:
中文状态;空值写「—」。
"""
code = str(status or "").strip().lower()
if not code:
return "—"
return {
"pending": "待发送",
"sent": "已发送",
"failed": "发送失败",
"resolved": "已关闭",
"sending": "发送中",
}.get(code, str(status).strip())
@@ -0,0 +1,205 @@
"""
backend/app/services/contract_payment/dms_client.py
用途:访问采购合同文档管理系统,作为 OA 附件缺失时的延迟补充来源。
依赖:requests、Flask 配置;接口模式复用固定资产图片服务的登录、目录查询和附件代理。
逻辑:使用配置的根 FolderID 逐级定位年份目录,按合同编号检索文件,再按创建日期窗口筛选并下载附件。
"""
from __future__ import annotations
import threading
import time
from datetime import date, datetime, timedelta
from typing import Any
from urllib.parse import urlencode
import requests
from flask import current_app
_LOCK = threading.Lock()
_CACHE: dict[str, Any] = {"session": None, "created_at": 0.0}
class ContractDmsClient:
"""采购合同文档库轻量客户端;不会把账号或密码返回给 API。"""
@classmethod
def _base(cls) -> str:
return str(current_app.config.get("CONTRACT_DMS_BASE_URL") or "").rstrip("/")
@classmethod
def is_configured(cls) -> bool:
"""判断 DMS 地址、账号、密码和文档库 ID 是否齐全。"""
return bool(
cls._base()
and current_app.config.get("CONTRACT_DMS_USERNAME")
and current_app.config.get("CONTRACT_DMS_PASSWORD")
and current_app.config.get("CONTRACT_DMS_LIBRARY_ID")
and current_app.config.get("CONTRACT_DMS_ROOT_FOLDER_ID")
)
@classmethod
def _session(cls, *, refresh: bool = False) -> requests.Session:
"""登录 DMS 并缓存会话;登录失败抛出异常,不暴露密码。"""
with _LOCK:
session = _CACHE.get("session")
if not refresh and isinstance(session, requests.Session) and time.time() - float(_CACHE.get("created_at") or 0) < 1200:
return session
session = requests.Session()
response = session.post(
f"{cls._base()}/Login/_api/Login",
json={"LoginName": current_app.config.get("CONTRACT_DMS_USERNAME"), "Pwd": current_app.config.get("CONTRACT_DMS_PASSWORD")},
timeout=20,
)
response.raise_for_status()
payload = response.json()
if int(payload.get("Code") or 0) != 0:
raise RuntimeError(payload.get("Msg") or "文档管理系统登录失败")
_CACHE.update({"session": session, "created_at": time.time()})
return session
@classmethod
def _page(cls, *, parent_folder_id: str, leaf_name: str = "", recursion: bool = False) -> list[dict[str, Any]]:
"""查询一个父目录下的条目;目录解析使用非递归,合同文件检索使用递归。"""
payload = {
"LibraryID": str(current_app.config.get("CONTRACT_DMS_LIBRARY_ID")),
"ParentFolderID": parent_folder_id,
"Keywords": "",
"Page": {"Size": 200, "Index": 1},
"Total": 0,
"Recursion": recursion,
"OrderBy": [],
"FieldQuery": [],
"LeafName": leaf_name,
}
session = cls._session()
response = session.post(f"{cls._base()}/Api/_api/APS/Public/Item/Page", json=payload, timeout=30)
if response.status_code in {401, 403}:
session = cls._session(refresh=True)
response = session.post(f"{cls._base()}/Api/_api/APS/Public/Item/Page", json=payload, timeout=30)
response.raise_for_status()
data = response.json()
if int(data.get("Code") or 0) != 0:
raise RuntimeError(data.get("Msg") or "文档管理系统查询失败")
section = data.get("Data") or {}
return section.get("Rows") or section.get("Items") or (section.get("Page") or {}).get("Items") or []
@classmethod
def resolve_folder(cls, *, archive_date: date | None = None, folder_id: str | None = None) -> str:
"""
根据归档年份解析合同目录 FolderID。
AI 触发时机:OA 附件缺失,需要在 DMS 补查合同时调用。
逻辑:传入 folder_id 时直接使用;否则从根目录查找“{year}年设备合同书”,查不到时回退根目录。
"""
explicit = str(folder_id or "").strip()
if explicit:
return explicit
root = str(current_app.config.get("CONTRACT_DMS_ROOT_FOLDER_ID") or "").strip()
if not root or not archive_date:
return root
if archive_date.year == 2026:
configured_2026 = str(current_app.config.get("CONTRACT_DMS_2026_FOLDER_ID") or "").strip()
if configured_2026:
return configured_2026
template = str(current_app.config.get("CONTRACT_DMS_YEAR_FOLDER_NAME_TEMPLATE") or "{year}年设备合同书")
wanted = template.format(year=archive_date.year)
rows = cls._page(parent_folder_id=root, recursion=False)
for row in rows:
if row.get("IsFolder") and str(row.get("LeafName") or "").strip() == wanted:
return str(row.get("ID") or root)
return root
@classmethod
def _created_at(cls, row: dict[str, Any]) -> datetime | None:
"""读取 DMS 条目的创建时间,无法解析时返回 None。"""
raw = row.get("CreatedDate") or row.get("CreatedAt") or row.get("CreateDate")
if isinstance(raw, datetime):
return raw.replace(tzinfo=None)
text = str(raw or "").strip()
if not text:
return None
try:
return datetime.fromisoformat(text.replace("Z", "+00:00")).replace(tzinfo=None)
except ValueError:
return None
@classmethod
def search(cls, *, contract_no: str, folder_id: str | None = None, archive_date: date | None = None) -> list[dict[str, Any]]:
"""
按合同编号查询 DMS 文件并按 OA 归档日期过滤。
AI 触发时机:OA 附件下载失败或延迟到达时调用。
约束:只返回文件元数据;不创建合同主记录、不生成采购单号。首选年份目录,最后查询暂存目录。
"""
if not cls.is_configured():
return []
normalized = str(contract_no or "").strip()
if not normalized:
return []
root = str(current_app.config.get("CONTRACT_DMS_ROOT_FOLDER_ID") or "").strip()
primary = cls.resolve_folder(archive_date=archive_date, folder_id=folder_id)
folder_ids = [primary]
temp_name = str(current_app.config.get("CONTRACT_DMS_TEMP_FOLDER_NAME") or "暂存").strip()
if primary == root and root:
rows = cls._page(parent_folder_id=root, recursion=False)
else:
rows = cls._page(parent_folder_id=root, recursion=False) if root else []
for row in rows:
if row.get("IsFolder") and str(row.get("LeafName") or "").strip() == temp_name:
temp_id = str(row.get("ID") or "")
if temp_id and temp_id not in folder_ids:
folder_ids.append(temp_id)
window = max(int(current_app.config.get("CONTRACT_DMS_LOOKUP_WINDOW_DAYS") or 30), 0)
start = datetime.combine(archive_date - timedelta(days=window), datetime.min.time()) if archive_date else None
end = datetime.combine(archive_date + timedelta(days=window), datetime.max.time()) if archive_date else None
matches: list[dict[str, Any]] = []
for current_folder in folder_ids:
for row in cls._page(parent_folder_id=current_folder, leaf_name=normalized, recursion=True):
if row.get("IsFolder"):
continue
if normalized.lower() not in str(row.get("LeafName") or "").lower():
continue
created = cls._created_at(row)
if start and end and created and not (start <= created <= end):
continue
row = dict(row)
row["DmsFolderID"] = current_folder
matches.append(row)
matches.sort(key=lambda row: cls._created_at(row) or datetime.min, reverse=True)
return matches
@classmethod
def download_attachment(cls, attachment_id: str, *, max_size: int | None = None) -> tuple[bytes, str, str | None]:
"""
下载 DMS 附件二进制,供 FileAsset 私有存储和合同解析使用。
参数约束:attachment_id 必须来自 DMS Item/Page 返回的 MainFileAttachment.ID。
返回:文件字节、MIME 类型、Content-Disposition 推断的文件名。
"""
attachment = str(attachment_id or "").strip()
if not attachment:
raise ValueError("DMS attachment ID is required")
session = cls._session()
response = session.get(cls.attachment_url(attachment), timeout=60, allow_redirects=True)
if response.status_code in {401, 403}:
session = cls._session(refresh=True)
response = session.get(cls.attachment_url(attachment), timeout=60, allow_redirects=True)
response.raise_for_status()
data = response.content
limit = max_size or 30 * 1024 * 1024
if len(data) > limit:
raise RuntimeError("DMS 附件超过文件大小限制")
content_type = (response.headers.get("content-type") or "application/octet-stream").split(";", 1)[0].strip().lower()
disposition = response.headers.get("content-disposition") or ""
filename = None
if "filename=" in disposition:
filename = disposition.split("filename=", 1)[1].strip().strip('"')
return data, content_type, filename
@classmethod
def attachment_url(cls, attachment_id: str) -> str:
"""生成同源附件 Embed URL;不把登录 Cookie 暴露给前端。"""
return f"{cls._base()}/Api/_api/DMS/Public/Attachment/Embed?{urlencode({'attachmentID': attachment_id})}"
@@ -0,0 +1,221 @@
"""
backend/app/services/contract_payment/erp_payment_service.py
用途:从 ERP Oracle `apa_file` 读取采购单付款记录,作为预付款和出货款的付款完成事实来源。
依赖:oracledb、Text2SQLService 的 Oracle 客户端初始化能力及 Flask 配置。
逻辑:仅执行只读查询;只接受 `apa00='15'`(厂商预付款作业)且 `apa41='Y'`、`apa63=1` 的记录,并按采购单收集 `apa34f` 供明细和阶段匹配使用。
"""
from __future__ import annotations
import itertools
from dataclasses import dataclass
from decimal import Decimal, InvalidOperation
from typing import Iterable
from flask import current_app
_PAYMENT_STAGE_ORDER = {"prepayment": 1, "shipment": 2}
@dataclass(frozen=True)
class ErpPaidRow:
"""ERP `apa_file` 中一条合格的付款记录。"""
amount: Decimal
# 付款日期(apa02)ISO 字符串;ERP 未提供或为空时保持 None。
paid_date: str | None
def fetch_paid_records(purchase_order_nos: Iterable[str]) -> dict[str, list[ErpPaidRow]]:
"""
查询采购单已完成付款记录(含付款日期)。
AI 触发时机:合同付款预警每日扫描前,需要判断预付款/出货款是否已经完成付款。
核心逻辑:查询 `apa_file`,先按 `apa00='15'` 限定为「厂商预付款作业」,再过滤 `apa41='Y'` 和 `apa63=1`,按 `apaud03` 收集 `apa34f`(金额)与 `apa02`(付款日期)。
Args:
purchase_order_nos: 待查询的采购单号集合;空集合不会连接 ERP。
Returns:
采购单号到合格付款记录列表的映射。ERP 未配置、驱动不可用或查询失败时返回空映射,
由调用方按未付款处理,避免错误停止预警。
"""
normalized = sorted({str(value or "").strip() for value in purchase_order_nos if str(value or "").strip()})
if not normalized:
return {}
dsn = str(current_app.config.get("CONTRACT_PAYMENT_ERP_DSN") or "").strip()
username = str(current_app.config.get("CONTRACT_PAYMENT_ERP_USERNAME") or "").strip()
password = str(current_app.config.get("CONTRACT_PAYMENT_ERP_PASSWORD") or "")
if not dsn or not username or not password:
# 打印缺失字段名,便于定位到底是 DSN / 用户名 / 密码哪一项在运行时为空(不输出密码本身)。
missing = [name for name, value in (("DSN", dsn), ("用户名", username), ("密码", password)) if not value]
current_app.logger.warning("合同付款预警:ERP 付款查询未配置,按未付款处理;缺失字段=%s", "、".join(missing) or "未知")
return {}
try:
import oracledb
from app.services.text2sql import Text2SQLService
except ImportError:
current_app.logger.warning("合同付款预警:Oracle 驱动不可用,按未付款处理")
return {}
connection = None
try:
# 合同付款仅需 apa_file 单表读取:优先尝试 thick(需本机 Oracle Client),
# 若本机未安装 Oracle Client(DPI-1047)则回退到 python-oracledb 默认的 thin 模式,
# 避免因缺少客户端库而把整笔已付事实误判为未付。
try:
Text2SQLService._init_oracle_client(oracledb)
except Exception:
current_app.logger.info("合同付款预警:Oracle Client 不可用,回退 thin 模式连接")
connection = oracledb.connect(user=username, password=password, dsn=dsn)
timeout = max(int(current_app.config.get("CONTRACT_PAYMENT_ERP_TIMEOUT_SECONDS") or 30), 5)
connection.call_timeout = timeout * 1000
cursor = connection.cursor()
placeholders = ", ".join(f":po_{index}" for index in range(len(normalized)))
# [STEP 1] 只取「厂商预付款作业」类型的付款记录:apa00='15' 为厂商预付款作业标志,
# 过滤掉其它作业类型(如对账/其它付款),避免把非预付款的付款误匹配到预付款/出货款节点;
# 后再叠加 apa41='Y'(有效)与 apa63=1(已完成付款)两层过滤,仅统计真正完成的预付款。
# apaud03 varchar2 40 采购单号
sql = f"""
SELECT TRIM(apaud03) AS purchase_order_no,
NVL(apa34f, 0) AS paid_amount,
TRUNC(apa02) AS paid_date
FROM apa_file
WHERE TRIM(apaud03) IN ({placeholders})
AND TRIM(TO_CHAR(apa00)) = '15'
AND UPPER(TRIM(apa41)) = 'Y'
AND TRIM(TO_CHAR(apa63)) = '1'
"""
cursor.execute(sql, {f"po_{index}": value for index, value in enumerate(normalized)})
result: dict[str, list[ErpPaidRow]] = {}
for raw_po, raw_amount, raw_paid_date in cursor:
po = str(raw_po or "").strip()
if not po:
continue
try:
amount = Decimal(str(raw_amount or "0"))
except (InvalidOperation, TypeError, ValueError):
continue
paid_date = getattr(raw_paid_date, "isoformat", lambda: None)().split("T")[0] if raw_paid_date else None
result.setdefault(po, []).append(ErpPaidRow(amount=amount, paid_date=paid_date))
return result
except Exception as exc:
# 记录具体 Oracle 错误码(如 ORA-01017/00942/12514)与消息,便于定位账号权限/服务名问题;不输出密码。
code = getattr(exc, "code", None) or getattr(exc, "full_code", None)
current_app.logger.warning(
"合同付款预警:ERP 付款查询失败,按未付款处理,error_type=%s code=%s message=%s",
type(exc).__name__,
code,
str(exc) or getattr(exc, "message", ""),
)
return {}
finally:
if connection is not None:
try:
connection.close()
except Exception:
pass
def fetch_paid_amounts(purchase_order_nos: Iterable[str]) -> dict[str, list[Decimal]]:
"""查询采购单已完成付款金额列表(兼容旧调用方)。"""
records = fetch_paid_records(purchase_order_nos)
return {po: [row.amount for row in rows] for po, rows in records.items()}
def _select_match(
unresolved: list[tuple[int, str, Decimal]],
amount: Decimal,
tolerance: Decimal,
) -> list[tuple[int, str, Decimal]]:
"""从待匹配节点列表中选出与某笔 ERP 付款金额匹配的节点。
核心逻辑:预付款与出货款可能「分开请款」也可能「同一笔请款一并请款」,
因此先按单节点金额匹配(分开请款场景);若单节点无命中,再按「多节点金额之和」
匹配(同一笔请款同时请预付款+出货款),命中后一次性返回全部相关节点,
由调用方把都标记为已付款,避免把组合金额漏判为未付款。
Args:
unresolved: 待匹配的 `(node_id, node_type, amount)` 列表,已按业务顺序排序。
amount: 本次 ERP 付款金额(apa34f)。
tolerance: 金额匹配容差(默认 0.01)。
Returns:
匹配到的节点列表;无匹配时返回空列表。单节点命中时只取顺序最前的一个。
"""
# [STEP 1] 分开请款:单节点金额与付款金额一致。
single = [item for item in unresolved if abs(item[2] - amount) <= tolerance]
if single:
return single[:1]
# [STEP 2] 同一笔请款:预付款+出货款等节点金额之和与付款金额一致,命中即全部视为已付。
# 节点数量极少(通常 2 个),组合搜索开销可忽略;优先从小组合(2 个)开始找。
for size in range(2, len(unresolved) + 1):
for combo in itertools.combinations(unresolved, size):
if abs(sum(item[2] for item in combo) - amount) <= tolerance:
return list(combo)
return []
def resolve_paid_node_dates(
nodes: Iterable[tuple[int, str, Decimal | None]],
paid_rows: Iterable[ErpPaidRow],
) -> dict[int, str | None]:
"""
将同一采购单的 ERP 付款记录匹配到预付款、出货款节点,并返回节点 ID 到付款日期的映射。
核心逻辑:`apa00='15'`、`apa41='Y'` 且 `apa63=1` 的每笔 ERP 付款按金额与节点匹配;
金额相同则按预付款、出货款的业务顺序匹配最前面仍未付款的节点;若单节点无匹配但
「预付款+出货款」金额之和与该笔付款一致,说明预付款与出货款在同一笔请款中一并请款,
则把两者同时标记为已付款,并携带该笔付款日期。
Args:
nodes: 同一采购单的 `(node_id, node_type, amount)` 节点;只传预付款、出货款的 active 节点。
paid_rows: 该采购单的合格 ERP 付款记录。
Returns:
已匹配节点的付款日期映射(节点 ID -> 付款日期,日期可能为空)。
"""
tolerance = Decimal("0.01")
unresolved = sorted(
((node_id, node_type, amount) for node_id, node_type, amount in nodes if amount is not None),
key=lambda item: (_PAYMENT_STAGE_ORDER.get(item[1], 99), item[0]),
)
matched: dict[int, str | None] = {}
for paid_row in paid_rows:
hits = _select_match(unresolved, paid_row.amount, tolerance)
if not hits:
continue
hit_ids = {item[0] for item in hits}
for item in hits:
matched[item[0]] = paid_row.paid_date
unresolved = [item for item in unresolved if item[0] not in hit_ids]
return matched
def resolve_paid_node_ids(
nodes: Iterable[tuple[int, str, Decimal | None]],
paid_amounts: Iterable[Decimal],
) -> set[int]:
"""
将同一采购单的 ERP 付款金额匹配到预付款、出货款节点。
核心逻辑:`apa00='15'`、`apa41='Y'` 且 `apa63=1` 的每笔 ERP 付款按 `apa34f` 与节点金额匹配;
金额不同则自然对应相应节点,金额相同时按预付款、出货款的业务顺序匹配最前面仍未付款的节点;
若单节点无匹配但「预付款+出货款」金额之和与该笔付款一致,则一并标记两者为已付款
(预付款、出货款在同一笔请款中一并请款的场景)。
Args:
nodes: 同一采购单的 `(node_id, node_type, amount)` 节点;只传预付款、出货款的 active 节点。
paid_amounts: 该采购单的合格 ERP 每笔付款金额。
Returns:
已付款节点 ID 集合。
"""
tolerance = Decimal("0.01")
unresolved = sorted(
((node_id, node_type, amount) for node_id, node_type, amount in nodes if amount is not None),
key=lambda item: (_PAYMENT_STAGE_ORDER.get(item[1], 99), item[0]),
)
matched: set[int] = set()
for paid_amount in paid_amounts:
hits = _select_match(unresolved, paid_amount, tolerance)
if not hits:
continue
hit_ids = {item[0] for item in hits}
matched.update(hit_ids)
unresolved = [item for item in unresolved if item[0] not in hit_ids]
return matched
@@ -0,0 +1,220 @@
"""
backend/app/services/contract_payment/ledger_focus.py
用途:合同台账汇总卡口径——即将到期、逾期未付、待补充、本月应付,均按合同计数。
依赖:ContractPaymentContract、ContractPaymentNode、业务时区 Asia/Shanghai。
逻辑:由 list/summary API 调用;分类规则与台账行状态标签对齐,本月应付可与前两项重叠。
"""
from __future__ import annotations
from collections import defaultdict
from datetime import date, datetime
from typing import Any, Iterable
from zoneinfo import ZoneInfo
from sqlalchemy.orm import Query, Session
from sqlalchemy.sql.expression import false
from app.models import ContractPaymentContract, ContractPaymentNode
LEDGER_FOCUS_DUE = "due"
LEDGER_FOCUS_OVERDUE = "overdue"
LEDGER_FOCUS_NEEDS_COMPLETION = "needs_completion"
LEDGER_FOCUS_DUE_THIS_MONTH = "due_this_month"
LEDGER_FOCUS_VALUES = {
LEDGER_FOCUS_DUE,
LEDGER_FOCUS_OVERDUE,
LEDGER_FOCUS_NEEDS_COMPLETION,
LEDGER_FOCUS_DUE_THIS_MONTH,
}
_NEAR_DUE_DAYS = 7
_SHANGHAI = ZoneInfo("Asia/Shanghai")
def business_today(*, today: date | None = None) -> date:
"""
返回汇总卡使用的业务日(上海日历)。
Args:
today: 测试注入的业务日;缺省为 Asia/Shanghai 当天。
Returns:
用于 7 日内到期、逾期和本月判断的日期。
"""
return today or datetime.now(_SHANGHAI).date()
def node_due_reference(due_date: date | None, anchor_date: date | None) -> date | None:
"""
付款节点到期判断基准日。
核心逻辑:与前台 paymentStatus.nodeDueReference 一致,优先 due_date,否则回退 anchor_date。
Args:
due_date: 节点到期日。
anchor_date: 节点锚点日。
Returns:
可用于比较的日期;两者皆空时为 None。
"""
return due_date or anchor_date
def classify_ledger_status(
*,
contract_status: str | None,
parse_status: str | None,
nodes: Iterable[dict[str, Any]],
today: date,
) -> str:
"""
按合同聚合出台账状态,与列表「状态」列一致。
核心逻辑:非激活或待确认 → 待补充;无进行中节点则按是否已付分为已完成/待补充;
进行中节点若已过到期日 → 逾期,若在今天起 7 天内 → 即将到期,否则进行中。
Args:
contract_status: 合同主状态。
parse_status: 解析状态。
nodes: 轻量节点 dict,含 status / due_date / anchor_date / paid_at。
today: 业务日。
Returns:
overdue / due / active / completed / needs_completion。
"""
node_list = list(nodes)
if str(contract_status or "").strip() != "active" or str(parse_status or "").strip() == "needs_review":
return LEDGER_FOCUS_NEEDS_COMPLETION
if not node_list:
return LEDGER_FOCUS_NEEDS_COMPLETION
active = [node for node in node_list if str(node.get("status") or "").strip().lower() == "active"]
if not active:
has_paid = any(
str(node.get("status") or "").strip().lower() == "paid" or bool(node.get("paid_at"))
for node in node_list
)
return "completed" if has_paid else LEDGER_FOCUS_NEEDS_COMPLETION
refs = [
ref
for node in active
if (ref := node_due_reference(node.get("due_date"), node.get("anchor_date")))
]
if any((ref - today).days < 0 for ref in refs):
return LEDGER_FOCUS_OVERDUE
if any(0 <= (ref - today).days <= _NEAR_DUE_DAYS for ref in refs):
return LEDGER_FOCUS_DUE
return "active"
def has_unpaid_due_this_month(nodes: Iterable[dict[str, Any]], today: date) -> bool:
"""
合同是否有未付节点的到期日落在本自然月。
核心逻辑:只看 status=active 的节点;月份按 today 所在自然月(含 today 所在月的逾期节点)。
Args:
nodes: 轻量节点 dict。
today: 业务日,用于确定自然月。
Returns:
存在本月未付到期节点时为 True。
"""
month_start = today.replace(day=1)
month_end = date(today.year + 1, 1, 1) if today.month == 12 else date(today.year, today.month + 1, 1)
for node in nodes:
if str(node.get("status") or "").strip().lower() != "active":
continue
ref = node_due_reference(node.get("due_date"), node.get("anchor_date"))
if ref and month_start <= ref < month_end:
return True
return False
def _node_payload(node: ContractPaymentNode) -> dict[str, Any]:
"""把 ORM 节点收成分类所需的轻量字段。"""
return {
"status": node.status,
"due_date": node.due_date,
"anchor_date": node.anchor_date,
"paid_at": (node.evidence_json or {}).get("paid_at"),
}
def collect_ledger_focus(*, session: Session, today: date | None = None) -> dict[str, set[int]]:
"""
扫描全部已解析台账合同,按汇总卡口径收集合同 ID。
核心逻辑:不应用页面 keyword;待确认合同不进入台账汇总。本月应付可与即将到期/逾期重叠。
Args:
session: 当前请求的 SQLAlchemy 会话。
today: 可选业务日。
Returns:
四个 focus 键到合同 ID 集合的映射。
"""
as_of = business_today(today=today)
contracts = (
session.query(ContractPaymentContract.id, ContractPaymentContract.status, ContractPaymentContract.parse_status)
.filter(ContractPaymentContract.parse_status == "parsed")
.all()
)
buckets: dict[str, set[int]] = {
LEDGER_FOCUS_DUE: set(),
LEDGER_FOCUS_OVERDUE: set(),
LEDGER_FOCUS_NEEDS_COMPLETION: set(),
LEDGER_FOCUS_DUE_THIS_MONTH: set(),
}
if not contracts:
return buckets
contract_ids = [row.id for row in contracts]
nodes_by_contract: dict[int, list[dict[str, Any]]] = defaultdict(list)
node_rows = (
session.query(ContractPaymentNode)
.filter(ContractPaymentNode.contract_id.in_(contract_ids))
.all()
)
for node in node_rows:
nodes_by_contract[node.contract_id].append(_node_payload(node))
for row in contracts:
nodes = nodes_by_contract.get(row.id, [])
status = classify_ledger_status(
contract_status=row.status,
parse_status=row.parse_status,
nodes=nodes,
today=as_of,
)
if status == LEDGER_FOCUS_DUE:
buckets[LEDGER_FOCUS_DUE].add(row.id)
elif status == LEDGER_FOCUS_OVERDUE:
buckets[LEDGER_FOCUS_OVERDUE].add(row.id)
elif status == LEDGER_FOCUS_NEEDS_COMPLETION:
buckets[LEDGER_FOCUS_NEEDS_COMPLETION].add(row.id)
if has_unpaid_due_this_month(nodes, as_of):
buckets[LEDGER_FOCUS_DUE_THIS_MONTH].add(row.id)
return buckets
def ledger_focus_counts(*, session: Session, today: date | None = None) -> dict[str, int]:
"""
返回四张汇总卡的合同份数。
Args:
session: 当前请求的 SQLAlchemy 会话。
today: 可选业务日。
Returns:
due / overdue / needs_completion / due_this_month 的计数。
"""
buckets = collect_ledger_focus(session=session, today=today)
return {key: len(ids) for key, ids in buckets.items()}
def apply_ledger_focus(query: Query, focus: str, *, session: Session, today: date | None = None) -> Query:
"""
按汇总卡口径把台账查询限制到对应合同 ID。
核心逻辑:空集合时强制无结果,避免 SQL IN () 退化成不过滤。
Args:
query: 已按解析状态/关键词过滤的合同查询。
focus: 四个合法口径之一。
session: 当前请求的 SQLAlchemy 会话。
today: 可选业务日。
Returns:
叠加 ID 过滤后的查询。
"""
ids = collect_ledger_focus(session=session, today=today).get(focus) or set()
if not ids:
return query.filter(false())
return query.filter(ContractPaymentContract.id.in_(ids))
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,414 @@
"""
backend/app/services/contract_payment/parse_service.py
用途:从 DOC/DOCX/PDF/TXT 抽取采购合同关键字段,并生成四个付款阶段的节点草稿。
依赖:标准库正则与日期处理;原文抽取由调用方传入,避免绑定某一种文件解析器。
逻辑:先识别固定字段和付款比例,再校验金额/比例/日期;无法确定的事实进入 needs_review,不猜测。
同一付款阶段的相同比例重复抽取不报重复;详情接口展示前对 issues 去重。
"""
from __future__ import annotations
from os import unlink
import re
import tempfile
from datetime import date, timedelta
from decimal import Decimal, InvalidOperation
from typing import Any
import requests
from flask import current_app
from app.services.procurement_contract.analyze import extract_text_from_bytes
_DATE_RE = re.compile(r"(20\d{2})[\s_]*[年./-][\s_]*(\d{1,2})[\s_]*[月./-][\s_]*(\d{1,2})[\s_]*日?")
_MONEY_RE = re.compile(r"(?:设备总价款\s*[((]?含税[))]?|人民币合同金额|合同金额|合同总价|含税总价)[::\s¥¥]*([\d,]+(?:\.\d+)?)", re.I)
_PERCENT_RE = re.compile(r"(预付款|定金|出货款|货款|验收款|质保款|保款|尾款)[^。;;\n]{0,140}?(\d+(?:\.\d+)?)\s*%", re.S)
_DELIVERY_RE = re.compile(r"(?:交货期限|约定到货日期|交付期限|交货期)[::\s]*[^。;;\n]{0,60}?(20\d{2}[^\n。;;]*)")
_WARRANTY_RE = re.compile(r"(?:质保期|保修期|保固期|质保款[^。;;\n]{0,100}?)(?:满后|为|:|:)?\s*(\d+)\s*(年|个月|月|天)")
_WARRANTY_PAYMENT_RE = re.compile(
r"(?:从验收(?:合格)?日起算\s*|质保款[^。;;\n]{0,100}?)(\d+)\s*(年|个月|月|天)\s*(?:质保期|保修期|保固期)?[^。;;\n]{0,24}?满后"
)
_CONTRACT_NO_RE = re.compile(r"(?:合同编号|合同号|Contract\s*No\.?)[::\s]*([A-Za-z0-9][A-Za-z0-9\-_/..]{3,63})", re.I)
_PAYMENT_NODE_LABELS = {
"prepayment": "预付款",
"shipment": "出货款",
"acceptance": "验收款",
"warranty": "质保款",
}
_PAYMENT_LABEL_TO_NODE_TYPE = {
"预付款": "prepayment", "定金": "prepayment",
"出货款": "shipment", "货款": "shipment",
"验收款": "acceptance",
"质保款": "warranty", "尾款": "warranty",
}
_PAYMENT_NODE_TYPES = tuple(_PAYMENT_NODE_LABELS)
def _parse_date(value: str | None) -> date | None:
"""
解析常见中文日期。
核心逻辑:只接受明确的年月日文本,避免将不完整期限猜测为业务日期。
Args:
value: 待解析的日期文本,可为空。
Returns:
合法日期;无法识别时返回 None。
"""
if not value:
return None
match = _DATE_RE.search(str(value))
if not match:
return None
try:
return date(int(match.group(1)), int(match.group(2)), int(match.group(3)))
except ValueError:
return None
def _parse_decimal(value: str | None) -> Decimal | None:
"""
解析金额或比例数字,忽略千分位逗号。
Args:
value: 金额或百分比中的数字文本。
Returns:
Decimal 数值;格式非法时返回 None。
"""
if value is None:
return None
try:
return Decimal(str(value).replace(",", "").strip())
except (InvalidOperation, ValueError):
return None
def _to_days(value: int, unit: str) -> int:
"""
将质保期限统一为自然日。
核心逻辑:按合同预警域现有约定,将年按 365 天、月按 30 天换算。
Args:
value: 期限数值,必须为非负整数。
unit: 年、月、个月或天。
Returns:
对应自然日数。
"""
if unit == "年":
return value * 365
if unit in {"月", "个月"}:
return value * 30
return value
def unique_parse_issues(issues: list[Any] | None) -> list[str]:
"""
按出现顺序去掉重复的解析问题文案。
核心逻辑:MinerU/OCR 常把付款表重复抽成多段,同一阶段会命中多次;页面只需要
每种原因一条,避免「出货款付款比例重复」连写六遍。空串和纯空白丢弃。
Args:
issues: 解析器或已落库 JSON 中的 issues 列表。
Returns:
去重后的问题文案;入参非法时返回空列表。
"""
if not isinstance(issues, list):
return []
seen: set[str] = set()
result: list[str] = []
for item in issues:
text = str(item or "").strip()
if not text or text in seen:
continue
seen.add(text)
result.append(text)
return result
def _extract_payment_percentages(body: str) -> tuple[dict[str, Decimal], list[str]]:
"""
提取四阶段付款比例,并校验阶段完整性及比例合计。
核心逻辑:同一语义阶段只允许一个比例。正文里同一比例被抽到多次(表格/页眉重复)
视为同一事实,不报重复;只有同一阶段出现不同比例才阻断。四阶段须完整且合计 100%。
Args:
body: 已抽取的合同正文。
Returns:
按付款节点归一化的比例,以及阻断自动预警的解析问题。
"""
found: dict[str, list[Decimal]] = {node_type: [] for node_type in _PAYMENT_NODE_TYPES}
issues: list[str] = []
for match in _PERCENT_RE.finditer(body):
label, raw = match.groups()
node_type = _PAYMENT_LABEL_TO_NODE_TYPE[label]
percentage = _parse_decimal(raw)
if percentage is None:
issues.append(f"{label}付款比例无法识别")
continue
found[node_type].append(percentage)
percentages: dict[str, Decimal] = {}
for node_type in _PAYMENT_NODE_TYPES:
values = found[node_type]
if not values:
continue
unique_values = list(dict.fromkeys(values))
if len(unique_values) > 1:
issues.append(f"{_PAYMENT_NODE_LABELS[node_type]}付款比例重复,需人工确认")
continue
percentages[node_type] = unique_values[0]
missing = [node_type for node_type in _PAYMENT_NODE_TYPES if node_type not in percentages]
if missing:
issues.append(f"付款阶段比例无法识别:{'、'.join(_PAYMENT_NODE_LABELS[item] for item in missing)}")
try:
matched = [(m.group(1), m.group(2)) for m in _PERCENT_RE.finditer(body)]
snippet = ""
for label in ("质保款", "验收款", "尾款"):
idx = body.find(label)
if idx >= 0:
snippet = body[max(0, idx - 40):idx + 80].replace("\n", "⏎")
break
current_app.logger.warning(
"合同付款预警:付款比例提取缺失 missing=%s matched=%s 片段=%r",
[_PAYMENT_NODE_LABELS[item] for item in missing], matched, snippet,
)
except Exception:
pass
elif sum(percentages.values(), Decimal("0")) != Decimal("100"):
issues.append("四阶段付款比例合计不等于100%")
return percentages, unique_parse_issues(issues)
def _log_delivery_extraction(body: str) -> None:
"""交货期限无法识别时输出正文片段与日期模式数,便于定位 MinerU/OCR 抽取差异。"""
from flask import current_app
snippet = ""
for token in ("交货期限", "约定到货", "交货期", "交付", "到货", "出货"):
idx = body.find(token)
if idx >= 0:
snippet = body[max(0, idx - 30):idx + 90].replace("\n", " ")
break
current_app.logger.warning(
"合同付款预警:交货期限未能识别;日期模式数=%s 正文片段=%r", len(_DATE_RE.findall(body)), snippet,
)
def _extract_mineru_text(filename: str, data: bytes) -> str:
"""
调用 MinerU 提取 PDF 的 Markdown 正文,作为合同付款条款的首选来源。
核心逻辑:将单份 PDF 上传至内网 MinerU `/file_parse`,只接受成功结果中非空的
`md_content`;Markdown 保留表格、标题与阅读顺序,便于后续规则识别付款比例。服务
未配置、超时或返回异常时返回空字符串,由调用方明确回退旧解析链路。
Args:
filename: 原始合同文件名,必须以 `.pdf` 结尾才会调用 MinerU。
data: 原始 PDF 字节,不允许为空。
Returns:
MinerU 返回的 Markdown 正文;未配置或解析失败时为空字符串。
"""
if not str(filename or "").lower().endswith(".pdf") or not data:
return ""
# 合同付款与采购合同审核解析同一类合同,固定复用审核域唯一的 MinerU 服务配置。
api_url = str(current_app.config.get("PROCUREMENT_CONTRACT_MINERU_API_URL") or "").strip().rstrip("/")
if not api_url:
return ""
connect_timeout = max(int(current_app.config.get("PROCUREMENT_CONTRACT_MINERU_CONNECT_TIMEOUT_SECONDS") or 5), 1)
read_timeout = max(int(current_app.config.get("PROCUREMENT_CONTRACT_MINERU_READ_TIMEOUT_SECONDS") or 300), 30)
backend = str(current_app.config.get("PROCUREMENT_CONTRACT_MINERU_BACKEND") or "pipeline").strip() or "pipeline"
parse_method = str(current_app.config.get("PROCUREMENT_CONTRACT_MINERU_PARSE_METHOD") or "auto").strip() or "auto"
try:
response = requests.post(
f"{api_url}/file_parse",
data={
"lang_list": "ch",
"backend": backend,
"parse_method": parse_method,
"formula_enable": "false",
},
files=[("files", (filename, data, "application/pdf"))],
timeout=(connect_timeout, read_timeout),
)
response.raise_for_status()
result = response.json()
except (ValueError, requests.RequestException):
return ""
if str(result.get("status") or "").lower() != "completed":
return ""
results = result.get("results")
if not isinstance(results, dict):
return ""
parsed = next((value for value in results.values() if isinstance(value, dict)), None)
return str((parsed or {}).get("md_content") or "").strip()
def _extract_ocr_text(filename: str, data: bytes) -> str:
"""
对扫描 PDF 执行 OCR 兜底。
核心逻辑:仅对 PDF 调用现有 OCR 能力;依赖不可用或解析失败时返回空文本,不伪造合同条款。
Args:
filename: 原始文件名,用于判断文件类型。
data: 原始文件字节。
Returns:
已识别的正文;无结果时为空字符串。
"""
if not str(filename or "").lower().endswith(".pdf"):
return ""
path = ""
try:
from edkb_system.contracts import Context
from edkb_system.skills import loader_pdf, ocr
with tempfile.NamedTemporaryFile(delete=False, suffix=".pdf") as handle:
handle.write(data)
path = handle.name
try:
context = Context(file_type="pdf")
blocks = loader_pdf.run({"file_path": path}, context)
if any(getattr(block, "type", "") == "image" for block in blocks):
blocks = ocr.run(blocks, context)
return "\n".join(
str(getattr(block, "text", "")).strip()
for block in blocks
if getattr(block, "type", "") in {"paragraph", "ocr_text"} and str(getattr(block, "text", "")).strip()
)
finally:
if path:
unlink(path)
except Exception:
return ""
def parse_contract_text(text: str, *, total_amount: Decimal | None = None, delivery_due_date: date | None = None) -> dict[str, Any]:
"""
解析合同正文并生成付款计划草稿。
AI 触发时机:合同附件保存后,需要自动获得付款节点时调用。
参数约束:text 为已抽取正文;不允许用模型猜测缺失日期或比例,结果必须可序列化为 JSON。
口径约定:合同正文是条款事实的权威来源;正文能抽取金额/交货期限时,即使与 OA 表单不同,
也以正文为准,不生成“与OA字段不一致”的待确认问题;仅当正文无法抽取时才回退 OA 表单值。
Returns:
包含 fields、nodes、status、issues、evidence 的结构化结果。
"""
body = str(text or "")
if body.startswith("[binary:"):
body = ""
issues: list[str] = []
# 合同正文是条款事实的权威来源;OA 字段只在正文未写明时作为补充。
# 正文能抽到金额/交货期限即以其为准,即使与 OA 表单不同也不再生成“不一致”待确认问题,
# 避免 OA 申请人录入错误把本可自动预警的合同永久卡在待复核。
amount_match = _MONEY_RE.search(body)
amount_from_contract = _parse_decimal(amount_match.group(1)) if amount_match else None
# OA 字段 total_amount 可能是字符串(如 _parse_amount 返回的 "221000.00"),统一归一为 Decimal,
# 否则下方 `amount * percentage` 会因字符串与 Decimal 相乘抛出 TypeError。
total_decimal = _parse_decimal(total_amount)
# 正文缺失时需回退 OA 交货期限;OA 字段可能以字符串到达(如 "2026-09-10"),
# 归一为 date 避免交付节点在 due_date.isoformat() 处因字符串抛错。
delivery_due_date = _parse_date(delivery_due_date)
amount = amount_from_contract if amount_from_contract is not None else total_decimal
delivery_match = _DELIVERY_RE.search(body)
delivery_from_contract = _parse_date(delivery_match.group(1)) if delivery_match else None
delivery = delivery_from_contract or delivery_due_date
if delivery is None:
# 合同常把日期写在“出货款/交货”句中,补充从付款条款附近抓取日期。
for match in _DATE_RE.finditer(body):
prefix = body[max(0, match.start() - 80):match.start()]
if any(token in prefix for token in ("交货", "交付", "到货", "出货")):
delivery = _parse_date(match.group(0))
break
warranty_days = None
# 付款条款中的期限优先于通用“保固”描述,确保质保款按应付款到期日预警。
warranty_match = _WARRANTY_PAYMENT_RE.search(body) or _WARRANTY_RE.search(body)
if warranty_match:
warranty_days = _to_days(int(warranty_match.group(1)), warranty_match.group(2))
contract_no_match = _CONTRACT_NO_RE.search(body)
contract_no = contract_no_match.group(1).strip(" 。;;,,") if contract_no_match else None
# [STEP 1] 一致性问题不再作为待确认阻断:正文为准,OA 仅在正文缺失时兜底。
# 资金与交货期限的取值已在上面以 amount / delivery 完成,此处只保留“无法识别”类问题。
if amount is None:
issues.append("合同金额无法识别")
if delivery is None:
issues.append("合同交货期限无法识别")
try:
_log_delivery_extraction(body)
except Exception:
pass
percentages, payment_issues = _extract_payment_percentages(body)
issues.extend(payment_issues)
issues = unique_parse_issues(issues)
nodes: list[dict[str, Any]] = []
for code, node_type in (("prepayment", "prepayment"), ("shipment", "shipment"), ("acceptance", "acceptance"), ("warranty", "warranty")):
percentage = percentages.get(node_type)
if percentage is None:
continue
node_amount = (amount * percentage / Decimal("100")).quantize(Decimal("0.01")) if amount is not None else None
# [STEP 1] 预付款和出货款是否已付款由 ERP apa_file 判定;合同只提供节点金额和出货款到期锚点。
anchor_type = (
"erp_payment"
if node_type in {"prepayment", "shipment"}
else "acceptance_archive"
)
due_date = delivery if node_type == "shipment" and delivery else None
nodes.append({
"node_code": code,
"node_type": node_type,
"amount": str(node_amount) if node_amount is not None else None,
"percentage": str(percentage),
"anchor_type": anchor_type,
"offset_days": 0,
"due_date": due_date.isoformat() if due_date else None,
"reminder_days": 0,
"evidence": {"matched_percent": str(percentage)},
})
if not nodes:
issues.append("未识别到预付款、出货款、验收款或质保款比例")
return {
"status": "needs_review" if issues else "parsed",
"fields": {
"contract_no": contract_no,
"total_amount": str(amount) if amount is not None else None,
"delivery_due_date": delivery.isoformat() if delivery else None,
"warranty_period_days": warranty_days,
},
"nodes": nodes,
"issues": issues,
"evidence": {
"parser": "contract-payment-four-stage-rules",
},
}
def parse_contract_bytes(filename: str, data: bytes, *, total_amount: Decimal | None = None, delivery_due_date: date | None = None) -> dict[str, Any]:
"""
从 DOC/DOCX/PDF 原文抽取文本后解析付款计划。
AI 触发时机:合同附件已资产化,需要直接从文件生成付款计划时调用。
核心逻辑:PDF 优先由 MinerU 提取 Markdown;服务不可用时再用统一附件解析器和旧 OCR
回退,最后委托文本解析器形成节点。
Args:
filename: 合同原始文件名,必须保留扩展名以供解析器选择路径。
data: 合同原始字节,不允许传入空字节伪造解析结果。
total_amount: OA 提供的合同总额,仅在正文未识别时作为补充。
delivery_due_date: OA 提供的约定到货日期,仅在正文未识别时作为补充。
Returns:
可 JSON 序列化的付款计划解析结果;不确定事实返回 needs_review。
"""
# [STEP 1] 扫描版 OA 合同没有可用文字层,MinerU 的版面 Markdown 优先于低精度 OCR。
mineru_text = _extract_mineru_text(filename, data)
extractor = "mineru" if mineru_text else "native_text"
text = mineru_text or extract_text_from_bytes(filename, data)
if text.startswith("[binary:"):
# [STEP 2] MinerU 不可用时保持旧 OCR 作为可用性兜底,不把附件同步整体判为失败。
ocr_text = _extract_ocr_text(filename, data)
if ocr_text.strip():
text = ocr_text
extractor = "legacy_ocr"
result = parse_contract_text(text, total_amount=total_amount, delivery_due_date=delivery_due_date)
result.setdefault("evidence", {})["document_extractor"] = extractor
current_app.logger.info(
"合同付款预警:合同正文抽取 extractor=%s mineru_len=%d text_len=%d",
extractor, len(mineru_text or ""), len(text or ""),
)
return result
@@ -0,0 +1,49 @@
"""合同付款预警默认排程种子:每日扫描与周五 18:00 汇总。"""
from __future__ import annotations
from datetime import datetime
from app import db
from app.models import ScheduleTask, User
from app.services.schedule.timezone_util import compute_next_run_at
_DEFAULTS = (
('SCH-CONTRACT-PAYMENT-SYNC', 'contract-payment-sync', '合同付款 OA 同步(日批)', '0 5 * * *'),
('SCH-CONTRACT-PAYMENT-ALERT-SCAN', 'contract-payment-alert-scan', '合同付款预警扫描(日批)', '0 6 * * *'),
('SCH-CONTRACT-PAYMENT-ALERT-WEEKLY', 'contract-payment-alert-weekly', '合同付款预警周汇总(周五 18:00)', '0 18 * * 5'),
)
def ensure_default_contract_payment_schedules(*, commit: bool = True):
"""幂等创建合同付款同步、每日扫描和周五汇总三个默认排程。
Args:
commit: 是否提交新建排程;测试或外层事务可传 False。
Returns:
新建的 ScheduleTask 列表;无用户时返回空列表。
"""
owner = db.session.query(User).filter(User.role == 'admin').order_by(User.id.asc()).first() or db.session.query(User).order_by(User.id.asc()).first()
if owner is None:
return []
created = []
for schedule_no, platform_path, name, cron in _DEFAULTS:
existing = db.session.query(ScheduleTask).filter((ScheduleTask.schedule_no == schedule_no) | (ScheduleTask.platform_api_path == platform_path)).first()
if existing:
continue
now = datetime.utcnow()
task = ScheduleTask(
schedule_no=schedule_no, name=name, schedule_type='platform_job', owner_user_id=owner.id,
cron_expr=cron, schedule_timezone='Asia/Shanghai', wait_seconds=0,
platform_api_path=platform_path, job_params={}, kb_sync_enabled=False,
notify_user_ids_json=[], notify_enabled=False, enabled=True,
next_run_at=compute_next_run_at(cron, timezone_name='Asia/Shanghai') or now,
created_by=owner.id, updated_by=owner.id, created_at=now, updated_at=now,
)
db.session.add(task); created.append(task)
if commit and created:
db.session.commit()
elif not commit:
db.session.flush()
return created
@@ -0,0 +1,316 @@
"""
backend/app/services/contract_payment/supervisor_oa_service.py
用途:从 OA ecology SQL Server 解析合同申请人的第二、三轮上级主管(企微收件人)。
依赖:OASQLServerService(复用 OA_SQLSERVER_* 只读连接)、Flask current_app。
逻辑:HrmResource.lastname = 申请人姓名 → departmentid;
Matrixtable_3.bm = departmentid,zz 为第二轮、jfl 为第三轮。
zz/jfl 即 HrmResource.id,也是企业微信 userid。查询失败 fail-safe 返回空,不向第一轮兜底。
"""
from __future__ import annotations
import re
from dataclasses import dataclass
from typing import Any
from flask import current_app
from app.services.oa_sqlserver import OASQLServerService
# [STEP] 仅允许字母数字下划线作为 SQL 标识符,表名/字段来自配置,禁止拼接任意字符串。
_SAFE_IDENT = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*$")
_DEFAULT_HRM_TABLE = "HrmResource"
_DEFAULT_HRM_NAME_FIELD = "lastname"
_DEFAULT_HRM_DEPT_FIELD = "departmentid"
_DEFAULT_MATRIX_TABLE = "Matrixtable_3"
_DEFAULT_MATRIX_DEPT_FIELD = "bm"
_DEFAULT_MATRIX_ROUND2_FIELD = "zz"
_DEFAULT_MATRIX_ROUND3_FIELD = "jfl"
@dataclass(frozen=True)
class SupervisorMatrix:
"""一份合同申请人在 OA 矩阵中解析出的第二、三轮主管。"""
applicant_oa_id: int | None
department_id: int | None
round2_oa_id: int | None
round3_oa_id: int | None
round2_name: str | None
round3_name: str | None
ok: bool
class SupervisorMatrixCache:
"""同一扫描内按申请人姓名缓存 OA 矩阵,避免每个付款节点重复打 SQL。"""
def __init__(self) -> None:
self._store: dict[str, SupervisorMatrix | None] = {}
def get(self, applicant_name: str | None) -> SupervisorMatrix | None:
"""
返回该申请人的上级矩阵;姓名为空时不查 OA。
核心逻辑:去空白后的姓名作缓存键;首次调用才访问 ecology。
Args:
applicant_name: 台账申请人姓名,对应 HrmResource.lastname。
Returns:
解析结果;查询失败或无法唯一确定时为 None。
"""
key = str(applicant_name or "").strip()
if not key:
return None
if key not in self._store:
self._store[key] = fetch_supervisor_matrix(key)
return self._store[key]
def fetch_supervisor_matrix(applicant_name: str) -> SupervisorMatrix | None:
"""
按申请人姓名查询 OA 部门矩阵,得到第二、三轮主管的 OA/企微 ID。
AI 触发时机:合同付款每日扫描解析第二、三轮收件人时调用。
核心逻辑:lastname 必须唯一命中一名 HrmResource;再用 departmentid 唯一命中
Matrixtable_3.bm。重名、无部门、无矩阵行或查询失败时返回 None,禁止猜测。
Args:
applicant_name: 合同台账申请人,须与 OA lastname 一致。
Returns:
SupervisorMatrix;无法确定时 None。
"""
name = str(applicant_name or "").strip()
if not name:
return None
hrm_table = _configured_ident("CONTRACT_PAYMENT_OA_HRM_TABLE", _DEFAULT_HRM_TABLE)
name_field = _configured_ident("CONTRACT_PAYMENT_OA_HRM_NAME_FIELD", _DEFAULT_HRM_NAME_FIELD)
dept_field = _configured_ident("CONTRACT_PAYMENT_OA_HRM_DEPT_FIELD", _DEFAULT_HRM_DEPT_FIELD)
matrix_table = _configured_ident("CONTRACT_PAYMENT_OA_MATRIX_TABLE", _DEFAULT_MATRIX_TABLE)
matrix_dept_field = _configured_ident(
"CONTRACT_PAYMENT_OA_MATRIX_DEPT_FIELD", _DEFAULT_MATRIX_DEPT_FIELD
)
round2_field = _configured_ident(
"CONTRACT_PAYMENT_OA_MATRIX_ROUND2_FIELD", _DEFAULT_MATRIX_ROUND2_FIELD
)
round3_field = _configured_ident(
"CONTRACT_PAYMENT_OA_MATRIX_ROUND3_FIELD", _DEFAULT_MATRIX_ROUND3_FIELD
)
connection = None
try:
connection = OASQLServerService._connect()
cursor = connection.cursor()
# [STEP 1] 按姓名唯一确定申请人及其部门;精确匹配为空时再按包装串模糊匹配
hrm_sql, hrm_params = build_hrm_lookup_sql(
table=hrm_table, name_field=name_field, dept_field=dept_field, applicant_name=name
)
cursor.execute(hrm_sql, hrm_params)
hrm_rows = list(cursor.fetchall() or [])
people = _unique_hrm_rows(hrm_rows, name)
if people is None and not hrm_rows:
like_sql, like_params = build_hrm_lookup_sql(
table=hrm_table,
name_field=name_field,
dept_field=dept_field,
applicant_name=name,
fuzzy=True,
)
cursor.execute(like_sql, like_params)
people = _unique_hrm_rows(cursor.fetchall(), name)
if people is None:
current_app.logger.warning(
"contract_payment supervisor skipped: applicant lastname not unique or missing name=%s",
name,
)
return None
applicant_oa_id, department_id = people
# [STEP 2] 部门 ID 关联矩阵表,读取第二轮 zz、第三轮 jfl
matrix_sql, matrix_params = build_matrix_lookup_sql(
table=matrix_table,
dept_field=matrix_dept_field,
round2_field=round2_field,
round3_field=round3_field,
department_id=department_id,
)
cursor.execute(matrix_sql, matrix_params)
matrix_rows = cursor.fetchall() or []
if len(matrix_rows) != 1:
current_app.logger.warning(
"contract_payment supervisor skipped: matrix rows=%s department_id=%s applicant=%s",
len(matrix_rows),
department_id,
name,
)
return None
round2_oa_id = _as_positive_int(_row_value(matrix_rows[0], 1))
round3_oa_id = _as_positive_int(_row_value(matrix_rows[0], 2))
round2_name = _lookup_resource_name(cursor, hrm_table, name_field, round2_oa_id)
round3_name = _lookup_resource_name(cursor, hrm_table, name_field, round3_oa_id)
return SupervisorMatrix(
applicant_oa_id=applicant_oa_id,
department_id=department_id,
round2_oa_id=round2_oa_id,
round3_oa_id=round3_oa_id,
round2_name=round2_name,
round3_name=round3_name,
ok=True,
)
except Exception:
current_app.logger.exception(
"contract_payment supervisor OA lookup failed applicant=%s", name
)
return None
finally:
if connection is not None:
try:
connection.close()
except Exception:
pass
def build_hrm_lookup_sql(
*,
table: str,
name_field: str,
dept_field: str,
applicant_name: str,
fuzzy: bool = False,
) -> tuple[str, list[Any]]:
"""
构造按姓名查询 HrmResource 的 SQL。
核心逻辑:默认去空白后精确匹配 lastname;fuzzy=True 时用 LIKE 兼容 OA 多语言包装串。
Args:
table: 人员表名,默认 HrmResource。
name_field: 姓名列,默认 lastname。
dept_field: 部门列,默认 departmentid。
applicant_name: 绑定为查询参数。
fuzzy: 为 True 时改为包含匹配,结果仍须在 Python 侧按规范化姓名唯一命中。
Returns:
(sql, params)。
"""
column = f"r.{_bracket_ident(name_field)}"
predicate = f"{column} LIKE ?" if fuzzy else f"LTRIM(RTRIM({column})) = ?"
sql = (
f"SELECT r.{_bracket_ident('id')}, {column}, "
f"r.{_bracket_ident(dept_field)} "
f"FROM {_bracket_ident(table)} r "
f"WHERE {predicate}"
)
return sql, [f"%{applicant_name}%"] if fuzzy else [applicant_name]
def build_matrix_lookup_sql(
*,
table: str,
dept_field: str,
round2_field: str,
round3_field: str,
department_id: int,
) -> tuple[str, list[Any]]:
"""
构造按部门查询 Matrixtable_3 的 SQL。
核心逻辑:bm = HrmResource.departmentid;zz 第二轮、jfl 第三轮。
Args:
table: 矩阵表名。
dept_field: 部门列,默认 bm。
round2_field: 第二轮主管列,默认 zz。
round3_field: 第三轮主管列,默认 jfl。
department_id: 申请人部门 ID。
Returns:
(sql, params)。
"""
sql = (
f"SELECT m.{_bracket_ident(dept_field)}, m.{_bracket_ident(round2_field)}, "
f"m.{_bracket_ident(round3_field)} "
f"FROM {_bracket_ident(table)} m "
f"WHERE m.{_bracket_ident(dept_field)} = ?"
)
return sql, [department_id]
def _lookup_resource_name(cursor: Any, table: str, name_field: str, oa_id: int | None) -> str | None:
"""按 HrmResource.id 取 lastname,供系统用户真实姓名回退匹配。"""
if oa_id is None:
return None
sql = (
f"SELECT TOP 1 r.{_bracket_ident(name_field)} "
f"FROM {_bracket_ident(table)} r "
f"WHERE r.{_bracket_ident('id')} = ?"
)
cursor.execute(sql, [oa_id])
row = cursor.fetchone()
if not row:
return None
return OASQLServerService._normalize_oa_text(_row_value(row, 0)) or None
def _unique_hrm_rows(rows: list[Any], applicant_name: str) -> tuple[int, int] | None:
"""姓名命中且仅一人、且部门 ID 有效时返回 (oa_id, department_id)。"""
matched: list[tuple[int, int]] = []
seen_ids: set[int] = set()
for row in rows or []:
lastname = OASQLServerService._normalize_oa_text(_row_value(row, 1))
if lastname != applicant_name:
continue
oa_id = _as_positive_int(_row_value(row, 0))
department_id = _as_positive_int(_row_value(row, 2))
if oa_id is None or department_id is None or oa_id in seen_ids:
continue
seen_ids.add(oa_id)
matched.append((oa_id, department_id))
if len(matched) != 1:
return None
return matched[0]
def _as_positive_int(value: Any) -> int | None:
"""将 OA 数字字段转为正整数;多值逗号串无法唯一确定时返回 None。"""
if value is None or isinstance(value, bool):
return None
if isinstance(value, int):
return value if value > 0 else None
try:
number = int(value)
return number if number > 0 else None
except (TypeError, ValueError):
pass
text = str(value).strip()
if not text:
return None
if re.fullmatch(r"\d+", text):
number = int(text)
return number if number > 0 else None
if re.fullmatch(r"\d{1,3}(,\d{3})+", text):
number = int(text.replace(",", ""))
return number if number > 0 else None
return None
def _configured_ident(config_key: str, default: str) -> str:
"""读取 Flask 配置中的 SQL 标识符,非法时回退默认值。"""
raw = str(current_app.config.get(config_key) or default).strip() or default
if not _SAFE_IDENT.match(raw):
current_app.logger.error(
"合同付款预警:非法 SQL 标识符 %s=%r,回退 %s", config_key, raw, default
)
return default
return raw
def _bracket_ident(name: str) -> str:
"""校验并返回 [ident] 形式的 SQL Server 标识符。"""
if not _SAFE_IDENT.match(name):
raise ValueError(f"非法 SQL 标识符: {name!r}")
return f"[{name}]"
def _row_value(row: Any, index: int) -> Any:
"""按位置取值,兼容 tuple 与 pyodbc.Row。"""
try:
return row[index]
except (IndexError, TypeError, KeyError):
return None
File diff suppressed because it is too large. Load diff
+64 -31
View File
@@ -551,6 +551,25 @@ class DifyService:
out["_workflow_error_type"] = error_type
return out
@staticmethod
def _observe_workflow_event(event_observer, event_type: str, event_data: dict[str, Any], state: dict[str, Any]) -> None:
"""向可选观察器发送脱敏 Workflow 生命周期字段;观察器错误不得中断Provider调用。"""
if event_observer is None:
return
node_data = event_data.get('node_data') if isinstance(event_data.get('node_data'), dict) else {}
try:
event_observer({
'event_type': str(event_type),
'workflow_run_id': event_data.get('workflow_run_id') or state.get('workflow_run_id'),
'node_execution_id': event_data.get('node_execution_id') or event_data.get('node_id'),
'node_type': event_data.get('node_type') or node_data.get('type'),
'node_title': event_data.get('title') or node_data.get('title'),
'event_status': event_data.get('status'),
})
except Exception:
if current_app:
current_app.logger.exception('[workflow-streaming] event observer failed')
@staticmethod
def _consume_workflow_stream(
*,
@@ -559,6 +578,7 @@ class DifyService:
payload: dict[str, Any],
timeout: tuple[int, int],
state: dict[str, Any],
event_observer=None,
) -> dict[str, Any]:
"""
执行一次 Workflow streaming POST 并消费 SSE 直至 workflow_finished。
@@ -590,6 +610,8 @@ class DifyService:
continue
event_type = evt.get("event", "")
event_data = evt.get('data') if isinstance(evt.get('data'), dict) else {}
DifyService._observe_workflow_event(event_observer, str(event_type), event_data, state)
if event_type == "workflow_started":
run_id = (evt.get("data") or {}).get("workflow_run_id")
@@ -628,6 +650,7 @@ class DifyService:
inputs: dict[str, Any] | None = None,
user: str = "system",
timeout: tuple[int, int] = (5, 300),
event_observer=None,
) -> dict[str, Any]:
"""
调用 Dify Workflow(streaming),并在断连/超时时优先 poll 补偿结果。
@@ -671,6 +694,7 @@ class DifyService:
payload=payload,
timeout=timeout,
state=stream_state,
event_observer=event_observer,
)
workflow_run_id = stream_state.get("workflow_run_id")
if workflow_run_id:
@@ -679,6 +703,9 @@ class DifyService:
# [STEP] 连接正常结束但未收到 workflow_finished 时,用 poll 补偿最终结果
if not result and workflow_run_id:
poll_used = True
DifyService._observe_workflow_event(
event_observer, 'poll_started', {'workflow_run_id': workflow_run_id}, stream_state,
)
if current_app:
current_app.logger.warning(
"[workflow-streaming] stream closed without finished event, polling run_id=%s",
@@ -689,6 +716,10 @@ class DifyService:
workflow_run_id=workflow_run_id,
max_wait=max_wait,
)
DifyService._observe_workflow_event(
event_observer, 'recovered' if result else 'stream_interrupted',
{'workflow_run_id': workflow_run_id, 'status': result.get('status') if result else 'timeout'}, stream_state,
)
poll_error_type = None if result else "poll_timeout"
return DifyService._attach_workflow_reliability_meta(
result,
@@ -745,6 +776,9 @@ class DifyService:
if workflow_run_id:
poll_used = True
DifyService._observe_workflow_event(
event_observer, 'stream_interrupted', {'workflow_run_id': workflow_run_id}, stream_state,
)
if current_app:
current_app.logger.warning(
"[workflow-streaming] polling after disconnect run_id=%s error_type=%s",
@@ -756,6 +790,10 @@ class DifyService:
workflow_run_id=workflow_run_id,
max_wait=max_wait,
)
DifyService._observe_workflow_event(
event_observer, 'recovered' if result else 'stream_interrupted',
{'workflow_run_id': workflow_run_id, 'status': result.get('status') if result else 'timeout'}, stream_state,
)
poll_error_type = None if result else "poll_timeout"
return DifyService._attach_workflow_reliability_meta(
result,
@@ -767,6 +805,9 @@ class DifyService:
if retryable and attempt < max_attempts - 1:
retry_count += 1
DifyService._observe_workflow_event(
event_observer, 'retry_started', {'workflow_run_id': workflow_run_id}, stream_state,
)
if current_app:
current_app.logger.info(
"[workflow-streaming] retrying attempt=%s error_type=%s",
@@ -894,7 +935,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}',
@@ -1177,43 +1218,35 @@ 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)
continue
if isinstance(e, requests.exceptions.ReadTimeout):
message = (
f"Dify 在 {int(getattr(Config, 'DIFY_CHAT_READ_TIMEOUT_SECONDS', 30) or 30)} 秒内没有返回响应。"
"请检查 Dify 应用地址/API Key、Chatflow 是否发布,以及 Dify 服务是否能正常执行。"
)
elif isinstance(e, requests.exceptions.ConnectTimeout):
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"
message = DifyService._friendly_stream_request_failure_message(e)
# [STEP 4] 错误事件与持久化对象必须是同一个 dict,确保 chat_log_id 能继续传给 relay/领域 Handler。
error_event = {
'event': 'error',
'conversation_id': normalized_conversation_id,
'answer': message,
'message': message,
'metadata': {},
}
persist_stream_chat(error_event, 'error')
yield f"data: {json.dumps(error_event, ensure_ascii=False)}\n\n"
@staticmethod
def run_chatflow_once(
+2 -2
View File
@@ -3,7 +3,7 @@ backend/app/services/faq_cache.py
用途:全局常用问题 FAQ 缓存匹配与 SSE 直答,避免重复调用 Dify。
依赖:models.QuickQuestion、ChatLog、SQLAlchemy db。
逻辑:chat.py 在调用 DifyService 前委托本模块 try_match;命中则 stream_chat 返回预置答案。
逻辑:chat.py 在调用 DifyService 前委托本模块 try_match(只看 cache_enabled,不看首页展示 is_enabled);命中则 stream_chat 返回预置答案。
"""
import json
import time
@@ -66,6 +66,7 @@ class FaqCacheService:
"""
尝试为指定 Agent 命中全局 FAQ 缓存条目。
核心逻辑:加载 cache_enabled 的全局条目,对 question/title/aliases 做归一化精确匹配。
is_enabled 只控制工作台首页是否展示快捷入口,不影响本方法是否直答。
@param query - 用户提问
@param agent_id - 当前 Agent 主键
@returns 命中的 QuickQuestion;未命中返回 None
@@ -80,7 +81,6 @@ class FaqCacheService:
QuickQuestion.user_id.is_(None),
QuickQuestion.agent_id == agent_id,
QuickQuestion.cache_enabled.is_(True),
QuickQuestion.is_enabled.is_(True),
QuickQuestion.answer.isnot(None),
QuickQuestion.answer != "",
QuickQuestion.stale_at.is_(None),
+9 -9
View File
@@ -2,7 +2,7 @@
backend/app/services/file_assets/cleanup.py
用途:过期未引用 FileAsset 与关联 intake 的清理编排。
依赖:file_assets.storage、models.FileAsset/ShippingNoticeIntake。
依赖:file_assets.storage、models.FileAsset/ShippingOrderIntake。
逻辑:由排程或 file_asset_cleanup Job 调用;先标记 expired → 删 MinIO → 成功后 mark deleted;
MinIO 删除失败不伪装成功,保留记录供下次重试。
"""
@@ -15,7 +15,7 @@ from datetime import datetime
from sqlalchemy import or_
from app import db
from app.models import FileAsset, ShippingNoticeIntake
from app.models import FileAsset, ShippingOrderIntake
from app.services.file_assets.storage import file_asset_storage
_LOGGER = logging.getLogger(__name__)
@@ -49,10 +49,10 @@ def cleanup_expired_temporary_assets(*, limit: int = 100) -> dict[str, int]:
stats = {'scanned': len(assets), 'expired': 0, 'deleted': 0, 'errors': 0}
for asset in assets:
consumed = (
db.session.query(ShippingNoticeIntake.id)
db.session.query(ShippingOrderIntake.id)
.filter(
ShippingNoticeIntake.asset_id == asset.id,
ShippingNoticeIntake.parse_status == 'consumed',
ShippingOrderIntake.asset_id == asset.id,
ShippingOrderIntake.parse_status == 'consumed',
)
.first()
)
@@ -61,11 +61,11 @@ def cleanup_expired_temporary_assets(*, limit: int = 100) -> dict[str, int]:
stats['expired'] += 1
asset.lifecycle_status = 'expired'
(
db.session.query(ShippingNoticeIntake)
db.session.query(ShippingOrderIntake)
.filter(
ShippingNoticeIntake.asset_id == asset.id,
ShippingNoticeIntake.consumed_at.is_(None),
ShippingNoticeIntake.parse_status.notin_(('consumed', 'cancelled')),
ShippingOrderIntake.asset_id == asset.id,
ShippingOrderIntake.consumed_at.is_(None),
ShippingOrderIntake.parse_status.notin_(('consumed', 'cancelled')),
)
.update({'parse_status': 'expired', 'updated_at': now}, synchronize_session=False)
)
@@ -151,6 +151,10 @@ def register_file_asset_cleanup_schedule_hooks() -> None:
try:
with Session(bind) as seed_session:
ensure_default_file_asset_cleanup_schedule(commit=True, session=seed_session)
from app.services.shipping_notice.order_extraction_progress_cleanup_schedule import (
ensure_default_order_extraction_progress_cleanup_schedule,
)
ensure_default_order_extraction_progress_cleanup_schedule(commit=True, session=seed_session)
except Exception as exc: # pragma: no cover - 防御不阻断建用户
_LOGGER.warning("ensure file-asset-cleanup after user create failed: %s", exc)
+5 -4
View File
@@ -381,11 +381,12 @@ def create_derived_file_asset_from_bytes(
expires_at=expires_at,
)
# [STEP] SAVEPOINT:唯一约束冲突时只回滚本插入,保留外层 Document 事务
# [STEP] 幂等插入派生资产:先查后建规避常见唯一约束冲突;冲突时回读已有行。
# 不使用 begin_nested SAVEPOINT:被 SAVEPOINT 语义包住的 INSERT 在同一 Session
# 内创建多个派生资产时,其行对后续 autoflush 的 UPDATE 不可见,会触发 StaleDataError。
try:
with db.session.begin_nested():
db.session.add(asset)
db.session.flush()
db.session.add(asset)
db.session.flush()
except IntegrityError:
raced = _find_derived_by_parent_hash(parent_id=int(parent.id), content_hash=content_hash)
if raced is not None:
@@ -16,7 +16,7 @@ from app.models import KbGroup, ScheduleTask
from app.services.knowledge_cleaning.dify_sync_service import KbDifySyncError, KbDifySyncService
DEFAULT_TOP_K = 5
MAX_TOP_K = 20
MAX_TOP_K = 10
MIN_TOP_K = 1
DEFAULT_SCORE_THRESHOLD = 0.3
@@ -178,7 +178,7 @@ def search_file_check_history(
Args:
task_id: ScheduleTask.id(Agent 绑定的 schedule_task_id)。
query: 用户自然语言检索问题。
top_k: 返回片段数,默认 5,最大 20。
top_k: 返回片段数,默认 5,最大 10。
score_threshold: 相似度阈值,默认 0.3。
Returns:
@@ -84,7 +84,7 @@
},
"responses": {
"200": {
"description": "启动成功;或已有 文件检核进行中,返回 ok=false/error_code=check_running",
"description": "启动成功;已有检核进行中或预检无资料时返回 ok=false。预检无资料仍返回已完成的 0 笔 run,供前端展示 100% 进度。",
"content": {
"application/json": {
"schema": {
@@ -94,6 +94,9 @@
},
{
"$ref": "#/components/schemas/CheckRunningResponse"
},
{
"$ref": "#/components/schemas/NoDataResponse"
}
]
}
@@ -220,6 +223,33 @@
"type": "integer",
"example": 12
}
},
{
"name": "hxops_turn_id",
"in": "query",
"required": false,
"schema": {
"type": "string"
},
"description": "当前 HXOPS 对话轮次 ID;传入后将最近批次绑定到该轮进度卡"
},
{
"name": "conversation_id",
"in": "query",
"required": false,
"schema": {
"type": "string"
},
"description": "当前 Dify 会话 ID,仅用于关联当前查询轮次"
},
{
"name": "user_message",
"in": "query",
"required": false,
"schema": {
"type": "string"
},
"description": "当前用户问题,仅用于关联当前查询轮次"
}
],
"responses": {
@@ -642,6 +672,36 @@
}
}
},
"NoDataResponse": {
"type": "object",
"required": [
"ok",
"error_code",
"message",
"run",
"task"
],
"properties": {
"ok": {
"type": "boolean",
"example": false
},
"error_code": {
"type": "string",
"example": "no_data_to_check"
},
"message": {
"type": "string",
"example": "目前没有资料需要检核"
},
"run": {
"$ref": "#/components/schemas/RunDetail"
},
"task": {
"$ref": "#/components/schemas/TaskSummary"
}
}
},
"GetRunResponse": {
"type": "object",
"required": [
@@ -702,7 +762,7 @@
"top_k": {
"type": "integer",
"minimum": 1,
"maximum": 20,
"maximum": 10,
"default": 5,
"description": "返回片段数,默认 5"
},
@@ -0,0 +1,8 @@
"""backend/app/services/in_transit_transfer/__init__.py
用途:在途仓自动调拨 Agent 一期独立领域模块入口。
依赖:同包 date_policy / status / quantity / strategy / contracts / audit;
Phase 1 起扩展 file_preparation / precheck_service 等。
逻辑:本包只承载调拨领域规则与确定性门禁,不混入 shipping_notice 订单解析;
对外部系统(RPA/ERP/企微)的访问通过本包隔离的 adapter 与 job/worker 完成。
"""
@@ -0,0 +1,168 @@
"""在途调拨 MinIO 归档与 Hash 校验。
用途:将大型快照/报文/Excel 归档到对象存储(MinIO),索引与 Hash 留库;
归档必须重新计算 Hash 并写审计事件(决策/规格 §11.3)。
依赖:typing.Protocol 对象存储协议、models.TransferArchive、audit。
逻辑:默认实现 MinioObjectStore 直连 MinIO(配置来自环境);测试注入 Fake。
凭据只来自环境/配置,绝不写入归档内容或索引。
"""
from __future__ import annotations
import hashlib
import io
import uuid
from datetime import datetime
from typing import Any, Protocol
from app import db
from app.core.errors import AppError
from app.models import TransferArchive
from app.services.in_transit_transfer.audit import build_transfer_audit_event
ARCHIVE_STORAGE_PROVIDER = "minio"
DEFAULT_ARCHIVE_BUCKET = "hxops-transfer"
class ObjectStore(Protocol):
"""对象存储协议(MinIO 或测试替身)。"""
def put_bytes(self, *, bucket: str, key: str, data: bytes, content_type: str) -> str:
"""写入对象,返回对象键。"""
def get_bytes(self, *, bucket: str, key: str) -> bytes:
"""读取对象字节。"""
def delete_object(self, *, bucket: str, key: str) -> None:
"""删除对象。"""
class MinioObjectStore:
"""默认 MinIO 对象存储;凭据仅来自 Flask config / 环境变量。"""
def __init__(self, bucket: str = DEFAULT_ARCHIVE_BUCKET) -> None:
from flask import current_app
self.bucket = str(current_app.config.get("IN_TRANSIT_TRANSFER_ARCHIVE_BUCKET") or bucket)
endpoint = str(current_app.config.get("MINIO_ENDPOINT") or "").strip()
access_key = str(current_app.config.get("MINIO_ACCESS_KEY") or "").strip()
secret_key = str(current_app.config.get("MINIO_SECRET_KEY") or "").strip()
secure = bool(current_app.config.get("MINIO_SECURE", False))
if not endpoint:
raise AppError(
code="TRANSFER.ARCHIVE_NOT_CONFIGURED",
message="MinIO endpoint not configured",
http_status=503,
)
from minio import Minio
self.client = Minio(endpoint, access_key=access_key, secret_key=secret_key, secure=secure)
def _ensure_bucket(self) -> None:
"""确保 bucket 存在(幂等)。"""
if not self.client.bucket_exists(self.bucket):
self.client.make_bucket(self.bucket)
def put_bytes(self, *, bucket: str, key: str, data: bytes, content_type: str) -> str:
"""写入对象并返回键。"""
self._ensure_bucket()
self.client.put_object(
bucket_name=bucket or self.bucket,
object_name=key,
data=io.BytesIO(data),
length=len(data),
content_type=content_type,
)
return key
def get_bytes(self, *, bucket: str, key: str) -> bytes:
"""读取对象字节。"""
response = self.client.get_object(bucket_name=bucket or self.bucket, object_name=key)
try:
return response.read()
finally:
response.close()
response.release_conn()
def delete_object(self, *, bucket: str, key: str) -> None:
"""删除对象。"""
self.client.remove_object(bucket_name=bucket or self.bucket, object_name=key)
def _safe_filename(name: str) -> str:
"""清洗文件名片段。"""
return "".join(char for char in str(name or "archive") if char.isalnum() or char in {"-", "_", "."}) or "archive"
def archive_snapshot(
*,
object_type: str,
object_id: str,
data: bytes,
original_filename: str,
content_type: str,
object_store: ObjectStore,
bucket: str = DEFAULT_ARCHIVE_BUCKET,
request_id: str | None = None,
) -> TransferArchive:
"""归档一份对象并持久化索引 + 审计。
Args:
object_type: 对象类型(erp_inventory_snapshot / exception_excel / receipt_file)。
object_id: 业务对象编号(precheck_no / run_no)。
data: 待归档字节。
original_filename: 原始文件名。
content_type: MIME。
object_store: 对象存储替身。
bucket: 目标 bucket。
Returns:
TransferArchive 索引记录。
"""
digest = hashlib.sha256(data).hexdigest()
key = (
f"{object_type}/{object_id}/{datetime.utcnow():%Y%m%d}/"
f"{uuid.uuid4().hex[:8]}-{_safe_filename(original_filename)}"
)
object_store.put_bytes(bucket=bucket, key=key, data=data, content_type=content_type)
archive = TransferArchive(
archive_no=f"ARC-{datetime.utcnow():%Y%m%d}-{uuid.uuid4().hex[:6].upper()}",
object_type=object_type,
object_id=object_id,
storage_provider=ARCHIVE_STORAGE_PROVIDER,
storage_bucket=bucket,
storage_key=key,
original_filename=original_filename,
content_type=content_type,
file_size=len(data),
sha256=digest,
)
db.session.add(archive)
db.session.add(build_transfer_audit_event(
event_type="TRANSFER_ARCHIVED",
aggregate_type=object_type,
aggregate_id=object_id,
actor_type="worker",
request_id=request_id,
result="success",
after={"storage_key": key, "sha256": digest, "file_size": len(data)},
))
db.session.commit()
return archive
def verify_archive_hash(archive: TransferArchive, *, object_store: ObjectStore) -> bool:
"""复核归档 Hash(下载对象重新计算)。
Args:
archive: TransferArchive 索引。
object_store: 对象存储替身。
Returns:
True 一致;False 损坏/篡改。
"""
data = object_store.get_bytes(bucket=archive.storage_bucket, key=archive.storage_key)
return hashlib.sha256(data).hexdigest() == archive.sha256
def restore_archive_bytes(archive: TransferArchive, *, object_store: ObjectStore) -> bytes:
"""恢复归档对象字节。"""
return object_store.get_bytes(bucket=archive.storage_bucket, key=archive.storage_key)
@@ -0,0 +1,182 @@
"""在途调拨审计服务。
用途:构建只追加审计事件(TransferAuditEvent),对快照脱敏并计算
before/after Hash 与事件 Hash,保证 Phase 4 Hash 校验可复算。
依赖:app.models.TransferAuditEvent、标准库 hashlib/json。
逻辑:所有快照先 sanitize(剔除密码/Token/密钥),再参与 Hash;
event_hash 由事件自身稳定字段复算,不依赖对象内部状态。
"""
from __future__ import annotations
from datetime import datetime
from typing import Any, Mapping
import hashlib
import json
from app.models import TransferAuditEvent
# 敏感字段片段:命中即从审计快照中剔除(Secret 永不进入审计/Hash/日志)。
AUDIT_FORBIDDEN_KEY_FRAGMENTS = (
"password", "secret", "token", "ciphertext", "credential",
"api_key", "apikey", "webhook", "authorization", "auth",
)
def is_forbidden_audit_key(key: str) -> bool:
"""判断键名是否命中敏感片段(大小写不敏感)。"""
lowered = str(key or "").lower()
return any(fragment in lowered for fragment in AUDIT_FORBIDDEN_KEY_FRAGMENTS)
def sanitize_snapshot(value: Any) -> Any:
"""递归剔除敏感键,返回可安全持久化的快照副本。
Args:
value: 原始快照(dict/list/标量)。
Returns:
脱敏后的副本。
"""
if isinstance(value, dict):
return {
str(key): sanitize_snapshot(item)
for key, item in value.items()
if not is_forbidden_audit_key(str(key))
}
if isinstance(value, (list, tuple)):
return [sanitize_snapshot(item) for item in value]
return value
def canonical_hash(value: Any) -> str:
"""对脱敏快照计算 SHA-256(键排序 + 紧凑 JSON)。
Args:
value: 任意 JSON 可序列化值。
Returns:
64 位十六进制 Hash。
"""
payload = json.dumps(
sanitize_snapshot(value),
ensure_ascii=True, sort_keys=True, separators=(",", ":"), default=str,
)
return hashlib.sha256(payload.encode("ascii")).hexdigest()
def snapshot_diff(before: Mapping[str, Any], after: Mapping[str, Any]) -> dict[str, Any]:
"""计算前后快照顶层差异。
Args:
before: 变更前快照。
after: 变更后快照。
Returns:
{"added": {...}, "removed": {...}, "changed": {key: (before, after)}}。
"""
before_keys = set(before)
after_keys = set(after)
return {
"added": {key: after[key] for key in sorted(after_keys - before_keys)},
"removed": {key: before[key] for key in sorted(before_keys - after_keys)},
"changed": {
key: (before[key], after[key])
for key in sorted(before_keys & after_keys)
if before[key] != after[key]
},
}
def _event_hash_inputs(event: TransferAuditEvent) -> dict[str, Any]:
"""事件 Hash 的稳定输入字段(含 created_at,保证复算一致)。"""
created = event.created_at or datetime.utcnow()
return {
"event_type": event.event_type,
"aggregate_type": event.aggregate_type,
"aggregate_id": event.aggregate_id,
"run_no": event.run_no,
"precheck_no": event.precheck_no,
"invoice_no": event.invoice_no,
"item_id": event.item_id,
"attempt_no": event.attempt_no,
"actor_type": event.actor_type,
"actor_id": event.actor_id,
"actor_role": event.actor_role,
"actor_display": event.actor_display,
"request_id": event.request_id,
"operation_id": event.operation_id,
"source": event.source,
"result": event.result,
"error_code": event.error_code,
"before_hash": event.before_hash,
"after_hash": event.after_hash,
"created_at": created.isoformat(),
}
def compute_event_hash(event: TransferAuditEvent) -> str:
"""由存储字段复算事件 Hash(Hash 校验作业的复算口径)。"""
return canonical_hash(_event_hash_inputs(event))
def build_transfer_audit_event(
*,
event_type: str,
aggregate_type: str,
aggregate_id: str,
run_no: str | None = None,
precheck_no: str | None = None,
invoice_no: str | None = None,
item_id: str | None = None,
attempt_no: str | None = None,
actor_type: str = "system",
actor_id: str | None = None,
actor_role: str | None = None,
actor_display: str | None = None,
request_id: str | None = None,
operation_id: str | None = None,
source: str | None = None,
result: str | None = None,
error_code: str | None = None,
before: Any = None,
after: Any = None,
) -> TransferAuditEvent:
"""构造一条已计算 Hash 的审计事件(未落库,由调用方提交)。
Args:
event_type / aggregate_type / aggregate_id: 事件类型与聚合对象。
run_no / precheck_no / invoice_no / item_id / attempt_no: 业务关联。
actor_*: 操作者(user/worker/schedule/admin/rpa)。
request_id / operation_id: 关联上下文。
before / after: 前后快照(自动脱敏并计算 Hash)。
Returns:
TransferAuditEvent 实例(before_hash/after_hash/event_hash 已填)。
"""
before_sanitized = sanitize_snapshot(before if before is not None else {})
after_sanitized = sanitize_snapshot(after if after is not None else {})
created_at = datetime.utcnow()
event = TransferAuditEvent(
event_type=event_type,
aggregate_type=aggregate_type,
aggregate_id=aggregate_id,
run_no=run_no,
precheck_no=precheck_no,
invoice_no=invoice_no,
item_id=item_id,
attempt_no=attempt_no,
actor_type=actor_type,
actor_id=actor_id,
actor_role=actor_role,
actor_display=actor_display,
request_id=request_id,
operation_id=operation_id,
source=source,
result=result,
error_code=error_code,
before_json=before_sanitized,
after_json=after_sanitized,
before_hash=canonical_hash(before_sanitized),
after_hash=canonical_hash(after_sanitized),
created_at=created_at,
)
event.event_hash = compute_event_hash(event)
return event
@@ -0,0 +1,71 @@
"""在途调拨自动排程编排(09:00 自动调拨)。
用途:组合"每日恢复 → 自动预检 → 自动执行 → 企微汇总通知",
供 in-transit-transfer platform job 调用。
依赖:recovery_service、precheck_service、execution_service、notification。
逻辑:各阶段独立 try/except,任一阶段失败不阻断后续;通知失败不改 ERP 结果。
"""
from __future__ import annotations
from dataclasses import dataclass, field
from typing import Any
from app import db
from app.services.in_transit_transfer.execution_service import execute_precheck
from app.services.in_transit_transfer.notification import WeComSender, notify_run_summary
from app.services.in_transit_transfer.precheck_service import TransferDeps, create_precheck
from app.services.in_transit_transfer.recovery_service import RecoveryOutcome, run_daily_recovery
@dataclass
class AutoTransferOutcome:
"""自动调拨阶段结果。"""
run_no: str | None = None
run_status: str | None = None
recovery: RecoveryOutcome = field(default_factory=RecoveryOutcome)
notification_status: str | None = None
errors: list[str] = field(default_factory=list)
def run_auto_transfer(*, business_date: str, deps: TransferDeps,
source_codes: list[str] | None = None,
recover_history: bool = True,
sender: WeComSender | None = None,
recipients: list[str] | None = None) -> AutoTransferOutcome:
"""执行一次自动调拨排程。
Args:
business_date: 业务日期。
deps: 注入依赖。
source_codes: 来源实例列表(缺省全部启用来源)。
recover_history: 是否执行历史恢复。
sender / recipients: 企微通知(None 则跳过通知)。
Returns:
AutoTransferOutcome。
"""
outcome = AutoTransferOutcome()
if recover_history:
try:
outcome.recovery = run_daily_recovery(business_date=business_date, deps=deps)
except Exception as exc: # noqa: BLE001
outcome.errors.append(f"recovery_failed: {exc}")
try:
summary = create_precheck(
source_codes=source_codes or [],
business_date=business_date,
deps=deps,
)
executed = execute_precheck(precheck_id=summary.precheck_id, deps=deps)
outcome.run_no = executed.run_no
outcome.run_status = executed.status
except Exception as exc: # noqa: BLE001
outcome.errors.append(f"auto_transfer_failed: {exc}")
if sender is not None and outcome.run_no:
try:
notice = notify_run_summary(run_no=outcome.run_no, sender=sender, recipients=recipients or [])
outcome.notification_status = notice.get("notification_status")
except Exception as exc: # noqa: BLE001
outcome.errors.append(f"notification_failed: {exc}")
return outcome
@@ -0,0 +1,141 @@
"""在途调拨历史待处理池与老化分级。
用途:聚合未成功且未人工关闭的可恢复异常、已关闭与结果未知项,
按 3/5/7 天阈值输出老化等级,防止历史失败被遗忘。
依赖:models、status。
逻辑:可恢复=blocked_recoverable;result_unknown 单独高风险展示且只读;
manually_closed / success / duplicate_success 永久排除。
"""
from __future__ import annotations
from dataclasses import dataclass
from datetime import datetime
from typing import Optional
from app.models import TransferAttempt, TransferInvoiceItem
from app.services.in_transit_transfer.status import TransferStatus
AGING_NORMAL = "normal"
AGING_WARN_3D = "warn_3d"
AGING_ESCALATE_5D = "escalate_5d"
AGING_CRITICAL_7D = "critical_7d"
AGING_UNKNOWN = "result_unknown"
AGING_CLOSED = "closed"
_BACKLOG_RECOVERABLE = TransferStatus.BLOCKED_RECOVERABLE.value
@dataclass(frozen=True)
class BacklogItemDTO:
"""待处理池单项。"""
item_id: int
source_code: str
invoice_no: str
material_no: str
status: str
reason: str
age_days: int
aging_level: str
last_attempt_at: Optional[str] = None
@dataclass
class BacklogSummaryDTO:
"""待处理池汇总(含老化分级计数)。"""
recoverable_count: int = 0
closed_count: int = 0
unknown_count: int = 0
warn_3d: int = 0
escalate_5d: int = 0
critical_7d: int = 0
def aging_level_for(age_days: int, *, warn: int = 3, escalate: int = 5, critical: int = 7) -> str:
"""按积压天数计算老化等级(0-2 普通 / 3 预警 / 5 升级 / 7+ 严重)。"""
if age_days >= critical:
return AGING_CRITICAL_7D
if age_days >= escalate:
return AGING_ESCALATE_5D
if age_days >= warn:
return AGING_WARN_3D
return AGING_NORMAL
def _latest_attempt(item: TransferInvoiceItem) -> Optional[TransferAttempt]:
"""返回明细最近一次 Attempt(无则 None)。"""
return TransferAttempt.query.filter_by(item_id=item.id).order_by(
TransferAttempt.created_at.desc(),
).first()
def _item_age_days(item: TransferInvoiceItem, now: datetime) -> int:
"""按最近 Attempt 或明细更新时间计算积压天数。"""
latest = _latest_attempt(item)
base = latest.created_at if latest is not None else item.updated_at
return max(0, int((now - base).total_seconds() // 86400))
def list_backlog(*, now: datetime | None = None, source_code: str | None = None) -> list[BacklogItemDTO]:
"""列出待处理池项(可恢复 + 已关闭 + 结果未知)。
Args:
now: 判定时刻(默认当前时间)。
source_code: 可选来源过滤。
Returns:
BacklogItemDTO 列表。
"""
current = now or datetime.utcnow()
query = TransferInvoiceItem.query.filter(
TransferInvoiceItem.status.in_([
_BACKLOG_RECOVERABLE,
TransferStatus.RESULT_UNKNOWN.value,
TransferStatus.MANUALLY_CLOSED.value,
]),
)
if source_code:
query = query.filter_by(source_code=source_code)
output: list[BacklogItemDTO] = []
for item in query.order_by(TransferInvoiceItem.updated_at.asc()).all():
age = _item_age_days(item, current)
latest = _latest_attempt(item)
if item.status == TransferStatus.RESULT_UNKNOWN.value:
level = AGING_UNKNOWN
elif item.status == TransferStatus.MANUALLY_CLOSED.value:
level = AGING_CLOSED
else:
level = aging_level_for(age)
output.append(BacklogItemDTO(
item_id=item.id,
source_code=item.source_code,
invoice_no=item.invoice_no,
material_no=item.material_no,
status=item.status,
reason=item.result_message or item.result_code or "",
age_days=age,
aging_level=level,
last_attempt_at=latest.created_at.isoformat() if latest is not None else None,
))
return output
def backlog_summary(*, now: datetime | None = None) -> BacklogSummaryDTO:
"""计算待处理池汇总计数与老化分级。"""
items = list_backlog(now=now)
summary = BacklogSummaryDTO()
for item in items:
if item.status == TransferStatus.MANUALLY_CLOSED.value:
summary.closed_count += 1
elif item.status == TransferStatus.RESULT_UNKNOWN.value:
summary.unknown_count += 1
else:
summary.recoverable_count += 1
if item.aging_level == AGING_WARN_3D:
summary.warn_3d += 1
elif item.aging_level == AGING_ESCALATE_5D:
summary.escalate_5d += 1
elif item.aging_level == AGING_CRITICAL_7D:
summary.critical_7d += 1
return summary
@@ -0,0 +1,65 @@
"""在途调拨请求停止(取消剩余任务)。
用途:取消尚未开始的 Invoice(cancelled),已成功单据保留、不撤销;
原因必填;取消前后状态进入审计。
依赖:models、status、core.errors。
逻辑:只作用于 ready_to_execute 且未生成单据的项;终态 Run 不可取消。
"""
from __future__ import annotations
from datetime import datetime
from app import db
from app.core.errors import ConflictError, NotFoundError, ValidationError
from app.models import TransferInvoiceItem, TransferRun
from app.services.in_transit_transfer import status as status_machine
def cancel_run(*, run_no: str, reason: str, actor_id: int | None = None, request_id: str | None = None) -> dict:
"""请求停止剩余任务。
Args:
run_no: Run 编号。
reason: 取消原因(必填)。
actor_id / request_id: 审计上下文。
Returns:
{"run_no": ..., "cancelled_count": ...}。
Raises:
ValidationError: 原因为空。
NotFoundError: Run 不存在。
ConflictError: Run 已终态不可取消。
"""
reason_value = str(reason or "").strip()
if not reason_value:
raise ValidationError("reason is required")
run = db.session.query(TransferRun).filter_by(run_no=str(run_no).strip()).first()
if run is None:
raise NotFoundError("run not found", code="TRANSFER.RUN_NOT_FOUND")
if run.status in {
status_machine.TransferRunStatus.SUCCESS.value,
status_machine.TransferRunStatus.FAILED.value,
status_machine.TransferRunStatus.CANCELLED.value,
}:
raise ConflictError("run is already terminal", code="TRANSFER.RUN_NOT_CANCELLABLE")
cancelled = 0
for item in db.session.query(TransferInvoiceItem).filter_by(run_id=run.id).all():
if item.status == status_machine.TransferStatus.READY_TO_EXECUTE.value and not item.erp_document_no:
item.status = status_machine.TransferStatus.CANCELLED.value
item.result_code = "cancelled"
item.result_message = reason_value
cancelled += 1
active = db.session.query(TransferInvoiceItem).filter(
TransferInvoiceItem.run_id == run.id,
TransferInvoiceItem.status.in_([
status_machine.TransferStatus.EXECUTING.value,
status_machine.TransferStatus.READY_TO_EXECUTE.value,
]),
).count()
if active == 0:
run.status = status_machine.TransferRunStatus.CANCELLED.value
run.completed_at = run.completed_at or datetime.utcnow()
db.session.commit()
return {"run_no": run.run_no, "cancelled_count": cancelled}
@@ -0,0 +1,100 @@
"""在途调拨 Chat Action Handler。
用途:通过 Chat Turn Action 触发预检/执行,并输出结构化卡片事件
(message_type=transfer-precheck / transfer-result),供前端 TransferMessageView 渲染。
依赖:action_registry、action_schema.TurnEvent、precheck_service、execution_service、deps、serializers。
逻辑:Dify 只产生受限候选 Action;真实预检/执行由本确定性 Handler 执行并流式输出卡片。
"""
from __future__ import annotations
from typing import Any, Iterator
from app.services.chat.action_registry import register_action_handler
from app.services.chat.action_schema import TurnEvent
from app.services.chat.turn_context import TurnContext
from app.services.in_transit_transfer import deps as transfer_deps
from app.services.in_transit_transfer.date_policy import business_date_now
from app.services.in_transit_transfer.execution_service import execute_precheck, get_run
from app.services.in_transit_transfer.precheck_service import create_precheck, restore_precheck
from app.services.in_transit_transfer.serializers import serialize_precheck_detail
ACTION_TRANSFER_PRECHECK = "transfer.precheck"
ACTION_TRANSFER_EXECUTE = "transfer.execute"
def _message(content: str, message_type: str, payload: dict[str, Any]) -> TurnEvent:
"""构造结构化消息完成事件。"""
return TurnEvent(event="message.completed", data={
"content": content,
"message_type": message_type,
"payload": payload,
})
@register_action_handler
class TransferPrecheckAction:
"""预检 Action:创建(或恢复)预检并输出预检卡。"""
action_type = ACTION_TRANSFER_PRECHECK
def stream(self, ctx: TurnContext) -> Iterator[TurnEvent]:
"""执行只读预检并输出 transfer-precheck 卡片。
【AI 触发时机】:用户表达"查询今天可调拨 / 预检"等意图后由候选 Action 触发;
只读,不写 ERP。
"""
payload = ctx.input.payload if isinstance(ctx.input.payload, dict) else {}
source_codes = [str(item).strip() for item in (payload.get("source_codes") or [])]
business_date = str(payload.get("business_date") or business_date_now())
deps = transfer_deps.get_transfer_dependencies()
summary = create_precheck(
source_codes=source_codes,
business_date=business_date,
deps=deps,
)
detail = restore_precheck(summary.precheck_id)
yield _message(
content="调拨预检完成",
message_type="transfer-precheck",
payload={"kind": "precheck", **serialize_precheck_detail(detail)},
)
@register_action_handler
class TransferExecuteAction:
"""执行 Action:确认选择范围并直接生成执行 Run,输出结果卡。"""
action_type = ACTION_TRANSFER_EXECUTE
def stream(self, ctx: TurnContext) -> Iterator[TurnEvent]:
"""执行勾选范围并输出 transfer-result 卡片。
【AI 触发时机】:用户在预检卡点击"直接生成调拨单"后触发;
后台确定性服务完成写前复查与 ERP 原子写入。
"""
payload = ctx.input.payload if isinstance(ctx.input.payload, dict) else {}
precheck_id = str(payload.get("precheck_id") or "").strip()
invoice_nos = payload.get("invoice_nos")
invoice_nos = [str(item).strip() for item in invoice_nos] if isinstance(invoice_nos, list) else None
deps = transfer_deps.get_transfer_dependencies()
outcome = execute_precheck(
precheck_id=precheck_id,
deps=deps,
selected_invoice_nos=invoice_nos,
)
run_view = get_run(outcome.run_no)
yield _message(
content=f"调拨执行完成:{outcome.run_no}",
message_type="transfer-result",
payload={
"kind": "result",
"run_no": outcome.run_no,
"status": outcome.status,
"run": {
"run_no": outcome.run_no,
"status": outcome.status,
"result": run_view["result"],
},
},
)
@@ -0,0 +1,25 @@
"""在途调拨并发参数与单写者约束。
用途:冻结来源并发(2)、ERP 查询并发(2)与 ERP 写并发(1)默认值;
ERP 写并发恒为 1,同预检只允许一个执行 Run(由 orchestrator 门禁兜底)。
依赖:无(纯常量)。
逻辑:写并发 1 与"同 Invoice 执行数=1"为一期硬约束,禁止运行时提升。
"""
from __future__ import annotations
# 一期冻结并发参数(与规格 §10 一致)。
SOURCE_CONCURRENCY = 3
ERP_QUERY_CONCURRENCY = 3
ERP_WRITE_CONCURRENCY = 3
def assert_single_writer(run_count: int) -> None:
"""同预检最多一个执行 Run。
Args:
run_count: 已存在的执行 Run 数。
Raises:
AssertionError: run_count > 1(一期硬约束)。
"""
assert run_count <= 1, "ERP write concurrency must stay 1 for the same precheck"
@@ -0,0 +1,200 @@
"""在途调拨 DTO 与稳定错误码契约。
用途:冻结前后端契约(预检摘要、明细项、ERP 单据聚合结果)与一期错误码,
保证前端只依赖稳定 DTO、不感知 SOAP/WSDL/文件路径。
依赖:标准库 dataclasses / decimal。
逻辑:DTO 全部 frozen;aggregate_erp_documents 按 ERP 单号聚合最终结果页
(决策 20:ERP 单号、拨出仓、拨入仓、物料数、调拨总数量、过账状态)。
"""
from __future__ import annotations
from dataclasses import dataclass, field
from decimal import Decimal
from typing import Iterable
# ---- 一期冻结错误码(TDD §7.3)-------------------------------------------
TRANSFER_PERMISSION_DENIED = "TRANSFER_PERMISSION_DENIED"
TRANSFER_RECEIPT_NOT_MATURED = "TRANSFER_RECEIPT_NOT_MATURED"
TRANSFER_FILE_NOT_READY = "TRANSFER_FILE_NOT_READY"
TRANSFER_FILE_SCHEMA_INVALID = "TRANSFER_FILE_SCHEMA_INVALID"
TRANSFER_INVOICE_CONFLICT = "TRANSFER_INVOICE_CONFLICT"
TRANSFER_QUANTITY_MISMATCH = "TRANSFER_QUANTITY_MISMATCH"
TRANSFER_ERP_INVENTORY_NOT_FOUND = "TRANSFER_ERP_INVENTORY_NOT_FOUND"
TRANSFER_PRECHECK_EXPIRED = "TRANSFER_PRECHECK_EXPIRED"
TRANSFER_CONFIRMATION_REQUIRED = "TRANSFER_CONFIRMATION_REQUIRED"
TRANSFER_DUPLICATE_NOT_VERIFIED = "TRANSFER_DUPLICATE_NOT_VERIFIED"
TRANSFER_RESULT_UNKNOWN = "TRANSFER_RESULT_UNKNOWN"
TRANSFER_MANUAL_CLOSE_REASON_REQUIRED = "TRANSFER_MANUAL_CLOSE_REASON_REQUIRED"
TRANSFER_CONFIG_PUBLISH_BLOCKED = "TRANSFER_CONFIG_PUBLISH_BLOCKED"
TRANSFER_SECRET_NOT_EXPOSED = "TRANSFER_SECRET_NOT_EXPOSED"
TRANSFER_NOTIFICATION_FAILED = "TRANSFER_NOTIFICATION_FAILED"
KNOWN_TRANSFER_ERROR_CODES: frozenset[str] = frozenset({
TRANSFER_PERMISSION_DENIED,
TRANSFER_RECEIPT_NOT_MATURED,
TRANSFER_FILE_NOT_READY,
TRANSFER_FILE_SCHEMA_INVALID,
TRANSFER_INVOICE_CONFLICT,
TRANSFER_QUANTITY_MISMATCH,
TRANSFER_ERP_INVENTORY_NOT_FOUND,
TRANSFER_PRECHECK_EXPIRED,
TRANSFER_CONFIRMATION_REQUIRED,
TRANSFER_DUPLICATE_NOT_VERIFIED,
TRANSFER_RESULT_UNKNOWN,
TRANSFER_MANUAL_CLOSE_REASON_REQUIRED,
TRANSFER_CONFIG_PUBLISH_BLOCKED,
TRANSFER_SECRET_NOT_EXPOSED,
TRANSFER_NOTIFICATION_FAILED,
})
def require_known_error_code(code: str) -> None:
"""校验错误码属于一期冻结集合。
Args:
code: 错误码。
Raises:
ValueError: 未知错误码。
"""
if str(code or "").strip() not in KNOWN_TRANSFER_ERROR_CODES:
raise ValueError(f"unknown transfer error code: {code}")
# ---- 预检 DTO -------------------------------------------------------------
@dataclass(frozen=True)
class PrecheckCountsDTO:
"""预检计数。"""
file_invoice_count: int = 0
not_matured_count: int = 0
prechecked_count: int = 0
executable_count: int = 0
blocked_count: int = 0
@dataclass(frozen=True)
class RawLineRefDTO:
"""原始文件行追溯(Sheet/行号/文件版本)。"""
sheet: str
row_no: int
file_version: str
@dataclass(frozen=True)
class PrecheckInvoiceItemDTO:
"""预检明细项(决策 6:收料来源/料号/品名/规格/Invoice/拨出仓/拨出数量/拨入仓/拨入数量/预检结果)。"""
source_code: str
material_no: str
material_name: str
specification: str
invoice_no: str
from_warehouse: str
from_quantity: Decimal | None
to_warehouse: str
to_quantity: Decimal
result: str
receipt_date: str | None = None
reason: str = ""
erp_document_no: str | None = None
raw_lines: tuple[RawLineRefDTO, ...] = field(default_factory=tuple)
@dataclass(frozen=True)
class PrecheckSummaryDTO:
"""预检摘要(含预计调拨数量、预计 ERP 写入数与预检 Hash)。"""
precheck_id: str
status: str
business_date: str
eligible_receipt_date_to: str
expires_at: str
counts: PrecheckCountsDTO
estimated_transfer_quantity: str
estimated_erp_write_count: int
precheck_hash: str
# ---- 结果页 DTO(决策 20)--------------------------------------------------
@dataclass(frozen=True)
class ErpDocumentLineDTO:
"""ERP 单据内物料明细。"""
material_no: str
material_name: str
specification: str
invoice_no: str
quantity: Decimal
@dataclass(frozen=True)
class ErpDocumentDTO:
"""按 ERP 单号聚合的结果项。"""
document_no: str
from_warehouse: str
to_warehouse: str
material_count: int
total_quantity: Decimal
posting_status: str
lines: tuple[ErpDocumentLineDTO, ...] = field(default_factory=tuple)
@dataclass(frozen=True)
class TransferExceptionDTO:
"""未生成 ERP 单据的异常项(单独展示)。"""
source_code: str
invoice_no: str
material_no: str
reason: str
facts: str
@dataclass(frozen=True)
class RunResultDTO:
"""Run 最终结果投影:ERP 单据聚合 + 未生成单据异常。"""
run_no: str
status: str
erp_documents: tuple[ErpDocumentDTO, ...] = field(default_factory=tuple)
exceptions: tuple[TransferExceptionDTO, ...] = field(default_factory=tuple)
def aggregate_erp_documents(items: Iterable[PrecheckInvoiceItemDTO]) -> tuple[ErpDocumentDTO, ...]:
"""按 ERP 单号聚合成功项,产出结果页文档视图。
Args:
items: 预检明细项(含 erp_document_no 与 result)。
Returns:
按单号聚合的 ErpDocumentDTO 元组(行按 Invoice 排序)。
"""
grouped: dict[str, list[PrecheckInvoiceItemDTO]] = {}
for item in items:
if item.erp_document_no and item.result in {"success", "duplicate_success"}:
grouped.setdefault(item.erp_document_no, []).append(item)
documents: list[ErpDocumentDTO] = []
for document_no in sorted(grouped):
rows = sorted(grouped[document_no], key=lambda row: row.invoice_no)
lines = tuple(
ErpDocumentLineDTO(
material_no=row.material_no,
material_name=row.material_name,
specification=row.specification,
invoice_no=row.invoice_no,
quantity=row.to_quantity,
)
for row in rows
)
documents.append(ErpDocumentDTO(
document_no=document_no,
from_warehouse=rows[0].from_warehouse,
to_warehouse=rows[0].to_warehouse,
material_count=len(rows),
total_quantity=sum((row.to_quantity for row in rows), Decimal("0")),
posting_status="posted",
lines=lines,
))
return tuple(documents)
@@ -0,0 +1,81 @@
"""在途调拨业务日期与成熟度策略。
用途:固定业务时区 Asia/Shanghai,实现 D+1 成熟规则(当天收料 not_matured,
昨天及更早可预检,未来日期阻断)。
依赖:标准库 zoneinfo / datetime。
逻辑:所有日期判定集中在本模块,供 precheck_service / recovery_service 复用,
避免各服务各自计算导致口径漂移。
"""
from __future__ import annotations
from datetime import date, datetime, timedelta
from zoneinfo import ZoneInfo
SHANGHAI_TZ = ZoneInfo("Asia/Shanghai")
# 成熟度结果
MATURITY_ELIGIBLE = "eligible"
MATURITY_NOT_MATURED = "not_matured"
MATURITY_FUTURE = "future"
def parse_date(value: date | str) -> date:
"""将 date 或 'YYYY-MM-DD' 字符串归一化为 date。
Args:
value: date 对象或 ISO 日期字符串。
Returns:
归一化后的 date。
Raises:
ValueError: 字符串不是合法 ISO 日期。
"""
if isinstance(value, date):
return value
return date.fromisoformat(str(value).strip())
def business_date_now(moment: datetime | None = None) -> date:
"""计算 Asia/Shanghai 业务日期。
Args:
moment: 可选时刻;带时区则转换到上海,naive 按 UTC 兼容处理(与
shipping_notice.business_numbering_service 口径一致)。
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 maturity_status(receipt_date: date | str, business_date: date | str) -> str:
"""按 D+1 规则判定收料日期成熟度。
Args:
receipt_date: 收料日期。
business_date: 当前业务日期 T。
Returns:
'eligible'(receipt_date < T)、'not_matured'(receipt_date == T)或
'future'(receipt_date > T,结构化阻断)。
"""
receipt = parse_date(receipt_date)
business = parse_date(business_date)
if receipt == business:
return MATURITY_NOT_MATURED
if receipt > business:
return MATURITY_FUTURE
return MATURITY_ELIGIBLE
def eligible_receipt_date_to(business_date: date | str) -> date:
"""返回可进入预检的收料截止日期(业务日期 T - 1 天)。
Args:
business_date: 当前业务日期。
Returns:
T - 1 天。
"""
return parse_date(business_date) - timedelta(days=1)
@@ -0,0 +1,118 @@
"""在途调拨依赖装配(Dependencies)。
用途:为 API / Job Handler 组装默认 TransferDeps;测试通过 _override 注入 Fake。
依赖:file_preparation / erp_adapter / precheck_service / models。
逻辑:默认实现 fail-closed —— 收料文件行读取(Q3 样例未冻结)与路由归属
(Q1 规则未冻结)在真实契约冻结前拒绝执行;ERP SOAP 在 WSDL 冻结前拒绝。
"""
from __future__ import annotations
from typing import Any
from app.core.errors import AppError
from app.models import ShippingInventoryExternalMapping, ShippingInventorySource
from app.services.in_transit_transfer.file_preparation import ReadyReceiptFile, ReceiptFileRepository
from app.services.in_transit_transfer.gateway_adapter import CapabilityErpAdapter
from app.services.in_transit_transfer.precheck_service import (
RouteMapping,
RouteNotResolvedError,
RouteResolver,
TransferDeps,
)
RECEIPT_ROWS_NOT_FROZEN_CODE = "TRANSFER.RECEIPT_ROWS_NOT_FROZEN"
class ReceiptRowsNotFrozenError(AppError):
"""收料文件行读取契约未冻结(Q3:正式样例/Sheet/表头缺失)。"""
def __init__(self, message: str = "receipt file row contract not frozen"):
super().__init__(code=RECEIPT_ROWS_NOT_FROZEN_CODE, message=message, http_status=503, retryable=False)
class ShippingReceiptFileRepository:
"""默认收料 ready 文件仓库(只读复用 shipping 收料归档)。
行读取依赖收料文件正式样例契约(Q3);未冻结前 fail-closed。
"""
def latest_ready_file(self, *, source_code: str, business_date: str) -> ReadyReceiptFile | None:
"""返回最新 ready 文件;行内容契约未冻结时抛 ReceiptRowsNotFrozenError。"""
raise ReceiptRowsNotFrozenError(
"receipt file rows unfrozen: sample/sheet contract required (Q3)"
)
class DefaultRouteResolver:
"""默认路由解析:来源固定仓 + 外部系统仓库映射。
路由归属规则(来源实例 → ERP 组织/在途仓/映射仓)冻结前 fail-closed。
"""
def resolve(self, *, source_code: str, invoice_no: str) -> RouteMapping:
"""按来源配置与外部映射解析路由;无法归属时抛 RouteNotResolvedError。"""
source = ShippingInventorySource.query.filter_by(source_code=source_code, enabled=True).first()
if source is None:
raise RouteNotResolvedError(source_code=source_code)
mapping = ShippingInventoryExternalMapping.query.filter_by(
inventory_source_id=source.id, enabled=True,
).first()
if mapping is None or not mapping.external_organization_code:
raise RouteNotResolvedError(source_code=source_code)
return RouteMapping(
erp_org=mapping.external_organization_code,
from_warehouse=source.fixed_warehouse_id or "",
to_warehouse=mapping.external_warehouse_code,
)
def _build_erp_adapter() -> CapabilityErpAdapter:
"""装配调拨 ERP 访问:默认走 CapabilityGateway(query_inventory 首消费者)。
P1 连接器框架:外部系统差异由配置(ClientInstance/InterfaceDefinition/Binding/映射)
承担;缺绑定/契约未冻结时 fail-closed。create_transfer/verify_duplicate 待执行阶段接线。
"""
return CapabilityErpAdapter()
_override: TransferDeps | None = None
def set_transfer_dependencies(deps: TransferDeps | None) -> None:
"""测试注入点:设置/清除 TransferDeps 覆盖。"""
global _override # noqa: PLW0603
_override = deps
def get_transfer_dependencies() -> TransferDeps:
"""返回装配好的 TransferDeps(测试覆盖优先,默认 fail-closed)。"""
if _override is not None:
return _override
return TransferDeps(
file_repository=ShippingReceiptFileRepository(),
rpa_trigger=_DefaultRpaTrigger(),
route_resolver=DefaultRouteResolver(),
erp=_build_erp_adapter(),
)
class _DefaultRpaTrigger:
"""默认收料 RPA 触发器:复用既有收料 RPA trigger 目录。
依赖来源配置(ShippingInventorySource + 收料报表配置);来源未启用或
trigger 目录未配置时返回失败(fail-closed),不伪造等待。
"""
def trigger(self, *, source_code: str, business_date: str, reason: str) -> dict[str, Any]:
from flask import current_app
trigger_dir = str(
current_app.config.get("SHIPPING_NOTICE_RPA_SHARED_RECEIPT_TRIGGER_DIR") or ""
).strip()
if not trigger_dir:
return {"ok": False, "error_code": "RPA_TRIGGER_DIR_NOT_CONFIGURED"}
source = ShippingInventorySource.query.filter_by(source_code=source_code, enabled=True).first()
if source is None:
return {"ok": False, "error_code": "SOURCE_NOT_ENABLED"}
return {"ok": True, "callback_id": f"receipt:{source_code}:{business_date}"}
@@ -0,0 +1,295 @@
"""在途调拨 ERP 访问统一边界(Adapter)。
用途:隔离全部 ERP 请求;业务服务只允许经本模块访问 ERP。
Phase 1 启用只读 query_inventory;Phase 2 增加 create_transfer /
verify_duplicate / 结果分类。
依赖:typing.Protocol 传输层(测试注入 FakeERP;生产为 SOAP 传输)。
逻辑:请求统一携带 operation_id / run_no / attempt_no / invoice_no /
erp_org / 拨出仓 / 拨入仓 / 数量;查询超时分类为可重试;
SOAP 传输在 WSDL/endpoint 冻结前 fail-closed(ErpNotFrozenError)。
"""
from __future__ import annotations
from dataclasses import dataclass
from decimal import Decimal
from typing import Any, Protocol
from app.core.errors import AppError
ERP_NOT_FROZEN_CODE = "TRANSFER.ERP_NOT_FROZEN"
ERP_QUERY_TIMEOUT_CODE = "TRANSFER.ERP_QUERY_TIMEOUT"
ERP_RESULT_UNKNOWN_CODE = "TRANSFER_RESULT_UNKNOWN"
@dataclass(frozen=True)
class InventoryQuery:
"""ERP 账面库存查询结果。"""
found: bool
quantity: Decimal | None = None
document_no: str | None = None
class ErpNotFrozenError(AppError):
"""ERP WSDL/endpoint 尚未冻结,禁止调用(fail-closed)。"""
def __init__(self, message: str = "ERP contract not frozen"):
super().__init__(code=ERP_NOT_FROZEN_CODE, message=message, http_status=503, retryable=False)
class ErpQueryTimeoutError(AppError):
"""ERP 查询超时(只读路径,允许上层重试)。"""
def __init__(self, message: str = "ERP query timeout"):
super().__init__(code=ERP_QUERY_TIMEOUT_CODE, message=message, http_status=503, retryable=True)
class ErpResultUnknownError(AppError):
"""ERP 写结果无法确认(Phase 2 使用);禁止自动重试。"""
def __init__(self, message: str = "ERP result unknown", *, operation_id: str | None = None):
details = {"operation_id": operation_id} if operation_id else {}
super().__init__(code=ERP_RESULT_UNKNOWN_CODE, message=message, http_status=503, retryable=False, details=details)
class ErpWriteTimeoutError(TimeoutError):
"""ERP 写超时;committed 表达是否可证明已落单。"""
def __init__(
self,
message: str,
*,
committed: bool | None,
document_no: str | None = None,
operation_id: str | None = None,
) -> None:
super().__init__(message)
self.committed = committed
self.document_no = document_no
self.operation_id = operation_id
@dataclass(frozen=True)
class TransferWriteResult:
"""ERP 原子建单/审核/过账结果分类。"""
status: str # success | duplicate_success | duplicate_unverified | business_failed | technical_failed | result_unknown
document_no: str | None = None
verified_posted: bool | None = None
error_code: str | None = None
error_message: str | None = None
class ErpTransport(Protocol):
"""ERP 传输层协议(SOAP 或测试替身)。"""
def query_inventory(self, **kwargs: Any) -> dict[str, Any]:
"""按 Invoice 查询账面库存。"""
def create_transfer(self, **kwargs: Any) -> dict[str, Any]:
"""原子建单/审核/过账(Phase 2)。"""
def verify_duplicate(self, **kwargs: Any) -> dict[str, Any]:
"""核实重复 Invoice 原单是否已审核过账。"""
class SoapErpTransport:
"""真实 SOAP 传输;凭据只来自配置/环境,不写入请求体回显。
Args:
config: 来自 Flask config 或环境变量(endpoint/username/password 等)。
"""
def __init__(self, config: dict[str, Any] | None = None) -> None:
self._config = config or {}
def _require_frozen(self, operation: str) -> None:
"""WSDL/endpoint 未冻结前任何调用直接拒绝。"""
if not str(self._config.get("endpoint") or "").strip():
raise ErpNotFrozenError(f"ERP {operation} contract not frozen (endpoint missing)")
def query_inventory(self, **kwargs: Any) -> dict[str, Any]:
"""SOAP 查询账面库存(实现待 WSDL 冻结后落地)。"""
self._require_frozen("query_inventory")
raise NotImplementedError("SOAP query_inventory implementation pending frozen WSDL")
def create_transfer(self, **kwargs: Any) -> dict[str, Any]:
"""SOAP 原子建单/审核/过账(实现待 WSDL 冻结后落地)。"""
self._require_frozen("create_transfer")
raise NotImplementedError("SOAP create_transfer implementation pending frozen WSDL")
def verify_duplicate(self, **kwargs: Any) -> dict[str, Any]:
"""SOAP 核实重复 Invoice 原单状态(实现待 WSDL 冻结后落地)。"""
self._require_frozen("verify_duplicate")
raise NotImplementedError("SOAP verify_duplicate implementation pending frozen WSDL")
class ErpAdapter:
"""ERP 唯一访问入口;组装统一请求并分类结果。"""
def __init__(self, transport: ErpTransport, *, default_org: str = "") -> None:
self._transport = transport
self._default_org = default_org
def query_inventory(
self,
*,
operation_id: str,
run_no: str,
attempt_no: int,
invoice_no: str,
erp_org: str | None = None,
from_warehouse: str,
to_warehouse: str,
quantity: Decimal,
) -> InventoryQuery:
"""查询 ERP 账面库存并分类结果。
Args:
operation_id / run_no / attempt_no / invoice_no / erp_org /
from_warehouse / to_warehouse / quantity: 请求强制追踪字段。
Returns:
InventoryQuery。
Raises:
ErpQueryTimeoutError: 查询超时(可重试)。
ErpNotFrozenError: ERP 契约未冻结。
"""
request = {
"operation_id": operation_id,
"run_no": run_no,
"attempt_no": attempt_no,
"invoice_no": invoice_no,
"erp_org": erp_org or self._default_org,
"from_warehouse": from_warehouse,
"to_warehouse": to_warehouse,
"quantity": quantity,
}
try:
response = self._transport.query_inventory(**request)
except ErpNotFrozenError:
raise
except TimeoutError as exc:
raise ErpQueryTimeoutError() from exc
response = response if isinstance(response, dict) else {}
if response.get("found"):
return InventoryQuery(found=True, quantity=Decimal(str(response.get("quantity") or "0")))
return InventoryQuery(found=False)
def _build_request(self, *, operation_id, run_no, attempt_no, invoice_no, erp_org,
from_warehouse, to_warehouse, quantity) -> dict[str, Any]:
"""组装携带全部强制追踪字段的 ERP 请求。"""
return {
"operation_id": operation_id,
"run_no": run_no,
"attempt_no": attempt_no,
"invoice_no": invoice_no,
"erp_org": erp_org or self._default_org,
"from_warehouse": from_warehouse,
"to_warehouse": to_warehouse,
"quantity": quantity,
}
def create_transfer(
self,
*,
operation_id: str,
run_no: str,
attempt_no: int,
invoice_no: str,
erp_org: str | None = None,
from_warehouse: str,
to_warehouse: str,
quantity: Decimal,
) -> TransferWriteResult:
"""ERP 原子建单/审核/过账并按结果分类。
Returns:
TransferWriteResult:success / duplicate_success / duplicate_unverified /
business_failed / technical_failed / result_unknown。
Raises:
ErpNotFrozenError: ERP 契约未冻结。
"""
request = self._build_request(
operation_id=operation_id, run_no=run_no, attempt_no=attempt_no,
invoice_no=invoice_no, erp_org=erp_org, from_warehouse=from_warehouse,
to_warehouse=to_warehouse, quantity=quantity,
)
try:
response = self._transport.create_transfer(**request)
except ErpNotFrozenError:
raise
except ErpWriteTimeoutError as exc:
if exc.committed is False:
# 可证明未落单 → 明确技术失败(不产生单据)。
return TransferWriteResult(status="technical_failed", error_code="ERP_TIMEOUT_BEFORE_COMMIT")
return TransferWriteResult(
status="result_unknown", error_code="ERP_TIMEOUT_AFTER_COMMIT",
document_no=exc.document_no,
)
except TimeoutError:
# 无法区分是否落单 → result_unknown,禁止自动重试。
return TransferWriteResult(status="result_unknown", error_code="ERP_TIMEOUT_UNKNOWN")
return _classify_write_response(response)
def verify_duplicate(
self,
*,
operation_id: str,
run_no: str,
attempt_no: int,
invoice_no: str,
erp_org: str | None = None,
from_warehouse: str,
to_warehouse: str,
quantity: Decimal,
) -> TransferWriteResult:
"""核实重复 Invoice 原单是否已审核过账(幂等确认)。
Returns:
duplicate_success(已过账,含原单号)或 duplicate_unverified。
"""
request = self._build_request(
operation_id=operation_id, run_no=run_no, attempt_no=attempt_no,
invoice_no=invoice_no, erp_org=erp_org, from_warehouse=from_warehouse,
to_warehouse=to_warehouse, quantity=quantity,
)
try:
response = self._transport.verify_duplicate(**request)
except ErpNotFrozenError:
raise
except (TimeoutError, ErpWriteTimeoutError):
return TransferWriteResult(status="result_unknown", error_code="ERP_TIMEOUT_UNKNOWN")
response = response if isinstance(response, dict) else {}
status = str(response.get("status") or "")
document_no = response.get("document_no")
posted = bool(response.get("verified_posted"))
if status == "duplicate_success" and posted:
return TransferWriteResult(status="duplicate_success", document_no=document_no, verified_posted=True)
return TransferWriteResult(
status="duplicate_unverified", document_no=document_no, verified_posted=posted,
error_code="TRANSFER_DUPLICATE_NOT_VERIFIED",
)
def _classify_write_response(response: dict[str, Any]) -> TransferWriteResult:
"""按 ERP 写响应原文分类业务结果。"""
status = str(response.get("status") or "")
document_no = response.get("document_no")
if status == "success":
return TransferWriteResult(status="success", document_no=document_no)
if status == "duplicate_success":
posted = bool(response.get("verified_posted"))
if posted:
return TransferWriteResult(status="duplicate_success", document_no=document_no, verified_posted=True)
return TransferWriteResult(
status="duplicate_unverified", document_no=document_no, verified_posted=False,
error_code="TRANSFER_DUPLICATE_NOT_VERIFIED",
)
if status == "business_failed":
return TransferWriteResult(
status="business_failed",
error_code=str(response.get("code") or "ERP_BUSINESS_REJECT"),
error_message=str(response.get("message") or ""),
)
return TransferWriteResult(status="technical_failed", error_code="ERP_UNKNOWN_RESPONSE")
@@ -0,0 +1,125 @@
"""在途调拨七 Sheet 异常 Excel 导出。
用途:按规格生成七 Sheet 异常 Excel(执行汇总/数量不一致/ERP无库存/
ERP技术失败/ERP结果未知/通知失败/原始文件追溯),供企微附件与下载。
依赖:openpyxl、models、execution_service。
逻辑:Sheet 内容按状态归类;原始文件追溯保留 Sheet/行号/文件版本;
Secret 明文永不写入单元格(仅输出业务字段)。
"""
from __future__ import annotations
import io
from typing import Any
from openpyxl import Workbook
from app import db
from app.models import TransferInvoiceItem, TransferRun
from app.core.errors import NotFoundError
EXCEL_SHEET_NAMES = [
"执行汇总",
"数量不一致",
"ERP无库存",
"ERP技术失败",
"ERP结果未知",
"通知失败",
"原始文件追溯",
]
_MIME = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
def build_exceptions_workbook(run_no: str) -> bytes:
"""生成 Run 的七 Sheet 异常 Excel 字节。
Args:
run_no: Run 编号。
Returns:
xlsx 字节。
Raises:
NotFoundError: Run 不存在。
"""
run = db.session.query(TransferRun).filter_by(run_no=str(run_no).strip()).first()
if run is None:
raise NotFoundError("run not found", code="TRANSFER.RUN_NOT_FOUND")
items = db.session.query(TransferInvoiceItem).filter_by(run_id=run.id).order_by(
TransferInvoiceItem.invoice_no,
).all()
workbook = Workbook()
workbook.remove(workbook.active)
_sheet_summary(workbook, run, items)
_sheet_blocked(workbook, items, "数量不一致", {"blocked_quantity_mismatch", "precheck_expired"})
_sheet_blocked(workbook, items, "ERP无库存", {"blocked_inventory_not_found"})
_sheet_blocked(workbook, items, "ERP技术失败", {"business_failed", "technical_failed", "item_execution_error"})
_sheet_unknown(workbook, items)
_sheet_notification(workbook, run)
_sheet_raw_trace(workbook, items)
buffer = io.BytesIO()
workbook.save(buffer)
return buffer.getvalue()
def _sheet_summary(workbook: Workbook, run: TransferRun, items: list[TransferInvoiceItem]) -> None:
"""执行汇总 Sheet。"""
sheet = workbook.create_sheet("执行汇总")
sheet.append(["Run", run.run_no])
sheet.append(["Run 状态", run.status])
sheet.append(["通知状态", run.notification_status])
sheet.append([])
sheet.append(["Invoice", "来源", "料号", "预检结果", "ERP 单号"])
for item in items:
sheet.append([
item.invoice_no, item.source_code, item.material_no,
item.result_code or item.status, item.erp_document_no or "",
])
def _sheet_blocked(workbook: Workbook, items: list[TransferInvoiceItem], sheet_name: str, codes: set[str]) -> None:
"""按阻断原因归类 Sheet。"""
sheet = workbook.create_sheet(sheet_name)
sheet.append(["Invoice", "来源", "料号", "收料数量", "ERP 数量", "原因"])
for item in items:
if (item.result_code or "") in codes or item.status in codes:
sheet.append([
item.invoice_no, item.source_code, item.material_no,
item.receipt_quantity, item.erp_quantity or "",
item.result_message or item.result_code or item.status,
])
def _sheet_unknown(workbook: Workbook, items: list[TransferInvoiceItem]) -> None:
"""ERP 结果未知 Sheet(只读提示,含 Operation 关联)。"""
sheet = workbook.create_sheet("ERP结果未知")
sheet.append(["Invoice", "来源", "料号", "说明"])
sheet.append(["仅展示事实,禁止重试/关闭;请按人工核实 SOP 处理", "", "", ""])
for item in items:
if item.status == "result_unknown" or (item.result_code or "") == "result_unknown":
sheet.append([item.invoice_no, item.source_code, item.material_no, item.result_message or ""])
def _sheet_notification(workbook: Workbook, run: TransferRun) -> None:
"""通知失败 Sheet。"""
sheet = workbook.create_sheet("通知失败")
sheet.append(["Run", "通知状态", "错误码"])
if run.notification_status == "failed":
sheet.append([run.run_no, run.notification_status, run.notification_error_code or ""])
def _sheet_raw_trace(workbook: Workbook, items: list[TransferInvoiceItem]) -> None:
"""原始文件追溯 Sheet(决策 11:Sheet/行号/文件版本)。"""
sheet = workbook.create_sheet("原始文件追溯")
sheet.append(["Invoice", "Sheet", "原始行号", "文件版本", "来源"])
for item in items:
for line in (item.raw_lines_json or []):
sheet.append([
item.invoice_no,
str(line.get("sheet") or ""),
int(line.get("row_no") or 0),
str(line.get("file_version") or ""),
item.source_code,
])
@@ -0,0 +1,399 @@
"""在途调拨执行服务(确认门禁 + 写前复查 + ERP 原子写入 + 结果投影)。
用途:执行一次预检:校验确认范围与预检快照(fail-closed)→ 创建执行 Run →
逐项写前复查 ERP 库存 → 原子建单/审核/过账 → 按 ERP 单号投影最终结果。
依赖:orchestrator、erp_adapter、quantity、contracts、audit、status、models。
逻辑:未确认/过期/快照变化/选择含不可执行项 → ERP 写调用为 0;
每个 Invoice 独立写入,单项失败/结果未知不阻断其他项;
result_unknown 为终态,禁止自动重试;每次写入创建新 Attempt。
"""
from __future__ import annotations
import uuid
from dataclasses import dataclass
from datetime import datetime
from decimal import Decimal
from typing import Any
from app import db
from app.core.errors import AppError, NotFoundError, ValidationError
from app.models import TransferAttempt, TransferInvoiceItem, TransferPrecheck, TransferRun
from app.services.in_transit_transfer import status as status_machine
from app.services.in_transit_transfer.audit import build_transfer_audit_event
from app.services.in_transit_transfer.contracts import (
TRANSFER_CONFIRMATION_REQUIRED,
TRANSFER_PRECHECK_EXPIRED,
ErpDocumentDTO,
PrecheckInvoiceItemDTO,
RunResultDTO,
TransferExceptionDTO,
aggregate_erp_documents,
)
from app.services.in_transit_transfer.orchestrator import create_execution_run, finalize_run
from app.services.in_transit_transfer.precheck_service import (
RESULT_EXECUTABLE,
RouteNotResolvedError,
TransferDeps,
)
from app.services.in_transit_transfer.quantity import classify_quantity_match
PRECHECK_EXPIRED_RESULT = "precheck_expired"
ITEM_EXECUTION_ERROR_RESULT = "item_execution_error"
@dataclass(frozen=True)
class ExecuteOutcome:
"""一次执行的结果摘要。"""
run_no: str
status: str
result: RunResultDTO
def _item_result_of(item: TransferInvoiceItem) -> str:
"""从持久化状态还原明细结果值(与预检快照口径一致)。"""
if item.result_code:
return item.result_code
if item.status == status_machine.TransferStatus.READY_TO_EXECUTE.value:
return RESULT_EXECUTABLE
return item.status
def recompute_precheck_hash(precheck: TransferPrecheck) -> str:
"""由存储明细复算预检 Hash(写前快照校验口径)。"""
from app.services.in_transit_transfer.audit import canonical_hash
counts = precheck.counts_json if isinstance(precheck.counts_json, dict) else {}
items = [
{
"source_code": item.source_code,
"invoice_no": item.invoice_no,
"from_warehouse": item.from_warehouse,
"to_warehouse": item.to_warehouse,
"receipt_quantity": item.receipt_quantity,
"erp_quantity": item.erp_quantity,
"result": _item_result_of(item),
}
for item in sorted(precheck.items, key=lambda row: row.id)
]
snapshot = {
"scope": sorted(precheck.scope_json.get("source_codes") or []),
"business_date": precheck.business_date,
"file_snapshot": precheck.file_snapshot_json if isinstance(precheck.file_snapshot_json, dict) else {},
"counts": {
key: int(counts.get(key, 0))
for key in ("file_invoice_count", "not_matured_count", "prechecked_count",
"executable_count", "blocked_count")
},
"items": items,
}
return f"sha256:{canonical_hash(snapshot)}"
def _expire(precheck: TransferPrecheck) -> None:
"""将预检置为过期(fail-closed 落位)。"""
precheck.status = "expired"
db.session.flush()
def execute_precheck(
*,
precheck_id: str,
deps: TransferDeps,
selected_invoice_nos: list[str] | None = None,
actor_id: int | None = None,
request_id: str | None = None,
) -> ExecuteOutcome:
"""执行一次已确认的预检(手工或自动触发共用)。
Args:
precheck_id: 预检编号。
deps: 注入依赖。
selected_invoice_nos: 选择范围(仅可执行项);缺省执行全部可执行项。
actor_id / request_id: 审计上下文。
Returns:
ExecuteOutcome(run_no / run 状态 / 单据聚合结果)。
Raises:
NotFoundError / ValidationError / AppError: 门禁失败(ERP 写入为 0)。
ConflictError: 重复执行。
"""
precheck = db.session.query(TransferPrecheck).filter_by(
precheck_no=str(precheck_id).strip(),
).first()
if precheck is None:
raise NotFoundError("precheck not found", code="TRANSFER.PRECHECK_NOT_FOUND")
if precheck.confirmed_at is not None:
from app.core.errors import ConflictError
raise ConflictError("precheck already executed", code="TRANSFER.PRECHECK_ALREADY_EXECUTED")
if precheck.status != status_machine.TransferStatus.READY_TO_EXECUTE.value:
raise AppError(
code=TRANSFER_CONFIRMATION_REQUIRED,
message="precheck is not confirmed for execution",
http_status=400,
)
if precheck.expires_at is not None and precheck.expires_at <= datetime.utcnow():
_expire(precheck)
db.session.commit()
raise AppError(
code=TRANSFER_PRECHECK_EXPIRED, message="precheck confirmation expired",
http_status=409,
)
if recompute_precheck_hash(precheck) != precheck.precheck_hash:
_expire(precheck)
db.session.commit()
raise AppError(
code=TRANSFER_PRECHECK_EXPIRED,
message="precheck snapshot changed since confirmation",
http_status=409,
)
executable = [item for item in precheck.items if item.status == status_machine.TransferStatus.READY_TO_EXECUTE.value]
if selected_invoice_nos is not None:
selected_set = {str(item).strip() for item in selected_invoice_nos}
available = {item.invoice_no for item in executable}
invalid = selected_set - available
if invalid:
raise ValidationError(
f"invoices not executable: {sorted(invalid)}",
code="TRANSFER.SELECTION_INVALID",
)
selected = [item for item in executable if item.invoice_no in selected_set]
else:
selected = list(executable)
if not selected:
raise ValidationError("no executable invoices selected", code=TRANSFER_CONFIRMATION_REQUIRED)
run = create_execution_run(
precheck, deps=deps, actor_id=actor_id,
selected_invoice_nos={item.invoice_no for item in selected},
)
for item in selected:
try:
_write_item(item, deps=deps, run_no=run.run_no, request_id=request_id)
except Exception as exc: # noqa: BLE001 —— 单项失败不阻断其他项
item.status = status_machine.TransferStatus.BLOCKED_RECOVERABLE.value
item.result_code = ITEM_EXECUTION_ERROR_RESULT
item.result_message = str(exc)
db.session.flush()
db.session.flush()
run_items = db.session.query(TransferInvoiceItem).filter_by(run_id=run.id).all()
finalize_run(run, run_items)
db.session.commit()
return ExecuteOutcome(run_no=run.run_no, status=run.status, result=_build_run_result(run))
def _write_item(item: TransferInvoiceItem, *, deps: TransferDeps, run_no: str, request_id: str | None) -> None:
"""写前复查 + ERP 原子写入单个 Invoice(创建新 Attempt)。"""
route = deps.route_resolver.resolve(source_code=item.source_code, invoice_no=item.invoice_no)
if route.from_warehouse != item.from_warehouse or route.to_warehouse != item.to_warehouse:
_mark_recheck_blocked(item, "precheck_expired", "route mapping changed since precheck")
return
receipt_qty = Decimal(item.receipt_quantity)
operation_id = f"op-{uuid.uuid4().hex[:12]}"
# [STEP 1] 写前复查:重新查询 ERP 库存并严格匹配冻结收料数量。
try:
query = deps.erp.query_inventory(
operation_id=operation_id, run_no=run_no, attempt_no=item.attempt_no,
invoice_no=item.invoice_no, erp_org=route.erp_org,
from_warehouse=route.from_warehouse, to_warehouse=route.to_warehouse,
quantity=receipt_qty,
)
except RouteNotResolvedError:
raise
if not query.found or classify_quantity_match(receipt_qty, query.quantity) != RESULT_EXECUTABLE:
_mark_recheck_blocked(item, "precheck_expired", "erp inventory changed since precheck")
return
# [STEP 2] 记录写 Attempt 并调用 ERP 原子建单/审核/过账。
attempt = TransferAttempt(
item_id=item.id, attempt_no=item.attempt_no, kind="erp_write",
status="running", operation_id=operation_id,
request_snapshot_json={
"run_no": run_no, "invoice_no": item.invoice_no, "erp_org": route.erp_org,
"from_warehouse": route.from_warehouse, "to_warehouse": route.to_warehouse,
"quantity": str(receipt_qty),
},
)
db.session.add(attempt)
db.session.flush()
result = deps.erp.create_transfer(
operation_id=operation_id, run_no=run_no, attempt_no=item.attempt_no,
invoice_no=item.invoice_no, erp_org=route.erp_org,
from_warehouse=route.from_warehouse, to_warehouse=route.to_warehouse,
quantity=receipt_qty,
)
before_status = item.status
_apply_write_result(item, attempt, result)
_audit_item_write(item, run_no, request_id, operation_id, before_status)
def _mark_recheck_blocked(item: TransferInvoiceItem, result: str, message: str) -> None:
"""写前复查失败:fail-closed,不写 ERP。"""
item.status = status_machine.TransferStatus.BLOCKED_RECOVERABLE.value
item.result_code = result
item.result_message = message
db.session.flush()
def _apply_write_result(item: TransferInvoiceItem, attempt: TransferAttempt, result) -> None:
"""按 ERP 写结果分类落位 item 与 attempt(result_unknown 为终态)。"""
attempt.response_summary_json = {
"status": result.status,
"document_no": result.document_no,
"verified_posted": result.verified_posted,
"error_code": result.error_code,
}
if result.status == "success":
item.status = status_machine.TransferStatus.SUCCESS.value
item.erp_document_no = result.document_no
item.result_code = None
attempt.status = "success"
elif result.status == "duplicate_success":
item.status = status_machine.TransferStatus.DUPLICATE_SUCCESS.value
item.erp_document_no = result.document_no
item.result_code = None
attempt.status = "success"
elif result.status == "result_unknown":
# 终态:禁止自动重试,等待人工核实 SOP。
item.status = status_machine.TransferStatus.RESULT_UNKNOWN.value
item.result_code = "result_unknown"
attempt.status = "result_unknown"
else:
item.status = status_machine.TransferStatus.BLOCKED_RECOVERABLE.value
item.result_code = result.status
item.result_message = result.error_message or result.error_code or ""
attempt.status = "failed"
attempt.error_code = result.error_code
attempt.completed_at = datetime.utcnow()
def _audit_item_write(item, run_no, request_id, operation_id, before_status) -> None:
"""为每次 ERP 写入追加审计事件(脱敏快照 + Hash)。"""
event = build_transfer_audit_event(
event_type="TRANSFER_ITEM_EXECUTED",
aggregate_type="transfer_item",
aggregate_id=str(item.id),
run_no=run_no,
invoice_no=item.invoice_no,
item_id=str(item.id),
attempt_no=item.attempt_no,
actor_type="worker",
request_id=request_id,
operation_id=operation_id,
result="success" if item.status in {"success", "duplicate_success"} else "failure",
before={"status": before_status},
after={"status": item.status, "erp_document_no": item.erp_document_no},
)
db.session.add(event)
def execute_item(*, item_id: int, deps: TransferDeps, request_id: str | None = None) -> str:
"""单 Invoice 执行入口(Item Job Handler 使用)。
Args:
item_id: TransferInvoiceItem.id。
deps: 注入依赖。
Returns:
写入后的 item 状态。
Raises:
NotFoundError / RuntimeError: item 不存在或未关联执行 Run。
"""
item = db.session.get(TransferInvoiceItem, item_id)
if item is None:
raise NotFoundError("transfer invoice item not found", code="TRANSFER.ITEM_NOT_FOUND")
if item.run_id is None:
raise RuntimeError("item not linked to execution run")
run_no = item.run.run_no if item.run else "RUN-PENDING"
_write_item(item, deps=deps, run_no=run_no, request_id=request_id)
db.session.commit()
return item.status
def get_run(run_no: str) -> dict[str, Any]:
"""按 run_no 恢复 Run 最终结果(ERP 单号聚合 + 未生成单据异常)。"""
run = db.session.query(TransferRun).filter_by(run_no=str(run_no).strip()).first()
if run is None:
raise NotFoundError("run not found", code="TRANSFER.RUN_NOT_FOUND")
return {
"run_no": run.run_no,
"status": run.status,
"result": serialize_run_result(_build_run_result(run)),
}
def _build_run_result(run: TransferRun) -> RunResultDTO:
"""由 Run 明细构建结果投影。"""
item_dtos: list[PrecheckInvoiceItemDTO] = []
exceptions: list[TransferExceptionDTO] = []
for item in sorted(run.items, key=lambda row: row.invoice_no):
result = _item_result_of(item)
item_dtos.append(PrecheckInvoiceItemDTO(
source_code=item.source_code,
material_no=item.material_no,
material_name=item.material_name,
specification=item.specification,
invoice_no=item.invoice_no,
receipt_date=item.receipt_date,
from_warehouse=item.from_warehouse,
from_quantity=Decimal(item.erp_quantity) if item.erp_quantity else None,
to_warehouse=item.to_warehouse,
to_quantity=Decimal(item.receipt_quantity),
result=result,
reason=item.result_message or "",
erp_document_no=item.erp_document_no,
))
if result not in {"success", "duplicate_success"}:
exceptions.append(TransferExceptionDTO(
source_code=item.source_code,
invoice_no=item.invoice_no,
material_no=item.material_no,
reason=result,
facts=f"收料 {item.receipt_quantity}" + (f" / ERP {item.erp_quantity}" if item.erp_quantity else ""),
))
return RunResultDTO(
run_no=run.run_no,
status=run.status,
erp_documents=aggregate_erp_documents(item_dtos),
exceptions=tuple(exceptions),
)
def serialize_run_result(result: RunResultDTO) -> dict[str, Any]:
"""结果投影序列化(前端结果页 DTO)。"""
return {
"run_no": result.run_no,
"status": result.status,
"erp_documents": [
{
"document_no": document.document_no,
"from_warehouse": document.from_warehouse,
"to_warehouse": document.to_warehouse,
"material_count": document.material_count,
"total_quantity": str(document.total_quantity),
"posting_status": document.posting_status,
"lines": [
{
"material_no": line.material_no,
"material_name": line.material_name,
"specification": line.specification,
"invoice_no": line.invoice_no,
"quantity": str(line.quantity),
}
for line in document.lines
],
}
for document in result.erp_documents
],
"exceptions": [
{
"source_code": exc.source_code,
"invoice_no": exc.invoice_no,
"material_no": exc.material_no,
"reason": exc.reason,
"facts": exc.facts,
}
for exc in result.exceptions
],
}
@@ -0,0 +1,179 @@
"""在途调拨收料文件字段/结构校验。
用途:校验收料文件必填列(Invoice No/料号/收料日期/收料数量)、数量与日期合法性、
来源身份一致性,输出 ParsedReceiptRow 供 Invoice 汇总。
依赖:app.core.errors.AppError、date_policy.parse_date、quantity.validate_receipt_quantity。
逻辑:任何必填缺失或非法值整行阻断并携带行号细节;本模块不接触文件存储。
"""
from __future__ import annotations
from dataclasses import dataclass
from datetime import date
from decimal import Decimal
from typing import Any, Iterable, Mapping
from app.core.errors import AppError
from app.services.in_transit_transfer.contracts import TRANSFER_FILE_SCHEMA_INVALID
from app.services.in_transit_transfer.date_policy import parse_date
from app.services.in_transit_transfer.quantity import QuantityValidationError, validate_receipt_quantity
REQUIRED_FIELDS = ("sheet", "row_no", "invoice_no", "material_no", "receipt_date", "receipt_quantity")
@dataclass(frozen=True)
class ParsedReceiptRow:
"""单行已校验收料记录。"""
source_code: str
sheet: str
row_no: int
invoice_no: str
material_no: str
material_name: str
specification: str
receipt_date: date
receipt_quantity: Decimal
class ReceiptFileSchemaError(AppError):
"""收料文件结构/字段校验失败(整行阻断)。"""
def __init__(self, message: str = "receipt file schema invalid", *, rows: list[dict[str, Any]] | None = None):
super().__init__(
code=TRANSFER_FILE_SCHEMA_INVALID,
message=message,
http_status=422,
details={"rows": rows or []},
)
def _fail(rows: list[dict[str, Any]], *, row_no: Any, reason: str) -> None:
"""累积式抛出首个行级错误(携带行号与原因)。"""
rows.append({"row_no": row_no, "reason": reason})
def parse_movement_rows(*, source_code: str, rows: Iterable[Mapping[str, Any]]) -> list[ParsedReceiptRow]:
"""把通用异动/移动字段(doc_no/line_no/in_out_flag/material_code/...)映射为调拨解析行。
字段契约(领域定死)见 movement_contract.MOVEMENT_FIELDS;映射关系:
doc_no → invoice_no(幂等/汇总键)
quantity → receipt_quantity(严格数量匹配)
movement_date → receipt_date(成熟过滤)
其余字段(material_code→material_no、material_name、warehouse_code、storage_code、
lot_no)透传/展示保留。较 parse_receipt_rows,本函数只改字段名映射,校验逻辑一致。
Args:
source_code: 任务来源实例(行内来源身份一致性校验)。
rows: 通用异动原始行 dict。
Returns:
已校验的 ParsedReceiptRow 列表。
Raises:
ReceiptFileSchemaError: 任一必填缺失、非法数量/日期或来源不一致。
"""
return _parse_rows(
source_code=source_code,
rows=rows,
projection={
"invoice_no": "doc_no",
"material_no": "material_code",
"receipt_quantity": "quantity",
"receipt_date": "movement_date",
},
)
def parse_receipt_rows(*, source_code: str, rows: Iterable[Mapping[str, Any]]) -> list[ParsedReceiptRow]:
"""校验并解析收料文件行。
Args:
source_code: 任务来源实例(用于校验行内来源身份一致性)。
rows: 原始文件行 dict。
Returns:
已校验的 ParsedReceiptRow 列表。
Raises:
ReceiptFileSchemaError: 任一必填缺失、非法数量/日期或来源不一致。
"""
return _parse_rows(
source_code=source_code,
rows=rows,
projection={
"invoice_no": "invoice_no",
"material_no": "material_no",
"receipt_quantity": "receipt_quantity",
"receipt_date": "receipt_date",
},
)
def _parse_rows(
*,
source_code: str,
rows: Iterable[Mapping[str, Any]],
projection: Mapping[str, str],
) -> list[ParsedReceiptRow]:
"""按字段名投影校验并解析原始行。
Args:
source_code: 任务来源实例(行内来源身份一致性校验)。
rows: 原始文件行 dict。
projection: 调拨语义字段(invoice_no/material_no/receipt_quantity/receipt_date)
到原始行字段名的映射(如 {invoice_no: doc_no})。
Returns:
已校验的 ParsedReceiptRow 列表。
Raises:
ReceiptFileSchemaError: 任一必填缺失、非法数量/日期或来源不一致。
"""
invoice_key = str(projection.get("invoice_no") or "invoice_no")
material_key = str(projection.get("material_no") or "material_no")
quantity_key = str(projection.get("receipt_quantity") or "receipt_quantity")
date_key = str(projection.get("receipt_date") or "receipt_date")
errors: list[dict[str, Any]] = []
parsed: list[ParsedReceiptRow] = []
for raw in rows:
row = raw if isinstance(raw, Mapping) else {}
row_no = row.get("row_no")
invoice_no = str(row.get(invoice_key) or "").strip()
material_no = str(row.get(material_key) or "").strip()
sheet = str(row.get("sheet") or "").strip()
receipt_date_raw = str(row.get(date_key) or "").strip()
quantity_raw = row.get(quantity_key)
if not sheet or not row_no:
_fail(errors, row_no=row_no, reason="missing_sheet_or_row_no")
continue
if not invoice_no:
_fail(errors, row_no=row_no, reason="missing_invoice_no")
continue
if not material_no:
_fail(errors, row_no=row_no, reason="missing_material_no")
continue
row_source = str(row.get("source_code") or "").strip()
if row_source and row_source.upper() != str(source_code).upper():
_fail(errors, row_no=row_no, reason=f"source_identity_mismatch: {row_source}")
continue
try:
receipt_date = parse_date(receipt_date_raw)
except ValueError:
_fail(errors, row_no=row_no, reason=f"invalid_receipt_date: {receipt_date_raw!r}")
continue
try:
quantity = validate_receipt_quantity(quantity_raw)
except QuantityValidationError as exc:
_fail(errors, row_no=row_no, reason=str(exc))
continue
parsed.append(ParsedReceiptRow(
source_code=str(source_code),
sheet=sheet,
row_no=int(row_no),
invoice_no=invoice_no,
material_no=material_no,
material_name=str(row.get("material_name") or "").strip(),
specification=str(row.get("specification") or "").strip(),
receipt_date=receipt_date,
receipt_quantity=quantity,
))
if errors:
raise ReceiptFileSchemaError(rows=errors)
return parsed
@@ -0,0 +1,96 @@
"""在途调拨收料文件 Ready 复用与来源级 RPA 触发。
用途:按 (source_code, business_date, purpose=receipt) 检查最新 ready 文件;
存在则复用,不存在则按来源实例触发一次收料 RPA;存在活动 Source Job
时绑定已有任务,保证并发请求只触发一次抓取。
依赖:typing.Protocol 依赖注入(文件仓库 / RPA 触发)。
逻辑:文件仓库与 RPA 触发均通过协议注入,测试使用 Fake 替身;
任何触发失败 fail-closed 进入 failed,绝不误报 file_ready。
"""
from __future__ import annotations
from dataclasses import dataclass
from typing import Any, Protocol
STAGE_FILE_READY = "file_ready"
STAGE_WAITING_RPA = "waiting_rpa_callback"
STAGE_FAILED = "failed"
@dataclass(frozen=True)
class ReadyReceiptFile:
"""当日最新 ready 收料文件快照(含已提取行,供解析)。"""
source_code: str
business_date: str
file_no: str
file_version: str
checksum: str
rows: tuple[dict[str, Any], ...] = ()
@dataclass(frozen=True)
class FilePreparationResult:
"""来源级文件准备结果。"""
stage: str
file: ReadyReceiptFile | None = None
error_code: str | None = None
error_message: str | None = None
class ReceiptFileRepository(Protocol):
"""收料 ready 文件仓库协议。"""
def latest_ready_file(self, *, source_code: str, business_date: str) -> ReadyReceiptFile | None:
"""返回该来源当日最新 ready 文件;不存在返回 None。"""
class RpaTrigger(Protocol):
"""收料 RPA 触发协议(DBS/Crane 共用)。"""
def trigger(self, *, source_code: str, business_date: str, reason: str) -> dict[str, Any]:
"""触发一次收料抓取,返回 {'ok': bool, 'callback_id'|'error_code': ...}。"""
def ensure_receipt_file_ready(
*,
source_code: str,
business_date: str,
repository: ReceiptFileRepository,
rpa_trigger: RpaTrigger,
active_source_job_key: str | None = None,
) -> FilePreparationResult:
"""确保来源当日 ready 文件可用。
Args:
source_code: 来源实例编码。
business_date: 业务日期(YYYY-MM-DD)。
repository: ready 文件仓库。
rpa_trigger: RPA 触发器。
active_source_job_key: 活动 Source Job 键;非空时绑定已有任务不重复触发。
Returns:
FilePreparationResult(file_ready / waiting_rpa_callback / failed)。
"""
ready = repository.latest_ready_file(source_code=source_code, business_date=business_date)
if ready is not None:
return FilePreparationResult(stage=STAGE_FILE_READY, file=ready)
if active_source_job_key is not None:
# 已有活动抓取任务:绑定等待,不重复触发。
return FilePreparationResult(stage=STAGE_WAITING_RPA)
outcome = rpa_trigger.trigger(
source_code=source_code,
business_date=business_date,
reason="precheck_missing_ready_file",
)
outcome = outcome if isinstance(outcome, dict) else {}
if outcome.get("ok"):
return FilePreparationResult(stage=STAGE_WAITING_RPA)
return FilePreparationResult(
stage=STAGE_FAILED,
error_code=str(outcome.get("error_code") or "RPA_TRIGGER_FAILED"),
error_message=str(outcome.get("error_message") or "rpa trigger failed"),
)
@@ -0,0 +1,80 @@
"""services/in_transit_transfer/gateway_adapter.py
用途:把调拨的 ERP 访问收敛为通过 Integration Connector CapabilityGateway 调用
(query_inventory 是首个配置绑定消费者)。
依赖:integration_connector.gateway / capability、erp_adapter.InventoryQuery/ErpQueryTimeoutError。
逻辑:领域只调 query_inventory 能力;外部系统差异全在连接器层。create_transfer /
verify_duplicate 留待调拨执行阶段(Phase 2)接线。
"""
from __future__ import annotations
from decimal import Decimal
from typing import Any
from app.core.errors import AppError
from app.services.in_transit_transfer.erp_adapter import ErpQueryTimeoutError, InventoryQuery
QUERY_INVENTORY_CAPABILITY = "in_transit_transfer.query_inventory"
class CapabilityErpAdapter:
"""把调拨 query_inventory 收敛为通过 CapabilityGateway 调用。
Args:
gateway: 可选 Gateway;缺省用 get_capability_gateway()(可注入替身测试)。
"""
def __init__(self, gateway: Any | None = None) -> None:
self._gateway = gateway
def _gateway_or_default(self):
if self._gateway is not None:
return self._gateway
from app.services.integration_connector.gateway import get_capability_gateway
return get_capability_gateway()
def query_inventory(
self,
*,
operation_id: str,
run_no: str,
attempt_no: int,
invoice_no: str,
erp_org: str,
from_warehouse: str,
to_warehouse: str,
quantity: Decimal,
) -> InventoryQuery:
"""查询外部系统库存(经连接器框架)。
Args/Raises:
与 erp_adapter.ErpAdapter.query_inventory 一致;超时→ErpQueryTimeoutError;
写失败→AppError(预检把它归为来源失败)。P1 用默认绑定(context={});
来源专属绑定待 P2/P3。
"""
result = self._gateway_or_default().call(
capability=QUERY_INVENTORY_CAPABILITY,
context={},
params={
"invoice_no": invoice_no,
"from_warehouse": from_warehouse,
"to_warehouse": to_warehouse,
"quantity": quantity,
},
operation_id=operation_id,
)
if result.status == "timeout":
raise ErpQueryTimeoutError()
if result.status != "success":
raise AppError(
code=result.error_code or "INTEGRATION.CALL_FAILED",
message=result.error_message or "query_inventory failed",
http_status=503,
retryable=False,
)
data = result.data or {}
found = bool(data.get("found"))
qty = data.get("quantity")
return InventoryQuery(found=found, quantity=Decimal(str(qty)) if qty is not None else None)
@@ -0,0 +1,91 @@
"""在途调拨 Invoice 多行汇总与冲突阻断。
用途:相同 Invoice 多行只汇总收料数量,并永久保留原始 Sheet/行号/文件版本;
同一 Invoice 出现多料号或多收料日期时整单阻断(InvoiceConflictError)。
依赖:app.core.errors.AppError、contracts.RawLineRefDTO。
逻辑:汇总键 (source_code, invoice_no);冲突判定基于料号与收料日期。
"""
from __future__ import annotations
from dataclasses import dataclass
from datetime import date
from decimal import Decimal
from typing import Iterable
from app.core.errors import AppError
from app.services.in_transit_transfer.contracts import TRANSFER_INVOICE_CONFLICT, RawLineRefDTO
from app.services.in_transit_transfer.file_parser import ParsedReceiptRow
@dataclass(frozen=True)
class AggregatedInvoice:
"""单 Invoice 汇总结果(含原始行追溯)。"""
source_code: str
invoice_no: str
material_no: str
material_name: str
specification: str
receipt_date: date
receipt_quantity: Decimal
raw_lines: tuple[RawLineRefDTO, ...]
class InvoiceConflictError(AppError):
"""同一 Invoice 出现冲突(多料号/多收料日期),整单阻断。"""
def __init__(self, message: str = "invoice conflict", *, invoice_no: str, conflict: str):
super().__init__(
code=TRANSFER_INVOICE_CONFLICT,
message=message,
http_status=422,
details={"invoice_no": invoice_no, "conflict": conflict},
)
def aggregate_invoices(rows: Iterable[ParsedReceiptRow], *, file_version: str = "v1") -> list[AggregatedInvoice]:
"""按 Invoice 汇总收料数量并保留原始行证据。
Args:
rows: 已校验的解析行。
file_version: 当前文件版本(写入原始行追溯)。
Returns:
汇总后的 Invoice 列表(按 Invoice 排序)。
Raises:
InvoiceConflictError: 同一 Invoice 多料号或多收料日期。
"""
grouped: dict[tuple[str, str], list[ParsedReceiptRow]] = {}
for row in rows:
grouped.setdefault((row.source_code, row.invoice_no), []).append(row)
invoices: list[AggregatedInvoice] = []
for (source_code, invoice_no), group in sorted(grouped.items()):
material_nos = {row.material_no for row in group}
dates = {row.receipt_date for row in group}
if len(material_nos) > 1:
raise InvoiceConflictError(
invoice_no=invoice_no,
conflict=f"multiple_material_no: {sorted(material_nos)}",
)
if len(dates) > 1:
raise InvoiceConflictError(
invoice_no=invoice_no,
conflict=f"multiple_receipt_date: {sorted(str(item) for item in dates)}",
)
first = group[0]
raw_lines = tuple(
RawLineRefDTO(sheet=row.sheet, row_no=row.row_no, file_version=file_version)
for row in group
)
invoices.append(AggregatedInvoice(
source_code=source_code,
invoice_no=invoice_no,
material_no=first.material_no,
material_name=first.material_name,
specification=first.specification,
receipt_date=first.receipt_date,
receipt_quantity=sum((row.receipt_quantity for row in group), Decimal("0")),
raw_lines=raw_lines,
))
return invoices
@@ -0,0 +1,66 @@
"""在途调拨人工关闭服务。
用途:将异常项标记为 manually_closed(原因必填、永久排除、历史保留)。
依赖:models、status、audit、contracts。
逻辑:result_unknown / success / duplicate_success / manually_closed 禁止关闭。
"""
from __future__ import annotations
from app import db
from app.core.errors import NotFoundError, ValidationError
from app.models import TransferInvoiceItem
from app.services.in_transit_transfer import status as status_machine
from app.services.in_transit_transfer.audit import build_transfer_audit_event
from app.services.in_transit_transfer.contracts import TRANSFER_MANUAL_CLOSE_REASON_REQUIRED
def manual_close_item(*, item_id: int, reason: str, actor_id: int | None = None, request_id: str | None = None) -> dict:
"""人工关闭一个异常 Invoice。
Args:
item_id: TransferInvoiceItem.id。
reason: 关闭原因(必填)。
actor_id / request_id: 审计上下文。
Returns:
{"item_id": ..., "status": "manually_closed"}。
Raises:
ValidationError: 原因缺失或状态不可关闭。
NotFoundError: item 不存在。
"""
reason_value = str(reason or "").strip()
if not reason_value:
raise ValidationError("manual close reason is required", code=TRANSFER_MANUAL_CLOSE_REASON_REQUIRED)
item = db.session.get(TransferInvoiceItem, item_id)
if item is None:
raise NotFoundError("transfer invoice item not found", code="TRANSFER.ITEM_NOT_FOUND")
if item.status == status_machine.TransferStatus.RESULT_UNKNOWN.value:
raise ValidationError("result_unknown is read-only; follow manual verification SOP", code="TRANSFER_RESULT_UNKNOWN")
if item.status in {
status_machine.TransferStatus.SUCCESS.value,
status_machine.TransferStatus.DUPLICATE_SUCCESS.value,
status_machine.TransferStatus.MANUALLY_CLOSED.value,
}:
raise ValidationError(f"item status {item.status} is not closeable", code="TRANSFER.MANUAL_CLOSE_NOT_ALLOWED")
before_status = item.status
item.status = status_machine.TransferStatus.MANUALLY_CLOSED.value
item.result_code = "manually_closed"
item.result_message = reason_value
item.manually_closed_reason = reason_value
db.session.add(build_transfer_audit_event(
event_type="TRANSFER_ITEM_MANUALLY_CLOSED",
aggregate_type="transfer_item",
aggregate_id=str(item.id),
run_no=item.run.run_no if item.run else None,
invoice_no=item.invoice_no,
item_id=str(item.id),
actor_type="user",
actor_id=str(actor_id) if actor_id is not None else None,
request_id=request_id,
result="success",
before={"status": before_status},
after={"status": item.status, "reason": reason_value},
))
db.session.commit()
return {"item_id": item.id, "status": item.status}
@@ -0,0 +1,56 @@
"""在途调拨运营指标。
用途:从数据库现状投影成功率、失败类型、待处理老化与通知失败等指标,
供运营看板与告警使用。
依赖:models、backlog_service。
逻辑:指标只读,不触发任何外部调用。
"""
from __future__ import annotations
from datetime import datetime
from typing import Any
from app import db
from app.models import TransferInvoiceItem, TransferRun
from app.services.in_transit_transfer.backlog_service import backlog_summary
from app.services.in_transit_transfer.status import TransferNotificationStatus
def collect_metrics(*, now: datetime | None = None) -> dict[str, Any]:
"""采集调拨域指标。
Args:
now: 判定时刻(老化计算用)。
Returns:
{"runs": {...}, "items": {...}, "backlog": {...}}。
"""
runs_by_status: dict[str, int] = {}
for (status,) in db.session.query(TransferRun.status).all():
runs_by_status[str(status)] = runs_by_status.get(str(status), 0) + 1
notification_failed_runs = TransferRun.query.filter_by(
notification_status=TransferNotificationStatus.FAILED.value,
).count()
items_by_status: dict[str, int] = {}
for (status,) in db.session.query(TransferInvoiceItem.status).all():
items_by_status[str(status)] = items_by_status.get(str(status), 0) + 1
backlog = backlog_summary(now=now)
return {
"runs": {
**runs_by_status,
"notification_failed_runs": notification_failed_runs,
},
"items": items_by_status,
"backlog": {
"recoverable": backlog.recoverable_count,
"closed": backlog.closed_count,
"unknown": backlog.unknown_count,
"aging": {
"warn_3d": backlog.warn_3d,
"escalate_5d": backlog.escalate_5d,
"critical_7d": backlog.critical_7d,
},
},
}
@@ -0,0 +1,75 @@
"""在途调拨通用异动/移动表领域字段契约。
用途:定义调拨消费的异动(入库/出库/收料/出货)文件领域字段——业务定死、不配置化。
未来出货/入库 Excel 复用同一套字段,靠 in_out_flag 区分方向。
依赖:标准库 dataclasses / enum。
逻辑:字段清单是 immutable 常量;幂等键为 doc_no,严格数量字段为 quantity,
成熟过滤字段为 movement_date;字段映射由 movement_parser 完成。
"""
from __future__ import annotations
from dataclasses import dataclass
from enum import StrEnum
class MovementFieldValueType(StrEnum):
"""领域字段值类型(校验与展示共用)。"""
TEXT = "text"
DECIMAL = "decimal"
DATE = "date"
@dataclass(frozen=True)
class MovementField:
"""单个定死异动字段契约。
Args:
code: 稳定字段名(运行时契约)。
label: 业务中文名。
value_type: 值类型(text / decimal / date)。
is_identity: 是否参与幂等/匹配键。
required: 是否必填(缺省阻断)。
"""
code: str
label: str
value_type: MovementFieldValueType
is_identity: bool = False
required: bool = False
# 定死的 10 个通用异动字段(领域契约,不配置化)。
MOVEMENT_FIELDS: tuple[MovementField, ...] = (
MovementField("doc_no", "单号", MovementFieldValueType.TEXT, is_identity=True, required=True),
MovementField("line_no", "项次", MovementFieldValueType.TEXT),
MovementField("in_out_flag", "进出库别", MovementFieldValueType.TEXT),
MovementField("material_code", "料号", MovementFieldValueType.TEXT, is_identity=True, required=True),
MovementField("material_name", "品名", MovementFieldValueType.TEXT),
MovementField("warehouse_code", "仓库", MovementFieldValueType.TEXT),
MovementField("storage_code", "储位", MovementFieldValueType.TEXT),
MovementField("lot_no", "批号", MovementFieldValueType.TEXT),
MovementField("quantity", "数量", MovementFieldValueType.DECIMAL, required=True),
MovementField("movement_date", "异动日期", MovementFieldValueType.DATE, is_identity=True, required=True),
)
def movement_match_key() -> str:
"""调拨幂等/汇总键:单号 doc_no。"""
return "doc_no"
def movement_quantity_field() -> str:
"""严格数量匹配字段:数量 quantity。"""
return "quantity"
def movement_identity_fields() -> set[str]:
"""参与幂等/匹配判定的字段集(doc_no / material_code / movement_date)。"""
return {field.code for field in MOVEMENT_FIELDS if field.is_identity}
def movement_field_codes() -> set[str]:
"""全部定死字段名集合。"""
return {field.code for field in MOVEMENT_FIELDS}
@@ -0,0 +1,125 @@
"""在途调拨真实异动(收料/出货)文件仓库。
用途:读取货代收料链路已落库的 ShippingReceiptReportFile(对象存储原始 xlsx),
用该来源收料配置绑定的 movement 解析规则(purpose='movement',端点=定死
领域字段 MOVEMENT_FIELDS)的 field_mapping 把列映射为领域行,产出 ReadyReceiptFile。
依赖:ShippingReceiptReportFile / ShippingReceiptReportConfig / file_asset_storage、
movement_contract、openpyxl。
逻辑:按来源取最新未过期(未清理)收料文件;无绑定 movement profile 或文件缺失时
返回 None(fail-closed),绝不伪造 ready 文件。行完整校验由下游 file_parser 完成。
"""
from __future__ import annotations
from io import BytesIO
from typing import Any, Mapping
from app.services.file_assets.storage import file_asset_storage
from app.services.in_transit_transfer.file_preparation import ReadyReceiptFile
class ShippingReceiptFileRepository:
"""真实收料/异动 ready 文件仓库(复用货代收料归档 + movement 解析规则)。"""
def __init__(self) -> None:
self._storage = file_asset_storage
def latest_ready_file(self, *, source_code: str, business_date: str) -> ReadyReceiptFile | None:
"""返回该来源最新未过期收料文件;无绑定规则或文件缺失时返回 None。
Args:
source_code: 来源实例编码。
business_date: 业务日期(用于展示/匹配成熟度,不强制匹配文件日期)。
Returns:
ReadyReceiptFile(rows 为领域字段名 dict)或 None。
"""
from app.models import ShippingInventorySource, ShippingReceiptReportConfig, ShippingReceiptReportFile
source = ShippingInventorySource.query.filter_by(source_code=source_code, enabled=True).first()
if source is None:
return None
config = ShippingReceiptReportConfig.query.filter_by(inventory_source_id=source.id, enabled=True).first()
if config is None or config.parsing_profile_id is None:
return None
profile = config.parsing_profile
if profile is None or profile.status != 'published' or profile.purpose != 'movement':
return None
report = (
ShippingReceiptReportFile.query
.join(ShippingReceiptReportFile.unit_run)
.filter(
ShippingReceiptReportFile.unit_run.has(source_code=source_code),
ShippingReceiptReportFile.archive_deleted_at.is_(None),
)
.order_by(ShippingReceiptReportFile.created_at.desc(), ShippingReceiptReportFile.id.desc())
.first()
)
if report is None:
return None
data = self._storage.get_bytes(report.storage_key)
rows = _extract_movement_rows(
data,
field_mapping=dict((profile.definition_json or {}).get('field_mapping') or {}),
sheet_name=str((profile.definition_json or {}).get('sheet_name') or '').strip() or None,
header_row_index=(profile.definition_json or {}).get('header_row_index'),
)
return ReadyReceiptFile(
source_code=source_code,
business_date=business_date,
file_no=report.original_filename or str(report.id),
file_version=f"sha256:{report.sha256}"[:64],
checksum=report.sha256,
rows=tuple(rows),
)
def _extract_movement_rows(
data: bytes,
*,
field_mapping: Mapping[str, str],
sheet_name: str | None = None,
header_row_index: int | None = None,
) -> list[dict[str, Any]]:
"""从 xlsx 字节按 movement field_mapping 提取领域行 dict。
field_mapping: {定死领域字段 code: Excel 表头别名}(端点必须是 MOVEMENT_FIELDS 的 code)。
输出以领域字段 code 为 key 的行,供 file_parser.parse_movement_rows 校验。
"""
from openpyxl import load_workbook
from app.services.shipping_notice.inventory_snapshot import find_inventory_header_row_index
wb = load_workbook(filename=BytesIO(data), data_only=True, read_only=True)
try:
if sheet_name and sheet_name in wb.sheetnames:
ws = wb[sheet_name]
else:
ws = wb.active
raw_rows: list[list[Any]] = [list(row) for row in ws.iter_rows(values_only=True)]
finally:
wb.close()
if not raw_rows:
return []
header_idx: int | None = None
if header_row_index is not None:
idx = int(header_row_index) - 1
if 0 <= idx < len(raw_rows):
header_idx = idx
if header_idx is None:
header_idx = find_inventory_header_row_index(raw_rows)
headers = [str(c or '').strip() for c in raw_rows[header_idx]]
data_rows = [list(r) for r in raw_rows[header_idx + 1:] if r]
header_to_code = {str(alias).strip(): str(code).strip() for code, alias in field_mapping.items()}
return [_map_header_row(headers, row, header_to_code) for row in data_rows]
def _map_header_row(headers: list[str], row: list[Any], header_to_code: dict[str, str]) -> dict[str, Any]:
"""把一行原始单元格按表头别名映射为定死领域字段 dict。"""
output: dict[str, Any] = {}
for index, header in enumerate(headers):
code = header_to_code.get(header)
if code and index < len(row):
output[code] = row[index]
return output
@@ -0,0 +1,84 @@
"""在途调拨企业微信汇总通知。
用途:每个非空 Run 恰好一条汇总通知;空数据不通知;通知失败记录
notification_failed 且不改变 ERP 业务结果(run.status 保持)。
依赖:models、audit、typing.Protocol。
逻辑:通知状态独立于 ERP 状态;已成功投递幂等(每个 Run 一条)。
"""
from __future__ import annotations
from typing import Any, Protocol
from app import db
from app.core.errors import NotFoundError
from app.models import TransferRun
from app.services.in_transit_transfer.audit import build_transfer_audit_event
from app.services.in_transit_transfer.status import TransferNotificationStatus
class WeComSender(Protocol):
"""企业微信汇总通知协议(测试注入 FakeWeCom)。"""
def send_summary(self, *, run_no: str, summary: dict[str, Any],
recipients: list[str], excel_path: str | None = None) -> dict[str, Any]:
"""发送一次汇总通知。"""
def notify_run_summary(*, run_no: str, sender: WeComSender, recipients: list[str] | None = None,
excel_path: str | None = None) -> dict[str, Any]:
"""为 Run 发送一条汇总通知(幂等)。
Args:
run_no: Run 编号。
sender: 企微发送器。
recipients: 接收人列表(缺省空)。
excel_path: 异常 Excel 附件路径(可空)。
Returns:
{"run_no", "notification_status", "delivered"};空数据返回 skipped。
Raises:
NotFoundError: Run 不存在。
"""
run = db.session.query(TransferRun).filter_by(run_no=str(run_no).strip()).first()
if run is None:
raise NotFoundError("run not found", code="TRANSFER.RUN_NOT_FOUND")
if not run.items:
# 空数据 Run:不通知(产品决策 C5:仅非空 Run 通知)。
return {"run_no": run.run_no, "notification_status": run.notification_status, "delivered": False, "skipped": "no_data"}
if run.notification_status == TransferNotificationStatus.SUCCESS.value:
# 已成功投递:幂等跳过,保证每个 Run 恰好一条。
return {"run_no": run.run_no, "notification_status": run.notification_status, "delivered": False}
summary = {
"run_no": run.run_no,
"status": run.status,
"business_date": run.business_date,
"counts": dict(run.counts_json or {}),
"result_summary": dict(run.result_summary_json or {}),
}
outcome = sender.send_summary(
run_no=run.run_no, summary=summary, recipients=list(recipients or []), excel_path=excel_path,
)
outcome = outcome if isinstance(outcome, dict) else {}
failed = str(outcome.get("status") or "success") != "success"
run.notification_status = TransferNotificationStatus.FAILED.value if failed else TransferNotificationStatus.SUCCESS.value
if failed:
run.notification_error_code = str(outcome.get("error_code") or "WECOM_SEND_FAILED")
run.notification_error_message = str(outcome.get("error_message") or "")
# 关键:通知失败绝不修改 run.status(ERP 业务结果保持)。
db.session.add(build_transfer_audit_event(
event_type="TRANSFER_NOTIFICATION",
aggregate_type="transfer_run",
aggregate_id=run.run_no,
run_no=run.run_no,
actor_type="worker",
result="failure" if failed else "success",
before={"status": run.status, "notification_status": "pending"},
after={"status": run.status, "notification_status": run.notification_status},
))
db.session.commit()
return {
"run_no": run.run_no,
"notification_status": run.notification_status,
"delivered": True,
}
@@ -0,0 +1,83 @@
"""在途调拨执行编排(Run 生命周期辅助)。
用途:创建执行 Run(关联预检与可执行明细、置 executing、记录确认)、
按明细终态收尾 Run(success / partial_failed)。
依赖:models、status、precheck_service.TransferDeps。
逻辑:同一预检只允许创建一个执行 Run(confirmed_at 防重复);重复创建 409。
"""
from __future__ import annotations
import uuid
from datetime import datetime
from app import db
from app.core.errors import ConflictError
from app.models import TransferInvoiceItem, TransferPrecheck, TransferRun
from app.services.in_transit_transfer import status as status_machine
from app.services.in_transit_transfer.precheck_service import TransferDeps
EXECUTION_CONFLICT_CODE = "TRANSFER.PRECHECK_ALREADY_EXECUTED"
def create_execution_run(
precheck: TransferPrecheck,
*,
deps: TransferDeps, # noqa: ARG001 —— 预留并发/锁参数扩展
actor_id: int | None = None,
selected_invoice_nos: set[str] | None = None,
) -> TransferRun:
"""为已就绪预检创建执行 Run 并关联选中的可执行明细。
Args:
precheck: 已预检(ready_to_execute)对象。
deps: 依赖集合(预留)。
actor_id: 确认操作者。
selected_invoice_nos: 选择范围(缺省关联全部可执行项)。
Returns:
状态为 executing 的 TransferRun。
Raises:
ConflictError: 预检已确认(重复执行)。
"""
if precheck.confirmed_at is not None:
raise ConflictError(
"precheck already executed", code=EXECUTION_CONFLICT_CODE,
)
run_no = f"RUN-{str(precheck.business_date).replace('-', '')}-{uuid.uuid4().hex[:6].upper()}"
run = TransferRun(
run_no=run_no,
trigger_type="manual",
business_date=precheck.business_date,
status=status_machine.TransferRunStatus.EXECUTING.value,
source_codes_json=list(precheck.scope_json.get("source_codes") or []),
counts_json=dict(precheck.counts_json or {}),
)
db.session.add(run)
db.session.flush()
precheck.run_id = run.id
precheck.status = status_machine.TransferRunStatus.EXECUTING.value
precheck.confirmed_at = datetime.utcnow()
precheck.confirmed_by = actor_id
for item in precheck.items:
if item.status != status_machine.TransferStatus.READY_TO_EXECUTE.value or item.run_id is not None:
continue
if selected_invoice_nos is not None and item.invoice_no not in selected_invoice_nos:
continue
item.run_id = run.id
item.status = status_machine.TransferStatus.EXECUTING.value
item.attempt_no += 1
db.session.flush()
return run
def finalize_run(run: TransferRun, items: list[TransferInvoiceItem]) -> None:
"""按明细终态汇总 Run 状态(全部 success/duplicate_success → success,否则 partial_failed)。"""
statuses = {str(item.status) for item in items}
terminal_ok = {status_machine.TransferStatus.SUCCESS.value, status_machine.TransferStatus.DUPLICATE_SUCCESS.value}
if statuses and statuses <= terminal_ok:
run.status = status_machine.TransferRunStatus.SUCCESS.value
else:
run.status = status_machine.TransferRunStatus.PARTIAL_FAILED.value
run.completed_at = datetime.utcnow()
@@ -0,0 +1,578 @@
"""在途调拨预检服务。
用途:编排"文件准备 → 解析 → Invoice 汇总 → D+1 成熟过滤 → ERP 库存查询 →
严格数量匹配 → 预检快照与 Hash",并支持预检进度恢复(restore)。
依赖:file_preparation / file_parser / invoice_aggregator / erp_adapter /
date_policy / quantity / contracts / audit / models。
逻辑:来源实例独立处理,任一来源失败不阻断其他来源;当天收料不查询 ERP;
预检 Hash 由冻结快照复算;create_precheck 落库 Run + Precheck + Items。
"""
from __future__ import annotations
import uuid
from dataclasses import asdict, dataclass, field
from datetime import date, datetime, timedelta
from decimal import Decimal
from typing import Any, Protocol
from app import db
from app.core.errors import AppError, NotFoundError, ValidationError
from app.models import TransferInvoiceItem, TransferPrecheck, TransferRun
from app.services.in_transit_transfer import status as status_machine
from app.services.in_transit_transfer.audit import canonical_hash
from app.services.in_transit_transfer.contracts import (
PrecheckCountsDTO,
PrecheckInvoiceItemDTO,
PrecheckSummaryDTO,
RawLineRefDTO,
)
from app.services.in_transit_transfer.date_policy import (
MATURITY_ELIGIBLE,
MATURITY_FUTURE,
MATURITY_NOT_MATURED,
maturity_status,
)
from app.services.in_transit_transfer.erp_adapter import ErpQueryTimeoutError
from app.services.in_transit_transfer.file_parser import (
ParsedReceiptRow,
ReceiptFileSchemaError,
parse_receipt_rows,
)
from app.services.in_transit_transfer.file_preparation import (
ReadyReceiptFile,
ReceiptFileRepository,
RpaTrigger,
ensure_receipt_file_ready,
)
from app.services.in_transit_transfer.invoice_aggregator import (
InvoiceConflictError,
aggregate_invoices,
)
from app.services.in_transit_transfer.quantity import classify_quantity_match
from app.services.in_transit_transfer.strategy import (
TransferStrategyPolicy,
default_strategy,
)
ROUTE_NOT_RESOLVED_CODE = "TRANSFER.ROUTE_NOT_RESOLVED"
# 明细结果值(对应 Invoice 项状态)
RESULT_EXECUTABLE = "executable"
RESULT_NOT_MATURED = "not_matured"
RESULT_QUANTITY_MISMATCH = "blocked_quantity_mismatch"
RESULT_INVENTORY_NOT_FOUND = "blocked_inventory_not_found"
RESULT_FUTURE_DATE = "blocked_future_date"
RESULT_ERP_QUERY_TIMEOUT = "erp_query_timeout"
@dataclass(frozen=True)
class RouteMapping:
"""来源路由:ERP 组织 / 拨出仓(ERP 在途仓)/ 拨入仓(ERP 映射仓)。"""
erp_org: str
from_warehouse: str
to_warehouse: str
class RouteNotResolvedError(AppError):
"""来源实例缺少路由归属映射(fail-closed)。"""
def __init__(self, *, source_code: str):
super().__init__(
code=ROUTE_NOT_RESOLVED_CODE,
message=f"route not resolved for source {source_code}",
http_status=422,
details={"source_code": source_code},
)
class RouteResolver(Protocol):
"""来源路由解析协议(路由归属规则冻结前由 Fake/门禁兜底)。"""
def resolve(self, *, source_code: str, invoice_no: str) -> RouteMapping:
"""返回 Invoice 的路由;无法归属时抛 RouteNotResolvedError。"""
@dataclass(frozen=True)
class SourceProgressDTO:
"""来源实例级进度(决策 18:来源隔离展示)。"""
source_code: str
stage: str
file_no: str | None = None
file_version: str | None = None
checksum: str | None = None
error_code: str | None = None
error_message: str | None = None
@dataclass(frozen=True)
class PrecheckRunResult:
"""一次预检运行的完整结果。"""
summary: PrecheckSummaryDTO
items: tuple[PrecheckInvoiceItemDTO, ...]
sources: tuple[SourceProgressDTO, ...]
@dataclass(frozen=True)
class TransferDeps:
"""预检/执行依赖集合(测试注入 Fake 替身)。"""
file_repository: ReceiptFileRepository
rpa_trigger: RpaTrigger
route_resolver: RouteResolver
erp: Any
strategy: TransferStrategyPolicy = field(default_factory=default_strategy)
def _summary_status(sources: tuple[SourceProgressDTO, ...], counts: PrecheckCountsDTO) -> str:
"""预检状态:存在未完成来源 → file_pending;否则按可执行数定。"""
if any(source.stage not in {"file_ready"} for source in sources):
return "file_pending"
if counts.executable_count > 0:
return "ready_to_execute"
return "success"
def run_precheck(
*,
source_codes: list[str],
business_date: str,
deps: TransferDeps,
active_source_job_key: str | None = None,
run_no: str = "RUN-PENDING",
) -> PrecheckRunResult:
"""执行一次只读预检(不写 ERP)。
Args:
source_codes: 来源实例列表(DBS/Crane 仅分组,实例为执行边界)。
business_date: 业务日期 T(YYYY-MM-DD)。
deps: 注入的文件仓库 / RPA / 路由 / ERP 依赖。
active_source_job_key: 活动 Source Job 键(缺文件时绑定已有任务)。
run_no: Run 编号(创建 Run 前可为占位)。
Returns:
PrecheckRunResult(摘要 + 明细 + 来源进度)。
Raises:
ValidationError: source_codes 为空。
"""
if not source_codes:
raise ValidationError("source_codes is required")
validate_strategy = deps.strategy
sources: list[SourceProgressDTO] = []
items: list[PrecheckInvoiceItemDTO] = []
file_snapshot: dict[str, Any] = {}
for source_code in source_codes:
source_stage: SourceProgressDTO
try:
prepared = ensure_receipt_file_ready(
source_code=source_code,
business_date=business_date,
repository=deps.file_repository,
rpa_trigger=deps.rpa_trigger,
active_source_job_key=active_source_job_key,
)
if prepared.stage != "file_ready" or prepared.file is None:
sources.append(SourceProgressDTO(
source_code=source_code,
stage=prepared.stage,
error_code=prepared.error_code,
error_message=prepared.error_message,
))
continue
ready_file = prepared.file
file_snapshot[source_code] = {
"file_no": ready_file.file_no,
"file_version": ready_file.file_version,
"checksum": ready_file.checksum,
}
parsed = parse_receipt_rows(source_code=source_code, rows=ready_file.rows)
invoices = aggregate_invoices(parsed, file_version=ready_file.file_version)
source_items = _precheck_invoices(
invoices=invoices,
source_code=source_code,
business_date=business_date,
ready_file=ready_file,
deps=deps,
run_no=run_no,
)
items.extend(source_items)
sources.append(SourceProgressDTO(
source_code=source_code,
stage="file_ready",
file_no=ready_file.file_no,
file_version=ready_file.file_version,
checksum=ready_file.checksum,
))
except (ReceiptFileSchemaError, InvoiceConflictError) as exc:
sources.append(SourceProgressDTO(
source_code=source_code, stage="failed",
error_code=exc.code, error_message=exc.message,
))
except RouteNotResolvedError as exc:
sources.append(SourceProgressDTO(
source_code=source_code, stage="failed",
error_code=exc.code, error_message=exc.message,
))
except Exception as exc: # noqa: BLE001 —— 来源级隔离,不阻断其他来源
sources.append(SourceProgressDTO(
source_code=source_code, stage="failed",
error_code="TRANSFER.SOURCE_PRECheck_ERROR",
error_message=str(exc),
))
counts = PrecheckCountsDTO(
file_invoice_count=sum(
1 for item in items
),
not_matured_count=sum(1 for item in items if item.result == RESULT_NOT_MATURED),
prechecked_count=sum(1 for item in items if item.result != RESULT_NOT_MATURED),
executable_count=sum(1 for item in items if item.result == RESULT_EXECUTABLE),
blocked_count=sum(1 for item in items if item.result.startswith("blocked_")),
)
estimated_quantity = sum(
(item.to_quantity for item in items if item.result == RESULT_EXECUTABLE), Decimal("0")
)
snapshot = {
"scope": sorted(set(source_codes)),
"business_date": business_date,
"file_snapshot": file_snapshot,
"counts": {
"file_invoice_count": counts.file_invoice_count,
"not_matured_count": counts.not_matured_count,
"prechecked_count": counts.prechecked_count,
"executable_count": counts.executable_count,
"blocked_count": counts.blocked_count,
},
"items": [
{
"source_code": item.source_code,
"invoice_no": item.invoice_no,
"from_warehouse": item.from_warehouse,
"to_warehouse": item.to_warehouse,
"receipt_quantity": str(item.to_quantity),
"erp_quantity": str(item.from_quantity) if item.from_quantity is not None else None,
"result": item.result,
}
for item in items
],
}
precheck_hash = f"sha256:{canonical_hash(snapshot)}"
sources_tuple = tuple(sources)
summary = PrecheckSummaryDTO(
precheck_id="", # 落库时回填
status=_summary_status(sources_tuple, counts),
business_date=business_date,
eligible_receipt_date_to=str(
(date.fromisoformat(business_date) - timedelta(days=1))
),
expires_at="",
counts=counts,
estimated_transfer_quantity=str(estimated_quantity),
estimated_erp_write_count=counts.executable_count,
precheck_hash=precheck_hash,
)
return PrecheckRunResult(summary=summary, items=tuple(items), sources=sources_tuple)
def _precheck_invoices(
*,
invoices: list,
source_code: str,
business_date: str,
ready_file: ReadyReceiptFile,
deps: TransferDeps,
run_no: str,
) -> list[PrecheckInvoiceItemDTO]:
"""对单个来源的汇总 Invoice 逐项预检(成熟过滤 → 路由 → ERP → 匹配)。"""
output: list[PrecheckInvoiceItemDTO] = []
for invoice in invoices:
maturity = maturity_status(invoice.receipt_date, business_date)
raw = tuple(
RawLineRefDTO(sheet=line.sheet, row_no=line.row_no, file_version=line.file_version)
for line in invoice.raw_lines
)
receipt_date_iso = invoice.receipt_date.isoformat()
if maturity == MATURITY_NOT_MATURED:
output.append(PrecheckInvoiceItemDTO(
source_code=source_code, material_no=invoice.material_no,
material_name=invoice.material_name, specification=invoice.specification,
invoice_no=invoice.invoice_no, receipt_date=receipt_date_iso,
from_warehouse="", from_quantity=None,
to_warehouse="", to_quantity=invoice.receipt_quantity,
result=RESULT_NOT_MATURED, reason="receipt not matured until next business day",
raw_lines=raw,
))
continue
if maturity == MATURITY_FUTURE:
output.append(PrecheckInvoiceItemDTO(
source_code=source_code, material_no=invoice.material_no,
material_name=invoice.material_name, specification=invoice.specification,
invoice_no=invoice.invoice_no, receipt_date=receipt_date_iso,
from_warehouse="", from_quantity=None,
to_warehouse="", to_quantity=invoice.receipt_quantity,
result=RESULT_FUTURE_DATE, reason="future receipt date",
raw_lines=raw,
))
continue
route = deps.route_resolver.resolve(source_code=source_code, invoice_no=invoice.invoice_no)
operation_id = f"op-{uuid.uuid4().hex[:12]}"
try:
query = deps.erp.query_inventory(
operation_id=operation_id,
run_no=run_no,
attempt_no=1,
invoice_no=invoice.invoice_no,
erp_org=route.erp_org,
from_warehouse=route.from_warehouse,
to_warehouse=route.to_warehouse,
quantity=invoice.receipt_quantity,
)
except ErpQueryTimeoutError:
output.append(PrecheckInvoiceItemDTO(
source_code=source_code, material_no=invoice.material_no,
material_name=invoice.material_name, specification=invoice.specification,
invoice_no=invoice.invoice_no, receipt_date=receipt_date_iso,
from_warehouse=route.from_warehouse,
from_quantity=None, to_warehouse=route.to_warehouse,
to_quantity=invoice.receipt_quantity,
result=RESULT_ERP_QUERY_TIMEOUT, reason="erp query timeout",
raw_lines=raw,
))
continue
if not query.found:
output.append(PrecheckInvoiceItemDTO(
source_code=source_code, material_no=invoice.material_no,
material_name=invoice.material_name, specification=invoice.specification,
invoice_no=invoice.invoice_no, receipt_date=receipt_date_iso,
from_warehouse=route.from_warehouse,
from_quantity=None, to_warehouse=route.to_warehouse,
to_quantity=invoice.receipt_quantity,
result=RESULT_INVENTORY_NOT_FOUND, reason="erp inventory not found",
raw_lines=raw,
))
continue
match = classify_quantity_match(invoice.receipt_quantity, query.quantity)
output.append(PrecheckInvoiceItemDTO(
source_code=source_code, material_no=invoice.material_no,
material_name=invoice.material_name, specification=invoice.specification,
invoice_no=invoice.invoice_no, receipt_date=receipt_date_iso,
from_warehouse=route.from_warehouse,
from_quantity=query.quantity, to_warehouse=route.to_warehouse,
to_quantity=invoice.receipt_quantity,
result=match, reason="" if match == RESULT_EXECUTABLE else "strict quantity mismatch",
raw_lines=raw,
))
return output
def _item_status(result: str) -> str:
"""明细结果 → Invoice 项状态。"""
mapping = {
RESULT_EXECUTABLE: status_machine.TransferStatus.READY_TO_EXECUTE.value,
RESULT_NOT_MATURED: status_machine.TransferStatus.NOT_MATURED.value,
RESULT_FUTURE_DATE: status_machine.TransferStatus.BLOCKED_RECOVERABLE.value,
RESULT_ERP_QUERY_TIMEOUT: status_machine.TransferStatus.BLOCKED_RECOVERABLE.value,
RESULT_QUANTITY_MISMATCH: status_machine.TransferStatus.BLOCKED_RECOVERABLE.value,
RESULT_INVENTORY_NOT_FOUND: status_machine.TransferStatus.BLOCKED_RECOVERABLE.value,
}
return mapping.get(result, status_machine.TransferStatus.BLOCKED_RECOVERABLE.value)
def _generate_no(prefix: str, business_date: str) -> str:
"""生成稳定业务编号(TPC-YYYYMMDD-XXXX / RUN-...)。"""
compact = str(business_date).replace("-", "")
return f"{prefix}-{compact}-{uuid.uuid4().hex[:6].upper()}"
def create_precheck(
*,
source_codes: list[str],
business_date: str,
deps: TransferDeps,
active_source_job_key: str | None = None,
) -> PrecheckSummaryDTO:
"""运行预检并落库 TransferRun + TransferPrecheck + InvoiceItems。
Args:
source_codes / business_date / deps: 同 run_precheck。
Returns:
预检摘要(precheck_id 已回填)。
"""
run_no = _generate_no("RUN", business_date)
result = run_precheck(
source_codes=source_codes,
business_date=business_date,
deps=deps,
active_source_job_key=active_source_job_key,
run_no=run_no,
)
now = datetime.utcnow()
run = TransferRun(
run_no=run_no,
trigger_type="manual",
business_date=business_date,
status="prechecking",
source_codes_json=list(source_codes),
counts_json=asdict(result.summary.counts),
)
db.session.add(run)
db.session.flush()
# 来源级状态真相源:按 run 内每来源建一条 job((run_id, source_code) 唯一)。
# 来源准备流程阶段(file_ready/waiting_rpa_callback/failed 等)与 job 状态集已对齐。
from app.services.in_transit_transfer.source_job_service import create_source_job
_valid_job_statuses = {
'pending', 'checking_file', 'file_ready', 'waiting_rpa_callback', 'parsing',
'prechecking', 'executing', 'success', 'partial_failed', 'failed', 'cancelled',
}
for job_source in result.sources:
create_source_job(
run_id=run.id,
source_code=job_source.source_code,
status=job_source.stage if job_source.stage in _valid_job_statuses else 'pending',
)
precheck_no = _generate_no("TPC", business_date)
precheck = TransferPrecheck(
precheck_no=precheck_no,
run_id=run.id,
business_date=business_date,
status=result.summary.status,
scope_json={"source_codes": list(source_codes)},
file_snapshot_json={
stage.source_code: {
"file_no": stage.file_no,
"file_version": stage.file_version,
"checksum": stage.checksum,
}
for stage in result.sources
if stage.file_no
},
mapping_version="v0",
strategy_version="v0",
counts_json=asdict(result.summary.counts),
estimated_transfer_quantity=result.summary.estimated_transfer_quantity,
estimated_erp_write_count=result.summary.estimated_erp_write_count,
precheck_hash=result.summary.precheck_hash,
expires_at=now + timedelta(seconds=deps.strategy.confirm_ttl_seconds),
)
db.session.add(precheck)
db.session.flush()
for item in result.items:
db.session.add(TransferInvoiceItem(
precheck_id=precheck.id,
# 预检阶段不绑定执行 Run(run_id 在执行 Run 创建时由 orchestrator 关联)。
source_code=item.source_code,
invoice_no=item.invoice_no,
material_no=item.material_no,
material_name=item.material_name,
specification=item.specification,
receipt_date=item.receipt_date,
from_warehouse=item.from_warehouse or "",
to_warehouse=item.to_warehouse or "",
receipt_quantity=str(item.to_quantity),
erp_quantity=str(item.from_quantity) if item.from_quantity is not None else None,
status=_item_status(item.result),
result_code=item.result if item.result != RESULT_EXECUTABLE else None,
result_message=item.reason or None,
raw_lines_json=[
{"sheet": line.sheet, "row_no": line.row_no, "file_version": line.file_version}
for line in item.raw_lines
],
))
db.session.commit()
summary = PrecheckSummaryDTO(
precheck_id=precheck_no,
status=precheck.status,
business_date=precheck.business_date,
eligible_receipt_date_to=result.summary.eligible_receipt_date_to,
expires_at=precheck.expires_at.isoformat() if precheck.expires_at else "",
counts=result.summary.counts,
estimated_transfer_quantity=result.summary.estimated_transfer_quantity,
estimated_erp_write_count=result.summary.estimated_erp_write_count,
precheck_hash=result.summary.precheck_hash,
)
return summary
def restore_precheck(precheck_id: str) -> dict[str, Any]:
"""按 precheck_no 恢复预检进度与明细(页面刷新/会话恢复)。
Args:
precheck_id: 预检编号(TPC-...)。
Returns:
{"summary": {...}, "items": [...], "sources": [...]}。
Raises:
NotFoundError: 预检不存在。
"""
precheck = db.session.query(TransferPrecheck).filter_by(
precheck_no=str(precheck_id).strip()
).first()
if precheck is None:
raise NotFoundError("precheck not found", code="TRANSFER.PRECHECK_NOT_FOUND")
counts = PrecheckCountsDTO(**{
key: int(precheck.counts_json.get(key, 0))
for key in ("file_invoice_count", "not_matured_count", "prechecked_count",
"executable_count", "blocked_count")
})
summary = PrecheckSummaryDTO(
precheck_id=precheck.precheck_no,
status=precheck.status,
business_date=precheck.business_date,
eligible_receipt_date_to=str(
date.fromisoformat(precheck.business_date) - timedelta(days=1)
),
expires_at=precheck.expires_at.isoformat() if precheck.expires_at else "",
counts=counts,
estimated_transfer_quantity=precheck.estimated_transfer_quantity or "0",
estimated_erp_write_count=int(precheck.estimated_erp_write_count or 0),
precheck_hash=precheck.precheck_hash,
)
items = []
for item in sorted(precheck.items, key=lambda row: row.invoice_no):
items.append(PrecheckInvoiceItemDTO(
source_code=item.source_code,
material_no=item.material_no,
material_name=item.material_name,
specification=item.specification,
invoice_no=item.invoice_no,
from_warehouse=item.from_warehouse,
from_quantity=Decimal(item.erp_quantity) if item.erp_quantity else None,
to_warehouse=item.to_warehouse,
to_quantity=Decimal(item.receipt_quantity),
result=item.result_code or (
RESULT_EXECUTABLE if item.status == "ready_to_execute" else item.status
),
raw_lines=tuple(
RawLineRefDTO(
sheet=line.get("sheet", ""),
row_no=int(line.get("row_no", 0)),
file_version=line.get("file_version", ""),
)
for line in (item.raw_lines_json or [])
),
))
sources = [
SourceProgressDTO(
source_code=job.source_code,
stage=job.status,
file_no=job.file_no,
file_version=None,
checksum=job.file_sha256,
)
for job in (precheck.run.source_jobs if precheck.run else [])
] or [
SourceProgressDTO(source_code=code, stage="file_ready")
for code in (precheck.scope_json.get("source_codes") or [])
]
return {
"summary": summary,
"items": items,
"sources": sources,
}
@@ -0,0 +1,61 @@
"""在途调拨严格数量门禁。
用途:实现"收料数量 == ERP 账面库存 才可执行"的精确匹配规则,
禁止部分调拨、数量容差与隐式截断。
依赖:标准库 decimal。
逻辑:所有比较基于 Decimal 精确语义;非法数量(0/负数/非数字)在解析层拒绝。
"""
from __future__ import annotations
from decimal import Decimal, InvalidOperation
from typing import Any
# 匹配结果
MATCH_EXECUTABLE = "executable"
MATCH_QUANTITY_MISMATCH = "blocked_quantity_mismatch"
MATCH_INVENTORY_NOT_FOUND = "blocked_inventory_not_found"
class QuantityValidationError(ValueError):
"""收料数量非法(0、负数、非数字)。"""
def validate_receipt_quantity(value: Any) -> Decimal:
"""校验并归一化收料数量。
Args:
value: 数字或数字字符串。
Returns:
归一化后的 Decimal。
Raises:
QuantityValidationError: 非数字、0 或负数。
"""
try:
quantity = Decimal(str(value))
except (InvalidOperation, ValueError) as exc:
raise QuantityValidationError(f"invalid receipt quantity: {value!r}") from exc
if quantity <= 0:
raise QuantityValidationError(f"receipt quantity must be positive: {value!r}")
return quantity
def strict_quantities_equal(left: Any, right: Any) -> bool:
"""Decimal 精确相等比较(1.0 == 1.00)。"""
return Decimal(str(left)) == Decimal(str(right))
def classify_quantity_match(receipt_quantity: Any, erp_quantity: Any | None) -> str:
"""按严格相等规则分类数量匹配结果。
Args:
receipt_quantity: 收料数量。
erp_quantity: ERP 账面库存;None 表示无库存。
Returns:
'executable' | 'blocked_quantity_mismatch' | 'blocked_inventory_not_found'。
"""
if erp_quantity is None:
return MATCH_INVENTORY_NOT_FOUND
if strict_quantities_equal(receipt_quantity, erp_quantity):
return MATCH_EXECUTABLE
return MATCH_QUANTITY_MISMATCH
@@ -0,0 +1,57 @@
"""在途调拨收料回调桥。
用途:货代收料 RPA 回调落文件后,按来源推进调拨等待中的 TransferSourceJob:
success/有文件 → file_ready(绑定 file_no/sha256);failed/empty → failed。
依赖:models(TransferSourceJob)、datetime。
逻辑:只推进 status='waiting_rpa_callback' 的来源任务(门禁);无匹配则不动作,
避免回调迟到误推进其他阶段任务。SourceJob 状态为字符串常量(见 models)。
"""
from __future__ import annotations
from datetime import datetime
from app import db
from app.models import TransferSourceJob
_FILE_READY = 'file_ready'
_WAITING_RPA_CALLBACK = 'waiting_rpa_callback'
_FAILED = 'failed'
def advance_source_job_from_receipt_callback(
*, source_code: str, file_no: str | None = None, file_sha256: str | None = None,
callback_ok: bool = True, error_code: str | None = None, error_message: str | None = None,
) -> TransferSourceJob | None:
"""按来源推进最新等待回调的调拨来源任务。
Args:
source_code: 回调所属来源实例。
file_no: 收料文件号(success 时)。
file_sha256: 收料文件 sha256(success 时)。
callback_ok / error_code / error_message: 回调终态。
Returns:
被推进的任务;无等待任务或已终态时返回 None。
"""
job = (
TransferSourceJob.query
.filter_by(source_code=source_code, status=_WAITING_RPA_CALLBACK)
.order_by(TransferSourceJob.id.desc())
.first()
)
if job is None:
return None
if callback_ok and file_no:
job.status = _FILE_READY
job.file_no = file_no
job.file_sha256 = file_sha256
job.error_code = None
job.error_message = None
job.finished_at = datetime.utcnow()
else:
job.status = _FAILED
job.error_code = error_code or 'RPA_RECEIPT_CALLBACK_FAILED'
job.error_message = error_message or 'receipt rpa callback failed'
job.finished_at = datetime.utcnow()
db.session.flush()
return job
@@ -0,0 +1,101 @@
"""在途调拨真实收料 RPA 触发服务。
用途:为单个来源触发一次收料/异动 RPA 抓取(复用货代收料 trigger 链路),不创建排程。
按来源取 ShippingInventorySource + ShippingReceiptReportConfig + rpa_profile,
装配收料 trigger unit,调用 write_receipt_export_batch_trigger 原子写 trigger。
依赖:write_receipt_export_batch_trigger(默认 writer)、models。
逻辑:来源停用/收料配置缺失/rpa_profile 缺失时 fail-closed(返回 ok=False),绝不伪造等待;
写 trigger writer 可注入替身(测试)。
"""
from __future__ import annotations
import uuid
from typing import Any, Callable
from app.services.shipping_notice.receipt_rpa import write_receipt_export_batch_trigger
RouteTriggerWriter = Callable[..., str | None]
def _build_trigger_unit(
*, source_code: str, business_date: str, reason: str,
) -> dict[str, Any]:
"""装配单来源收料 trigger unit;配置缺失时抛 RuntimeError(由调用方转 fail-closed)。"""
from app.models import ShippingInventorySource, ShippingReceiptReportConfig
source = ShippingInventorySource.query.filter_by(source_code=source_code, enabled=True).first()
if source is None:
raise RuntimeError(f'source not enabled: {source_code}')
config = ShippingReceiptReportConfig.query.filter_by(inventory_source_id=source.id, enabled=True).first()
if config is None:
raise RuntimeError(f'receipt config missing: {source_code}')
profile = source.rpa_profile
if profile is None or not profile.enabled:
raise RuntimeError(f'receipt source profile unavailable: {source_code}')
warehouses = config.warehouse_ids_json or [] if source.connector_type == 'dbs' else [None]
warehouse_id = str(warehouses[0]) if warehouses else None
snapshot = {
'config_id': config.id, 'config_version': config.config_version,
'connector_type': source.connector_type,
'report_path_json': config.report_path_json or {},
'query_parameters_json': config.query_parameters_json or [],
'warehouse_id': warehouse_id, 'rpa_profile_id': source.rpa_profile_id,
}
return {
'unit_run_id': 0,
'callback_id': f'receipt:{uuid.uuid4().hex}',
'source_code': source.source_code,
'connector_type': source.connector_type,
'warehouse_id': warehouse_id,
'rpa_profile_id': profile.id,
'rpa_profile_code': profile.profile_code,
'login_url': profile.login_url,
'login_config': dict(profile.login_config_json or {}),
'credential_envelope': {
'username_ciphertext': profile.username_ciphertext,
'password_ciphertext': profile.password_ciphertext,
},
'report_path_json': dict(snapshot.get('report_path_json') or {}),
'query_parameters_json': list(snapshot.get('query_parameters_json') or []),
'config_snapshot': snapshot,
'business_date': business_date,
'reason': reason,
}
def trigger_receipt_rpa(
*,
source_code: str,
business_date: str,
reason: str = 'transfer_retry_receipt',
writer: RouteTriggerWriter | None = None,
) -> dict[str, Any]:
"""触发一次来源收料 RPA 抓取。
Args:
source_code: 来源实例编码。
business_date: 业务日期。
reason: 触发原因(写入 trigger)。
writer: 触发写者;缺省复用 write_receipt_export_batch_trigger。
Returns:
{"ok": True, "callback_id": ..., "trigger_path": ...} 或
{"ok": False, "error_code": ...}(配置缺失 / 触发目录不可用)。
"""
try:
unit = _build_trigger_unit(source_code=source_code, business_date=business_date, reason=reason)
except RuntimeError as exc:
return {"ok": False, "error_code": "RPA_RECEIPT_CONFIG_MISSING", "error_message": str(exc)}
run_no = f"TRIG-{source_code}-{uuid.uuid4().hex[:8].upper()}"
writer_fn = writer or write_receipt_export_batch_trigger
path = writer_fn(run_no, [unit], payload={
'schema_version': 'shipping_receipt_rpa.v1',
'action': 'receipt_export_batch',
'source_code': source_code,
'business_date': business_date,
'reason': reason,
})
if not path:
return {"ok": False, "error_code": "RPA_RECEIPT_TRIGGER_UNAVAILABLE"}
return {"ok": True, "callback_id": unit['callback_id'], "trigger_path": path}
@@ -0,0 +1,87 @@
"""在途调拨 Worker 崩溃/陈旧执行恢复(区别于 recovery_service 的每日历史复核)。
用途:回收租约过期的 executing 项(重新写前复查 + 幂等写入,不重复建单),
并将全部明细已终态但 Run 仍 executing 的停滞 Run 收尾。
依赖:execution_service._write_item、orchestrator.finalize_run、status。
逻辑:恢复依赖 Invoice 幂等(重复返回原单号 duplicate_success);
result_unknown 绝不自动重试。
"""
from __future__ import annotations
from datetime import datetime, timedelta
from app import db
from app.models import TransferInvoiceItem, TransferRun
from app.services.in_transit_transfer import status as status_machine
from app.services.in_transit_transfer.execution_service import _write_item
from app.services.in_transit_transfer.orchestrator import finalize_run
from app.services.in_transit_transfer.precheck_service import TransferDeps
STALE_EXECUTION_THRESHOLD_SECONDS = 3600
_TERMINAL_ITEM_STATUSES = {
status_machine.TransferStatus.SUCCESS.value,
status_machine.TransferStatus.DUPLICATE_SUCCESS.value,
status_machine.TransferStatus.BLOCKED_RECOVERABLE.value,
status_machine.TransferStatus.RESULT_UNKNOWN.value,
status_machine.TransferStatus.MANUALLY_CLOSED.value,
status_machine.TransferStatus.CANCELLED.value,
}
def recover_stale_execution_items(*, deps: TransferDeps, now: datetime | None = None,
request_id: str | None = None) -> dict:
"""回收租约过期的执行中明细。
Args:
deps: 注入依赖。
now: 判定时刻。
request_id: 审计上下文。
Returns:
{"recovered": n, "skipped_result_unknown": n, "failed": n}。
"""
current = now or datetime.utcnow()
threshold = current - timedelta(seconds=STALE_EXECUTION_THRESHOLD_SECONDS)
items = TransferInvoiceItem.query.filter(
TransferInvoiceItem.status == status_machine.TransferStatus.EXECUTING.value,
TransferInvoiceItem.updated_at <= threshold,
).all()
recovered = skipped_unknown = failed = 0
for item in items:
if (item.result_code or "") == "result_unknown" or item.status == status_machine.TransferStatus.RESULT_UNKNOWN.value:
skipped_unknown += 1
continue
run_no = item.run.run_no if item.run else "RUN-PENDING"
try:
_write_item(item, deps=deps, run_no=run_no, request_id=request_id)
recovered += 1
except Exception: # noqa: BLE001 —— 单项恢复失败不阻断其他项
item.status = status_machine.TransferStatus.BLOCKED_RECOVERABLE.value
item.result_code = "recovery_failed"
failed += 1
db.session.flush()
db.session.commit()
return {"recovered": recovered, "skipped_result_unknown": skipped_unknown, "failed": failed}
def finalize_stale_runs(*, now: datetime | None = None) -> list[int]:
"""将全部明细已终态但 Run 仍 executing 的停滞 Run 收尾。
Args:
now: 判定时刻(保留参数)。
Returns:
已收尾的 Run id 列表。
"""
finalized: list[int] = []
runs = TransferRun.query.filter_by(
status=status_machine.TransferRunStatus.EXECUTING.value,
).all()
for run in runs:
items = list(run.items)
if items and all(item.status in _TERMINAL_ITEM_STATUSES for item in items):
finalize_run(run, items)
finalized.append(run.id)
db.session.flush()
db.session.commit()
return finalized
@@ -0,0 +1,66 @@
"""在途调拨每日历史恢复(自动复核待处理池)。
用途:下一排程对可恢复异常项用最新文件与 ERP 重新预检并创建新 Attempt;
result_unknown / manually_closed / success 不自动写入。
依赖:models、retry_service._recheck_item、TransferDeps。
逻辑:恢复仅查询/匹配,不写 ERP;每次恢复新 Attempt,旧 Attempt 不变。
"""
from __future__ import annotations
from dataclasses import dataclass
from app import db
from app.models import TransferInvoiceItem
from app.services.in_transit_transfer import status as status_machine
from app.services.in_transit_transfer.precheck_service import TransferDeps
from app.services.in_transit_transfer.retry_service import _recheck_item
@dataclass
class RecoveryOutcome:
"""每日恢复结果汇总。"""
recovered_count: int = 0
still_blocked_count: int = 0
skipped_result_unknown: int = 0
skipped_manually_closed: int = 0
attempts_created: int = 0
def run_daily_recovery(*, business_date: str, deps: TransferDeps) -> RecoveryOutcome:
"""对可恢复异常执行每日自动复核。
Args:
business_date: 业务日期(仅用于审计上下文)。
deps: 注入依赖。
Returns:
RecoveryOutcome。
"""
outcome = RecoveryOutcome()
items = TransferInvoiceItem.query.filter(
TransferInvoiceItem.status.in_([
status_machine.TransferStatus.BLOCKED_RECOVERABLE.value,
status_machine.TransferStatus.RESULT_UNKNOWN.value,
status_machine.TransferStatus.MANUALLY_CLOSED.value,
]),
).all()
for item in items:
if item.status == status_machine.TransferStatus.RESULT_UNKNOWN.value:
# 只读隔离:不查询、不写入、不创建 Attempt。
outcome.skipped_result_unknown += 1
continue
if item.status == status_machine.TransferStatus.MANUALLY_CLOSED.value:
# 永久排除。
outcome.skipped_manually_closed += 1
continue
before_attempt = item.attempt_no
new_status = _recheck_item(item, deps=deps, request_id=None)
if new_status == status_machine.TransferStatus.READY_TO_EXECUTE.value:
outcome.recovered_count += 1
else:
outcome.still_blocked_count += 1
if item.attempt_no > before_attempt:
outcome.attempts_created += 1
db.session.commit()
return outcome
@@ -0,0 +1,120 @@
"""在途调拨人工重试服务(基于冻结文件仅重新查询 ERP)。
用途:对允许的异常项执行人工重试,只创建新 Attempt 并重新查询 ERP;
Run 创建后禁止重新抓取 RPA(文件冻结);result_unknown 只读拒绝。
依赖:models、erp_adapter、quantity、status、audit、precheck_service.TransferDeps。
逻辑:重试不写 ERP、不替换文件;匹配成功进入 ready_to_execute,否则保持阻断。
"""
from __future__ import annotations
import uuid
from datetime import datetime
from decimal import Decimal
from app import db
from app.core.errors import NotFoundError, ValidationError
from app.models import TransferAttempt, TransferInvoiceItem
from app.services.in_transit_transfer import status as status_machine
from app.services.in_transit_transfer.audit import build_transfer_audit_event
from app.services.in_transit_transfer.precheck_service import RESULT_EXECUTABLE, TransferDeps
from app.services.in_transit_transfer.quantity import classify_quantity_match
RETRY_KIND_ERP_RECHECK = "erp_recheck"
RETRY_KIND_RPA_REFETCH = "rpa_refetch"
def _recheck_item(item: TransferInvoiceItem, *, deps: TransferDeps, request_id: str | None) -> str:
"""对单个异常项重新查询 ERP 并更新状态(创建新 Attempt)。
Returns:
重检后的 item 状态。
"""
route = deps.route_resolver.resolve(source_code=item.source_code, invoice_no=item.invoice_no)
operation_id = f"op-{uuid.uuid4().hex[:12]}"
receipt_qty = Decimal(item.receipt_quantity)
query = deps.erp.query_inventory(
operation_id=operation_id,
run_no=item.run.run_no if item.run else "RUN-PENDING",
attempt_no=item.attempt_no + 1,
invoice_no=item.invoice_no,
erp_org=route.erp_org,
from_warehouse=route.from_warehouse,
to_warehouse=route.to_warehouse,
quantity=receipt_qty,
)
item.attempt_no += 1
before_status = item.status
attempt = TransferAttempt(
item_id=item.id, attempt_no=item.attempt_no, kind="erp_query",
status="running", operation_id=operation_id,
request_snapshot_json={
"invoice_no": item.invoice_no, "erp_org": route.erp_org,
"from_warehouse": route.from_warehouse, "to_warehouse": route.to_warehouse,
"quantity": str(receipt_qty),
},
)
db.session.add(attempt)
db.session.flush()
if not query.found or classify_quantity_match(receipt_qty, query.quantity) != RESULT_EXECUTABLE:
item.status = status_machine.TransferStatus.BLOCKED_RECOVERABLE.value
item.result_code = "blocked_inventory_not_found" if not query.found else "blocked_quantity_mismatch"
item.result_message = "erp inventory not found" if not query.found else "strict quantity mismatch"
attempt.status = "failed"
else:
item.status = status_machine.TransferStatus.READY_TO_EXECUTE.value
item.result_code = None
item.result_message = None
item.erp_quantity = str(query.quantity)
attempt.status = "success"
attempt.completed_at = datetime.utcnow()
db.session.add(build_transfer_audit_event(
event_type="TRANSFER_ITEM_RECHECKED",
aggregate_type="transfer_item",
aggregate_id=str(item.id),
run_no=item.run.run_no if item.run else None,
invoice_no=item.invoice_no,
item_id=str(item.id),
attempt_no=item.attempt_no,
actor_type="worker",
request_id=request_id,
operation_id=operation_id,
result="success" if item.status == status_machine.TransferStatus.READY_TO_EXECUTE.value else "failure",
before={"status": before_status},
after={"status": item.status, "attempt_no": item.attempt_no},
))
db.session.flush()
return item.status
def retry_item(*, item_id: int, deps: TransferDeps, kind: str = RETRY_KIND_ERP_RECHECK,
actor_id: int | None = None, request_id: str | None = None) -> dict:
"""人工重试异常项。
Args:
item_id: TransferInvoiceItem.id。
deps: 注入依赖。
kind: erp_recheck(默认);rpa_refetch 在 Run 创建后禁止。
actor_id / request_id: 审计上下文。
Returns:
{"item_id": ..., "status": ..., "attempt_no": ...}。
Raises:
ValidationError: 状态不可重试 / 重试类型不允许 / result_unknown 只读。
NotFoundError: item 不存在。
"""
kind_value = str(kind or "").strip()
if kind_value == RETRY_KIND_RPA_REFETCH:
raise ValidationError("RPA refetch is not allowed after execution run is created", code="TRANSFER.RETRY_RPA_NOT_ALLOWED")
if kind_value != RETRY_KIND_ERP_RECHECK:
raise ValidationError(f"unsupported retry kind: {kind_value}", code="TRANSFER.RETRY_KIND_INVALID")
item = db.session.get(TransferInvoiceItem, item_id)
if item is None:
raise NotFoundError("transfer invoice item not found", code="TRANSFER.ITEM_NOT_FOUND")
if item.status == status_machine.TransferStatus.RESULT_UNKNOWN.value:
raise ValidationError("result_unknown is read-only; follow manual verification SOP", code="TRANSFER_RESULT_UNKNOWN")
if item.status not in {status_machine.TransferStatus.BLOCKED_RECOVERABLE.value}:
raise ValidationError(f"item status {item.status} is not retryable", code="TRANSFER.RETRY_NOT_ALLOWED")
status = _recheck_item(item, deps=deps, request_id=request_id)
db.session.commit()
return {"item_id": item.id, "status": status, "attempt_no": item.attempt_no}
@@ -0,0 +1,77 @@
"""在途调拨 DTO 序列化(API 与 Chat Action 共用)。
用途:将领域 DTO 转为前端稳定 JSON(预检摘要/明细/来源进度/执行结果)。
依赖:contracts、execution_service。
逻辑:单一序列化来源,避免 API 与 Chat Action 各自实现导致契约漂移。
"""
from __future__ import annotations
from typing import Any
from app.services.in_transit_transfer.execution_service import serialize_run_result
def serialize_summary(summary) -> dict[str, Any]:
"""预检摘要序列化。"""
return {
"precheck_id": summary.precheck_id,
"status": summary.status,
"business_date": summary.business_date,
"eligible_receipt_date_to": summary.eligible_receipt_date_to,
"expires_at": summary.expires_at,
"counts": {
"file_invoice_count": summary.counts.file_invoice_count,
"not_matured_count": summary.counts.not_matured_count,
"prechecked_count": summary.counts.prechecked_count,
"executable_count": summary.counts.executable_count,
"blocked_count": summary.counts.blocked_count,
},
"estimated_transfer_quantity": summary.estimated_transfer_quantity,
"estimated_erp_write_count": summary.estimated_erp_write_count,
"precheck_hash": summary.precheck_hash,
}
def serialize_item(item) -> dict[str, Any]:
"""明细项序列化(决策 6 十列字段)。"""
return {
"source_code": item.source_code,
"material_no": item.material_no,
"material_name": item.material_name,
"specification": item.specification,
"invoice_no": item.invoice_no,
"receipt_date": item.receipt_date,
"from_warehouse": item.from_warehouse,
"from_quantity": str(item.from_quantity) if item.from_quantity is not None else None,
"to_warehouse": item.to_warehouse,
"to_quantity": str(item.to_quantity),
"result": item.result,
"reason": item.reason,
"raw_lines": [
{"sheet": line.sheet, "row_no": line.row_no, "file_version": line.file_version}
for line in item.raw_lines
],
}
def serialize_source(source) -> dict[str, Any]:
"""来源进度序列化。"""
return {
"source_code": source.source_code,
"stage": source.stage,
"file_no": source.file_no,
"file_version": source.file_version,
"checksum": source.checksum,
"error_code": source.error_code,
"error_message": source.error_message,
}
def serialize_precheck_detail(detail: dict[str, Any]) -> dict[str, Any]:
"""预检恢复详情(summary + items + sources)。"""
return {
"summary": serialize_summary(detail["summary"]),
"items": [serialize_item(item) for item in detail["items"]],
"sources": [serialize_source(source) for source in detail["sources"]],
}
@@ -0,0 +1,63 @@
"""在途调拨来源收料文件状态投影服务。
用途:只读货代收料链路已有事实(ShippingReceiptRpaUnitRun + ShippingReceiptReportFile),
按来源实例投影出"是否有 ready 文件 / 是否抓取中 / 是否失败 / 无文件待触发",
供 /sources 接口与前端门禁/状态标识使用。调拨不维护独立抓取状态表(低耦合)。
依赖:models(ShippingReceiptRpaUnitRun / ShippingReceiptReportFile)。
逻辑:按来源取该来源最新收料执行单元;有文件 → ready;有进行中单元 → fetching;
最新单元为失败终态 → failed;否则 → none。
"""
from __future__ import annotations
from app.models import ShippingReceiptReportFile, ShippingReceiptRpaUnitRun
RUNNING_UNIT_STATUSES = ('queued', 'awaiting_rpa', 'processing')
FAILED_UNIT_STATUSES = ('failed', 'empty', 'cancelled')
def resolve_source_file_status(*, source_code: str) -> dict:
"""返回某来源的收料文件状态投影。
Returns:
{"file_status": ..., "has_ready_file": bool, "file_no": ..., "file_sha256": ...},
file_status ∈ {'ready', 'fetching', 'failed', 'none'}。
"""
report = (
ShippingReceiptReportFile.query
.join(ShippingReceiptReportFile.unit_run)
.filter(
ShippingReceiptReportFile.unit_run.has(source_code=source_code),
ShippingReceiptReportFile.archive_deleted_at.is_(None),
)
.order_by(ShippingReceiptReportFile.created_at.desc(), ShippingReceiptReportFile.id.desc())
.first()
)
if report is not None:
return {
'file_status': 'ready',
'has_ready_file': True,
'file_no': report.original_filename or str(report.id),
'file_sha256': report.sha256,
}
active_unit = (
ShippingReceiptRpaUnitRun.query
.filter_by(source_code=source_code)
.filter(ShippingReceiptRpaUnitRun.status.in_(RUNNING_UNIT_STATUSES))
.order_by(ShippingReceiptRpaUnitRun.id.desc())
.first()
)
if active_unit is not None:
return {'file_status': 'fetching', 'has_ready_file': False, 'file_no': None, 'file_sha256': None}
latest_unit = (
ShippingReceiptRpaUnitRun.query
.filter_by(source_code=source_code)
.order_by(ShippingReceiptRpaUnitRun.id.desc())
.first()
)
if latest_unit is not None and latest_unit.status in FAILED_UNIT_STATUSES:
return {'file_status': 'failed', 'has_ready_file': False, 'file_no': None, 'file_sha256': None}
return {'file_status': 'none', 'has_ready_file': False, 'file_no': None, 'file_sha256': None}
@@ -0,0 +1,70 @@
"""在途调拨来源级状态服务(唯一推进入口)。
用途:统一创建/推进 TransferSourceJob(run 内来源级状态真相源),
让 create_precheck / restore / 未来回调等调用方都经由本服务,不各自散落改表。
依赖:models(TransferSourceJob)、status_machine。
逻辑:本服务只操作 run 内来源状态;(run_id, source_code) 唯一由模型约束;
不承担跨 run 防重(不同 run/不同人各自独立 job),也不写 ERP/触发 RPA。
"""
from __future__ import annotations
from datetime import datetime
from typing import Any
from app import db
from app.models import TransferSourceJob
SOURCE_JOB_STATUSES = (
'pending', 'checking_file', 'file_ready', 'waiting_rpa_callback', 'parsing',
'prechecking', 'executing', 'success', 'partial_failed', 'failed', 'cancelled',
)
def create_source_job(*, run_id: int, source_code: str, status: str = 'pending') -> TransferSourceJob:
"""为一次 run 创建一条来源级 job;(run_id, source_code) 唯一由模型约束。
Args:
run_id: 所属 TransferRun.id。
source_code: 来源实例编码。
status: 初始状态。
Returns:
新建(或复用已存在同 run 同来源)的 TransferSourceJob。
"""
existing = (
TransferSourceJob.query.filter_by(run_id=run_id, source_code=source_code).order_by(TransferSourceJob.id.desc()).first()
)
if existing is not None:
return existing
job = TransferSourceJob(run_id=run_id, source_code=source_code, status=status)
db.session.add(job)
db.session.flush()
return job
def advance_source_job(*, job: TransferSourceJob, status: str, **fields: Any) -> TransferSourceJob:
"""推进单条来源 job 状态并写入来源级事实字段。
Args:
job: 目标 TransferSourceJob。
status: 目标状态(须在 SOURCE_JOB_STATUSES 内,模型 CheckConstraint 兜底)。
fields: 其余来源级字段(file_no/file_sha256/error_code/error_message/lease_until 等),
可选 finished_at 被重置为当前时间。
Returns:
更新后的 job。
"""
job.status = status
for key, value in fields.items():
if hasattr(job, key):
setattr(job, key, value)
if status in ('success', 'partial_failed', 'failed', 'cancelled'):
job.finished_at = datetime.utcnow()
if status == 'pending':
job.started_at = datetime.utcnow()
db.session.flush()
return job
def source_jobs_for_run(run_id: int) -> list[TransferSourceJob]:
"""读取某次 run 的全部来源级 job(供 restore/投影)。"""
return TransferSourceJob.query.filter_by(run_id=run_id).order_by(TransferSourceJob.source_code).all()
@@ -0,0 +1,217 @@
"""在途调拨状态机与转换门禁。
用途:定义提示词冻结的 13 个业务状态(TransferStatus)、Run 生命周期
(TransferRunStatus)与通知状态(TransferNotificationStatus),
并强制所有状态转换走服务端门禁。
依赖:app.core.errors.AppError。
逻辑:转换表声明即白名单,未声明的迁移一律抛 TransferStateError;
result_unknown / manually_closed / success / duplicate_success /
not_matured / cancelled 为无出边终态;
通知失败(notification_failed)是通知投递状态,绝不改写 ERP 业务结果。
"""
from __future__ import annotations
from enum import StrEnum
from typing import Mapping
from app.core.errors import AppError
INVALID_STATE_TRANSITION_CODE = "TRANSFER.INVALID_STATE_TRANSITION"
class TransferStatus(StrEnum):
"""Invoice 项业务状态(含提示词冻结的全部 13 个状态)。"""
FILE_PENDING = "file_pending"
FILE_READY = "file_ready"
PRECHECKING = "prechecking"
READY_TO_EXECUTE = "ready_to_execute"
EXECUTING = "executing"
SUCCESS = "success"
DUPLICATE_SUCCESS = "duplicate_success"
BLOCKED_RECOVERABLE = "blocked_recoverable"
NOT_MATURED = "not_matured"
RESULT_UNKNOWN = "result_unknown"
MANUALLY_CLOSED = "manually_closed"
CANCELLED = "cancelled"
NOTIFICATION_FAILED = "notification_failed"
class TransferRunStatus(StrEnum):
"""Run 级生命周期;ERP 结果与通知结果分离。"""
QUEUED = "queued"
PREPARING_FILES = "preparing_files"
PRECHECKING = "prechecking"
READY_TO_EXECUTE = "ready_to_execute"
EXECUTING = "executing"
SUCCESS = "success"
PARTIAL_FAILED = "partial_failed"
FAILED = "failed"
CANCELLED = "cancelled"
class TransferNotificationStatus(StrEnum):
"""通知投递状态;failed 即提示词中 notification_failed 的语义。"""
PENDING = "pending"
SUCCESS = "success"
FAILED = "failed"
# 无出边终态:这些状态不得再触发任何自动或手工迁移。
TERMINAL_TRANSFER_STATUSES: frozenset[str] = frozenset({
TransferStatus.SUCCESS.value,
TransferStatus.DUPLICATE_SUCCESS.value,
TransferStatus.RESULT_UNKNOWN.value,
TransferStatus.MANUALLY_CLOSED.value,
TransferStatus.CANCELLED.value,
TransferStatus.NOT_MATURED.value,
TransferStatus.NOTIFICATION_FAILED.value,
})
# Invoice 项转换白名单:key=当前状态,value=允许的目标状态集合。
ITEM_TRANSITIONS: dict[str, frozenset[str]] = {
TransferStatus.FILE_PENDING.value: frozenset({
TransferStatus.FILE_READY.value,
TransferStatus.BLOCKED_RECOVERABLE.value,
}),
TransferStatus.FILE_READY.value: frozenset({
TransferStatus.PRECHECKING.value,
TransferStatus.BLOCKED_RECOVERABLE.value,
}),
TransferStatus.PRECHECKING.value: frozenset({
TransferStatus.READY_TO_EXECUTE.value,
TransferStatus.BLOCKED_RECOVERABLE.value,
TransferStatus.NOT_MATURED.value,
TransferStatus.CANCELLED.value,
}),
TransferStatus.READY_TO_EXECUTE.value: frozenset({
TransferStatus.PRECHECKING.value, # 确认失效/库存变化 → 新 Attempt 重新预检
TransferStatus.EXECUTING.value,
TransferStatus.BLOCKED_RECOVERABLE.value,
TransferStatus.CANCELLED.value,
}),
TransferStatus.EXECUTING.value: frozenset({
TransferStatus.SUCCESS.value,
TransferStatus.DUPLICATE_SUCCESS.value,
TransferStatus.BLOCKED_RECOVERABLE.value,
TransferStatus.RESULT_UNKNOWN.value,
TransferStatus.CANCELLED.value,
}),
TransferStatus.BLOCKED_RECOVERABLE.value: frozenset({
TransferStatus.PRECHECKING.value, # 仅 ERP 重查/重新预检,创建新 Attempt
TransferStatus.MANUALLY_CLOSED.value,
TransferStatus.CANCELLED.value,
}),
TransferStatus.NOT_MATURED.value: frozenset(),
TransferStatus.SUCCESS.value: frozenset(),
TransferStatus.DUPLICATE_SUCCESS.value: frozenset(),
TransferStatus.RESULT_UNKNOWN.value: frozenset(),
TransferStatus.MANUALLY_CLOSED.value: frozenset(),
TransferStatus.CANCELLED.value: frozenset(),
TransferStatus.NOTIFICATION_FAILED.value: frozenset(),
}
# Run 级转换白名单。
RUN_TRANSITIONS: dict[str, frozenset[str]] = {
TransferRunStatus.QUEUED.value: frozenset({
TransferRunStatus.PREPARING_FILES.value,
TransferRunStatus.CANCELLED.value,
}),
TransferRunStatus.PREPARING_FILES.value: frozenset({
TransferRunStatus.PRECHECKING.value,
TransferRunStatus.FAILED.value,
TransferRunStatus.CANCELLED.value,
}),
TransferRunStatus.PRECHECKING.value: frozenset({
TransferRunStatus.READY_TO_EXECUTE.value,
TransferRunStatus.FAILED.value,
TransferRunStatus.CANCELLED.value,
}),
TransferRunStatus.READY_TO_EXECUTE.value: frozenset({
TransferRunStatus.EXECUTING.value,
TransferRunStatus.CANCELLED.value,
}),
TransferRunStatus.EXECUTING.value: frozenset({
TransferRunStatus.SUCCESS.value,
TransferRunStatus.PARTIAL_FAILED.value,
TransferRunStatus.FAILED.value,
TransferRunStatus.CANCELLED.value,
}),
TransferRunStatus.SUCCESS.value: frozenset(),
TransferRunStatus.PARTIAL_FAILED.value: frozenset(),
TransferRunStatus.FAILED.value: frozenset(),
TransferRunStatus.CANCELLED.value: frozenset(),
}
class TransferStateError(AppError):
"""非法状态转换领域错误。"""
def __init__(
self,
message: str = "Invalid state transition",
*,
current: str | None = None,
target: str | None = None,
):
details: dict[str, str] = {}
if current is not None:
details["current"] = current
if target is not None:
details["target"] = target
super().__init__(
code=INVALID_STATE_TRANSITION_CODE,
message=message,
http_status=409,
details=details,
)
def assert_transition_allowed(
current: str,
target: str,
*,
transitions: Mapping[str, frozenset[str]] = ITEM_TRANSITIONS,
) -> None:
"""服务端状态转换门禁。
Args:
current: 当前状态。
target: 目标状态。
transitions: 转换白名单(默认 Invoice 项表)。
Raises:
TransferStateError: 当前状态未知或目标不在允许集合内。
"""
current_value = str(current or "").strip()
target_value = str(target or "").strip()
allowed = transitions.get(current_value)
if allowed is None:
raise TransferStateError("unknown current status", current=current_value)
if target_value not in allowed:
raise TransferStateError(
"status transition not allowed",
current=current_value,
target=target_value,
)
def apply_notification_failure(run_status: str) -> str:
"""通知失败不改变 ERP 结果。
Args:
run_status: Run 的 ERP 业务终态。
Returns:
原 run_status(保持不变)。
Raises:
TransferStateError: Run 尚未进入 ERP 终态时不允许记录通知失败。
"""
status = str(run_status or "").strip()
if status not in {TransferRunStatus.SUCCESS.value, TransferRunStatus.PARTIAL_FAILED.value}:
raise TransferStateError(
"notification failure only allowed after ERP terminal status",
current=status,
)
return status
@@ -0,0 +1,61 @@
"""在途调拨策略硬门禁。
用途:一期策略禁止部分数量调拨、数量容差与 ERP 自动重试,
强制默认 10 分钟确认有效期。
依赖:app.core.errors.AppError、standard decimal。
逻辑:任何策略变体触碰三项禁令之一即抛 StrategyViolationError,
阻止发布/执行(fail-closed)。
"""
from __future__ import annotations
from dataclasses import dataclass
from decimal import Decimal
from app.core.errors import AppError
STRATEGY_VIOLATION_CODE = "TRANSFER.STRATEGY_VIOLATION"
DEFAULT_CONFIRM_TTL_SECONDS = 600 # 10 分钟
@dataclass(frozen=True)
class TransferStrategyPolicy:
"""调拨策略冻结快照;三项禁令默认关闭。"""
allow_partial: bool = False
quantity_tolerance: Decimal = Decimal("0")
allow_erp_auto_retry: bool = False
confirm_ttl_seconds: int = DEFAULT_CONFIRM_TTL_SECONDS
class StrategyViolationError(AppError):
"""策略触碰一期禁令。"""
def __init__(self, message: str, *, reason: str):
super().__init__(
code=STRATEGY_VIOLATION_CODE,
message=message,
http_status=409,
details={"reason": reason},
)
def validate_strategy(strategy: TransferStrategyPolicy) -> None:
"""校验策略是否违反一期硬门禁。
Args:
strategy: 待校验策略。
Raises:
StrategyViolationError: 开启部分调拨、非零容差或 ERP 自动重试。
"""
if strategy.allow_partial:
raise StrategyViolationError("partial transfer is not supported in phase 1", reason="allow_partial")
if strategy.quantity_tolerance != Decimal("0"):
raise StrategyViolationError("quantity tolerance is not supported in phase 1", reason="quantity_tolerance")
if strategy.allow_erp_auto_retry:
raise StrategyViolationError("ERP auto retry is forbidden in phase 1", reason="allow_erp_auto_retry")
def default_strategy() -> TransferStrategyPolicy:
"""返回一期默认策略(全部禁令关闭,确认有效期 600 秒)。"""
return TransferStrategyPolicy()
@@ -0,0 +1,7 @@
"""services/integration_connector/__init__.py
Integration Connector(外部系统连接器框架):能力契约、绑定解析、REST/SOAP 传输、
声明式映射、凭据引用与调用引擎(CapabilityGateway)。
"""
from __future__ import annotations
@@ -0,0 +1,124 @@
"""services/integration_connector/binding.py
用途:Binding 解析与版本冻结——按 (capability, context, environment) 解析到
(客户端 + 接口 + 映射版本),并冻结调用期配置快照。
依赖:IntegrationBinding/IntegrationClientInstance/IntegrationInterfaceDefinition、errors.py。
逻辑:只命中 published + environment 匹配 + 生效区间 + context_selector 是 context 子集;
同 context 下 priority 高者优先;无命中抛 BindingNotFoundError(fail-closed)。
"""
from __future__ import annotations
from dataclasses import dataclass
from datetime import datetime, timezone
from app.models import IntegrationBinding, IntegrationClientInstance, IntegrationInterfaceDefinition
from app.services.integration_connector.errors import BindingNotFoundError
@dataclass(frozen=True)
class BindingSnapshot:
"""一次调用冻结的绑定快照:调用期配置 + 版本号(非活表引用)。"""
capability: str
context_selector: dict
client_code: str
interface_code: str
connector_type: str
interface_version: int
mapping_version: int
credential_ref_code: str | None
config: dict
request_spec: dict
response_mapping: dict
output_schema: dict
def _to_naive(dt: datetime | None) -> datetime | None:
if dt is None:
return None
if dt.tzinfo is not None:
return dt.astimezone(timezone.utc).replace(tzinfo=None)
return dt
def _within_window(binding: IntegrationBinding, now: datetime) -> bool:
effective_from = _to_naive(binding.effective_from)
effective_to = _to_naive(binding.effective_to)
if effective_from is not None and now < effective_from:
return False
if effective_to is not None and now > effective_to:
return False
return True
def _is_subset(selector: dict, context: dict) -> bool:
"""selector 的键值须全部存在于 context(空 selector 恒命中)。"""
return all(context.get(k) == v for k, v in selector.items())
def resolve_binding(capability: str, context: dict, environment: str, *, now: datetime | None = None) -> BindingSnapshot:
"""解析最佳绑定并冻结调用期快照。
Args:
capability: 能力名(如 in_transit_transfer.query_inventory)。
context: 路由上下文(来源/组织/租户等),如 {"source_code": "DBS-AWSBI"}。
environment: 环境(prod/test/dev)。
now: 可选时钟(测试注入);缺省用 utcnow。
Returns:
BindingSnapshot。
Raises:
BindingNotFoundError: 无可用绑定(fail-closed)。
"""
base_now = now or datetime.utcnow()
rows = IntegrationBinding.query.filter_by(capability=capability, environment=environment, status='published').all()
candidates: list[tuple[IntegrationBinding, dict]] = []
for row in rows:
if not _within_window(row, base_now):
continue
selector = row.context_selector_json or {}
if not _is_subset(selector, context or {}):
continue
candidates.append((row, selector))
if not candidates:
raise BindingNotFoundError(capability=capability)
candidates.sort(key=lambda item: (item[0].priority, len(item[1])), reverse=True)
row, selector = candidates[0]
client = IntegrationClientInstance.query.filter_by(code=row.client_instance_code).first()
iface = IntegrationInterfaceDefinition.query.filter_by(code=row.interface_definition_code).first()
if client is None or iface is None:
raise BindingNotFoundError(capability=capability)
# 兼容层:把独立列拼回 dict,供 engine/mapping/transport 无感消费。
# 优先列值,缺失回退 JSON(config_json / request_spec_json / context_selector_json)。
config = dict(client.config_json or {})
if client.endpoint is not None:
config['endpoint'] = client.endpoint
if client.timeout_seconds is not None:
config['timeout_seconds'] = client.timeout_seconds
request_spec = dict(iface.request_spec_json or {})
if iface.http_method is not None:
request_spec['method'] = iface.http_method
if iface.request_path is not None:
request_spec['path'] = iface.request_path
selector = dict(row.context_selector_json or {})
if row.context_source_code is not None and 'source_code' not in selector:
selector['source_code'] = row.context_source_code
return BindingSnapshot(
capability=row.capability,
context_selector=selector,
client_code=client.code,
interface_code=iface.code,
connector_type=client.connector_type,
interface_version=iface.version,
mapping_version=row.mapping_version,
credential_ref_code=client.credential_ref_code,
config=config,
request_spec=request_spec,
response_mapping=iface.response_mapping_json or {},
output_schema=iface.output_schema_json or {},
)
@@ -0,0 +1,125 @@
"""services/integration_connector/capability.py
用途:Capability 强类型契约注册表(能力名称/输入输出 Schema/幂等语义/是否写)。
依赖:app.core.errors、errors.py;纯代码,不依赖 DB。
逻辑:能力必须由代码注册,不能由管理端动态定义;领域只调用已注册能力,未注册 fail-closed。
"""
from __future__ import annotations
from dataclasses import dataclass
from app.core.errors import ValidationError
from app.services.integration_connector.errors import CapabilityNotFoundError
# 在途调拨能力输入/输出 Schema(JSON Schema 最小子集,供入参/出参校验)。
_QUERY_INPUT_SCHEMA: dict = {
"type": "object",
"required": ["invoice_no", "from_warehouse", "to_warehouse", "quantity"],
"properties": {
"invoice_no": {"type": "string"},
"from_warehouse": {"type": "string"},
"to_warehouse": {"type": "string"},
"quantity": {"type": "number"},
},
}
_QUERY_OUTPUT_SCHEMA: dict = {
"type": "object",
"properties": {
"found": {"type": "boolean"},
"quantity": {"type": ["number", "null"]},
},
}
_WRITE_OUTPUT_SCHEMA: dict = {
"type": "object",
"required": ["status"],
"properties": {
"status": {
"type": "string",
"enum": ["success", "business_failed", "technical_failed", "timeout", "result_unknown"],
},
"document_no": {"type": ["string", "null"]},
"verified_posted": {"type": ["boolean", "null"]},
},
}
@dataclass(frozen=True)
class CapabilitySpec:
"""强类型能力契约(由代码注册)。"""
name: str
input_schema: dict
output_schema: dict
idempotency: str
write: bool
_CAPABILITIES: dict[str, CapabilitySpec] = {}
_LOADED = False
def register_capability(spec: CapabilitySpec) -> CapabilitySpec:
"""注册能力;同名重复注册抛 ValidationError。"""
if spec.name in _CAPABILITIES:
raise ValidationError(
f"capability already registered: {spec.name}",
code="INTEGRATION.CAPABILITY_DUPLICATE",
details={"name": spec.name},
)
_CAPABILITIES[spec.name] = spec
return spec
def get_capability(name: str) -> CapabilitySpec:
"""按名查询能力;未注册抛 CapabilityNotFoundError(fail-closed)。"""
spec = _CAPABILITIES.get(name)
if spec is None:
raise CapabilityNotFoundError(name=name)
return spec
def list_capabilities() -> list[CapabilitySpec]:
"""返回全部已注册能力(按名排序)。"""
return sorted(_CAPABILITIES.values(), key=lambda s: s.name)
def ensure_capabilities_loaded() -> None:
"""惰性注册内置能力(幂等);由网关/API 在解析前调用。"""
global _LOADED # noqa: PLW0603
if _LOADED:
return
_LOADED = True
_register_transfer_capabilities()
def _register_transfer_capabilities() -> None:
"""注册在途调拨域内置能力;领域代码只调这些能力,外部系统差异全在连接器层。"""
register_capability(CapabilitySpec(
name="in_transit_transfer.query_inventory",
input_schema=_QUERY_INPUT_SCHEMA,
output_schema=_QUERY_OUTPUT_SCHEMA,
idempotency="none",
write=False,
))
register_capability(CapabilitySpec(
name="in_transit_transfer.create_transfer",
input_schema=_QUERY_INPUT_SCHEMA,
output_schema=_WRITE_OUTPUT_SCHEMA,
idempotency="invoice",
write=True,
))
register_capability(CapabilitySpec(
name="in_transit_transfer.verify_duplicate",
input_schema=_QUERY_INPUT_SCHEMA,
output_schema=_WRITE_OUTPUT_SCHEMA,
idempotency="invoice",
write=False,
))
def reset_capability_registry_for_tests() -> None:
"""单测隔离:清空注册表并重置加载标记。"""
global _LOADED # noqa: PLW0603
_CAPABILITIES.clear()
_LOADED = False
@@ -0,0 +1,153 @@
"""services/integration_connector/engine.py
用途:CapabilityGateway 调用引擎——统一执行 resolve→validate→build→call→map→classify→audit。
依赖:capability/binding/mapping/security/transports、IntegrationCall 模型、errors.py。
逻辑:读能力映射校验通过即 success;写能力按原始 status 分类;超时→timeout;
入参非法/无绑定/映射失败/契约未冻结均 fail-closed;result_unknown 不自动重试。
"""
from __future__ import annotations
import time
import uuid
from dataclasses import replace
from app import db
from app.services.integration_connector.binding import BindingSnapshot, resolve_binding
from app.services.integration_connector.capability import CapabilitySpec, ensure_capabilities_loaded, get_capability
from app.services.integration_connector.errors import CallFailedError, InputInvalidError
from app.services.integration_connector.mapping import map_response, schema_errors
from app.services.integration_connector.security import sanitize
from app.services.integration_connector.transports.base import IntegrationCallResult, Transport, classify_transport_response
from app.models import IntegrationCall
def build_request(request_spec: dict, config: dict, params: dict) -> dict:
"""按接口请求规格构造请求:填充 path 占位符,组装 params/body/headers。"""
request_spec = request_spec or {}
spec_path = str(request_spec.get('path') or '')
try:
path = spec_path.format(**params)
except (KeyError, IndexError, ValueError):
path = spec_path
headers = dict(config.get('headers') or {})
spec_params = list(request_spec.get('params') or [])
selected = {k: params[k] for k in spec_params if k in params} or params
template = request_spec.get('template')
if isinstance(template, dict):
body = _fill_template(template, params)
else:
body = selected
return {'path': path, 'params': selected, 'body': body, 'headers': headers}
def _fill_template(template: dict, params: dict) -> dict:
"""填充模板 dict 中的 {placeholder} 占位符。"""
filled: dict = {}
for key, value in template.items():
if isinstance(value, str) and '{' in value:
try:
filled[key] = value.format(**params)
except (KeyError, IndexError, ValueError):
filled[key] = value
else:
filled[key] = value
return filled
def _environment() -> str:
"""从 Flask 配置推导环境(dev/test/prod),缺省 prod。"""
try:
from flask import current_app, has_app_context
if has_app_context():
value = str(current_app.config.get('ENV_NAME') or '').strip().lower()
if value in {'dev', 'test', 'prod'}:
return value
except Exception:
pass
return 'prod'
class CapabilityGateway:
"""能力调用引擎;transports 为 {connector_type: Transport} 可注入。"""
def __init__(self, transports: dict[str, Transport] | None = None) -> None:
self.transports = dict(transports or {})
def call(
self,
*,
capability: str,
context: dict,
params: dict,
operation_id: str,
idempotency_key: str | None = None,
environment: str | None = None,
transports: dict[str, Transport] | None = None,
) -> IntegrationCallResult:
ensure_capabilities_loaded()
spec = get_capability(capability)
input_errors = schema_errors(params, spec.input_schema)
if input_errors:
raise InputInvalidError(details={'errors': input_errors})
env = environment or _environment()
snapshot = resolve_binding(capability, context, env)
transport = (transports or self.transports).get(snapshot.connector_type)
if transport is None:
raise CallFailedError(details={'reason': f'no transport for connector_type={snapshot.connector_type}'})
request = build_request(snapshot.request_spec, snapshot.config, params)
trace_id = f'ic-{uuid.uuid4().hex}'
start_ms = int(time.time() * 1000)
try:
raw = transport.call(
client={'config_json': snapshot.config, 'credential': {}},
interface={'request_spec_json': snapshot.request_spec},
request=request,
)
except TimeoutError:
result = IntegrationCallResult(status='timeout', error_code='ERP_TIMEOUT_UNKNOWN', trace_id=trace_id)
_record_call(operation_id, capability, snapshot, params, None, result, start_ms, trace_id)
return result
result = classify_transport_response(raw) if spec.write else IntegrationCallResult(status='success')
if not spec.write or result.status in ('success', 'duplicate_success', 'duplicate_unverified'):
data = map_response(snapshot.response_mapping, raw, snapshot.output_schema or spec.output_schema)
result = replace(result, data=data)
result = replace(result, trace_id=trace_id)
_record_call(operation_id, capability, snapshot, params, raw, result, start_ms, trace_id)
return result
def _record_call(
operation_id: str,
capability: str,
snapshot: BindingSnapshot,
params: dict,
raw: dict | None,
result: IntegrationCallResult,
start_ms: int,
trace_id: str,
) -> None:
"""落 IntegrationCall(冻结绑定版本 + 脱敏请求/响应摘要)。"""
elapsed_ms = int(time.time() * 1000) - start_ms
call = IntegrationCall(
operation_id=operation_id,
capability=capability,
binding_snapshot_json={
'client_code': snapshot.client_code,
'interface_code': snapshot.interface_code,
'connector_type': snapshot.connector_type,
'interface_version': snapshot.interface_version,
'mapping_version': snapshot.mapping_version,
'credential_ref_code': snapshot.credential_ref_code,
},
request_summary_json=sanitize(params),
response_summary_json=sanitize(raw or {}),
status=result.status,
elapsed_ms=elapsed_ms,
trace_id=trace_id,
)
db.session.add(call)
db.session.commit()
@@ -0,0 +1,104 @@
"""services/integration_connector/errors.py
用途:Integration Connector 框架统一业务异常类(INTEGRATION.* 错误码)。
依赖:app.core.errors.AppError。
逻辑:fail-closed —— 缺绑定/缺凭据/映射不合法/契约未冻结均抛出,绝不猜测。
"""
from __future__ import annotations
from typing import Any
from app.core.errors import AppError
INTEGRATION_CAPABILITY_NOT_FOUND = "INTEGRATION.CAPABILITY_NOT_FOUND"
INTEGRATION_INPUT_INVALID = "INTEGRATION.INPUT_INVALID"
INTEGRATION_BINDING_NOT_FOUND = "INTEGRATION.BINDING_NOT_FOUND"
INTEGRATION_TRANSPORT_NOT_FROZEN = "INTEGRATION.TRANSPORT_NOT_FROZEN"
INTEGRATION_MAPPING_INVALID = "INTEGRATION.MAPPING_INVALID"
INTEGRATION_CREDENTIAL_UNRESOLVED = "INTEGRATION.CREDENTIAL_UNRESOLVED"
INTEGRATION_RESULT_UNKNOWN = "INTEGRATION.RESULT_UNKNOWN"
INTEGRATION_CALL_FAILED = "INTEGRATION.CALL_FAILED"
class CapabilityNotFoundError(AppError):
"""能力未注册(fail-closed)。"""
def __init__(self, message: str = "capability not registered", *, name: str | None = None):
details = {"name": name} if name else {}
super().__init__(
code=INTEGRATION_CAPABILITY_NOT_FOUND, message=message, http_status=404, details=details,
retryable=False,
)
class InputInvalidError(AppError):
"""入参不合能力输入 Schema。"""
def __init__(self, message: str = "input invalid", *, details: dict[str, Any] | None = None):
super().__init__(
code=INTEGRATION_INPUT_INVALID, message=message, http_status=400, details=details or {},
retryable=False,
)
class BindingNotFoundError(AppError):
"""无可用绑定(fail-closed)。"""
def __init__(self, message: str = "no binding for capability", *, capability: str | None = None):
details = {"capability": capability} if capability else {}
super().__init__(
code=INTEGRATION_BINDING_NOT_FOUND, message=message, http_status=503, details=details,
retryable=False,
)
class TransportNotFrozenError(AppError):
"""传输契约未冻结(缺 endpoint/wsdl)。"""
def __init__(self, message: str = "transport not frozen"):
super().__init__(
code=INTEGRATION_TRANSPORT_NOT_FROZEN, message=message, http_status=503, retryable=False,
)
class MappingInvalidError(AppError):
"""映射结果不合输出 Schema(fail-closed)。"""
def __init__(self, message: str = "mapping invalid", *, details: dict[str, Any] | None = None):
super().__init__(
code=INTEGRATION_MAPPING_INVALID, message=message, http_status=503, details=details or {},
retryable=False,
)
class CredentialUnresolvedError(AppError):
"""凭据无法解析(fail-closed)。"""
def __init__(self, message: str = "credential unresolved", *, ref: str | None = None):
details = {"secret_ref": ref} if ref else {}
super().__init__(
code=INTEGRATION_CREDENTIAL_UNRESOLVED, message=message, http_status=503, details=details,
retryable=False,
)
class ResultUnknownError(AppError):
"""写结果无法确认;禁止自动重试。"""
def __init__(self, message: str = "result unknown", *, operation_id: str | None = None):
details = {"operation_id": operation_id} if operation_id else {}
super().__init__(
code=INTEGRATION_RESULT_UNKNOWN, message=message, http_status=503, details=details,
retryable=False,
)
class CallFailedError(AppError):
"""调用技术失败(非业务失败)。"""
def __init__(self, message: str = "call failed", *, details: dict[str, Any] | None = None):
super().__init__(
code=INTEGRATION_CALL_FAILED, message=message, http_status=502, details=details or {},
retryable=False,
)
@@ -0,0 +1,27 @@
"""services/integration_connector/gateway.py
用途:模块级 CapabilityGateway 装配与测试注入点。
依赖:engine.CapabilityGateway、transports.rest/soap。
逻辑:生产用 REST/SOAP 传输;测试通过 set_capability_gateway 注入替身。
"""
from __future__ import annotations
from app.services.integration_connector.engine import CapabilityGateway
from app.services.integration_connector.transports.rest import RestTransport
from app.services.integration_connector.transports.soap import SoapTransport
_override: CapabilityGateway | None = None
def set_capability_gateway(gateway: CapabilityGateway | None) -> None:
"""测试注入点:设置/清除 CapabilityGateway 覆盖。"""
global _override # noqa: PLW0603
_override = gateway
def get_capability_gateway() -> CapabilityGateway:
"""返回装配好的 CapabilityGateway(测试覆盖优先,默认 REST/SOAP)。"""
if _override is not None:
return _override
return CapabilityGateway(transports={'rest': RestTransport(), 'soap': SoapTransport()})
@@ -0,0 +1,210 @@
"""services/integration_connector/mapping.py
用途:声明式映射引擎——把外部原始响应映射为统一结果(提取路径 + 白名单转换 + 输出 Schema 校验)。
依赖:decimal、errors.py;纯函数,无 IO/网络/DB。
逻辑:只允许点路径/数组下标提取与白名单转换函数,禁止任意 Python/JS/SQL;
缺字段且不可满足→MappingInvalidError;输出不合 Schema→MappingInvalidError(fail-closed)。
"""
from __future__ import annotations
from decimal import Decimal
from typing import Any
from app.services.integration_connector.errors import MappingInvalidError
# 表达式安全边界:路径长度/深度上限(失败即 fail-closed)。
MAX_PATH_LENGTH = 256
MAX_DEPTH = 8
# 缺字段哨兵:与合法值 None 区分。
MISSING = object()
def _tokenize(path: str) -> list[str]:
"""把点路径 + 数组下标拆成 token 序列,如 a.b[0].c -> ['a','b','0','c']。"""
tokens: list[str] = []
current = ""
i = 0
n = len(path)
while i < n:
c = path[i]
if c == "[":
if current:
tokens.append(current)
current = ""
j = path.index("]", i)
tokens.append(path[i + 1:j])
i = j + 1
elif c == ".":
if current:
tokens.append(current)
current = ""
i += 1
else:
current += c
i += 1
if current:
tokens.append(current)
return tokens
def extract_path(obj: Any, path: str) -> Any:
"""按点路径/数组下标提取;缺任一节点返回 MISSING;路径超长/超深抛 MappingInvalidError。"""
path = str(path or "")
if len(path) > MAX_PATH_LENGTH:
raise MappingInvalidError(details={"reason": "path_too_long"})
tokens = _tokenize(path)
if len(tokens) > MAX_DEPTH:
raise MappingInvalidError(details={"reason": "path_too_deep"})
cur = obj
for tok in tokens:
if isinstance(cur, list) and tok.isdigit():
idx = int(tok)
if idx >= len(cur):
return MISSING
cur = cur[idx]
elif isinstance(cur, dict) and tok in cur:
cur = cur[tok]
else:
return MISSING
return cur
# ---- 白名单转换函数(纯函数,无 IO/网络/eval) ----
def _default(value: Any, default: Any) -> Any:
return default if value is MISSING else value
def _fallback(value: Any, fallback: Any) -> Any:
return fallback if value is MISSING or value in (None, "") else value
def _decimal(value: Any) -> Any:
if value is MISSING:
return MISSING
return Decimal(str(value))
def _cast(value: Any, to: str) -> Any:
if value is MISSING or value is None:
return MISSING
if to == "int":
return int(value)
if to == "float":
return float(value)
if to == "str":
return str(value)
if to == "bool":
return bool(value)
return value
def _enum_map(value: Any, mapping: dict[str, str]) -> Any:
if value is MISSING:
return MISSING
return mapping.get(str(value), value)
def _list_map(value: Any, mapping: dict[str, str]) -> list[Any]:
if value is MISSING:
return MISSING
return [mapping.get(str(item), item) for item in (value or [])]
def _if_else(value: Any, condition: str, then: Any, else_: Any) -> Any:
if value is MISSING:
return MISSING
return then if condition == "truthy" and bool(value) else else_
TRANSFORMS: dict[str, Any] = {
"default": _default,
"fallback": _fallback,
"decimal": _decimal,
"cast": _cast,
"enum-map": _enum_map,
"list-map": _list_map,
"if-else": _if_else,
}
# ---- 最小 JSON Schema 子集校验(type/required/properties/enum/items)----
def _matches_type(value: Any, type_spec: Any) -> bool:
if isinstance(type_spec, list):
return any(_matches_type(value, t) for t in type_spec)
if type_spec == "object":
return isinstance(value, dict)
if type_spec == "array":
return isinstance(value, (list, tuple))
if type_spec == "string":
return isinstance(value, str)
if type_spec == "number":
return isinstance(value, (int, float, Decimal)) and not isinstance(value, bool)
if type_spec == "integer":
return isinstance(value, int) and not isinstance(value, bool)
if type_spec == "boolean":
return isinstance(value, bool)
if type_spec == "null":
return value is None
return True
def _validate_against_schema(value: Any, schema: dict, path: str = "") -> list[tuple[str, str]]:
"""返回不合规项 [(字段路径, 原因)];空列表表示合规。"""
if not isinstance(schema, dict):
return []
errors: list[tuple[str, str]] = []
if "enum" in schema and value not in schema["enum"]:
errors.append((path, f"not in enum: {value!r}"))
if "type" in schema and not _matches_type(value, schema["type"]):
errors.append((path, f"expected {schema['type']}, got {type(value).__name__}"))
if isinstance(value, dict):
for req in schema.get("required") or []:
if req not in value:
errors.append((f"{path}.{req}" if path else req, "required missing"))
for key, sub in (schema.get("properties") or {}).items():
if key in value:
errors.extend(_validate_against_schema(value[key], sub, f"{path}.{key}" if path else key))
elif isinstance(value, list) and "items" in schema:
for i, item in enumerate(value):
errors.extend(_validate_against_schema(item, schema["items"], f"{path}[{i}]"))
return errors
def schema_errors(value: Any, schema: dict) -> list[tuple[str, str]]:
"""对 value 做最小 Schema 校验,返回不合规项 [(字段路径, 原因)];空列表表示合规。"""
return _validate_against_schema(value, schema or {})
def map_response(mapping: dict, raw: dict, output_schema: dict) -> dict:
"""按 mapping 从 raw 提取并转换字段,组装 result 后经 output_schema 校验。
Raises:
MappingInvalidError: 未知转换函数 / 缺必需字段 / 类型或枚举不合。
"""
mapping = mapping or {}
result: dict[str, Any] = {}
for field, spec in mapping.items():
if not isinstance(spec, dict):
raise MappingInvalidError(details={"field": field, "reason": "invalid_mapping_spec"})
if "default" in spec:
value = spec["default"]
else:
expr = spec.get("expr")
value = extract_path(raw, expr) if expr is not None else MISSING
transform = spec.get("transform")
if transform:
fn = TRANSFORMS.get(transform)
if fn is None:
raise MappingInvalidError(details={"field": field, "reason": f"unknown_transform:{transform}"})
value = fn(value, **(spec.get("args") or {}))
if value is not MISSING:
result[field] = value
errors = _validate_against_schema(result, output_schema or {})
if errors:
raise MappingInvalidError(details={"errors": errors})
return result
@@ -0,0 +1,83 @@
"""services/integration_connector/security.py
用途:凭据引用解析(fail-closed)与敏感字段脱敏。
依赖:IntegrationCredentialReference 模型、current_app.config、errors.py。
逻辑:凭据只存 secret_ref 引用;解析时读当前环境配置,缺失即抛 CredentialUnresolvedError;
sanitize 递归脱敏敏感键;credential_summary 只回元数据,绝不回显明文。
"""
from __future__ import annotations
from typing import Any
from app.models import IntegrationCredentialReference
from app.services.integration_connector.errors import CredentialUnresolvedError
DEFAULT_SENSITIVE_KEYS = frozenset({
'password', 'token', 'secret', 'authorization', 'cookie', 'access_key',
'secret_key', 'credential', 'api_key', 'apikey', 'credentials',
})
def resolve_credential(credential_ref_code: str) -> dict[str, Any]:
"""按凭据引用解析当前环境真实凭据(从 current_app.config[secret_ref] 读取)。
Raises:
CredentialUnresolvedError: 引用不存在或 secret_ref 对应配置缺失/为空。
"""
from flask import current_app
cred = IntegrationCredentialReference.query.filter_by(
code=credential_ref_code, status='active',
).first()
if cred is None:
raise CredentialUnresolvedError(ref=credential_ref_code)
secret_ref = cred.secret_ref
value = current_app.config.get(secret_ref) if has_app_ctx() else None
if value is None or value == '':
raise CredentialUnresolvedError(ref=secret_ref)
if isinstance(value, dict):
return dict(value)
return {'value': value}
def has_app_ctx() -> bool:
"""当前是否处于 Flask app 上下文(无则返回 False)。"""
try:
from flask import has_app_context
return has_app_context()
except Exception:
return False
def sanitize(obj: Any, sensitive_keys: set[str] | None = None) -> Any:
"""递归脱敏:把敏感键对应的值替换为 ***;保留原始结构。
Args:
obj: 待脱敏对象(dict/list/标量)。
sensitive_keys: 附加敏感键集合;缺省用 DEFAULT_SENSITIVE_KEYS。
Returns:
脱敏后的新对象(不修改入参)。
"""
keys = DEFAULT_SENSITIVE_KEYS | (sensitive_keys or set())
if isinstance(obj, dict):
return {
key: ('***' if str(key).lower() in keys else sanitize(value, sensitive_keys))
for key, value in obj.items()
}
if isinstance(obj, (list, tuple)):
return [sanitize(item, sensitive_keys) for item in obj]
return obj
def credential_summary(cred: IntegrationCredentialReference) -> dict[str, Any]:
"""只回凭据元数据,绝不含解析出的明文。"""
return {
'code': cred.code,
'secret_ref': cred.secret_ref,
'secret_provider': cred.secret_provider,
'credential_type': cred.credential_type,
'version': cred.version,
'status': cred.status,
'last_verified_at': cred.last_verified_at.isoformat() if cred.last_verified_at else None,
}
@@ -0,0 +1,18 @@
"""services/integration_connector/transports/__init__.py
集成连接器传输层:base(契约+分类)、rest、soap。后续扩展 rpa/sql/file。
"""
from __future__ import annotations
from app.services.integration_connector.transports.base import IntegrationCallResult, Transport, classify_transport_response
from app.services.integration_connector.transports.rest import RestTransport
from app.services.integration_connector.transports.soap import SoapTransport
__all__ = [
'IntegrationCallResult',
'Transport',
'classify_transport_response',
'RestTransport',
'SoapTransport',
]
@@ -0,0 +1,73 @@
"""services/integration_connector/transports/base.py
用途:Transport 统一契约 + 结果分类(IntegrationCallResult)。
依赖:typing.Protocol、dataclass;无 Flask/DB。
逻辑:Transport.call 返回原始 dict;classify_transport_response 把原始响应归一为
IntegrationCallResult(复用调拨六态分类语义)。fail-closed 由各 Transport 抛异常。
"""
from __future__ import annotations
from dataclasses import dataclass, field
from typing import Any, Protocol
# 结果状态集(与在途调拨写入结果分类一致):success / duplicate_success /
# duplicate_unverified / business_failed / technical_failed / timeout / result_unknown
RESULT_STATUSES = (
'success', 'duplicate_success', 'duplicate_unverified', 'business_failed',
'technical_failed', 'timeout', 'result_unknown',
)
@dataclass(frozen=True)
class IntegrationCallResult:
"""一次调用归一后的结果对象。"""
status: str
data: dict[str, Any] | None = None
error_code: str | None = None
error_message: str | None = None
document_no: str | None = None
trace_id: str | None = None
class Transport(Protocol):
"""传输层协议:REST/SOAP(后续 RPA/SQL/FILE)。call 返回原始响应 dict。"""
connector_type: str
def call(self, *, client: dict, interface: dict, request: dict) -> dict[str, Any]:
...
def classify_transport_response(raw: dict[str, Any]) -> IntegrationCallResult:
"""按原始响应文本归一化结果分类(复用调拨六态分类语义)。
Args:
raw: 原始响应 dict,含 status/document_no/verified_posted/code/message。
Returns:
IntegrationCallResult。
"""
status = str(raw.get('status') or 'technical_failed')
document_no = raw.get('document_no')
if status == 'success':
return IntegrationCallResult(status='success', data=raw, document_no=document_no)
if status == 'duplicate_success':
posted = bool(raw.get('verified_posted'))
if posted:
return IntegrationCallResult(status='duplicate_success', data=raw, document_no=document_no)
return IntegrationCallResult(
status='duplicate_unverified', data=raw, document_no=document_no,
error_code='INTEGRATION_DUPLICATE_NOT_VERIFIED',
)
if status == 'business_failed':
return IntegrationCallResult(
status='business_failed', data=raw,
error_code=str(raw.get('code') or 'ERP_BUSINESS_REJECT'),
error_message=str(raw.get('message') or ''),
)
if status == 'timeout':
return IntegrationCallResult(status='timeout', error_code='ERP_TIMEOUT_UNKNOWN')
if status == 'result_unknown':
return IntegrationCallResult(status='result_unknown', error_code='ERP_RESULT_UNKNOWN', document_no=document_no)
return IntegrationCallResult(status='technical_failed', error_code='ERP_UNKNOWN_RESPONSE')
@@ -0,0 +1,62 @@
"""services/integration_connector/transports/rest.py
用途:REST Transport——按 client 配置与 interface 请求规格构造 HTTP 请求并返回原始 dict。
依赖:requests(默认注入),可注入 http_request 供测试替身。
逻辑:endpoint 未冻结 fail-closed(TransportNotFrozenError);4xx/5xx 映射为
business_failed dict;非 JSON 响应映射为 technical_failed。
"""
from __future__ import annotations
from typing import Any, Callable
import requests
from app.services.integration_connector.errors import TransportNotFrozenError
HttpRequest = Callable[..., Any]
class RestTransport:
"""REST 传输;http_request 可注入以便单元测试(默认 requests.request)。"""
connector_type = 'rest'
def __init__(self, http_request: HttpRequest | None = None) -> None:
self._http_request = http_request or requests.request
def call(self, *, client: dict, interface: dict, request: dict) -> dict[str, Any]:
config = client.get('config_json') or {}
endpoint = str(config.get('endpoint') or '').strip()
if not endpoint:
raise TransportNotFrozenError('REST endpoint not frozen (missing endpoint)')
spec = interface.get('request_spec_json') or {}
method = str(spec.get('method') or 'GET').upper()
path = str(spec.get('path') or '').strip()
url = endpoint.rstrip('/') + '/' + path.lstrip('/')
headers = {**(config.get('headers') or {}), **(request.get('headers') or {})}
timeout = int(config.get('timeout_seconds') or 60)
response = self._http_request(
method,
url,
params=request.get('params'),
json=request.get('body'),
headers=headers,
timeout=timeout,
)
if int(getattr(response, 'status_code', 0)) >= 400:
return {
'status': 'business_failed',
'code': f"HTTP_{int(response.status_code)}",
'message': str(getattr(response, 'text', ''))[:500],
}
try:
return response.json()
except Exception:
return {
'status': 'technical_failed',
'code': 'NON_JSON',
'message': str(getattr(response, 'text', ''))[:500],
}
@@ -0,0 +1,29 @@
"""services/integration_connector/transports/soap.py
用途:SOAP Transport——WSDL/endpoint 未冻结时 fail-closed;真实实现待 WSDL 冻结后落地。
依赖:zeep(延时导入);errors.py。
逻辑:无 wsdl/endpoint → TransportNotFrozenError;冻结后走 zeep.Client(暂 NotImplemented)。
"""
from __future__ import annotations
from typing import Any
from app.services.integration_connector.errors import TransportNotFrozenError
class SoapTransport:
"""SOAP 传输;真实 SOAP 调用待 WSDL 冻结后实现(fail-closed 守卫已就位)。"""
connector_type = 'soap'
def call(self, *, client: dict, interface: dict, request: dict) -> dict[str, Any]:
config = client.get('config_json') or {}
# SOAP 只需一个连接地址(WSDL):WSDL 已含服务端点,不需单独的 REST 式 endpoint。
# 该地址存于 config['endpoint'](语义即连接地址);timeout 与 REST 同语义。
wsdl = str(config.get('endpoint') or '').strip()
if not wsdl:
raise TransportNotFrozenError('SOAP contract not frozen (missing wsdl/endpoint)')
# 真实 SOAP 调用(zeep.Client(timeout=int(config.get('timeout_seconds') or 60), ...)) 待 WSDL 冻结后落地。
raise NotImplementedError('SOAP implementation pending frozen WSDL')
@@ -103,6 +103,23 @@ def list_document_versions(document_id: int) -> list[KbDocumentVersion]:
return list(document.versions)
def resolve_training_preview_file_path(version_id: int) -> tuple[Path, str]:
"""
解析培训资料的可预览文件路径。
用途:培训配置的资料预览优先返回上传原件;部署环境未保留原件时,回退到清洗后预览文件,避免学习流程因历史文件缺失中断。
参数与输出约束:仅接受有效且未删除的知识库版本;返回存在的绝对路径及下载展示名,不存在任何可用文件时抛出 NotFoundError。
"""
version = load_document_version(version_id)
candidate_paths = (version.source_file_path, version.cleaned_preview_path, version.cleaned_file_path)
for candidate in candidate_paths:
preview_path = resolve_storage_path(candidate)
if preview_path and preview_path.exists() and preview_path.is_file():
filename = version.source_file_name or preview_path.name
return preview_path, filename
raise NotFoundError('培训资料文件不存在或已被移除')
def resolve_source_file_path(version_id: int) -> tuple[Path, str]:
"""
解析版本原始文件路径。
@@ -1,11 +1,15 @@
"""
backend/app/services/knowledge_cleaning/dify_sync_service.py
文件用途:知识库文档版本到 Dify 的最小同步服务
用途:将知识库文档版本同步至 Dify Dataset,并提供 Dataset 创建、检索和远端文档管理能力。
依赖:requests、知识库 ORM 模型及 settings_service 的运行时 Dify 配置。
逻辑:知识库 Job/文件检核历史查询调用本服务;服务读取管理端配置并向 Dify Dataset API 发起请求,结果再写回本地同步记录。
"""
from __future__ import annotations
from datetime import datetime
import hashlib
from math import isfinite
import re
import time
from pathlib import Path
@@ -33,6 +37,54 @@ def _as_bool_setting(value: str | None) -> bool:
return str(value or '').strip().lower() in ('true', '1', 'yes', 'on')
def _as_int_setting(value: str | int | None, *, default: int, minimum: int, maximum: int) -> int:
"""
解析受边界约束的整数配置,兼容旧环境中尚未写入的新配置。
Args:
value: 原始配置值。
default: 原始值无效时使用的默认值。
minimum: 允许的最小值。
maximum: 允许的最大值。
Returns:
int: 位于最小值和最大值之间的整数。
"""
try:
parsed = int(str(value).strip())
except (TypeError, ValueError):
parsed = default
return max(minimum, min(parsed, maximum))
def _as_float_setting(
value: str | float | int | None,
*,
default: float,
minimum: float,
maximum: float,
) -> float:
"""
解析受边界约束的浮点配置,兼容旧环境中尚未写入的新配置。
Args:
value: 原始配置值。
default: 原始值无效时使用的默认值。
minimum: 允许的最小值。
maximum: 允许的最大值。
Returns:
float: 位于最小值和最大值之间的浮点数。
"""
try:
parsed = float(str(value).strip())
except (TypeError, ValueError):
parsed = default
if not isfinite(parsed):
parsed = default
return max(minimum, min(parsed, maximum))
def resolve_source_file_ext(version: KbDocumentVersion) -> str | None:
"""Lowercase extension without dot, e.g. xlsx."""
ext = str(version.source_file_ext or '').strip().lower().lstrip('.')
@@ -50,7 +102,17 @@ class KbDifySyncError(RuntimeError):
class KbDifySyncService:
"""封装知识库与 Dify Dataset API 的同步及检索交互。"""
def __init__(self) -> None:
"""
读取当前运行时 Dify 配置并初始化 Dataset API 客户端参数。
核心逻辑:管理端保存的 AppSetting 优先于部署环境变量;新建 Dataset 时使用其中的检索模型默认值。
Returns:
None.
"""
settings = get_kb_dify_settings()
self.base_url = str(settings.get('DIFY_API_BASE') or '').rstrip('/')
self.api_key = str(settings.get('DIFY_API_KEY') or '').strip()
@@ -58,13 +120,26 @@ class KbDifySyncService:
self.indexing_technique = str(settings.get('KB_DIFY_INDEXING_TECHNIQUE') or 'high_quality')
self.search_method = str(settings.get('KB_DIFY_SEARCH_METHOD') or 'semantic_search')
self.doc_form = str(settings.get('KB_DIFY_DOC_FORM') or 'text_model')
self.reranking_enable = _as_bool_setting(settings.get('KB_DIFY_RERANKING_ENABLE', 'true'))
self.top_k = _as_int_setting(settings.get('KB_DIFY_TOP_K'), default=5, minimum=1, maximum=10)
self.score_threshold_enabled = _as_bool_setting(settings.get('KB_DIFY_SCORE_THRESHOLD_ENABLED'))
self.score_threshold = _as_float_setting(
settings.get('KB_DIFY_SCORE_THRESHOLD'),
default=0.25,
minimum=0.0,
maximum=1.0,
)
self.process_mode = str(settings.get('KB_DIFY_PROCESS_MODE') or 'automatic').strip().lower()
self.process_mode_excel = str(settings.get('KB_DIFY_PROCESS_MODE_EXCEL') or 'custom').strip().lower()
self.segment_separator = _decode_separator(str(settings.get('KB_DIFY_SEGMENT_SEPARATOR') or '\\n\\n'))
self.segment_separator_excel = _decode_separator(
str(settings.get('KB_DIFY_SEGMENT_SEPARATOR_EXCEL') or '\\n\\n')
)
self.segment_max_tokens = int(str(settings.get('KB_DIFY_SEGMENT_MAX_TOKENS') or '800'))
# 普通文档与 Excel/CSV 使用独立 Token 上限,避免放大表格分段影响制度类文档。
self.segment_max_tokens = int(str(settings.get('KB_DIFY_SEGMENT_MAX_TOKENS') or '600'))
self.segment_max_tokens_excel = int(
str(settings.get('KB_DIFY_SEGMENT_MAX_TOKENS_EXCEL') or '1200')
)
self.segment_chunk_overlap = int(str(settings.get('KB_DIFY_SEGMENT_CHUNK_OVERLAP') or '50'))
self.remove_urls_emails = _as_bool_setting(settings.get('KB_DIFY_REMOVE_URLS'))
self.timeout = 60
@@ -77,9 +152,11 @@ class KbDifySyncService:
if ext in _EXCEL_SOURCE_EXTENSIONS:
mode = self.process_mode_excel
separator = self.segment_separator_excel
max_tokens = self.segment_max_tokens_excel
else:
mode = self.process_mode
separator = self.segment_separator
max_tokens = self.segment_max_tokens
if mode != 'custom':
return {'mode': 'automatic'}
@@ -93,7 +170,7 @@ class KbDifySyncService:
],
'segmentation': {
'separator': separator,
'max_tokens': self.segment_max_tokens,
'max_tokens': max_tokens,
'chunk_overlap': self.segment_chunk_overlap,
},
},
@@ -134,6 +211,21 @@ class KbDifySyncService:
return payload.get('data', []) if isinstance(payload, dict) else []
def create_dataset(self, *, name: str, description: str | None) -> dict:
"""
在 Dify 中创建知识库 Dataset,并写入管理端配置的默认检索模型。
核心逻辑:组合权限、索引和 retrieval_model 配置后调用 Dify ``POST /datasets``;仅在本地分组尚未绑定 Dataset 时由同步流程触发。
Args:
name: Dataset 名称,必须是知识库分组的非空显示名称。
description: Dataset 说明;未提供时向 Dify 提交空字符串。
Returns:
dict: Dify 创建 Dataset 接口返回的原始 JSON。
Raises:
KbDifySyncError: Dify 地址、密钥未配置或远端创建请求失败。
"""
payload = {
'name': name,
'description': description or '',
@@ -142,10 +234,10 @@ class KbDifySyncService:
'doc_form': self.doc_form,
'retrieval_model': {
'search_method': self.search_method,
'reranking_enable': False,
'top_k': 5,
'score_threshold_enabled': True,
'score_threshold': 0.25,
'reranking_enable': self.reranking_enable,
'top_k': self.top_k,
'score_threshold_enabled': self.score_threshold_enabled,
'score_threshold': self.score_threshold,
},
}
return self._request('POST', '/datasets', json=payload)
@@ -219,7 +311,7 @@ class KbDifySyncService:
Args:
dataset_id: Dify Dataset UUID。
query: 检索问题。
top_k: 返回片段数(1–20)。
top_k: 返回片段数(1–10)。
score_threshold: 相似度阈值;为 None 时不启用阈值过滤。
Returns:
@@ -228,10 +320,10 @@ class KbDifySyncService:
normalized_query = str(query or '').strip()
if not normalized_query:
raise KbDifySyncError('检索 query 不能为空')
normalized_top_k = max(1, min(int(top_k or 5), 20))
normalized_top_k = _as_int_setting(top_k, default=5, minimum=1, maximum=10)
retrieval_model: dict[str, object] = {
'search_method': self.search_method,
'reranking_enable': False,
'reranking_enable': self.reranking_enable,
'top_k': normalized_top_k,
}
if score_threshold is None:
@@ -239,7 +331,12 @@ class KbDifySyncService:
retrieval_model['score_threshold'] = None
else:
retrieval_model['score_threshold_enabled'] = True
retrieval_model['score_threshold'] = max(0.0, min(float(score_threshold), 1.0))
retrieval_model['score_threshold'] = _as_float_setting(
score_threshold,
default=0.3,
minimum=0.0,
maximum=1.0,
)
payload = {
'query': normalized_query,
'retrieval_model': retrieval_model,
@@ -1,242 +0,0 @@
"""
backend/app/services/knowledge_cleaning/dify_sync_service.py
文件用途:知识库文档版本到 Dify 的最小同步服务
"""
from __future__ import annotations
from datetime import datetime
import hashlib
from pathlib import Path
import requests
from app import db
from app.models import KbDifySyncRecord, KbDocumentVersion, KbGroup
from app.services.knowledge_cleaning.settings_service import get_kb_dify_settings
class KbDifySyncError(RuntimeError):
pass
class KbDifySyncService:
def __init__(self) -> None:
settings = get_kb_dify_settings()
self.base_url = str(settings.get('DIFY_API_BASE') or '').rstrip('/')
self.api_key = str(settings.get('DIFY_API_KEY') or '').strip()
self.permission = str(settings.get('KB_DIFY_PERMISSION') or 'only_me')
self.indexing_technique = str(settings.get('KB_DIFY_INDEXING_TECHNIQUE') or 'high_quality')
self.search_method = str(settings.get('KB_DIFY_SEARCH_METHOD') or 'semantic_search')
self.doc_form = str(settings.get('KB_DIFY_DOC_FORM') or 'text_model')
self.timeout = 60
def _headers(self) -> dict[str, str]:
if not self.base_url:
raise KbDifySyncError('DIFY_API_BASE 未配置')
if not self.api_key:
raise KbDifySyncError('DIFY_API_KEY 未配置')
return {
'Authorization': f'Bearer {self.api_key}',
'Content-Type': 'application/json',
}
def _request(self, method: str, path: str, **kwargs):
url = f'{self.base_url}{path}'
try:
response = requests.request(
method,
url,
headers=self._headers(),
timeout=self.timeout,
**kwargs,
)
except requests.RequestException as exc:
raise KbDifySyncError(f'Dify API {method} {path} 请求失败: {exc}') from exc
if response.status_code >= 400:
raise KbDifySyncError(
f'Dify API {method} {path} failed: {response.status_code} {response.text}'
)
if response.status_code == 204:
return None
return response.json()
def list_datasets(self) -> list[dict]:
payload = self._request('GET', '/datasets')
return payload.get('data', []) if isinstance(payload, dict) else []
def create_dataset(self, *, name: str, description: str | None) -> dict:
payload = {
'name': name,
'description': description or '',
'permission': self.permission,
'indexing_technique': self.indexing_technique,
'doc_form': self.doc_form,
'retrieval_model': {
'search_method': self.search_method,
'reranking_enable': False,
'top_k': 3,
'score_threshold_enabled': False,
'score_threshold': None,
},
}
return self._request('POST', '/datasets', json=payload)
def ensure_dataset(self, group: KbGroup) -> tuple[str, str]:
if group.dify_dataset_id:
return group.dify_dataset_id, group.dify_dataset_name or group.name
dataset_name = group.dify_dataset_name or group.name
existing = next((item for item in self.list_datasets() if item.get('name') == dataset_name), None)
if existing:
group.dify_dataset_id = existing.get('id')
group.dify_dataset_name = existing.get('name') or dataset_name
db.session.commit()
return group.dify_dataset_id, group.dify_dataset_name
created = self.create_dataset(name=dataset_name, description=group.description)
group.dify_dataset_id = created.get('id')
group.dify_dataset_name = created.get('name') or dataset_name
db.session.commit()
return group.dify_dataset_id, group.dify_dataset_name
def create_document_by_text(self, *, dataset_id: str, name: str, text: str) -> dict:
payload = {
'name': name,
'text': text,
'indexing_technique': self.indexing_technique,
'doc_form': self.doc_form,
'process_rule': {'mode': 'automatic'},
}
return self._request('POST', f'/datasets/{dataset_id}/document/create-by-text', json=payload)
def update_document_by_text(self, *, dataset_id: str, document_id: str, name: str, text: str) -> dict:
payload = {
'name': name,
'text': text,
'process_rule': {'mode': 'automatic'},
}
return self._request(
'POST',
f'/datasets/{dataset_id}/documents/{document_id}/update-by-text',
json=payload,
)
def _load_sync_text(version: KbDocumentVersion) -> tuple[str, str]:
candidate_paths = [version.cleaned_file_path, version.cleaned_preview_path, version.source_file_path]
for value in candidate_paths:
if not value:
continue
path = Path(value)
if not path.exists():
continue
text = path.read_text(encoding='utf-8', errors='ignore').strip()
if text:
return text, str(path)
raise KbDifySyncError('没有可用于同步的文本结果')
def sync_document_version_to_dify(document_version_id: int, synced_by_id: int | None = None) -> dict:
version = db.session.get(KbDocumentVersion, document_version_id)
if not version or not version.document or not version.document.group:
raise KbDifySyncError('文档版本或关联分组不存在')
group = version.document.group
document = version.document
text, source_path = _load_sync_text(version)
sync_hash = hashlib.sha256(text.encode('utf-8')).hexdigest()
service = KbDifySyncService()
dataset_id, dataset_name = service.ensure_dataset(group)
existing_record = (
db.session.query(KbDifySyncRecord)
.filter(
KbDifySyncRecord.document_id == document.id,
KbDifySyncRecord.remote_document_id.isnot(None),
)
.order_by(KbDifySyncRecord.updated_at.desc(), KbDifySyncRecord.id.desc())
.first()
)
remote_document_id = None
remote_document_name = None
if existing_record and existing_record.sync_hash == sync_hash:
remote_document_id = existing_record.remote_document_id
remote_document_name = existing_record.remote_document_name
elif existing_record and existing_record.dataset_id == dataset_id:
try:
payload = service.update_document_by_text(
dataset_id=dataset_id,
document_id=existing_record.remote_document_id,
name=document.title,
text=text,
)
except KbDifySyncError as exc:
error_text = str(exc)
remote_missing = (
'404' in error_text
and ('Document not found' in error_text or '"code":"not_found"' in error_text)
)
if not remote_missing:
raise
payload = service.create_document_by_text(
dataset_id=dataset_id,
name=document.title,
text=text,
)
remote_document_id = payload.get('document', {}).get('id') or payload.get('id') or existing_record.remote_document_id
remote_document_name = payload.get('document', {}).get('name') or document.title
else:
payload = service.create_document_by_text(
dataset_id=dataset_id,
name=document.title,
text=text,
)
remote_document_id = payload.get('document', {}).get('id') or payload.get('id')
remote_document_name = payload.get('document', {}).get('name') or document.title
if not remote_document_id:
raise KbDifySyncError('Dify 未返回远端文档 ID')
record = (
db.session.query(KbDifySyncRecord)
.filter(
KbDifySyncRecord.document_version_id == version.id,
KbDifySyncRecord.remote_document_id == remote_document_id,
)
.first()
)
if not record:
record = KbDifySyncRecord(
group_id=group.id,
document_id=document.id,
document_version_id=version.id,
dataset_id=dataset_id,
dataset_name=dataset_name,
remote_document_id=remote_document_id,
remote_document_name=remote_document_name,
status='synced',
sync_hash=sync_hash,
synced_by_id=synced_by_id,
)
db.session.add(record)
else:
record.dataset_id = dataset_id
record.dataset_name = dataset_name
record.remote_document_name = remote_document_name
record.status = 'synced'
record.sync_hash = sync_hash
record.error_message = None
record.synced_by_id = synced_by_id
record.synced_at = datetime.utcnow()
db.session.commit()
return {
'dataset_id': dataset_id,
'dataset_name': dataset_name,
'remote_document_id': remote_document_id,
'remote_document_name': remote_document_name,
'sync_hash': sync_hash,
'source_path': source_path,
}
@@ -1,15 +1,20 @@
"""
backend/app/services/knowledge_cleaning/settings_service.py
文件用途:知识库 Dify 设置读写服务
用途:读取、校验并持久化知识库 Dify 连接、同步和检索模型默认配置。
依赖:AppSetting、env_persistence、Flask current_app 及知识库同步相关 ORM 模型。
逻辑:知识库 Dify API 调用本模块读写运行时配置;KbDifySyncService 随后读取这些配置以创建 Dataset 或检索文档。
"""
from __future__ import annotations
import os
from math import isfinite
from flask import current_app
from app import db
from app.core.config.env_persistence import persist_env_settings
from app.core.errors import ValidationError
from app.models import AppSetting, KbDifySyncRecord, KbGroup, KbJob, KbDocumentVersion
@@ -21,17 +26,172 @@ SETTING_DEFAULTS = {
# 混合检索同时利用关键词与向量相似度,适合“水型灭火器/A 类火灾”等实体明确问法。
'KB_DIFY_SEARCH_METHOD': 'hybrid_search',
'KB_DIFY_DOC_FORM': 'text_model',
# Dify Dataset 创建/检索使用的默认 retrieval_model 参数。
'KB_DIFY_RERANKING_ENABLE': 'true',
'KB_DIFY_TOP_K': '5',
'KB_DIFY_SCORE_THRESHOLD_ENABLED': 'true',
'KB_DIFY_SCORE_THRESHOLD': '0.25',
# 普通制度文档也按空行保留完整知识单元,避免标题、适用范围和禁用条件被拆散。
'KB_DIFY_PROCESS_MODE': 'custom',
'KB_DIFY_PROCESS_MODE_EXCEL': 'custom',
'KB_DIFY_SEGMENT_SEPARATOR': '\\n\\n',
'KB_DIFY_SEGMENT_SEPARATOR_EXCEL': '\\n\\n',
# 普通文档的 Dify 自定义分段上限;保持原值,避免制度类文档分段变大。
'KB_DIFY_SEGMENT_MAX_TOKENS': '600',
# Excel/CSV 专用的 Dify 分段上限;表格行较长时允许一个 Segment 容纳更多完整行。
'KB_DIFY_SEGMENT_MAX_TOKENS_EXCEL': '1200',
'KB_DIFY_SEGMENT_CHUNK_OVERLAP': '100',
'KB_DIFY_REMOVE_URLS': 'false',
}
def _normalize_retrieval_settings(values: dict[str, object]) -> dict[str, object]:
"""
校验并规范化管理端提交的 Dify 检索及文档分段参数,防止无效值持久化后导致 Dify 请求失败。
Args:
values: API 提交的配置键值,可能只包含部分可编辑项。
Returns:
dict[str, object]: 保留其他字段,并将布尔值和数值转换为可安全持久化的标准值。
Raises:
ValidationError: 布尔值、Top K、相似度阈值或分段参数不在支持范围内。
"""
normalized = dict(values)
for key in ('KB_DIFY_RERANKING_ENABLE', 'KB_DIFY_SCORE_THRESHOLD_ENABLED'):
if key not in normalized:
continue
value = normalized[key]
if isinstance(value, bool):
normalized[key] = value
continue
text = str(value or '').strip().lower()
if text not in ('true', 'false'):
raise ValidationError(f'{key} 必须为 true 或 false')
normalized[key] = text == 'true'
if 'KB_DIFY_TOP_K' in normalized:
raw_top_k = normalized['KB_DIFY_TOP_K']
try:
if isinstance(raw_top_k, bool):
raise ValueError
top_k = int(str(raw_top_k).strip())
except (TypeError, ValueError):
raise ValidationError('KB_DIFY_TOP_K 必须是 1 到 10 的整数')
if not 1 <= top_k <= 10:
raise ValidationError('KB_DIFY_TOP_K 必须是 1 到 10 的整数')
normalized['KB_DIFY_TOP_K'] = top_k
if 'KB_DIFY_SCORE_THRESHOLD' in normalized:
raw_threshold = normalized['KB_DIFY_SCORE_THRESHOLD']
try:
if isinstance(raw_threshold, bool):
raise ValueError
threshold = float(str(raw_threshold).strip())
except (TypeError, ValueError):
raise ValidationError('KB_DIFY_SCORE_THRESHOLD 必须是 0 到 1 的数值')
if not isfinite(threshold) or not 0 <= threshold <= 1:
raise ValidationError('KB_DIFY_SCORE_THRESHOLD 必须是 0 到 1 的数值')
normalized['KB_DIFY_SCORE_THRESHOLD'] = threshold
segment_max_tokens = _normalize_positive_integer_setting(
normalized,
'KB_DIFY_SEGMENT_MAX_TOKENS',
minimum=1,
maximum=10000,
)
excel_segment_max_tokens = _normalize_positive_integer_setting(
normalized,
'KB_DIFY_SEGMENT_MAX_TOKENS_EXCEL',
minimum=1,
maximum=10000,
)
segment_chunk_overlap = _normalize_positive_integer_setting(
normalized,
'KB_DIFY_SEGMENT_CHUNK_OVERLAP',
minimum=0,
maximum=9999,
)
effective_segment_max_tokens = segment_max_tokens if segment_max_tokens is not None else _get_positive_integer_setting(
'KB_DIFY_SEGMENT_MAX_TOKENS',
default=600,
)
# Excel 专用上限独立校验;未提交时读取已保存值,避免 PATCH 单字段时误判。
effective_excel_segment_max_tokens = (
excel_segment_max_tokens
if excel_segment_max_tokens is not None
else _get_positive_integer_setting('KB_DIFY_SEGMENT_MAX_TOKENS_EXCEL', default=1200)
)
effective_segment_chunk_overlap = segment_chunk_overlap if segment_chunk_overlap is not None else _get_positive_integer_setting(
'KB_DIFY_SEGMENT_CHUNK_OVERLAP',
default=100,
)
if effective_segment_chunk_overlap >= effective_segment_max_tokens:
raise ValidationError('KB_DIFY_SEGMENT_CHUNK_OVERLAP 必须小于 KB_DIFY_SEGMENT_MAX_TOKENS')
if effective_segment_chunk_overlap >= effective_excel_segment_max_tokens:
raise ValidationError(
'KB_DIFY_SEGMENT_CHUNK_OVERLAP 必须小于 KB_DIFY_SEGMENT_MAX_TOKENS_EXCEL'
)
return normalized
def _normalize_positive_integer_setting(
values: dict[str, object],
key: str,
*,
minimum: int,
maximum: int,
) -> int | None:
"""
校验并标准化一个可选的正整数运行时配置。
Args:
values: 管理端提交的可持久化配置。
key: 要校验的配置键。
minimum: 允许的最小整数。
maximum: 允许的最大整数。
Returns:
int | None: 键未提交时返回 None,否则返回已标准化整数。
Raises:
ValidationError: 值不是指定范围内的整数。
"""
if key not in values:
return None
raw_value = values[key]
try:
if isinstance(raw_value, bool):
raise ValueError
normalized_value = int(str(raw_value).strip())
except (TypeError, ValueError):
raise ValidationError(f'{key} 必须是 {minimum} 到 {maximum} 的整数')
if not minimum <= normalized_value <= maximum:
raise ValidationError(f'{key} 必须是 {minimum} 到 {maximum} 的整数')
values[key] = normalized_value
return normalized_value
def _get_positive_integer_setting(key: str, *, default: int) -> int:
"""
读取当前已保存的整数配置,用于校验 PATCH 中未提交的关联字段。
Args:
key: 要读取的运行时配置键。
default: 当前值缺失或无效时使用的安全默认值。
Returns:
int: 当前设置或安全默认值。
"""
try:
value = int(_get_setting_value(key))
except (TypeError, ValueError):
return default
return value if value >= 0 else default
def _get_setting_value(key: str) -> str:
row = db.session.get(AppSetting, key)
if row and row.value is not None:
@@ -49,7 +209,20 @@ def get_kb_dify_settings() -> dict:
def save_kb_dify_settings(values: dict[str, object]) -> dict:
"""
保存知识库 Dify 配置,并在写入前校验检索参数的类型与取值范围。
Args:
values: 管理端提交的部分或全部知识库 Dify 设置。
Returns:
dict: 读取后的完整设置和 Dify API Key 是否已配置标记。
Raises:
ValidationError: Top K、阈值或布尔开关无效。
"""
allowed = {key: values[key] for key in SETTING_DEFAULTS if key in values}
allowed = _normalize_retrieval_settings(allowed)
persisted = persist_env_settings(allowed)
return {
**get_kb_dify_settings(),
@@ -0,0 +1,213 @@
"""
backend/app/services/lean_training_push_service.py
用途:按"每周任务数量"分批推送精益培训视频给受训对象并发送企微通知,记录每轮推送日志;
同时承担"每周自动滚动创建当周任务"与"推送成功后立即提醒已延期人员"两项周任务规则。
依赖:LeanTrainingWeeklyTask/LeanTrainingVideoPushLog/LeanTrainingReminder/User、lean_training_service(受训对象/当周边界)、lean_training_reminder_service(企微发送模板/延期提醒)、wecom_notify。
逻辑:以 task.pushed_video_count 为游标,按视频冻结顺序每次取 weekly_count 个视频;员工端展示已推送前缀;
企微 event_key 按"批次区间"幂等防止重复打扰;每轮执行写入 lean_training_video_push_logs 便于管理端查看失败明细;
排程入口每周一 09:00 先自动滚动创建当周任务(复制最近一期配置,无需人工维护),再对各任务推进一批推送。
"""
from __future__ import annotations
from datetime import datetime
from sqlalchemy import select
from app.extensions import db
from app.models import LeanTrainingVideoPushLog, LeanTrainingWeeklyTask, User
from app.services.lean_training_reminder_service import (
_send_reminder,
notify_overdue_users_after_push,
send_initial_target_notifications,
)
from app.services.lean_training_service import _current_week_bounds, target_user_ids_for_task
from app.services.schedule.timezone_util import utc_now_naive
VIDEO_PUSH_EVENT_TYPE = "training_lean_video_push"
def ensure_current_week_task(*, now: datetime | None = None) -> LeanTrainingWeeklyTask | None:
"""
每周自动滚动:当周任务不存在时,以最近一期已发布任务为模板自动创建当周任务(无需人工维护)。
Args:
now: 覆盖当前时间(UTC naive,测试用)。
Returns:
当周任务(已存在或新建);系统内尚无任何历史任务模板时返回 None,等待管理员手动发布。
业务约束:
- 任务周=当周周一、截止时间=当周周日 23:59:59(服务端计算,每周自动更新);
- 模板仅从"严格早于当周"的最近一期已发布任务选取:任务周已支持管理员指定任意自然周,
必须排除未来周任务,避免其(更大游标/不同配置)污染当周滚动进度;
- 模板复制视频冻结列表、每周推送数量与受训对象;推送游标继承模板进度,
保证"推过的视频不重复推",跨周按视频列表顺序连续推进直至全部推完。
"""
week_start, due_at = _current_week_bounds(now)
week_key = week_start.isoformat()
existing = db.session.execute(select(LeanTrainingWeeklyTask).where(LeanTrainingWeeklyTask.week_key == week_key)).scalar_one_or_none()
if existing:
return existing
template = db.session.execute(
select(LeanTrainingWeeklyTask)
.where(LeanTrainingWeeklyTask.status == "published", LeanTrainingWeeklyTask.week_key < week_key)
.order_by(LeanTrainingWeeklyTask.week_key.desc())
).scalars().first()
if not template:
return None
# [STEP 1] 复制最近一期配置滚动创建当周任务(视频列表沿用冻结顺序,游标继承已推送进度避免重复推送)
task = LeanTrainingWeeklyTask(
config_id=template.config_id,
week_key=week_key,
created_by_id=template.created_by_id,
weekly_count=template.weekly_count,
pushed_video_count=template.pushed_video_count,
due_at=due_at,
video_resource_ids=list(template.video_resource_ids or []),
target_roles=list(template.target_roles or []),
target_user_ids=list(template.target_user_ids or []),
status="published",
)
db.session.add(task)
db.session.commit()
# [STEP 2] 同步发送任务发布通知(幂等),受训员工发布后立即可学
send_initial_target_notifications(task.id, now=now)
return task
def pending_video_ids(task: LeanTrainingWeeklyTask) -> list[int]:
"""返回当前任务尚未推送的视频 ID 列表(保持选择顺序,供游标推进与耗尽判断使用)。"""
return list(task.video_resource_ids or [])[task.pushed_video_count:]
def serialize_push_log(log: LeanTrainingVideoPushLog) -> dict[str, object]:
"""序列化推送日志,供管理端展示每轮推送的批次、数量与失败原因。"""
return {
"id": log.id,
"weekly_task_id": log.weekly_task_id,
"trigger": log.trigger,
"pushed_resource_ids": list(log.pushed_resource_ids or []),
"pushed_count": log.pushed_count,
"recipient_count": log.recipient_count,
"sent_count": log.sent_count,
"skipped_count": log.skipped_count,
"failed_count": log.failed_count,
"status": log.status,
"error_message": log.error_message,
"created_by_id": log.created_by_id,
"created_at": log.created_at.isoformat() if log.created_at else None,
}
def list_push_logs(task_id: int, *, limit: int = 50) -> list[dict[str, object]]:
"""按时间倒序返回指定周任务的推送日志,供管理端"推送记录"区块展示。"""
logs = db.session.execute(
select(LeanTrainingVideoPushLog)
.where(LeanTrainingVideoPushLog.weekly_task_id == task_id)
.order_by(LeanTrainingVideoPushLog.id.desc())
.limit(limit)
).scalars().all()
return [serialize_push_log(log) for log in logs]
def push_lean_training_videos(
task_id: int,
*,
trigger: str = "schedule",
current_user_id: int | None = None,
now: datetime | None = None,
) -> dict[str, object]:
"""
推送下一批精益培训视频(数量=weekly_count)并写推送日志。
Args:
task_id: 精益周任务 ID,必须为已发布状态。
trigger: 推送来源,publish=发布任务立即推首批 / schedule=每周一排程 / manual=管理端手动推送。
current_user_id: 手动推送时的操作人,写入日志审计。
now: 覆盖当前时间(测试用)。
Returns:
含 status(completed=无待推视频/partial/failed/sent)、batch、counts 与日志字段的 dict。
业务约束:企微发送失败不影响游标前进(员工端已可见视频),失败明细仅记录在日志中。
"""
task = db.session.get(LeanTrainingWeeklyTask, task_id)
if not task or task.status != "published":
raise ValueError("Lean training weekly task not found")
current = now or utc_now_naive()
# [STEP 1] 计算本批视频:按选择顺序从游标起取 weekly_count 个;无待推视频时视为全部推送完
batch = pending_video_ids(task)[: task.weekly_count]
if not batch:
return {"status": "completed", "message": "all videos pushed", "pushed_count": 0}
start_index = task.pushed_video_count
event_key = f"video-push-{start_index}-{start_index + len(batch)}"
# [STEP 2] 面向全体在职受训对象发送企微通知;event_key 按批次区间幂等,同批重推不重复打扰
recipients = db.session.execute(
select(User).where(User.id.in_(target_user_ids_for_task(task)), User.status == "active")
).scalars().all()
counts = {"sent": 0, "skipped": 0, "failed": 0}
failure_details: list[str] = []
for recipient in recipients:
result = _send_reminder(
task=task,
recipient=recipient,
event_key=event_key,
event_type=VIDEO_PUSH_EVENT_TYPE,
title="精益管理培训视频推送",
content=f"本周精益管理培训已更新,请观看 {len(batch)} 个新视频并提交不少于50字的学习感悟。",
current=current,
)
counts[result] = counts.get(result, 0) + 1
if result == "failed" and recipient.id not in {line.split(":")[0] for line in failure_details}:
failure_details.append(f"{recipient.id}:{recipient.real_name or recipient.username}")
# [STEP 3] 游标前进(企微失败不回退,员工端已可见该批视频),并落盘本轮推送日志
task.pushed_video_count = start_index + len(batch)
status = "sent" if counts["failed"] == 0 else ("failed" if counts["sent"] == 0 and counts["skipped"] == 0 else "partial")
log = LeanTrainingVideoPushLog(
weekly_task_id=task.id,
trigger=trigger,
pushed_resource_ids=batch,
pushed_count=len(batch),
recipient_count=len(recipients),
sent_count=counts["sent"],
skipped_count=counts["skipped"],
failed_count=counts["failed"],
status=status,
error_message=";".join(failure_details)[:2000] if failure_details else None,
created_by_id=current_user_id,
)
db.session.add(log)
db.session.commit()
# [STEP 4] 消息推送规则:本批推送成功后立马对任务中"已延期"(过截止未提交)的受训人员发送企微提醒
notify_overdue_users_after_push(
task,
event_key=f"overdue-after-push-{start_index}-{start_index + len(batch)}",
current=current,
)
return serialize_push_log(log)
def run_lean_training_video_push(*, now: datetime | None = None) -> dict[str, object]:
"""
排程入口(每周一 09:00):先自动滚动创建当周任务(无需人工维护),再对当周任务推进一批视频推送。
业务约束:
- 仅推进当周任务,保证"视频列表顺序分批、跨周连续、不重复推"的单一进度线;
- 历史任务不再由排程推进,其补推由管理端手动触发(立即新增任务补推);
- 系统内尚无任务模板时无事可做,返回 completed 汇总。
"""
current = now or utc_now_naive()
week_task = ensure_current_week_task(now=current)
if week_task is None:
return {"tasks": 0, "pushed": 0, "sent": 0, "skipped": 0, "failed": 0, "completed": 1, "task_results": []}
result = push_lean_training_videos(week_task.id, trigger="schedule", now=current)
if result.get("status") == "completed":
return {"tasks": 1, "pushed": 0, "sent": 0, "skipped": 0, "failed": 0, "completed": 1, "task_results": []}
return {
"tasks": 1,
"pushed": int(result.get("pushed_count") or 0),
"sent": int(result.get("sent_count") or 0),
"skipped": int(result.get("skipped_count") or 0),
"failed": int(result.get("failed_count") or 0),
"completed": 0,
"task_results": [result],
}
@@ -0,0 +1,234 @@
"""
backend/app/services/lean_training_reminder_service.py
用途:执行精益管理周度培训的企微提醒生成与发送。
依赖:精益培训任务/完成/提醒模型、User、wecom_notify。
逻辑:排程按周日截止、周一/周三/周五催学规则写入幂等提醒,再由统一企微服务发送并落审计。
"""
from __future__ import annotations
import uuid
from datetime import datetime, timezone
from flask import current_app
from sqlalchemy import select
from sqlalchemy.exc import IntegrityError
from app.extensions import db
from app.models import LeanTrainingCompletion, LeanTrainingReminder, LeanTrainingWeeklyTask, User
from app.services.lean_training_service import target_user_ids_for_task
from app.services.wecom_notify import send_wecom_event_message
from app.services.schedule.timezone_util import resolve_schedule_tzinfo, utc_now_naive
def _send_reminder(
*,
task: LeanTrainingWeeklyTask,
recipient: User,
event_key: str,
event_type: str,
title: str,
content: str,
current: datetime,
) -> str:
reminder = db.session.execute(
select(LeanTrainingReminder).where(
LeanTrainingReminder.weekly_task_id == task.id,
LeanTrainingReminder.recipient_user_id == recipient.id,
LeanTrainingReminder.event_key == event_key,
)
).scalar_one_or_none()
if reminder:
return "skipped"
reminder = LeanTrainingReminder(
weekly_task_id=task.id,
recipient_user_id=recipient.id,
event_key=event_key,
)
try:
with db.session.begin_nested():
db.session.add(reminder)
db.session.flush()
except IntegrityError:
return "skipped"
# [STEP] 企微卡片跳转地址:指向员工培训聊天页(agent 16),由前端消费 training_type=lean_management
# 自动展开精益页签;agent id 走配置,便于多环境调整,避免硬编码。
jump_agent_id = int(current_app.config.get("WECOM_LEAN_TRAINING_JUMP_AGENT_ID") or 16)
result = send_wecom_event_message(
event_type=event_type,
user=recipient,
title=title,
content=content,
jump_path=f"/chat/{jump_agent_id}",
jump_params={"training_type": "lean_management", "weekly_task_id": task.id},
)
reminder.trace_id = result.get("trace_id")
if result.get("ok"):
reminder.status = "sent"
reminder.sent_at = current
return "sent"
reminder.status = "skipped" if result.get("reason") in {"event_disabled", "notify_disabled", "user_unbound"} else "failed"
reminder.error_message = str(result.get("reason") or "send_failed")[:255]
return reminder.status
def send_initial_target_notifications(task_id: int, *, now: datetime | None = None) -> dict[str, int]:
"""向 HR 指定的在职受训对象发送任务发布提醒,审计唯一键保证重复发布不重复推送。"""
task = db.session.get(LeanTrainingWeeklyTask, task_id)
if not task or task.status != "published":
return {"created": 0, "sent": 0, "skipped": 0, "failed": 0}
current = now or utc_now_naive()
totals = {"created": 0, "sent": 0, "skipped": 0, "failed": 0}
recipients = db.session.execute(select(User).where(User.id.in_(target_user_ids_for_task(task)))).scalars().all()
for recipient in recipients:
result = _send_reminder(
task=task,
recipient=recipient,
event_key="task-initial",
event_type="training_lean_task_initial",
title="精益管理培训任务已发布",
content="您已被指定参加本周精益管理培训,请观看指定视频并提交不少于50字的学习感悟。",
current=current,
)
totals["created"] += result != "skipped"
totals[result] += 1
db.session.commit()
return totals
def send_targeted_reminders(task_id: int, user_ids: list[int], *, now: datetime | None = None) -> dict[str, int]:
"""由 HR 对本周指定且尚未完成的员工发起定向提醒,不允许跨任务对象发送。"""
task = db.session.get(LeanTrainingWeeklyTask, task_id)
if not task or task.status != "published":
raise ValueError("Lean training weekly task not found")
current = now or utc_now_naive()
completed_user_ids = set(
db.session.execute(
select(LeanTrainingCompletion.user_id).where(
LeanTrainingCompletion.weekly_task_id == task.id,
LeanTrainingCompletion.status == "completed",
)
).scalars()
)
recipients = db.session.execute(
select(User).where(User.id.in_(user_ids), User.status == "active")
).scalars().all()
recipients_by_id = {recipient.id: recipient for recipient in recipients}
unavailable_ids = sorted(set(user_ids) - set(recipients_by_id))
if unavailable_ids:
raise ValueError("Some reminder recipients are unavailable")
forbidden_ids = sorted(set(user_ids) - target_user_ids_for_task(task))
if forbidden_ids:
raise ValueError("Some reminder recipients are outside the task target")
totals = {"created": 0, "sent": 0, "skipped": 0, "failed": 0}
for recipient in recipients:
if recipient.id in completed_user_ids:
totals["skipped"] += 1
continue
result = _send_reminder(
task=task,
recipient=recipient,
event_key=f"targeted-{uuid.uuid4().hex}",
event_type="training_lean_targeted_reminder",
title="精益管理培训定向提醒",
content="您尚未完成本周精益管理培训,请观看指定视频并提交不少于50字的学习感悟。",
current=current,
)
totals["created"] += result != "skipped"
totals[result] += 1
db.session.commit()
return totals
def notify_overdue_users_after_push(
task: LeanTrainingWeeklyTask,
*,
event_key: str,
current: datetime | None = None,
) -> dict[str, int]:
"""
视频批次推送成功后,立即对该任务中"已延期"(已过截止时间且未提交感悟)的受训人员发送企微提醒。
对应周任务消息推送规则:每次推送周任务成功后立马推送延期提醒(与批次 event_key 绑定幂等,同批重推不重复打扰)。
Args:
task: 刚完成视频推送的周任务(必须已发布)。
event_key: 幂等键,建议携带批次区间(如 overdue-after-push-0-2),与推送批次一一对应。
current: 覆盖当前时间(UTC naive,测试用)。
Returns:
{"created", "sent", "skipped", "failed"} 汇总统计。
"""
now = current or utc_now_naive()
totals = {"created": 0, "sent": 0, "skipped": 0, "failed": 0}
# 未过截止时间不存在"已延期"人员,直接返回,避免无意义扫描
if now <= task.due_at:
return totals
completed_user_ids = set(
db.session.execute(
select(LeanTrainingCompletion.user_id).where(
LeanTrainingCompletion.weekly_task_id == task.id,
LeanTrainingCompletion.status == "completed",
)
).scalars()
)
overdue_ids = target_user_ids_for_task(task) - completed_user_ids
users = db.session.execute(select(User).where(User.id.in_(overdue_ids), User.status == "active")).scalars().all() if overdue_ids else []
for user in users:
result = _send_reminder(
task=task,
recipient=user,
event_key=event_key,
event_type="training_lean_overdue",
title="精益管理培训延期提醒",
content="您本周精益管理培训已延期,尚未完成视频观看与学习感悟提交,请尽快完成。",
current=now,
)
totals["created"] += result != "skipped"
totals[result] += 1
db.session.commit()
return totals
def _event_key(task: LeanTrainingWeeklyTask, now: datetime) -> str | None:
"""按周日截止后的周一、周三、周五计算本轮逾期提醒唯一键。"""
if now <= task.due_at:
return None
local_now = now.replace(tzinfo=timezone.utc).astimezone(resolve_schedule_tzinfo("Asia/Shanghai"))
weekday = local_now.weekday()
if weekday not in {0, 2, 4}:
return None
return f"overdue-{local_now.date().isoformat()}"
def run_lean_training_reminders(*, now: datetime | None = None) -> dict[str, int]:
"""扫描未完成人员并发送本轮提醒,重复运行由唯一约束确保不重复推送。"""
current = now or utc_now_naive()
tasks = db.session.execute(select(LeanTrainingWeeklyTask).where(LeanTrainingWeeklyTask.status == "published")).scalars().all()
created = sent = skipped = failed = 0
for task in tasks:
event_key = _event_key(task, current)
if not event_key:
continue
completed_user_ids = set(db.session.execute(select(LeanTrainingCompletion.user_id).where(LeanTrainingCompletion.weekly_task_id == task.id, LeanTrainingCompletion.status == "completed")).scalars())
target_user_ids = target_user_ids_for_task(task)
users = db.session.execute(select(User).where(User.id.in_(target_user_ids - completed_user_ids))).scalars().all() if target_user_ids else []
for user in users:
result = _send_reminder(
task=task,
recipient=user,
event_key=event_key,
event_type="training_lean_overdue",
title="精益管理培训逾期提醒",
content="本周精益管理培训尚未完成,请观看指定视频并提交不少于50字的学习感悟。",
current=current,
)
created += result != "skipped"
if result == "sent":
sent += 1
elif result == "failed":
failed += 1
else:
skipped += 1
db.session.commit()
return {"created": created, "sent": sent, "skipped": skipped, "failed": failed}
Loaded 100 of 2050 files, more files were not shown because too many files have changed in this diff. Show more