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:
commit
ca9c174f29
2050 files changed
+511839
-42320
No files matched your search
@@ -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')
|
||||
|
||||
@@ -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:
|
||||
|
||||
Reference in new issue
Block a user