Merge branch 'dev' into snow

# Conflicts:
#	backend/app/api/chat.py
#	backend/app/services/admin/permission_service.py
#	frontend/src/features/user/views/UserProfilePage.vue
This commit is contained in:
HTEWJ\26070045 committed 2026-09-23 14:34:20 +08:00
commit 5faf86b184
691 files changed
+55948 -17728

No files matched your search

+1 -1
View File
@@ -27,7 +27,7 @@ from app.services.admin.training_exam_pdf_service import parse_training_question
from app.services.agent_registry.admin_payload import apply_agent_payload, validate_agent_payload
from app.services.agent_registry.catalog_loader import get_dify_required_providers
from app.services.agent_registry.serialization import serialize_agent_for_admin
from app.services.dify import DifyService
from app.services.integrations.dify import DifyService
def serialize_agent(agent: Agent) -> dict:
+1 -1
View File
@@ -14,7 +14,7 @@ from werkzeug.datastructures import FileStorage
from app import db
from app.core.errors import AppError, NotFoundError, ValidationError
from app.models import AgentGuide
from app.services.minio_service import minio_service
from app.services.integrations.minio import minio_service
GUIDE_USAGE_GENERAL = 'general'
@@ -1,8 +1,8 @@
"""
backend/app/services/admin/permission_service.py
用途:用户 Agent 权限批量/单用户更新,以及权限申请审批业务逻辑。
依赖:models、wecom_notify.send_wecom_event_message。
用途:用户 Agent 权限批量/单用户更新业务逻辑。
依赖:models、integrations.wecom.notify.send_wecom_event_message。
逻辑:由 api/admin/permissions.py 调用;users 路由 /users/<id>/permissions 亦委托本模块。
"""
from __future__ import annotations
@@ -12,7 +12,7 @@ from typing import Any
from app import db
from app.core.errors import NotFoundError, ValidationError
from app.models import Agent, User
from app.services.wecom_notify import send_wecom_event_message
from app.services.integrations.wecom.notify import send_wecom_event_message
_BATCH_ACTION_LABELS = {'add': '新增', 'remove': '移除', 'set': '重置为'}
@@ -95,67 +95,3 @@ def update_user_permissions(user_id: int, data: dict[str, Any]) -> dict:
user.agents = agents
db.session.commit()
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'}
@@ -153,13 +153,7 @@ def _customer_row_validation(raw: dict[str, Any], *, default_source_system: str)
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,
})
# 客户简码允许重复(业务规则),导入预检不再因简码撞码产生 warning。
normalized_name = normalize_customer_name(name)
similar = [
item for item in db.session.query(ShippingCustomer).all()
@@ -37,6 +37,47 @@ from app.services.shipping_notice.customer_normalization import (
CUSTOMER_STATUSES = frozenset({'active', 'inactive', 'merged'})
IDENTIFIER_STATUSES = frozenset({'pending', 'approved', 'disabled'})
_ODM_ID_MAX_ITEMS = 100
_ODM_ID_MAX_LENGTH = 64
def _normalize_odm_ids(value: Any) -> list[str] | None:
"""
规范化客户 ODM ID 清单:逐项 trim、去空、去重(保持原顺序)。
Args:
value: 前端提交的清单(字符串列表);None 表示未提交,空列表表示清空。
Returns:
规范化后的清单;None 仅当输入为 None。
Raises:
ValidationError: 条目超长或清单超量。
"""
if value is None:
return None
if not isinstance(value, list):
raise ValidationError(
'ODM ID list must be an array of strings',
code='SHIPPING.CUSTOMER_ODM_IDS_INVALID',
)
normalized: list[str] = []
for item in value:
text = str(item or '').strip()
if not text:
continue
if len(text) > _ODM_ID_MAX_LENGTH:
raise ValidationError(
'ODM ID is too long',
code='SHIPPING.CUSTOMER_ODM_IDS_INVALID',
details={'odm_id': text},
)
if text not in normalized:
normalized.append(text)
if len(normalized) > _ODM_ID_MAX_ITEMS:
raise ValidationError(
'Too many ODM IDs',
code='SHIPPING.CUSTOMER_ODM_IDS_INVALID',
)
return normalized
def _record_lifecycle_event(
@@ -142,6 +183,7 @@ def serialize_customer(
'status': record.status,
'merged_into_customer_id': record.merged_into_customer_id,
'remark': record.remark,
'odm_ids': list(record.odm_ids or []) if record.odm_ids is not None else None,
'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,
@@ -278,23 +320,12 @@ def get_customer(customer_id: int) -> dict[str, Any]:
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。
@@ -309,7 +340,6 @@ def create_customer(data: dict[str, Any], *, actor_id: int | None) -> dict[str,
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')
@@ -318,6 +348,7 @@ def create_customer(data: dict[str, Any], *, actor_id: int | None) -> dict[str,
short_code=short_code,
status=status,
remark=clean_text(data.get('remark')) or None,
odm_ids=_normalize_odm_ids(data.get('odm_ids')) if 'odm_ids' in data else None,
created_by_id=actor_id,
updated_by_id=actor_id,
)
@@ -385,11 +416,13 @@ def update_customer(customer_id: int, data: dict[str, Any], *, actor_id: int | N
'short_code': record.short_code,
'status': record.status,
'remark': record.remark,
'odm_ids': list(record.odm_ids or []) if record.odm_ids is not None else None,
}
next_name = before['standard_name']
next_short_code = before['short_code']
next_status = before['status']
next_remark = before['remark']
next_odm_ids = before['odm_ids']
if 'standard_name' in data:
name = clean_text(data.get('standard_name'))
if not name:
@@ -397,18 +430,20 @@ def update_customer(customer_id: int, data: dict[str, Any], *, actor_id: int | N
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
if 'odm_ids' in data:
next_odm_ids = _normalize_odm_ids(data.get('odm_ids'))
after = {
'standard_name': next_name,
'short_code': next_short_code,
'status': next_status,
'remark': next_remark,
'odm_ids': next_odm_ids,
}
changes = {key: {'before': before[key], 'after': after[key]} for key in before if before[key] != after[key]}
if changes:
@@ -418,6 +453,7 @@ def update_customer(customer_id: int, data: dict[str, Any], *, actor_id: int | N
record.short_code = next_short_code
record.status = next_status
record.remark = next_remark
record.odm_ids = next_odm_ids
record.updated_by_id = actor_id
_record_lifecycle_event(
record,
@@ -67,19 +67,6 @@ def _json_object(data: dict[str, Any], field: str) -> dict[str, Any]:
return dict(value)
def _json_string_list(data: dict[str, Any], field: str) -> list[str]:
"""读取非空、去重的字符串列表,供 Source 别名等业务配置使用。"""
value = data.get(field, [])
if not isinstance(value, list) or any(not isinstance(item, str) for item in value):
raise ValidationError(f'{field} must be a string list', code='SHIPPING.INVENTORY_SOURCE_CONFIG_INVALID')
result: list[str] = []
for item in value:
normalized = item.strip()
if normalized and normalized not in result:
result.append(normalized)
return result
def _validate_profile_login_config(data: dict[str, Any]) -> dict[str, str]:
"""校验连接级登录配置,不接收页面选择器或报表操作字段。"""
value = data.get('login_config_json', {})
@@ -268,20 +255,47 @@ def _source_payload(source: ShippingInventorySource) -> dict[str, Any]:
def _receipt_report_config_payload(config: ShippingReceiptReportConfig) -> dict[str, Any]:
"""序列化独立收料配置,禁止把库存路径或凭据透传至管理端。"""
profile = config.parsing_profile
return {
'id': config.id, 'inventory_source_id': config.inventory_source_id, 'enabled': bool(config.enabled),
'id': config.id, 'inventory_source_id': config.inventory_source_id,
'report_path_json': config.report_path_json or {},
'query_parameters_json': config.query_parameters_json or [],
'warehouse_ids_json': config.warehouse_ids_json or [], 'config_version': config.config_version,
# 异动解析绑定:供抽屉回显当前规则;摘要只取展示字段,不透传定义。
'parsing_profile_id': config.parsing_profile_id,
'parsing_profile': ({
'id': profile.id, 'profile_code': profile.profile_code, 'display_name': profile.display_name,
'version': profile.version, 'status': profile.status,
} if profile else None),
'config_version': config.config_version,
'created_at': _iso(config.created_at), 'updated_at': _iso(config.updated_at),
}
def _validate_movement_profile_binding(profile_id: Any) -> int | None:
"""校验收料配置绑定的异动解析规则:必须已发布且 purpose='movement';空值表示解绑。
Args:
profile_id: 请求中的 parsing_profile_id;None/空串表示解绑。
Returns:
规整后的规则 id 或 None。
Raises:
ValidationError: 规则不存在/未发布/用途不是 movement(fail-closed,防误绑库存规则)。
"""
if profile_id is None or str(profile_id).strip() == '':
return None
profile = db.session.get(ShippingInventoryParsingProfile, int(profile_id))
if profile is None or profile.status != 'published' or profile.purpose != 'movement':
raise ValidationError(
'Receipt movement parsing profile must be published with purpose movement',
code='SHIPPING.RECEIPT_MOVEMENT_PROFILE_INVALID',
)
return profile.id
def _validate_receipt_report_config(
source: ShippingInventorySource, data: dict[str, Any],
) -> tuple[bool, dict[str, str], list[dict[str, Any]], list[str]]:
"""规范收料配置,确保日期保持空值、DBS/Crane 路径与仓库拆分规则不混用。"""
enabled = _bool(data, 'enabled', True)
) -> tuple[dict[str, str], list[dict[str, Any]]]:
"""规范收料配置,与库存同构:路径+查询条件;日期禁填,DBS 以 Warehouse 条件为逐仓拆分维度。"""
try:
parameters = _validate_query_parameters(data)
except ValidationError as exc:
@@ -289,19 +303,22 @@ def _validate_receipt_report_config(
# 报表日期不筛选,避免管理端误传日期使跨日排程导出产生漏数。
if any('date' in str(item.get('name') or '').strip().lower() for item in parameters):
raise ValidationError('Receipt report date filtering is not supported', code='SHIPPING.RECEIPT_REPORT_CONFIG_INVALID')
raw_warehouses = _json_string_list(data, 'warehouse_ids_json')
raw_path = _json_object(data, 'report_path_json')
if source.connector_type == 'dbs':
try:
path = _validate_report_path('dbs', raw_path)
except ValidationError as exc:
raise ValidationError(str(exc), code='SHIPPING.RECEIPT_REPORT_CONFIG_INVALID') from exc
if enabled and not raw_warehouses:
raise ValidationError('DBS receipt report requires warehouse_ids_json', code='SHIPPING.RECEIPT_REPORT_CONFIG_INVALID')
return enabled, path, parameters, raw_warehouses
# Warehouse 条件即逐仓拆分维度(不单独持久化仓库清单):必须恰一条且至少一个有效值。
warehouse_conditions = [item for item in parameters if str(item.get('name') or '').strip().lower() == 'warehouse']
warehouse_values = [str(value or '').strip() for value in (warehouse_conditions[0].get('values') or [])] if warehouse_conditions else []
if len(warehouse_conditions) != 1 or not any(warehouse_values):
raise ValidationError(
'DBS receipt report requires exactly one Warehouse query condition with values',
code='SHIPPING.RECEIPT_REPORT_CONFIG_INVALID',
)
return path, parameters
if source.connector_type == 'crane':
if raw_warehouses:
raise ValidationError('Crane receipt report does not support Warehouse split', code='SHIPPING.RECEIPT_REPORT_CONFIG_INVALID')
if set(raw_path) - {'report_name'} or raw_path.get('report_name') not in (None, '', 'Inbound Details'):
raise ValidationError('Crane receipt report is fixed to Inbound Details', code='SHIPPING.RECEIPT_REPORT_CONFIG_INVALID')
if parameters:
@@ -309,7 +326,7 @@ def _validate_receipt_report_config(
'Crane receipt report does not support query parameters',
code='SHIPPING.RECEIPT_REPORT_CONFIG_INVALID',
)
return enabled, {'report_name': 'Inbound Details'}, [], []
return {'report_name': 'Inbound Details'}, []
raise ValidationError('Unsupported receipt connector type', code='SHIPPING.RECEIPT_REPORT_CONFIG_INVALID')
@@ -327,7 +344,7 @@ def save_receipt_report_config(source_id: int, data: dict[str, Any], *, actor_id
source = db.session.get(ShippingInventorySource, source_id)
if source is None:
raise NotFoundError('Inventory Source not found', code='SHIPPING.INVENTORY_SOURCE_NOT_FOUND')
enabled, path, parameters, warehouses = _validate_receipt_report_config(source, data)
path, parameters = _validate_receipt_report_config(source, data)
config = ShippingReceiptReportConfig.query.filter_by(inventory_source_id=source.id).one_or_none()
before = _receipt_report_config_payload(config) if config else None
is_new = config is None
@@ -337,10 +354,9 @@ def save_receipt_report_config(source_id: int, data: dict[str, Any], *, actor_id
db.session.add(config)
else:
config.config_version += 1
config.enabled = enabled
config.report_path_json = path
config.query_parameters_json = parameters
config.warehouse_ids_json = warehouses
config.parsing_profile_id = _validate_movement_profile_binding(data.get('parsing_profile_id'))
config.updated_by = actor_id
db.session.flush()
after = _receipt_report_config_payload(config)
@@ -348,7 +364,8 @@ def save_receipt_report_config(source_id: int, data: dict[str, Any], *, actor_id
event_type='shipping_receipt_report_config_saved', aggregate_type='shipping_receipt_report_config',
aggregate_id=str(source.id), actor_type='admin', actor_id=actor_id, action='create' if is_new else 'update',
result='success', before=before, after=after,
metadata={'inventory_source_id': source.id, 'connector_type': source.connector_type},
metadata={'inventory_source_id': source.id, 'connector_type': source.connector_type,
'parsing_profile_id': config.parsing_profile_id},
)
db.session.commit()
return after
@@ -1160,6 +1177,7 @@ def _external_payload(mapping: ShippingInventoryExternalMapping) -> dict[str, An
'freight_warehouse_id': mapping.freight_warehouse_id, 'external_system_code': mapping.external_system_code,
'external_organization_code': mapping.external_organization_code, 'external_site_code': mapping.external_site_code,
'external_warehouse_code': mapping.external_warehouse_code, 'external_warehouse_name': mapping.external_warehouse_name,
'in_transit_warehouse_code': mapping.in_transit_warehouse_code,
'enabled': bool(mapping.enabled), 'version': mapping.version,
}
@@ -1191,8 +1209,11 @@ def save_external_mapping(data: dict[str, Any], *, actor_id: int | None, mapping
raise ValidationError('Inventory Source not found', code='SHIPPING.INVENTORY_SOURCE_NOT_FOUND')
record = record or ShippingInventoryExternalMapping(inventory_source_id=source_id, external_system_code='', external_warehouse_code='', external_warehouse_name='')
record.inventory_source_id = source_id
# Freight warehouse is a business identity token; normalize it to match runtime inventory rows.
record.freight_warehouse_id = (_text(data, 'freight_warehouse_id') or '').upper() or None
# 货代仓库改为可选维度:inventory_match 源按「收料文件仓库 == 货代仓库」匹配映射行,
# 空值即「空库位」默认映射行;归一化为大写以与收料仓库值精确比对。
record.freight_warehouse_id = str(_text(data, 'freight_warehouse_id') or '').upper() or None
# 在途仓编码是在途调拨拨出库位来源(DefaultRouteResolver),保存端必填并大写归一。
record.in_transit_warehouse_code = str(_text(data, 'in_transit_warehouse_code', required=True)).upper()
record.external_system_code = str(_text(data, 'external_system_code', required=True)).upper()
record.external_organization_code = _text(data, 'external_organization_code')
record.external_site_code = _text(data, 'external_site_code')
@@ -20,7 +20,7 @@ from app.core.errors import NotFoundError, ValidationError
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 app.services.integrations.minio import minio_service
from edkb_system.contracts import Block, Context
from edkb_system.skills import loader_pdf, ocr
@@ -21,7 +21,7 @@ from app.core.config.env_persistence import persist_env_settings
from app.core.errors import AppError, ConflictError, NotFoundError, ValidationError
from app.models import Agent, LoginAudit, User, WecomNotifyAudit
from app.services.auth import wecom_auth_service
from app.services.oa_wecom_sync import sync_wecom_userids_from_oa
from app.services.integrations.oa.wecom_sync import sync_wecom_userids_from_oa
def serialize_debug_match_user(user: User) -> dict:
@@ -12,5 +12,7 @@ from __future__ import annotations
RUNTIME_HANDLER_BINDINGS: dict[str, str] = {
'shipping_notice': 'shipping_notice',
'file_check': 'file_check',
'contract_payment': 'contract_payment',
'voucher_check': 'voucher_check',
'in_transit_transfer': 'in_transit_transfer',
}
@@ -129,6 +129,37 @@ agent_types:
file_upload: true
human_confirm: false
handler_config_schema: {}
contract_payment:
label: 合同付款预警
conversation_mode_default: task_chat
runtime_provider_default: builtin
models:
- ContractPaymentContract
- ContractPaymentAlert
- ContractPaymentAlertBatch
required_fields: []
default_capabilities:
streaming: false
file_upload: false
task_progress: false
forced_capabilities:
file_upload: false
handler_config_schema: {}
voucher_check:
label: 立账凭证
conversation_mode_default: task_chat
runtime_provider_default: builtin
models:
- VoucherCheckRun
- VoucherCheckNotification
required_fields: []
default_capabilities:
streaming: false
file_upload: false
task_progress: false
forced_capabilities:
file_upload: false
handler_config_schema: {}
in_transit_transfer:
label: 在途仓自动调拨
conversation_mode_default: task_chat
@@ -2,7 +2,7 @@
backend/app/services/agent_registry/handlers/bootstrap.py
用途:应用启动时加载 HANDLER_REGISTRY。
依赖:handlers.shipping_notice 等领域 handler 模块。
依赖:handlers.shipping_notice、handlers.contract_payment、handlers.voucher_check 等领域 handler 模块。
逻辑:create_app 在 load_context_adapters 之后调用 load_handlers()。
"""
@@ -29,12 +29,16 @@ def load_handlers() -> None:
import importlib
import app.services.agent_registry.handlers.contract_payment as contract_payment_mod
import app.services.agent_registry.handlers.file_check as file_check_mod
import app.services.agent_registry.handlers.in_transit_transfer as in_transit_transfer_mod
import app.services.agent_registry.handlers.shipping_notice as shipping_mod
import app.services.agent_registry.handlers.voucher_check as voucher_check_mod
importlib.reload(file_check_mod)
importlib.reload(shipping_mod)
importlib.reload(contract_payment_mod)
importlib.reload(voucher_check_mod)
importlib.reload(in_transit_transfer_mod)
logger.info('Agent handlers loaded: %s', sorted(HANDLER_REGISTRY.keys()))
@@ -0,0 +1,31 @@
"""
backend/app/services/agent_registry/handlers/contract_payment.py
用途:合同付款预警 builtin Handler。第一期不走对话 completions,只满足 Catalog 对 builtin 必须声明 runtime_handler 的校验。
依赖:agent_registry.handlers.base / registry。
逻辑:Chat 主区渲染台账 Tab,不调用 Dify;prepare_stream 原样返回上下文,供后续 hybrid 接入预留。
"""
from __future__ import annotations
from typing import Any
from app.services.agent_registry.handlers.base import AgentHandler, ChatStreamContext
from app.services.agent_registry.handlers.registry import register_handler
@register_handler('contract_payment')
class ContractPaymentHandler(AgentHandler):
"""
合同付款预警业务 Handler。
核心逻辑:第一期隐藏输入框,不进入聊天流;保留钩子以便第二期改 hybrid 后注入合同摘要。
"""
def prepare_stream(self, ctx: ChatStreamContext) -> ChatStreamContext:
"""聊天流开始前原样返回上下文;第一期前端不会发起 completions。"""
return ctx
def build_ui_state_event(self, ctx: ChatStreamContext) -> dict[str, Any] | None:
"""第一期无领域 UI State;台账由独立 HTTP API 加载。"""
return None
@@ -0,0 +1,31 @@
"""
backend/app/services/agent_registry/handlers/voucher_check.py
用途:立账凭证检核 builtin Handler。第一期不走对话 completions,只满足 Catalog 对 builtin 必须声明 runtime_handler 的校验。
依赖:agent_registry.handlers.base / registry。
逻辑:Chat 主区渲染检核任务 / 企微发送记录 Tab,不调用 Dify;prepare_stream 原样返回上下文,供后续 hybrid 接入预留。
"""
from __future__ import annotations
from typing import Any
from app.services.agent_registry.handlers.base import AgentHandler, ChatStreamContext
from app.services.agent_registry.handlers.registry import register_handler
@register_handler('voucher_check')
class VoucherCheckHandler(AgentHandler):
"""
立账凭证检核业务 Handler。
核心逻辑:第一期隐藏输入框,不进入聊天流;保留钩子以便第二期改 hybrid 后注入批次摘要。
"""
def prepare_stream(self, ctx: ChatStreamContext) -> ChatStreamContext:
"""聊天流开始前原样返回上下文;第一期前端不会发起 completions。"""
return ctx
def build_ui_state_event(self, ctx: ChatStreamContext) -> dict[str, Any] | None:
"""第一期无领域 UI State;检核列表由独立 HTTP API 加载。"""
return None
@@ -15,7 +15,7 @@ from app.services.chat.executors.base import (
ChatStreamContext,
build_dify_inputs_for_context,
)
from app.services.dify import DifyService
from app.services.integrations.dify import DifyService
class DifyChatExecutor(ChatExecutor):
@@ -16,13 +16,13 @@ from app.services.chat.intent_route_registry import (
def _match(ctx: ChatIntentRouteContext) -> bool:
from app.services.plm_oracle import PLMOracleService
from app.services.integrations.plm.oracle import PLMOracleService
return PLMOracleService.supports(ctx.query, ctx.agent)
def _stream(ctx: ChatIntentRouteContext):
from app.services.plm_oracle import PLMOracleService
from app.services.integrations.plm.oracle import PLMOracleService
return PLMOracleService.stream_chat(
ctx.query,
@@ -27,7 +27,7 @@ def _match(ctx: ChatIntentRouteContext) -> bool:
def _stream(ctx: ChatIntentRouteContext):
from app.services.text2sql import Text2SQLService
from app.services.integrations.text2sql import Text2SQLService
return Text2SQLService.stream_chat(
ctx.query,
@@ -16,7 +16,7 @@ from typing import Any
from flask import current_app
from app.services.oa_sqlserver import OASQLServerService
from app.services.integrations.oa.sqlserver import OASQLServerService
# [STEP] 仅允许字母数字下划线作为 SQL 标识符,表名/字段来自配置,禁止拼接任意字符串。
_SAFE_IDENT = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*$")
@@ -29,7 +29,7 @@ from app.models import (
ContractPaymentNode,
User,
)
from app.services.wecom_notify import (
from app.services.integrations.wecom.notify import (
send_wecom_event_message,
send_wecom_file_message,
upload_wecom_temp_media,
@@ -53,7 +53,7 @@ def fetch_paid_records(purchase_order_nos: Iterable[str]) -> dict[str, list[ErpP
return {}
try:
import oracledb
from app.services.text2sql import Text2SQLService
from app.services.integrations.text2sql import Text2SQLService
except ImportError:
current_app.logger.warning("合同付款预警:Oracle 驱动不可用,按未付款处理")
return {}
@@ -1,9 +1,9 @@
"""
backend/app/services/contract_payment/ledger_focus.py
用途:合同台账汇总卡口径——即将到期、逾期未付、待补充、本月应付,均按合同计数。
用途:合同台账汇总卡口径——即将到期、逾期未付、进行中、本月应付,均按合同计数。
依赖:ContractPaymentContract、ContractPaymentNode、业务时区 Asia/Shanghai。
逻辑:由 list/summary API 调用;分类规则与台账行状态标签对齐,本月应付可与前两项重叠。
逻辑:由 list/summary API 调用;即将到期/逾期/进行中互斥,本月应付可与这三项重叠。行级「待补充」不进汇总卡。
"""
from __future__ import annotations
@@ -20,12 +20,12 @@ from app.models import ContractPaymentContract, ContractPaymentNode
LEDGER_FOCUS_DUE = "due"
LEDGER_FOCUS_OVERDUE = "overdue"
LEDGER_FOCUS_NEEDS_COMPLETION = "needs_completion"
LEDGER_FOCUS_ACTIVE = "active"
LEDGER_FOCUS_DUE_THIS_MONTH = "due_this_month"
LEDGER_FOCUS_VALUES = {
LEDGER_FOCUS_DUE,
LEDGER_FOCUS_OVERDUE,
LEDGER_FOCUS_NEEDS_COMPLETION,
LEDGER_FOCUS_ACTIVE,
LEDGER_FOCUS_DUE_THIS_MONTH,
}
_NEAR_DUE_DAYS = 7
@@ -68,7 +68,7 @@ def classify_ledger_status(
"""
按合同聚合出台账状态,与列表「状态」列一致。
核心逻辑:非激活或待确认 → 待补充;无进行中节点则按是否已付分为已完成/待补充;
核心逻辑:非激活或待确认 → 待补充(仅行状态,不进汇总卡);无进行中节点则按是否已付分为已完成/待补充;
进行中节点若已过到期日 → 逾期,若在今天起 7 天内 → 即将到期,否则进行中。
Args:
contract_status: 合同主状态。
@@ -80,16 +80,16 @@ def classify_ledger_status(
"""
node_list = list(nodes)
if str(contract_status or "").strip() != "active" or str(parse_status or "").strip() == "needs_review":
return LEDGER_FOCUS_NEEDS_COMPLETION
return "needs_completion"
if not node_list:
return LEDGER_FOCUS_NEEDS_COMPLETION
return "needs_completion"
active = [node for node in node_list if str(node.get("status") or "").strip().lower() == "active"]
if not active:
has_paid = any(
str(node.get("status") or "").strip().lower() == "paid" or bool(node.get("paid_at"))
for node in node_list
)
return "completed" if has_paid else LEDGER_FOCUS_NEEDS_COMPLETION
return "completed" if has_paid else "needs_completion"
refs = [
ref
for node in active
@@ -99,7 +99,7 @@ def classify_ledger_status(
return LEDGER_FOCUS_OVERDUE
if any(0 <= (ref - today).days <= _NEAR_DUE_DAYS for ref in refs):
return LEDGER_FOCUS_DUE
return "active"
return LEDGER_FOCUS_ACTIVE
def has_unpaid_due_this_month(nodes: Iterable[dict[str, Any]], today: date) -> bool:
@@ -138,7 +138,7 @@ def collect_ledger_focus(*, session: Session, today: date | None = None) -> dict
"""
扫描全部已解析台账合同,按汇总卡口径收集合同 ID。
核心逻辑:不应用页面 keyword;待确认合同不进入台账汇总。本月应付可与即将到期/逾期重叠。
核心逻辑:不应用页面 keyword;待确认合同不进入台账汇总。进行中为未到期且未逾期的未付合同;本月应付可与即将到期、逾期或进行中重叠。
Args:
session: 当前请求的 SQLAlchemy 会话。
today: 可选业务日。
@@ -154,7 +154,7 @@ def collect_ledger_focus(*, session: Session, today: date | None = None) -> dict
buckets: dict[str, set[int]] = {
LEDGER_FOCUS_DUE: set(),
LEDGER_FOCUS_OVERDUE: set(),
LEDGER_FOCUS_NEEDS_COMPLETION: set(),
LEDGER_FOCUS_ACTIVE: set(),
LEDGER_FOCUS_DUE_THIS_MONTH: set(),
}
if not contracts:
@@ -180,8 +180,8 @@ def collect_ledger_focus(*, session: Session, today: date | None = None) -> dict
buckets[LEDGER_FOCUS_DUE].add(row.id)
elif status == LEDGER_FOCUS_OVERDUE:
buckets[LEDGER_FOCUS_OVERDUE].add(row.id)
elif status == LEDGER_FOCUS_NEEDS_COMPLETION:
buckets[LEDGER_FOCUS_NEEDS_COMPLETION].add(row.id)
elif status == LEDGER_FOCUS_ACTIVE:
buckets[LEDGER_FOCUS_ACTIVE].add(row.id)
if has_unpaid_due_this_month(nodes, as_of):
buckets[LEDGER_FOCUS_DUE_THIS_MONTH].add(row.id)
return buckets
@@ -195,7 +195,7 @@ def ledger_focus_counts(*, session: Session, today: date | None = None) -> dict[
session: 当前请求的 SQLAlchemy 会话。
today: 可选业务日。
Returns:
due / overdue / needs_completion / due_this_month 的计数。
due / overdue / active / due_this_month 的计数。
"""
buckets = collect_ledger_focus(session=session, today=today)
return {key: len(ids) for key, ids in buckets.items()}
@@ -16,7 +16,7 @@ from typing import Any
from flask import current_app
from app.services.oa_sqlserver import OASQLServerService
from app.services.integrations.oa.sqlserver import OASQLServerService
# [STEP] 仅允许字母数字下划线作为 SQL 标识符,表名/字段来自配置,禁止拼接任意字符串。
_SAFE_IDENT = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*$")
File diff suppressed because it is too large. Load diff
+2 -2
View File
@@ -14,8 +14,8 @@ from flask import current_app
from app import db
from app.models import KbDifySyncRecord, QuickQuestion
from app.services.dify import DifyService
from app.services.integration_api import IntegrationApiService
from app.services.integrations.dify import DifyService
from app.services.integrations.integration_api import IntegrationApiService
STALE_REASON_KB_UPDATED = 'kb_document_updated'
STALE_REASON_KB_DELETED = 'kb_document_deleted'
+1 -1
View File
@@ -12,7 +12,7 @@ from typing import Any
import requests
from app.services.dify import DifyService
from app.services.integrations.dify import DifyService
VALID_FILE_CHECK_RESULTS = {"合格", "不合格", "人工判定"}
@@ -284,7 +284,7 @@ ORDER BY faj.faj02
def _fetch_snapshot_rows(cls, timeout_seconds: int) -> list[dict[str, str]]:
"""从 ERP Oracle 拉取固定资产全量快照。"""
import oracledb
from app.services.text2sql import Text2SQLService
from app.services.integrations.text2sql import Text2SQLService
username, password, dsn = cls._oracle_credentials()
Text2SQLService._init_oracle_client(oracledb)
@@ -729,7 +729,7 @@ INSERT INTO fixed_assets (
user_context: dict[str, Any] | None = None,
) -> tuple[str, list[str], dict[str, Any]]:
"""根据用户问句生成本地快照过滤条件。"""
from app.services.text2sql import Text2SQLService
from app.services.integrations.text2sql import Text2SQLService
clauses: list[str] = []
params: list[str] = []
+13 -11
View File
@@ -2,12 +2,14 @@
backend/app/services/hxops_tool_api.py
用途:解析 HXOPS 两类对外基地址——Dify Tool API(服务端)与用户浏览器访问(下载链等)。
依赖:Flask current_app / request。
依赖:Flask current_app、core.http_context。
逻辑:Dify/RPA 调 Tool API 走 resolve_HXOPS_TOOLS_API_BASE;用户可见下载链走 resolve_hxops_user_facing_base_url。
"""
from __future__ import annotations
from flask import current_app, has_request_context, request
from flask import current_app
from app.core.http_context import has_http_request, host_url
def _resolve_config(config: dict | None = None) -> dict:
@@ -25,11 +27,11 @@ def resolve_HXOPS_TOOLS_API_BASE(*, config: dict | None = None, request_host: st
核心逻辑:仅读 HXOPS_TOOLS_API_BASE(常为内网 IP),与浏览器下载链、PUBLIC_BASE_URL 分离。
Args:
参数:
config: 可选配置字典;缺省时读 current_app.config。
request_host: 可选请求 host_url;缺省且在请求上下文中时取 request.host_url。
request_host: 可选请求 host_url;缺省且在请求上下文中时取 host_url()。
Returns:
返回:
无尾斜杠的根地址,如 http://192.168.100.192:8890。
"""
cfg = _resolve_config(config)
@@ -39,8 +41,8 @@ def resolve_HXOPS_TOOLS_API_BASE(*, config: dict | None = None, request_host: st
return configured
host = request_host
if host is None and has_request_context():
host = request.host_url.rstrip("/")
if host is None and has_http_request():
host = host_url()
return host or ""
@@ -50,10 +52,10 @@ def resolve_hxops_user_facing_base_url(*, config: dict | None = None) -> str:
核心逻辑:仅读 HXOPS_PUBLIC_BASE_URL / WECOM_PUBLIC_BASE_URL,不复用 Tool API 内网地址或通知地址。
Args:
参数:
config: 可选配置字典;缺省时读 current_app.config。
Returns:
返回:
无尾斜杠的根地址,如 https://ai.example.com。
"""
cfg = _resolve_config(config)
@@ -63,7 +65,7 @@ def resolve_hxops_user_facing_base_url(*, config: dict | None = None) -> str:
if configured:
return configured
if has_request_context():
return request.host_url.rstrip("/")
if has_http_request():
return host_url()
return resolve_HXOPS_TOOLS_API_BASE(config=cfg)
@@ -4,5 +4,5 @@
依赖:同包 date_policy / status / quantity / strategy / contracts / audit;
Phase 1 起扩展 file_preparation / precheck_service 等。
逻辑:本包只承载调拨领域规则与确定性门禁,不混入 shipping_notice 订单解析;
对外部系统(RPA/ERP/企微)的访问通过本包隔离的 adapter 与 job/worker 完成。
对外部系统(RPA/外部系统/企微)的访问通过本包隔离的 adapter 与 job/worker 完成。
"""
@@ -108,7 +108,7 @@ def archive_snapshot(
"""归档一份对象并持久化索引 + 审计。
Args:
object_type: 对象类型(erp_inventory_snapshot / exception_excel / receipt_file)。
object_type: 对象类型(external_inventory_snapshot / exception_excel / receipt_file)。
object_id: 业务对象编号(precheck_no / run_no)。
data: 待归档字节。
original_filename: 原始文件名。
@@ -3,7 +3,7 @@
用途:组合"每日恢复 → 自动预检 → 自动执行 → 企微汇总通知",
供 in-transit-transfer platform job 调用。
依赖:recovery_service、precheck_service、execution_service、notification。
逻辑:各阶段独立 try/except,任一阶段失败不阻断后续;通知失败不改 ERP 结果。
逻辑:各阶段独立 try/except,任一阶段失败不阻断后续;通知失败不改 外部系统 结果。
"""
from __future__ import annotations
@@ -45,7 +45,7 @@ def cancel_run(*, run_no: str, reason: str, actor_id: int | None = None, request
cancelled = 0
for item in db.session.query(TransferInvoiceItem).filter_by(run_id=run.id).all():
if item.status == status_machine.TransferStatus.READY_TO_EXECUTE.value and not item.erp_document_no:
if item.status == status_machine.TransferStatus.READY_TO_EXECUTE.value and not item.external_document_no:
item.status = status_machine.TransferStatus.CANCELLED.value
item.result_code = "cancelled"
item.result_message = reason_value
@@ -0,0 +1,103 @@
"""services/in_transit_transfer/capabilities.py
用途:在途调拨域的能力声明——本域经集成连接器暴露的能力契约(入参/出参 Schema、
幂等语义、读写标志),代码注册、禁止管理端动态定义。
依赖:integration_connector.capability(机制层:CapabilitySpec/注册表)。
逻辑:本模块属于领域包而非连接器框架——框架只提供注册/校验机制,域契约随域代码
版本化;应用组合根(app/__init__.py)在每次 create_app 时调用
register_transfer_capabilities()(幂等),保证管理端「能力清单」冷启动即可见,
测试 reset 注册表后也能重建。
"""
from __future__ import annotations
from app.services.integration_connector.capability import (
CapabilitySpec,
list_capabilities,
register_capability,
)
# 在途调拨能力输入/输出 Schema(JSON Schema 最小子集,供入参/出参校验)。
# 查询契约:按组织批量查库存,目标为 (料号, 拨出库位, 拨出批号) 元组列表;
# external_org 取自仓库映射(external_organization_code),由绑定参数映射翻译为接口的 organization。
_QUERY_INPUT_SCHEMA: dict = {
"type": "object",
"required": ["external_org", "targets"],
"properties": {
"external_org": {"type": "string"},
"targets": {"type": "array", "items": {
"type": "object",
"required": ["material_no", "from_warehouse", "lot_no"],
"properties": {
"material_no": {"type": "string"},
"from_warehouse": {"type": "string"},
"lot_no": {"type": "string"},
},
}},
},
}
_QUERY_OUTPUT_SCHEMA: dict = {
"type": "object",
"required": ["rows"],
"properties": {
"rows": {"type": "array", "items": {
"type": "object",
"required": ["material_no", "from_warehouse", "lot_no", "quantity"],
"properties": {
"material_no": {"type": "string"},
"from_warehouse": {"type": "string"},
"lot_no": {"type": "string"},
"quantity": {"type": "number"},
},
}},
},
}
_WRITE_OUTPUT_SCHEMA: dict = {
"type": "object",
"required": ["status"],
"properties": {
"status": {
"type": "string",
"enum": ["success", "business_failed", "technical_failed", "timeout", "result_unknown"],
},
"document_no": {"type": ["string", "null"]},
"verified_posted": {"type": ["boolean", "null"]},
},
}
def register_transfer_capabilities() -> None:
"""注册在途调拨域的三个能力(幂等:已注册的同名跳过)。
幂等是硬要求:组合根每次 create_app 都会调用;测试 reset 注册表后(模块缓存导致
import 副作用不再执行)也依赖本函数重建,故不能依赖「只注册一次」。
"""
registered = {spec.name for spec in list_capabilities()}
for spec in (
CapabilitySpec(
name="in_transit_transfer.query_inventory",
input_schema=_QUERY_INPUT_SCHEMA,
output_schema=_QUERY_OUTPUT_SCHEMA,
idempotency="none",
write=False,
),
CapabilitySpec(
name="in_transit_transfer.create_transfer",
input_schema=_QUERY_INPUT_SCHEMA,
output_schema=_WRITE_OUTPUT_SCHEMA,
idempotency="invoice",
write=True,
),
CapabilitySpec(
name="in_transit_transfer.verify_duplicate",
input_schema=_QUERY_INPUT_SCHEMA,
output_schema=_WRITE_OUTPUT_SCHEMA,
idempotency="invoice",
write=False,
),
):
if spec.name not in registered:
register_capability(spec)
register_transfer_capabilities()
@@ -0,0 +1,283 @@
"""services/in_transit_transfer/capability_client.py
用途:在途调拨域的外部访问统一客户端——查询经 CapabilityGateway 按能力批量调用;
写路径在外部契约冻结前 fail-closed(Phase 2 接线点);域异常与写结果分类集中于此。
依赖:integration_connector.gateway / errors、app.core.errors。
逻辑:查询按 (料号, 拨出库位, 拨出批号) 元组批量进行,组织键 external_org 取自
仓库映射(external_organization_code);查询超时→ExternalQueryTimeoutError,
网关失败→AppError;写 transport 未注入时 create_transfer/verify_duplicate
抛 ExternalNotFrozenError,注入后超时分类为 technical_failed / result_unknown。
"""
from __future__ import annotations
from dataclasses import dataclass
from decimal import Decimal
from typing import Any
from app.core.errors import AppError
QUERY_INVENTORY_CAPABILITY = "in_transit_transfer.query_inventory"
EXTERNAL_NOT_FROZEN_CODE = "TRANSFER.EXTERNAL_NOT_FROZEN"
EXTERNAL_QUERY_TIMEOUT_CODE = "TRANSFER.EXTERNAL_QUERY_TIMEOUT"
EXTERNAL_RESULT_UNKNOWN_CODE = "TRANSFER_RESULT_UNKNOWN"
class ExternalNotFrozenError(AppError):
"""外部系统契约(WSDL/endpoint)尚未冻结,禁止调用(fail-closed)。"""
def __init__(self, message: str = "external system contract not frozen"):
super().__init__(code=EXTERNAL_NOT_FROZEN_CODE, message=message, http_status=503, retryable=False)
class ExternalQueryTimeoutError(AppError):
"""外部系统查询超时(只读路径,允许上层重试)。"""
def __init__(self, message: str = "external query timeout"):
super().__init__(code=EXTERNAL_QUERY_TIMEOUT_CODE, message=message, http_status=503, retryable=True)
class ExternalResultUnknownError(AppError):
"""外部系统写结果无法确认(Phase 2 使用);禁止自动重试。"""
def __init__(self, message: str = "external result unknown", *, operation_id: str | None = None):
details = {"operation_id": operation_id} if operation_id else {}
super().__init__(code=EXTERNAL_RESULT_UNKNOWN_CODE, message=message, http_status=503, retryable=False, details=details)
class ExternalWriteTimeoutError(TimeoutError):
"""外部系统写超时;committed 表达是否可证明已落单。"""
def __init__(
self,
message: str,
*,
committed: bool | None,
document_no: str | None = None,
operation_id: str | None = None,
) -> None:
super().__init__(message)
self.committed = committed
self.document_no = document_no
self.operation_id = operation_id
@dataclass(frozen=True)
class TransferWriteResult:
"""外部系统原子建单/审核/过账结果分类。"""
status: str # success | duplicate_success | duplicate_unverified | business_failed | technical_failed | result_unknown
document_no: str | None = None
verified_posted: bool | None = None
error_code: str | None = None
error_message: str | None = None
@dataclass(frozen=True)
class StockTarget:
"""库存查询目标元组:料号 + 拨出库位 + 拨出批号。"""
material_no: str
from_warehouse: str
lot_no: str
@dataclass(frozen=True)
class StockRow:
"""外部系统返回的一行账面库存。"""
material_no: str
from_warehouse: str
lot_no: str
quantity: Decimal
@dataclass(frozen=True)
class StockQueryResult:
"""一次批量库存查询的结果;按元组精确匹配取数。"""
rows: tuple[StockRow, ...]
def lookup(self, *, material_no: str, from_warehouse: str, lot_no: str) -> Decimal | None:
"""按三元组取库存数量;同键多行累加;未命中返回 None。"""
total: Decimal | None = None
for row in self.rows:
if (row.material_no, row.from_warehouse, row.lot_no) == (material_no, from_warehouse, lot_no):
total = row.quantity if total is None else total + row.quantity
return total
class CapabilityClient:
"""域内外部访问统一客户端:查询经 CapabilityGateway,写路径 fail-closed。
Args:
gateway: 可注入替身(测试);缺省 get_capability_gateway()。
write_transport: 写路径传输替身(Phase 2 前恒 None → 写调用抛
ExternalNotFrozenError;测试注入后走经典写分类:可证明未落单→
technical_failed,否则 result_unknown)。
"""
def __init__(self, gateway: Any | None = None, write_transport: Any | None = None) -> None:
self._gateway_override = gateway
self._write_transport = write_transport
def _gateway(self) -> Any:
if self._gateway_override is not None:
return self._gateway_override
from app.services.integration_connector.gateway import get_capability_gateway
return get_capability_gateway()
def query_stock(
self,
*,
operation_id: str,
external_org: str,
targets: list[StockTarget],
) -> StockQueryResult:
"""按组织批量查询库存(一次调用覆盖全部目标元组)。
Raises:
ExternalQueryTimeoutError: 查询超时(可重试)。
AppError: 网关失败(绑定缺失/调用失败,fail-closed)。
"""
if not targets:
return StockQueryResult(rows=())
result = self._gateway().call(
capability=QUERY_INVENTORY_CAPABILITY,
context={},
params={
"external_org": external_org,
"targets": [
{
"material_no": target.material_no,
"from_warehouse": target.from_warehouse,
"lot_no": target.lot_no,
}
for target in targets
],
},
operation_id=operation_id,
)
if result.status == "timeout":
raise ExternalQueryTimeoutError()
if result.status != "success":
raise AppError(
code=result.error_code or "INTEGRATION.CALL_FAILED",
message=result.error_message or "query_inventory failed",
http_status=503,
retryable=False,
)
rows = [
StockRow(
material_no=str(row.get("material_no") or ""),
from_warehouse=str(row.get("from_warehouse") or ""),
lot_no=str(row.get("lot_no") or ""),
quantity=Decimal(str(row.get("quantity") or "0")),
)
for row in ((result.data or {}).get("rows") or [])
]
return StockQueryResult(rows=tuple(rows))
def create_transfer(
self,
*,
operation_id: str,
run_no: str,
attempt_no: int,
invoice_no: str,
external_org: str,
from_warehouse: str,
to_warehouse: str,
quantity: Decimal,
) -> TransferWriteResult:
"""外部系统原子建单/审核/过账并按结果分类。
Returns:
TransferWriteResult:success / duplicate_success / duplicate_unverified /
business_failed / technical_failed / result_unknown。
Raises:
ExternalNotFrozenError: 写契约未冻结(write_transport 未注入)。
"""
if self._write_transport is None:
raise ExternalNotFrozenError("external create_transfer contract not frozen (endpoint missing)")
try:
response = self._write_transport.create_transfer(
operation_id=operation_id, run_no=run_no, attempt_no=attempt_no,
invoice_no=invoice_no, external_org=external_org,
from_warehouse=from_warehouse, to_warehouse=to_warehouse, quantity=quantity,
)
except ExternalWriteTimeoutError as exc:
if exc.committed is False:
# 可证明未落单 → 明确技术失败(不产生单据)。
return TransferWriteResult(status="technical_failed", error_code="EXTERNAL_TIMEOUT_BEFORE_COMMIT")
return TransferWriteResult(
status="result_unknown", error_code="EXTERNAL_TIMEOUT_AFTER_COMMIT",
document_no=exc.document_no,
)
except TimeoutError:
# 无法区分是否落单 → result_unknown,禁止自动重试。
return TransferWriteResult(status="result_unknown", error_code="EXTERNAL_TIMEOUT_UNKNOWN")
return _classify_write_response(response)
def verify_duplicate(
self,
*,
operation_id: str,
run_no: str,
attempt_no: int,
invoice_no: str,
external_org: str,
from_warehouse: str,
to_warehouse: str,
quantity: Decimal,
) -> TransferWriteResult:
"""核实重复 Invoice 原单是否已审核过账(幂等确认)。
Returns:
duplicate_success(已过账,含原单号)或 duplicate_unverified。
"""
if self._write_transport is None:
raise ExternalNotFrozenError("external verify_duplicate contract not frozen (endpoint missing)")
try:
response = self._write_transport.verify_duplicate(
operation_id=operation_id, run_no=run_no, attempt_no=attempt_no,
invoice_no=invoice_no, external_org=external_org,
from_warehouse=from_warehouse, to_warehouse=to_warehouse, quantity=quantity,
)
except (TimeoutError, ExternalWriteTimeoutError):
return TransferWriteResult(status="result_unknown", error_code="EXTERNAL_TIMEOUT_UNKNOWN")
response = response if isinstance(response, dict) else {}
status = str(response.get("status") or "")
document_no = response.get("document_no")
posted = bool(response.get("verified_posted"))
if status == "duplicate_success" and posted:
return TransferWriteResult(status="duplicate_success", document_no=document_no, verified_posted=True)
return TransferWriteResult(
status="duplicate_unverified", document_no=document_no, verified_posted=posted,
error_code="TRANSFER_DUPLICATE_NOT_VERIFIED",
)
def _classify_write_response(response: dict[str, Any]) -> TransferWriteResult:
"""按外部系统写响应原文分类业务结果。"""
status = str(response.get("status") or "")
document_no = response.get("document_no")
if status == "success":
return TransferWriteResult(status="success", document_no=document_no)
if status == "duplicate_success":
posted = bool(response.get("verified_posted"))
if posted:
return TransferWriteResult(status="duplicate_success", document_no=document_no, verified_posted=True)
return TransferWriteResult(
status="duplicate_unverified", document_no=document_no, verified_posted=False,
error_code="TRANSFER_DUPLICATE_NOT_VERIFIED",
)
if status == "business_failed":
return TransferWriteResult(
status="business_failed",
error_code=str(response.get("code") or "EXTERNAL_BUSINESS_REJECT"),
error_message=str(response.get("message") or ""),
)
return TransferWriteResult(status="technical_failed", error_code="EXTERNAL_UNKNOWN_RESPONSE")
@@ -42,16 +42,18 @@ class TransferPrecheckAction:
"""执行只读预检并输出 transfer-precheck 卡片。
【AI 触发时机】:用户表达"查询今天可调拨 / 预检"等意图后由候选 Action 触发;
只读,不写 ERP。
只读,不写 外部系统。
"""
payload = ctx.input.payload if isinstance(ctx.input.payload, dict) else {}
source_codes = [str(item).strip() for item in (payload.get("source_codes") or [])]
business_date = str(payload.get("business_date") or business_date_now())
transfer_type = str(payload.get("transfer_type")) if payload.get("transfer_type") else None
deps = transfer_deps.get_transfer_dependencies()
summary = create_precheck(
source_codes=source_codes,
business_date=business_date,
deps=deps,
transfer_type=transfer_type,
)
detail = restore_precheck(summary.precheck_id)
yield _message(
@@ -71,7 +73,7 @@ class TransferExecuteAction:
"""执行勾选范围并输出 transfer-result 卡片。
【AI 触发时机】:用户在预检卡点击"直接生成调拨单"后触发;
后台确定性服务完成写前复查与 ERP 原子写入。
后台确定性服务完成写前复查与 外部系统 原子写入。
"""
payload = ctx.input.payload if isinstance(ctx.input.payload, dict) else {}
precheck_id = str(payload.get("precheck_id") or "").strip()
@@ -1,7 +1,7 @@
"""在途调拨并发参数与单写者约束。
用途:冻结来源并发(2)、ERP 查询并发(2)与 ERP 写并发(1)默认值;
ERP 写并发恒为 1,同预检只允许一个执行 Run(由 orchestrator 门禁兜底)。
用途:冻结来源并发(2)、外部系统 查询并发(2)与 外部系统 写并发(1)默认值;
外部系统 写并发恒为 1,同预检只允许一个执行 Run(由 orchestrator 门禁兜底)。
依赖:无(纯常量)。
逻辑:写并发 1 与"同 Invoice 执行数=1"为一期硬约束,禁止运行时提升。
"""
@@ -10,8 +10,8 @@ from __future__ import annotations
# 一期冻结并发参数(与规格 §10 一致)。
SOURCE_CONCURRENCY = 3
ERP_QUERY_CONCURRENCY = 3
ERP_WRITE_CONCURRENCY = 3
外部系统_QUERY_CONCURRENCY = 3
外部系统_WRITE_CONCURRENCY = 3
def assert_single_writer(run_count: int) -> None:
@@ -22,4 +22,4 @@ def assert_single_writer(run_count: int) -> None:
Raises:
AssertionError: run_count > 1(一期硬约束)。
"""
assert run_count <= 1, "ERP write concurrency must stay 1 for the same precheck"
assert run_count <= 1, "External write concurrency must stay 1 for the same precheck"
@@ -1,10 +1,10 @@
"""在途调拨 DTO 与稳定错误码契约。
用途:冻结前后端契约(预检摘要、明细项、ERP 单据聚合结果)与一期错误码,
用途:冻结前后端契约(预检摘要、明细项、外部系统 单据聚合结果)与一期错误码,
保证前端只依赖稳定 DTO、不感知 SOAP/WSDL/文件路径。
依赖:标准库 dataclasses / decimal。
逻辑:DTO 全部 frozen;aggregate_erp_documents 按 ERP 单号聚合最终结果页
(决策 20:ERP 单号、拨出仓、拨入仓、物料数、调拨总数量、过账状态)。
逻辑:DTO 全部 frozen;aggregate_external_documents 按 外部系统 单号聚合最终结果页
(决策 20:外部系统 单号、拨出仓、拨入仓、物料数、调拨总数量、过账状态)。
"""
from __future__ import annotations
@@ -20,7 +20,7 @@ TRANSFER_FILE_NOT_READY = "TRANSFER_FILE_NOT_READY"
TRANSFER_FILE_SCHEMA_INVALID = "TRANSFER_FILE_SCHEMA_INVALID"
TRANSFER_INVOICE_CONFLICT = "TRANSFER_INVOICE_CONFLICT"
TRANSFER_QUANTITY_MISMATCH = "TRANSFER_QUANTITY_MISMATCH"
TRANSFER_ERP_INVENTORY_NOT_FOUND = "TRANSFER_ERP_INVENTORY_NOT_FOUND"
TRANSFER_EXTERNAL_INVENTORY_NOT_FOUND = "TRANSFER_EXTERNAL_INVENTORY_NOT_FOUND"
TRANSFER_PRECHECK_EXPIRED = "TRANSFER_PRECHECK_EXPIRED"
TRANSFER_CONFIRMATION_REQUIRED = "TRANSFER_CONFIRMATION_REQUIRED"
TRANSFER_DUPLICATE_NOT_VERIFIED = "TRANSFER_DUPLICATE_NOT_VERIFIED"
@@ -37,7 +37,7 @@ KNOWN_TRANSFER_ERROR_CODES: frozenset[str] = frozenset({
TRANSFER_FILE_SCHEMA_INVALID,
TRANSFER_INVOICE_CONFLICT,
TRANSFER_QUANTITY_MISMATCH,
TRANSFER_ERP_INVENTORY_NOT_FOUND,
TRANSFER_EXTERNAL_INVENTORY_NOT_FOUND,
TRANSFER_PRECHECK_EXPIRED,
TRANSFER_CONFIRMATION_REQUIRED,
TRANSFER_DUPLICATE_NOT_VERIFIED,
@@ -84,7 +84,7 @@ class RawLineRefDTO:
@dataclass(frozen=True)
class PrecheckInvoiceItemDTO:
"""预检明细项(决策 6:收料来源/料号/品名/规格/Invoice/拨出仓/拨出数量/拨入仓/拨入数量/预检结果)。"""
"""预检明细项(决策 6 十列 + 2026-09-21 增批号:拨出批号/拨入批号由 lot_no 转换派生,lot_no 存原值)。"""
source_code: str
material_no: str
@@ -98,13 +98,16 @@ class PrecheckInvoiceItemDTO:
result: str
receipt_date: str | None = None
reason: str = ""
erp_document_no: str | None = None
external_document_no: str | None = None
raw_lines: tuple[RawLineRefDTO, ...] = field(default_factory=tuple)
lot_no: str = ""
# 收料文件「仓库」列原值:inventory_match 源映射行匹配键(明细审计与执行期重解析输入)。
receipt_warehouse_code: str = ""
@dataclass(frozen=True)
class PrecheckSummaryDTO:
"""预检摘要(含预计调拨数量、预计 ERP 写入数与预检 Hash)。"""
"""预检摘要(含预计调拨数量、预计 外部系统 写入数与预检 Hash)。"""
precheck_id: str
status: str
@@ -113,14 +116,14 @@ class PrecheckSummaryDTO:
expires_at: str
counts: PrecheckCountsDTO
estimated_transfer_quantity: str
estimated_erp_write_count: int
estimated_external_write_count: int
precheck_hash: str
# ---- 结果页 DTO(决策 20)--------------------------------------------------
@dataclass(frozen=True)
class ErpDocumentLineDTO:
"""ERP 单据内物料明细。"""
class ExternalDocumentLineDTO:
"""外部系统 单据内物料明细。"""
material_no: str
material_name: str
@@ -130,8 +133,8 @@ class ErpDocumentLineDTO:
@dataclass(frozen=True)
class ErpDocumentDTO:
"""按 ERP 单号聚合的结果项。"""
class ExternalDocumentDTO:
"""按 外部系统 单号聚合的结果项。"""
document_no: str
from_warehouse: str
@@ -139,12 +142,12 @@ class ErpDocumentDTO:
material_count: int
total_quantity: Decimal
posting_status: str
lines: tuple[ErpDocumentLineDTO, ...] = field(default_factory=tuple)
lines: tuple[ExternalDocumentLineDTO, ...] = field(default_factory=tuple)
@dataclass(frozen=True)
class TransferExceptionDTO:
"""未生成 ERP 单据的异常项(单独展示)。"""
"""未生成 外部系统 单据的异常项(单独展示)。"""
source_code: str
invoice_no: str
@@ -155,31 +158,31 @@ class TransferExceptionDTO:
@dataclass(frozen=True)
class RunResultDTO:
"""Run 最终结果投影:ERP 单据聚合 + 未生成单据异常。"""
"""Run 最终结果投影:外部系统 单据聚合 + 未生成单据异常。"""
run_no: str
status: str
erp_documents: tuple[ErpDocumentDTO, ...] = field(default_factory=tuple)
external_documents: tuple[ExternalDocumentDTO, ...] = field(default_factory=tuple)
exceptions: tuple[TransferExceptionDTO, ...] = field(default_factory=tuple)
def aggregate_erp_documents(items: Iterable[PrecheckInvoiceItemDTO]) -> tuple[ErpDocumentDTO, ...]:
"""按 ERP 单号聚合成功项,产出结果页文档视图。
def aggregate_external_documents(items: Iterable[PrecheckInvoiceItemDTO]) -> tuple[ExternalDocumentDTO, ...]:
"""按 外部系统 单号聚合成功项,产出结果页文档视图。
Args:
items: 预检明细项(含 erp_document_no 与 result)。
items: 预检明细项(含 external_document_no 与 result)。
Returns:
按单号聚合的 ErpDocumentDTO 元组(行按 Invoice 排序)。
按单号聚合的 ExternalDocumentDTO 元组(行按 Invoice 排序)。
"""
grouped: dict[str, list[PrecheckInvoiceItemDTO]] = {}
for item in items:
if item.erp_document_no and item.result in {"success", "duplicate_success"}:
grouped.setdefault(item.erp_document_no, []).append(item)
documents: list[ErpDocumentDTO] = []
if item.external_document_no and item.result in {"success", "duplicate_success"}:
grouped.setdefault(item.external_document_no, []).append(item)
documents: list[ExternalDocumentDTO] = []
for document_no in sorted(grouped):
rows = sorted(grouped[document_no], key=lambda row: row.invoice_no)
lines = tuple(
ErpDocumentLineDTO(
ExternalDocumentLineDTO(
material_no=row.material_no,
material_name=row.material_name,
specification=row.specification,
@@ -188,7 +191,7 @@ def aggregate_erp_documents(items: Iterable[PrecheckInvoiceItemDTO]) -> tuple[Er
)
for row in rows
)
documents.append(ErpDocumentDTO(
documents.append(ExternalDocumentDTO(
document_no=document_no,
from_warehouse=rows[0].from_warehouse,
to_warehouse=rows[0].to_warehouse,
@@ -20,19 +20,30 @@ MATURITY_NOT_MATURED = "not_matured"
MATURITY_FUTURE = "future"
def parse_date(value: date | str) -> date:
"""将 date 或 'YYYY-MM-DD' 字符串归一化为 date。
def parse_date(value: date | datetime | str) -> date:
"""将 date/datetime 或日期字符串归一化为 date。
Args:
value: date 对象或 ISO 日期字符串。
value: date/datetime 对象,或日期字符串(允许携带时间部分,如
Excel 日期单元格经字符串化的 '2026-08-26 17:38:38')。
Returns:
归一化后的 date。
Raises:
ValueError: 字符串不是合法 ISO 日期。
ValueError: 字符串不是可识别的日期/日期时间。
"""
if isinstance(value, datetime):
return value.date()
if isinstance(value, date):
return value
return date.fromisoformat(str(value).strip())
text = str(value).strip()
try:
return date.fromisoformat(text)
except ValueError:
pass
try:
return datetime.fromisoformat(text).date()
except ValueError as exc:
raise ValueError(f"Invalid date value: {value!r}") from exc
def business_date_now(moment: datetime | None = None) -> date:
@@ -51,6 +62,29 @@ def business_date_now(moment: datetime | None = None) -> date:
return moment.astimezone(SHANGHAI_TZ).date()
def business_date_utc_window(now: datetime | None = None) -> tuple[datetime, datetime]:
"""返回当前业务日期(Asia/Shanghai)在 UTC 存储时间轴上的 [起, 止) 窗口。
用途:判定"文件是否当天抓取"等新鲜度场景。数据库统一存 naive UTC 时间,
直接取 .date() 与业务日期比较会漂移 8 小时,必须先换算窗口再比较。
Args:
now: 可选时刻;naive 按 UTC 兼容处理(与 business_date_now 口径一致)。
Returns:
(窗口起, 窗口止);两者均为 naive UTC datetime,止为开区间(时长 24h)。
"""
if now is None:
now = datetime.now(SHANGHAI_TZ)
if now.tzinfo is None:
now = now.replace(tzinfo=ZoneInfo("UTC"))
sh_now = now.astimezone(SHANGHAI_TZ)
start_utc = (
datetime(sh_now.year, sh_now.month, sh_now.day, tzinfo=SHANGHAI_TZ)
.astimezone(ZoneInfo("UTC"))
.replace(tzinfo=None)
)
return start_utc, start_utc + timedelta(hours=24)
def maturity_status(receipt_date: date | str, business_date: date | str) -> str:
"""按 D+1 规则判定收料日期成熟度。
@@ -1,19 +1,20 @@
"""在途调拨依赖装配(Dependencies)。
用途:为 API / Job Handler 组装默认 TransferDeps;测试通过 _override 注入 Fake。
依赖:file_preparation / erp_adapter / precheck_service / models。
逻辑:默认实现 fail-closed —— 收料文件行读取(Q3 样例未冻结)与路由归属
(Q1 规则未冻结)在真实契约冻结前拒绝执行;ERP SOAP 在 WSDL 冻结前拒绝。
依赖:movement_file_repository / capability_client / precheck_service / models。
逻辑:默认实现直接接线真实链路 —— 收料文件行读取走 movement_file_repository
(复用货代收料归档 + movement 解析规则,无文件/无规则时返回 None 由
预检走等待 RPA);路由归属规则(Q1)冻结前由 DefaultRouteResolver
fail-closed 拒绝;外部访问统一走 CapabilityClient(绑定缺失时 fail-closed)。
"""
from __future__ import annotations
from typing import Any
from app.core.errors import AppError
from app.models import ShippingInventoryExternalMapping, ShippingInventorySource
from app.services.in_transit_transfer.file_preparation import ReadyReceiptFile, ReceiptFileRepository
from app.services.in_transit_transfer.gateway_adapter import CapabilityErpAdapter
from app.services.in_transit_transfer.capability_client import CapabilityClient
from app.services.in_transit_transfer.movement_file_repository import ShippingReceiptFileRepository
from app.services.in_transit_transfer.precheck_service import (
RouteMapping,
RouteNotResolvedError,
@@ -21,59 +22,68 @@ from app.services.in_transit_transfer.precheck_service import (
TransferDeps,
)
RECEIPT_ROWS_NOT_FROZEN_CODE = "TRANSFER.RECEIPT_ROWS_NOT_FROZEN"
class ReceiptRowsNotFrozenError(AppError):
"""收料文件行读取契约未冻结(Q3:正式样例/Sheet/表头缺失)。"""
def __init__(self, message: str = "receipt file row contract not frozen"):
super().__init__(code=RECEIPT_ROWS_NOT_FROZEN_CODE, message=message, http_status=503, retryable=False)
class ShippingReceiptFileRepository:
"""默认收料 ready 文件仓库(只读复用 shipping 收料归档)。
行读取依赖收料文件正式样例契约(Q3);未冻结前 fail-closed。
"""
def latest_ready_file(self, *, source_code: str, business_date: str) -> ReadyReceiptFile | None:
"""返回最新 ready 文件;行内容契约未冻结时抛 ReceiptRowsNotFrozenError。"""
raise ReceiptRowsNotFrozenError(
"receipt file rows unfrozen: sample/sheet contract required (Q3)"
)
class DefaultRouteResolver:
"""默认路由解析:来源固定仓 + 外部系统仓库映射。
"""默认路由解析:仓库映射的在途仓编码 + 外部系统仓库。
路由归属规则(来源实例 → ERP 组织/在途仓/映射仓)冻结前 fail-closed。
拨出库位 = 映射行的在途仓编码(in_transit_warehouse_code);拨入仓库 = 映射的
目标仓库代码;组织 = 映射的外部组织编码。映射行按库存源识别方式选择:
inventory_match 源优先「收料文件仓库列 == 货代仓库」精确匹配,匹配不到回退
货代仓库为空的默认映射行(空库位兜底);fixed 源仅一条启用映射直接取用。
不借用站点固定仓库(那是货代发货/库存导出链路的字段)。
"""
def resolve(self, *, source_code: str, invoice_no: str) -> RouteMapping:
"""按来源配置与外部映射解析路由;无法归属时抛 RouteNotResolvedError。"""
def resolve(self, *, source_code: str, invoice_no: str, warehouse_code: str = "") -> RouteMapping:
"""按来源识别方式选择映射行并解析路由;无法归属时抛 RouteNotResolvedError。
Args:
source_code: 来源实例编码(须启用)。
invoice_no: Invoice 单号(当前不参与匹配,保留协议兼容)。
warehouse_code: 收料文件「仓库」列原值(inventory_match 源的映射匹配键)。
Returns:
RouteMapping(external_org / from_warehouse=在途仓编码 / to_warehouse)。
Raises:
RouteNotResolvedError: 来源不存在、无可用映射行或在途仓编码未维护。
"""
source = ShippingInventorySource.query.filter_by(source_code=source_code, enabled=True).first()
if source is None:
raise RouteNotResolvedError(source_code=source_code)
mapping = ShippingInventoryExternalMapping.query.filter_by(
mappings = ShippingInventoryExternalMapping.query.filter_by(
inventory_source_id=source.id, enabled=True,
).first()
if mapping is None or not mapping.external_organization_code:
).all()
selected = None
if getattr(source, 'warehouse_resolution_mode', '') == 'inventory_match':
# [匹配] 收料仓库大写归一后与货代仓库精确比对;空库位走默认映射行兜底。
# 部分唯一索引保证同源「精确/默认」各最多一条启用映射,选择结果确定。
key = str(warehouse_code or '').strip().upper()
if key:
selected = next(
(m for m in mappings if str(m.freight_warehouse_id or '').strip().upper() == key), None,
)
if selected is None:
selected = next((m for m in mappings if not str(m.freight_warehouse_id or '').strip()), None)
else:
selected = mappings[0] if mappings else None
if selected is None or not selected.external_organization_code:
raise RouteNotResolvedError(source_code=source_code)
from_warehouse = str(selected.in_transit_warehouse_code or '').strip()
if not from_warehouse:
# 拨出库位无来源(映射未维护在途仓编码)——fail-closed,不猜测。
raise RouteNotResolvedError(source_code=source_code)
return RouteMapping(
erp_org=mapping.external_organization_code,
from_warehouse=source.fixed_warehouse_id or "",
to_warehouse=mapping.external_warehouse_code,
external_org=selected.external_organization_code,
from_warehouse=from_warehouse,
to_warehouse=selected.external_warehouse_code,
)
def _build_erp_adapter() -> CapabilityErpAdapter:
"""装配调拨 ERP 访问:默认走 CapabilityGateway(query_inventory 首消费者)。
def _build_capability_client() -> CapabilityClient:
"""装配调拨外部访问客户端:查询走 CapabilityGateway(绑定缺失时 fail-closed)。
P1 连接器框架:外部系统差异由配置(ClientInstance/InterfaceDefinition/Binding/映射)
承担;缺绑定/契约未冻结时 fail-closed。create_transfer/verify_duplicate 待执行阶段接线。
承担;create_transfer/verify_duplicate 在 WSDL 冻结前 fail-closed(Phase 2 接线)。
"""
return CapabilityErpAdapter()
return CapabilityClient()
_override: TransferDeps | None = None
@@ -86,33 +96,45 @@ def set_transfer_dependencies(deps: TransferDeps | None) -> None:
def get_transfer_dependencies() -> TransferDeps:
"""返回装配好的 TransferDeps(测试覆盖优先,默认 fail-closed)。"""
"""返回装配好的 TransferDeps(测试覆盖优先;默认接线真实文件仓库/触发服务/外部系统 网关)。"""
if _override is not None:
return _override
return TransferDeps(
file_repository=ShippingReceiptFileRepository(),
rpa_trigger=_DefaultRpaTrigger(),
route_resolver=DefaultRouteResolver(),
erp=_build_erp_adapter(),
capabilities=_build_capability_client(),
)
class _DefaultRpaTrigger:
"""默认收料 RPA 触发器:复用既有收料 RPA trigger 目录。
"""默认收料 RPA 触发器:委托真实触发服务(trigger_receipt_rpa)。
依赖来源配置(ShippingInventorySource + 收料报表配置);来源未启用或
trigger 目录未配置时返回失败(fail-closed),不伪造等待。
真实链路 = 落单元行 + 原子写 trigger 文件;来源/收料配置缺失或 trigger
目录未配置时由触发服务返回 fail-closed(ok=False),本类只透传结果。
另在本类前置守卫:收料配置存在但未绑定已发布 movement 解析规则时
直接返回 RPA_RECEIPT_MOVEMENT_PROFILE_MISSING,不触发徒劳抓取。
"""
def trigger(self, *, source_code: str, business_date: str, reason: str) -> dict[str, Any]:
from flask import current_app
from app.services.in_transit_transfer.receipt_trigger_service import trigger_receipt_rpa
# [守卫] 收料配置存在但未绑定已发布 movement 解析规则时,触发 RPA 必然徒劳:
# 抓回的文件无法被 latest_ready_file 复用,预检会反复重抓。fail-closed 返回明确错误码。
from app.models import ShippingInventorySource, ShippingReceiptReportConfig
trigger_dir = str(
current_app.config.get("SHIPPING_NOTICE_RPA_SHARED_RECEIPT_TRIGGER_DIR") or ""
).strip()
if not trigger_dir:
return {"ok": False, "error_code": "RPA_TRIGGER_DIR_NOT_CONFIGURED"}
source = ShippingInventorySource.query.filter_by(source_code=source_code, enabled=True).first()
if source is None:
return {"ok": False, "error_code": "SOURCE_NOT_ENABLED"}
return {"ok": True, "callback_id": f"receipt:{source_code}:{business_date}"}
if source is not None:
config = ShippingReceiptReportConfig.query.filter_by(inventory_source_id=source.id).first()
if config is not None:
profile = config.parsing_profile
if profile is None or profile.status != 'published' or profile.purpose != 'movement':
return {'ok': False, 'error_code': 'RPA_RECEIPT_MOVEMENT_PROFILE_MISSING'}
outcome = trigger_receipt_rpa(source_code=source_code, business_date=business_date, reason=reason)
return {
"ok": bool(outcome.get("ok")),
"callback_id": outcome.get("callback_id"),
"error_code": outcome.get("error_code"),
"error_message": outcome.get("error_message"),
}
@@ -1,295 +0,0 @@
"""在途调拨 ERP 访问统一边界(Adapter)。
用途:隔离全部 ERP 请求;业务服务只允许经本模块访问 ERP。
Phase 1 启用只读 query_inventory;Phase 2 增加 create_transfer /
verify_duplicate / 结果分类。
依赖:typing.Protocol 传输层(测试注入 FakeERP;生产为 SOAP 传输)。
逻辑:请求统一携带 operation_id / run_no / attempt_no / invoice_no /
erp_org / 拨出仓 / 拨入仓 / 数量;查询超时分类为可重试;
SOAP 传输在 WSDL/endpoint 冻结前 fail-closed(ErpNotFrozenError)。
"""
from __future__ import annotations
from dataclasses import dataclass
from decimal import Decimal
from typing import Any, Protocol
from app.core.errors import AppError
ERP_NOT_FROZEN_CODE = "TRANSFER.ERP_NOT_FROZEN"
ERP_QUERY_TIMEOUT_CODE = "TRANSFER.ERP_QUERY_TIMEOUT"
ERP_RESULT_UNKNOWN_CODE = "TRANSFER_RESULT_UNKNOWN"
@dataclass(frozen=True)
class InventoryQuery:
"""ERP 账面库存查询结果。"""
found: bool
quantity: Decimal | None = None
document_no: str | None = None
class ErpNotFrozenError(AppError):
"""ERP WSDL/endpoint 尚未冻结,禁止调用(fail-closed)。"""
def __init__(self, message: str = "ERP contract not frozen"):
super().__init__(code=ERP_NOT_FROZEN_CODE, message=message, http_status=503, retryable=False)
class ErpQueryTimeoutError(AppError):
"""ERP 查询超时(只读路径,允许上层重试)。"""
def __init__(self, message: str = "ERP query timeout"):
super().__init__(code=ERP_QUERY_TIMEOUT_CODE, message=message, http_status=503, retryable=True)
class ErpResultUnknownError(AppError):
"""ERP 写结果无法确认(Phase 2 使用);禁止自动重试。"""
def __init__(self, message: str = "ERP result unknown", *, operation_id: str | None = None):
details = {"operation_id": operation_id} if operation_id else {}
super().__init__(code=ERP_RESULT_UNKNOWN_CODE, message=message, http_status=503, retryable=False, details=details)
class ErpWriteTimeoutError(TimeoutError):
"""ERP 写超时;committed 表达是否可证明已落单。"""
def __init__(
self,
message: str,
*,
committed: bool | None,
document_no: str | None = None,
operation_id: str | None = None,
) -> None:
super().__init__(message)
self.committed = committed
self.document_no = document_no
self.operation_id = operation_id
@dataclass(frozen=True)
class TransferWriteResult:
"""ERP 原子建单/审核/过账结果分类。"""
status: str # success | duplicate_success | duplicate_unverified | business_failed | technical_failed | result_unknown
document_no: str | None = None
verified_posted: bool | None = None
error_code: str | None = None
error_message: str | None = None
class ErpTransport(Protocol):
"""ERP 传输层协议(SOAP 或测试替身)。"""
def query_inventory(self, **kwargs: Any) -> dict[str, Any]:
"""按 Invoice 查询账面库存。"""
def create_transfer(self, **kwargs: Any) -> dict[str, Any]:
"""原子建单/审核/过账(Phase 2)。"""
def verify_duplicate(self, **kwargs: Any) -> dict[str, Any]:
"""核实重复 Invoice 原单是否已审核过账。"""
class SoapErpTransport:
"""真实 SOAP 传输;凭据只来自配置/环境,不写入请求体回显。
Args:
config: 来自 Flask config 或环境变量(endpoint/username/password 等)。
"""
def __init__(self, config: dict[str, Any] | None = None) -> None:
self._config = config or {}
def _require_frozen(self, operation: str) -> None:
"""WSDL/endpoint 未冻结前任何调用直接拒绝。"""
if not str(self._config.get("endpoint") or "").strip():
raise ErpNotFrozenError(f"ERP {operation} contract not frozen (endpoint missing)")
def query_inventory(self, **kwargs: Any) -> dict[str, Any]:
"""SOAP 查询账面库存(实现待 WSDL 冻结后落地)。"""
self._require_frozen("query_inventory")
raise NotImplementedError("SOAP query_inventory implementation pending frozen WSDL")
def create_transfer(self, **kwargs: Any) -> dict[str, Any]:
"""SOAP 原子建单/审核/过账(实现待 WSDL 冻结后落地)。"""
self._require_frozen("create_transfer")
raise NotImplementedError("SOAP create_transfer implementation pending frozen WSDL")
def verify_duplicate(self, **kwargs: Any) -> dict[str, Any]:
"""SOAP 核实重复 Invoice 原单状态(实现待 WSDL 冻结后落地)。"""
self._require_frozen("verify_duplicate")
raise NotImplementedError("SOAP verify_duplicate implementation pending frozen WSDL")
class ErpAdapter:
"""ERP 唯一访问入口;组装统一请求并分类结果。"""
def __init__(self, transport: ErpTransport, *, default_org: str = "") -> None:
self._transport = transport
self._default_org = default_org
def query_inventory(
self,
*,
operation_id: str,
run_no: str,
attempt_no: int,
invoice_no: str,
erp_org: str | None = None,
from_warehouse: str,
to_warehouse: str,
quantity: Decimal,
) -> InventoryQuery:
"""查询 ERP 账面库存并分类结果。
Args:
operation_id / run_no / attempt_no / invoice_no / erp_org /
from_warehouse / to_warehouse / quantity: 请求强制追踪字段。
Returns:
InventoryQuery。
Raises:
ErpQueryTimeoutError: 查询超时(可重试)。
ErpNotFrozenError: ERP 契约未冻结。
"""
request = {
"operation_id": operation_id,
"run_no": run_no,
"attempt_no": attempt_no,
"invoice_no": invoice_no,
"erp_org": erp_org or self._default_org,
"from_warehouse": from_warehouse,
"to_warehouse": to_warehouse,
"quantity": quantity,
}
try:
response = self._transport.query_inventory(**request)
except ErpNotFrozenError:
raise
except TimeoutError as exc:
raise ErpQueryTimeoutError() from exc
response = response if isinstance(response, dict) else {}
if response.get("found"):
return InventoryQuery(found=True, quantity=Decimal(str(response.get("quantity") or "0")))
return InventoryQuery(found=False)
def _build_request(self, *, operation_id, run_no, attempt_no, invoice_no, erp_org,
from_warehouse, to_warehouse, quantity) -> dict[str, Any]:
"""组装携带全部强制追踪字段的 ERP 请求。"""
return {
"operation_id": operation_id,
"run_no": run_no,
"attempt_no": attempt_no,
"invoice_no": invoice_no,
"erp_org": erp_org or self._default_org,
"from_warehouse": from_warehouse,
"to_warehouse": to_warehouse,
"quantity": quantity,
}
def create_transfer(
self,
*,
operation_id: str,
run_no: str,
attempt_no: int,
invoice_no: str,
erp_org: str | None = None,
from_warehouse: str,
to_warehouse: str,
quantity: Decimal,
) -> TransferWriteResult:
"""ERP 原子建单/审核/过账并按结果分类。
Returns:
TransferWriteResult:success / duplicate_success / duplicate_unverified /
business_failed / technical_failed / result_unknown。
Raises:
ErpNotFrozenError: ERP 契约未冻结。
"""
request = self._build_request(
operation_id=operation_id, run_no=run_no, attempt_no=attempt_no,
invoice_no=invoice_no, erp_org=erp_org, from_warehouse=from_warehouse,
to_warehouse=to_warehouse, quantity=quantity,
)
try:
response = self._transport.create_transfer(**request)
except ErpNotFrozenError:
raise
except ErpWriteTimeoutError as exc:
if exc.committed is False:
# 可证明未落单 → 明确技术失败(不产生单据)。
return TransferWriteResult(status="technical_failed", error_code="ERP_TIMEOUT_BEFORE_COMMIT")
return TransferWriteResult(
status="result_unknown", error_code="ERP_TIMEOUT_AFTER_COMMIT",
document_no=exc.document_no,
)
except TimeoutError:
# 无法区分是否落单 → result_unknown,禁止自动重试。
return TransferWriteResult(status="result_unknown", error_code="ERP_TIMEOUT_UNKNOWN")
return _classify_write_response(response)
def verify_duplicate(
self,
*,
operation_id: str,
run_no: str,
attempt_no: int,
invoice_no: str,
erp_org: str | None = None,
from_warehouse: str,
to_warehouse: str,
quantity: Decimal,
) -> TransferWriteResult:
"""核实重复 Invoice 原单是否已审核过账(幂等确认)。
Returns:
duplicate_success(已过账,含原单号)或 duplicate_unverified。
"""
request = self._build_request(
operation_id=operation_id, run_no=run_no, attempt_no=attempt_no,
invoice_no=invoice_no, erp_org=erp_org, from_warehouse=from_warehouse,
to_warehouse=to_warehouse, quantity=quantity,
)
try:
response = self._transport.verify_duplicate(**request)
except ErpNotFrozenError:
raise
except (TimeoutError, ErpWriteTimeoutError):
return TransferWriteResult(status="result_unknown", error_code="ERP_TIMEOUT_UNKNOWN")
response = response if isinstance(response, dict) else {}
status = str(response.get("status") or "")
document_no = response.get("document_no")
posted = bool(response.get("verified_posted"))
if status == "duplicate_success" and posted:
return TransferWriteResult(status="duplicate_success", document_no=document_no, verified_posted=True)
return TransferWriteResult(
status="duplicate_unverified", document_no=document_no, verified_posted=posted,
error_code="TRANSFER_DUPLICATE_NOT_VERIFIED",
)
def _classify_write_response(response: dict[str, Any]) -> TransferWriteResult:
"""按 ERP 写响应原文分类业务结果。"""
status = str(response.get("status") or "")
document_no = response.get("document_no")
if status == "success":
return TransferWriteResult(status="success", document_no=document_no)
if status == "duplicate_success":
posted = bool(response.get("verified_posted"))
if posted:
return TransferWriteResult(status="duplicate_success", document_no=document_no, verified_posted=True)
return TransferWriteResult(
status="duplicate_unverified", document_no=document_no, verified_posted=False,
error_code="TRANSFER_DUPLICATE_NOT_VERIFIED",
)
if status == "business_failed":
return TransferWriteResult(
status="business_failed",
error_code=str(response.get("code") or "ERP_BUSINESS_REJECT"),
error_message=str(response.get("message") or ""),
)
return TransferWriteResult(status="technical_failed", error_code="ERP_UNKNOWN_RESPONSE")
@@ -1,7 +1,7 @@
"""在途调拨七 Sheet 异常 Excel 导出。
用途:按规格生成七 Sheet 异常 Excel(执行汇总/数量不一致/ERP无库存/
ERP技术失败/ERP结果未知/通知失败/原始文件追溯),供企微附件与下载。
用途:按规格生成七 Sheet 异常 Excel(执行汇总/数量不一致/外部系统无库存/
外部系统技术失败/外部系统结果未知/通知失败/原始文件追溯),供企微附件与下载。
依赖:openpyxl、models、execution_service。
逻辑:Sheet 内容按状态归类;原始文件追溯保留 Sheet/行号/文件版本;
Secret 明文永不写入单元格(仅输出业务字段)。
@@ -21,9 +21,9 @@ from app.core.errors import NotFoundError
EXCEL_SHEET_NAMES = [
"执行汇总",
"数量不一致",
"ERP无库存",
"ERP技术失败",
"ERP结果未知",
"外部系统无库存",
"外部系统技术失败",
"外部系统结果未知",
"通知失败",
"原始文件追溯",
]
@@ -53,8 +53,8 @@ def build_exceptions_workbook(run_no: str) -> bytes:
_sheet_summary(workbook, run, items)
_sheet_blocked(workbook, items, "数量不一致", {"blocked_quantity_mismatch", "precheck_expired"})
_sheet_blocked(workbook, items, "ERP无库存", {"blocked_inventory_not_found"})
_sheet_blocked(workbook, items, "ERP技术失败", {"business_failed", "technical_failed", "item_execution_error"})
_sheet_blocked(workbook, items, "外部系统无库存", {"blocked_inventory_not_found"})
_sheet_blocked(workbook, items, "外部系统技术失败", {"business_failed", "technical_failed", "item_execution_error"})
_sheet_unknown(workbook, items)
_sheet_notification(workbook, run)
_sheet_raw_trace(workbook, items)
@@ -71,30 +71,30 @@ def _sheet_summary(workbook: Workbook, run: TransferRun, items: list[TransferInv
sheet.append(["Run 状态", run.status])
sheet.append(["通知状态", run.notification_status])
sheet.append([])
sheet.append(["Invoice", "来源", "料号", "预检结果", "ERP 单号"])
sheet.append(["Invoice", "来源", "料号", "预检结果", "外部系统 单号"])
for item in items:
sheet.append([
item.invoice_no, item.source_code, item.material_no,
item.result_code or item.status, item.erp_document_no or "",
item.result_code or item.status, item.external_document_no or "",
])
def _sheet_blocked(workbook: Workbook, items: list[TransferInvoiceItem], sheet_name: str, codes: set[str]) -> None:
"""按阻断原因归类 Sheet。"""
sheet = workbook.create_sheet(sheet_name)
sheet.append(["Invoice", "来源", "料号", "收料数量", "ERP 数量", "原因"])
sheet.append(["Invoice", "来源", "料号", "收料数量", "外部系统 数量", "原因"])
for item in items:
if (item.result_code or "") in codes or item.status in codes:
sheet.append([
item.invoice_no, item.source_code, item.material_no,
item.receipt_quantity, item.erp_quantity or "",
item.receipt_quantity, item.external_quantity or "",
item.result_message or item.result_code or item.status,
])
def _sheet_unknown(workbook: Workbook, items: list[TransferInvoiceItem]) -> None:
"""ERP 结果未知 Sheet(只读提示,含 Operation 关联)。"""
sheet = workbook.create_sheet("ERP结果未知")
"""外部系统 结果未知 Sheet(只读提示,含 Operation 关联)。"""
sheet = workbook.create_sheet("外部系统结果未知")
sheet.append(["Invoice", "来源", "料号", "说明"])
sheet.append(["仅展示事实,禁止重试/关闭;请按人工核实 SOP 处理", "", "", ""])
for item in items:
@@ -1,9 +1,9 @@
"""在途调拨执行服务(确认门禁 + 写前复查 + ERP 原子写入 + 结果投影)。
"""在途调拨执行服务(确认门禁 + 写前复查 + 外部系统 原子写入 + 结果投影)。
用途:执行一次预检:校验确认范围与预检快照(fail-closed)→ 创建执行 Run →
逐项写前复查 ERP 库存 → 原子建单/审核/过账 → 按 ERP 单号投影最终结果。
依赖:orchestrator、erp_adapter、quantity、contracts、audit、status、models。
逻辑:未确认/过期/快照变化/选择含不可执行项 → ERP 写调用为 0;
逐项写前复查 外部系统 库存 → 原子建单/审核/过账 → 按 外部系统 单号投影最终结果。
依赖:orchestrator、capability_client、quantity、contracts、audit、status、models。
逻辑:未确认/过期/快照变化/选择含不可执行项 → 外部系统 写调用为 0;
每个 Invoice 独立写入,单项失败/结果未知不阻断其他项;
result_unknown 为终态,禁止自动重试;每次写入创建新 Attempt。
"""
@@ -24,11 +24,11 @@ from app.services.in_transit_transfer.audit import build_transfer_audit_event
from app.services.in_transit_transfer.contracts import (
TRANSFER_CONFIRMATION_REQUIRED,
TRANSFER_PRECHECK_EXPIRED,
ErpDocumentDTO,
ExternalDocumentDTO,
PrecheckInvoiceItemDTO,
RunResultDTO,
TransferExceptionDTO,
aggregate_erp_documents,
aggregate_external_documents,
)
from app.services.in_transit_transfer.orchestrator import create_execution_run, finalize_run
from app.services.in_transit_transfer.precheck_service import (
@@ -36,6 +36,7 @@ from app.services.in_transit_transfer.precheck_service import (
RouteNotResolvedError,
TransferDeps,
)
from app.services.in_transit_transfer.capability_client import StockTarget
from app.services.in_transit_transfer.quantity import classify_quantity_match
PRECHECK_EXPIRED_RESULT = "precheck_expired"
@@ -72,7 +73,7 @@ def recompute_precheck_hash(precheck: TransferPrecheck) -> str:
"from_warehouse": item.from_warehouse,
"to_warehouse": item.to_warehouse,
"receipt_quantity": item.receipt_quantity,
"erp_quantity": item.erp_quantity,
"external_quantity": item.external_quantity,
"result": _item_result_of(item),
}
for item in sorted(precheck.items, key=lambda row: row.id)
@@ -88,6 +89,11 @@ def recompute_precheck_hash(precheck: TransferPrecheck) -> str:
},
"items": items,
}
# [调拨类型] 创建时快照含 transfer_type(2026-09-22 起 scope_json 恒写入);
# 存量预检 scope_json 无该字段时保持旧快照形状,避免复算 Hash 不一致误判过期。
scope_transfer_type = str(precheck.scope_json.get("transfer_type") or "").strip()
if scope_transfer_type:
snapshot["transfer_type"] = scope_transfer_type
return f"sha256:{canonical_hash(snapshot)}"
@@ -115,7 +121,7 @@ def execute_precheck(
Returns:
ExecuteOutcome(run_no / run 状态 / 单据聚合结果)。
Raises:
NotFoundError / ValidationError / AppError: 门禁失败(ERP 写入为 0)。
NotFoundError / ValidationError / AppError: 门禁失败(外部系统 写入为 0)。
ConflictError: 重复执行。
"""
precheck = db.session.query(TransferPrecheck).filter_by(
@@ -185,42 +191,48 @@ def execute_precheck(
def _write_item(item: TransferInvoiceItem, *, deps: TransferDeps, run_no: str, request_id: str | None) -> None:
"""写前复查 + ERP 原子写入单个 Invoice(创建新 Attempt)。"""
route = deps.route_resolver.resolve(source_code=item.source_code, invoice_no=item.invoice_no)
"""写前复查 + 外部系统 原子写入单个 Invoice(创建新 Attempt)。"""
route = deps.route_resolver.resolve(
source_code=item.source_code, invoice_no=item.invoice_no,
warehouse_code=item.receipt_warehouse_code or "",
)
if route.from_warehouse != item.from_warehouse or route.to_warehouse != item.to_warehouse:
_mark_recheck_blocked(item, "precheck_expired", "route mapping changed since precheck")
return
receipt_qty = Decimal(item.receipt_quantity)
operation_id = f"op-{uuid.uuid4().hex[:12]}"
# [STEP 1] 写前复查:重新查询 ERP 库存并严格匹配冻结收料数量。
# [STEP 1] 写前复查:重新查询外部系统库存并严格匹配冻结收料数量。
try:
query = deps.erp.query_inventory(
operation_id=operation_id, run_no=run_no, attempt_no=item.attempt_no,
invoice_no=item.invoice_no, erp_org=route.erp_org,
from_warehouse=route.from_warehouse, to_warehouse=route.to_warehouse,
quantity=receipt_qty,
stock = deps.capabilities.query_stock(
operation_id=operation_id, external_org=route.external_org,
targets=[StockTarget(
material_no=item.material_no, from_warehouse=item.from_warehouse, lot_no=item.lot_no or "",
)],
)
stock_qty = stock.lookup(
material_no=item.material_no, from_warehouse=item.from_warehouse, lot_no=item.lot_no or "",
)
except RouteNotResolvedError:
raise
if not query.found or classify_quantity_match(receipt_qty, query.quantity) != RESULT_EXECUTABLE:
_mark_recheck_blocked(item, "precheck_expired", "erp inventory changed since precheck")
if stock_qty is None or classify_quantity_match(receipt_qty, stock_qty) != RESULT_EXECUTABLE:
_mark_recheck_blocked(item, "precheck_expired", "external inventory changed since precheck")
return
# [STEP 2] 记录写 Attempt 并调用 ERP 原子建单/审核/过账。
# [STEP 2] 记录写 Attempt 并调用外部系统原子建单/审核/过账。
attempt = TransferAttempt(
item_id=item.id, attempt_no=item.attempt_no, kind="erp_write",
item_id=item.id, attempt_no=item.attempt_no, kind="external_write",
status="running", operation_id=operation_id,
request_snapshot_json={
"run_no": run_no, "invoice_no": item.invoice_no, "erp_org": route.erp_org,
"run_no": run_no, "invoice_no": item.invoice_no, "external_org": route.external_org,
"from_warehouse": route.from_warehouse, "to_warehouse": route.to_warehouse,
"quantity": str(receipt_qty),
},
)
db.session.add(attempt)
db.session.flush()
result = deps.erp.create_transfer(
result = deps.capabilities.create_transfer(
operation_id=operation_id, run_no=run_no, attempt_no=item.attempt_no,
invoice_no=item.invoice_no, erp_org=route.erp_org,
invoice_no=item.invoice_no, external_org=route.external_org,
from_warehouse=route.from_warehouse, to_warehouse=route.to_warehouse,
quantity=receipt_qty,
)
@@ -230,7 +242,7 @@ def _write_item(item: TransferInvoiceItem, *, deps: TransferDeps, run_no: str, r
def _mark_recheck_blocked(item: TransferInvoiceItem, result: str, message: str) -> None:
"""写前复查失败:fail-closed,不写 ERP。"""
"""写前复查失败:fail-closed,不写 外部系统。"""
item.status = status_machine.TransferStatus.BLOCKED_RECOVERABLE.value
item.result_code = result
item.result_message = message
@@ -238,7 +250,7 @@ def _mark_recheck_blocked(item: TransferInvoiceItem, result: str, message: str)
def _apply_write_result(item: TransferInvoiceItem, attempt: TransferAttempt, result) -> None:
"""按 ERP 写结果分类落位 item 与 attempt(result_unknown 为终态)。"""
"""按 外部系统 写结果分类落位 item 与 attempt(result_unknown 为终态)。"""
attempt.response_summary_json = {
"status": result.status,
"document_no": result.document_no,
@@ -247,12 +259,12 @@ def _apply_write_result(item: TransferInvoiceItem, attempt: TransferAttempt, res
}
if result.status == "success":
item.status = status_machine.TransferStatus.SUCCESS.value
item.erp_document_no = result.document_no
item.external_document_no = result.document_no
item.result_code = None
attempt.status = "success"
elif result.status == "duplicate_success":
item.status = status_machine.TransferStatus.DUPLICATE_SUCCESS.value
item.erp_document_no = result.document_no
item.external_document_no = result.document_no
item.result_code = None
attempt.status = "success"
elif result.status == "result_unknown":
@@ -270,7 +282,7 @@ def _apply_write_result(item: TransferInvoiceItem, attempt: TransferAttempt, res
def _audit_item_write(item, run_no, request_id, operation_id, before_status) -> None:
"""为每次 ERP 写入追加审计事件(脱敏快照 + Hash)。"""
"""为每次 外部系统 写入追加审计事件(脱敏快照 + Hash)。"""
event = build_transfer_audit_event(
event_type="TRANSFER_ITEM_EXECUTED",
aggregate_type="transfer_item",
@@ -284,7 +296,7 @@ def _audit_item_write(item, run_no, request_id, operation_id, before_status) ->
operation_id=operation_id,
result="success" if item.status in {"success", "duplicate_success"} else "failure",
before={"status": before_status},
after={"status": item.status, "erp_document_no": item.erp_document_no},
after={"status": item.status, "external_document_no": item.external_document_no},
)
db.session.add(event)
@@ -312,7 +324,7 @@ def execute_item(*, item_id: int, deps: TransferDeps, request_id: str | None = N
def get_run(run_no: str) -> dict[str, Any]:
"""按 run_no 恢复 Run 最终结果(ERP 单号聚合 + 未生成单据异常)。"""
"""按 run_no 恢复 Run 最终结果(外部系统 单号聚合 + 未生成单据异常)。"""
run = db.session.query(TransferRun).filter_by(run_no=str(run_no).strip()).first()
if run is None:
raise NotFoundError("run not found", code="TRANSFER.RUN_NOT_FOUND")
@@ -337,12 +349,13 @@ def _build_run_result(run: TransferRun) -> RunResultDTO:
invoice_no=item.invoice_no,
receipt_date=item.receipt_date,
from_warehouse=item.from_warehouse,
from_quantity=Decimal(item.erp_quantity) if item.erp_quantity else None,
from_quantity=Decimal(item.external_quantity) if item.external_quantity else None,
to_warehouse=item.to_warehouse,
to_quantity=Decimal(item.receipt_quantity),
result=result,
reason=item.result_message or "",
erp_document_no=item.erp_document_no,
external_document_no=item.external_document_no,
receipt_warehouse_code=item.receipt_warehouse_code or "",
))
if result not in {"success", "duplicate_success"}:
exceptions.append(TransferExceptionDTO(
@@ -350,12 +363,12 @@ def _build_run_result(run: TransferRun) -> RunResultDTO:
invoice_no=item.invoice_no,
material_no=item.material_no,
reason=result,
facts=f"收料 {item.receipt_quantity}" + (f" / ERP {item.erp_quantity}" if item.erp_quantity else ""),
facts=f"收料 {item.receipt_quantity}" + (f" / 外部系统 {item.external_quantity}" if item.external_quantity else ""),
))
return RunResultDTO(
run_no=run.run_no,
status=run.status,
erp_documents=aggregate_erp_documents(item_dtos),
external_documents=aggregate_external_documents(item_dtos),
exceptions=tuple(exceptions),
)
@@ -365,7 +378,7 @@ def serialize_run_result(result: RunResultDTO) -> dict[str, Any]:
return {
"run_no": result.run_no,
"status": result.status,
"erp_documents": [
"external_documents": [
{
"document_no": document.document_no,
"from_warehouse": document.from_warehouse,
@@ -384,7 +397,7 @@ def serialize_run_result(result: RunResultDTO) -> dict[str, Any]:
for line in document.lines
],
}
for document in result.erp_documents
for document in result.external_documents
],
"exceptions": [
{
@@ -9,7 +9,7 @@
from __future__ import annotations
from dataclasses import dataclass
from datetime import date
from datetime import date, datetime
from decimal import Decimal
from typing import Any, Iterable, Mapping
@@ -34,6 +34,9 @@ class ParsedReceiptRow:
specification: str
receipt_date: date
receipt_quantity: Decimal
lot_no: str = ""
# 收料文件「仓库」列原值(movement 契约 warehouse_code):inventory_match 源映射行匹配键。
warehouse_code: str = ""
class ReceiptFileSchemaError(AppError):
@@ -53,6 +56,18 @@ def _fail(rows: list[dict[str, Any]], *, row_no: Any, reason: str) -> None:
rows.append({"row_no": row_no, "reason": reason})
def _is_unreceived_row(date_value: Any) -> bool:
"""判断是否为"无收料事实的在途行":无异动日期即跳过。
WMS 异动报告会携带两类无日期行,均不是可用的收料事实:
① 未收料在途 ASN(Date Received 空、Qty Received 0);
② 收料执行中(ASN Status=Executing,Qty Received 已计数但收料日期未盖章)。
收料日期是匹配身份与成熟过滤的必要字段,缺失即无法参与预检;
跳过后由下次排程抓取补齐(ASN 完成时盖章日期),不得整文件阻断。
"""
return not (isinstance(date_value, (date, datetime)) or str(date_value or "").strip())
def parse_movement_rows(*, source_code: str, rows: Iterable[Mapping[str, Any]]) -> list[ParsedReceiptRow]:
"""把通用异动/移动字段(doc_no/line_no/in_out_flag/material_code/...)映射为调拨解析行。
@@ -60,8 +75,9 @@ def parse_movement_rows(*, source_code: str, rows: Iterable[Mapping[str, Any]])
doc_no → invoice_no(幂等/汇总键)
quantity → receipt_quantity(严格数量匹配)
movement_date → receipt_date(成熟过滤)
其余字段(material_code→material_no、material_name、warehouse_code、storage_code、
lot_no)透传/展示保留。较 parse_receipt_rows,本函数只改字段名映射,校验逻辑一致。
其余字段(material_code→material_no、material_name、doc_no)透传/展示保留;
warehouse_code 透传至 ParsedReceiptRow.warehouse_code(inventory_match 源路由匹配键);
storage_code 仍仅展示保留。较 parse_receipt_rows,本函数只改字段名映射,校验逻辑一致。
Args:
source_code: 任务来源实例(行内来源身份一致性校验)。
@@ -120,7 +136,7 @@ def _parse_rows(
projection: 调拨语义字段(invoice_no/material_no/receipt_quantity/receipt_date)
到原始行字段名的映射(如 {invoice_no: doc_no})。
Returns:
已校验的 ParsedReceiptRow 列表。
已校验的 ParsedReceiptRow 列表("无异动日期"的在途/执行中行已跳过)。
Raises:
ReceiptFileSchemaError: 任一必填缺失、非法数量/日期或来源不一致。
"""
@@ -137,7 +153,7 @@ def _parse_rows(
invoice_no = str(row.get(invoice_key) or "").strip()
material_no = str(row.get(material_key) or "").strip()
sheet = str(row.get("sheet") or "").strip()
receipt_date_raw = str(row.get(date_key) or "").strip()
receipt_date_value = row.get(date_key)
quantity_raw = row.get(quantity_key)
if not sheet or not row_no:
@@ -153,10 +169,12 @@ def _parse_rows(
if row_source and row_source.upper() != str(source_code).upper():
_fail(errors, row_no=row_no, reason=f"source_identity_mismatch: {row_source}")
continue
if _is_unreceived_row(receipt_date_value):
continue
try:
receipt_date = parse_date(receipt_date_raw)
receipt_date = parse_date(receipt_date_value)
except ValueError:
_fail(errors, row_no=row_no, reason=f"invalid_receipt_date: {receipt_date_raw!r}")
_fail(errors, row_no=row_no, reason=f"invalid_receipt_date: {receipt_date_value!r}")
continue
try:
quantity = validate_receipt_quantity(quantity_raw)
@@ -173,6 +191,8 @@ def _parse_rows(
specification=str(row.get("specification") or "").strip(),
receipt_date=receipt_date,
receipt_quantity=quantity,
lot_no=str(row.get("lot_no") or "").strip(),
warehouse_code=str(row.get("warehouse_code") or "").strip(),
))
if errors:
raise ReceiptFileSchemaError(rows=errors)
@@ -1,80 +0,0 @@
"""services/in_transit_transfer/gateway_adapter.py
用途:把调拨的 ERP 访问收敛为通过 Integration Connector CapabilityGateway 调用
(query_inventory 是首个配置绑定消费者)。
依赖:integration_connector.gateway / capability、erp_adapter.InventoryQuery/ErpQueryTimeoutError。
逻辑:领域只调 query_inventory 能力;外部系统差异全在连接器层。create_transfer /
verify_duplicate 留待调拨执行阶段(Phase 2)接线。
"""
from __future__ import annotations
from decimal import Decimal
from typing import Any
from app.core.errors import AppError
from app.services.in_transit_transfer.erp_adapter import ErpQueryTimeoutError, InventoryQuery
QUERY_INVENTORY_CAPABILITY = "in_transit_transfer.query_inventory"
class CapabilityErpAdapter:
"""把调拨 query_inventory 收敛为通过 CapabilityGateway 调用。
Args:
gateway: 可选 Gateway;缺省用 get_capability_gateway()(可注入替身测试)。
"""
def __init__(self, gateway: Any | None = None) -> None:
self._gateway = gateway
def _gateway_or_default(self):
if self._gateway is not None:
return self._gateway
from app.services.integration_connector.gateway import get_capability_gateway
return get_capability_gateway()
def query_inventory(
self,
*,
operation_id: str,
run_no: str,
attempt_no: int,
invoice_no: str,
erp_org: str,
from_warehouse: str,
to_warehouse: str,
quantity: Decimal,
) -> InventoryQuery:
"""查询外部系统库存(经连接器框架)。
Args/Raises:
与 erp_adapter.ErpAdapter.query_inventory 一致;超时→ErpQueryTimeoutError;
写失败→AppError(预检把它归为来源失败)。P1 用默认绑定(context={});
来源专属绑定待 P2/P3。
"""
result = self._gateway_or_default().call(
capability=QUERY_INVENTORY_CAPABILITY,
context={},
params={
"invoice_no": invoice_no,
"from_warehouse": from_warehouse,
"to_warehouse": to_warehouse,
"quantity": quantity,
},
operation_id=operation_id,
)
if result.status == "timeout":
raise ErpQueryTimeoutError()
if result.status != "success":
raise AppError(
code=result.error_code or "INTEGRATION.CALL_FAILED",
message=result.error_message or "query_inventory failed",
http_status=503,
retryable=False,
)
data = result.data or {}
found = bool(data.get("found"))
qty = data.get("quantity")
return InventoryQuery(found=found, quantity=Decimal(str(qty)) if qty is not None else None)
@@ -1,9 +1,9 @@
"""在途调拨 Invoice 多行汇总与冲突阻断。
"""在途调拨 Invoice 多行汇总。
用途:相同 Invoice 多行只汇总收料数量,并永久保留原始 Sheet/行号/文件版本;
同一 Invoice 出现多料号或多收料日期时整单阻断(InvoiceConflictError)。
用途:相同 Invoice+料号+收料日期 的多行只汇总收料数量,并永久保留原始
Sheet/行号/文件版本;同 Invoice 跨料号或跨日期自然拆分为多张发票。
依赖:app.core.errors.AppError、contracts.RawLineRefDTO。
逻辑:汇总键 (source_code, invoice_no);冲突判定基于料号与收料日期。
逻辑:汇总键 (source_code, invoice_no, material_no, receipt_date)。
"""
from __future__ import annotations
@@ -30,6 +30,9 @@ class AggregatedInvoice:
receipt_date: date
receipt_quantity: Decimal
raw_lines: tuple[RawLineRefDTO, ...]
lot_no: str = ""
# 组内首行收料仓库值(movement 契约 warehouse_code):inventory_match 源路由匹配键。
warehouse_code: str = ""
class InvoiceConflictError(AppError):
@@ -45,34 +48,25 @@ class InvoiceConflictError(AppError):
def aggregate_invoices(rows: Iterable[ParsedReceiptRow], *, file_version: str = "v1") -> list[AggregatedInvoice]:
"""按 Invoice 汇总收料数量并保留原始行证据。
"""按 Invoice+料号+收料日期 汇总收料数量并保留原始行证据。
汇总键 (source_code, invoice_no, material_no, receipt_date):Invoice 语义为
调拨拨出单据号(如 WMS 的 External ASN #);同单号跨料号或跨收料日期时
自然拆分为多张发票(部分交付场景),不做整单阻断。
Args:
rows: 已校验的解析行。
file_version: 当前文件版本(写入原始行追溯)。
Returns:
汇总后的 Invoice 列表(按 Invoice 排序)。
Raises:
InvoiceConflictError: 同一 Invoice 多料号或多收料日期。
汇总后的 Invoice 列表(按汇总键排序)。
"""
grouped: dict[tuple[str, str], list[ParsedReceiptRow]] = {}
grouped: dict[tuple[str, str, str, date], list[ParsedReceiptRow]] = {}
for row in rows:
grouped.setdefault((row.source_code, row.invoice_no), []).append(row)
grouped.setdefault(
(row.source_code, row.invoice_no, row.material_no, row.receipt_date), [],
).append(row)
invoices: list[AggregatedInvoice] = []
for (source_code, invoice_no), group in sorted(grouped.items()):
material_nos = {row.material_no for row in group}
dates = {row.receipt_date for row in group}
if len(material_nos) > 1:
raise InvoiceConflictError(
invoice_no=invoice_no,
conflict=f"multiple_material_no: {sorted(material_nos)}",
)
if len(dates) > 1:
raise InvoiceConflictError(
invoice_no=invoice_no,
conflict=f"multiple_receipt_date: {sorted(str(item) for item in dates)}",
)
for (source_code, invoice_no, material_no, receipt_date), group in sorted(grouped.items()):
first = group[0]
raw_lines = tuple(
RawLineRefDTO(sheet=row.sheet, row_no=row.row_no, file_version=file_version)
@@ -81,11 +75,13 @@ def aggregate_invoices(rows: Iterable[ParsedReceiptRow], *, file_version: str =
invoices.append(AggregatedInvoice(
source_code=source_code,
invoice_no=invoice_no,
material_no=first.material_no,
material_no=material_no,
material_name=first.material_name,
specification=first.specification,
receipt_date=first.receipt_date,
receipt_date=receipt_date,
receipt_quantity=sum((row.receipt_quantity for row in group), Decimal("0")),
raw_lines=raw_lines,
lot_no=first.lot_no,
warehouse_code=first.warehouse_code,
))
return invoices
@@ -41,6 +41,8 @@ class MovementField:
# 定死的 10 个通用异动字段(领域契约,不配置化)。
# [PROMPT_UPDATE] 2026-09-21:Invoice 保持锚定单号(doc_no,WMS 收料单号);
# 批号(lot_no)为展示维度——预检列「拨出/拨入批号」由 lot_no 经 WTP→HOW 转换派生。
MOVEMENT_FIELDS: tuple[MovementField, ...] = (
MovementField("doc_no", "单号", MovementFieldValueType.TEXT, is_identity=True, required=True),
MovementField("line_no", "项次", MovementFieldValueType.TEXT),
@@ -4,9 +4,11 @@
用该来源收料配置绑定的 movement 解析规则(purpose='movement',端点=定死
领域字段 MOVEMENT_FIELDS)的 field_mapping 把列映射为领域行,产出 ReadyReceiptFile。
依赖:ShippingReceiptReportFile / ShippingReceiptReportConfig / file_asset_storage、
movement_contract、openpyxl。
逻辑:按来源取最新未过期(未清理)收料文件;无绑定 movement profile 或文件缺失时
返回 None(fail-closed),绝不伪造 ready 文件。行完整校验由下游 file_parser 完成。
movement_contract、receipt_file_gate(可用性门禁)、openpyxl。
逻辑:按来源取最新【当天(业务日)抓取】且未过期(未清理)的收料文件;无绑定规则、
文件缺失或隔日旧文件时返回 None(fail-closed),绝不伪造 ready 文件。行 dict = 领域
字段 + 溯源字段(sheet=实际工作表标题、row_no=工作表真实 1-based 行号);行完整
校验由下游 file_parser 完成。
"""
from __future__ import annotations
@@ -16,6 +18,7 @@ from typing import Any, Mapping
from app.services.file_assets.storage import file_asset_storage
from app.services.in_transit_transfer.file_preparation import ReadyReceiptFile
from app.services.in_transit_transfer.receipt_file_gate import usable_receipt_file_condition
class ShippingReceiptFileRepository:
@@ -25,20 +28,21 @@ class ShippingReceiptFileRepository:
self._storage = file_asset_storage
def latest_ready_file(self, *, source_code: str, business_date: str) -> ReadyReceiptFile | None:
"""返回该来源最新未过期收料文件;无绑定规则或文件缺失时返回 None。
"""返回该来源最新且当天(业务日)抓取的未过期收料文件;否则返回 None。
Args:
source_code: 来源实例编码。
business_date: 业务日期(用于展示/匹配成熟度,不强制匹配文件日期)。
Returns:
ReadyReceiptFile(rows 为领域字段名 dict)或 None。
ReadyReceiptFile(rows 为领域字段 + 溯源 sheet/row_no 的 dict)或 None。
新鲜度/保留期/缺失均 fail-closed 返回 None(fail 消息由上游触发重抓)。
"""
from app.models import ShippingInventorySource, ShippingReceiptReportConfig, ShippingReceiptReportFile
source = ShippingInventorySource.query.filter_by(source_code=source_code, enabled=True).first()
if source is None:
return None
config = ShippingReceiptReportConfig.query.filter_by(inventory_source_id=source.id, enabled=True).first()
config = ShippingReceiptReportConfig.query.filter_by(inventory_source_id=source.id).first()
if config is None or config.parsing_profile_id is None:
return None
profile = config.parsing_profile
@@ -50,7 +54,8 @@ class ShippingReceiptFileRepository:
.join(ShippingReceiptReportFile.unit_run)
.filter(
ShippingReceiptReportFile.unit_run.has(source_code=source_code),
ShippingReceiptReportFile.archive_deleted_at.is_(None),
# 可用门禁(未清理 + 当天业务日抓取 + 未过保留期)单一事实来源见 receipt_file_gate。
usable_receipt_file_condition(),
)
.order_by(ShippingReceiptReportFile.created_at.desc(), ShippingReceiptReportFile.id.desc())
.first()
@@ -85,7 +90,8 @@ def _extract_movement_rows(
"""从 xlsx 字节按 movement field_mapping 提取领域行 dict。
field_mapping: {定死领域字段 code: Excel 表头别名}(端点必须是 MOVEMENT_FIELDS 的 code)。
输出以领域字段 code 为 key 的行,供 file_parser.parse_movement_rows 校验。
输出以领域字段 code 为 key 的行,并附带溯源字段(sheet=实际使用的工作表标题、
row_no=数据行在工作表中的真实 1-based 行号),供 file_parser.parse_movement_rows 校验。
"""
from openpyxl import load_workbook
from app.services.shipping_notice.inventory_snapshot import find_inventory_header_row_index
@@ -111,15 +117,32 @@ def _extract_movement_rows(
headers = [str(c or '').strip() for c in raw_rows[header_idx]]
data_rows = [list(r) for r in raw_rows[header_idx + 1:] if r]
header_to_code = {str(alias).strip(): str(code).strip() for code, alias in field_mapping.items()}
return [_map_header_row(headers, row, header_to_code) for row in data_rows]
header_to_code: dict[str, list[str]] = {}
for code, alias in field_mapping.items():
# 一个表头别名可被多个领域字段共用(如 CRANE 单号/批号同源 ASN 列);
# 反查必须是 一别名→多字段,不得互相覆盖。
header_to_code.setdefault(str(alias).strip(), []).append(str(code).strip())
# 溯源字段:sheet 取实际使用的工作表标题;row_no 为数据行在工作表中的真实
# 1-based 行号(表头在第 header_idx+1 行,第 offset 个数据行 = header_idx+2+offset),
# 使下游 RawLineRef 证据引用指向真实电子表格行,并满足 parse_movement_rows 行校验。
sheet_title = str(ws.title or '').strip()
return [
{"sheet": sheet_title, "row_no": header_idx + 2 + offset,
**_map_header_row(headers, row, header_to_code)}
for offset, row in enumerate(data_rows)
]
def _map_header_row(headers: list[str], row: list[Any], header_to_code: dict[str, str]) -> dict[str, Any]:
"""把一行原始单元格按表头别名映射为定死领域字段 dict。"""
def _map_header_row(headers: list[str], row: list[Any], header_to_code: dict[str, list[str]]) -> dict[str, Any]:
"""把一行原始单元格按表头别名映射为定死领域字段 dict。
header_to_code 为 一别名→多字段 列表:共用同一表头别名的字段
(如 doc_no 与 lot_no 同源一列)各自都写入该单元格值,互不覆盖。
"""
output: dict[str, Any] = {}
for index, header in enumerate(headers):
code = header_to_code.get(header)
if code and index < len(row):
output[code] = row[index]
codes = header_to_code.get(header)
if codes and index < len(row):
for code in codes:
output[code] = row[index]
return output
@@ -1,9 +1,9 @@
"""在途调拨企业微信汇总通知。
用途:每个非空 Run 恰好一条汇总通知;空数据不通知;通知失败记录
notification_failed 且不改变 ERP 业务结果(run.status 保持)。
notification_failed 且不改变 外部系统 业务结果(run.status 保持)。
依赖:models、audit、typing.Protocol。
逻辑:通知状态独立于 ERP 状态;已成功投递幂等(每个 Run 一条)。
逻辑:通知状态独立于 外部系统 状态;已成功投递幂等(每个 Run 一条)。
"""
from __future__ import annotations
@@ -65,7 +65,7 @@ def notify_run_summary(*, run_no: str, sender: WeComSender, recipients: list[str
if failed:
run.notification_error_code = str(outcome.get("error_code") or "WECOM_SEND_FAILED")
run.notification_error_message = str(outcome.get("error_message") or "")
# 关键:通知失败绝不修改 run.status(ERP 业务结果保持)。
# 关键:通知失败绝不修改 run.status(外部系统 业务结果保持)。
db.session.add(build_transfer_audit_event(
event_type="TRANSFER_NOTIFICATION",
aggregate_type="transfer_run",
@@ -1,10 +1,10 @@
"""在途调拨预检服务。
用途:编排"文件准备 → 解析 → Invoice 汇总 → D+1 成熟过滤 → ERP 库存查询 →
用途:编排"文件准备 → 解析 → Invoice 汇总 → D+1 成熟过滤 → 外部系统 库存查询 →
严格数量匹配 → 预检快照与 Hash",并支持预检进度恢复(restore)。
依赖:file_preparation / file_parser / invoice_aggregator / erp_adapter /
依赖:file_preparation / file_parser / invoice_aggregator / capability_client /
date_policy / quantity / contracts / audit / models。
逻辑:来源实例独立处理,任一来源失败不阻断其他来源;当天收料不查询 ERP;
逻辑:来源实例独立处理,任一来源失败不阻断其他来源;当天收料不查询 外部系统;
预检 Hash 由冻结快照复算;create_precheck 落库 Run + Precheck + Items。
"""
@@ -29,14 +29,17 @@ from app.services.in_transit_transfer.contracts import (
)
from app.services.in_transit_transfer.date_policy import (
MATURITY_ELIGIBLE,
eligible_receipt_date_to,
MATURITY_FUTURE,
MATURITY_NOT_MATURED,
maturity_status,
parse_date,
)
from app.services.in_transit_transfer.erp_adapter import ErpQueryTimeoutError
from app.services.in_transit_transfer.capability_client import ExternalQueryTimeoutError, StockTarget
from app.services.in_transit_transfer.file_parser import (
ParsedReceiptRow,
ReceiptFileSchemaError,
parse_movement_rows,
parse_receipt_rows,
)
from app.services.in_transit_transfer.file_preparation import (
@@ -46,7 +49,6 @@ from app.services.in_transit_transfer.file_preparation import (
ensure_receipt_file_ready,
)
from app.services.in_transit_transfer.invoice_aggregator import (
InvoiceConflictError,
aggregate_invoices,
)
from app.services.in_transit_transfer.quantity import classify_quantity_match
@@ -54,6 +56,13 @@ from app.services.in_transit_transfer.strategy import (
TransferStrategyPolicy,
default_strategy,
)
from app.services.in_transit_transfer.transfer_type import (
TransferType,
ensure_transfer_type_supported,
filter_invoices_for_type,
normalize_transfer_type,
transfer_type_scope_note,
)
ROUTE_NOT_RESOLVED_CODE = "TRANSFER.ROUTE_NOT_RESOLVED"
@@ -63,14 +72,15 @@ RESULT_NOT_MATURED = "not_matured"
RESULT_QUANTITY_MISMATCH = "blocked_quantity_mismatch"
RESULT_INVENTORY_NOT_FOUND = "blocked_inventory_not_found"
RESULT_FUTURE_DATE = "blocked_future_date"
RESULT_ERP_QUERY_TIMEOUT = "erp_query_timeout"
RESULT_EXTERNAL_QUERY_FAILED = "blocked_external_query_failed"
RESULT_EXTERNAL_QUERY_TIMEOUT = "external_query_timeout"
@dataclass(frozen=True)
class RouteMapping:
"""来源路由:ERP 组织 / 拨出仓(ERP 在途仓)/ 拨入仓(ERP 映射仓)。"""
"""来源路由:外部组织(external_org,取自仓库映射)/ 拨出仓(外部在途仓)/ 拨入仓(映射仓)。"""
erp_org: str
external_org: str
from_warehouse: str
to_warehouse: str
@@ -90,8 +100,8 @@ class RouteNotResolvedError(AppError):
class RouteResolver(Protocol):
"""来源路由解析协议(路由归属规则冻结前由 Fake/门禁兜底)。"""
def resolve(self, *, source_code: str, invoice_no: str) -> RouteMapping:
"""返回 Invoice 的路由;无法归属时抛 RouteNotResolvedError。"""
def resolve(self, *, source_code: str, invoice_no: str, warehouse_code: str = "") -> RouteMapping:
"""返回 Invoice 的路由(warehouse_code 为收料文件仓库列,inventory_match 源匹配键);无法归属时抛 RouteNotResolvedError。"""
@dataclass(frozen=True)
@@ -123,7 +133,7 @@ class TransferDeps:
file_repository: ReceiptFileRepository
rpa_trigger: RpaTrigger
route_resolver: RouteResolver
erp: Any
capabilities: Any
strategy: TransferStrategyPolicy = field(default_factory=default_strategy)
@@ -143,22 +153,40 @@ def run_precheck(
deps: TransferDeps,
active_source_job_key: str | None = None,
run_no: str = "RUN-PENDING",
receipt_date_from: str | None = None,
receipt_date_to: str | None = None,
transfer_type: TransferType | str | None = None,
) -> PrecheckRunResult:
"""执行一次只读预检(不写 ERP)。
"""执行一次只读预检(不写 外部系统)。
Args:
source_codes: 来源实例列表(DBS/Crane 仅分组,实例为执行边界)。
business_date: 业务日期 T(YYYY-MM-DD)。
deps: 注入的文件仓库 / RPA / 路由 / ERP 依赖。
deps: 注入的文件仓库 / RPA / 路由 / 外部系统 依赖。
active_source_job_key: 活动 Source Job 键(缺文件时绑定已有任务)。
run_no: Run 编号(创建 Run 前可为占位)。
receipt_date_from / receipt_date_to: 可选收料日期查询范围。
transfer_type: 调拨业务类型(缺省在途仓至HUB仓);类型决定收料数据范围。
Returns:
PrecheckRunResult(摘要 + 明细 + 来源进度)。
Raises:
ValidationError: source_codes 为空。
ValidationError: source_codes 为空、日期范围非法或调拨类型非法/未支持。
"""
if not source_codes:
raise ValidationError("source_codes is required")
resolved_transfer_type = normalize_transfer_type(transfer_type)
ensure_transfer_type_supported(resolved_transfer_type)
# [日期范围] 可选收料日期过滤;卡控:截止不得超出 D+1 规则(业务日期-1),起始不得晚于截止。
range_from = parse_date(receipt_date_from) if receipt_date_from else None
range_to = parse_date(receipt_date_to) if receipt_date_to else None
if range_from and range_to and range_from > range_to:
raise ValidationError(
"receipt date range is invalid", code="TRANSFER.RECEIPT_DATE_RANGE_INVALID",
)
if range_to and range_to > eligible_receipt_date_to(business_date):
raise ValidationError(
"receipt date range end exceeds D+1 maturity limit", code="TRANSFER.RECEIPT_DATE_RANGE_INVALID",
)
validate_strategy = deps.strategy
sources: list[SourceProgressDTO] = []
@@ -188,8 +216,17 @@ def run_precheck(
"file_version": ready_file.file_version,
"checksum": ready_file.checksum,
}
parsed = parse_receipt_rows(source_code=source_code, rows=ready_file.rows)
# 真实仓库(movement_file_repository)产出 movement 领域字段行
# (doc_no/material_code/quantity/movement_date),按异动解析规则映射校验。
parsed = parse_movement_rows(source_code=source_code, rows=ready_file.rows)
invoices = aggregate_invoices(parsed, file_version=ready_file.file_version)
if range_from is not None:
invoices = [invoice for invoice in invoices if invoice.receipt_date >= range_from]
if range_to is not None:
invoices = [invoice for invoice in invoices if invoice.receipt_date <= range_to]
# [调拨类型] 类型决定收料数据范围(如类型1仅保留 INVOICE 前缀 HOM/HOX/WTP),
# 范围外票与日期范围过滤同语义:静默排除、不入明细、不阻断来源。
invoices = filter_invoices_for_type(invoices, resolved_transfer_type)
source_items = _precheck_invoices(
invoices=invoices,
source_code=source_code,
@@ -206,7 +243,7 @@ def run_precheck(
file_version=ready_file.file_version,
checksum=ready_file.checksum,
))
except (ReceiptFileSchemaError, InvoiceConflictError) as exc:
except ReceiptFileSchemaError as exc:
sources.append(SourceProgressDTO(
source_code=source_code, stage="failed",
error_code=exc.code, error_message=exc.message,
@@ -238,6 +275,7 @@ def run_precheck(
snapshot = {
"scope": sorted(set(source_codes)),
"business_date": business_date,
"transfer_type": resolved_transfer_type.value,
"file_snapshot": file_snapshot,
"counts": {
"file_invoice_count": counts.file_invoice_count,
@@ -253,7 +291,7 @@ def run_precheck(
"from_warehouse": item.from_warehouse,
"to_warehouse": item.to_warehouse,
"receipt_quantity": str(item.to_quantity),
"erp_quantity": str(item.from_quantity) if item.from_quantity is not None else None,
"external_quantity": str(item.from_quantity) if item.from_quantity is not None else None,
"result": item.result,
}
for item in items
@@ -271,7 +309,7 @@ def run_precheck(
expires_at="",
counts=counts,
estimated_transfer_quantity=str(estimated_quantity),
estimated_erp_write_count=counts.executable_count,
estimated_external_write_count=counts.executable_count,
precheck_hash=precheck_hash,
)
return PrecheckRunResult(summary=summary, items=tuple(items), sources=sources_tuple)
@@ -286,8 +324,12 @@ def _precheck_invoices(
deps: TransferDeps,
run_no: str,
) -> list[PrecheckInvoiceItemDTO]:
"""对单个来源的汇总 Invoice 逐项预检(成熟过滤 → 路由 → ERP → 匹配)。"""
"""对单个来源的汇总 Invoice 预检(成熟过滤 → 路由 → 按组织分组批量查 外部系统 → 匹配)。"""
output: list[PrecheckInvoiceItemDTO] = []
# [STEP 1] 成熟过滤与路由解析(不查询):未成熟/未来日期直接落位,
# 成熟项按 external_org(仓库映射的外部组织)分组,每组合并为一次批量查询。
matured: list[tuple[Any, RouteMapping, tuple[RawLineRefDTO, ...], str]] = []
for invoice in invoices:
maturity = maturity_status(invoice.receipt_date, business_date)
raw = tuple(
@@ -299,10 +341,11 @@ def _precheck_invoices(
output.append(PrecheckInvoiceItemDTO(
source_code=source_code, material_no=invoice.material_no,
material_name=invoice.material_name, specification=invoice.specification,
invoice_no=invoice.invoice_no, receipt_date=receipt_date_iso,
invoice_no=invoice.invoice_no, lot_no=invoice.lot_no, receipt_date=receipt_date_iso,
from_warehouse="", from_quantity=None,
to_warehouse="", to_quantity=invoice.receipt_quantity,
result=RESULT_NOT_MATURED, reason="receipt not matured until next business day",
receipt_warehouse_code=invoice.warehouse_code or "",
raw_lines=raw,
))
continue
@@ -310,61 +353,98 @@ def _precheck_invoices(
output.append(PrecheckInvoiceItemDTO(
source_code=source_code, material_no=invoice.material_no,
material_name=invoice.material_name, specification=invoice.specification,
invoice_no=invoice.invoice_no, receipt_date=receipt_date_iso,
invoice_no=invoice.invoice_no, lot_no=invoice.lot_no, receipt_date=receipt_date_iso,
from_warehouse="", from_quantity=None,
to_warehouse="", to_quantity=invoice.receipt_quantity,
result=RESULT_FUTURE_DATE, reason="future receipt date",
receipt_warehouse_code=invoice.warehouse_code or "",
raw_lines=raw,
))
continue
route = deps.route_resolver.resolve(source_code=source_code, invoice_no=invoice.invoice_no)
route = deps.route_resolver.resolve(
source_code=source_code, invoice_no=invoice.invoice_no,
warehouse_code=invoice.warehouse_code or "",
)
matured.append((invoice, route, raw, receipt_date_iso))
groups: dict[str, list[tuple[Any, RouteMapping, tuple[RawLineRefDTO, ...], str]]] = {}
for entry in matured:
groups.setdefault(entry[1].external_org, []).append(entry)
# [STEP 2] 每个组织一次批量查询(targets = 料号+拨出库位+拨出批号 元组列表),
# 组内逐票按三元组精确匹配库存数量;组级故障降级到组内全部票,不炸整来源。
for external_org, entries in groups.items():
targets = [
StockTarget(material_no=invoice.material_no, from_warehouse=route.from_warehouse, lot_no=invoice.lot_no)
for invoice, route, _, _ in entries
]
operation_id = f"op-{uuid.uuid4().hex[:12]}"
try:
query = deps.erp.query_inventory(
operation_id=operation_id,
run_no=run_no,
attempt_no=1,
invoice_no=invoice.invoice_no,
erp_org=route.erp_org,
from_warehouse=route.from_warehouse,
to_warehouse=route.to_warehouse,
quantity=invoice.receipt_quantity,
stock = deps.capabilities.query_stock(
operation_id=operation_id, external_org=external_org, targets=targets,
)
except ErpQueryTimeoutError:
except ExternalQueryTimeoutError:
for invoice, route, raw, receipt_date_iso in entries:
output.append(PrecheckInvoiceItemDTO(
source_code=source_code, material_no=invoice.material_no,
material_name=invoice.material_name, specification=invoice.specification,
invoice_no=invoice.invoice_no, lot_no=invoice.lot_no, receipt_date=receipt_date_iso,
from_warehouse=route.from_warehouse,
from_quantity=None, to_warehouse=route.to_warehouse,
to_quantity=invoice.receipt_quantity,
result=RESULT_EXTERNAL_QUERY_TIMEOUT, reason="external query timeout",
receipt_warehouse_code=invoice.warehouse_code or "",
raw_lines=raw,
))
continue
except Exception as exc: # noqa: BLE001 —— 网关/绑定层故障降级为整组阻断,不炸整来源
# [语义] 绑定缺失、连接失败等基础设施故障是环境问题而非业务阻断:
# 组内逐票给 blocked_external_query_failed + 原因,预检列表保持可见可解释。
detail = str(exc).strip() or getattr(exc, "message", "") or exc.__class__.__name__
for invoice, route, raw, receipt_date_iso in entries:
output.append(PrecheckInvoiceItemDTO(
source_code=source_code, material_no=invoice.material_no,
material_name=invoice.material_name, specification=invoice.specification,
invoice_no=invoice.invoice_no, lot_no=invoice.lot_no, receipt_date=receipt_date_iso,
from_warehouse=route.from_warehouse,
from_quantity=None, to_warehouse=route.to_warehouse,
to_quantity=invoice.receipt_quantity,
result=RESULT_EXTERNAL_QUERY_FAILED, reason=f"external query failed: {detail}",
receipt_warehouse_code=invoice.warehouse_code or "",
raw_lines=raw,
))
continue
for invoice, route, raw, receipt_date_iso in entries:
stock_qty = stock.lookup(
material_no=invoice.material_no, from_warehouse=route.from_warehouse, lot_no=invoice.lot_no,
)
if stock_qty is None:
output.append(PrecheckInvoiceItemDTO(
source_code=source_code, material_no=invoice.material_no,
material_name=invoice.material_name, specification=invoice.specification,
invoice_no=invoice.invoice_no, lot_no=invoice.lot_no, receipt_date=receipt_date_iso,
from_warehouse=route.from_warehouse,
# 查无库存记录也是外部系统的真实答复:库存数按 0 展示(而非"-"),
# 避免用户误以为查询失败;分类仍为 blocked_inventory_not_found。
from_quantity=Decimal("0"), to_warehouse=route.to_warehouse,
to_quantity=invoice.receipt_quantity,
result=RESULT_INVENTORY_NOT_FOUND, reason="external inventory not found",
receipt_warehouse_code=invoice.warehouse_code or "",
raw_lines=raw,
))
continue
match = classify_quantity_match(invoice.receipt_quantity, stock_qty)
output.append(PrecheckInvoiceItemDTO(
source_code=source_code, material_no=invoice.material_no,
material_name=invoice.material_name, specification=invoice.specification,
invoice_no=invoice.invoice_no, receipt_date=receipt_date_iso,
invoice_no=invoice.invoice_no, lot_no=invoice.lot_no, receipt_date=receipt_date_iso,
from_warehouse=route.from_warehouse,
from_quantity=None, to_warehouse=route.to_warehouse,
from_quantity=stock_qty, to_warehouse=route.to_warehouse,
to_quantity=invoice.receipt_quantity,
result=RESULT_ERP_QUERY_TIMEOUT, reason="erp query timeout",
result=match, reason="" if match == RESULT_EXECUTABLE else "strict quantity mismatch",
receipt_warehouse_code=invoice.warehouse_code or "",
raw_lines=raw,
))
continue
if not query.found:
output.append(PrecheckInvoiceItemDTO(
source_code=source_code, material_no=invoice.material_no,
material_name=invoice.material_name, specification=invoice.specification,
invoice_no=invoice.invoice_no, receipt_date=receipt_date_iso,
from_warehouse=route.from_warehouse,
from_quantity=None, to_warehouse=route.to_warehouse,
to_quantity=invoice.receipt_quantity,
result=RESULT_INVENTORY_NOT_FOUND, reason="erp inventory not found",
raw_lines=raw,
))
continue
match = classify_quantity_match(invoice.receipt_quantity, query.quantity)
output.append(PrecheckInvoiceItemDTO(
source_code=source_code, material_no=invoice.material_no,
material_name=invoice.material_name, specification=invoice.specification,
invoice_no=invoice.invoice_no, receipt_date=receipt_date_iso,
from_warehouse=route.from_warehouse,
from_quantity=query.quantity, to_warehouse=route.to_warehouse,
to_quantity=invoice.receipt_quantity,
result=match, reason="" if match == RESULT_EXECUTABLE else "strict quantity mismatch",
raw_lines=raw,
))
return output
@@ -374,7 +454,7 @@ def _item_status(result: str) -> str:
RESULT_EXECUTABLE: status_machine.TransferStatus.READY_TO_EXECUTE.value,
RESULT_NOT_MATURED: status_machine.TransferStatus.NOT_MATURED.value,
RESULT_FUTURE_DATE: status_machine.TransferStatus.BLOCKED_RECOVERABLE.value,
RESULT_ERP_QUERY_TIMEOUT: status_machine.TransferStatus.BLOCKED_RECOVERABLE.value,
RESULT_EXTERNAL_QUERY_TIMEOUT: status_machine.TransferStatus.BLOCKED_RECOVERABLE.value,
RESULT_QUANTITY_MISMATCH: status_machine.TransferStatus.BLOCKED_RECOVERABLE.value,
RESULT_INVENTORY_NOT_FOUND: status_machine.TransferStatus.BLOCKED_RECOVERABLE.value,
}
@@ -393,20 +473,29 @@ def create_precheck(
business_date: str,
deps: TransferDeps,
active_source_job_key: str | None = None,
receipt_date_from: str | None = None,
receipt_date_to: str | None = None,
transfer_type: TransferType | str | None = None,
) -> PrecheckSummaryDTO:
"""运行预检并落库 TransferRun + TransferPrecheck + InvoiceItems。
Args:
source_codes / business_date / deps: 同 run_precheck。
receipt_date_from / receipt_date_to / transfer_type: 同 run_precheck。
Returns:
预检摘要(precheck_id 已回填)。
"""
resolved_transfer_type = normalize_transfer_type(transfer_type)
ensure_transfer_type_supported(resolved_transfer_type)
run_no = _generate_no("RUN", business_date)
result = run_precheck(
source_codes=source_codes,
business_date=business_date,
deps=deps,
active_source_job_key=active_source_job_key,
receipt_date_from=receipt_date_from,
receipt_date_to=receipt_date_to,
transfer_type=resolved_transfer_type,
run_no=run_no,
)
now = datetime.utcnow()
@@ -417,6 +506,7 @@ def create_precheck(
status="prechecking",
source_codes_json=list(source_codes),
counts_json=asdict(result.summary.counts),
transfer_type=resolved_transfer_type.value,
)
db.session.add(run)
db.session.flush()
@@ -434,6 +524,8 @@ def create_precheck(
run_id=run.id,
source_code=job_source.source_code,
status=job_source.stage if job_source.stage in _valid_job_statuses else 'pending',
error_code=job_source.error_code,
error_message=job_source.error_message,
)
precheck_no = _generate_no("TPC", business_date)
@@ -442,7 +534,13 @@ def create_precheck(
run_id=run.id,
business_date=business_date,
status=result.summary.status,
scope_json={"source_codes": list(source_codes)},
scope_json={
"source_codes": list(source_codes),
"receipt_date_from": receipt_date_from,
"receipt_date_to": receipt_date_to,
"transfer_type": resolved_transfer_type.value,
"transfer_type_scope": transfer_type_scope_note(resolved_transfer_type),
},
file_snapshot_json={
stage.source_code: {
"file_no": stage.file_no,
@@ -456,34 +554,65 @@ def create_precheck(
strategy_version="v0",
counts_json=asdict(result.summary.counts),
estimated_transfer_quantity=result.summary.estimated_transfer_quantity,
estimated_erp_write_count=result.summary.estimated_erp_write_count,
estimated_external_write_count=result.summary.estimated_external_write_count,
precheck_hash=result.summary.precheck_hash,
expires_at=now + timedelta(seconds=deps.strategy.confirm_ttl_seconds),
)
db.session.add(precheck)
db.session.flush()
# [幂等] 相同 (来源,单号,料号,收料日期) 的重复预检不得累加异常行:
# 非终态行原地刷新并挂到最新预检;终态行(已执行/人工关闭等)保持既定事实不复活。
_terminal_item_statuses = {
status_machine.TransferStatus.SUCCESS.value,
status_machine.TransferStatus.DUPLICATE_SUCCESS.value,
status_machine.TransferStatus.MANUALLY_CLOSED.value,
status_machine.TransferStatus.CANCELLED.value,
status_machine.TransferStatus.EXECUTING.value,
}
for item in result.items:
fields = {
"precheck_id": precheck.id,
"status": _item_status(item.result),
"result_code": item.result if item.result != RESULT_EXECUTABLE else None,
"result_message": item.reason or None,
"from_warehouse": item.from_warehouse or "",
"to_warehouse": item.to_warehouse or "",
"receipt_quantity": str(item.to_quantity),
"external_quantity": str(item.from_quantity) if item.from_quantity is not None else None,
"lot_no": item.lot_no or "",
"receipt_warehouse_code": item.receipt_warehouse_code or "",
"raw_lines_json": [
{"sheet": line.sheet, "row_no": line.row_no, "file_version": line.file_version}
for line in item.raw_lines
],
}
# 禁 autoflush:避免本批 pending 插入在查询时提前落库(应随循环末统一 commit)。
with db.session.no_autoflush:
existing = (
TransferInvoiceItem.query.filter_by(
source_code=item.source_code,
invoice_no=item.invoice_no,
material_no=item.material_no,
receipt_date=item.receipt_date,
)
.order_by(TransferInvoiceItem.id.desc())
.first()
)
if existing is not None:
if existing.status not in _terminal_item_statuses:
for attr, value in fields.items():
setattr(existing, attr, value)
continue
# 预检阶段不绑定执行 Run(run_id 在执行 Run 创建时由 orchestrator 关联)。
db.session.add(TransferInvoiceItem(
precheck_id=precheck.id,
# 预检阶段不绑定执行 Run(run_id 在执行 Run 创建时由 orchestrator 关联)。
source_code=item.source_code,
invoice_no=item.invoice_no,
material_no=item.material_no,
material_name=item.material_name,
specification=item.specification,
receipt_date=item.receipt_date,
from_warehouse=item.from_warehouse or "",
to_warehouse=item.to_warehouse or "",
receipt_quantity=str(item.to_quantity),
erp_quantity=str(item.from_quantity) if item.from_quantity is not None else None,
status=_item_status(item.result),
result_code=item.result if item.result != RESULT_EXECUTABLE else None,
result_message=item.reason or None,
raw_lines_json=[
{"sheet": line.sheet, "row_no": line.row_no, "file_version": line.file_version}
for line in item.raw_lines
],
**fields,
))
db.session.commit()
@@ -495,7 +624,7 @@ def create_precheck(
expires_at=precheck.expires_at.isoformat() if precheck.expires_at else "",
counts=result.summary.counts,
estimated_transfer_quantity=result.summary.estimated_transfer_quantity,
estimated_erp_write_count=result.summary.estimated_erp_write_count,
estimated_external_write_count=result.summary.estimated_external_write_count,
precheck_hash=result.summary.precheck_hash,
)
return summary
@@ -531,7 +660,7 @@ def restore_precheck(precheck_id: str) -> dict[str, Any]:
expires_at=precheck.expires_at.isoformat() if precheck.expires_at else "",
counts=counts,
estimated_transfer_quantity=precheck.estimated_transfer_quantity or "0",
estimated_erp_write_count=int(precheck.estimated_erp_write_count or 0),
estimated_external_write_count=int(precheck.estimated_external_write_count or 0),
precheck_hash=precheck.precheck_hash,
)
items = []
@@ -542,13 +671,19 @@ def restore_precheck(precheck_id: str) -> dict[str, Any]:
material_name=item.material_name,
specification=item.specification,
invoice_no=item.invoice_no,
receipt_date=item.receipt_date,
lot_no=item.lot_no or "",
receipt_warehouse_code=item.receipt_warehouse_code or "",
from_warehouse=item.from_warehouse,
from_quantity=Decimal(item.erp_quantity) if item.erp_quantity else None,
from_quantity=Decimal(item.external_quantity) if item.external_quantity else None,
to_warehouse=item.to_warehouse,
to_quantity=Decimal(item.receipt_quantity),
result=item.result_code or (
RESULT_EXECUTABLE if item.status == "ready_to_execute" else item.status
),
# 失败原因落库于 result_message(预检/重查降级均写);restore 不回读则
# 前端刷新后原因恒为空,呈现「安静阻断」无法排查。
reason=item.result_message or "",
raw_lines=tuple(
RawLineRefDTO(
sheet=line.get("sheet", ""),
@@ -565,6 +700,8 @@ def restore_precheck(precheck_id: str) -> dict[str, Any]:
file_no=job.file_no,
file_version=None,
checksum=job.file_sha256,
error_code=job.error_code,
error_message=job.error_message,
)
for job in (precheck.run.source_jobs if precheck.run else [])
] or [
@@ -1,6 +1,6 @@
"""在途调拨严格数量门禁。
用途:实现"收料数量 == ERP 账面库存 才可执行"的精确匹配规则,
用途:实现"收料数量 == 外部系统 账面库存 才可执行"的精确匹配规则,
禁止部分调拨、数量容差与隐式截断。
依赖:标准库 decimal。
逻辑:所有比较基于 Decimal 精确语义;非法数量(0/负数/非数字)在解析层拒绝。
@@ -45,17 +45,17 @@ def strict_quantities_equal(left: Any, right: Any) -> bool:
return Decimal(str(left)) == Decimal(str(right))
def classify_quantity_match(receipt_quantity: Any, erp_quantity: Any | None) -> str:
def classify_quantity_match(receipt_quantity: Any, external_quantity: Any | None) -> str:
"""按严格相等规则分类数量匹配结果。
Args:
receipt_quantity: 收料数量。
erp_quantity: ERP 账面库存;None 表示无库存。
external_quantity: 外部系统 账面库存;None 表示无库存。
Returns:
'executable' | 'blocked_quantity_mismatch' | 'blocked_inventory_not_found'。
"""
if erp_quantity is None:
if external_quantity is None:
return MATCH_INVENTORY_NOT_FOUND
if strict_quantities_equal(receipt_quantity, erp_quantity):
if strict_quantities_equal(receipt_quantity, external_quantity):
return MATCH_EXECUTABLE
return MATCH_QUANTITY_MISMATCH
@@ -9,7 +9,7 @@
from __future__ import annotations
from datetime import datetime
from datetime import datetime, timedelta
from app import db
from app.models import TransferSourceJob
@@ -55,3 +55,33 @@ def advance_source_job_from_receipt_callback(
job.finished_at = datetime.utcnow()
db.session.flush()
return job
def recover_stale_waiting_source_jobs() -> int:
"""把超过收料回调超时仍 waiting_rpa_callback 的调拨来源任务回收为 failed。
【AI 触发时机】:仅由排程队列周期扫描(queue_service)与收料超时回收同批调用;
不自动重试 RPA——用户可在来源选择卡手动重试(与收料回收"绝不自动重试"口径一致)。
Returns:
本次回收的任务数。
"""
from flask import current_app
try:
timeout = max(60, int(current_app.config.get('FREIGHT_RPA_RECEIPT_TIMEOUT_SECONDS', 900)))
except (TypeError, ValueError):
timeout = 900
cutoff = datetime.utcnow() - timedelta(seconds=timeout)
stale = (
TransferSourceJob.query
.filter(TransferSourceJob.status == _WAITING_RPA_CALLBACK, TransferSourceJob.updated_at < cutoff)
.all()
)
for job in stale:
job.status = _FAILED
job.error_code = 'RPA_RECEIPT_CALLBACK_TIMEOUT'
job.error_message = f'receipt rpa callback not received within {timeout}s'
job.finished_at = datetime.utcnow()
if stale:
db.session.commit()
return len(stale)
@@ -0,0 +1,69 @@
"""在途调拨收料归档文件的可用性门禁(单一事实来源)。
用途:把「一份 ShippingReceiptReportFile 是否可用于调拨链路」的判定收敛为本模块,
供来源状态投影(source_file_status)、预检取文件(movement_file_repository)、
收料文件下载(api/in_transit_transfer)三处统一引用,防止口径漂移。
依赖:models(ShippingReceiptReportFile)、date_policy(业务日 UTC 窗口换算)。
逻辑:可用 = 未清理 且 当天(Asia/Shanghai 业务日)抓取 且 未过保留期;
已失效(expired)= 可用核心的反相(未清理 且 [保留期已到 或 非当天抓取])。
两函数同核推导,规则文本只存在一处。
"""
from __future__ import annotations
from datetime import datetime
from sqlalchemy import ColumnElement, and_, not_, or_
from app.models import ShippingReceiptReportFile
from app.services.in_transit_transfer.date_policy import business_date_utc_window
def _fresh_and_retention_valid(now: datetime) -> ColumnElement:
"""新鲜度 + 保留期核心条件(不含清理态,供可用/失效两函数共用)。"""
window_start, window_end = business_date_utc_window(now)
return and_(
ShippingReceiptReportFile.created_at >= window_start,
ShippingReceiptReportFile.created_at < window_end,
or_(
ShippingReceiptReportFile.archive_expires_at.is_(None),
ShippingReceiptReportFile.archive_expires_at > now,
),
)
def usable_receipt_file_condition(*, now: datetime | None = None) -> ColumnElement:
"""返回「当前可用的收料归档文件」SQL 条件。
判定:未清理(archive_deleted_at 为空)+ 当天(Asia/Shanghai 业务日)抓取
+ 未过保留期(archive_expires_at 为空视为长期有效)。预检复用与下载
只认可用文件;隔日/过期文件一律 fail-closed,交由上游触发重抓。
Args:
now: 可选判定时刻;naive 按 UTC 兼容处理,缺省取当前 UTC。
Returns:
可直接并入 .filter() 的单个 SQLAlchemy 条件。
"""
now = now or datetime.utcnow()
return and_(
ShippingReceiptReportFile.archive_deleted_at.is_(None),
_fresh_and_retention_valid(now),
)
def expired_receipt_file_condition(*, now: datetime | None = None) -> ColumnElement:
"""返回「文件仍在但已失效」SQL 条件(来源状态投影 expired 的依据)。
判定:未清理 且 可用核心不成立(保留期已到 或 非当天业务日抓取)。
命中即提示用户重试重抓,不报 ready,也不等待保留期清理任务落位。
Args:
now: 可选判定时刻;naive 按 UTC 兼容处理,缺省取当前 UTC。
Returns:
可直接并入 .filter() 的单个 SQLAlchemy 条件。
"""
now = now or datetime.utcnow()
return and_(
ShippingReceiptReportFile.archive_deleted_at.is_(None),
not_(_fresh_and_retention_valid(now)),
)
@@ -2,10 +2,11 @@
用途:为单个来源触发一次收料/异动 RPA 抓取(复用货代收料 trigger 链路),不创建排程。
按来源取 ShippingInventorySource + ShippingReceiptReportConfig + rpa_profile,
装配收料 trigger unit,调用 write_receipt_export_batch_trigger 原子写 trigger。
依赖:write_receipt_export_batch_trigger(默认 writer)、models。
先落 ShippingReceiptRpaUnitRun(awaiting_rpa,回调按 callback_id 查库可达),
再装配收料 trigger unit 并调用 write_receipt_export_batch_trigger 原子写 trigger。
依赖:write_receipt_export_batch_trigger(默认 writer)、models、db。
逻辑:来源停用/收料配置缺失/rpa_profile 缺失时 fail-closed(返回 ok=False),绝不伪造等待;
写 trigger writer 可注入替身(测试)。
写 trigger 失败把单元行标 failed 并 commit;写 trigger writer 可注入替身(测试)。
"""
from __future__ import annotations
@@ -23,27 +24,29 @@ def _build_trigger_unit(
) -> dict[str, Any]:
"""装配单来源收料 trigger unit;配置缺失时抛 RuntimeError(由调用方转 fail-closed)。"""
from app.models import ShippingInventorySource, ShippingReceiptReportConfig
from app.services.shipping_notice.receipt_rpa import receipt_unit_parameters, receipt_warehouse_values
source = ShippingInventorySource.query.filter_by(source_code=source_code, enabled=True).first()
if source is None:
raise RuntimeError(f'source not enabled: {source_code}')
config = ShippingReceiptReportConfig.query.filter_by(inventory_source_id=source.id, enabled=True).first()
config = ShippingReceiptReportConfig.query.filter_by(inventory_source_id=source.id).first()
if config is None:
raise RuntimeError(f'receipt config missing: {source_code}')
profile = source.rpa_profile
if profile is None or not profile.enabled:
raise RuntimeError(f'receipt source profile unavailable: {source_code}')
warehouses = config.warehouse_ids_json or [] if source.connector_type == 'dbs' else [None]
warehouse_id = str(warehouses[0]) if warehouses else None
# Warehouse 条件即逐仓拆分维度:按需触发取第一个仓,单元快照剥离 Warehouse 条件。
warehouses = receipt_warehouse_values(config) if source.connector_type == 'dbs' else [None]
warehouse_id = str(warehouses[0]) if warehouses and warehouses[0] else None
snapshot = {
'config_id': config.id, 'config_version': config.config_version,
'connector_type': source.connector_type,
'report_path_json': config.report_path_json or {},
'query_parameters_json': config.query_parameters_json or [],
'query_parameters_json': receipt_unit_parameters(config),
'warehouse_id': warehouse_id, 'rpa_profile_id': source.rpa_profile_id,
}
return {
'unit_run_id': 0,
'inventory_source_id': source.id,
'callback_id': f'receipt:{uuid.uuid4().hex}',
'source_code': source.source_code,
'connector_type': source.connector_type,
@@ -71,7 +74,7 @@ def trigger_receipt_rpa(
reason: str = 'transfer_retry_receipt',
writer: RouteTriggerWriter | None = None,
) -> dict[str, Any]:
"""触发一次来源收料 RPA 抓取。
"""触发一次来源收料 RPA 抓取(先落单元行再写 trigger,保证回调可达)。
Args:
source_code: 来源实例编码。
@@ -83,13 +86,33 @@ def trigger_receipt_rpa(
{"ok": False, "error_code": ...}(配置缺失 / 触发目录不可用)。
"""
try:
unit = _build_trigger_unit(source_code=source_code, business_date=business_date, reason=reason)
unit_payload = _build_trigger_unit(source_code=source_code, business_date=business_date, reason=reason)
except RuntimeError as exc:
return {"ok": False, "error_code": "RPA_RECEIPT_CONFIG_MISSING", "error_message": str(exc)}
# [STEP 1] 先落可审计单元行并 flush 取 id——回调入口按 callback_id 查库,
# 不落行则回调必然 404(与排程路径 _build_unit 同一模式)。
from app import db
from app.models import ShippingReceiptRpaUnitRun
unit = ShippingReceiptRpaUnitRun(
# 按需触发无 ScheduleRun:schedule_run_id 保持 NULL(列可空;FK 禁止 0 占位)。
inventory_source_id=unit_payload['inventory_source_id'],
source_code=unit_payload['source_code'],
connector_type=unit_payload['connector_type'],
warehouse_id=unit_payload.get('warehouse_id'),
callback_id=unit_payload['callback_id'],
status='awaiting_rpa',
config_snapshot_json=dict(unit_payload['config_snapshot']),
)
db.session.add(unit)
db.session.flush()
unit_payload['unit_run_id'] = unit.id
# [STEP 2] 原子写 trigger;目录不可用则单元标 failed(fail-closed,不留永久 awaiting)。
run_no = f"TRIG-{source_code}-{uuid.uuid4().hex[:8].upper()}"
writer_fn = writer or write_receipt_export_batch_trigger
path = writer_fn(run_no, [unit], payload={
path = writer_fn(run_no, [unit_payload], payload={
'schema_version': 'shipping_receipt_rpa.v1',
'action': 'receipt_export_batch',
'source_code': source_code,
@@ -97,5 +120,13 @@ def trigger_receipt_rpa(
'reason': reason,
})
if not path:
unit.status = 'failed'
unit.error_code = 'RPA_RECEIPT_TRIGGER_UNAVAILABLE'
unit.error_message = 'receipt trigger directory unavailable'
db.session.commit()
return {"ok": False, "error_code": "RPA_RECEIPT_TRIGGER_UNAVAILABLE"}
return {"ok": True, "callback_id": unit['callback_id'], "trigger_path": path}
# [STEP 3] 冻结快照供审计;commit 必须先于返回——Worker 拿到文件即可能回调。
unit.trigger_snapshot_json = unit_payload
db.session.commit()
return {"ok": True, "callback_id": unit_payload['callback_id'], "trigger_path": path}
@@ -1,9 +1,9 @@
"""在途调拨每日历史恢复(自动复核待处理池)。
用途:下一排程对可恢复异常项用最新文件与 ERP 重新预检并创建新 Attempt;
用途:下一排程对可恢复异常项用最新文件与 外部系统 重新预检并创建新 Attempt;
result_unknown / manually_closed / success 不自动写入。
依赖:models、retry_service._recheck_item、TransferDeps。
逻辑:恢复仅查询/匹配,不写 ERP;每次恢复新 Attempt,旧 Attempt 不变。
逻辑:恢复仅查询/匹配,不写 外部系统;每次恢复新 Attempt,旧 Attempt 不变。
"""
from __future__ import annotations
@@ -1,13 +1,14 @@
"""在途调拨人工重试服务(基于冻结文件仅重新查询 ERP)。
"""在途调拨人工重试服务(基于冻结文件仅重新查询 外部系统)。
用途:对允许的异常项执行人工重试,只创建新 Attempt 并重新查询 ERP;
用途:对允许的异常项执行人工重试,只创建新 Attempt 并重新查询 外部系统;
Run 创建后禁止重新抓取 RPA(文件冻结);result_unknown 只读拒绝。
依赖:models、erp_adapter、quantity、status、audit、precheck_service.TransferDeps。
逻辑:重试不写 ERP、不替换文件;匹配成功进入 ready_to_execute,否则保持阻断。
依赖:models、capability_client、quantity、status、audit、precheck_service.TransferDeps。
逻辑:重试不写 外部系统、不替换文件;匹配成功进入 ready_to_execute,否则保持阻断。
"""
from __future__ import annotations
import logging
import uuid
from datetime import datetime
from decimal import Decimal
@@ -17,55 +18,107 @@ from app.core.errors import NotFoundError, ValidationError
from app.models import TransferAttempt, TransferInvoiceItem
from app.services.in_transit_transfer import status as status_machine
from app.services.in_transit_transfer.audit import build_transfer_audit_event
from app.services.in_transit_transfer.precheck_service import RESULT_EXECUTABLE, TransferDeps
from app.services.in_transit_transfer.capability_client import StockTarget
from app.services.in_transit_transfer.precheck_service import (
RESULT_EXTERNAL_QUERY_FAILED,
RESULT_EXECUTABLE,
TransferDeps,
)
from app.services.in_transit_transfer.quantity import classify_quantity_match
RETRY_KIND_ERP_RECHECK = "erp_recheck"
RETRY_KIND_EXTERNAL_RECHECK = "external_recheck"
RETRY_KIND_RPA_REFETCH = "rpa_refetch"
# 可重查状态:可恢复阻断 + 可执行(已可执行的行也允许重查核对最新库存,
# 避免预检后库存变化无法发现);终态(已执行/人工关闭等)仍不可重查。
_RETRYABLE_STATUSES = {
status_machine.TransferStatus.BLOCKED_RECOVERABLE.value,
status_machine.TransferStatus.READY_TO_EXECUTE.value,
}
logger = logging.getLogger(__name__)
def _recheck_item(item: TransferInvoiceItem, *, deps: TransferDeps, request_id: str | None) -> str:
"""对单个异常项重新查询 ERP 并更新状态(创建新 Attempt)。
"""对单个异常项重新查询 外部系统 并更新状态(创建新 Attempt)。
Returns:
重检后的 item 状态。
"""
route = deps.route_resolver.resolve(source_code=item.source_code, invoice_no=item.invoice_no)
route = deps.route_resolver.resolve(
source_code=item.source_code, invoice_no=item.invoice_no,
warehouse_code=item.receipt_warehouse_code or "",
)
operation_id = f"op-{uuid.uuid4().hex[:12]}"
receipt_qty = Decimal(item.receipt_quantity)
query = deps.erp.query_inventory(
operation_id=operation_id,
run_no=item.run.run_no if item.run else "RUN-PENDING",
attempt_no=item.attempt_no + 1,
invoice_no=item.invoice_no,
erp_org=route.erp_org,
from_warehouse=route.from_warehouse,
to_warehouse=route.to_warehouse,
quantity=receipt_qty,
)
item.attempt_no += 1
before_status = item.status
attempt = TransferAttempt(
item_id=item.id, attempt_no=item.attempt_no, kind="erp_query",
item_id=item.id, attempt_no=item.attempt_no, kind="external_query",
status="running", operation_id=operation_id,
request_snapshot_json={
"invoice_no": item.invoice_no, "erp_org": route.erp_org,
"invoice_no": item.invoice_no, "external_org": route.external_org,
"from_warehouse": route.from_warehouse, "to_warehouse": route.to_warehouse,
"quantity": str(receipt_qty),
},
)
db.session.add(attempt)
db.session.flush()
if not query.found or classify_quantity_match(receipt_qty, query.quantity) != RESULT_EXECUTABLE:
# [降级] 与 precheck 逐票语义一致:外部系统网关/绑定故障(如集成连接器缺绑定
# BindingNotFoundError)记为该行 blocked_external_query_failed + 原因,
# 不中断批量重查、不向调用方抛基础设施异常(避免全局错误弹窗)。
try:
stock = deps.capabilities.query_stock(
operation_id=operation_id, external_org=route.external_org,
targets=[StockTarget(
material_no=item.material_no, from_warehouse=item.from_warehouse, lot_no=item.lot_no or "",
)],
)
stock_qty = stock.lookup(
material_no=item.material_no, from_warehouse=item.from_warehouse, lot_no=item.lot_no or "",
)
except Exception as exc: # noqa: BLE001
detail = str(exc).strip() or getattr(exc, "message", "") or exc.__class__.__name__
# 降级只落 DB(result_message/审计),若再无应用日志,控制台侧完全无痕可查。
logger.warning(
"transfer external recheck failed (degrade to blocked): invoice=%s item=%s attempt=%s error=%s",
item.invoice_no, item.id, item.attempt_no, detail,
)
item.status = status_machine.TransferStatus.BLOCKED_RECOVERABLE.value
item.result_code = "blocked_inventory_not_found" if not query.found else "blocked_quantity_mismatch"
item.result_message = "erp inventory not found" if not query.found else "strict quantity mismatch"
item.result_code = RESULT_EXTERNAL_QUERY_FAILED
item.result_message = f"external query failed: {detail}"
attempt.status = "failed"
attempt.completed_at = datetime.utcnow()
db.session.add(build_transfer_audit_event(
event_type="TRANSFER_ITEM_RECHECKED",
aggregate_type="transfer_item",
aggregate_id=str(item.id),
run_no=item.run.run_no if item.run else None,
invoice_no=item.invoice_no,
item_id=str(item.id),
attempt_no=item.attempt_no,
actor_type="worker",
request_id=request_id,
operation_id=operation_id,
result="failure",
before={"status": before_status},
after={"status": item.status, "attempt_no": item.attempt_no, "error": detail},
))
db.session.flush()
return item.status
if stock_qty is None or classify_quantity_match(receipt_qty, stock_qty) != RESULT_EXECUTABLE:
item.status = status_machine.TransferStatus.BLOCKED_RECOVERABLE.value
item.result_code = "blocked_inventory_not_found" if stock_qty is None else "blocked_quantity_mismatch"
item.result_message = "external inventory not found" if stock_qty is None else "strict quantity mismatch"
# 查无记录与数量不足都是外部系统的真实答复:库存数必须落库展示(查无记录按 0),
# 不得显示"-"让用户误以为查询失败。
item.external_quantity = str(stock_qty) if stock_qty is not None else "0"
attempt.status = "failed"
else:
item.status = status_machine.TransferStatus.READY_TO_EXECUTE.value
item.result_code = None
item.result_message = None
item.erp_quantity = str(query.quantity)
item.external_quantity = str(stock_qty)
attempt.status = "success"
attempt.completed_at = datetime.utcnow()
db.session.add(build_transfer_audit_event(
@@ -87,14 +140,14 @@ def _recheck_item(item: TransferInvoiceItem, *, deps: TransferDeps, request_id:
return item.status
def retry_item(*, item_id: int, deps: TransferDeps, kind: str = RETRY_KIND_ERP_RECHECK,
def retry_item(*, item_id: int, deps: TransferDeps, kind: str = RETRY_KIND_EXTERNAL_RECHECK,
actor_id: int | None = None, request_id: str | None = None) -> dict:
"""人工重试异常项。
Args:
item_id: TransferInvoiceItem.id。
deps: 注入依赖。
kind: erp_recheck(默认);rpa_refetch 在 Run 创建后禁止。
kind: external_recheck(默认);rpa_refetch 在 Run 创建后禁止。
actor_id / request_id: 审计上下文。
Returns:
{"item_id": ..., "status": ..., "attempt_no": ...}。
@@ -105,16 +158,65 @@ def retry_item(*, item_id: int, deps: TransferDeps, kind: str = RETRY_KIND_ERP_R
kind_value = str(kind or "").strip()
if kind_value == RETRY_KIND_RPA_REFETCH:
raise ValidationError("RPA refetch is not allowed after execution run is created", code="TRANSFER.RETRY_RPA_NOT_ALLOWED")
if kind_value != RETRY_KIND_ERP_RECHECK:
if kind_value != RETRY_KIND_EXTERNAL_RECHECK:
raise ValidationError(f"unsupported retry kind: {kind_value}", code="TRANSFER.RETRY_KIND_INVALID")
item = db.session.get(TransferInvoiceItem, item_id)
if item is None:
raise NotFoundError("transfer invoice item not found", code="TRANSFER.ITEM_NOT_FOUND")
if item.status == status_machine.TransferStatus.RESULT_UNKNOWN.value:
raise ValidationError("result_unknown is read-only; follow manual verification SOP", code="TRANSFER_RESULT_UNKNOWN")
if item.status not in {status_machine.TransferStatus.BLOCKED_RECOVERABLE.value}:
if item.status not in _RETRYABLE_STATUSES:
raise ValidationError(f"item status {item.status} is not retryable", code="TRANSFER.RETRY_NOT_ALLOWED")
status = _recheck_item(item, deps=deps, request_id=request_id)
db.session.commit()
return {"item_id": item.id, "status": status, "attempt_no": item.attempt_no}
def requery_items(*, precheck_no: str, deps: TransferDeps, invoice_nos: list[str] | None = None,
actor_id: int | None = None, request_id: str | None = None) -> dict:
"""批量重查 外部系统 库存:对同一预检下全部/指定的可重查行(可恢复阻断 + 可执行)逐票重查并刷新。
Args:
precheck_no: 预检编号(定位明细集合)。
deps: 注入依赖(capabilities = 外部系统网关客户端)。
invoice_nos: 可选,按 Invoice(单号)过滤;缺省 = 该预检全部可重查行。
actor_id / request_id: 审计上下文。
Returns:
{"precheck_no", "total", "results": [{invoice_no, item_id, ok, status|error}]};
单行失败(状态不允许/不存在)不影响其余行(来源级隔离同款语义)。
"""
from app.models import TransferPrecheck
precheck = TransferPrecheck.query.filter_by(precheck_no=precheck_no).first()
if precheck is None:
raise NotFoundError("precheck not found", code="TRANSFER.PRECHECK_NOT_FOUND")
query = TransferInvoiceItem.query.filter(
TransferInvoiceItem.precheck_id == precheck.id,
TransferInvoiceItem.status.in_(_RETRYABLE_STATUSES),
)
wanted = [str(x or "").strip() for x in (invoice_nos or []) if str(x or "").strip()]
if wanted:
query = query.filter(TransferInvoiceItem.invoice_no.in_(wanted))
items = query.order_by(TransferInvoiceItem.id).all()
results: list[dict] = []
for item in items:
try:
retry_item(item_id=item.id, deps=deps, kind=RETRY_KIND_EXTERNAL_RECHECK,
actor_id=actor_id, request_id=request_id)
results.append({"invoice_no": item.invoice_no, "item_id": item.id,
"ok": True, "status": item.status})
except (ValidationError, NotFoundError) as exc:
results.append({"invoice_no": item.invoice_no, "item_id": item.id,
"ok": False, "error": exc.message})
except Exception as exc: # noqa: BLE001 —— 批量隔离兜底:任何单行异常不炸整批
# 与 _recheck_item 降级同理:DB 只留单行结果,控制台必须同步留痕。
logger.warning(
"transfer requery row crashed (skipped): invoice=%s item=%s error=%s",
item.invoice_no, item.id, str(exc).strip() or exc.__class__.__name__,
)
results.append({"invoice_no": item.invoice_no, "item_id": item.id,
"ok": False,
"error": str(exc).strip() or exc.__class__.__name__})
return {"precheck_no": precheck_no, "total": len(items), "results": results}
@@ -28,7 +28,7 @@ def serialize_summary(summary) -> dict[str, Any]:
"blocked_count": summary.counts.blocked_count,
},
"estimated_transfer_quantity": summary.estimated_transfer_quantity,
"estimated_erp_write_count": summary.estimated_erp_write_count,
"estimated_external_write_count": summary.estimated_external_write_count,
"precheck_hash": summary.precheck_hash,
}
@@ -41,6 +41,7 @@ def serialize_item(item) -> dict[str, Any]:
"material_name": item.material_name,
"specification": item.specification,
"invoice_no": item.invoice_no,
"lot_no": item.lot_no,
"receipt_date": item.receipt_date,
"from_warehouse": item.from_warehouse,
"from_quantity": str(item.from_quantity) if item.from_quantity is not None else None,
@@ -3,14 +3,20 @@
用途:只读货代收料链路已有事实(ShippingReceiptRpaUnitRun + ShippingReceiptReportFile),
按来源实例投影出"是否有 ready 文件 / 是否抓取中 / 是否失败 / 无文件待触发",
供 /sources 接口与前端门禁/状态标识使用。调拨不维护独立抓取状态表(低耦合)。
依赖:models(ShippingReceiptRpaUnitRun / ShippingReceiptReportFile)。
逻辑:按来源取该来源最新收料执行单元;有文件 → ready;有进行中单元 → fetching;
最新单元为失败终态 → failed;否则 → none。
依赖:models(ShippingReceiptRpaUnitRun / ShippingReceiptReportFile)、
receipt_file_gate(可用/失效判定单一事实来源)。
逻辑:按来源取该来源最新收料执行单元;命中可用门禁(当天业务日抓取且未过期,
见 receipt_file_gate)→ ready;有进行中单元 → fetching;
最新单元为失败终态 → failed;文件仍在但已失效 → expired;否则 → none。
"""
from __future__ import annotations
from app.models import ShippingReceiptReportFile, ShippingReceiptRpaUnitRun
from app.services.in_transit_transfer.receipt_file_gate import (
expired_receipt_file_condition,
usable_receipt_file_condition,
)
RUNNING_UNIT_STATUSES = ('queued', 'awaiting_rpa', 'processing')
FAILED_UNIT_STATUSES = ('failed', 'empty', 'cancelled')
@@ -19,16 +25,19 @@ FAILED_UNIT_STATUSES = ('failed', 'empty', 'cancelled')
def resolve_source_file_status(*, source_code: str) -> dict:
"""返回某来源的收料文件状态投影。
失效判定(不依赖保留期清理任务落位,与预检取文件/下载同口径,见
receipt_file_gate):保留期已到 或 非当前业务日(Asia/Shanghai)抓取。
Returns:
{"file_status": ..., "has_ready_file": bool, "file_no": ..., "file_sha256": ...},
file_status ∈ {'ready', 'fetching', 'failed', 'none'}。
file_status ∈ {'ready', 'fetching', 'failed', 'expired', 'none'}。
"""
report = (
ShippingReceiptReportFile.query
.join(ShippingReceiptReportFile.unit_run)
.filter(
ShippingReceiptReportFile.unit_run.has(source_code=source_code),
ShippingReceiptReportFile.archive_deleted_at.is_(None),
usable_receipt_file_condition(),
)
.order_by(ShippingReceiptReportFile.created_at.desc(), ShippingReceiptReportFile.id.desc())
.first()
@@ -60,4 +69,17 @@ def resolve_source_file_status(*, source_code: str) -> dict:
if latest_unit is not None and latest_unit.status in FAILED_UNIT_STATUSES:
return {'file_status': 'failed', 'has_ready_file': False, 'file_no': None, 'file_sha256': None}
# 文件仍在但已失效(保留期已到或隔日旧文件):不报 ready,单独投影 expired 提示重抓。
expired_report = (
ShippingReceiptReportFile.query
.join(ShippingReceiptReportFile.unit_run)
.filter(
ShippingReceiptReportFile.unit_run.has(source_code=source_code),
expired_receipt_file_condition(),
)
.first()
)
if expired_report is not None:
return {'file_status': 'expired', 'has_ready_file': False, 'file_no': None, 'file_sha256': None}
return {'file_status': 'none', 'has_ready_file': False, 'file_no': None, 'file_sha256': None}
@@ -4,7 +4,7 @@
让 create_precheck / restore / 未来回调等调用方都经由本服务,不各自散落改表。
依赖:models(TransferSourceJob)、status_machine。
逻辑:本服务只操作 run 内来源状态;(run_id, source_code) 唯一由模型约束;
不承担跨 run 防重(不同 run/不同人各自独立 job),也不写 ERP/触发 RPA。
不承担跨 run 防重(不同 run/不同人各自独立 job),也不写 外部系统/触发 RPA。
"""
from __future__ import annotations
@@ -21,13 +21,22 @@ SOURCE_JOB_STATUSES = (
)
def create_source_job(*, run_id: int, source_code: str, status: str = 'pending') -> TransferSourceJob:
def create_source_job(
*,
run_id: int,
source_code: str,
status: str = 'pending',
error_code: str | None = None,
error_message: str | None = None,
) -> TransferSourceJob:
"""为一次 run 创建一条来源级 job;(run_id, source_code) 唯一由模型约束。
Args:
run_id: 所属 TransferRun.id。
source_code: 来源实例编码。
status: 初始状态。
error_code / error_message: 来源级失败事实(如解析失败 error_code),
随创建落库,保证刷新/恢复后失败原因仍可见(不静默丢成全 0)。
Returns:
新建(或复用已存在同 run 同来源)的 TransferSourceJob。
"""
@@ -36,7 +45,13 @@ def create_source_job(*, run_id: int, source_code: str, status: str = 'pending')
)
if existing is not None:
return existing
job = TransferSourceJob(run_id=run_id, source_code=source_code, status=status)
job = TransferSourceJob(
run_id=run_id,
source_code=source_code,
status=status,
error_code=error_code,
error_message=error_message,
)
db.session.add(job)
db.session.flush()
return job
@@ -7,7 +7,7 @@
逻辑:转换表声明即白名单,未声明的迁移一律抛 TransferStateError;
result_unknown / manually_closed / success / duplicate_success /
not_matured / cancelled 为无出边终态;
通知失败(notification_failed)是通知投递状态,绝不改写 ERP 业务结果。
通知失败(notification_failed)是通知投递状态,绝不改写 外部系统 业务结果。
"""
from __future__ import annotations
@@ -39,7 +39,7 @@ class TransferStatus(StrEnum):
class TransferRunStatus(StrEnum):
"""Run 级生命周期;ERP 结果与通知结果分离。"""
"""Run 级生命周期;外部系统 结果与通知结果分离。"""
QUEUED = "queued"
PREPARING_FILES = "preparing_files"
@@ -101,7 +101,7 @@ ITEM_TRANSITIONS: dict[str, frozenset[str]] = {
TransferStatus.CANCELLED.value,
}),
TransferStatus.BLOCKED_RECOVERABLE.value: frozenset({
TransferStatus.PRECHECKING.value, # 仅 ERP 重查/重新预检,创建新 Attempt
TransferStatus.PRECHECKING.value, # 仅 外部系统 重查/重新预检,创建新 Attempt
TransferStatus.MANUALLY_CLOSED.value,
TransferStatus.CANCELLED.value,
}),
@@ -199,19 +199,19 @@ def assert_transition_allowed(
def apply_notification_failure(run_status: str) -> str:
"""通知失败不改变 ERP 结果。
"""通知失败不改变 外部系统 结果。
Args:
run_status: Run 的 ERP 业务终态。
run_status: Run 的 外部系统 业务终态。
Returns:
原 run_status(保持不变)。
Raises:
TransferStateError: Run 尚未进入 ERP 终态时不允许记录通知失败。
TransferStateError: Run 尚未进入 外部系统 终态时不允许记录通知失败。
"""
status = str(run_status or "").strip()
if status not in {TransferRunStatus.SUCCESS.value, TransferRunStatus.PARTIAL_FAILED.value}:
raise TransferStateError(
"notification failure only allowed after ERP terminal status",
"notification failure only allowed after 外部系统 terminal status",
current=status,
)
return status
@@ -1,6 +1,6 @@
"""在途调拨策略硬门禁。
用途:一期策略禁止部分数量调拨、数量容差与 ERP 自动重试,
用途:一期策略禁止部分数量调拨、数量容差与 外部系统 自动重试,
强制默认 10 分钟确认有效期。
依赖:app.core.errors.AppError、standard decimal。
逻辑:任何策略变体触碰三项禁令之一即抛 StrategyViolationError,
@@ -24,7 +24,7 @@ class TransferStrategyPolicy:
allow_partial: bool = False
quantity_tolerance: Decimal = Decimal("0")
allow_erp_auto_retry: bool = False
allow_external_auto_retry: bool = False
confirm_ttl_seconds: int = DEFAULT_CONFIRM_TTL_SECONDS
@@ -46,14 +46,14 @@ def validate_strategy(strategy: TransferStrategyPolicy) -> None:
Args:
strategy: 待校验策略。
Raises:
StrategyViolationError: 开启部分调拨、非零容差或 ERP 自动重试。
StrategyViolationError: 开启部分调拨、非零容差或 外部系统 自动重试。
"""
if strategy.allow_partial:
raise StrategyViolationError("partial transfer is not supported in phase 1", reason="allow_partial")
if strategy.quantity_tolerance != Decimal("0"):
raise StrategyViolationError("quantity tolerance is not supported in phase 1", reason="quantity_tolerance")
if strategy.allow_erp_auto_retry:
raise StrategyViolationError("ERP auto retry is forbidden in phase 1", reason="allow_erp_auto_retry")
if strategy.allow_external_auto_retry:
raise StrategyViolationError("External auto retry is forbidden in phase 1", reason="allow_external_auto_retry")
def default_strategy() -> TransferStrategyPolicy:
@@ -0,0 +1,109 @@
"""在途调拨类型契约。
用途:定义调拨业务类型(在途仓至HUB仓 / HUB仓维修出 / HUB仓间调拨)及各类型
的收料数据范围规则;类型 2/3 一期占位(fail-closed 拒绝预检,规则先冻结)。
依赖:app.core.errors.ValidationError、invoice_aggregator.AggregatedInvoice。
逻辑:类型决定预检纳入哪些收料票——类型 1 只保留 INVOICE 以 HOM/HOX/WTP 开头
的票(大小写不敏感,范围外票与收料日期范围过滤同语义,静默排除不入明细);
类型 2 规则已定(ODM ID=HoxinRMA)待收料文件解析层支持 odm_id 字段后启用;
类型 3 规则待业务定义。调用方必须先 ensure_transfer_type_supported 再过滤。
"""
from __future__ import annotations
from enum import StrEnum
from typing import Iterable
from app.core.errors import ValidationError
from app.services.in_transit_transfer.invoice_aggregator import AggregatedInvoice
# 类型不支持(占位类型被调用)时的稳定错误码。
TRANSFER_TYPE_NOT_SUPPORTED = "TRANSFER.TRANSFER_TYPE_NOT_SUPPORTED"
class TransferType(StrEnum):
"""调拨业务类型(值与前端/i18n、transfer_runs.transfer_type 列一致)。"""
IN_TRANSIT_TO_HUB = "in_transit_to_hub" # 在途仓至HUB仓
HUB_REPAIR_OUT = "hub_repair_out" # HUB仓维修出(占位)
HUB_TO_HUB = "hub_to_hub" # HUB仓间调拨(占位)
# 一期已实现预检/执行链路的类型;其余类型 fail-closed(占位,防止误生成 外部系统 单)。
SUPPORTED_TRANSFER_TYPES: frozenset[TransferType] = frozenset({TransferType.IN_TRANSIT_TO_HUB})
# 类型 1(在途仓至HUB仓)数据范围:INVOICE 开头前缀(大小写不敏感)。
IN_TRANSIT_TO_HUB_INVOICE_PREFIXES: tuple[str, ...] = ("HOM", "HOX", "WTP")
# 类型 2(HUB仓维修出)数据范围:ODM ID 精确值;待 movement 文件暴露 odm_id 后启用。
HUB_REPAIR_OUT_ODM_ID = "HoxinRMA"
def normalize_transfer_type(value: str | TransferType | None) -> TransferType:
"""规范化调拨类型入参;缺省/空值回落到类型 1(存量调用方语义不变)。
Args:
value: 前端/API 传入的调拨类型值。
Returns:
TransferType 枚举。
Raises:
ValidationError: 非法类型值(不在枚举内)。
"""
raw = str(value.value if isinstance(value, TransferType) else (value or "")).strip()
if not raw:
return TransferType.IN_TRANSIT_TO_HUB
try:
return TransferType(raw)
except ValueError as exc:
raise ValidationError(
f"unknown transfer type: {raw}",
code="TRANSFER.TRANSFER_TYPE_INVALID",
details={"transfer_type": raw},
) from exc
def ensure_transfer_type_supported(transfer_type: TransferType) -> None:
"""占位类型 fail-closed:类型 2/3 处理链路未实现前禁止进入预检。
Args:
transfer_type: 已规范化的调拨类型。
Raises:
ValidationError: 类型未实现(TRANSFER_TYPE_NOT_SUPPORTED)。
"""
if transfer_type not in SUPPORTED_TRANSFER_TYPES:
raise ValidationError(
f"transfer type not supported yet: {transfer_type.value}",
code=TRANSFER_TYPE_NOT_SUPPORTED,
details={"transfer_type": transfer_type.value},
)
def filter_invoices_for_type(
invoices: Iterable[AggregatedInvoice],
transfer_type: TransferType,
) -> list[AggregatedInvoice]:
"""按类型的收料数据范围过滤汇总票(返回保留项,保持原顺序)。
Args:
invoices: 已汇总的收料票。
transfer_type: 已规范化且已确认支持的调拨类型。
Returns:
类型范围内的票列表。
"""
if transfer_type == TransferType.IN_TRANSIT_TO_HUB:
prefixes = tuple(prefix.upper() for prefix in IN_TRANSIT_TO_HUB_INVOICE_PREFIXES)
return [
invoice for invoice in invoices
if str(invoice.invoice_no or "").strip().upper().startswith(prefixes)
]
# 类型 2/3 的过滤规则在启用时补齐(此前 ensure_transfer_type_supported 已拦截)。
return list(invoices)
def transfer_type_scope_note(transfer_type: TransferType) -> str:
"""类型的范围规则说明(写入 TransferPrecheck.scope_json 供审计追溯)。"""
if transfer_type == TransferType.IN_TRANSIT_TO_HUB:
return f"invoice_prefix:{'+'.join(IN_TRANSIT_TO_HUB_INVOICE_PREFIXES).lower()}"
if transfer_type == TransferType.HUB_REPAIR_OUT:
return f"odm_id:{HUB_REPAIR_OUT_ODM_ID}"
return "pending_rule"
-514
View File
@@ -1,514 +0,0 @@
"""
backend/app/services/integration_api.py
用途:解析 Dify dataset/document 对应的源文件下载链接(本地 KB 映射 + Dify 签名 URL 兜底)。
依赖:Flask request/current_app、requests、Kb* 模型。
逻辑:chat.resolve_source_file / 预览代理调用本服务;本地无可读文件时回退 Dify download。
"""
from datetime import datetime, timedelta, timezone
from typing import Any, Dict, List, Optional, Tuple
from urllib.parse import urlparse
import requests
from flask import current_app, has_app_context, has_request_context, request
from app.core.config.settings import Config
class IntegrationApiService:
_cache: Dict[Tuple[str, str], Dict[str, Any]] = {}
@staticmethod
def _request_origin_url() -> str:
if not has_request_context():
return ""
forwarded_proto = (request.headers.get("X-Forwarded-Proto") or "").split(",")[0].strip()
forwarded_host = (request.headers.get("X-Forwarded-Host") or "").split(",")[0].strip()
if forwarded_proto and forwarded_host:
return f"{forwarded_proto}://{forwarded_host}".rstrip("/")
origin = str(request.headers.get("Origin") or "").strip().rstrip("/")
if origin:
return origin
referer = str(request.headers.get("Referer") or "").strip()
if referer:
parsed = urlparse(referer)
if parsed.scheme and parsed.netloc:
return f"{parsed.scheme}://{parsed.netloc}".rstrip("/")
return request.host_url.rstrip("/")
@staticmethod
def _lookup_from_dify_document_api(dataset_id: str, remote_document_id: str) -> Optional[Dict[str, Any]]:
"""
当集成映射服务缺失时,直接调用 Dify 数据集文档下载接口兜底。
适用于“检索已返回 document_id,但 8891 没有同步 source file mapping”的场景。
"""
if not dataset_id or not remote_document_id:
return None
try:
from app.services.knowledge_cleaning.dify_sync_service import KbDifySyncService
except Exception:
return None
try:
service = KbDifySyncService()
if not service.base_url or not service.api_key:
return None
document_payload = service.get_document(
dataset_id=str(dataset_id),
document_id=str(remote_document_id),
)
if not isinstance(document_payload, dict):
return None
download_resp = requests.get(
f"{service.base_url.rstrip('/')}/datasets/{dataset_id}/documents/{remote_document_id}/download",
headers=service._headers(),
timeout=(5, 15),
)
if download_resp.status_code != 200:
if has_app_context():
current_app.logger.info(
"Dify document download lookup missed: dataset_id=%s remote_document_id=%s status=%s",
dataset_id,
remote_document_id,
download_resp.status_code,
)
return None
download_payload = download_resp.json() if download_resp.content else {}
source_url = str((download_payload or {}).get("url") or "").strip()
if not source_url:
return None
upload_info = (
((document_payload.get("data_source_info") or {}).get("upload_file"))
if isinstance(document_payload.get("data_source_info"), dict)
else {}
) or {}
source_filename = str(
upload_info.get("name")
or document_payload.get("name")
or ""
).strip() or None
source_ext = str(
upload_info.get("extension")
or (source_filename.rsplit(".", 1)[-1] if source_filename and "." in source_filename else "")
).strip().lower() or None
# Dify 返回的签名下载地址通常是短效的,这里主动给缓存一个较短 TTL,避免长期复用旧链接。
expires_at = (datetime.now(timezone.utc) + timedelta(minutes=10)).isoformat()
return {
"source_download_url": source_url,
"source_filename": source_filename,
"source_ext": source_ext,
"download_url_expires_at": expires_at,
"version_id": None,
"document_id": remote_document_id,
}
except Exception as e:
if has_app_context():
current_app.logger.warning(
"Dify document API fallback lookup failed: dataset_id=%s remote_document_id=%s err=%s",
dataset_id,
remote_document_id,
e,
)
return None
@staticmethod
def _normalize_batch_row(row: Dict[str, Any]) -> Optional[Tuple[Tuple[str, str], Dict[str, Any]]]:
if not isinstance(row, dict):
return None
req = row.get("request") if isinstance(row.get("request"), dict) else {}
dataset_id = str(req.get("dataset_id") or "").strip()
remote_document_id = str(req.get("remote_document_id") or "").strip()
if not dataset_id or not remote_document_id or not row.get("found"):
return None
doc = row.get("document") if isinstance(row.get("document"), dict) else {}
source_url = doc.get("source_download_url")
if not source_url:
return None
normalized = {
"source_download_url": source_url,
"source_filename": doc.get("source_filename"),
"source_ext": doc.get("source_ext"),
"download_url_expires_at": doc.get("download_url_expires_at"),
"version_id": doc.get("version_id"),
"document_id": doc.get("document_id"),
}
key = IntegrationApiService._cache_key(dataset_id, remote_document_id)
return key, normalized
@staticmethod
def _is_loopback_url(url: str) -> bool:
host = (urlparse(str(url or "").strip()).hostname or "").strip().lower()
return host in {"127.0.0.1", "localhost", "::1"}
@staticmethod
def get_api_key() -> str:
if has_app_context():
return str(current_app.config.get("INTEGRATION_API_KEY") or "").strip()
return str(Config.INTEGRATION_API_KEY or "").strip()
@staticmethod
def get_base_url() -> str:
mode = "local"
if has_app_context():
mode = str(current_app.config.get("INTEGRATION_API_MODE") or "local").strip().lower()
configured = str(current_app.config.get("INTEGRATION_API_BASE") or "").strip().rstrip("/")
public_base = str(current_app.config.get("WECOM_PUBLIC_BASE_URL") or "").strip().rstrip("/")
else:
mode = str(getattr(Config, "INTEGRATION_API_MODE", "local") or "local").strip().lower()
configured = str(Config.INTEGRATION_API_BASE or "").strip().rstrip("/")
public_base = ""
# For server-side lookups, always prefer the explicitly configured
# integration service endpoint when present. Falling back to the current
# request host would incorrectly call this backend itself.
if configured:
return configured
if mode != "external":
request_origin = IntegrationApiService._request_origin_url()
if request_origin:
return request_origin
if public_base:
return public_base
if has_request_context():
return request.host_url.rstrip("/")
return configured
@staticmethod
def _cache_key(dataset_id: str, remote_document_id: str) -> Tuple[str, str]:
return (str(dataset_id), str(remote_document_id))
@staticmethod
def _is_cache_valid(payload: Dict[str, Any]) -> bool:
exp_str = payload.get("download_url_expires_at")
if exp_str:
try:
return datetime.fromisoformat(exp_str) > datetime.now().astimezone()
except Exception:
pass
# 如果没有明确的过期时间,尝试解析 url 里的 JWT token 检查
source_url = payload.get("source_download_url") or ""
if "token=" in source_url:
try:
import base64
import json
from urllib.parse import urlparse, parse_qs
import time
qs = parse_qs(urlparse(source_url).query)
if 'token' in qs:
token = qs['token'][0]
parts = token.split('.')
if len(parts) >= 2:
payload_b64 = parts[1]
payload_b64 += '=' * (-len(payload_b64) % 4)
payload_data = json.loads(base64.urlsafe_b64decode(payload_b64).decode('utf-8'))
exp = payload_data.get('exp', 0)
if exp and exp < time.time() + 300:
return False # 已过期或即将过期
except Exception:
pass
return True
@staticmethod
def _lookup_local_db(dataset_id: str, remote_document_id: str) -> Optional[Dict[str, Any]]:
"""
从本地 KbDifySyncRecord 反查可预览下载链接。
核心逻辑:优先返回磁盘上存在的源文件;缺失时回退清洗 Markdown;
两者皆无则返回 None,让上层继续走 Dify 签名下载兜底。
"""
if not has_app_context():
return None
from pathlib import Path
from app import db
from app.models import KbDifySyncRecord, KbDocumentVersion, KbDocument
normalized_dataset_id = str(dataset_id or '').strip()
normalized_remote_document_id = str(remote_document_id or '').strip()
if not normalized_dataset_id or not normalized_remote_document_id:
return None
record = (
db.session.query(KbDifySyncRecord)
.join(KbDocumentVersion, KbDocumentVersion.id == KbDifySyncRecord.document_version_id)
.join(KbDocument, KbDocument.id == KbDocumentVersion.document_id)
.filter(
KbDocument.is_deleted.is_(False),
KbDifySyncRecord.dataset_id == normalized_dataset_id,
KbDifySyncRecord.remote_document_id == normalized_remote_document_id,
)
.order_by(KbDifySyncRecord.updated_at.desc(), KbDifySyncRecord.id.desc())
.first()
)
if not record or not record.document_version or not record.document_version.document:
return None
version = record.document_version
document = version.document
def _existing(path_value: str | None):
if not path_value:
return None
raw = Path(str(path_value))
root = Path(current_app.config.get('KB_STORAGE_ROOT')).resolve()
candidate = (raw if raw.is_absolute() else (root / raw)).resolve()
try:
candidate.relative_to(root)
except ValueError:
return None
if candidate.exists() and candidate.is_file():
return candidate
return None
source_path = _existing(version.source_file_path)
markdown_path = _existing(version.cleaned_file_path) or _existing(version.cleaned_preview_path)
if source_path is None and markdown_path is None:
current_app.logger.info(
'[integration-lookup] local mapping found but no readable file document_id=%s version_id=%s',
document.id,
version.id,
)
return None
base_url = IntegrationApiService._request_origin_url()
if not base_url:
explicit = str(current_app.config.get('WECOM_PUBLIC_BASE_URL') or '').strip().rstrip('/')
if explicit:
base_url = explicit
elif has_request_context():
base_url = request.host_url.rstrip('/')
else:
base_url = ''
import time
import jwt
secret = str(current_app.config.get('INTEGRATION_API_KEY') or '').strip()
if not secret:
secret = str(current_app.config.get('SECRET_KEY') or 'default-secret').strip()
exp = int(time.time()) + 86400 * 7 # 7 days expiration for local tokens
payload = {
'dataset_id': normalized_dataset_id,
'remote_document_id': normalized_remote_document_id,
'version_id': version.id,
'exp': exp
}
token = jwt.encode(payload, secret, algorithm='HS256')
if source_path is not None:
kind = 'source'
source_filename = version.source_file_name
source_ext = version.source_file_ext
else:
kind = 'md'
stem = Path(str(version.source_file_name or document.title or f'document-{document.id}')).stem
source_filename = f'{stem}.md'
source_ext = 'md'
source_download_url = (
f'{base_url}/api/integration/files/{document.id}/download'
f'?kind={kind}&version_id={version.id}&token={token}'
)
return {
"source_download_url": source_download_url,
"source_filename": source_filename,
"source_ext": source_ext,
"download_url_expires_at": None,
"version_id": version.id,
"document_id": document.id,
}
@staticmethod
def lookup_file_by_dify(dataset_id: str, remote_document_id: str) -> Optional[Dict[str, Any]]:
if not dataset_id or not remote_document_id:
return None
cache_key = IntegrationApiService._cache_key(dataset_id, remote_document_id)
cached = IntegrationApiService._cache.get(cache_key)
if cached and IntegrationApiService._is_cache_valid(cached):
return cached
base_url = IntegrationApiService.get_base_url()
api_key = IntegrationApiService.get_api_key()
if not base_url or not api_key:
return IntegrationApiService._lookup_local_db(dataset_id, remote_document_id)
url = f"{base_url}/api/integration/dify-file"
headers = {"X-Integration-Key": api_key}
params = {
"dataset_id": str(dataset_id),
"remote_document_id": str(remote_document_id),
}
try:
resp = requests.get(url, headers=headers, params=params, timeout=(4, 8))
if resp.status_code == 200:
payload = resp.json()
if isinstance(payload, dict):
IntegrationApiService._cache[cache_key] = payload
return payload
elif has_app_context():
current_app.logger.info(
"Integration API single lookup missed, falling back to batch resolve: dataset_id=%s remote_document_id=%s status=%s",
dataset_id,
remote_document_id,
resp.status_code,
)
except Exception as e:
if has_app_context():
current_app.logger.warning(f"Integration API lookup failed: {e}")
batch_url = f"{base_url}/api/integration/dify-files/resolve"
batch_headers = {
"X-Integration-Key": api_key,
"Content-Type": "application/json",
}
batch_body = {
"items": [
{
"dataset_id": str(dataset_id),
"remote_document_id": str(remote_document_id),
}
]
}
try:
resp = requests.post(batch_url, headers=batch_headers, json=batch_body, timeout=(5, 12))
if resp.status_code == 200:
payload = resp.json()
data = payload.get("data") if isinstance(payload, dict) else None
if isinstance(data, list):
for row in data:
normalized_row = IntegrationApiService._normalize_batch_row(row)
if not normalized_row:
continue
key, normalized = normalized_row
IntegrationApiService._cache[key] = normalized
if key == cache_key:
return normalized
except Exception as e:
if has_app_context():
current_app.logger.warning(f"Integration API batch fallback lookup failed: {e}")
# Fallback to local database if remote integration API fails or misses
local_result = IntegrationApiService._lookup_local_db(dataset_id, remote_document_id)
if local_result:
IntegrationApiService._cache[cache_key] = local_result
return local_result
# Last fallback: query Dify document API directly and request a signed download URL.
dify_result = IntegrationApiService._lookup_from_dify_document_api(dataset_id, remote_document_id)
if dify_result:
IntegrationApiService._cache[cache_key] = dify_result
return dify_result
return None
@staticmethod
def lookup_files_by_dify(items: List[Dict[str, str]]) -> Dict[Tuple[str, str], Dict[str, Any]]:
"""
Batch resolve source files by (dataset_id, remote_document_id).
Returns a mapping keyed by (dataset_id, remote_document_id).
"""
results: Dict[Tuple[str, str], Dict[str, Any]] = {}
if not items:
return results
unresolved: List[Dict[str, str]] = []
seen = set()
for item in items:
dataset_id = str(item.get("dataset_id") or "").strip()
remote_document_id = str(item.get("remote_document_id") or "").strip()
if not dataset_id or not remote_document_id:
continue
key = IntegrationApiService._cache_key(dataset_id, remote_document_id)
if key in seen:
continue
seen.add(key)
cached = IntegrationApiService._cache.get(key)
if cached and IntegrationApiService._is_cache_valid(cached):
results[key] = cached
else:
unresolved.append({
"dataset_id": dataset_id,
"remote_document_id": remote_document_id,
})
if not unresolved:
return results
base_url = IntegrationApiService.get_base_url()
api_key = IntegrationApiService.get_api_key()
if not base_url or not api_key:
return results
url = f"{base_url}/api/integration/dify-files/resolve"
headers = {
"X-Integration-Key": api_key,
"Content-Type": "application/json",
}
body = {"items": unresolved}
try:
resp = requests.post(url, headers=headers, json=body, timeout=(5, 12))
if resp.status_code != 200:
if has_app_context():
current_app.logger.warning(
"Integration API batch lookup failed: status=%s", resp.status_code
)
else:
payload = resp.json()
data = payload.get("data") if isinstance(payload, dict) else None
if isinstance(data, list):
for row in data:
if not isinstance(row, dict):
continue
normalized_row = IntegrationApiService._normalize_batch_row(row)
if not normalized_row:
continue
key, normalized = normalized_row
IntegrationApiService._cache[key] = normalized
results[key] = normalized
except Exception as e:
if has_app_context():
current_app.logger.warning(f"Integration API batch lookup exception: {e}")
# Fallback to single lookup or local DB for unresolved items
for item in unresolved:
dataset_id = item["dataset_id"]
remote_document_id = item["remote_document_id"]
key = IntegrationApiService._cache_key(dataset_id, remote_document_id)
if key in results:
continue
# Check if single lookup was not called already (if it was, it might be cached)
# Actually, `_lookup_local_db` should be checked directly since remote batch failed to find it.
local_result = IntegrationApiService._lookup_local_db(dataset_id, remote_document_id)
if local_result:
IntegrationApiService._cache[key] = local_result
results[key] = local_result
continue
# As a last resort, try remote single lookup if batch missed it
payload = IntegrationApiService.lookup_file_by_dify(dataset_id, remote_document_id)
if payload:
results[key] = payload
return results
@@ -4,16 +4,21 @@
(客户端 + 接口 + 映射版本),并冻结调用期配置快照。
依赖:IntegrationBinding/IntegrationClientInstance/IntegrationInterfaceDefinition、errors.py。
逻辑:只命中 published + environment 匹配 + 生效区间 + context_selector 是 context 子集;
且接口定义须为 published、客户端实例须 enabled(管理端「发布/退役」「启停」的总开关);
同 context 下 priority 高者优先;无命中抛 BindingNotFoundError(fail-closed)。
"""
from __future__ import annotations
import logging
from dataclasses import dataclass
from datetime import datetime, timezone
from app.models import IntegrationBinding, IntegrationClientInstance, IntegrationInterfaceDefinition
from app.services.integration_connector.errors import BindingNotFoundError
from app.services.integration_connector.transports.base import merge_client_config
logger = logging.getLogger(__name__)
@dataclass(frozen=True)
@@ -32,6 +37,9 @@ class BindingSnapshot:
request_spec: dict
response_mapping: dict
output_schema: dict
# 域参数→接口参数映射(空 = 同名直通)与接口入参 Schema(映射结果校验)。
param_mapping: dict
input_schema: dict
def _to_naive(dt: datetime | None) -> datetime | None:
@@ -68,7 +76,8 @@ def resolve_binding(capability: str, context: dict, environment: str, *, now: da
Returns:
BindingSnapshot。
Raises:
BindingNotFoundError: 无可用绑定(fail-closed)。
BindingNotFoundError: 无可用绑定(fail-closed);接口未发布或客户端已停用同样按
无可用绑定处理(与列表「发布/退役」「启停」按钮语义闭环,且不向调用方泄露配置细节)。
"""
base_now = now or datetime.utcnow()
rows = IntegrationBinding.query.filter_by(capability=capability, environment=environment, status='published').all()
@@ -81,6 +90,12 @@ def resolve_binding(capability: str, context: dict, environment: str, *, now: da
continue
candidates.append((row, selector))
if not candidates:
# fail-closed 必须可排障:区分「一条 published 都没有」与「有但路由选择器/生效窗口不命中」,
# 否则调用方只看到 no binding for capability(2026-09 排障实测痛点)。
logger.warning(
"connector binding miss: capability=%s env=%s published_rows=%s context_keys=%s",
capability, environment, len(rows), sorted((context or {}).keys()),
)
raise BindingNotFoundError(capability=capability)
candidates.sort(key=lambda item: (item[0].priority, len(item[1])), reverse=True)
row, selector = candidates[0]
@@ -88,15 +103,28 @@ def resolve_binding(capability: str, context: dict, environment: str, *, now: da
client = IntegrationClientInstance.query.filter_by(code=row.client_instance_code).first()
iface = IntegrationInterfaceDefinition.query.filter_by(code=row.interface_definition_code).first()
if client is None or iface is None:
logger.warning(
"connector binding target missing: capability=%s binding_id=%s client=%s iface=%s",
capability, row.id, row.client_instance_code, row.interface_definition_code,
)
raise BindingNotFoundError(capability=capability)
# fail-closed 门禁:接口未发布(draft/retired)或客户端已停用视同无可用绑定——
# 管理端「发布/退役」「启停」按钮因此具备真实的调用期语义;错误类型与无命中一致。
if iface.status != 'published' or not client.enabled:
logger.warning(
"connector binding gated: capability=%s binding_id=%s iface_status=%s client_enabled=%s",
capability, row.id, iface.status, client.enabled,
)
raise BindingNotFoundError(capability=capability)
# 兼容层:把独立列拼回 dict,供 engine/mapping/transport 无感消费。
# 兼容层:把独立列拼回 dict,供 engine/mapping/transport 无感消费
# (与 transports.base.merge_client_config 同一实现)。
# 优先列值,缺失回退 JSON(config_json / request_spec_json / context_selector_json)。
config = dict(client.config_json or {})
if client.endpoint is not None:
config['endpoint'] = client.endpoint
if client.timeout_seconds is not None:
config['timeout_seconds'] = client.timeout_seconds
config = merge_client_config({
'config_json': client.config_json,
'endpoint': client.endpoint,
'timeout_seconds': client.timeout_seconds,
})
request_spec = dict(iface.request_spec_json or {})
if iface.http_method is not None:
@@ -105,8 +133,6 @@ def resolve_binding(capability: str, context: dict, environment: str, *, now: da
request_spec['path'] = iface.request_path
selector = dict(row.context_selector_json or {})
if row.context_source_code is not None and 'source_code' not in selector:
selector['source_code'] = row.context_source_code
return BindingSnapshot(
capability=row.capability,
@@ -121,4 +147,6 @@ def resolve_binding(capability: str, context: dict, environment: str, *, now: da
request_spec=request_spec,
response_mapping=iface.response_mapping_json or {},
output_schema=iface.output_schema_json or {},
param_mapping=row.param_mapping_json or {},
input_schema=iface.input_schema_json or {},
)
@@ -2,7 +2,9 @@
用途:Capability 强类型契约注册表(能力名称/输入输出 Schema/幂等语义/是否写)。
依赖:app.core.errors、errors.py;纯代码,不依赖 DB。
逻辑:能力必须由代码注册,不能由管理端动态定义;领域只调用已注册能力,未注册 fail-closed。
逻辑:能力必须由代码注册,不能由管理端动态定义;各域契约声明在各域包的
capabilities 模块(如 in_transit_transfer/capabilities.py),由应用组合根
import 完成注册;领域只调用已注册能力,未注册 fail-closed。
"""
from __future__ import annotations
@@ -12,37 +14,6 @@ from dataclasses import dataclass
from app.core.errors import ValidationError
from app.services.integration_connector.errors import CapabilityNotFoundError
# 在途调拨能力输入/输出 Schema(JSON Schema 最小子集,供入参/出参校验)。
_QUERY_INPUT_SCHEMA: dict = {
"type": "object",
"required": ["invoice_no", "from_warehouse", "to_warehouse", "quantity"],
"properties": {
"invoice_no": {"type": "string"},
"from_warehouse": {"type": "string"},
"to_warehouse": {"type": "string"},
"quantity": {"type": "number"},
},
}
_QUERY_OUTPUT_SCHEMA: dict = {
"type": "object",
"properties": {
"found": {"type": "boolean"},
"quantity": {"type": ["number", "null"]},
},
}
_WRITE_OUTPUT_SCHEMA: dict = {
"type": "object",
"required": ["status"],
"properties": {
"status": {
"type": "string",
"enum": ["success", "business_failed", "technical_failed", "timeout", "result_unknown"],
},
"document_no": {"type": ["string", "null"]},
"verified_posted": {"type": ["boolean", "null"]},
},
}
@dataclass(frozen=True)
class CapabilitySpec:
@@ -56,7 +27,6 @@ class CapabilitySpec:
_CAPABILITIES: dict[str, CapabilitySpec] = {}
_LOADED = False
def register_capability(spec: CapabilitySpec) -> CapabilitySpec:
@@ -84,42 +54,6 @@ def list_capabilities() -> list[CapabilitySpec]:
return sorted(_CAPABILITIES.values(), key=lambda s: s.name)
def ensure_capabilities_loaded() -> None:
"""惰性注册内置能力(幂等);由网关/API 在解析前调用。"""
global _LOADED # noqa: PLW0603
if _LOADED:
return
_LOADED = True
_register_transfer_capabilities()
def _register_transfer_capabilities() -> None:
"""注册在途调拨域内置能力;领域代码只调这些能力,外部系统差异全在连接器层。"""
register_capability(CapabilitySpec(
name="in_transit_transfer.query_inventory",
input_schema=_QUERY_INPUT_SCHEMA,
output_schema=_QUERY_OUTPUT_SCHEMA,
idempotency="none",
write=False,
))
register_capability(CapabilitySpec(
name="in_transit_transfer.create_transfer",
input_schema=_QUERY_INPUT_SCHEMA,
output_schema=_WRITE_OUTPUT_SCHEMA,
idempotency="invoice",
write=True,
))
register_capability(CapabilitySpec(
name="in_transit_transfer.verify_duplicate",
input_schema=_QUERY_INPUT_SCHEMA,
output_schema=_WRITE_OUTPUT_SCHEMA,
idempotency="invoice",
write=False,
))
def reset_capability_registry_for_tests() -> None:
"""单测隔离:清空注册表并重置加载标记。"""
global _LOADED # noqa: PLW0603
"""单测隔离:清空注册表(领域 capabilities 模块可重调其注册函数重建)。"""
_CAPABILITIES.clear()
_LOADED = False
@@ -0,0 +1,79 @@
"""services/integration_connector/credential_types.py
用途:凭据形态注册表——每种凭据类型定义自己的字段清单(键名/是否密文/是否必填),
是 UI 动态渲染与 API 组装/校验的唯一事实来源。
依赖:app.core.errors;纯代码注册表,无 DB/IO。
逻辑:类型由代码注册(与能力注册同哲学),管理端不可动态定义;字段键名即模板
占位符 credential_<key> 的 <key>;新增形态 = 加一个注册条目 + 前端标签,零迁移。
"""
from __future__ import annotations
from typing import Any
from app.core.errors import ValidationError
# 凭据形态注册表:key 为稳定类型编码(credential_type 列值),fields 为字段清单。
# secret=True 的字段加密落库且永不回显;required 在「合并旧值后」仍缺失即拒绝。
CREDENTIAL_TYPE_SPECS: dict[str, dict[str, Any]] = {
"password": {
"fields": [
{"key": "username", "secret": False, "required": True},
{"key": "password", "secret": True, "required": True},
],
},
"token": {
"fields": [
{"key": "token", "secret": True, "required": True},
],
},
"api_key": {
"fields": [
{"key": "api_key", "secret": True, "required": True},
],
},
}
def get_credential_type(credential_type: str) -> dict[str, Any] | None:
"""按类型编码查字段定义;未知类型返回 None(调用方 fail-closed)。"""
return CREDENTIAL_TYPE_SPECS.get(str(credential_type or "").strip())
def list_credential_types() -> list[dict[str, Any]]:
"""返回全部已注册类型及其字段定义(供 GET /credential-references/types)。"""
return [
{"type": type_code, "fields": [dict(field) for field in spec["fields"]]}
for type_code, spec in sorted(CREDENTIAL_TYPE_SPECS.items())
]
def build_secret_dict(credential_type: str, values: dict) -> dict[str, str]:
"""按类型定义从「合并旧值后的提交值」组装凭据字典。
只保留类型定义内的键(未知键丢弃);必填字段缺失抛 ValidationError(fail-closed)。
"""
spec = get_credential_type(credential_type)
if spec is None:
raise ValidationError("unknown credential_type", details={"credential_type": credential_type})
result: dict[str, str] = {}
for field in spec["fields"]:
value = values.get(field["key"])
if value is not None and str(value) != "":
result[field["key"]] = str(value)
missing = [field["key"] for field in spec["fields"] if field["required"] and not result.get(field["key"])]
if missing:
raise ValidationError("required credential fields missing", details={"fields": missing})
return result
def visible_fields(credential_type: str, secret_dict: dict) -> dict[str, str]:
"""按类型定义回显非密字段(secret=True 的字段永不回显)。"""
spec = get_credential_type(credential_type)
if spec is None:
return {}
return {
field["key"]: str(secret_dict[field["key"]])
for field in spec["fields"]
if not field["secret"] and secret_dict.get(field["key"])
}
@@ -1,26 +1,36 @@
"""services/integration_connector/engine.py
用途:CapabilityGateway 调用引擎——统一执行 resolve→validate→build→call→map→classify→audit。
用途:CapabilityGateway 调用引擎——统一执行 resolve→validate→map-params→call→classify→audit。
依赖:capability/binding/mapping/security/transports、IntegrationCall 模型、errors.py。
逻辑:读能力映射校验通过即 success;写能力按原始 status 分类;超时→timeout;
逻辑:域入参先经能力 Schema 校验,再按绑定 param_mapping 翻译为接口参数(对照接口
入参 Schema 校验);凭据按引用解析后以 credential_* 注入传输层;读能力返回
带 status 的失败 dict 时原样分类,其余映射校验通过即 success;
入参非法/无绑定/映射失败/契约未冻结均 fail-closed;result_unknown 不自动重试。
"""
from __future__ import annotations
import logging
import time
import uuid
from dataclasses import replace
from app import db
from app.services.integration_connector.binding import BindingSnapshot, resolve_binding
from app.services.integration_connector.capability import CapabilitySpec, ensure_capabilities_loaded, get_capability
from app.services.integration_connector.capability import CapabilitySpec, get_capability
from app.services.integration_connector.errors import CallFailedError, InputInvalidError
from app.services.integration_connector.mapping import map_response, schema_errors
from app.services.integration_connector.security import sanitize
from app.services.integration_connector.transports.base import IntegrationCallResult, Transport, classify_transport_response
from app.services.integration_connector.security import resolve_credential, sanitize
from app.services.integration_connector.transports.base import (
RESULT_FAILURE_STATUSES,
IntegrationCallResult,
Transport,
classify_transport_response,
)
from app.models import IntegrationCall
logger = logging.getLogger(__name__)
def build_request(request_spec: dict, config: dict, params: dict) -> dict:
"""按接口请求规格构造请求:填充 path 占位符,组装 params/body/headers。"""
@@ -85,34 +95,51 @@ class CapabilityGateway:
environment: str | None = None,
transports: dict[str, Transport] | None = None,
) -> IntegrationCallResult:
ensure_capabilities_loaded()
spec = get_capability(capability)
input_errors = schema_errors(params, spec.input_schema)
if input_errors:
# InputInvalidError 只带 message 不带明细,降级进 result_message 后只剩
# "input invalid";不落日志则字段级原因(required missing/类型不符)永久丢失。
logger.warning(
"connector input invalid: capability=%s errors=%s",
capability, input_errors,
)
raise InputInvalidError(details={'errors': input_errors})
env = environment or _environment()
snapshot = resolve_binding(capability, context, env)
# 域参数 → 接口参数翻译:绑定配置了 param_mapping 时按映射引擎执行,
# 结果对照接口入参 Schema 校验;未配置时同名直通(能力入参原样下传)。
params = map_response(snapshot.param_mapping, params, snapshot.input_schema) \
if snapshot.param_mapping else params
transport = (transports or self.transports).get(snapshot.connector_type)
if transport is None:
raise CallFailedError(details={'reason': f'no transport for connector_type={snapshot.connector_type}'})
# 凭据按引用解析(db 密文解密 / env 配置键读取),缺失即 fail-closed。
credential = resolve_credential(snapshot.credential_ref_code) if snapshot.credential_ref_code else {}
request = build_request(snapshot.request_spec, snapshot.config, params)
trace_id = f'ic-{uuid.uuid4().hex}'
start_ms = int(time.time() * 1000)
try:
raw = transport.call(
client={'config_json': snapshot.config, 'credential': {}},
client={'config_json': snapshot.config, 'credential': credential},
interface={'request_spec_json': snapshot.request_spec},
request=request,
)
except TimeoutError:
result = IntegrationCallResult(status='timeout', error_code='ERP_TIMEOUT_UNKNOWN', trace_id=trace_id)
result = IntegrationCallResult(status='timeout', error_code='EXTERNAL_TIMEOUT_UNKNOWN', trace_id=trace_id)
_record_call(operation_id, capability, snapshot, params, None, result, start_ms, trace_id)
return result
result = classify_transport_response(raw) if spec.write else IntegrationCallResult(status='success')
if not spec.write or result.status in ('success', 'duplicate_success', 'duplicate_unverified'):
if spec.write:
result = classify_transport_response(raw)
elif isinstance(raw, dict) and raw.get('status') in RESULT_FAILURE_STATUSES:
# 传输层已判失败(HTTP 4xx/5xx、SOAP Fault、非 XML)→ 原样分类,不做输出映射。
result = classify_transport_response(raw)
else:
result = IntegrationCallResult(status='success')
if result.status in ('success', 'duplicate_success', 'duplicate_unverified'):
data = map_response(snapshot.response_mapping, raw, snapshot.output_schema or spec.output_schema)
result = replace(result, data=data)
result = replace(result, trace_id=trace_id)
@@ -2,12 +2,14 @@
用途:声明式映射引擎——把外部原始响应映射为统一结果(提取路径 + 白名单转换 + 输出 Schema 校验)。
依赖:decimal、errors.py;纯函数,无 IO/网络/DB。
逻辑:只允许点路径/数组下标提取与白名单转换函数,禁止任意 Python/JS/SQL;
缺字段且不可满足→MappingInvalidError;输出不合 Schema→MappingInvalidError(fail-closed)。
逻辑:只允许点路径/数组下标提取与白名单转换函数(含 pick 键值取值、template 参数模板、
each 列表逐元素子映射),禁止任意 Python/JS/SQL;缺字段且不可满足→MappingInvalidError;
输出不合 Schema→MappingInvalidError(fail-closed)。
"""
from __future__ import annotations
import string
from decimal import Decimal
from typing import Any
@@ -50,25 +52,37 @@ def _tokenize(path: str) -> list[str]:
def extract_path(obj: Any, path: str) -> Any:
"""按点路径/数组下标提取;缺任一节点返回 MISSING;路径超长/超深抛 MappingInvalidError。"""
"""按点路径/数组下标提取;缺任一节点返回 MISSING;路径超长/超深抛 MappingInvalidError。
路径途经重复节点列表(名称段撞上列表)时逐元素收集剩余路径的命中:
全部未命中视为 MISSING,部分命中收集为列表——同一配置在单/多记录
(如多条件查询返回多个 RecordSet)之间不再随机失效。
"""
path = str(path or "")
if len(path) > MAX_PATH_LENGTH:
raise MappingInvalidError(details={"reason": "path_too_long"})
tokens = _tokenize(path)
if len(tokens) > MAX_DEPTH:
raise MappingInvalidError(details={"reason": "path_too_deep"})
cur = obj
for tok in tokens:
if isinstance(cur, list) and tok.isdigit():
idx = int(tok)
if idx >= len(cur):
return MISSING
cur = cur[idx]
elif isinstance(cur, dict) and tok in cur:
cur = cur[tok]
else:
return _walk(obj, tokens)
def _walk(cur: Any, tokens: list[str]) -> Any:
"""按 token 序列递归取值;列表遇名称段做扇出收集(重复节点归一化的路径侧配套)。"""
if not tokens:
return cur
tok, rest = tokens[0], tokens[1:]
if isinstance(cur, list) and tok.isdigit():
idx = int(tok)
if idx >= len(cur):
return MISSING
return cur
return _walk(cur[idx], rest)
if isinstance(cur, dict) and tok in cur:
return _walk(cur[tok], rest)
if isinstance(cur, list):
collected = [hit for item in cur if (hit := _walk(item, tokens)) is not MISSING]
return collected if collected else MISSING
return MISSING
# ---- 白名单转换函数(纯函数,无 IO/网络/eval) ----
@@ -119,6 +133,81 @@ def _if_else(value: Any, condition: str, then: Any, else_: Any) -> Any:
return then if condition == "truthy" and bool(value) else else_
def _pick(value: Any, key_field: str | None = None, key_value: Any = None,
value_field: str | None = None, exists: bool = False, cast: str | None = None) -> Any:
"""从「键值对记录列表」按 key_field==key_value 取值(行转列通用需求)。
Args:
value: 目标列表(每项为 dict,如 XML 归一化后的 Field 列表)。
key_field / key_value: 匹配键字段名与期望值(按字符串比较)。
value_field: 命中后取的字段名;缺省返回整条记录。
exists: True 时返回布尔(是否命中),不取值。
cast: 可选 "decimal" 或 _cast 支持的标量类型。
"""
if value is MISSING:
return MISSING
if key_field is None or key_value is None:
raise MappingInvalidError(details={"reason": "pick_requires_key_field_and_key_value"})
if not isinstance(value, list):
raise MappingInvalidError(details={"reason": "pick_target_not_list"})
for item in value:
if isinstance(item, dict) and str(item.get(key_field)) == str(key_value):
if exists:
return True
found = item.get(value_field) if value_field is not None else item
if cast == "decimal":
return _decimal(found)
return _cast(found, cast) if cast else found
if exists:
return False
return MISSING
def _each(value: Any, fields: dict | None = None) -> Any:
"""对列表逐元素套用子映射,产出 dict 列表(多条外部记录→多行结果的通用需求)。
Args:
value: 目标列表(每项为 dict,如归一化后的 Master 记录列表)。
fields: 子映射 {输出字段: {expr/transform/args}},语义与 map_response 顶层一致:
元素内缺字段按 MISSING 处理(跳过该键),转换函数复用 TRANSFORMS 白名单。
"""
if value is MISSING:
# 目标记录集整体缺失(外部系统对"查无记录"返回空 XML)→ 归一为空列表:
# 空结果是合法答案(如库存查无此批号),交领域层归类为"未找到",
# 不得因输出 Schema 校验 fail-closed 成映射错误。
return []
# XML 重复节点归一化后单条记录是 dict、多条是 list:单记录归一为单元素列表,
# 否则同一配置在单/多记录间会随机 fail-closed。
if isinstance(value, dict):
value = [value]
if not isinstance(value, list):
raise MappingInvalidError(details={"reason": "each_target_not_list"})
out: list[Any] = []
for item in value:
row: dict[str, Any] = {}
for field, spec in (fields or {}).items():
if not isinstance(spec, dict):
raise MappingInvalidError(details={"field": field, "reason": "invalid_mapping_spec"})
if "default" in spec:
v: Any = spec["default"]
else:
expr = spec.get("expr")
v = extract_path(item, expr) if expr is not None else MISSING
transform = spec.get("transform")
if transform:
fn = TRANSFORMS.get(transform)
if fn is None:
raise MappingInvalidError(details={"field": field, "reason": f"unknown_transform:{transform}"})
v = fn(v, **(spec.get("args") or {}))
if v is not MISSING:
row[field] = v
if row:
# 全字段缺失的空行(如 Master 节点存在但无 Record 子节点)跳过,
# 避免产出违反行 Schema 的 {} 行;部分缺失仍保留,由行 Schema fail-closed。
out.append(row)
return out
TRANSFORMS: dict[str, Any] = {
"default": _default,
"fallback": _fallback,
@@ -127,9 +216,64 @@ TRANSFORMS: dict[str, Any] = {
"enum-map": _enum_map,
"list-map": _list_map,
"if-else": _if_else,
"pick": _pick,
"each": _each,
}
# ---- 参数模板填充(spec 级 "template",对整个参数表渲染,多用于域参数→接口参数翻译)----
def _render_template_value(value: Any, args: dict) -> str:
"""渲染单个占位符值:列表按 list_item_template 逐项渲染后用 separator 连接。
列表项为 dict 时,item_template 的占位符对 item 的键校验(缺失即
template_item_field_missing,fail-closed)并按字段转义渲染,
如 list_item_template = "(img01 = '{material_no}' AND img04 = '{lot_no}')"。
"""
item_template = str(args.get("list_item_template") or "{item}")
separator = str(args.get("separator") if args.get("separator") is not None else ",")
escape = args.get("escape")
def _escape(text: Any) -> str:
text = str(text)
if escape == "quote":
text = text.replace("'", "''")
return text
if isinstance(value, (list, tuple)):
rendered: list[str] = []
for item in value:
if isinstance(item, dict):
placeholders = {f for _, f, _, _ in string.Formatter().parse(item_template) if f}
missing = sorted(p for p in placeholders if p not in item)
if missing:
raise MappingInvalidError(details={"reason": "template_item_field_missing", "field": missing[0]})
rendered.append(item_template.format(**{k: _escape(v) for k, v in item.items()}))
else:
rendered.append(item_template.format(item=_escape(item)))
return separator.join(rendered)
return _escape(value)
def fill_param_template(template: str, params: dict, args: dict | None = None) -> str:
"""按 {param} 占位符对参数表渲染模板(str.format 语义,{{}} 转义字面大括号)。
缺占位符即抛 MappingInvalidError(fail-closed),绝不静默输出空串。
"""
template = str(template or "")
args = args or {}
placeholders = {fname for _, fname, _, _ in string.Formatter().parse(template) if fname}
rendered: dict[str, str] = {}
for name in placeholders:
if name not in (params or {}):
raise MappingInvalidError(details={"reason": "template_param_missing", "param": name})
rendered[name] = _render_template_value(params[name], args)
try:
return template.format(**rendered)
except (KeyError, IndexError, ValueError) as exc:
raise MappingInvalidError(details={"reason": "template_invalid"}) from exc
# ---- 最小 JSON Schema 子集校验(type/required/properties/enum/items)----
def _matches_type(value: Any, type_spec: Any) -> bool:
@@ -190,7 +334,10 @@ def map_response(mapping: dict, raw: dict, output_schema: dict) -> dict:
for field, spec in mapping.items():
if not isinstance(spec, dict):
raise MappingInvalidError(details={"field": field, "reason": "invalid_mapping_spec"})
if "default" in spec:
if "template" in spec:
# 参数模板:对整个 raw(参数表)渲染,与单字段 expr 提取互补。
value = fill_param_template(spec["template"], raw, spec.get("args") or {})
elif "default" in spec:
value = spec["default"]
else:
expr = spec.get("expr")
@@ -1,18 +1,32 @@
"""services/integration_connector/security.py
用途:凭据引用解析(fail-closed)与敏感字段脱敏。
依赖:IntegrationCredentialReference 模型、current_app.config、errors.py。
逻辑:凭据只存 secret_ref 引用;解析时读当前环境配置,缺失即抛 CredentialUnresolvedError;
sanitize 递归脱敏敏感键;credential_summary 只回元数据,绝不回显明文。
依赖:IntegrationCredentialReference 模型、core.credential_crypto、current_app.config、errors.py。
逻辑:db 模式解密 secret_ciphertext(主密钥 INTEGRATION_CREDENTIAL_KEY 环境注入);
env 模式按 secret_ref 读当前环境配置,缺失即抛 CredentialUnresolvedError;
sanitize 递归脱敏敏感键;credential_summary 只回元数据,绝不回显明文/密文。
"""
from __future__ import annotations
import json
from typing import Any
from app.core.credential_crypto import CredentialCryptoErrorCodes, decrypt_secret
from app.core.errors import AppError
from app.models import IntegrationCredentialReference
from app.services.integration_connector.errors import CredentialUnresolvedError
# 连接器凭据密文的 Fernet 主密钥配置键与错误码。
CREDENTIAL_KEY_CONFIG_NAME = 'INTEGRATION_CREDENTIAL_KEY'
_DB_SECRET_CODES = CredentialCryptoErrorCodes(
key_missing='INTEGRATION.CREDENTIAL_KEY_MISSING',
key_invalid='INTEGRATION.CREDENTIAL_KEY_INVALID',
secret_empty='INTEGRATION.CREDENTIAL_SECRET_EMPTY',
secret_missing='INTEGRATION.CREDENTIAL_SECRET_MISSING',
secret_invalid='INTEGRATION.CREDENTIAL_SECRET_INVALID',
)
DEFAULT_SENSITIVE_KEYS = frozenset({
'password', 'token', 'secret', 'authorization', 'cookie', 'access_key',
'secret_key', 'credential', 'api_key', 'apikey', 'credentials',
@@ -20,10 +34,10 @@ DEFAULT_SENSITIVE_KEYS = frozenset({
def resolve_credential(credential_ref_code: str) -> dict[str, Any]:
"""按凭据引用解析当前环境真实凭据(从 current_app.config[secret_ref] 读取)。
"""按凭据引用解析真实凭据(db 解密 / env 配置键),fail-closed。
Raises:
CredentialUnresolvedError: 引用不存在或 secret_ref 对应配置缺失/为空。
CredentialUnresolvedError: 引用不存在、密文缺失、主密钥缺失/无效或 env 键缺失。
"""
from flask import current_app
@@ -32,13 +46,29 @@ def resolve_credential(credential_ref_code: str) -> dict[str, Any]:
).first()
if cred is None:
raise CredentialUnresolvedError(ref=credential_ref_code)
if cred.secret_provider == 'db':
if not cred.secret_ciphertext:
raise CredentialUnresolvedError(ref=credential_ref_code)
try:
value = decrypt_secret(
cred.secret_ciphertext,
key_config_name=CREDENTIAL_KEY_CONFIG_NAME,
codes=_DB_SECRET_CODES,
)
except AppError as exc:
raise CredentialUnresolvedError(message=str(exc.message)) from exc
try:
parsed = json.loads(value)
except (ValueError, TypeError):
parsed = None
return dict(parsed) if isinstance(parsed, dict) else {'value': value}
secret_ref = cred.secret_ref
value = current_app.config.get(secret_ref) if has_app_ctx() else None
if value is None or value == '':
config_value = current_app.config.get(secret_ref) if has_app_ctx() else None
if config_value is None or config_value == '':
raise CredentialUnresolvedError(ref=secret_ref)
if isinstance(value, dict):
return dict(value)
return {'value': value}
if isinstance(config_value, dict):
return dict(config_value)
return {'value': config_value}
def has_app_ctx() -> bool:
@@ -4,6 +4,7 @@
依赖:typing.Protocol、dataclass;无 Flask/DB。
逻辑:Transport.call 返回原始 dict;classify_transport_response 把原始响应归一为
IntegrationCallResult(复用调拨六态分类语义)。fail-closed 由各 Transport 抛异常。
probe 为可选实现的连接测试探针(只证明网络可达,不做业务调用)。
"""
from __future__ import annotations
@@ -18,6 +19,9 @@ RESULT_STATUSES = (
'technical_failed', 'timeout', 'result_unknown',
)
# 传输层直接判失败的子集(读能力返回带这些 status 的原始 dict 时不再做输出映射)。
RESULT_FAILURE_STATUSES = ('business_failed', 'technical_failed')
@dataclass(frozen=True)
class IntegrationCallResult:
@@ -32,13 +36,44 @@ class IntegrationCallResult:
class Transport(Protocol):
"""传输层协议:REST/SOAP(后续 RPA/SQL/FILE)。call 返回原始响应 dict。"""
"""传输层协议:REST/SOAP(后续 RPA/SQL/FILE)。call 返回原始响应 dict。
probe 为可选实现的连接测试探针:只证明网络/服务可达,不要求接口契约;
Admin API 测试端点优先调 probe,未实现时回退 call(空 interface 规格)。
"""
connector_type: str
def call(self, *, client: dict, interface: dict, request: dict) -> dict[str, Any]:
...
def probe(self, *, client: dict) -> dict[str, Any]:
...
def merge_client_config(client: dict) -> dict:
"""把客户端实例独立列(endpoint/timeout_seconds)拼回 config_json 的兼容层。
与 binding.resolve_binding 的列拼回逻辑同源(单一实现),供连接测试等
不经绑定解析、直接消费客户端实例的调用方复用;返回副本,不改入参。
"""
config = dict(client.get('config_json') or {})
if client.get('endpoint') is not None:
config['endpoint'] = client['endpoint']
if client.get('timeout_seconds') is not None:
config['timeout_seconds'] = client['timeout_seconds']
return config
def mask_secrets(text: str, credential: dict | None) -> str:
"""把凭据值从自由文本(错误回显/响应摘要)中替换为 ***,防外泄进审计与日志。"""
result = str(text or '')
for value in (credential or {}).values():
secret = str(value or '')
if secret:
result = result.replace(secret, '***')
return result
def classify_transport_response(raw: dict[str, Any]) -> IntegrationCallResult:
"""按原始响应文本归一化结果分类(复用调拨六态分类语义)。
@@ -67,7 +102,7 @@ def classify_transport_response(raw: dict[str, Any]) -> IntegrationCallResult:
error_message=str(raw.get('message') or ''),
)
if status == 'timeout':
return IntegrationCallResult(status='timeout', error_code='ERP_TIMEOUT_UNKNOWN')
return IntegrationCallResult(status='timeout', error_code='EXTERNAL_TIMEOUT_UNKNOWN')
if status == 'result_unknown':
return IntegrationCallResult(status='result_unknown', error_code='ERP_RESULT_UNKNOWN', document_no=document_no)
return IntegrationCallResult(status='result_unknown', error_code='EXTERNAL_RESULT_UNKNOWN', document_no=document_no)
return IntegrationCallResult(status='technical_failed', error_code='ERP_UNKNOWN_RESPONSE')
@@ -4,6 +4,7 @@
依赖:requests(默认注入),可注入 http_request 供测试替身。
逻辑:endpoint 未冻结 fail-closed(TransportNotFrozenError);4xx/5xx 映射为
business_failed dict;非 JSON 响应映射为 technical_failed。
probe 连接测试探针:GET endpoint,任意 HTTP 响应即算可达(连接异常才算不通)。
"""
from __future__ import annotations
@@ -13,6 +14,7 @@ from typing import Any, Callable
import requests
from app.services.integration_connector.errors import TransportNotFrozenError
from app.services.integration_connector.transports.base import mask_secrets
HttpRequest = Callable[..., Any]
@@ -50,7 +52,8 @@ class RestTransport:
return {
'status': 'business_failed',
'code': f"HTTP_{int(response.status_code)}",
'message': str(getattr(response, 'text', ''))[:500],
# 错误回显可能包含请求内容(含凭据),先脱敏再截断。
'message': mask_secrets(str(getattr(response, 'text', ''))[:2000], client.get('credential'))[:500],
}
try:
return response.json()
@@ -58,5 +61,26 @@ class RestTransport:
return {
'status': 'technical_failed',
'code': 'NON_JSON',
'message': str(getattr(response, 'text', ''))[:500],
'message': mask_secrets(str(getattr(response, 'text', ''))[:2000], client.get('credential'))[:500],
}
def probe(self, *, client: dict) -> dict[str, Any]:
"""连接测试探针:GET endpoint,任意 HTTP 响应(含 4xx/5xx)都证明网络可达。
与 call 的区别:不要求接口契约(method/path),不做业务语义解析;
连接建立失败(DNS/超时/拒绝)才算不通。异常回显先脱敏再截断。
"""
config = client.get('config_json') or {}
endpoint = str(config.get('endpoint') or '').strip()
if not endpoint:
raise TransportNotFrozenError('REST endpoint not frozen (missing endpoint)')
timeout = int(config.get('timeout_seconds') or 60)
try:
response = self._http_request('GET', endpoint, timeout=timeout)
except Exception as exc:
return {'ok': False, 'code': 'CONNECTION_FAILED', 'message': mask_secrets(str(exc)[:500], client.get('credential'))}
return {
'ok': True,
'code': f"HTTP_{int(getattr(response, 'status_code', 0))}",
'message': mask_secrets(str(getattr(response, 'text', ''))[:200], client.get('credential'))[:200],
}
@@ -1,29 +1,215 @@
"""services/integration_connector/transports/soap.py
用途:SOAP Transport——WSDL/endpoint 未冻结时 fail-closed;真实实现待 WSDL 冻结后落地。
依赖:zeep(延时导入);errors.py。
逻辑:无 wsdl/endpoint → TransportNotFrozenError;冻结后走 zeep.Client(暂 NotImplemented)。
用途:SOAP Transport——按接口消息配置(soap.body_template)生成报文并解析 XML 响应。
依赖:requests(默认注入)、xml.etree.ElementTree、errors.py。
逻辑:endpoint 或 body_template 缺失 → fail-closed(TransportNotFrozenError);
模板占位符从请求参数 + 凭据(credential_* 保留前缀)填充,缺参即失败;
响应按 localname 解析(不绑命名空间前缀),Body 首子节点为业务根,
叶节点文本本身是合法 XML 时递归展开(内嵌转义报文的通用规则);
标准 SOAP 1.1 Fault(faultcode/faultstring)→ business_failed(SOAP 1.2 的
Code/Reason 结构暂只归 business_failed 不提取消息);HTTP ≥400 → business_failed;
非 XML → technical_failed。
probe 连接测试探针:GET WSDL 地址并校验返回 XML(definitions/Envelope 任一即通);
裸服务端点自动补 ?wsdl(SOAP 端点对裸 GET 常返回 404/405/501)。
"""
from __future__ import annotations
from typing import Any
import string
import xml.etree.ElementTree as ET
from typing import Any, Callable
from app.services.integration_connector.errors import TransportNotFrozenError
import requests
from app.services.integration_connector.errors import (
InputInvalidError,
TransportNotFrozenError,
)
from app.services.integration_connector.transports.base import mask_secrets
HttpRequest = Callable[..., Any]
# 内嵌转义 XML 的最大递归展开深度(防深嵌套/构造报文拖垮解析)。
MAX_EMBED_DEPTH = 3
def _localname(tag: Any) -> str:
"""去掉命名空间 URI,只取元素/属性的本地名(厂商前缀差异不影响映射路径)。"""
return tag.rsplit('}', 1)[-1] if isinstance(tag, str) else ''
def fill_soap_template(template: str, params: dict, credential: dict) -> str:
"""填充 SOAP 报文模板:{param} 来自请求参数,{credential_*} 来自凭据注入。
Args:
template: 接口配置里的完整报文模板(str.format 语义,{{}} 为字面大括号)。
params: 引擎映射后的接口参数。
credential: resolve_credential 解析出的凭据字典,按 credential_ 前缀注入。
Raises:
InputInvalidError: 占位符无对应值(fail-closed,绝不静默出空串)。
"""
merged: dict[str, Any] = dict(params or {})
# 凭据后注入并覆盖同名占位符:请求参数不得冒充/覆盖 credential_* 值。
for key, value in (credential or {}).items():
merged[f'credential_{key}'] = value
missing = sorted({
field for _, field, _, _ in string.Formatter().parse(template)
if field and field not in merged
})
if missing:
raise InputInvalidError(details={'reason': 'soap_template_param_missing', 'params': missing})
for key, value in merged.items():
# CDATA 内出现 ]]> 会截断报文;模板骨架自身的 CDATA 结束符不受影响,仅查替换值。
if ']]>' in str(value):
raise InputInvalidError(details={'reason': 'soap_cdata_terminator_in_params', 'param': key})
try:
return template.format(**merged)
except (KeyError, IndexError, ValueError) as exc:
# 覆盖裸 {} / 格式规格非法等 str.format 原生异常,统一 fail-closed 语义。
raise InputInvalidError(details={'reason': 'soap_template_invalid'}) from exc
def _element_to_value(elem: ET.Element, embed_depth: int) -> Any:
"""把元素转为通用 dict:属性 → @key;重复同名子元素 → list;叶子文本为值。
叶子文本本身是合法 XML(网关型系统常见的转义内嵌报文)时递归解析并保留内层根标签。
"""
attrs = {f'@{_localname(key)}': value for key, value in elem.attrib.items()}
children = list(elem)
text = (elem.text or '').strip()
if children:
node: dict[str, Any] = dict(attrs)
grouped: dict[str, list[Any]] = {}
for child in children:
name = _localname(child.tag)
grouped.setdefault(name, []).append(_element_to_value(child, embed_depth))
for name, items in grouped.items():
node[name] = items[0] if len(items) == 1 else items
if text:
node['#text'] = text
return node
if text.startswith('<') and embed_depth > 0:
try:
inner = ET.fromstring(text)
except ET.ParseError:
inner = None
if inner is not None:
return {_localname(inner.tag): _element_to_value(inner, embed_depth - 1)}
if not attrs:
return text or None
if text:
return {**attrs, '#text': text}
return attrs
def _parse_soap_payload(text: str) -> dict[str, Any]:
"""解析 SOAP 信封:取 Body 首子元素为业务根并转 dict;检测标准 Fault。"""
root = ET.fromstring(text)
body = None
for node in root.iter():
if _localname(node.tag) == 'Body':
body = node
break
payload = list(body)[0] if body is not None and len(body) else root
for node in payload.iter():
if _localname(node.tag) == 'Fault':
code = message = ''
for child in node.iter():
name = _localname(child.tag)
if name == 'faultcode' and not code:
code = (child.text or '').strip()
if name == 'faultstring' and not message:
message = (child.text or '').strip()
return {
'status': 'business_failed',
'code': code or 'SOAP_FAULT',
'message': message,
}
return {_localname(payload.tag): _element_to_value(payload, MAX_EMBED_DEPTH)}
class SoapTransport:
"""SOAP 传输;真实 SOAP 调用待 WSDL 冻结后实现(fail-closed 守卫已就位)。"""
"""SOAP 传输;http_request 可注入以便单元测试(默认 requests.request)。"""
connector_type = 'soap'
def __init__(self, http_request: HttpRequest | None = None):
self._http_request = http_request or requests.request
def call(self, *, client: dict, interface: dict, request: dict) -> dict[str, Any]:
config = client.get('config_json') or {}
# SOAP 只需一个连接地址(WSDL):WSDL 已含服务端点,不需单独的 REST 式 endpoint。
# 该地址存于 config['endpoint'](语义即连接地址);timeout 与 REST 同语义。
wsdl = str(config.get('endpoint') or '').strip()
if not wsdl:
endpoint = str(config.get('endpoint') or '').strip()
if not endpoint:
raise TransportNotFrozenError('SOAP contract not frozen (missing wsdl/endpoint)')
# 真实 SOAP 调用(zeep.Client(timeout=int(config.get('timeout_seconds') or 60), ...)) 待 WSDL 冻结后落地。
raise NotImplementedError('SOAP implementation pending frozen WSDL')
spec = interface.get('request_spec_json') or {}
soap_spec = spec.get('soap') or {}
template = str(soap_spec.get('body_template') or '').strip()
if not template:
raise TransportNotFrozenError('SOAP contract not frozen (missing soap.body_template)')
body = fill_soap_template(template, request.get('params') or {}, client.get('credential') or {})
headers = {'Content-Type': 'text/xml; charset=utf-8'}
action = str(soap_spec.get('action') or '').strip()
# SOAPAction 头必须存在且按规范带引号(空契约即 '""'):不带引号或缺失
# 会被鼎捷网关以 415 拒绝(2026-09-22 实测)。
headers['SOAPAction'] = f'"{action}"'
method = str(spec.get('method') or 'POST').upper()
path = str(spec.get('path') or '').strip()
url = endpoint.rstrip('/') + '/' + path.lstrip('/') if path else endpoint
response = self._http_request(
method,
url,
data=body.encode('utf-8'),
headers=headers,
timeout=int(config.get('timeout_seconds') or 60),
)
if int(getattr(response, 'status_code', 0)) >= 400:
return {
'status': 'business_failed',
'code': f"HTTP_{int(response.status_code)}",
# 错误回显可能包含请求体(含凭据),先脱敏再截断。
'message': mask_secrets(str(getattr(response, 'text', ''))[:2000], client.get('credential'))[:500],
}
response_text = mask_secrets(str(getattr(response, 'text', '') or ''), client.get('credential'))
try:
return _parse_soap_payload(response_text)
except ET.ParseError:
return {
'status': 'technical_failed',
'code': 'NON_XML',
'message': response_text[:500],
}
def probe(self, *, client: dict) -> dict[str, Any]:
"""连接测试探针:GET WSDL 地址并校验返回 XML,只证明网络与服务可达。
与 call 的区别:不要求 soap.body_template 契约;根元素为 definitions
(WSDL 地址约定)或 Envelope(直连服务端点约定)任一即算通过。
裸服务端点对 GET 常返回 404/405/501(SOAP 只实现 POST),故未带 query
时自动补 ?wsdl 取服务描述;已带 query(如 ?wsdl)则按原地址探测。
连接失败 / HTTP ≥400 / 非 XML / 根元素不符 → ok=False;错误回显先脱敏。
"""
config = client.get('config_json') or {}
endpoint = str(config.get('endpoint') or '').strip()
if not endpoint:
raise TransportNotFrozenError('SOAP contract not frozen (missing wsdl/endpoint)')
timeout = int(config.get('timeout_seconds') or 60)
probe_url = endpoint if '?' in endpoint else f'{endpoint}?wsdl'
try:
response = self._http_request('GET', probe_url, timeout=timeout)
except Exception as exc:
return {'ok': False, 'code': 'CONNECTION_FAILED', 'message': mask_secrets(str(exc)[:500], client.get('credential'))}
status = int(getattr(response, 'status_code', 0))
text = mask_secrets(str(getattr(response, 'text', '') or '')[:500], client.get('credential'))
if status >= 400:
return {'ok': False, 'code': f'HTTP_{status}', 'message': text}
try:
root = ET.fromstring(str(getattr(response, 'text', '') or ''))
except ET.ParseError:
return {'ok': False, 'code': 'NON_XML', 'message': text}
root_name = _localname(root.tag)
if root_name not in ('definitions', 'Envelope'):
return {'ok': False, 'code': 'NOT_WSDL', 'message': f'unexpected root <{root_name}>'}
return {'ok': True, 'code': f'HTTP_{status}', 'message': f'wsdl root <{root_name}>'}
@@ -2,16 +2,17 @@
backend/app/services/integration_tool_auth.py
用途:Dify / 集成方 HTTP Tool API 共用鉴权(Bearer 或 X-Integration-Key)。
依赖:Flask current_app、core.errors。
依赖:Flask current_app、core.errors、core.http_context。
逻辑:file-check / accounting-voucher-check 等 Tool Blueprint before_request 调用;
密钥优先 FILE_CHECK_TOOL_API_KEY,回退 INTEGRATION_API_KEY。
"""
from __future__ import annotations
from flask import current_app, request
from flask import current_app
from app.core.errors import ServiceUnavailableError, UnauthorizedError
from app.core.http_context import header
def require_integration_tool_auth() -> None:
@@ -19,7 +20,7 @@ def require_integration_tool_auth() -> None:
校验 Tool API 访问权限。
核心逻辑:Authorization Bearer 与 X-Integration-Key 二选一,值须与配置密钥完全一致。
Raises:
异常:
ServiceUnavailableError: 服务端未配置密钥。
UnauthorizedError: 缺少或错误的凭证。
"""
@@ -34,9 +35,9 @@ def require_integration_tool_auth() -> None:
code="missing_auth",
)
bearer = str(request.headers.get("Authorization") or "").strip()
bearer = header("Authorization").strip()
api_token = bearer[7:].strip() if bearer.lower().startswith("bearer ") else ""
integration_key = str(request.headers.get("X-Integration-Key") or "").strip()
integration_key = header("X-Integration-Key").strip()
if configured in {api_token, integration_key}:
return
if not api_token and not integration_key:
File diff suppressed because it is too large. Load diff
@@ -1,8 +1,514 @@
"""
backend/app/services/integrations/integration_api.py
用途:知识库源文件反查等集成 API 适配。
用途:解析 Dify dataset/document 对应的源文件下载链接(本地 KB 映射 + Dify 签名 URL 兜底)。
依赖:Flask current_app、core.http_context、requests、Kb* 模型。
逻辑:chat.resolve_source_file / 预览代理调用本服务;本地无可读文件时回退 Dify download。
"""
from app.services import integration_api # noqa: F401
from datetime import datetime, timedelta, timezone
from typing import Any, Dict, List, Optional, Tuple
from urllib.parse import urlparse
__all__ = ['integration_api']
import requests
from flask import current_app, has_app_context
from app.core.config.settings import Config
from app.core.http_context import has_http_request, header, host_url
class IntegrationApiService:
_cache: Dict[Tuple[str, str], Dict[str, Any]] = {}
@staticmethod
def _request_origin_url() -> str:
if not has_http_request():
return ""
forwarded_proto = header("X-Forwarded-Proto").split(",")[0].strip()
forwarded_host = header("X-Forwarded-Host").split(",")[0].strip()
if forwarded_proto and forwarded_host:
return f"{forwarded_proto}://{forwarded_host}".rstrip("/")
origin = header("Origin").strip().rstrip("/")
if origin:
return origin
referer = header("Referer").strip()
if referer:
parsed = urlparse(referer)
if parsed.scheme and parsed.netloc:
return f"{parsed.scheme}://{parsed.netloc}".rstrip("/")
return host_url()
@staticmethod
def _lookup_from_dify_document_api(dataset_id: str, remote_document_id: str) -> Optional[Dict[str, Any]]:
"""
当集成映射服务缺失时,直接调用 Dify 数据集文档下载接口兜底。
适用于“检索已返回 document_id,但 8891 没有同步 source file mapping”的场景。
"""
if not dataset_id or not remote_document_id:
return None
try:
from app.services.knowledge_cleaning.dify_sync_service import KbDifySyncService
except Exception:
return None
try:
service = KbDifySyncService()
if not service.base_url or not service.api_key:
return None
document_payload = service.get_document(
dataset_id=str(dataset_id),
document_id=str(remote_document_id),
)
if not isinstance(document_payload, dict):
return None
download_resp = requests.get(
f"{service.base_url.rstrip('/')}/datasets/{dataset_id}/documents/{remote_document_id}/download",
headers=service._headers(),
timeout=(5, 15),
)
if download_resp.status_code != 200:
if has_app_context():
current_app.logger.info(
"Dify document download lookup missed: dataset_id=%s remote_document_id=%s status=%s",
dataset_id,
remote_document_id,
download_resp.status_code,
)
return None
download_payload = download_resp.json() if download_resp.content else {}
source_url = str((download_payload or {}).get("url") or "").strip()
if not source_url:
return None
upload_info = (
((document_payload.get("data_source_info") or {}).get("upload_file"))
if isinstance(document_payload.get("data_source_info"), dict)
else {}
) or {}
source_filename = str(
upload_info.get("name")
or document_payload.get("name")
or ""
).strip() or None
source_ext = str(
upload_info.get("extension")
or (source_filename.rsplit(".", 1)[-1] if source_filename and "." in source_filename else "")
).strip().lower() or None
# Dify 返回的签名下载地址通常是短效的,这里主动给缓存一个较短 TTL,避免长期复用旧链接。
expires_at = (datetime.now(timezone.utc) + timedelta(minutes=10)).isoformat()
return {
"source_download_url": source_url,
"source_filename": source_filename,
"source_ext": source_ext,
"download_url_expires_at": expires_at,
"version_id": None,
"document_id": remote_document_id,
}
except Exception as e:
if has_app_context():
current_app.logger.warning(
"Dify document API fallback lookup failed: dataset_id=%s remote_document_id=%s err=%s",
dataset_id,
remote_document_id,
e,
)
return None
@staticmethod
def _normalize_batch_row(row: Dict[str, Any]) -> Optional[Tuple[Tuple[str, str], Dict[str, Any]]]:
if not isinstance(row, dict):
return None
req = row.get("request") if isinstance(row.get("request"), dict) else {}
dataset_id = str(req.get("dataset_id") or "").strip()
remote_document_id = str(req.get("remote_document_id") or "").strip()
if not dataset_id or not remote_document_id or not row.get("found"):
return None
doc = row.get("document") if isinstance(row.get("document"), dict) else {}
source_url = doc.get("source_download_url")
if not source_url:
return None
normalized = {
"source_download_url": source_url,
"source_filename": doc.get("source_filename"),
"source_ext": doc.get("source_ext"),
"download_url_expires_at": doc.get("download_url_expires_at"),
"version_id": doc.get("version_id"),
"document_id": doc.get("document_id"),
}
key = IntegrationApiService._cache_key(dataset_id, remote_document_id)
return key, normalized
@staticmethod
def _is_loopback_url(url: str) -> bool:
host = (urlparse(str(url or "").strip()).hostname or "").strip().lower()
return host in {"127.0.0.1", "localhost", "::1"}
@staticmethod
def get_api_key() -> str:
if has_app_context():
return str(current_app.config.get("INTEGRATION_API_KEY") or "").strip()
return str(Config.INTEGRATION_API_KEY or "").strip()
@staticmethod
def get_base_url() -> str:
mode = "local"
if has_app_context():
mode = str(current_app.config.get("INTEGRATION_API_MODE") or "local").strip().lower()
configured = str(current_app.config.get("INTEGRATION_API_BASE") or "").strip().rstrip("/")
public_base = str(current_app.config.get("WECOM_PUBLIC_BASE_URL") or "").strip().rstrip("/")
else:
mode = str(getattr(Config, "INTEGRATION_API_MODE", "local") or "local").strip().lower()
configured = str(Config.INTEGRATION_API_BASE or "").strip().rstrip("/")
public_base = ""
# 服务端查询优先使用显式配置的集成服务地址;
# 回退到当前请求 host 会错误地打到本后端自身。
if configured:
return configured
if mode != "external":
request_origin = IntegrationApiService._request_origin_url()
if request_origin:
return request_origin
if public_base:
return public_base
if has_http_request():
return host_url()
return configured
@staticmethod
def _cache_key(dataset_id: str, remote_document_id: str) -> Tuple[str, str]:
return (str(dataset_id), str(remote_document_id))
@staticmethod
def _is_cache_valid(payload: Dict[str, Any]) -> bool:
exp_str = payload.get("download_url_expires_at")
if exp_str:
try:
return datetime.fromisoformat(exp_str) > datetime.now().astimezone()
except Exception:
pass
# 如果没有明确的过期时间,尝试解析 url 里的 JWT token 检查
source_url = payload.get("source_download_url") or ""
if "token=" in source_url:
try:
import base64
import json
from urllib.parse import urlparse, parse_qs
import time
qs = parse_qs(urlparse(source_url).query)
if 'token' in qs:
token = qs['token'][0]
parts = token.split('.')
if len(parts) >= 2:
payload_b64 = parts[1]
payload_b64 += '=' * (-len(payload_b64) % 4)
payload_data = json.loads(base64.urlsafe_b64decode(payload_b64).decode('utf-8'))
exp = payload_data.get('exp', 0)
if exp and exp < time.time() + 300:
return False # 已过期或即将过期
except Exception:
pass
return True
@staticmethod
def _lookup_local_db(dataset_id: str, remote_document_id: str) -> Optional[Dict[str, Any]]:
"""
从本地 KbDifySyncRecord 反查可预览下载链接。
核心逻辑:优先返回磁盘上存在的源文件;缺失时回退清洗 Markdown;
两者皆无则返回 None,让上层继续走 Dify 签名下载兜底。
"""
if not has_app_context():
return None
from pathlib import Path
from app import db
from app.models import KbDifySyncRecord, KbDocumentVersion, KbDocument
normalized_dataset_id = str(dataset_id or '').strip()
normalized_remote_document_id = str(remote_document_id or '').strip()
if not normalized_dataset_id or not normalized_remote_document_id:
return None
record = (
db.session.query(KbDifySyncRecord)
.join(KbDocumentVersion, KbDocumentVersion.id == KbDifySyncRecord.document_version_id)
.join(KbDocument, KbDocument.id == KbDocumentVersion.document_id)
.filter(
KbDocument.is_deleted.is_(False),
KbDifySyncRecord.dataset_id == normalized_dataset_id,
KbDifySyncRecord.remote_document_id == normalized_remote_document_id,
)
.order_by(KbDifySyncRecord.updated_at.desc(), KbDifySyncRecord.id.desc())
.first()
)
if not record or not record.document_version or not record.document_version.document:
return None
version = record.document_version
document = version.document
def _existing(path_value: str | None):
if not path_value:
return None
raw = Path(str(path_value))
root = Path(current_app.config.get('KB_STORAGE_ROOT')).resolve()
candidate = (raw if raw.is_absolute() else (root / raw)).resolve()
try:
candidate.relative_to(root)
except ValueError:
return None
if candidate.exists() and candidate.is_file():
return candidate
return None
source_path = _existing(version.source_file_path)
markdown_path = _existing(version.cleaned_file_path) or _existing(version.cleaned_preview_path)
if source_path is None and markdown_path is None:
current_app.logger.info(
'[integration-lookup] local mapping found but no readable file document_id=%s version_id=%s',
document.id,
version.id,
)
return None
base_url = IntegrationApiService._request_origin_url()
if not base_url:
explicit = str(current_app.config.get('WECOM_PUBLIC_BASE_URL') or '').strip().rstrip('/')
if explicit:
base_url = explicit
elif has_http_request():
base_url = host_url()
else:
base_url = ''
import time
import jwt
secret = str(current_app.config.get('INTEGRATION_API_KEY') or '').strip()
if not secret:
secret = str(current_app.config.get('SECRET_KEY') or 'default-secret').strip()
exp = int(time.time()) + 86400 * 7 # 7 days expiration for local tokens
payload = {
'dataset_id': normalized_dataset_id,
'remote_document_id': normalized_remote_document_id,
'version_id': version.id,
'exp': exp
}
token = jwt.encode(payload, secret, algorithm='HS256')
if source_path is not None:
kind = 'source'
source_filename = version.source_file_name
source_ext = version.source_file_ext
else:
kind = 'md'
stem = Path(str(version.source_file_name or document.title or f'document-{document.id}')).stem
source_filename = f'{stem}.md'
source_ext = 'md'
source_download_url = (
f'{base_url}/api/integration/files/{document.id}/download'
f'?kind={kind}&version_id={version.id}&token={token}'
)
return {
"source_download_url": source_download_url,
"source_filename": source_filename,
"source_ext": source_ext,
"download_url_expires_at": None,
"version_id": version.id,
"document_id": document.id,
}
@staticmethod
def lookup_file_by_dify(dataset_id: str, remote_document_id: str) -> Optional[Dict[str, Any]]:
if not dataset_id or not remote_document_id:
return None
cache_key = IntegrationApiService._cache_key(dataset_id, remote_document_id)
cached = IntegrationApiService._cache.get(cache_key)
if cached and IntegrationApiService._is_cache_valid(cached):
return cached
base_url = IntegrationApiService.get_base_url()
api_key = IntegrationApiService.get_api_key()
if not base_url or not api_key:
return IntegrationApiService._lookup_local_db(dataset_id, remote_document_id)
url = f"{base_url}/api/integration/dify-file"
headers = {"X-Integration-Key": api_key}
params = {
"dataset_id": str(dataset_id),
"remote_document_id": str(remote_document_id),
}
try:
resp = requests.get(url, headers=headers, params=params, timeout=(4, 8))
if resp.status_code == 200:
payload = resp.json()
if isinstance(payload, dict):
IntegrationApiService._cache[cache_key] = payload
return payload
elif has_app_context():
current_app.logger.info(
"Integration API single lookup missed, falling back to batch resolve: dataset_id=%s remote_document_id=%s status=%s",
dataset_id,
remote_document_id,
resp.status_code,
)
except Exception as e:
if has_app_context():
current_app.logger.warning(f"Integration API lookup failed: {e}")
batch_url = f"{base_url}/api/integration/dify-files/resolve"
batch_headers = {
"X-Integration-Key": api_key,
"Content-Type": "application/json",
}
batch_body = {
"items": [
{
"dataset_id": str(dataset_id),
"remote_document_id": str(remote_document_id),
}
]
}
try:
resp = requests.post(batch_url, headers=batch_headers, json=batch_body, timeout=(5, 12))
if resp.status_code == 200:
payload = resp.json()
data = payload.get("data") if isinstance(payload, dict) else None
if isinstance(data, list):
for row in data:
normalized_row = IntegrationApiService._normalize_batch_row(row)
if not normalized_row:
continue
key, normalized = normalized_row
IntegrationApiService._cache[key] = normalized
if key == cache_key:
return normalized
except Exception as e:
if has_app_context():
current_app.logger.warning(f"Integration API batch fallback lookup failed: {e}")
# Fallback to local database if remote integration API fails or misses
local_result = IntegrationApiService._lookup_local_db(dataset_id, remote_document_id)
if local_result:
IntegrationApiService._cache[cache_key] = local_result
return local_result
# 最终兜底:直接查 Dify 文档 API 并请求签名下载 URL。
dify_result = IntegrationApiService._lookup_from_dify_document_api(dataset_id, remote_document_id)
if dify_result:
IntegrationApiService._cache[cache_key] = dify_result
return dify_result
return None
@staticmethod
def lookup_files_by_dify(items: List[Dict[str, str]]) -> Dict[Tuple[str, str], Dict[str, Any]]:
"""
Batch resolve source files by (dataset_id, remote_document_id).
Returns a mapping keyed by (dataset_id, remote_document_id).
"""
results: Dict[Tuple[str, str], Dict[str, Any]] = {}
if not items:
return results
unresolved: List[Dict[str, str]] = []
seen = set()
for item in items:
dataset_id = str(item.get("dataset_id") or "").strip()
remote_document_id = str(item.get("remote_document_id") or "").strip()
if not dataset_id or not remote_document_id:
continue
key = IntegrationApiService._cache_key(dataset_id, remote_document_id)
if key in seen:
continue
seen.add(key)
cached = IntegrationApiService._cache.get(key)
if cached and IntegrationApiService._is_cache_valid(cached):
results[key] = cached
else:
unresolved.append({
"dataset_id": dataset_id,
"remote_document_id": remote_document_id,
})
if not unresolved:
return results
base_url = IntegrationApiService.get_base_url()
api_key = IntegrationApiService.get_api_key()
if not base_url or not api_key:
return results
url = f"{base_url}/api/integration/dify-files/resolve"
headers = {
"X-Integration-Key": api_key,
"Content-Type": "application/json",
}
body = {"items": unresolved}
try:
resp = requests.post(url, headers=headers, json=body, timeout=(5, 12))
if resp.status_code != 200:
if has_app_context():
current_app.logger.warning(
"Integration API batch lookup failed: status=%s", resp.status_code
)
else:
payload = resp.json()
data = payload.get("data") if isinstance(payload, dict) else None
if isinstance(data, list):
for row in data:
if not isinstance(row, dict):
continue
normalized_row = IntegrationApiService._normalize_batch_row(row)
if not normalized_row:
continue
key, normalized = normalized_row
IntegrationApiService._cache[key] = normalized
results[key] = normalized
except Exception as e:
if has_app_context():
current_app.logger.warning(f"Integration API batch lookup exception: {e}")
# Fallback to single lookup or local DB for unresolved items
for item in unresolved:
dataset_id = item["dataset_id"]
remote_document_id = item["remote_document_id"]
key = IntegrationApiService._cache_key(dataset_id, remote_document_id)
if key in results:
continue
# Check if single lookup was not called already (if it was, it might be cached)
# Actually, `_lookup_local_db` should be checked directly since remote batch failed to find it.
local_result = IntegrationApiService._lookup_local_db(dataset_id, remote_document_id)
if local_result:
IntegrationApiService._cache[key] = local_result
results[key] = local_result
continue
# As a last resort, try remote single lookup if batch missed it
payload = IntegrationApiService.lookup_file_by_dify(dataset_id, remote_document_id)
if payload:
results[key] = payload
return results
+137 -3
View File
@@ -1,8 +1,142 @@
"""
backend/app/services/integrations/minio.py
用途:MinIO 对象存储适配。
用途:MinIO 对象存储适配(Agent 指南等文件上传/下载)。
依赖:minio SDK、app.core.config.settings。
逻辑:初始化客户端与 bucket;供 admin/agents、培训指南等模块读写对象。
"""
from app.services import minio_service # noqa: F401
import os
import uuid
from typing import BinaryIO
from minio import Minio
from minio.error import S3Error
from werkzeug.utils import secure_filename
from app.core.config.settings import config, ACTIVE_ENV_NAME
__all__ = ['minio_service']
cfg = config[ACTIVE_ENV_NAME]
class MinioService:
def __init__(self):
self.client = Minio(
cfg.MINIO_ENDPOINT,
access_key=cfg.MINIO_ACCESS_KEY,
secret_key=cfg.MINIO_SECRET_KEY,
secure=cfg.MINIO_SECURE,
)
self.bucket_name = cfg.MINIO_AGENT_GUIDES_BUCKET
self._ensure_bucket_exists()
def _ensure_bucket_exists(self):
try:
if not self.client.bucket_exists(self.bucket_name):
self.client.make_bucket(self.bucket_name)
# Set bucket policy to public read
policy = {
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": {"AWS": ["*"]},
"Action": ["s3:GetObject"],
"Resource": [f"arn:aws:s3:::{self.bucket_name}/*"]
}
]
}
import json
self.client.set_bucket_policy(self.bucket_name, json.dumps(policy))
except Exception as e:
# log or print error
print(f"MinIO bucket error (or not reachable): {e}")
def upload_file(self, file_stream: BinaryIO, filename: str, content_type: str, file_size: int) -> str:
"""
Uploads a file to MinIO and returns the generated object name.
"""
# If MinIO is not running, we could fallback to local storage or raise clear error
try:
self._ensure_bucket_exists()
except Exception:
pass
ext = os.path.splitext(filename)[1]
unique_filename = f"{uuid.uuid4().hex}{ext}"
try:
self.client.put_object(
bucket_name=self.bucket_name,
object_name=unique_filename,
data=file_stream,
length=file_size,
content_type=content_type
)
except Exception as e:
# For development, if minio is down, let's mock it so UI can continue
print(f"Warning: Minio upload failed ({e}). Fallback to local storage.")
# fallback to local storage
os.makedirs('data/agent-guides', exist_ok=True)
local_path = os.path.join('data/agent-guides', unique_filename)
file_stream.seek(0)
with open(local_path, 'wb') as f:
f.write(file_stream.read())
return unique_filename
def get_public_url(self, object_name: str) -> str:
"""
返回同源的指南文件代理地址。
用途:避免 HTTPS 页面直接加载 HTTP MinIO 对象时被移动端浏览器拦截。
参数约束:object_name 必须是系统生成的对象名;返回地址由指南文件接口提供 Range 响应。
"""
return f"/api/agents/guides/files/{object_name}"
def open_file_stream(self, object_name: str, *, offset: int = 0, length: int | None = None):
"""
按指定字节范围打开 MinIO 指南对象流。
用途:供同源指南文件接口透传视频数据,满足 iOS 媒体播放器的 Range/206 请求。
参数约束:offset 从 0 开始,length 为本次最多读取字节数;调用方必须关闭返回流。
"""
return self.client.get_object(
self.bucket_name,
object_name,
offset=offset,
length=length,
)
def stat_file(self, object_name: str):
"""
获取 MinIO 指南对象元数据。
用途:在返回视频前确定文件大小和 MIME 类型,以生成 iOS 可识别的媒体响应头。
参数约束:object_name 必须是系统保存的对象名;对象不存在时由 MinIO 异常上抛。
"""
return self.client.stat_object(self.bucket_name, object_name)
def get_file_bytes(self, object_name: str) -> bytes:
"""
读取对象的原始字节内容。
用途:给后台解析 PDF、图片等资料时复用统一文件读取入口,避免业务层自己判断本地回退还是 MinIO。
参数约束:object_name 必须是已存储的对象名,不接受外部 URL。
"""
local_path = os.path.join('data/agent-guides', object_name)
if os.path.exists(local_path):
with open(local_path, 'rb') as file_obj:
return file_obj.read()
response = self.client.get_object(self.bucket_name, object_name)
try:
return response.read()
finally:
response.close()
response.release_conn()
def delete_file(self, object_name: str):
try:
self.client.remove_object(self.bucket_name, object_name)
except S3Error as e:
print(f"Error deleting file from MinIO: {e}")
minio_service = MinioService()
@@ -1,2 +1,446 @@
"""OA 请假 Workflow SOAP 适配(Wave 4 自 oa_leave_workflow.py 迁入)。"""
from app.services import oa_leave_workflow # noqa: F401
"""
backend/app/services/integrations/oa/leave_workflow.py
用途:OA 请假流程 SOAP 适配(创建/查询请假单)。
依赖:requests、SOAP XML、OA WorkflowService、integrations.oa.sqlserver。
逻辑:由 HR 请假聊天意图或相关服务调用;组装 WorkflowRequestInfo 并提交 OA。
"""
from __future__ import annotations
from copy import deepcopy
from datetime import datetime
from typing import Any
import os
import xml.etree.ElementTree as ET
import requests
from flask import current_app
SOAP_ENV_NS = 'http://schemas.xmlsoap.org/soap/envelope/'
SERVICE_NS = 'webservices.services.weaver.com.cn'
WORKFLOW_NS = 'http://webservices.workflow.weaver'
XSI_NS = 'http://www.w3.org/2001/XMLSchema-instance'
NS = {
'soapenv': SOAP_ENV_NS,
'svc': SERVICE_NS,
'wf': WORKFLOW_NS,
'xsi': XSI_NS,
}
ET.register_namespace('soapenv', SOAP_ENV_NS)
ET.register_namespace('svc', SERVICE_NS)
ET.register_namespace('wf', WORKFLOW_NS)
ET.register_namespace('xsi', XSI_NS)
class OALeaveWorkflowError(RuntimeError):
"""Raised when OA leave workflow submission fails."""
class OALeaveWorkflowService:
WORKFLOW_ID = '879'
# Keep backend leave labels aligned with the chat form options so OA browser
# fields always receive the expected showValue instead of a raw code.
LEAVE_TYPE_LABELS = {
'005': '事假(小时)',
'006': '病假(小时)',
'007': '丧假(天)',
'010': '年假(天)',
'021': '因公出差(小时)',
'025': '调休假(小时)',
'035': '其他假(小时)',
'401': '产假(天)',
'402': '陪产假(天)',
'403': '婚假(天)',
'405': '住院病假(小时)',
'406': '工伤假(天)',
'408': '育儿假(小时)',
'ZZ01': '返乡假(小时)',
'ZZ04': '事假(经理专用小时)',
'ZZ05': '病假(经理专用小时)',
'ZZ07': '丧假(经理专用天)',
'ZZ08': '产假(经理专用天)',
'ZZ09': '陪产假(经理专用天)',
'ZZ10': '婚假(经理专用天)',
}
ERROR_MESSAGES = {
'-1': '创建流程失败',
'-2': '用户没有流程创建权限',
'-3': '创建流程基本信息失败',
'-4': '保存表单主表信息失败',
'-5': '更新紧急程度失败',
'-6': '流程操作者失败',
'-7': '流转至下一节点失败',
'-8': '节点附加操作失败',
}
@classmethod
def _get_wsdl_url(cls) -> str:
return (
current_app.config.get('OA_WORKFLOW_WSDL_URL')
or os.getenv('OA_WORKFLOW_WSDL_URL')
or 'http://oa.well-trust.com:8888/services/WorkflowService?wsdl'
).strip()
@classmethod
def _get_service_url(cls) -> str:
wsdl_url = cls._get_wsdl_url()
return wsdl_url[:-5] if wsdl_url.lower().endswith('?wsdl') else wsdl_url
@classmethod
def _request_timeout(cls) -> tuple[int, int]:
return (5, 25)
@classmethod
def _post_soap(cls, action: str, body_el: ET.Element) -> ET.Element:
envelope = ET.Element(f'{{{SOAP_ENV_NS}}}Envelope')
ET.SubElement(envelope, f'{{{SOAP_ENV_NS}}}Header')
body = ET.SubElement(envelope, f'{{{SOAP_ENV_NS}}}Body')
body.append(body_el)
payload = ET.tostring(envelope, encoding='utf-8', xml_declaration=True)
headers = {
'Content-Type': 'text/xml; charset=utf-8',
'SOAPAction': action,
}
max_retries = 3
last_exc = None
for attempt in range(1, max_retries + 1):
try:
response = requests.post(
cls._get_service_url(),
data=payload,
headers=headers,
timeout=cls._request_timeout(),
)
response.raise_for_status()
return ET.fromstring(response.text)
except requests.RequestException as exc:
last_exc = exc
status_code = getattr(getattr(exc, 'response', None), 'status_code', None)
retryable = status_code in (502, 503, 504) if status_code else True
if retryable and attempt < max_retries:
import time
wait = attempt * 2
current_app.logger.warning(
'[oa-leave] SOAP request failed (attempt %d/%d, status=%s), retrying in %ds: %s',
attempt, max_retries, status_code, wait, exc,
)
time.sleep(wait)
continue
raise OALeaveWorkflowError(f'OA WorkflowService 请求失败:{exc}') from exc
except ET.ParseError as exc:
raise OALeaveWorkflowError('OA WorkflowService 返回了无法解析的 XML。') from exc
raise OALeaveWorkflowError(f'OA WorkflowService 请求失败(重试{max_retries}次后仍出错):{last_exc}') from last_exc
@classmethod
def resolve_creator_oa_user(cls, employee_id: str | None, real_name: str | None = None) -> dict[str, str]:
return cls._resolve_runtime_oa_user(employee_id, real_name, role_label='请假人')
@classmethod
def resolve_agent_oa_user(cls, employee_id: str | None, real_name: str | None = None) -> dict[str, str]:
return cls._resolve_runtime_oa_user(employee_id, real_name, role_label='代理人')
@classmethod
def _resolve_runtime_oa_user(
cls,
employee_id: str | None,
real_name: str | None = None,
*,
role_label: str,
) -> dict[str, str]:
employee_id = (employee_id or '').strip()
real_name = (real_name or '').strip()
if not employee_id:
raise OALeaveWorkflowError(f'缺少{role_label}工号,无法匹配 OA 用户。')
if not real_name:
raise OALeaveWorkflowError(f'缺少{role_label}姓名,无法匹配 OA 用户。')
try:
from app.services.oa_sqlserver import OASQLServerService
matched = OASQLServerService.get_employee_by_name_and_workcode(real_name, employee_id)
except Exception as exc:
raise OALeaveWorkflowError(f'查询{role_label} OA 用户失败:{exc}') from exc
if not matched:
raise OALeaveWorkflowError(f'未找到{role_label} OA 用户:{real_name}({employee_id})。')
return {
'employee_id': matched['employeeId'],
'user_id': matched['uid'],
'name': matched['name'],
'jobtitle': matched.get('jobtitle', ''),
'jobtitleName': matched.get('jobtitleName', ''),
'departmentid': matched.get('departmentid', ''),
'departmentName': matched.get('departmentName', ''),
'subcompanyid1': matched.get('subcompanyid1', ''),
'subcompanyName': matched.get('subcompanyName', ''),
}
@staticmethod
def _pick_browser_field_value(*values: Any) -> str:
for value in values:
text = ('' if value is None else str(value)).strip()
if text:
return text
return ''
@classmethod
def _build_get_template_body(cls, workflow_id: str, oa_user_id: str) -> ET.Element:
root = ET.Element(f'{{{SERVICE_NS}}}getCreateWorkflowRequestInfo')
ET.SubElement(root, f'{{{SERVICE_NS}}}in0').text = str(workflow_id)
ET.SubElement(root, f'{{{SERVICE_NS}}}in1').text = str(oa_user_id)
return root
@classmethod
def _get_template_request_info(cls, workflow_id: str, oa_user_id: str) -> ET.Element:
action = 'urn:weaver.workflow.webservices.WorkflowService.getCreateWorkflowRequestInfo'
root = cls._post_soap(action, cls._build_get_template_body(workflow_id, oa_user_id))
out = root.find('.//svc:out', NS)
if out is None or out.attrib.get(f'{{{XSI_NS}}}nil') == 'true' or len(list(out)) == 0:
raise OALeaveWorkflowError('OA 未返回建单模板,请确认 workflowId 与 OA userid 是否正确。')
return deepcopy(out)
@classmethod
def _find_field(cls, request_info: ET.Element, field_name: str) -> ET.Element | None:
for field in request_info.findall('.//wf:WorkflowRequestTableField', NS):
if (field.findtext('wf:fieldName', default='', namespaces=NS) or '').strip() == field_name:
return field
return None
@classmethod
def _set_field(
cls,
request_info: ET.Element,
field_name: str,
*,
value: str | None,
show_value: str | None = None,
) -> None:
field = cls._find_field(request_info, field_name)
if field is None:
current_app.logger.warning('[oa-leave] field not found in template: %s', field_name)
return
value_node = field.find('wf:fieldValue', NS)
if value_node is None:
value_node = ET.SubElement(field, f'{{{WORKFLOW_NS}}}fieldValue')
value_node.text = '' if value is None else str(value)
if show_value is not None:
show_node = field.find('wf:fieldShowValue', NS)
if show_node is None:
show_node = ET.SubElement(field, f'{{{WORKFLOW_NS}}}fieldShowValue')
show_node.text = str(show_value)
field_html_type = (field.findtext('wf:fieldHtmlType', default='', namespaces=NS) or '').strip()
if field_html_type == '3':
filed_html_node = field.find('wf:filedHtmlShow', NS)
if filed_html_node is not None:
filed_html_node.text = str(show_value)
for tag in ['edit', 'view']:
node = field.find(f'wf:{tag}', NS)
if node is not None:
node.text = 'true'
else:
node = ET.SubElement(field, f'{{{WORKFLOW_NS}}}{tag}')
node.text = 'true'
@classmethod
def _set_text(cls, parent: ET.Element, xpath: str, value: str) -> None:
node = parent.find(xpath, NS)
if node is not None:
node.text = value
@classmethod
def _parse_frontend_datetime(cls, raw: str, field_name: str) -> datetime:
text = (raw or '').strip().replace('T', ' ')
try:
return datetime.strptime(text, '%Y-%m-%d %H:%M')
except ValueError as exc:
raise OALeaveWorkflowError(f'{field_name} 格式不正确,应为 YYYY-MM-DD HH:MM。') from exc
@classmethod
def _build_request_name(cls, creator_name: str, start_dt: datetime) -> str:
return f'请假申请单-{creator_name}-{start_dt.strftime("%Y-%m-%d")}'
@classmethod
def _normalize_duration(cls, value: Any) -> str:
try:
hours = float(value)
except (TypeError, ValueError) as exc:
raise OALeaveWorkflowError('请假时长格式不正确。') from exc
if hours <= 0:
raise OALeaveWorkflowError('请假时长必须大于 0。')
return f'{hours:.2f}'.rstrip('0').rstrip('.')
@classmethod
def build_request_info(cls, form_data: dict[str, Any], current_user: Any) -> tuple[ET.Element, dict[str, str], dict[str, str], dict[str, str]]:
filler_name = (
form_data.get('fillerName')
or getattr(current_user, 'real_name', None)
or getattr(current_user, 'username', None)
or '当前用户'
)
filler = cls._resolve_runtime_oa_user(
getattr(current_user, 'employee_id', None),
filler_name,
role_label='填单人'
)
applicant_name = (
form_data.get('applicantName')
or getattr(current_user, 'real_name', None)
or getattr(current_user, 'username', None)
or '当前用户'
)
applicant = cls.resolve_creator_oa_user(
form_data.get('employeeId') or getattr(current_user, 'employee_id', None),
applicant_name,
)
agent = cls.resolve_agent_oa_user(form_data.get('agentEmployeeId'), form_data.get('agentName'))
workflow_id = str(current_app.config.get('OA_LEAVE_WORKFLOW_CODE') or cls.WORKFLOW_ID)
request_info = cls._get_template_request_info(workflow_id, filler['user_id'])
start_dt = cls._parse_frontend_datetime(form_data.get('startTime'), '开始时间')
end_dt = cls._parse_frontend_datetime(form_data.get('endTime'), '结束时间')
if end_dt <= start_dt:
raise OALeaveWorkflowError('结束时间必须晚于开始时间。')
leave_type_code = (form_data.get('leaveType') or '').strip()
if not leave_type_code:
raise OALeaveWorkflowError('缺少假别编码。')
leave_type_label = cls.LEAVE_TYPE_LABELS.get(leave_type_code, leave_type_code)
request_name = cls._build_request_name(applicant['name'], start_dt)
cls._set_text(request_info, 'wf:creatorId', filler['user_id'])
cls._set_text(request_info, 'wf:creatorName', filler['name'])
cls._set_text(request_info, 'wf:requestLevel', '0')
cls._set_text(request_info, 'wf:requestName', request_name)
cls._set_text(request_info, './/wf:workflowBaseInfo/wf:workflowId', workflow_id)
cls._set_field(request_info, 'requestname', value=request_name, show_value=request_name)
cls._set_field(request_info, 'tdrgh', value=filler['employee_id'])
cls._set_field(request_info, 'sqrgh', value=applicant['employee_id'])
cls._set_field(request_info, 'tdrxm', value=filler['user_id'], show_value=filler['name'])
cls._set_field(request_info, 'sqrxm', value=applicant['user_id'], show_value=applicant['name'])
filler_jobtitle = cls._pick_browser_field_value(filler.get('jobtitle'), form_data.get('fillerJobTitle'))
filler_jobtitle_name = cls._pick_browser_field_value(filler.get('jobtitleName'))
filler_department = cls._pick_browser_field_value(filler.get('departmentid'), form_data.get('fillerDepartmentId'))
filler_department_name = cls._pick_browser_field_value(filler.get('departmentName'))
filler_subcompany = cls._pick_browser_field_value(filler.get('subcompanyid1'), form_data.get('fillerSubCompanyId1'))
filler_subcompany_name = cls._pick_browser_field_value(filler.get('subcompanyName'))
applicant_jobtitle = cls._pick_browser_field_value(applicant.get('jobtitle'), form_data.get('applicantJobTitle'))
applicant_jobtitle_name = cls._pick_browser_field_value(applicant.get('jobtitleName'))
applicant_department = cls._pick_browser_field_value(applicant.get('departmentid'), form_data.get('applicantDepartmentId'))
applicant_department_name = cls._pick_browser_field_value(applicant.get('departmentName'))
applicant_subcompany = cls._pick_browser_field_value(applicant.get('subcompanyid1'), form_data.get('applicantSubCompanyId1'))
applicant_subcompany_name = cls._pick_browser_field_value(applicant.get('subcompanyName'))
try:
from app.services.oa_sqlserver import OASQLServerService
if filler_jobtitle and not filler_jobtitle_name:
filler_jobtitle_name = OASQLServerService.get_jobtitle_name(filler_jobtitle)
if filler_department and not filler_department_name:
filler_department_name = OASQLServerService.get_department_name(filler_department)
if filler_subcompany and not filler_subcompany_name:
filler_subcompany_name = OASQLServerService.get_subcompany_name(filler_subcompany)
if applicant_jobtitle and not applicant_jobtitle_name:
applicant_jobtitle_name = OASQLServerService.get_jobtitle_name(applicant_jobtitle)
if applicant_department and not applicant_department_name:
applicant_department_name = OASQLServerService.get_department_name(applicant_department)
if applicant_subcompany and not applicant_subcompany_name:
applicant_subcompany_name = OASQLServerService.get_subcompany_name(applicant_subcompany)
except Exception:
pass
cls._set_field(request_info, 'tdrzw', value=filler_jobtitle, show_value=filler_jobtitle_name or filler_jobtitle or '暂无')
cls._set_field(request_info, 'tdrbm', value=filler_department, show_value=filler_department_name or filler_department or '暂无')
cls._set_field(request_info, 'tdrgs', value=filler_subcompany, show_value=filler_subcompany_name or filler_subcompany or '暂无')
cls._set_field(request_info, 'sqrzw', value=applicant_jobtitle, show_value=applicant_jobtitle_name or applicant_jobtitle or '暂无')
cls._set_field(request_info, 'sqrbm', value=applicant_department, show_value=applicant_department_name or applicant_department or '暂无')
cls._set_field(request_info, 'sqrgs', value=applicant_subcompany, show_value=applicant_subcompany_name or applicant_subcompany or '暂无')
current_app.logger.info(
'[oa-leave] field values: tdrzw=%s/%s tdrbm=%s/%s tdrgs=%s/%s sqrzw=%s/%s sqrbm=%s/%s sqrgs=%s/%s',
filler_jobtitle, filler_jobtitle_name or filler_jobtitle or '暂无',
filler_department, filler_department_name or filler_department or '暂无',
filler_subcompany, filler_subcompany_name or filler_subcompany or '暂无',
applicant_jobtitle, applicant_jobtitle_name or applicant_jobtitle or '暂无',
applicant_department, applicant_department_name or applicant_department or '暂无',
applicant_subcompany, applicant_subcompany_name or applicant_subcompany or '暂无',
)
cls._set_field(request_info, 'dlrgh', value=agent['employee_id'])
cls._set_field(request_info, 'dlrxm', value=agent['user_id'], show_value=agent['name'])
cls._set_field(request_info, 'dlrlogid', value=agent['user_id'], show_value=agent['user_id'])
cls._set_field(request_info, 'jb', value=leave_type_code, show_value=leave_type_label)
cls._set_field(request_info, 'jbbh', value=leave_type_code, show_value=leave_type_code)
cls._set_field(request_info, 'kssj', value=start_dt.strftime('%Y-%m-%d'), show_value=start_dt.strftime('%Y-%m-%d'))
cls._set_field(request_info, 'kssk', value=start_dt.strftime('%H:%M'), show_value=start_dt.strftime('%H:%M'))
cls._set_field(request_info, 'jssj', value=end_dt.strftime('%Y-%m-%d'), show_value=end_dt.strftime('%Y-%m-%d'))
cls._set_field(request_info, 'jssk', value=end_dt.strftime('%H:%M'), show_value=end_dt.strftime('%H:%M'))
cls._set_field(request_info, 'qjsc', value=cls._normalize_duration(form_data.get('durationHours')), show_value=cls._normalize_duration(form_data.get('durationHours')))
cls._set_field(request_info, 'sfwgs', value=str(form_data.get('isWorkInjury')), show_value='是' if str(form_data.get('isWorkInjury')) == '0' else '否')
cls._set_field(request_info, 'sfwc', value=str(form_data.get('isOutOfOffice')), show_value='是' if str(form_data.get('isOutOfOffice')) == '0' else '否')
cls._set_field(request_info, 'bz', value=(form_data.get('remark') or '').strip(), show_value=(form_data.get('remark') or '').strip())
return request_info, filler, applicant, agent
@classmethod
def _build_create_body(cls, request_info: ET.Element, oa_user_id: str) -> ET.Element:
root = ET.Element(f'{{{SERVICE_NS}}}doCreateWorkflowRequest')
in0 = deepcopy(request_info)
in0.tag = f'{{{SERVICE_NS}}}in0'
root.append(in0)
ET.SubElement(root, f'{{{SERVICE_NS}}}in1').text = str(oa_user_id)
return root
@classmethod
def _parse_create_response(cls, root: ET.Element) -> str:
out = root.findtext('.//svc:out', default='', namespaces=NS)
out = (out or '').strip()
if not out:
raise OALeaveWorkflowError('OA 未返回单据编号。')
if out in cls.ERROR_MESSAGES:
raise OALeaveWorkflowError(cls.ERROR_MESSAGES[out])
if out.startswith('-'):
raise OALeaveWorkflowError(f'OA 创建流程失败,返回码:{out}')
return out
@classmethod
def serialize_request_xml(cls, request_info: ET.Element) -> str:
return ET.tostring(request_info, encoding='unicode')
@classmethod
def submit_leave_request(cls, form_data: dict[str, Any], current_user: Any) -> dict[str, Any]:
request_info, filler, applicant, agent = cls.build_request_info(form_data, current_user)
log_fields = ['tdrzw', 'tdrbm', 'tdrgs', 'sqrzw', 'sqrbm', 'sqrgs', 'qjsc', 'tdrgh', 'sqrgh']
for fn in log_fields:
f = cls._find_field(request_info, fn)
if f is not None:
fv = f.findtext('wf:fieldValue', default='', namespaces=NS)
fsv = f.findtext('wf:fieldShowValue', default='', namespaces=NS)
fe = f.findtext('wf:edit', default='(removed)', namespaces=NS)
current_app.logger.info('[oa-leave] PUSH field %s: value=%s showValue=%s edit=%s', fn, fv, fsv, fe)
action = 'urn:weaver.workflow.webservices.WorkflowService.doCreateWorkflowRequest'
root = cls._post_soap(action, cls._build_create_body(request_info, filler['user_id']))
request_id = cls._parse_create_response(root)
current_app.logger.info('[oa-leave] OA response request_id=%s', request_id)
return {
'ok': True,
'request_id': request_id,
'request_name': request_info.findtext('wf:requestName', default='', namespaces=NS),
'submitted_at': datetime.now().strftime('%Y-%m-%d %H:%M'),
'creator': applicant,
'filler': filler,
'agent': agent,
'workflow_id': str(current_app.config.get('OA_LEAVE_WORKFLOW_CODE') or cls.WORKFLOW_ID),
'request_xml': cls.serialize_request_xml(request_info),
}
@@ -1,2 +1,258 @@
"""OA SQL Server 适配(Wave 4 自 oa_sqlserver.py 迁入)。"""
from app.services import oa_sqlserver # noqa: F401
"""
backend/app/services/integrations/oa/sqlserver.py
用途:封装 OA SQL Server 的员工检索与组织信息查询,供请假代理人/申请人选择等场景复用。
依赖:pyodbc、OA ecology 视图 userInfo_view / HrmDepartment / HrmSubCompany / HrmJobTitles。
逻辑:只读 SQL 查询返回 OA 用户与组织字段;对 OA 多语言包装串在服务层清洗为可展示中文。
"""
import os
import re
import pyodbc
from flask import current_app
_OA_MULTILINGUAL_WRAPPER_PATTERN = re.compile(
r"~`~`7\s*(.*?)\s*~`8\s*(.*?)\s*~`9\s*(.*?)\s*~`~"
)
class OASQLServerService:
@staticmethod
def _normalize_oa_text(value) -> str:
"""
清洗 OA 多语言包装字段。
AI 触发时机:当 OA 视图返回的姓名、部门、分部、职务等字段中夹带
`~`~`7 中文 ~`8 English ~`9 繁中 ~`~` 这类原始包装串时,需统一提取
可直接给用户展示的文本,避免在代理人选择弹窗中看到乱码样式的标记串。
Args:
value: 来自 OA SQL Server 的原始字段值。
Returns:
优先返回简体中文,其次英文、繁中;若未命中包装规则,则返回原始去空白文本。
"""
text = str(value or "").strip()
if not text:
return ""
matched = _OA_MULTILINGUAL_WRAPPER_PATTERN.search(text)
if not matched:
return text
simplified, english, traditional = (
segment.strip().strip("`").strip()
for segment in matched.groups()
)
return simplified or english or traditional or text
@staticmethod
def _pick_driver():
drivers = pyodbc.drivers()
preferred = [
"ODBC Driver 18 for SQL Server",
"ODBC Driver 17 for SQL Server",
"SQL Server",
]
for name in preferred:
if name in drivers:
return name
if not drivers:
raise RuntimeError("未找到可用的 SQL Server ODBC 驱动")
return drivers[-1]
@classmethod
def _connect(cls):
driver = os.getenv("OA_SQLSERVER_DRIVER", "").strip() or cls._pick_driver()
available_drivers = pyodbc.drivers()
if driver not in available_drivers:
driver = cls._pick_driver()
server = os.getenv("OA_SQLSERVER_HOST", "192.168.100.225").strip()
port = os.getenv("OA_SQLSERVER_PORT", "1433").strip()
database = os.getenv("OA_SQLSERVER_DATABASE", "ecology").strip()
username = os.getenv("OA_SQLSERVER_USERNAME", "AI_Knowledge_Base_OA").strip()
password = os.getenv("OA_SQLSERVER_PASSWORD", "hoo-thai@123_AI_OA").strip()
encrypt = os.getenv("OA_SQLSERVER_ENCRYPT", "no").strip().lower()
trust_cert = os.getenv("OA_SQLSERVER_TRUST_CERT", "yes").strip().lower()
timeout = int(os.getenv("OA_SQLSERVER_TIMEOUT", "10"))
conn_str = (
f"DRIVER={{{driver}}};"
f"SERVER={server},{port};"
f"DATABASE={database};"
f"UID={username};"
f"PWD={password};"
)
if driver != "SQL Server":
conn_str += (
f"Encrypt={encrypt};"
f"TrustServerCertificate={trust_cert};"
)
return pyodbc.connect(conn_str, timeout=timeout)
@classmethod
def search_employees(cls, keyword: str, page: int, page_size: int):
connection = cls._connect()
cursor = connection.cursor()
try:
offset = (page - 1) * page_size
params = []
# Count total
count_sql = "SELECT COUNT(1) FROM userInfo_view WHERE 1=1"
if keyword:
count_sql += " AND (workcode LIKE ? OR lastname LIKE ?)"
like_kw = f"%{keyword}%"
params.extend([like_kw, like_kw])
cursor.execute(count_sql, params)
total = cursor.fetchone()[0]
# Fetch page
# Compatible with older SQL Server versions (2008/2012)
query_sql = """
SELECT id, workcode, lastname, jobtitle, departmentid, subcompanyid1,
departmentname, subcompanyname, jobtitlename
FROM (
SELECT v.id, v.workcode, v.lastname, v.jobtitle, v.departmentid, v.subcompanyid1,
d.departmentname, s.subcompanyname, j.jobtitlename,
ROW_NUMBER() OVER(ORDER BY v.id) as rn
FROM userInfo_view v
LEFT JOIN HrmDepartment d ON v.departmentid = d.id
LEFT JOIN HrmSubCompany s ON v.subcompanyid1 = s.id
LEFT JOIN HrmJobTitles j ON v.jobtitle = j.id
WHERE 1=1
"""
if keyword:
query_sql += " AND (workcode LIKE ? OR lastname LIKE ?)"
query_sql += """
) as T
WHERE rn > ? AND rn <= ?
"""
page_params = params + [offset, offset + page_size]
cursor.execute(query_sql, page_params)
items = []
for row in cursor.fetchall():
items.append({
"uid": str(row.id) if row.id is not None else "",
"employeeId": str(row.workcode) if row.workcode is not None else "",
"name": cls._normalize_oa_text(row.lastname),
"jobtitle": cls._normalize_oa_text(row.jobtitle),
"departmentid": str(row.departmentid) if row.departmentid is not None else "",
"subcompanyid1": str(row.subcompanyid1) if row.subcompanyid1 is not None else "",
"departmentName": cls._normalize_oa_text(row.departmentname),
"subcompanyName": cls._normalize_oa_text(row.subcompanyname),
"jobtitleName": cls._normalize_oa_text(row.jobtitlename),
})
return {
"items": items,
"total": total,
"page": page,
"page_size": page_size
}
finally:
try:
cursor.close()
finally:
connection.close()
@classmethod
def get_employee_by_name_and_workcode(cls, real_name: str, employee_id: str):
connection = cls._connect()
cursor = connection.cursor()
try:
normalized_name = (real_name or "").strip()
normalized_employee_id = (employee_id or "").strip()
if not normalized_name or not normalized_employee_id:
raise RuntimeError("缺少姓名或工号,无法查询 OA 用户")
query_sql = """
SELECT TOP 1 v.id, v.workcode, v.lastname, v.jobtitle, v.departmentid, v.subcompanyid1,
d.departmentname, s.subcompanyname, j.jobtitlename
FROM userInfo_view v
LEFT JOIN HrmDepartment d ON v.departmentid = d.id
LEFT JOIN HrmSubCompany s ON v.subcompanyid1 = s.id
LEFT JOIN HrmJobTitles j ON v.jobtitle = j.id
WHERE v.workcode = ? AND v.lastname = ?
ORDER BY v.id
"""
cursor.execute(query_sql, [normalized_employee_id, normalized_name])
row = cursor.fetchone()
if not row:
return None
return {
"uid": str(row.id) if row.id is not None else "",
"employeeId": str(row.workcode) if row.workcode is not None else "",
"name": cls._normalize_oa_text(row.lastname),
"jobtitle": cls._normalize_oa_text(row.jobtitle),
"departmentid": str(row.departmentid) if row.departmentid is not None else "",
"subcompanyid1": str(row.subcompanyid1) if row.subcompanyid1 is not None else "",
"departmentName": cls._normalize_oa_text(row.departmentname),
"subcompanyName": cls._normalize_oa_text(row.subcompanyname),
"jobtitleName": cls._normalize_oa_text(row.jobtitlename),
}
finally:
try:
cursor.close()
finally:
connection.close()
@classmethod
def get_department_name(cls, department_id: str) -> str:
if not department_id or not department_id.strip():
return ""
connection = cls._connect()
cursor = connection.cursor()
try:
cursor.execute(
"SELECT TOP 1 departmentname FROM HrmDepartment WHERE id = ?",
[department_id.strip()],
)
row = cursor.fetchone()
return cls._normalize_oa_text(row.departmentname) if row and row.departmentname else ""
finally:
try:
cursor.close()
finally:
connection.close()
@classmethod
def get_subcompany_name(cls, subcompany_id: str) -> str:
if not subcompany_id or not subcompany_id.strip():
return ""
connection = cls._connect()
cursor = connection.cursor()
try:
cursor.execute(
"SELECT TOP 1 subcompanyname FROM HrmSubCompany WHERE id = ?",
[subcompany_id.strip()],
)
row = cursor.fetchone()
return cls._normalize_oa_text(row.subcompanyname) if row and row.subcompanyname else ""
finally:
try:
cursor.close()
finally:
connection.close()
@classmethod
def get_jobtitle_name(cls, jobtitle_id: str) -> str:
if not jobtitle_id or not jobtitle_id.strip():
return ""
connection = cls._connect()
cursor = connection.cursor()
try:
cursor.execute(
"SELECT TOP 1 jobtitlename FROM HrmJobTitles WHERE id = ?",
[jobtitle_id.strip()],
)
row = cursor.fetchone()
return cls._normalize_oa_text(row.jobtitlename) if row and row.jobtitlename else ""
finally:
try:
cursor.close()
finally:
connection.close()
@@ -1,2 +1,473 @@
"""OA 与企微同步适配(Wave 4 自 oa_wecom_sync.py 迁入)。"""
from app.services import oa_wecom_sync # noqa: F401
"""
backend/app/services/integrations/oa/wecom_sync.py
用途:从 OA SQL Server userInfo_view 按本地工号回填 users.wecom_userid。
依赖:OASQLServerService、SQLAlchemy db、User 模型。
逻辑:先查本地有 employee_id 的用户,再按工号 IN 查询 OA;供 admin 绑定管理预览/写入。
"""
from __future__ import annotations
from typing import Any
from app import db
from app.models import User
from app.services.integrations.oa.sqlserver import OASQLServerService
_PREVIEW_LIMIT = 20
_OA_VIEW = 'userInfo_view'
_OA_IN_BATCH_SIZE = 500
def _clean_str(value) -> str | None:
"""
规范化字符串;空值返回 None。
@param value: 任意输入
Returns:
去首尾空白后的字符串,或 None
"""
if value is None:
return None
text = str(value).strip()
return text or None
def _load_local_users_with_employee_id() -> list[tuple[User, str]]:
"""
加载本地含有效工号的用户列表。
核心逻辑:查询 employee_id 非空记录,trim 后过滤空串。
Returns:
(User, employee_id) 元组列表
"""
rows: list[tuple[User, str]] = []
for user in db.session.query(User).filter(User.employee_id.isnot(None)).all():
employee_id = _clean_str(user.employee_id)
if not employee_id:
continue
rows.append((user, employee_id))
return rows
def fetch_oa_wecom_bindings_for_workcodes(workcodes: list[str]) -> list[dict[str, str | None]]:
"""
按工号批量查询 OA userInfo_view 中的企微 userid 映射。
核心逻辑:工号去重后分批 IN 查询,避免全表扫描。
@param workcodes: 本地 users.employee_id 列表
Returns:
每项含 workcode、wecom_userid、name
Raises:
RuntimeError: ODBC 连接或查询失败
"""
unique_codes: list[str] = []
seen: set[str] = set()
for code in workcodes:
cleaned = _clean_str(code)
if not cleaned or cleaned in seen:
continue
seen.add(cleaned)
unique_codes.append(cleaned)
if not unique_codes:
return []
connection = OASQLServerService._connect()
cursor = connection.cursor()
rows: list[dict[str, str | None]] = []
try:
for offset in range(0, len(unique_codes), _OA_IN_BATCH_SIZE):
batch = unique_codes[offset : offset + _OA_IN_BATCH_SIZE]
placeholders = ','.join('?' for _ in batch)
cursor.execute(
f"""
SELECT id, workcode, lastname
FROM userInfo_view
WHERE workcode IN ({placeholders})
AND id IS NOT NULL
""",
batch,
)
for row in cursor.fetchall():
workcode = _clean_str(row.workcode)
wecom_userid = _clean_str(row.id)
if not workcode or not wecom_userid:
continue
rows.append(
{
'workcode': workcode,
'wecom_userid': wecom_userid,
'name': _clean_str(row.lastname),
}
)
return rows
finally:
try:
cursor.close()
finally:
connection.close()
def sync_wecom_userids_from_oa(*, apply: bool) -> dict[str, Any]:
"""
执行 OA 工号 → wecom_userid 同步(本地用户驱动)。
核心逻辑:读本地工号 → 按 IN 查 OA → 匹配并 dry-run 或写入 wecom_userid。
@param apply: True 时提交数据库;存在 conflicts 时不写入
Returns:
统计摘要 dict(结构与企微通讯录同步兼容,便于前端复用)
Raises:
RuntimeError: OA 未配置、连接失败或 apply 时存在冲突
"""
local_users = _load_local_users_with_employee_id()
workcodes = [employee_id for _, employee_id in local_users]
oa_rows = fetch_oa_wecom_bindings_for_workcodes(workcodes)
summary: dict[str, Any] = {
'apply': apply,
'employee_id_source': f'oa:{_OA_VIEW}.workcode',
'department_ids': [],
'local_candidates': len(local_users),
'wecom_users': 0,
'wecom_without_employee_id': 0,
'local_matched': 0,
'would_update': 0,
'updated': 0,
'already_bound': 0,
'local_missing': 0,
'conflicts': [],
'missing_samples': [],
'pending_updates': [],
}
oa_by_workcode: dict[str, dict[str, str | None]] = {}
duplicate_workcodes: set[str] = set()
for row in oa_rows:
workcode = row['workcode']
if not workcode:
continue
if workcode in oa_by_workcode:
duplicate_workcodes.add(workcode)
summary['conflicts'].append(
{
'employee_id': workcode,
'username': '',
'new_wecom_userid': row['wecom_userid'],
'reason': 'duplicate_workcode_in_oa',
}
)
continue
oa_by_workcode[workcode] = row
summary['wecom_users'] = len(oa_by_workcode)
for local_user, employee_id in local_users:
if employee_id in duplicate_workcodes:
continue
oa_row = oa_by_workcode.get(employee_id)
if not oa_row:
summary['local_missing'] += 1
if len(summary['missing_samples']) < _PREVIEW_LIMIT:
summary['missing_samples'].append(
{
'employee_id': employee_id,
'username': local_user.username,
}
)
continue
wecom_userid = oa_row['wecom_userid']
name = oa_row.get('name')
if not wecom_userid:
summary['wecom_without_employee_id'] += 1
continue
summary['local_matched'] += 1
if local_user.wecom_userid == wecom_userid:
summary['already_bound'] += 1
continue
conflict = None
if local_user.wecom_userid and local_user.wecom_userid != wecom_userid:
conflict = {
'employee_id': employee_id,
'username': local_user.username,
'old_wecom_userid': local_user.wecom_userid,
'new_wecom_userid': wecom_userid,
}
else:
occupied = (
db.session.query(User)
.filter(User.wecom_userid == wecom_userid, User.id != local_user.id)
.first()
)
if occupied:
conflict = {
'employee_id': employee_id,
'username': local_user.username,
'new_wecom_userid': wecom_userid,
'occupied_by_user_id': occupied.id,
'occupied_by_username': occupied.username,
}
if conflict:
summary['conflicts'].append(conflict)
continue
summary['would_update'] += 1
if len(summary['pending_updates']) < _PREVIEW_LIMIT:
summary['pending_updates'].append(
{
'employee_id': employee_id,
'username': local_user.username,
'wecom_userid': wecom_userid,
'name': name,
}
)
if apply:
local_user.wecom_userid = wecom_userid
summary['updated'] += 1
if summary['conflicts'] and apply:
db.session.rollback()
raise RuntimeError('Conflicts detected; resolve manually before apply')
if apply and summary['updated'] > 0:
db.session.commit()
elif apply:
db.session.rollback()
return summary
+381 -2
View File
@@ -1,2 +1,381 @@
"""PLM Oracle 流式查询适配(Wave 4 自 plm_oracle.py 迁入)。"""
from app.services import plm_oracle # noqa: F401
"""
backend/app/services/integrations/plm/oracle.py
用途:PLM Oracle 物料/SOP 查询与流式聊天快路径。
依赖:Flask current_app、Text2SQLService、ChatLog 模型。
逻辑:聊天意图路由命中 PLM 时调用;查询 Oracle 并格式化为 SSE 结果。
"""
import json
import os
import re
import time
from datetime import datetime
from html import escape
from urllib.parse import quote
from flask import current_app
from app import db
from app.models import ChatLog
from app.services.integrations.text2sql import Text2SQLService
class PLMOracleService:
_MAX_RESULT_ROWS = 50
_PLM_PREVIEW_SHARE_ROOT = (os.getenv("PLM_PREVIEW_SHARE_ROOT") or "\\\\192.168.0.11\\dss\\dssroot\\").strip()
_SUMMARY_COLUMNS = ("NAME", "EXTENTIONNAME", "FILETYPE", "FILESIZE", "RELATIVEPATH", "LASTACCESSTIME")
_MATERIAL_PATTERN = re.compile(r"\b[A-Z0-9]+(?:-[A-Z0-9]+)+\b", re.IGNORECASE)
_EXPLICIT_LABEL_PATTERN = re.compile(
r"(?:料号|料號|物料料号|物料料號|物料编号|物料編號|part\s*(?:no|number)?)\s*[::]?\s*([A-Z0-9][A-Z0-9._-]{5,})",
re.IGNORECASE,
)
_RELATIONAL_SQL = """
select *
from bi_file endb
where endb.revisionguid in (
select bb.revisionguid
from (
select v.end1, b.*
from viewobject_0 v, NT_00064_0 str, NT_00016_0 cad, bi_file b
where v.name in ('ITEM-CAD2D$', 'ITEM-CAD3D$')
and str.viewfk = v.guid
and str.end2$master = cad.masterfk
and cad.latestrevision like '%m%'
and b.revisionguid = cad.guid
union
select v.end1, b.*
from viewobject_0 v, NT_00064_0 str, NT_00018_0 cad, bi_file b
where v.name in ('ITEM-CAD2D$', 'ITEM-CAD3D$')
and str.viewfk = v.guid
and str.end2$master = cad.masterfk
and cad.latestrevision like '%m%'
and b.revisionguid = cad.guid
union
select v.end1, b.*
from viewobject_0 v,
StructureObject_0 str,
document_0 doc,
bi_file b
where v.name in ('RelatedDoc')
and str.viewfk = v.guid
and str.end2$master = doc.masterfk
and doc.latestrevision like '%m%'
and b.revisionguid = doc.guid
) bb,
item_0 i
where bb.end1 = i.guid
and i.id = :item_id
and i.latestrevision like '%m%'
)
and endb.lastaccesstime is not null
"""
_FILENAME_SQL = """
select *
from bi_file
where upper(name) like :name_pattern
and lastaccesstime is not null
order by lastaccesstime desc nulls last
"""
@classmethod
def supports(cls, query: str, agent) -> bool:
_ = agent
return bool(cls.extract_material_no(query))
@classmethod
def extract_material_no(cls, query: str) -> str | None:
text = str(query or "").strip().upper()
if not text:
return None
explicit = cls._EXPLICIT_LABEL_PATTERN.search(text)
if explicit:
return explicit.group(1).strip().upper()
direct_match = cls._MATERIAL_PATTERN.fullmatch(text)
if direct_match:
return direct_match.group(0).upper()
for match in cls._MATERIAL_PATTERN.finditer(text):
candidate = match.group(0).upper()
if any(ch.isalpha() for ch in candidate) and any(ch.isdigit() for ch in candidate):
return candidate
return None
@staticmethod
def _get_connect_kwargs() -> dict:
dsn = (os.getenv("PLM_ORACLE_DSN") or "").strip()
host = (os.getenv("PLM_ORACLE_HOST") or "192.168.0.11").strip()
port = int((os.getenv("PLM_ORACLE_PORT") or "1521").strip())
service_name = (os.getenv("PLM_ORACLE_SERVICE_NAME") or "").strip()
sid = (os.getenv("PLM_ORACLE_SID") or "orcl").strip()
kwargs = {
"user": (os.getenv("PLM_ORACLE_USERNAME") or "PLM").strip(),
"password": (os.getenv("PLM_ORACLE_PASSWORD") or "PLM").strip(),
}
if dsn:
kwargs["dsn"] = dsn
return kwargs
import oracledb
if service_name:
kwargs["dsn"] = oracledb.makedsn(host, port, service_name=service_name)
else:
kwargs["dsn"] = oracledb.makedsn(host, port, sid=sid)
return kwargs
@classmethod
def _connect(cls):
try:
import oracledb
except ImportError as exc:
raise RuntimeError("oracledb 未安装,无法连接 PLM Oracle") from exc
oracle_client_dir = Text2SQLService._get_oracle_client_dir()
Text2SQLService._prepare_oracle_runtime_env(oracle_client_dir)
Text2SQLService._init_oracle_client(oracledb)
return oracledb.connect(**cls._get_connect_kwargs())
@classmethod
def _execute_query(cls, sql: str, **params) -> tuple[list[str], list[tuple]]:
connection = cls._connect()
cursor = connection.cursor()
try:
cursor.execute(sql, params)
columns = [col[0] for col in cursor.description] if cursor.description else []
rows = cursor.fetchmany(cls._MAX_RESULT_ROWS + 1)
return columns, rows
finally:
try:
cursor.close()
finally:
connection.close()
@classmethod
def _query_files(cls, material_no: str) -> tuple[list[str], list[tuple], str]:
try:
columns, rows = cls._execute_query(cls._RELATIONAL_SQL, item_id=material_no)
if rows:
return columns, rows, "relational"
except Exception as exc:
if current_app:
current_app.logger.warning("[plm-oracle] relational query failed for %s: %s", material_no, exc)
columns, rows = cls._execute_query(
cls._FILENAME_SQL,
name_pattern=f"{material_no.upper()}%",
)
return columns, rows, "filename_fallback"
@staticmethod
def _format_datetime(value) -> str:
if value is None:
return "-"
if isinstance(value, datetime):
return value.strftime("%Y-%m-%d %H:%M:%S")
return str(value)
@staticmethod
def _format_size(value) -> str:
if value in (None, ""):
return "-"
try:
size = int(value)
except (TypeError, ValueError):
return str(value)
if size < 1024:
return f"{size} B"
if size < 1024 * 1024:
return f"{size / 1024:.1f} KB"
return f"{size / 1024 / 1024:.2f} MB"
@classmethod
def _build_plm_share_path(cls, storage_id, file_path, file_id: str) -> str:
parts = [cls._PLM_PREVIEW_SHARE_ROOT.rstrip("\\/")]
for value in (storage_id, file_path, file_id):
text = str(value or "").strip()
if not text:
continue
parts.append(text.replace("/", "\\").strip("\\"))
return "\\".join(part for part in parts if part)
@classmethod
def _render_file_name(cls, row: tuple, index_map: dict[str, int]) -> str:
def raw(column_name: str):
idx = index_map.get(column_name.upper())
if idx is None or idx >= len(row):
return None
value = row[idx]
return None if value in (None, "") else value
file_name = str(raw("NAME") or "").strip()
if not file_name:
return "-"
storage_id = raw("STORAGEID")
file_path = raw("FILEPATH")
file_id = str(raw("ID") or "").strip()
if not storage_id or file_path is None or not file_id:
return escape(file_name)
share_path = cls._build_plm_share_path(storage_id, file_path, file_id)
preview_href = f"#plm-preview?name={quote(file_name, safe='')}&url={quote(share_path, safe='')}"
return f'<a href="{preview_href}">{escape(file_name)}</a>'
@staticmethod
def _escape_markdown_cell(value: str) -> str:
return str(value).replace("|", r"\|").replace("\r", " ").replace("\n", "<br>")
@staticmethod
def _escape_html_text(value) -> str:
return escape(str(value), quote=True).replace("\r", " ").replace("\n", "<br>")
@classmethod
def _render_column_value(cls, row: tuple, column_name: str, index_map: dict[str, int]) -> str:
idx = index_map.get(column_name.upper())
if idx is None or idx >= len(row):
return "-"
value = row[idx]
if value in (None, ""):
return "-"
upper_name = column_name.upper()
if upper_name in {"CREATETIME", "LASTACCESSTIME"}:
return cls._format_datetime(value)
if upper_name == "FILESIZE":
return cls._format_size(value)
if upper_name == "NAME":
return cls._render_file_name(row, index_map)
return str(value)
@classmethod
def _build_record_summary(cls, row: tuple, index_map: dict[str, int], row_no: int) -> str:
parts = [f"记录 {row_no}"]
for column_name in cls._SUMMARY_COLUMNS:
if column_name.upper() not in index_map:
continue
rendered = cls._render_column_value(row, column_name, index_map)
label = {
"NAME": "文件名",
"EXTENTIONNAME": "扩展名",
"FILETYPE": "文件类型",
"FILESIZE": "文件大小",
"RELATIVEPATH": "相对路径",
"LASTACCESSTIME": "最后访问时间",
}.get(column_name.upper(), column_name)
if column_name.upper() == "NAME":
parts.append(f"{label}: {rendered}")
else:
parts.append(f"{label}: {cls._escape_html_text(rendered)}")
return " | ".join(parts)
@classmethod
def _build_record_detail_html(cls, row: tuple, columns: list[str], index_map: dict[str, int], row_no: int) -> str:
rows_html = []
for column_name in columns:
rendered_value = cls._render_column_value(row, column_name, index_map)
safe_value = rendered_value if column_name.upper() == "NAME" else cls._escape_html_text(rendered_value)
rows_html.append(
"<tr>"
f"<th style=\"padding:6px 10px;text-align:left;border:1px solid #d1d5db;background:#f8fafc;white-space:nowrap;\">{cls._escape_html_text(column_name)}</th>"
f"<td style=\"padding:6px 10px;border:1px solid #d1d5db;word-break:break-all;\">{safe_value}</td>"
"</tr>"
)
summary_html = cls._build_record_summary(row, index_map, row_no)
return (
"<details style=\"margin:12px 0;border:1px solid #e5e7eb;border-radius:8px;padding:8px 12px;background:#ffffff;\">"
f"<summary style=\"cursor:pointer;font-weight:600;\">{summary_html}</summary>"
"<div style=\"margin-top:10px;overflow:auto;\">"
"<table style=\"width:100%;border-collapse:collapse;font-size:13px;\">"
"<thead><tr>"
"<th style=\"padding:6px 10px;text-align:left;border:1px solid #d1d5db;background:#f1f5f9;width:220px;\">字段</th>"
"<th style=\"padding:6px 10px;text-align:left;border:1px solid #d1d5db;background:#f1f5f9;\">值</th>"
"</tr></thead>"
f"<tbody>{''.join(rows_html)}</tbody>"
"</table>"
"</div>"
"</details>"
)
@classmethod
def _build_answer(cls, material_no: str, columns: list[str], rows: list[tuple]) -> str:
if not rows:
return f"已在 PLM 中查询料号 `{material_no}`,未找到符合条件的相关资料。"
overflow = len(rows) > cls._MAX_RESULT_ROWS
visible_rows = rows[: cls._MAX_RESULT_ROWS]
index_map = {name.upper(): idx for idx, name in enumerate(columns)}
lines = [
f"已在 PLM 中查询到料号 `{material_no}` 的相关资料,共返回 {len(visible_rows)} 条记录"
+ ("(仅展示前 50 条)" if overflow else "。"),
"",
"以下结果支持点击单条记录展开,展开后按数据库原始字段顺序展示完整数据:",
]
for idx, row in enumerate(visible_rows, start=1):
lines.extend(["", cls._build_record_detail_html(row, columns, index_map, idx)])
if overflow:
lines.extend(["", "如需查看更多结果,请进一步限定料号或资料范围。"])
return "\n".join(lines)
@classmethod
def stream_chat(cls, query: str, user, agent, conversation_id: str | None = None, session_id: str | None = None):
start_time = time.time()
final_conversation_id = conversation_id or f"plm_{int(time.time())}"
material_no = cls.extract_material_no(query)
try:
if not material_no:
raise RuntimeError("未识别到有效料号,请输入类似 F3-A12M290000019 的料号。")
yield f"data: {json.dumps({'event': 'message', 'answer': f'已识别料号 `{material_no}`,正在查询 PLM 资料,请稍候...\\n'}, ensure_ascii=False)}\n\n"
columns, rows, query_mode = cls._query_files(material_no)
answer = cls._build_answer(material_no, columns, rows)
latency = int((time.time() - start_time) * 1000)
chat_log_id = None
try:
chat_log = ChatLog(
user_id=user.id,
agent_id=agent.id,
conversation_id=final_conversation_id,
session_id=session_id,
query=query,
answer=answer,
tokens_used=0,
latency=latency,
payload={
"material_no": material_no,
"row_count": min(len(rows), cls._MAX_RESULT_ROWS),
"query_mode": query_mode,
},
)
db.session.add(chat_log)
db.session.commit()
chat_log_id = chat_log.id
except Exception as exc:
if current_app:
current_app.logger.error("Failed to log PLM chat: %s", exc)
db.session.rollback()
end_data = {
"event": "message_end",
"answer": answer,
"replace_answer": True,
"chat_log_id": chat_log_id,
"conversation_id": final_conversation_id,
}
yield f"data: {json.dumps(end_data, ensure_ascii=False)}\n\n"
except Exception as exc:
if current_app:
current_app.logger.exception("[plm-oracle] stream_chat failed query=%s", query)
error_data = {
"event": "error",
"message": str(exc) or "PLM 查询失败",
"conversation_id": final_conversation_id,
}
yield f"data: {json.dumps(error_data, ensure_ascii=False)}\n\n"
File diff suppressed because it is too large. Load diff
@@ -1,2 +1,97 @@
"""企微回调加解密(Wave 4 自 wecom_crypto.py 迁入)。"""
from app.services import wecom_crypto # noqa: F401
"""
backend/app/services/integrations/wecom/crypto.py
用途:企业微信回调加解密工具(兼容 WXBizMsgCrypt 布局)。
依赖:pycryptodome AES。
逻辑:user/auth 企微回调验签、解密 Encrypt 字段时调用。
"""
from __future__ import annotations
import base64
import hashlib
import random
import struct
from typing import Optional
from Crypto.Cipher import AES
def sha1_hex(parts: list[str]) -> str:
merged = ''.join(sorted([str(p) for p in parts if p is not None]))
return hashlib.sha1(merged.encode('utf-8')).hexdigest()
def _pkcs7_pad(data: bytes, block_size: int = 32) -> bytes:
pad_len = block_size - (len(data) % block_size)
return data + bytes([pad_len] * pad_len)
def _pkcs7_unpad(data: bytes) -> bytes:
if not data:
return data
pad_len = data[-1]
if pad_len < 1 or pad_len > 32:
raise ValueError('invalid pkcs7 padding')
if data[-pad_len:] != bytes([pad_len] * pad_len):
raise ValueError('invalid pkcs7 padding tail')
return data[:-pad_len]
def _aes_key_from_encoding_key(encoding_aes_key_b64: str) -> bytes:
raw = (encoding_aes_key_b64 or '').strip()
key = base64.b64decode(raw + '=')
if len(key) != 32:
raise ValueError('EncodingAESKey must decode to 32 bytes')
return key
def encrypt_wecom_aes(plain_text: str, encoding_aes_key_b64: str, corp_id: str) -> str:
"""
Encrypt plain text to base64 ciphertext (for tests / optional outbound use).
"""
aes_key = _aes_key_from_encoding_key(encoding_aes_key_b64)
iv = aes_key[:16]
random_bytes = bytes(random.randint(0, 255) for _ in range(16))
msg_bytes = plain_text.encode('utf-8')
pack = (
random_bytes
+ struct.pack('>I', len(msg_bytes))
+ msg_bytes
+ corp_id.encode('utf-8')
)
padded = _pkcs7_pad(pack, 32)
cipher = AES.new(aes_key, AES.MODE_CBC, iv)
encrypted = cipher.encrypt(padded)
return base64.b64encode(encrypted).decode('ascii')
def decrypt_wecom_aes(cipher_b64: str, encoding_aes_key_b64: str, corp_id: str) -> str:
aes_key = _aes_key_from_encoding_key(encoding_aes_key_b64)
iv = aes_key[:16]
cipher_bytes = base64.b64decode(cipher_b64)
cipher = AES.new(aes_key, AES.MODE_CBC, iv)
plain_padded = cipher.decrypt(cipher_bytes)
plain = _pkcs7_unpad(plain_padded)
content = plain[16:]
if len(content) < 4:
raise ValueError('decrypted payload too short')
xml_len = struct.unpack('>I', content[:4])[0]
xml_bytes = content[4:4 + xml_len]
tail = content[4 + xml_len:]
if tail.decode('utf-8', errors='strict') != corp_id:
raise ValueError('corp_id mismatch after decrypt')
return xml_bytes.decode('utf-8')
def extract_encrypt_field(xml_body: str) -> Optional[str]:
if not xml_body:
return None
import re
m = re.search(r'<Encrypt><!\[CDATA\[(.*?)\]\]></Encrypt>', xml_body, re.DOTALL)
if m:
return m.group(1).strip()
m2 = re.search(r'<Encrypt>(.*?)</Encrypt>', xml_body, re.DOTALL)
if m2:
return m2.group(1).strip()
return None
@@ -1,2 +1,244 @@
"""企微通讯录同步(Wave 4 自 wecom_directory_sync.py 迁入)。"""
from app.services import wecom_directory_sync # noqa: F401
"""
backend/app/services/integrations/wecom/directory_sync.py
用途:从企业微信通讯录拉取成员,按工号回填本地 users.wecom_userid。
依赖:Flask current_app、SQLAlchemy db、wecom.notify._get_access_token、User 模型。
逻辑:供 admin API 与 scripts/sync_wecom_userid_by_employee_id.py 共用;支持 dry-run 与 apply。
"""
from __future__ import annotations
from typing import Any
import requests
from flask import current_app
from app import db
from app.models import User
from app.services.integrations.wecom.notify import _get_access_token
_PREVIEW_LIMIT = 20
def _clean_str(value) -> str | None:
"""裁剪字符串类取值;空串视为 None。"""
if value is None:
return None
text = str(value).strip()
return text or None
def _extract_wecom_extattr_value(wecom_user: dict, key: str) -> str | None:
"""
从企微成员 extattr.attrs 中读取指定扩展字段。
@param wecom_user: user/list 返回的成员 dict
@param key: 扩展属性名
Returns:
字段文本或 None
"""
extattr = wecom_user.get('extattr') or {}
attrs = extattr.get('attrs') if isinstance(extattr, dict) else None
if not isinstance(attrs, list):
return None
for attr in attrs:
if not isinstance(attr, dict):
continue
if _clean_str(attr.get('name')) != key:
continue
raw = attr.get('value')
if isinstance(raw, dict):
raw = raw.get('text') or raw.get('web') or raw.get('value')
return _clean_str(raw)
return None
def extract_employee_id_from_wecom_user(wecom_user: dict, employee_id_source: str) -> str | None:
"""
按 WECOM_EMPLOYEE_ID_SOURCE 从企微成员解析工号。
核心逻辑:userid / extattr:xxx / 其它字段名,与 user.py _extract_wecom_identity 对齐。
"""
userid = _clean_str(wecom_user.get('userid'))
source = _clean_str(employee_id_source) or 'userid'
if source == 'userid':
return userid
if source.startswith('extattr:'):
return _extract_wecom_extattr_value(wecom_user, source.split(':', 1)[1])
return _clean_str(wecom_user.get(source))
def fetch_wecom_departments(access_token: str) -> list[dict[str, Any]]:
"""
拉取企业微信部门列表。
Raises:
RuntimeError: API 失败
"""
resp = requests.get(
'https://qyapi.weixin.qq.com/cgi-bin/department/list',
params={'access_token': access_token},
timeout=15,
)
data = resp.json() or {}
if data.get('errcode') != 0:
raise RuntimeError(f'department/list failed: {data}')
departments = data.get('department') or []
if not isinstance(departments, list):
return []
return [item for item in departments if isinstance(item, dict)]
def fetch_wecom_users_in_department(access_token: str, department_id: int) -> list[dict[str, Any]]:
"""
拉取指定部门(含子部门)成员简要列表。
@param department_id: 企微部门 ID
Returns:
user/list 返回的 userlist
"""
resp = requests.get(
'https://qyapi.weixin.qq.com/cgi-bin/user/list',
params={
'access_token': access_token,
'department_id': department_id,
'fetch_child': 1,
},
timeout=30,
)
data = resp.json() or {}
if data.get('errcode') != 0:
raise RuntimeError(f'user/list failed department_id={department_id}: {data}')
userlist = data.get('userlist') or []
if not isinstance(userlist, list):
return []
return [item for item in userlist if isinstance(item, dict)]
def collect_wecom_users(access_token: str, department_ids: list[int]) -> dict[str, dict[str, Any]]:
"""
汇总多个部门成员,按 wecom_userid 去重。
Returns:
key=userid, value=成员 dict
"""
merged: dict[str, dict[str, Any]] = {}
for dept_id in department_ids:
for user in fetch_wecom_users_in_department(access_token, dept_id):
userid = _clean_str(user.get('userid'))
if userid:
merged[userid] = user
return merged
def sync_wecom_userids_from_directory(*, apply: bool, department_id: int | None = None) -> dict[str, Any]:
"""
执行工号 → wecom_userid 同步。
核心逻辑:拉企微成员 → 解析 employee_id → 匹配本地 User → dry-run 或写 wecom_userid/wecom_unionid。
@param apply: True 时提交数据库;存在 conflicts 时不写入
@param department_id: 指定根部门 ID;None 时使用全部部门
Returns:
统计摘要 dict(含 conflicts、pending_updates 预览)
"""
if not current_app.config.get('WECOM_CORP_ID') or not current_app.config.get('WECOM_SECRET'):
raise RuntimeError('WECOM_CORP_ID / WECOM_SECRET is not configured')
employee_id_source = _clean_str(current_app.config.get('WECOM_EMPLOYEE_ID_SOURCE')) or 'userid'
token = _get_access_token()
if department_id is not None:
department_ids = [department_id]
else:
departments = fetch_wecom_departments(token)
department_ids = [int(item.get('id')) for item in departments if item.get('id') is not None]
if not department_ids:
department_ids = [1]
wecom_users = collect_wecom_users(token, department_ids)
summary: dict[str, Any] = {
'apply': apply,
'employee_id_source': employee_id_source,
'department_ids': department_ids,
'wecom_users': len(wecom_users),
'wecom_without_employee_id': 0,
'local_matched': 0,
'would_update': 0,
'updated': 0,
'already_bound': 0,
'local_missing': 0,
'conflicts': [],
'missing_samples': [],
'pending_updates': [],
}
for wecom_user in wecom_users.values():
wecom_userid = _clean_str(wecom_user.get('userid'))
wecom_unionid = _clean_str(wecom_user.get('unionid'))
employee_id = extract_employee_id_from_wecom_user(wecom_user, employee_id_source)
if not employee_id:
summary['wecom_without_employee_id'] += 1
if len(summary['missing_samples']) < _PREVIEW_LIMIT:
summary['missing_samples'].append(
{'wecom_userid': wecom_userid, 'name': _clean_str(wecom_user.get('name'))}
)
continue
local_user = db.session.query(User).filter(User.employee_id == employee_id).first()
if not local_user:
summary['local_missing'] += 1
continue
summary['local_matched'] += 1
if local_user.wecom_userid == wecom_userid:
summary['already_bound'] += 1
continue
conflict = None
if local_user.wecom_userid and local_user.wecom_userid != wecom_userid:
conflict = {
'employee_id': employee_id,
'username': local_user.username,
'old_wecom_userid': local_user.wecom_userid,
'new_wecom_userid': wecom_userid,
}
else:
occupied = (
db.session.query(User)
.filter(User.wecom_userid == wecom_userid, User.id != local_user.id)
.first()
)
if occupied:
conflict = {
'employee_id': employee_id,
'username': local_user.username,
'new_wecom_userid': wecom_userid,
'occupied_by_user_id': occupied.id,
'occupied_by_username': occupied.username,
}
if conflict:
summary['conflicts'].append(conflict)
continue
summary['would_update'] += 1
if len(summary['pending_updates']) < _PREVIEW_LIMIT:
summary['pending_updates'].append(
{
'employee_id': employee_id,
'username': local_user.username,
'wecom_userid': wecom_userid,
'name': _clean_str(wecom_user.get('name')),
}
)
if apply:
local_user.wecom_userid = wecom_userid
if wecom_unionid:
local_user.wecom_unionid = wecom_unionid
summary['updated'] += 1
if summary['conflicts'] and apply:
db.session.rollback()
raise RuntimeError('Conflicts detected; resolve manually before apply')
if apply and summary['updated'] > 0:
db.session.commit()
elif apply:
db.session.rollback()
return summary
@@ -1,2 +1,264 @@
"""企微消息通知(Wave 4 自 wecom_notify.py 迁入)。"""
from app.services import wecom_notify # noqa: F401
"""
backend/app/services/integrations/wecom/notify.py
用途:企业微信消息通知适配(文本卡片、文件、事件消息)。
依赖:requests、Flask current_app、User / WecomNotifyAudit 模型。
逻辑:排程完成、权限申请、培训提醒等业务事件调用本模块发送企微消息并写审计。
"""
from __future__ import annotations
from datetime import datetime, timedelta
from io import BytesIO
from urllib.parse import urlencode, urlparse, parse_qsl, urlunparse
import uuid
import requests
from flask import current_app
from app import db
from app.models import User, WecomNotifyAudit
_TOKEN_CACHE = {
'token': None,
'expires_at': None,
}
def _get_enabled_events() -> set[str]:
raw = current_app.config.get('WECOM_NOTIFY_EVENTS', '')
if isinstance(raw, str):
return {x.strip() for x in raw.split(',') if x.strip()}
if isinstance(raw, (list, tuple, set)):
return {str(x).strip() for x in raw if str(x).strip()}
return set()
def _get_notify_base_url() -> str:
"""
解析企微 textcard 跳转基地址(用户点击入口,须为浏览器可访问的 HTTPS 公网域名)。
核心逻辑:优先 WECOM_PUBLIC_BASE_URL,其次 HXOPS_PUBLIC_BASE_URL;
WECOM_NOTIFY_BASE_URL 仅作历史内网/端口兼容兜底。
Returns:
去掉尾斜杠的基地址;均未配置时返回空字符串。
"""
for key in ('WECOM_PUBLIC_BASE_URL', 'HXOPS_PUBLIC_BASE_URL', 'WECOM_NOTIFY_BASE_URL'):
raw = current_app.config.get(key)
if isinstance(raw, str) and raw.strip():
return raw.strip().rstrip('/')
return ''
def _build_jump_url(path: str, trace_id: str, params: dict | None = None) -> str:
base = _get_notify_base_url()
if not base:
return ''
base = base.rstrip('/')
if not path.startswith('/'):
path = f'/{path}'
merged = {'wecom_trace': trace_id}
if params:
merged.update({k: v for k, v in params.items() if v is not None})
return f'{base}{path}?{urlencode(merged)}'
def _get_access_token() -> str:
now = datetime.utcnow()
token = _TOKEN_CACHE.get('token')
expires_at = _TOKEN_CACHE.get('expires_at')
if token and expires_at and now < expires_at:
return token
corp_id = current_app.config.get('WECOM_CORP_ID')
secret = current_app.config.get('WECOM_SECRET')
resp = requests.get(
'https://qyapi.weixin.qq.com/cgi-bin/gettoken',
params={'corpid': corp_id, 'corpsecret': secret},
timeout=8,
)
data = resp.json()
if data.get('errcode') != 0 or not data.get('access_token'):
raise RuntimeError(f"Failed to fetch WeCom token: {data}")
_TOKEN_CACHE['token'] = data['access_token']
_TOKEN_CACHE['expires_at'] = now + timedelta(seconds=max(int(data.get('expires_in', 7200)) - 120, 60))
return data['access_token']
def _create_audit(
event_type: str,
user: User,
title: str,
content: str,
trace_id: str,
) -> WecomNotifyAudit:
audit = WecomNotifyAudit(
event_type=event_type,
status='failed',
trace_id=trace_id,
user_id=user.id if user else None,
username=user.username if user else None,
wecom_userid=user.wecom_userid if user else None,
title=title,
content=content,
)
db.session.add(audit)
return audit
def upload_wecom_temp_media(file_data: bytes, filename: str) -> str:
token = _get_access_token()
url = (
f'https://qyapi.weixin.qq.com/cgi-bin/media/upload'
f'?access_token={token}&type=file'
)
resp = requests.post(
url,
files={'media': (filename, BytesIO(file_data), 'application/octet-stream')},
timeout=30,
)
data = resp.json()
if data.get('errcode', 0) != 0 or not data.get('media_id'):
raise RuntimeError(f"WeCom media upload failed: {data}")
return data['media_id']
def send_wecom_file_message(wecom_userid: str, media_id: str) -> dict:
token = _get_access_token()
payload = {
'touser': wecom_userid,
'msgtype': 'file',
'agentid': int(current_app.config.get('WECOM_AGENT_ID')),
'file': {'media_id': media_id},
'safe': 0,
}
resp = requests.post(
'https://qyapi.weixin.qq.com/cgi-bin/message/send',
params={'access_token': token},
json=payload,
timeout=8,
)
return resp.json()
def send_wecom_textcard_message(
wecom_userid: str,
title: str,
description: str,
jump_url: str,
) -> dict:
token = _get_access_token()
payload = {
'touser': wecom_userid,
'msgtype': 'textcard',
'agentid': int(current_app.config.get('WECOM_AGENT_ID')),
'textcard': {
'title': title[:120],
'description': (description or '')[:1024],
'url': jump_url or _get_notify_base_url() or 'https://work.weixin.qq.com',
'btntxt': '查看详情',
},
'safe': 0,
}
resp = requests.post(
'https://qyapi.weixin.qq.com/cgi-bin/message/send',
params={'access_token': token},
json=payload,
timeout=8,
)
return resp.json()
def _append_query_param(url: str, key: str, value: str) -> str:
"""
向 URL 追加单个 query 参数,保留已有参数。
@param url: 原始 URL
@param key: 参数名
@param value: 参数值
Returns:
追加参数后的 URL
"""
parsed = urlparse(url)
pairs = parse_qsl(parsed.query, keep_blank_values=True)
pairs.append((key, value))
return urlunparse(parsed._replace(query=urlencode(pairs)))
def send_wecom_event_message(
*,
event_type: str,
user: User,
title: str,
content: str,
jump_path: str = '/workspace',
jump_params: dict | None = None,
jump_url: str | None = None,
wecom_userid: str | None = None,
) -> dict:
"""
发送企微事件 textcard;可选 jump_url 覆盖默认跳转(如密码重置外链)。
核心逻辑:默认使用 `user.wecom_userid`;合同付款第二、三轮可传入 OA HrmResource.id
作为 wecom_userid,因为该 id 同时是企业微信 userid。
Args:
event_type: 通知事件开关名。
user: 审计关联的系统用户,可为收件人在 HXOPS 中的映射账号。
title: 卡片标题。
content: 卡片正文。
jump_path: 站内跳转路径。
jump_params: 跳转查询参数。
jump_url: 若传入则覆盖默认拼接的跳转地址。
wecom_userid: 可选,显式指定企微 touser;空则回退 user.wecom_userid。
Returns:
含 ok / trace_id 的发送结果字典。
"""
trace_id = uuid.uuid4().hex
audit = _create_audit(event_type, user, title, content, trace_id)
target_userid = str(wecom_userid or (user.wecom_userid if user else "") or "").strip()
if target_userid:
audit.wecom_userid = target_userid
if not current_app.config.get('WECOM_NOTIFY_ENABLED', True):
audit.error_code = 'NOTIFY_DISABLED'
audit.error_message = 'WECOM_NOTIFY_ENABLED=false'
return {'ok': False, 'trace_id': trace_id, 'reason': 'notify_disabled'}
if event_type not in _get_enabled_events():
audit.error_code = 'EVENT_DISABLED'
audit.error_message = f'event {event_type} disabled'
return {'ok': False, 'trace_id': trace_id, 'reason': 'event_disabled'}
if not target_userid:
audit.error_code = 'WECOM_USER_UNBOUND'
audit.error_message = 'user has no wecom_userid'
return {'ok': False, 'trace_id': trace_id, 'reason': 'user_unbound'}
try:
if jump_url:
final_jump_url = _append_query_param(jump_url, 'wecom_trace', trace_id)
else:
final_jump_url = _build_jump_url(jump_path, trace_id, jump_params)
audit.jump_url = final_jump_url
data = send_wecom_textcard_message(target_userid, title, content, final_jump_url)
if data.get('errcode') == 0:
audit.status = 'sent'
return {'ok': True, 'trace_id': trace_id}
audit.error_code = str(data.get('errcode'))
audit.error_message = str(data.get('errmsg', 'unknown error'))[:255]
return {'ok': False, 'trace_id': trace_id, 'reason': 'send_failed', 'raw': data}
except Exception as exc:
audit.error_code = 'EXCEPTION'
audit.error_message = str(exc)[:255]
return {'ok': False, 'trace_id': trace_id, 'reason': 'exception'}
def mark_wecom_message_opened(trace_id: str) -> bool:
if not trace_id:
return False
row = db.session.query(WecomNotifyAudit).filter_by(trace_id=trace_id).first()
if not row:
return False
if not row.opened_at:
row.opened_at = datetime.utcnow()
return True
@@ -4,9 +4,11 @@ backend/app/services/lean_training_push_service.py
用途:按"每周任务数量"分批推送精益培训视频给受训对象并发送企微通知,记录每轮推送日志;
同时承担"每周自动滚动创建当周任务"与"推送成功后立即提醒已延期人员"两项周任务规则。
依赖:LeanTrainingWeeklyTask/LeanTrainingVideoPushLog/LeanTrainingReminder/User、lean_training_service(受训对象/当周边界)、lean_training_reminder_service(企微发送模板/延期提醒)、wecom_notify。
逻辑:以 task.pushed_video_count 为游标,按视频冻结顺序每次取 weekly_count 个视频;员工端展示已推送前缀;
逻辑:以 task.pushed_video_count 为游标,每次从游标向后取 weekly_count 个"未被任何任务推送过"的视频(跨任务
按已推送前缀并集去重,推过的视频绝不重复推);员工端展示已推送前缀;
企微 event_key 按"批次区间"幂等防止重复打扰;每轮执行写入 lean_training_video_push_logs 便于管理端查看失败明细;
排程入口每周一 09:00 先自动滚动创建当周任务(复制最近一期配置,无需人工维护),再对各任务推进一批推送。
排程入口每周一 09:00 先自动滚动创建当周任务(复制最近一期配置并自动追加配置新增视频,无需人工维护;
视频库全部推完且无新增视频时暂停滚动、不创建内容重复的新一期),再对各任务推进一批推送。
"""
from __future__ import annotations
@@ -22,7 +24,13 @@ from app.services.lean_training_reminder_service import (
notify_overdue_users_after_push,
send_initial_target_notifications,
)
from app.services.lean_training_service import _current_week_bounds, target_user_ids_for_task
from app.services.lean_training_service import (
_already_pushed_resource_ids,
_config_video_resource_ids,
_current_week_bounds,
format_beijing_iso,
target_user_ids_for_task,
)
from app.services.schedule.timezone_util import utc_now_naive
VIDEO_PUSH_EVENT_TYPE = "training_lean_video_push"
@@ -41,7 +49,12 @@ def ensure_current_week_task(*, now: datetime | None = None) -> LeanTrainingWeek
- 模板仅从"严格早于当周"的最近一期已发布任务选取:任务周已支持管理员指定任意自然周,
必须排除未来周任务,避免其(更大游标/不同配置)污染当周滚动进度;
- 模板复制视频冻结列表、每周推送数量与受训对象;推送游标继承模板进度,
保证"推过的视频不重复推",跨周按视频列表顺序连续推进直至全部推完。
保证"推过的视频不重复推",跨周按视频列表顺序连续推进直至全部推完;
- 配置中新增上传、尚未冻结进模板列表的视频按上传时间倒序自动追加到列表末尾:
HR 事后手动勾选补推的进度经游标继承持续生效,每周自动计划从断点继续向后推;
追加只发生在末尾,已推送前缀与游标不变,推过的视频绝不重复推;
- 视频库已全部推完且配置无新增视频时**暂停滚动**:不再创建内容重复的新一期任务
(对应"全部视频推送完成后暂停,不再重复推送"规则);新视频上传后下周一自动恢复创建。
"""
week_start, due_at = _current_week_bounds(now)
week_key = week_start.isoformat()
@@ -55,15 +68,40 @@ def ensure_current_week_task(*, now: datetime | None = None) -> LeanTrainingWeek
).scalars().first()
if not template:
return None
# [RULE] 视频库已全部推完且配置无新增视频时暂停滚动:不再创建内容重复的新一期任务。
# 若继续创建,新一期只会继承同一份已推完的清单,学员端每期显示完全相同的视频、
# 也无可推送的新内容(对应"全部视频推送完成后暂停,不再重复推送"规则);
# 配置上传新视频后,下周一滚动自动恢复创建并只推新视频。
template_video_ids = list(template.video_resource_ids or [])
if template.pushed_video_count >= len(template_video_ids):
template_frozen_ids = {int(resource_id) for resource_id in template_video_ids}
has_new_config_videos = any(
resource.id not in template_frozen_ids
for resource in _config_video_resource_ids(template.config)
)
if not has_new_config_videos:
return None
# [STEP 1] 复制最近一期配置滚动创建当周任务(视频列表沿用冻结顺序,游标继承已推送进度避免重复推送)
video_resource_ids = template_video_ids
# [RULE] 自动追加配置新增视频(上传时间倒序、只追加到末尾):前缀与游标保持对齐,断点续推不重推
frozen_ids = {int(resource_id) for resource_id in video_resource_ids}
video_resource_ids.extend(
resource.id
for resource in sorted(
_config_video_resource_ids(template.config),
key=lambda resource: resource.created_at or datetime.min,
reverse=True,
)
if resource.id not in frozen_ids
)
task = LeanTrainingWeeklyTask(
config_id=template.config_id,
week_key=week_key,
created_by_id=template.created_by_id,
weekly_count=template.weekly_count,
pushed_video_count=template.pushed_video_count,
pushed_video_count=min(template.pushed_video_count, len(video_resource_ids)),
due_at=due_at,
video_resource_ids=list(template.video_resource_ids or []),
video_resource_ids=video_resource_ids,
target_roles=list(template.target_roles or []),
target_user_ids=list(template.target_user_ids or []),
status="published",
@@ -95,7 +133,8 @@ def serialize_push_log(log: LeanTrainingVideoPushLog) -> dict[str, object]:
"status": log.status,
"error_message": log.error_message,
"created_by_id": log.created_by_id,
"created_at": log.created_at.isoformat() if log.created_at else None,
# 展示层转北京时间:管理端"推送记录"直接渲染该字段,UTC 直出会比实际早 8 小时
"created_at": format_beijing_iso(log.created_at),
}
@@ -128,18 +167,36 @@ def push_lean_training_videos(
Returns:
含 status(completed=无待推视频/partial/failed/sent)、batch、counts 与日志字段的 dict。
业务约束:企微发送失败不影响游标前进(员工端已可见视频),失败明细仅记录在日志中。
业务约束:
- 企微发送失败不影响游标前进(员工端已可见视频),失败明细仅记录在日志中;
- 跨任务绝对去重:已被其它周任务推送过的视频不进入本批(游标越过),待推区间全部重复时
游标直接推进到末尾并返回 completed,不发送企微。
"""
task = db.session.get(LeanTrainingWeeklyTask, task_id)
if not task or task.status != "published":
raise ValueError("Lean training weekly task not found")
current = now or utc_now_naive()
# [STEP 1] 计算本批视频:按选择顺序从游标起取 weekly_count 个;无待推视频时视为全部推送完
batch = pending_video_ids(task)[: task.weekly_count]
if not batch:
# [STEP 1] 计算本批视频:按选择顺序从游标向后扫描,取满 weekly_count 个"未被任何任务推送过"的新视频;
# 已被其它任务推送过的视频仅越过(游标同步越过),绝不重复进入批次;无新视频可推时不发企微
candidates = pending_video_ids(task)
if not candidates:
return {"status": "completed", "message": "all videos pushed", "pushed_count": 0}
start_index = task.pushed_video_count
event_key = f"video-push-{start_index}-{start_index + len(batch)}"
already_pushed = _already_pushed_resource_ids(exclude_task_id=task.id)
batch: list[int] = []
consumed = 0
for resource_id in candidates:
if len(batch) >= task.weekly_count:
break
consumed += 1
if int(resource_id) not in already_pushed:
batch.append(resource_id)
if not batch:
# [RULE] 待推区间已全部被其它任务推送过:游标推进到末尾即视为全部推完,不重复推送、不重复打扰
task.pushed_video_count = start_index + consumed
db.session.commit()
return {"status": "completed", "message": "all pending videos already pushed", "pushed_count": 0}
event_key = f"video-push-{start_index}-{start_index + consumed}"
# [STEP 2] 面向全体在职受训对象发送企微通知;event_key 按批次区间幂等,同批重推不重复打扰
recipients = db.session.execute(
select(User).where(User.id.in_(target_user_ids_for_task(task)), User.status == "active")
@@ -159,8 +216,8 @@ def push_lean_training_videos(
counts[result] = counts.get(result, 0) + 1
if result == "failed" and recipient.id not in {line.split(":")[0] for line in failure_details}:
failure_details.append(f"{recipient.id}:{recipient.real_name or recipient.username}")
# [STEP 3] 游标前进(企微失败不回退,员工端已可见该批视频),并落盘本轮推送日志
task.pushed_video_count = start_index + len(batch)
# [STEP 3] 游标前进(越过跳过的重复视频与本批新视频;企微失败不回退,员工端已可见该批视频),并落盘本轮推送日志
task.pushed_video_count = start_index + consumed
status = "sent" if counts["failed"] == 0 else ("failed" if counts["sent"] == 0 and counts["skipped"] == 0 else "partial")
log = LeanTrainingVideoPushLog(
weekly_task_id=task.id,
@@ -11,14 +11,16 @@ from __future__ import annotations
import uuid
from datetime import datetime, timezone
from flask import current_app
from sqlalchemy import select
from sqlalchemy.exc import IntegrityError
from app.extensions import db
from app.models import LeanTrainingCompletion, LeanTrainingReminder, LeanTrainingWeeklyTask, User
from app.services.lean_training_service import target_user_ids_for_task
from app.services.wecom_notify import send_wecom_event_message
from app.services.lean_training_service import (
resolve_lean_training_jump_agent_id,
target_user_ids_for_task,
)
from app.services.integrations.wecom.notify import send_wecom_event_message
from app.services.schedule.timezone_util import resolve_schedule_tzinfo, utc_now_naive
@@ -52,10 +54,11 @@ def _send_reminder(
db.session.flush()
except IntegrityError:
return "skipped"
# [STEP] 企微卡片跳转地址:指向员工培训聊天页(默认 agent 27,content_profile=training),
# [STEP] 企微卡片跳转地址:动态解析各环境「员工培训」聊天页(content_profile=training),
# 由前端 TrainingWorkspacePanel 消费 training_type=lean_management 自动展开精益页签;
# agent id 走配置(app_settings/env 覆盖),便于多环境调整,避免硬编码。
jump_agent_id = int(current_app.config.get("WECOM_LEAN_TRAINING_JUMP_AGENT_ID") or 27)
# 支持 WECOM_LEAN_TRAINING_JUMP_AGENT_ID 显式覆盖,动态解析失败回退历史默认 27([FIX] 2026-09-18
# 历史固定默认 27 在部分环境实为其它 Agent,导致卡片落地后无法定位精益模块)。
jump_agent_id = resolve_lean_training_jump_agent_id()
result = send_wecom_event_message(
event_type=event_type,
user=recipient,
+217 -15
View File
@@ -10,24 +10,121 @@ backend/app/services/lean_training_service.py
from __future__ import annotations
from datetime import date, datetime, time, timedelta, timezone
from io import BytesIO
from typing import Any
from openpyxl import Workbook
from sqlalchemy import func, or_, select
from app.core.errors import NotFoundError, ValidationError
from app.extensions import db
from app.models import (
Agent,
LeanTrainingCompletion,
LeanTrainingWeeklyTask,
TrainingConfig,
TrainingConfigResource,
User,
)
from app.services.minio_service import minio_service
from app.services.integrations.minio import minio_service
from app.services.schedule.timezone_util import resolve_schedule_tzinfo, to_utc_naive, utc_now_naive
LEAN_TRAINING_TYPE = "lean_management"
MIN_SUMMARY_LENGTH = 50
# 精益提醒/推送企微卡片跳转 Agent 的历史默认值;仅当动态解析失败(系统内无培训 Agent)时兜底
LEGACY_LEAN_JUMP_AGENT_ID = 27
def resolve_lean_training_jump_agent_id() -> int:
"""
解析精益提醒/推送企微卡片落地聊天页的「员工培训」Agent ID。
用途:卡片须跳 /chat/<培训agent>?training_type=lean_management,由前端 TrainingWorkspacePanel
自动展开精益页签;前端仅在目标 Agent 是培训 Agent 时才消费深链参数,
因此 Agent ID 指错环境会导致卡片落地后无法定位精益模块。
核心逻辑:各环境培训 Agent ID 不同,禁止依赖固定值——优先取 WECOM_LEAN_TRAINING_JUMP_AGENT_ID
显式配置覆盖,否则在启用 Agent 中按 handler_config.content_profile='training' 动态解析;
均不可用时回退历史默认 27 保持兼容。
Returns:
培训 Agent ID。
"""
from flask import current_app
override = int(current_app.config.get("WECOM_LEAN_TRAINING_JUMP_AGENT_ID") or 0)
if override > 0:
return override
agents = db.session.execute(
select(Agent).where(Agent.is_active.is_(True)).order_by(Agent.sort_order, Agent.id)
).scalars().all()
for agent in agents:
handler_config = agent.handler_config if isinstance(agent.handler_config, dict) else {}
if str(handler_config.get("content_profile") or "").strip() == "training":
return int(agent.id)
return LEGACY_LEAN_JUMP_AGENT_ID
def _format_dashboard_datetime(value: str | None) -> str:
"""将看板 ISO 时间统一为页面展示的年月日时分格式。"""
text = str(value or "").strip()
return text[:16].replace("T", " ") if text else ""
def format_beijing_iso(value: datetime | str | None) -> str | None:
"""
将存储的 UTC 时间转换为北京时间 ISO 字符串,供页面/Excel 展示。
用途:培训模块数据库统一存 UTC naive(观看/完成/截止时间),而业务要求所有对外展示为北京时间;
此前序列化直接输出 UTC 导致页面显示比实际早 8 小时(如 18:47 显示 10:47)。
Args:
value: UTC naive datetime 或 ISO 字符串;naive 按 UTC 处理,带时区则先归一到绝对时间;
字符串无法解析时原样返回,避免历史脏数据导致展示层报错。
Returns:
带 +08:00 偏移的 ISO 字符串(如 2026-09-22T18:47:00+08:00,前端 slice(0,16) 即得北京时间);入参为空返回 None。
业务约束:仅用于序列化输出层,禁止将转换结果写回数据库——存储与服务端比较(超期判定等)仍一律 UTC。
"""
if value is None or (isinstance(value, str) and not value.strip()):
return None
if isinstance(value, str):
try:
parsed = datetime.fromisoformat(value.strip())
except ValueError:
return value.strip()
else:
parsed = value
if parsed.tzinfo is None:
parsed = parsed.replace(tzinfo=timezone.utc)
return parsed.astimezone(resolve_schedule_tzinfo("Asia/Shanghai")).isoformat()
def parse_client_iso_to_utc_text(text: str) -> str:
"""
将客户端回显的观看时间 ISO 字符串归一为 UTC naive ISO 文本,供存储。
用途:save_completion 会合并客户端提交的 watched_at 兜底值(服务端记录缺失时入库);
客户端时间格式随版本演进(UTC 带 Z / 北京时间带 +08:00),必须归一为 UTC,
否则 watched_at_json 混入非 UTC 值会破坏"存储一律 UTC"的约定,后续服务端比较将出错。
Args:
text: 客户端提交的 ISO 时间字符串。
Returns:
UTC naive ISO 文本;无法解析时原样返回(与历史行为一致,不因脏数据阻塞提交)。
"""
try:
parsed = datetime.fromisoformat(str(text))
except ValueError:
return str(text)
if parsed.tzinfo is None:
# naive 视为北京时间墙钟(新版客户端口径),入库前转 UTC
parsed = parsed.replace(tzinfo=resolve_schedule_tzinfo("Asia/Shanghai"))
return to_utc_naive(parsed).isoformat()
def _dashboard_status_label(status: str | None) -> str:
"""将看板状态转换为页面一致的中文文案。"""
return {
"completed": "已完成",
"overdue": "已延期",
"in_progress": "进行中",
}.get(str(status or ""), str(status or ""))
def _get_lean_config() -> TrainingConfig:
@@ -69,6 +166,22 @@ def week_index_for_task(task: LeanTrainingWeeklyTask) -> int:
return int(earlier_count) + 1
def _config_video_resource_ids(config: TrainingConfig) -> list[TrainingConfigResource]:
"""
返回精益配置下全部"视频型"学习资源(agent_guide 且文件类型为 video)。
用途:冻结列表自动填充与每周自动滚动追加新增视频共用同一判定,避免两处视频口径漂移。
Args:
config: 已发布的精益培训配置(需含 resources 关系)。
Returns:
视频资源列表(顺序由调用方排序)。
"""
return [
resource for resource in config.resources
if resource.resource_type == "agent_guide" and resource.agent_guide and str(resource.agent_guide.file_type or "").lower().startswith("video")
]
def _normalize_video_ids(value: Any, config: TrainingConfig) -> list[int]:
"""
校验周任务绑定的视频资源并返回冻结顺序列表。
@@ -83,10 +196,7 @@ def _normalize_video_ids(value: Any, config: TrainingConfig) -> list[int]:
- 未选择时自动按资源上传时间倒序冻结全部视频(对应"发布周任务按上传时间倒序推送"规则);
- 推过的视频不能重复推:由推送游标(pushed_video_count)保证,直至全部视频推完。
"""
video_resources = [
resource for resource in config.resources
if resource.resource_type == "agent_guide" and resource.agent_guide and str(resource.agent_guide.file_type or "").lower().startswith("video")
]
video_resources = _config_video_resource_ids(config)
# [RULE] 管理端未显式勾选视频时,按上传时间倒序自动冻结全部视频,满足"直至全部上传视频推送完"
if not isinstance(value, list) or len(value) == 0:
if value is not None and not isinstance(value, list):
@@ -183,7 +293,8 @@ def serialize_weekly_task(task: LeanTrainingWeeklyTask, *, learner_view: bool =
"week_key": task.week_key,
"week_end": (week_start + timedelta(days=6)).isoformat() if week_start else None,
"week_index": week_index_for_task(task),
"due_at": task.due_at.isoformat(),
# 展示层转北京时间:管理端编辑器/看板头与学员端均直接渲染该字段,UTC 直出会比实际早 8 小时
"due_at": format_beijing_iso(task.due_at),
"video_resource_ids": visible_ids,
"target_roles": list(task.target_roles or []),
"target_user_ids": list(task.target_user_ids or []),
@@ -195,6 +306,48 @@ def serialize_weekly_task(task: LeanTrainingWeeklyTask, *, learner_view: bool =
}
def _already_pushed_resource_ids(*, exclude_task_id: int | None = None) -> set[int]:
"""
汇总全部已发布周任务中"实际已推送过员工"的视频资源 ID(各任务推送前缀的并集)。
用途:作为跨任务去重基线,保证"推过的视频绝对不能重复推"——新建任务继承游标与推送分批都以此集合为准。
Args:
exclude_task_id: 需要排除的任务 ID(对已存在任务推进批次时排除自身,自身前缀已由游标表达)。
Returns:
已推送视频资源 ID 集合。
"""
tasks = db.session.execute(
select(LeanTrainingWeeklyTask).where(LeanTrainingWeeklyTask.status == "published")
).scalars().all()
pushed: set[int] = set()
for task in tasks:
if exclude_task_id is not None and task.id == exclude_task_id:
continue
pushed.update(int(resource_id) for resource_id in list(task.video_resource_ids or [])[: task.pushed_video_count])
return pushed
def _inherited_pushed_video_count(video_ids: list[int]) -> int:
"""
计算手动新建周任务应继承的推送游标:新视频列表的"最长已推送前缀"长度。
用途:修复 HR 手动新建下一期任务时游标从 0 重推首批的问题——必须从上一任务断点续推。
核心逻辑:以已推送前缀并集为基线,从头统计新列表中有多少个视频已被推送过;
列表与上一期一致时精确继承断点;自动填充顺序因新上传视频变化时也能正确定位到首个未推送视频。
Args:
video_ids: 新任务冻结的视频资源 ID 顺序列表。
Returns:
继承后的推送游标(0 <= 游标 <= len(video_ids))。
"""
already_pushed = _already_pushed_resource_ids()
inherited = 0
for resource_id in video_ids:
if int(resource_id) not in already_pushed:
break
inherited += 1
return inherited
def create_or_update_weekly_task(data: dict[str, Any], user_id: int) -> dict[str, Any]:
"""
创建或更新精益视频周任务,并由 HR 冻结视频列表、每周推送数量与受训对象。
@@ -204,7 +357,9 @@ def create_or_update_weekly_task(data: dict[str, Any], user_id: int) -> dict[str
- 截止时间支持修改:显式传 due_at 按所选时刻落库,缺省为所选周周日 23:59:59;
不得早于所选周周一 00:00(Asia/Shanghai),避免任务创建即处于"已延期"的明显配置错误;
- 修改后【发布周任务】/【立即新增任务补推】均作用于所选周任务(发布仅首次自动推首批);
- 同周重复提交为更新(游标不回退),新周提交为新建。
- 同周重复提交为更新(游标不回退),新周提交为新建;
- 新建任务的推送游标从历史已推送进度继承(新列表的最长已推送前缀),推过的视频绝不从 0 重推,
后续批次自动从上一任务断点继续向后推进。
"""
config = _get_lean_config()
shanghai_tz = resolve_schedule_tzinfo("Asia/Shanghai")
@@ -247,8 +402,12 @@ def create_or_update_weekly_task(data: dict[str, Any], user_id: int) -> dict[str
task = existing or LeanTrainingWeeklyTask(config_id=config.id, week_key=week_start.isoformat(), created_by_id=user_id, weekly_count=1, pushed_video_count=0)
task.due_at = due_at
task.video_resource_ids = video_ids
# [STEP] 视频列表可能被追加,推送游标不能超出列表长度,否则下一轮无视频可推
task.pushed_video_count = min(task.pushed_video_count, len(video_ids))
if existing:
# [STEP] 视频列表可能被追加,推送游标不能超出列表长度,否则下一轮无视频可推
task.pushed_video_count = min(task.pushed_video_count, len(video_ids))
else:
# [RULE] 手动新建周任务继承历史推送进度:推过的视频绝不从 0 重推,从上一任务断点续推
task.pushed_video_count = _inherited_pushed_video_count(video_ids)
task.weekly_count = weekly_count
task.target_roles = target_roles
task.target_user_ids = target_user_ids
@@ -305,8 +464,9 @@ def list_my_weekly_tasks(user: User) -> list[dict[str, Any]]:
item["task_status"] = "completed" if completion and completion.completed_at else ("overdue" if now > task.due_at else "in_progress")
item["completion"] = {
"summary_text": completion.summary_text,
"watched_at": dict(completion.watched_at_json or {}),
"completed_at": completion.completed_at.isoformat() if completion.completed_at else None,
# 展示层转北京时间:学员端"已观看"直接渲染该字典值,存储仍为 UTC
"watched_at": {key: format_beijing_iso(value) for key, value in (completion.watched_at_json or {}).items()},
"completed_at": format_beijing_iso(completion.completed_at),
} if completion else None
items.append(item)
return items
@@ -342,7 +502,8 @@ def mark_video_watched(user: User, data: dict[str, Any]) -> dict[str, Any]:
# 观看草稿:保持 completed_at 为空,任务仍为进行中/已延期,直至感悟提交完成
db.session.add(completion)
db.session.commit()
return {"watched_at": watched}
# 返回值供学员端即时回显"已观看时间",展示层转北京时间;数据库中保持 UTC
return {"watched_at": {key: format_beijing_iso(value) for key, value in watched.items()}}
def save_completion(user: User, data: dict[str, Any]) -> dict[str, Any]:
@@ -356,7 +517,8 @@ def save_completion(user: User, data: dict[str, Any]) -> dict[str, Any]:
# 员工只能观看已推送的前缀视频,完成校验同样基于已推送范围而非全量选择列表
required_ids = list(task.video_resource_ids or [])[: task.pushed_video_count]
# 观看记录以服务端持久化为准(mark_video_watched 已逐个保存),客户端仅作回显兜底,防止伪造观看
watched = {str(key): str(value) for key, value in (data.get("watched_at") or {}).items()}
# 兜底值入库前归一为 UTC:客户端可能提交北京时间(+08:00)或 UTC(Z)格式,存储一律 UTC
watched = {str(key): parse_client_iso_to_utc_text(value) for key, value in (data.get("watched_at") or {}).items()}
completion = db.session.execute(
select(LeanTrainingCompletion).where(LeanTrainingCompletion.weekly_task_id == task.id, LeanTrainingCompletion.user_id == user.id)
).scalar_one_or_none() or LeanTrainingCompletion(weekly_task_id=task.id, user_id=user.id)
@@ -392,7 +554,7 @@ def _task_video_rows(task: LeanTrainingWeeklyTask, completion: LeanTrainingCompl
# [RULE] 看板视频列只展示已推送前缀(video_resource_ids[:pushed_video_count]):未推送视频不属于本周期学习范围,避免名单出现从未布置过的视频
visible_ids = task.video_resource_ids[: task.pushed_video_count]
return [
{"name": titles.get(resource_id, ""), "watched_at": watched.get(str(resource_id))}
{"name": titles.get(resource_id, ""), "watched_at": format_beijing_iso(watched.get(str(resource_id)))}
for resource_id in visible_ids
]
@@ -413,7 +575,7 @@ def serialize_completion(completion: LeanTrainingCompletion, task: LeanTrainingW
"videos": _task_video_rows(task, completion),
"summary_text": completion.summary_text,
"status": status,
"completed_at": completion.completed_at.isoformat() if completion.completed_at else None,
"completed_at": format_beijing_iso(completion.completed_at),
}
@@ -441,3 +603,43 @@ def list_dashboard(task_id: int | None) -> dict[str, Any]:
row = serialize_completion(item, task, user) if item else {"user_id": user.id, "employee_id": user.employee_id, "name": user.real_name or user.username, "department": user.department, "videos": _task_video_rows(task, None), "summary_text": None, "status": "overdue" if utc_now_naive() > task.due_at else "in_progress", "completed_at": None}
(completed if row["status"] == "completed" else incomplete).append(row)
return {"task": serialize_weekly_task(task), "completed": completed, "incomplete": incomplete, "periods": periods}
def export_dashboard_excel(task_id: int | None) -> tuple[bytes, str]:
"""导出指定精益培训期次的完整看板数据。
Args:
task_id: 指定周任务 ID;为空时按看板规则导出最新一期。
Returns:
Excel 二进制内容与下载文件名;无可导出任务时抛出 NotFoundError。
"""
dashboard = list_dashboard(task_id)
task = dashboard["task"]
if not task:
raise NotFoundError("Lean training weekly task not found")
workbook = Workbook()
worksheet = workbook.active
worksheet.title = "lean_training"
worksheet.append(["期号", "培训周次", "截止时间", "工号", "姓名", "部门", "视频名称", "观看时间", "状态", "学习感悟", "完成时间"])
rows = [*dashboard["completed"], *dashboard["incomplete"]]
for row in rows:
videos = row.get("videos") or []
worksheet.append([
task.get("week_index") or "",
task.get("week_key") or "",
_format_dashboard_datetime(task.get("due_at")),
row.get("employee_id") or "",
row.get("name") or "",
row.get("department") or "",
"\n".join(str(video.get("name") or "") for video in videos),
"\n".join(_format_dashboard_datetime(video.get("watched_at")) for video in videos),
_dashboard_status_label(row.get("status")),
row.get("summary_text") or "",
_format_dashboard_datetime(row.get("completed_at")),
])
buffer = BytesIO()
workbook.save(buffer)
filename = f"lean_training_dashboard_{task['week_key']}.xlsx"
return buffer.getvalue(), filename
-135
View File
@@ -1,135 +0,0 @@
import os
import uuid
from typing import BinaryIO
from minio import Minio
from minio.error import S3Error
from werkzeug.utils import secure_filename
from app.core.config.settings import config, ACTIVE_ENV_NAME
cfg = config[ACTIVE_ENV_NAME]
class MinioService:
def __init__(self):
self.client = Minio(
cfg.MINIO_ENDPOINT,
access_key=cfg.MINIO_ACCESS_KEY,
secret_key=cfg.MINIO_SECRET_KEY,
secure=cfg.MINIO_SECURE,
)
self.bucket_name = cfg.MINIO_AGENT_GUIDES_BUCKET
self._ensure_bucket_exists()
def _ensure_bucket_exists(self):
try:
if not self.client.bucket_exists(self.bucket_name):
self.client.make_bucket(self.bucket_name)
# Set bucket policy to public read
policy = {
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": {"AWS": ["*"]},
"Action": ["s3:GetObject"],
"Resource": [f"arn:aws:s3:::{self.bucket_name}/*"]
}
]
}
import json
self.client.set_bucket_policy(self.bucket_name, json.dumps(policy))
except Exception as e:
# log or print error
print(f"MinIO bucket error (or not reachable): {e}")
def upload_file(self, file_stream: BinaryIO, filename: str, content_type: str, file_size: int) -> str:
"""
Uploads a file to MinIO and returns the generated object name.
"""
# If MinIO is not running, we could fallback to local storage or raise clear error
try:
self._ensure_bucket_exists()
except Exception:
pass
ext = os.path.splitext(filename)[1]
unique_filename = f"{uuid.uuid4().hex}{ext}"
try:
self.client.put_object(
bucket_name=self.bucket_name,
object_name=unique_filename,
data=file_stream,
length=file_size,
content_type=content_type
)
except Exception as e:
# For development, if minio is down, let's mock it so UI can continue
print(f"Warning: Minio upload failed ({e}). Fallback to local storage.")
# fallback to local storage
os.makedirs('data/agent-guides', exist_ok=True)
local_path = os.path.join('data/agent-guides', unique_filename)
file_stream.seek(0)
with open(local_path, 'wb') as f:
f.write(file_stream.read())
return unique_filename
def get_public_url(self, object_name: str) -> str:
"""
返回同源的指南文件代理地址。
用途:避免 HTTPS 页面直接加载 HTTP MinIO 对象时被移动端浏览器拦截。
参数约束:object_name 必须是系统生成的对象名;返回地址由指南文件接口提供 Range 响应。
"""
return f"/api/agents/guides/files/{object_name}"
def open_file_stream(self, object_name: str, *, offset: int = 0, length: int | None = None):
"""
按指定字节范围打开 MinIO 指南对象流。
用途:供同源指南文件接口透传视频数据,满足 iOS 媒体播放器的 Range/206 请求。
参数约束:offset 从 0 开始,length 为本次最多读取字节数;调用方必须关闭返回流。
"""
return self.client.get_object(
self.bucket_name,
object_name,
offset=offset,
length=length,
)
def stat_file(self, object_name: str):
"""
获取 MinIO 指南对象元数据。
用途:在返回视频前确定文件大小和 MIME 类型,以生成 iOS 可识别的媒体响应头。
参数约束:object_name 必须是系统保存的对象名;对象不存在时由 MinIO 异常上抛。
"""
return self.client.stat_object(self.bucket_name, object_name)
def get_file_bytes(self, object_name: str) -> bytes:
"""
读取对象的原始字节内容。
用途:给后台解析 PDF、图片等资料时复用统一文件读取入口,避免业务层自己判断本地回退还是 MinIO。
参数约束:object_name 必须是已存储的对象名,不接受外部 URL。
"""
local_path = os.path.join('data/agent-guides', object_name)
if os.path.exists(local_path):
with open(local_path, 'rb') as file_obj:
return file_obj.read()
response = self.client.get_object(self.bucket_name, object_name)
try:
return response.read()
finally:
response.close()
response.release_conn()
def delete_file(self, object_name: str):
try:
self.client.remove_object(self.bucket_name, object_name)
except S3Error as e:
print(f"Error deleting file from MinIO: {e}")
minio_service = MinioService()
-439
View File
@@ -1,439 +0,0 @@
from __future__ import annotations
from copy import deepcopy
from datetime import datetime
from typing import Any
import os
import xml.etree.ElementTree as ET
import requests
from flask import current_app
SOAP_ENV_NS = 'http://schemas.xmlsoap.org/soap/envelope/'
SERVICE_NS = 'webservices.services.weaver.com.cn'
WORKFLOW_NS = 'http://webservices.workflow.weaver'
XSI_NS = 'http://www.w3.org/2001/XMLSchema-instance'
NS = {
'soapenv': SOAP_ENV_NS,
'svc': SERVICE_NS,
'wf': WORKFLOW_NS,
'xsi': XSI_NS,
}
ET.register_namespace('soapenv', SOAP_ENV_NS)
ET.register_namespace('svc', SERVICE_NS)
ET.register_namespace('wf', WORKFLOW_NS)
ET.register_namespace('xsi', XSI_NS)
class OALeaveWorkflowError(RuntimeError):
"""Raised when OA leave workflow submission fails."""
class OALeaveWorkflowService:
WORKFLOW_ID = '879'
# Keep backend leave labels aligned with the chat form options so OA browser
# fields always receive the expected showValue instead of a raw code.
LEAVE_TYPE_LABELS = {
'005': '事假(小时)',
'006': '病假(小时)',
'007': '丧假(天)',
'010': '年假(天)',
'021': '因公出差(小时)',
'025': '调休假(小时)',
'035': '其他假(小时)',
'401': '产假(天)',
'402': '陪产假(天)',
'403': '婚假(天)',
'405': '住院病假(小时)',
'406': '工伤假(天)',
'408': '育儿假(小时)',
'ZZ01': '返乡假(小时)',
'ZZ04': '事假(经理专用小时)',
'ZZ05': '病假(经理专用小时)',
'ZZ07': '丧假(经理专用天)',
'ZZ08': '产假(经理专用天)',
'ZZ09': '陪产假(经理专用天)',
'ZZ10': '婚假(经理专用天)',
}
ERROR_MESSAGES = {
'-1': '创建流程失败',
'-2': '用户没有流程创建权限',
'-3': '创建流程基本信息失败',
'-4': '保存表单主表信息失败',
'-5': '更新紧急程度失败',
'-6': '流程操作者失败',
'-7': '流转至下一节点失败',
'-8': '节点附加操作失败',
}
@classmethod
def _get_wsdl_url(cls) -> str:
return (
current_app.config.get('OA_WORKFLOW_WSDL_URL')
or os.getenv('OA_WORKFLOW_WSDL_URL')
or 'http://oa.well-trust.com:8888/services/WorkflowService?wsdl'
).strip()
@classmethod
def _get_service_url(cls) -> str:
wsdl_url = cls._get_wsdl_url()
return wsdl_url[:-5] if wsdl_url.lower().endswith('?wsdl') else wsdl_url
@classmethod
def _request_timeout(cls) -> tuple[int, int]:
return (5, 25)
@classmethod
def _post_soap(cls, action: str, body_el: ET.Element) -> ET.Element:
envelope = ET.Element(f'{{{SOAP_ENV_NS}}}Envelope')
ET.SubElement(envelope, f'{{{SOAP_ENV_NS}}}Header')
body = ET.SubElement(envelope, f'{{{SOAP_ENV_NS}}}Body')
body.append(body_el)
payload = ET.tostring(envelope, encoding='utf-8', xml_declaration=True)
headers = {
'Content-Type': 'text/xml; charset=utf-8',
'SOAPAction': action,
}
max_retries = 3
last_exc = None
for attempt in range(1, max_retries + 1):
try:
response = requests.post(
cls._get_service_url(),
data=payload,
headers=headers,
timeout=cls._request_timeout(),
)
response.raise_for_status()
return ET.fromstring(response.text)
except requests.RequestException as exc:
last_exc = exc
status_code = getattr(getattr(exc, 'response', None), 'status_code', None)
retryable = status_code in (502, 503, 504) if status_code else True
if retryable and attempt < max_retries:
import time
wait = attempt * 2
current_app.logger.warning(
'[oa-leave] SOAP request failed (attempt %d/%d, status=%s), retrying in %ds: %s',
attempt, max_retries, status_code, wait, exc,
)
time.sleep(wait)
continue
raise OALeaveWorkflowError(f'OA WorkflowService 请求失败:{exc}') from exc
except ET.ParseError as exc:
raise OALeaveWorkflowError('OA WorkflowService 返回了无法解析的 XML。') from exc
raise OALeaveWorkflowError(f'OA WorkflowService 请求失败(重试{max_retries}次后仍出错):{last_exc}') from last_exc
@classmethod
def resolve_creator_oa_user(cls, employee_id: str | None, real_name: str | None = None) -> dict[str, str]:
return cls._resolve_runtime_oa_user(employee_id, real_name, role_label='请假人')
@classmethod
def resolve_agent_oa_user(cls, employee_id: str | None, real_name: str | None = None) -> dict[str, str]:
return cls._resolve_runtime_oa_user(employee_id, real_name, role_label='代理人')
@classmethod
def _resolve_runtime_oa_user(
cls,
employee_id: str | None,
real_name: str | None = None,
*,
role_label: str,
) -> dict[str, str]:
employee_id = (employee_id or '').strip()
real_name = (real_name or '').strip()
if not employee_id:
raise OALeaveWorkflowError(f'缺少{role_label}工号,无法匹配 OA 用户。')
if not real_name:
raise OALeaveWorkflowError(f'缺少{role_label}姓名,无法匹配 OA 用户。')
try:
from app.services.oa_sqlserver import OASQLServerService
matched = OASQLServerService.get_employee_by_name_and_workcode(real_name, employee_id)
except Exception as exc:
raise OALeaveWorkflowError(f'查询{role_label} OA 用户失败:{exc}') from exc
if not matched:
raise OALeaveWorkflowError(f'未找到{role_label} OA 用户:{real_name}({employee_id})。')
return {
'employee_id': matched['employeeId'],
'user_id': matched['uid'],
'name': matched['name'],
'jobtitle': matched.get('jobtitle', ''),
'jobtitleName': matched.get('jobtitleName', ''),
'departmentid': matched.get('departmentid', ''),
'departmentName': matched.get('departmentName', ''),
'subcompanyid1': matched.get('subcompanyid1', ''),
'subcompanyName': matched.get('subcompanyName', ''),
}
@staticmethod
def _pick_browser_field_value(*values: Any) -> str:
for value in values:
text = ('' if value is None else str(value)).strip()
if text:
return text
return ''
@classmethod
def _build_get_template_body(cls, workflow_id: str, oa_user_id: str) -> ET.Element:
root = ET.Element(f'{{{SERVICE_NS}}}getCreateWorkflowRequestInfo')
ET.SubElement(root, f'{{{SERVICE_NS}}}in0').text = str(workflow_id)
ET.SubElement(root, f'{{{SERVICE_NS}}}in1').text = str(oa_user_id)
return root
@classmethod
def _get_template_request_info(cls, workflow_id: str, oa_user_id: str) -> ET.Element:
action = 'urn:weaver.workflow.webservices.WorkflowService.getCreateWorkflowRequestInfo'
root = cls._post_soap(action, cls._build_get_template_body(workflow_id, oa_user_id))
out = root.find('.//svc:out', NS)
if out is None or out.attrib.get(f'{{{XSI_NS}}}nil') == 'true' or len(list(out)) == 0:
raise OALeaveWorkflowError('OA 未返回建单模板,请确认 workflowId 与 OA userid 是否正确。')
return deepcopy(out)
@classmethod
def _find_field(cls, request_info: ET.Element, field_name: str) -> ET.Element | None:
for field in request_info.findall('.//wf:WorkflowRequestTableField', NS):
if (field.findtext('wf:fieldName', default='', namespaces=NS) or '').strip() == field_name:
return field
return None
@classmethod
def _set_field(
cls,
request_info: ET.Element,
field_name: str,
*,
value: str | None,
show_value: str | None = None,
) -> None:
field = cls._find_field(request_info, field_name)
if field is None:
current_app.logger.warning('[oa-leave] field not found in template: %s', field_name)
return
value_node = field.find('wf:fieldValue', NS)
if value_node is None:
value_node = ET.SubElement(field, f'{{{WORKFLOW_NS}}}fieldValue')
value_node.text = '' if value is None else str(value)
if show_value is not None:
show_node = field.find('wf:fieldShowValue', NS)
if show_node is None:
show_node = ET.SubElement(field, f'{{{WORKFLOW_NS}}}fieldShowValue')
show_node.text = str(show_value)
field_html_type = (field.findtext('wf:fieldHtmlType', default='', namespaces=NS) or '').strip()
if field_html_type == '3':
filed_html_node = field.find('wf:filedHtmlShow', NS)
if filed_html_node is not None:
filed_html_node.text = str(show_value)
for tag in ['edit', 'view']:
node = field.find(f'wf:{tag}', NS)
if node is not None:
node.text = 'true'
else:
node = ET.SubElement(field, f'{{{WORKFLOW_NS}}}{tag}')
node.text = 'true'
@classmethod
def _set_text(cls, parent: ET.Element, xpath: str, value: str) -> None:
node = parent.find(xpath, NS)
if node is not None:
node.text = value
@classmethod
def _parse_frontend_datetime(cls, raw: str, field_name: str) -> datetime:
text = (raw or '').strip().replace('T', ' ')
try:
return datetime.strptime(text, '%Y-%m-%d %H:%M')
except ValueError as exc:
raise OALeaveWorkflowError(f'{field_name} 格式不正确,应为 YYYY-MM-DD HH:MM。') from exc
@classmethod
def _build_request_name(cls, creator_name: str, start_dt: datetime) -> str:
return f'请假申请单-{creator_name}-{start_dt.strftime("%Y-%m-%d")}'
@classmethod
def _normalize_duration(cls, value: Any) -> str:
try:
hours = float(value)
except (TypeError, ValueError) as exc:
raise OALeaveWorkflowError('请假时长格式不正确。') from exc
if hours <= 0:
raise OALeaveWorkflowError('请假时长必须大于 0。')
return f'{hours:.2f}'.rstrip('0').rstrip('.')
@classmethod
def build_request_info(cls, form_data: dict[str, Any], current_user: Any) -> tuple[ET.Element, dict[str, str], dict[str, str], dict[str, str]]:
filler_name = (
form_data.get('fillerName')
or getattr(current_user, 'real_name', None)
or getattr(current_user, 'username', None)
or '当前用户'
)
filler = cls._resolve_runtime_oa_user(
getattr(current_user, 'employee_id', None),
filler_name,
role_label='填单人'
)
applicant_name = (
form_data.get('applicantName')
or getattr(current_user, 'real_name', None)
or getattr(current_user, 'username', None)
or '当前用户'
)
applicant = cls.resolve_creator_oa_user(
form_data.get('employeeId') or getattr(current_user, 'employee_id', None),
applicant_name,
)
agent = cls.resolve_agent_oa_user(form_data.get('agentEmployeeId'), form_data.get('agentName'))
workflow_id = str(current_app.config.get('OA_LEAVE_WORKFLOW_CODE') or cls.WORKFLOW_ID)
request_info = cls._get_template_request_info(workflow_id, filler['user_id'])
start_dt = cls._parse_frontend_datetime(form_data.get('startTime'), '开始时间')
end_dt = cls._parse_frontend_datetime(form_data.get('endTime'), '结束时间')
if end_dt <= start_dt:
raise OALeaveWorkflowError('结束时间必须晚于开始时间。')
leave_type_code = (form_data.get('leaveType') or '').strip()
if not leave_type_code:
raise OALeaveWorkflowError('缺少假别编码。')
leave_type_label = cls.LEAVE_TYPE_LABELS.get(leave_type_code, leave_type_code)
request_name = cls._build_request_name(applicant['name'], start_dt)
cls._set_text(request_info, 'wf:creatorId', filler['user_id'])
cls._set_text(request_info, 'wf:creatorName', filler['name'])
cls._set_text(request_info, 'wf:requestLevel', '0')
cls._set_text(request_info, 'wf:requestName', request_name)
cls._set_text(request_info, './/wf:workflowBaseInfo/wf:workflowId', workflow_id)
cls._set_field(request_info, 'requestname', value=request_name, show_value=request_name)
cls._set_field(request_info, 'tdrgh', value=filler['employee_id'])
cls._set_field(request_info, 'sqrgh', value=applicant['employee_id'])
cls._set_field(request_info, 'tdrxm', value=filler['user_id'], show_value=filler['name'])
cls._set_field(request_info, 'sqrxm', value=applicant['user_id'], show_value=applicant['name'])
filler_jobtitle = cls._pick_browser_field_value(filler.get('jobtitle'), form_data.get('fillerJobTitle'))
filler_jobtitle_name = cls._pick_browser_field_value(filler.get('jobtitleName'))
filler_department = cls._pick_browser_field_value(filler.get('departmentid'), form_data.get('fillerDepartmentId'))
filler_department_name = cls._pick_browser_field_value(filler.get('departmentName'))
filler_subcompany = cls._pick_browser_field_value(filler.get('subcompanyid1'), form_data.get('fillerSubCompanyId1'))
filler_subcompany_name = cls._pick_browser_field_value(filler.get('subcompanyName'))
applicant_jobtitle = cls._pick_browser_field_value(applicant.get('jobtitle'), form_data.get('applicantJobTitle'))
applicant_jobtitle_name = cls._pick_browser_field_value(applicant.get('jobtitleName'))
applicant_department = cls._pick_browser_field_value(applicant.get('departmentid'), form_data.get('applicantDepartmentId'))
applicant_department_name = cls._pick_browser_field_value(applicant.get('departmentName'))
applicant_subcompany = cls._pick_browser_field_value(applicant.get('subcompanyid1'), form_data.get('applicantSubCompanyId1'))
applicant_subcompany_name = cls._pick_browser_field_value(applicant.get('subcompanyName'))
try:
from app.services.oa_sqlserver import OASQLServerService
if filler_jobtitle and not filler_jobtitle_name:
filler_jobtitle_name = OASQLServerService.get_jobtitle_name(filler_jobtitle)
if filler_department and not filler_department_name:
filler_department_name = OASQLServerService.get_department_name(filler_department)
if filler_subcompany and not filler_subcompany_name:
filler_subcompany_name = OASQLServerService.get_subcompany_name(filler_subcompany)
if applicant_jobtitle and not applicant_jobtitle_name:
applicant_jobtitle_name = OASQLServerService.get_jobtitle_name(applicant_jobtitle)
if applicant_department and not applicant_department_name:
applicant_department_name = OASQLServerService.get_department_name(applicant_department)
if applicant_subcompany and not applicant_subcompany_name:
applicant_subcompany_name = OASQLServerService.get_subcompany_name(applicant_subcompany)
except Exception:
pass
cls._set_field(request_info, 'tdrzw', value=filler_jobtitle, show_value=filler_jobtitle_name or filler_jobtitle or '暂无')
cls._set_field(request_info, 'tdrbm', value=filler_department, show_value=filler_department_name or filler_department or '暂无')
cls._set_field(request_info, 'tdrgs', value=filler_subcompany, show_value=filler_subcompany_name or filler_subcompany or '暂无')
cls._set_field(request_info, 'sqrzw', value=applicant_jobtitle, show_value=applicant_jobtitle_name or applicant_jobtitle or '暂无')
cls._set_field(request_info, 'sqrbm', value=applicant_department, show_value=applicant_department_name or applicant_department or '暂无')
cls._set_field(request_info, 'sqrgs', value=applicant_subcompany, show_value=applicant_subcompany_name or applicant_subcompany or '暂无')
current_app.logger.info(
'[oa-leave] field values: tdrzw=%s/%s tdrbm=%s/%s tdrgs=%s/%s sqrzw=%s/%s sqrbm=%s/%s sqrgs=%s/%s',
filler_jobtitle, filler_jobtitle_name or filler_jobtitle or '暂无',
filler_department, filler_department_name or filler_department or '暂无',
filler_subcompany, filler_subcompany_name or filler_subcompany or '暂无',
applicant_jobtitle, applicant_jobtitle_name or applicant_jobtitle or '暂无',
applicant_department, applicant_department_name or applicant_department or '暂无',
applicant_subcompany, applicant_subcompany_name or applicant_subcompany or '暂无',
)
cls._set_field(request_info, 'dlrgh', value=agent['employee_id'])
cls._set_field(request_info, 'dlrxm', value=agent['user_id'], show_value=agent['name'])
cls._set_field(request_info, 'dlrlogid', value=agent['user_id'], show_value=agent['user_id'])
cls._set_field(request_info, 'jb', value=leave_type_code, show_value=leave_type_label)
cls._set_field(request_info, 'jbbh', value=leave_type_code, show_value=leave_type_code)
cls._set_field(request_info, 'kssj', value=start_dt.strftime('%Y-%m-%d'), show_value=start_dt.strftime('%Y-%m-%d'))
cls._set_field(request_info, 'kssk', value=start_dt.strftime('%H:%M'), show_value=start_dt.strftime('%H:%M'))
cls._set_field(request_info, 'jssj', value=end_dt.strftime('%Y-%m-%d'), show_value=end_dt.strftime('%Y-%m-%d'))
cls._set_field(request_info, 'jssk', value=end_dt.strftime('%H:%M'), show_value=end_dt.strftime('%H:%M'))
cls._set_field(request_info, 'qjsc', value=cls._normalize_duration(form_data.get('durationHours')), show_value=cls._normalize_duration(form_data.get('durationHours')))
cls._set_field(request_info, 'sfwgs', value=str(form_data.get('isWorkInjury')), show_value='是' if str(form_data.get('isWorkInjury')) == '0' else '否')
cls._set_field(request_info, 'sfwc', value=str(form_data.get('isOutOfOffice')), show_value='是' if str(form_data.get('isOutOfOffice')) == '0' else '否')
cls._set_field(request_info, 'bz', value=(form_data.get('remark') or '').strip(), show_value=(form_data.get('remark') or '').strip())
return request_info, filler, applicant, agent
@classmethod
def _build_create_body(cls, request_info: ET.Element, oa_user_id: str) -> ET.Element:
root = ET.Element(f'{{{SERVICE_NS}}}doCreateWorkflowRequest')
in0 = deepcopy(request_info)
in0.tag = f'{{{SERVICE_NS}}}in0'
root.append(in0)
ET.SubElement(root, f'{{{SERVICE_NS}}}in1').text = str(oa_user_id)
return root
@classmethod
def _parse_create_response(cls, root: ET.Element) -> str:
out = root.findtext('.//svc:out', default='', namespaces=NS)
out = (out or '').strip()
if not out:
raise OALeaveWorkflowError('OA 未返回单据编号。')
if out in cls.ERROR_MESSAGES:
raise OALeaveWorkflowError(cls.ERROR_MESSAGES[out])
if out.startswith('-'):
raise OALeaveWorkflowError(f'OA 创建流程失败,返回码:{out}')
return out
@classmethod
def serialize_request_xml(cls, request_info: ET.Element) -> str:
return ET.tostring(request_info, encoding='unicode')
@classmethod
def submit_leave_request(cls, form_data: dict[str, Any], current_user: Any) -> dict[str, Any]:
request_info, filler, applicant, agent = cls.build_request_info(form_data, current_user)
log_fields = ['tdrzw', 'tdrbm', 'tdrgs', 'sqrzw', 'sqrbm', 'sqrgs', 'qjsc', 'tdrgh', 'sqrgh']
for fn in log_fields:
f = cls._find_field(request_info, fn)
if f is not None:
fv = f.findtext('wf:fieldValue', default='', namespaces=NS)
fsv = f.findtext('wf:fieldShowValue', default='', namespaces=NS)
fe = f.findtext('wf:edit', default='(removed)', namespaces=NS)
current_app.logger.info('[oa-leave] PUSH field %s: value=%s showValue=%s edit=%s', fn, fv, fsv, fe)
action = 'urn:weaver.workflow.webservices.WorkflowService.doCreateWorkflowRequest'
root = cls._post_soap(action, cls._build_create_body(request_info, filler['user_id']))
request_id = cls._parse_create_response(root)
current_app.logger.info('[oa-leave] OA response request_id=%s', request_id)
return {
'ok': True,
'request_id': request_id,
'request_name': request_info.findtext('wf:requestName', default='', namespaces=NS),
'submitted_at': datetime.now().strftime('%Y-%m-%d %H:%M'),
'creator': applicant,
'filler': filler,
'agent': agent,
'workflow_id': str(current_app.config.get('OA_LEAVE_WORKFLOW_CODE') or cls.WORKFLOW_ID),
'request_xml': cls.serialize_request_xml(request_info),
}
-258
View File
@@ -1,258 +0,0 @@
"""
backend/app/services/oa_sqlserver.py
用途:封装 OA SQL Server 的员工检索与组织信息查询能力,供请假代理人/申请人选择等场景复用。
依赖:pyodbc、OA ecology 数据库视图 userInfo_view / HrmDepartment / HrmSubCompany / HrmJobTitles。
逻辑:通过只读 SQL 查询返回 OA 用户与组织字段;对于 OA 中夹带的多语言包装串,统一在服务层清洗成可直接展示的中文文本。
"""
import os
import re
import pyodbc
from flask import current_app
_OA_MULTILINGUAL_WRAPPER_PATTERN = re.compile(
r"~`~`7\s*(.*?)\s*~`8\s*(.*?)\s*~`9\s*(.*?)\s*~`~"
)
class OASQLServerService:
@staticmethod
def _normalize_oa_text(value) -> str:
"""
清洗 OA 多语言包装字段。
AI 触发时机:当 OA 视图返回的姓名、部门、分部、职务等字段中夹带
`~`~`7 中文 ~`8 English ~`9 繁中 ~`~` 这类原始包装串时,需统一提取
可直接给用户展示的文本,避免在代理人选择弹窗中看到乱码样式的标记串。
Args:
value: 来自 OA SQL Server 的原始字段值。
Returns:
优先返回简体中文,其次英文、繁中;若未命中包装规则,则返回原始去空白文本。
"""
text = str(value or "").strip()
if not text:
return ""
matched = _OA_MULTILINGUAL_WRAPPER_PATTERN.search(text)
if not matched:
return text
simplified, english, traditional = (
segment.strip().strip("`").strip()
for segment in matched.groups()
)
return simplified or english or traditional or text
@staticmethod
def _pick_driver():
drivers = pyodbc.drivers()
preferred = [
"ODBC Driver 18 for SQL Server",
"ODBC Driver 17 for SQL Server",
"SQL Server",
]
for name in preferred:
if name in drivers:
return name
if not drivers:
raise RuntimeError("未找到可用的 SQL Server ODBC 驱动")
return drivers[-1]
@classmethod
def _connect(cls):
driver = os.getenv("OA_SQLSERVER_DRIVER", "").strip() or cls._pick_driver()
available_drivers = pyodbc.drivers()
if driver not in available_drivers:
driver = cls._pick_driver()
server = os.getenv("OA_SQLSERVER_HOST", "192.168.100.225").strip()
port = os.getenv("OA_SQLSERVER_PORT", "1433").strip()
database = os.getenv("OA_SQLSERVER_DATABASE", "ecology").strip()
username = os.getenv("OA_SQLSERVER_USERNAME", "AI_Knowledge_Base_OA").strip()
password = os.getenv("OA_SQLSERVER_PASSWORD", "hoo-thai@123_AI_OA").strip()
encrypt = os.getenv("OA_SQLSERVER_ENCRYPT", "no").strip().lower()
trust_cert = os.getenv("OA_SQLSERVER_TRUST_CERT", "yes").strip().lower()
timeout = int(os.getenv("OA_SQLSERVER_TIMEOUT", "10"))
conn_str = (
f"DRIVER={{{driver}}};"
f"SERVER={server},{port};"
f"DATABASE={database};"
f"UID={username};"
f"PWD={password};"
)
if driver != "SQL Server":
conn_str += (
f"Encrypt={encrypt};"
f"TrustServerCertificate={trust_cert};"
)
return pyodbc.connect(conn_str, timeout=timeout)
@classmethod
def search_employees(cls, keyword: str, page: int, page_size: int):
connection = cls._connect()
cursor = connection.cursor()
try:
offset = (page - 1) * page_size
params = []
# Count total
count_sql = "SELECT COUNT(1) FROM userInfo_view WHERE 1=1"
if keyword:
count_sql += " AND (workcode LIKE ? OR lastname LIKE ?)"
like_kw = f"%{keyword}%"
params.extend([like_kw, like_kw])
cursor.execute(count_sql, params)
total = cursor.fetchone()[0]
# Fetch page
# Compatible with older SQL Server versions (2008/2012)
query_sql = """
SELECT id, workcode, lastname, jobtitle, departmentid, subcompanyid1,
departmentname, subcompanyname, jobtitlename
FROM (
SELECT v.id, v.workcode, v.lastname, v.jobtitle, v.departmentid, v.subcompanyid1,
d.departmentname, s.subcompanyname, j.jobtitlename,
ROW_NUMBER() OVER(ORDER BY v.id) as rn
FROM userInfo_view v
LEFT JOIN HrmDepartment d ON v.departmentid = d.id
LEFT JOIN HrmSubCompany s ON v.subcompanyid1 = s.id
LEFT JOIN HrmJobTitles j ON v.jobtitle = j.id
WHERE 1=1
"""
if keyword:
query_sql += " AND (workcode LIKE ? OR lastname LIKE ?)"
query_sql += """
) as T
WHERE rn > ? AND rn <= ?
"""
page_params = params + [offset, offset + page_size]
cursor.execute(query_sql, page_params)
items = []
for row in cursor.fetchall():
items.append({
"uid": str(row.id) if row.id is not None else "",
"employeeId": str(row.workcode) if row.workcode is not None else "",
"name": cls._normalize_oa_text(row.lastname),
"jobtitle": cls._normalize_oa_text(row.jobtitle),
"departmentid": str(row.departmentid) if row.departmentid is not None else "",
"subcompanyid1": str(row.subcompanyid1) if row.subcompanyid1 is not None else "",
"departmentName": cls._normalize_oa_text(row.departmentname),
"subcompanyName": cls._normalize_oa_text(row.subcompanyname),
"jobtitleName": cls._normalize_oa_text(row.jobtitlename),
})
return {
"items": items,
"total": total,
"page": page,
"page_size": page_size
}
finally:
try:
cursor.close()
finally:
connection.close()
@classmethod
def get_employee_by_name_and_workcode(cls, real_name: str, employee_id: str):
connection = cls._connect()
cursor = connection.cursor()
try:
normalized_name = (real_name or "").strip()
normalized_employee_id = (employee_id or "").strip()
if not normalized_name or not normalized_employee_id:
raise RuntimeError("缺少姓名或工号,无法查询 OA 用户")
query_sql = """
SELECT TOP 1 v.id, v.workcode, v.lastname, v.jobtitle, v.departmentid, v.subcompanyid1,
d.departmentname, s.subcompanyname, j.jobtitlename
FROM userInfo_view v
LEFT JOIN HrmDepartment d ON v.departmentid = d.id
LEFT JOIN HrmSubCompany s ON v.subcompanyid1 = s.id
LEFT JOIN HrmJobTitles j ON v.jobtitle = j.id
WHERE v.workcode = ? AND v.lastname = ?
ORDER BY v.id
"""
cursor.execute(query_sql, [normalized_employee_id, normalized_name])
row = cursor.fetchone()
if not row:
return None
return {
"uid": str(row.id) if row.id is not None else "",
"employeeId": str(row.workcode) if row.workcode is not None else "",
"name": cls._normalize_oa_text(row.lastname),
"jobtitle": cls._normalize_oa_text(row.jobtitle),
"departmentid": str(row.departmentid) if row.departmentid is not None else "",
"subcompanyid1": str(row.subcompanyid1) if row.subcompanyid1 is not None else "",
"departmentName": cls._normalize_oa_text(row.departmentname),
"subcompanyName": cls._normalize_oa_text(row.subcompanyname),
"jobtitleName": cls._normalize_oa_text(row.jobtitlename),
}
finally:
try:
cursor.close()
finally:
connection.close()
@classmethod
def get_department_name(cls, department_id: str) -> str:
if not department_id or not department_id.strip():
return ""
connection = cls._connect()
cursor = connection.cursor()
try:
cursor.execute(
"SELECT TOP 1 departmentname FROM HrmDepartment WHERE id = ?",
[department_id.strip()],
)
row = cursor.fetchone()
return cls._normalize_oa_text(row.departmentname) if row and row.departmentname else ""
finally:
try:
cursor.close()
finally:
connection.close()
@classmethod
def get_subcompany_name(cls, subcompany_id: str) -> str:
if not subcompany_id or not subcompany_id.strip():
return ""
connection = cls._connect()
cursor = connection.cursor()
try:
cursor.execute(
"SELECT TOP 1 subcompanyname FROM HrmSubCompany WHERE id = ?",
[subcompany_id.strip()],
)
row = cursor.fetchone()
return cls._normalize_oa_text(row.subcompanyname) if row and row.subcompanyname else ""
finally:
try:
cursor.close()
finally:
connection.close()
@classmethod
def get_jobtitle_name(cls, jobtitle_id: str) -> str:
if not jobtitle_id or not jobtitle_id.strip():
return ""
connection = cls._connect()
cursor = connection.cursor()
try:
cursor.execute(
"SELECT TOP 1 jobtitlename FROM HrmJobTitles WHERE id = ?",
[jobtitle_id.strip()],
)
row = cursor.fetchone()
return cls._normalize_oa_text(row.jobtitlename) if row and row.jobtitlename else ""
finally:
try:
cursor.close()
finally:
connection.close()
-240
View File
@@ -1,240 +0,0 @@
"""
backend/app/services/oa_wecom_sync.py
用途:从 OA SQL Server userInfo_view 按本地工号回填 users.wecom_userid。
依赖:OASQLServerService、SQLAlchemy db、User 模型。
逻辑:先查本地有 employee_id 的用户,再按工号 IN 查询 OA;供 admin 绑定管理预览/写入。
"""
from __future__ import annotations
from typing import Any
from app import db
from app.models import User
from app.services.oa_sqlserver import OASQLServerService
_PREVIEW_LIMIT = 20
_OA_VIEW = 'userInfo_view'
_OA_IN_BATCH_SIZE = 500
def _clean_str(value) -> str | None:
"""
规范化字符串;空值返回 None。
@param value: 任意输入
Returns:
去首尾空白后的字符串,或 None
"""
if value is None:
return None
text = str(value).strip()
return text or None
def _load_local_users_with_employee_id() -> list[tuple[User, str]]:
"""
加载本地含有效工号的用户列表。
核心逻辑:查询 employee_id 非空记录,trim 后过滤空串。
Returns:
(User, employee_id) 元组列表
"""
rows: list[tuple[User, str]] = []
for user in db.session.query(User).filter(User.employee_id.isnot(None)).all():
employee_id = _clean_str(user.employee_id)
if not employee_id:
continue
rows.append((user, employee_id))
return rows
def fetch_oa_wecom_bindings_for_workcodes(workcodes: list[str]) -> list[dict[str, str | None]]:
"""
按工号批量查询 OA userInfo_view 中的企微 userid 映射。
核心逻辑:工号去重后分批 IN 查询,避免全表扫描。
@param workcodes: 本地 users.employee_id 列表
Returns:
每项含 workcode、wecom_userid、name
Raises:
RuntimeError: ODBC 连接或查询失败
"""
unique_codes: list[str] = []
seen: set[str] = set()
for code in workcodes:
cleaned = _clean_str(code)
if not cleaned or cleaned in seen:
continue
seen.add(cleaned)
unique_codes.append(cleaned)
if not unique_codes:
return []
connection = OASQLServerService._connect()
cursor = connection.cursor()
rows: list[dict[str, str | None]] = []
try:
for offset in range(0, len(unique_codes), _OA_IN_BATCH_SIZE):
batch = unique_codes[offset : offset + _OA_IN_BATCH_SIZE]
placeholders = ','.join('?' for _ in batch)
cursor.execute(
f"""
SELECT id, workcode, lastname
FROM userInfo_view
WHERE workcode IN ({placeholders})
AND id IS NOT NULL
""",
batch,
)
for row in cursor.fetchall():
workcode = _clean_str(row.workcode)
wecom_userid = _clean_str(row.id)
if not workcode or not wecom_userid:
continue
rows.append(
{
'workcode': workcode,
'wecom_userid': wecom_userid,
'name': _clean_str(row.lastname),
}
)
return rows
finally:
try:
cursor.close()
finally:
connection.close()
def sync_wecom_userids_from_oa(*, apply: bool) -> dict[str, Any]:
"""
执行 OA 工号 → wecom_userid 同步(本地用户驱动)。
核心逻辑:读本地工号 → 按 IN 查 OA → 匹配并 dry-run 或写入 wecom_userid。
@param apply: True 时提交数据库;存在 conflicts 时不写入
Returns:
统计摘要 dict(结构与企微通讯录同步兼容,便于前端复用)
Raises:
RuntimeError: OA 未配置、连接失败或 apply 时存在冲突
"""
local_users = _load_local_users_with_employee_id()
workcodes = [employee_id for _, employee_id in local_users]
oa_rows = fetch_oa_wecom_bindings_for_workcodes(workcodes)
summary: dict[str, Any] = {
'apply': apply,
'employee_id_source': f'oa:{_OA_VIEW}.workcode',
'department_ids': [],
'local_candidates': len(local_users),
'wecom_users': 0,
'wecom_without_employee_id': 0,
'local_matched': 0,
'would_update': 0,
'updated': 0,
'already_bound': 0,
'local_missing': 0,
'conflicts': [],
'missing_samples': [],
'pending_updates': [],
}
oa_by_workcode: dict[str, dict[str, str | None]] = {}
duplicate_workcodes: set[str] = set()
for row in oa_rows:
workcode = row['workcode']
if not workcode:
continue
if workcode in oa_by_workcode:
duplicate_workcodes.add(workcode)
summary['conflicts'].append(
{
'employee_id': workcode,
'username': '',
'new_wecom_userid': row['wecom_userid'],
'reason': 'duplicate_workcode_in_oa',
}
)
continue
oa_by_workcode[workcode] = row
summary['wecom_users'] = len(oa_by_workcode)
for local_user, employee_id in local_users:
if employee_id in duplicate_workcodes:
continue
oa_row = oa_by_workcode.get(employee_id)
if not oa_row:
summary['local_missing'] += 1
if len(summary['missing_samples']) < _PREVIEW_LIMIT:
summary['missing_samples'].append(
{
'employee_id': employee_id,
'username': local_user.username,
}
)
continue
wecom_userid = oa_row['wecom_userid']
name = oa_row.get('name')
if not wecom_userid:
summary['wecom_without_employee_id'] += 1
continue
summary['local_matched'] += 1
if local_user.wecom_userid == wecom_userid:
summary['already_bound'] += 1
continue
conflict = None
if local_user.wecom_userid and local_user.wecom_userid != wecom_userid:
conflict = {
'employee_id': employee_id,
'username': local_user.username,
'old_wecom_userid': local_user.wecom_userid,
'new_wecom_userid': wecom_userid,
}
else:
occupied = (
db.session.query(User)
.filter(User.wecom_userid == wecom_userid, User.id != local_user.id)
.first()
)
if occupied:
conflict = {
'employee_id': employee_id,
'username': local_user.username,
'new_wecom_userid': wecom_userid,
'occupied_by_user_id': occupied.id,
'occupied_by_username': occupied.username,
}
if conflict:
summary['conflicts'].append(conflict)
continue
summary['would_update'] += 1
if len(summary['pending_updates']) < _PREVIEW_LIMIT:
summary['pending_updates'].append(
{
'employee_id': employee_id,
'username': local_user.username,
'wecom_userid': wecom_userid,
'name': name,
}
)
if apply:
local_user.wecom_userid = wecom_userid
summary['updated'] += 1
if summary['conflicts'] and apply:
db.session.rollback()
raise RuntimeError('Conflicts detected; resolve manually before apply')
if apply and summary['updated'] > 0:
db.session.commit()
elif apply:
db.session.rollback()
return summary
-374
View File
@@ -1,374 +0,0 @@
import json
import os
import re
import time
from datetime import datetime
from html import escape
from urllib.parse import quote
from flask import current_app
from app import db
from app.models import ChatLog
from app.services.text2sql import Text2SQLService
class PLMOracleService:
_MAX_RESULT_ROWS = 50
_PLM_PREVIEW_SHARE_ROOT = (os.getenv("PLM_PREVIEW_SHARE_ROOT") or "\\\\192.168.0.11\\dss\\dssroot\\").strip()
_SUMMARY_COLUMNS = ("NAME", "EXTENTIONNAME", "FILETYPE", "FILESIZE", "RELATIVEPATH", "LASTACCESSTIME")
_MATERIAL_PATTERN = re.compile(r"\b[A-Z0-9]+(?:-[A-Z0-9]+)+\b", re.IGNORECASE)
_EXPLICIT_LABEL_PATTERN = re.compile(
r"(?:料号|料號|物料料号|物料料號|物料编号|物料編號|part\s*(?:no|number)?)\s*[::]?\s*([A-Z0-9][A-Z0-9._-]{5,})",
re.IGNORECASE,
)
_RELATIONAL_SQL = """
select *
from bi_file endb
where endb.revisionguid in (
select bb.revisionguid
from (
select v.end1, b.*
from viewobject_0 v, NT_00064_0 str, NT_00016_0 cad, bi_file b
where v.name in ('ITEM-CAD2D$', 'ITEM-CAD3D$')
and str.viewfk = v.guid
and str.end2$master = cad.masterfk
and cad.latestrevision like '%m%'
and b.revisionguid = cad.guid
union
select v.end1, b.*
from viewobject_0 v, NT_00064_0 str, NT_00018_0 cad, bi_file b
where v.name in ('ITEM-CAD2D$', 'ITEM-CAD3D$')
and str.viewfk = v.guid
and str.end2$master = cad.masterfk
and cad.latestrevision like '%m%'
and b.revisionguid = cad.guid
union
select v.end1, b.*
from viewobject_0 v,
StructureObject_0 str,
document_0 doc,
bi_file b
where v.name in ('RelatedDoc')
and str.viewfk = v.guid
and str.end2$master = doc.masterfk
and doc.latestrevision like '%m%'
and b.revisionguid = doc.guid
) bb,
item_0 i
where bb.end1 = i.guid
and i.id = :item_id
and i.latestrevision like '%m%'
)
and endb.lastaccesstime is not null
"""
_FILENAME_SQL = """
select *
from bi_file
where upper(name) like :name_pattern
and lastaccesstime is not null
order by lastaccesstime desc nulls last
"""
@classmethod
def supports(cls, query: str, agent) -> bool:
_ = agent
return bool(cls.extract_material_no(query))
@classmethod
def extract_material_no(cls, query: str) -> str | None:
text = str(query or "").strip().upper()
if not text:
return None
explicit = cls._EXPLICIT_LABEL_PATTERN.search(text)
if explicit:
return explicit.group(1).strip().upper()
direct_match = cls._MATERIAL_PATTERN.fullmatch(text)
if direct_match:
return direct_match.group(0).upper()
for match in cls._MATERIAL_PATTERN.finditer(text):
candidate = match.group(0).upper()
if any(ch.isalpha() for ch in candidate) and any(ch.isdigit() for ch in candidate):
return candidate
return None
@staticmethod
def _get_connect_kwargs() -> dict:
dsn = (os.getenv("PLM_ORACLE_DSN") or "").strip()
host = (os.getenv("PLM_ORACLE_HOST") or "192.168.0.11").strip()
port = int((os.getenv("PLM_ORACLE_PORT") or "1521").strip())
service_name = (os.getenv("PLM_ORACLE_SERVICE_NAME") or "").strip()
sid = (os.getenv("PLM_ORACLE_SID") or "orcl").strip()
kwargs = {
"user": (os.getenv("PLM_ORACLE_USERNAME") or "PLM").strip(),
"password": (os.getenv("PLM_ORACLE_PASSWORD") or "PLM").strip(),
}
if dsn:
kwargs["dsn"] = dsn
return kwargs
import oracledb
if service_name:
kwargs["dsn"] = oracledb.makedsn(host, port, service_name=service_name)
else:
kwargs["dsn"] = oracledb.makedsn(host, port, sid=sid)
return kwargs
@classmethod
def _connect(cls):
try:
import oracledb
except ImportError as exc:
raise RuntimeError("oracledb 未安装,无法连接 PLM Oracle") from exc
oracle_client_dir = Text2SQLService._get_oracle_client_dir()
Text2SQLService._prepare_oracle_runtime_env(oracle_client_dir)
Text2SQLService._init_oracle_client(oracledb)
return oracledb.connect(**cls._get_connect_kwargs())
@classmethod
def _execute_query(cls, sql: str, **params) -> tuple[list[str], list[tuple]]:
connection = cls._connect()
cursor = connection.cursor()
try:
cursor.execute(sql, params)
columns = [col[0] for col in cursor.description] if cursor.description else []
rows = cursor.fetchmany(cls._MAX_RESULT_ROWS + 1)
return columns, rows
finally:
try:
cursor.close()
finally:
connection.close()
@classmethod
def _query_files(cls, material_no: str) -> tuple[list[str], list[tuple], str]:
try:
columns, rows = cls._execute_query(cls._RELATIONAL_SQL, item_id=material_no)
if rows:
return columns, rows, "relational"
except Exception as exc:
if current_app:
current_app.logger.warning("[plm-oracle] relational query failed for %s: %s", material_no, exc)
columns, rows = cls._execute_query(
cls._FILENAME_SQL,
name_pattern=f"{material_no.upper()}%",
)
return columns, rows, "filename_fallback"
@staticmethod
def _format_datetime(value) -> str:
if value is None:
return "-"
if isinstance(value, datetime):
return value.strftime("%Y-%m-%d %H:%M:%S")
return str(value)
@staticmethod
def _format_size(value) -> str:
if value in (None, ""):
return "-"
try:
size = int(value)
except (TypeError, ValueError):
return str(value)
if size < 1024:
return f"{size} B"
if size < 1024 * 1024:
return f"{size / 1024:.1f} KB"
return f"{size / 1024 / 1024:.2f} MB"
@classmethod
def _build_plm_share_path(cls, storage_id, file_path, file_id: str) -> str:
parts = [cls._PLM_PREVIEW_SHARE_ROOT.rstrip("\\/")]
for value in (storage_id, file_path, file_id):
text = str(value or "").strip()
if not text:
continue
parts.append(text.replace("/", "\\").strip("\\"))
return "\\".join(part for part in parts if part)
@classmethod
def _render_file_name(cls, row: tuple, index_map: dict[str, int]) -> str:
def raw(column_name: str):
idx = index_map.get(column_name.upper())
if idx is None or idx >= len(row):
return None
value = row[idx]
return None if value in (None, "") else value
file_name = str(raw("NAME") or "").strip()
if not file_name:
return "-"
storage_id = raw("STORAGEID")
file_path = raw("FILEPATH")
file_id = str(raw("ID") or "").strip()
if not storage_id or file_path is None or not file_id:
return escape(file_name)
share_path = cls._build_plm_share_path(storage_id, file_path, file_id)
preview_href = f"#plm-preview?name={quote(file_name, safe='')}&url={quote(share_path, safe='')}"
return f'<a href="{preview_href}">{escape(file_name)}</a>'
@staticmethod
def _escape_markdown_cell(value: str) -> str:
return str(value).replace("|", r"\|").replace("\r", " ").replace("\n", "<br>")
@staticmethod
def _escape_html_text(value) -> str:
return escape(str(value), quote=True).replace("\r", " ").replace("\n", "<br>")
@classmethod
def _render_column_value(cls, row: tuple, column_name: str, index_map: dict[str, int]) -> str:
idx = index_map.get(column_name.upper())
if idx is None or idx >= len(row):
return "-"
value = row[idx]
if value in (None, ""):
return "-"
upper_name = column_name.upper()
if upper_name in {"CREATETIME", "LASTACCESSTIME"}:
return cls._format_datetime(value)
if upper_name == "FILESIZE":
return cls._format_size(value)
if upper_name == "NAME":
return cls._render_file_name(row, index_map)
return str(value)
@classmethod
def _build_record_summary(cls, row: tuple, index_map: dict[str, int], row_no: int) -> str:
parts = [f"记录 {row_no}"]
for column_name in cls._SUMMARY_COLUMNS:
if column_name.upper() not in index_map:
continue
rendered = cls._render_column_value(row, column_name, index_map)
label = {
"NAME": "文件名",
"EXTENTIONNAME": "扩展名",
"FILETYPE": "文件类型",
"FILESIZE": "文件大小",
"RELATIVEPATH": "相对路径",
"LASTACCESSTIME": "最后访问时间",
}.get(column_name.upper(), column_name)
if column_name.upper() == "NAME":
parts.append(f"{label}: {rendered}")
else:
parts.append(f"{label}: {cls._escape_html_text(rendered)}")
return " | ".join(parts)
@classmethod
def _build_record_detail_html(cls, row: tuple, columns: list[str], index_map: dict[str, int], row_no: int) -> str:
rows_html = []
for column_name in columns:
rendered_value = cls._render_column_value(row, column_name, index_map)
safe_value = rendered_value if column_name.upper() == "NAME" else cls._escape_html_text(rendered_value)
rows_html.append(
"<tr>"
f"<th style=\"padding:6px 10px;text-align:left;border:1px solid #d1d5db;background:#f8fafc;white-space:nowrap;\">{cls._escape_html_text(column_name)}</th>"
f"<td style=\"padding:6px 10px;border:1px solid #d1d5db;word-break:break-all;\">{safe_value}</td>"
"</tr>"
)
summary_html = cls._build_record_summary(row, index_map, row_no)
return (
"<details style=\"margin:12px 0;border:1px solid #e5e7eb;border-radius:8px;padding:8px 12px;background:#ffffff;\">"
f"<summary style=\"cursor:pointer;font-weight:600;\">{summary_html}</summary>"
"<div style=\"margin-top:10px;overflow:auto;\">"
"<table style=\"width:100%;border-collapse:collapse;font-size:13px;\">"
"<thead><tr>"
"<th style=\"padding:6px 10px;text-align:left;border:1px solid #d1d5db;background:#f1f5f9;width:220px;\">字段</th>"
"<th style=\"padding:6px 10px;text-align:left;border:1px solid #d1d5db;background:#f1f5f9;\">值</th>"
"</tr></thead>"
f"<tbody>{''.join(rows_html)}</tbody>"
"</table>"
"</div>"
"</details>"
)
@classmethod
def _build_answer(cls, material_no: str, columns: list[str], rows: list[tuple]) -> str:
if not rows:
return f"已在 PLM 中查询料号 `{material_no}`,未找到符合条件的相关资料。"
overflow = len(rows) > cls._MAX_RESULT_ROWS
visible_rows = rows[: cls._MAX_RESULT_ROWS]
index_map = {name.upper(): idx for idx, name in enumerate(columns)}
lines = [
f"已在 PLM 中查询到料号 `{material_no}` 的相关资料,共返回 {len(visible_rows)} 条记录"
+ ("(仅展示前 50 条)" if overflow else "。"),
"",
"以下结果支持点击单条记录展开,展开后按数据库原始字段顺序展示完整数据:",
]
for idx, row in enumerate(visible_rows, start=1):
lines.extend(["", cls._build_record_detail_html(row, columns, index_map, idx)])
if overflow:
lines.extend(["", "如需查看更多结果,请进一步限定料号或资料范围。"])
return "\n".join(lines)
@classmethod
def stream_chat(cls, query: str, user, agent, conversation_id: str | None = None, session_id: str | None = None):
start_time = time.time()
final_conversation_id = conversation_id or f"plm_{int(time.time())}"
material_no = cls.extract_material_no(query)
try:
if not material_no:
raise RuntimeError("未识别到有效料号,请输入类似 F3-A12M290000019 的料号。")
yield f"data: {json.dumps({'event': 'message', 'answer': f'已识别料号 `{material_no}`,正在查询 PLM 资料,请稍候...\\n'}, ensure_ascii=False)}\n\n"
columns, rows, query_mode = cls._query_files(material_no)
answer = cls._build_answer(material_no, columns, rows)
latency = int((time.time() - start_time) * 1000)
chat_log_id = None
try:
chat_log = ChatLog(
user_id=user.id,
agent_id=agent.id,
conversation_id=final_conversation_id,
session_id=session_id,
query=query,
answer=answer,
tokens_used=0,
latency=latency,
payload={
"material_no": material_no,
"row_count": min(len(rows), cls._MAX_RESULT_ROWS),
"query_mode": query_mode,
},
)
db.session.add(chat_log)
db.session.commit()
chat_log_id = chat_log.id
except Exception as exc:
if current_app:
current_app.logger.error("Failed to log PLM chat: %s", exc)
db.session.rollback()
end_data = {
"event": "message_end",
"answer": answer,
"replace_answer": True,
"chat_log_id": chat_log_id,
"conversation_id": final_conversation_id,
}
yield f"data: {json.dumps(end_data, ensure_ascii=False)}\n\n"
except Exception as exc:
if current_app:
current_app.logger.exception("[plm-oracle] stream_chat failed query=%s", query)
error_data = {
"event": "error",
"message": str(exc) or "PLM 查询失败",
"conversation_id": final_conversation_id,
}
yield f"data: {json.dumps(error_data, ensure_ascii=False)}\n\n"
@@ -18,7 +18,7 @@ from flask import current_app
from app import db
from app.core.config.settings import Config
from app.models import Agent
from app.services.dify import DifyService
from app.services.integrations.dify import DifyService
MAX_FINDINGS = 20
@@ -71,15 +71,23 @@ def finalize_receipt_schedule_run_if_complete(schedule_run_id: int) -> dict:
run.error_message = '; '.join(filter(None, (unit.error_message for unit in units if unit.status == 'failed')))[:2000] or None
run.response_summary_json = {**summary, 'awaiting_receipt_rpa': False, 'success_count': success_count, 'empty_count': skipped_count, 'failed_count': failed_count}
db.session.commit()
from app.services.shipping_notice.receipt_report_notification import deliver_schedule_receipt_summary
deliver_schedule_receipt_summary(run.id)
# 通知与库存 RPA 完全同构:run 终态后走通用排程出口一次性发 textcard+全部收料文件。
try:
task = run.task
if task is not None and task.notify_enabled:
from app.services.schedule.scheduler_service import _notify_schedule_run_wecom
_notify_schedule_run_wecom(task, run)
db.session.commit()
except Exception as wecom_exc:
current_app.logger.error('[schedule-run] receipt RPA wecom notify failed: %s', wecom_exc)
return {'finalized': True, 'status': run.status}
def _receipt_timeout_seconds() -> int:
"""读取收料回调等待上限;超时只标记失败,不会自动重试或重发。"""
try:
return max(60, int(current_app.config.get('SHIPPING_NOTICE_RPA_RECEIPT_TIMEOUT_SECONDS', 900)))
return max(60, int(current_app.config.get('FREIGHT_RPA_RECEIPT_TIMEOUT_SECONDS', 900)))
except (TypeError, ValueError):
return 900
@@ -7,7 +7,7 @@ from typing import Any
from app import db
from app.models import ScheduleRun, ScheduleTask, ShippingInventorySource, ShippingReceiptReportConfig, ShippingReceiptRpaUnitRun
from app.services.shipping_notice.receipt_rpa import write_receipt_export_batch_trigger
from app.services.shipping_notice.receipt_rpa import receipt_unit_parameters, receipt_warehouse_values, write_receipt_export_batch_trigger
RECEIPT_RPA_JOB_KEY = 'freight-receipt-rpa'
AWAITING_RECEIPT_RPA_CALLBACK_STATUS = 'awaiting_receipt_rpa_callback'
@@ -28,20 +28,23 @@ def _eligible_sources(task: ScheduleTask) -> list[tuple[ShippingInventorySource,
wanted = _wanted_source_codes(task)
rows = db.session.query(ShippingInventorySource, ShippingReceiptReportConfig).join(
ShippingReceiptReportConfig, ShippingReceiptReportConfig.inventory_source_id == ShippingInventorySource.id,
).filter(ShippingInventorySource.enabled.is_(True), ShippingReceiptReportConfig.enabled.is_(True)).all()
).filter(ShippingInventorySource.enabled.is_(True)).all()
return [(source, config) for source, config in rows if not wanted or source.source_code.upper() in wanted]
def _build_unit(source: ShippingInventorySource, config: ShippingReceiptReportConfig, warehouse_id: str | None) -> ShippingReceiptRpaUnitRun:
def _build_unit(
source: ShippingInventorySource, config: ShippingReceiptReportConfig,
warehouse_id: str | None, schedule_run_id: int,
) -> ShippingReceiptRpaUnitRun:
"""冻结可审计的收料执行单元;DBS 日期字段不进入查询快照。"""
callback_id = f'receipt:{uuid.uuid4().hex}'
snapshot = {
'config_id': config.id, 'config_version': config.config_version, 'connector_type': source.connector_type,
'report_path_json': config.report_path_json or {}, 'query_parameters_json': config.query_parameters_json or [],
'report_path_json': config.report_path_json or {}, 'query_parameters_json': receipt_unit_parameters(config),
'warehouse_id': warehouse_id, 'rpa_profile_id': source.rpa_profile_id,
}
return ShippingReceiptRpaUnitRun(
schedule_run_id=0, inventory_source_id=source.id, source_code=source.source_code,
schedule_run_id=schedule_run_id, inventory_source_id=source.id, source_code=source.source_code,
connector_type=source.connector_type, warehouse_id=warehouse_id, callback_id=callback_id,
status='awaiting_rpa', config_snapshot_json=snapshot,
)
@@ -78,11 +81,10 @@ def run_freight_receipt_rpa_schedule(task: ScheduleTask, run: ScheduleRun) -> Sc
"""写独立收料 trigger;一个 DBS Warehouse 或一个 Crane 站点对应一个单元。"""
units: list[ShippingReceiptRpaUnitRun] = []
for source, config in _eligible_sources(task):
warehouses = config.warehouse_ids_json or [] if source.connector_type == 'dbs' else [None]
# Warehouse 条件即逐仓拆分维度:运行时从条件派生仓库清单,不读取持久化列表。
warehouses = receipt_warehouse_values(config) if source.connector_type == 'dbs' else [None]
for warehouse_id in warehouses:
unit = _build_unit(source, config, str(warehouse_id) if warehouse_id else None)
unit.schedule_run_id = run.id
units.append(unit)
units.append(_build_unit(source, config, str(warehouse_id) if warehouse_id else None, run.id))
if not units:
return 0, 0, 0, 1, [], ['no enabled receipt report sources'], [{'step': 'freight_receipt_rpa', 'status': 'skipped'}]
db.session.add_all(units)
+1 -1
View File
@@ -57,7 +57,7 @@ def _shipping_receipt_sources_options() -> list[dict[str, Any]]:
rows = db.session.query(ShippingInventorySource, ShippingReceiptReportConfig).join(
ShippingReceiptReportConfig, ShippingReceiptReportConfig.inventory_source_id == ShippingInventorySource.id,
).filter(ShippingInventorySource.enabled.is_(True), ShippingReceiptReportConfig.enabled.is_(True)).all()
).filter(ShippingInventorySource.enabled.is_(True)).all()
return [{
'label': source.display_name or source.source_code, 'value': source.source_code,
'description': f'{source.connector_type} · 收料已配置',
+87 -3
View File
@@ -2,7 +2,7 @@
backend/app/services/schedule/job_registry.py
用途:平台内置排程 Job Registry(任务契约中心:key → handler + 展示信息 + params_schema + defaults)。
依赖:shipping_inventory_rpa_job、faq_hot_aggregate_job、fixed_assets_snapshot_job、voucher_check_job、job_params。
依赖:shipping_inventory_rpa_job、faq_hot_aggregate_job、fixed_assets_snapshot_job、voucher_check_job、voucher_po_print_job、voucher_oa_sales_release_job、job_params。
逻辑:internal_jobs API 与 platform_job 排程通过 platform_api_path 引用已注册 key;
api/schedule/platform_tasks.py 下发 params_schema 供前端 DynamicTaskParamsForm 通用渲染。
"""
@@ -140,11 +140,17 @@ def _register_builtin_platform_jobs() -> None:
run_shipping_post_ot_auto_fulfill_compensation_schedule,
)
from app.services.schedule.voucher_check_job import run_voucher_check_schedule
from app.services.schedule.voucher_oa_sales_release_job import run_voucher_oa_sales_release_schedule
from app.services.schedule.voucher_po_print_job import run_voucher_po_print_schedule
from app.services.schedule.contract_payment_job import (
run_contract_payment_alert_schedule,
run_contract_payment_sync_schedule,
)
from app.services.voucher_check.config import DEFAULT_JOB_PARAMS
from app.services.voucher_check.config import (
DEFAULT_JOB_PARAMS,
DEFAULT_OA_SALES_RELEASE_JOB_PARAMS,
DEFAULT_PO_PRINT_JOB_PARAMS,
)
from app.services.schedule.contract_payment_job import (
run_contract_payment_alert_schedule,
run_contract_payment_sync_schedule,
@@ -374,9 +380,50 @@ def _register_builtin_platform_jobs() -> None:
"type": "boolean",
"label": "缺资料通知",
"label_key": "admin.schedule.form.voucherCheckNotifyMissing",
"help": "总开关。缺件接收人在 Chat「通知配置」按文件类型设置。",
"help_key": "admin.schedule.form.voucherCheckNotifyMissingHint",
"required": False,
"default": True,
},
{
"key": "notify_failure_enabled",
"type": "boolean",
"label": "失败告警",
"label_key": "admin.schedule.form.voucherCheckNotifyFailure",
"help": "技术失败发给排程「选择通知人员」。",
"help_key": "admin.schedule.form.voucherCheckNotifyFailureHint",
"required": False,
"default": True,
},
),
defaults=dict(DEFAULT_JOB_PARAMS),
))
register_platform_job(PlatformJobDefinition(
key="accounting-voucher-po-print",
label="立账凭证 PO 订单生成",
label_key="admin.schedule.form.platformJobAccountingVoucherPoPrint",
handler=run_voucher_po_print_schedule,
description="每周二 05:00 按上月发票从 TGHX 取数,生成制式采购单 PDF 并上传到「PO订单」;早于 06:00 检核周批。",
description_key="admin.schedule.form.accountingVoucherPoPrintHint",
category="finance",
params_schema=(
{
"key": "scope_code",
"type": "select",
"label": "账套",
"label_key": "admin.schedule.form.voucherCheckScope",
"required": True,
"default": "HXJM",
"options": [{"value": "HXJM", "label": "HXJM"}],
},
{
"key": "profile_code",
"type": "text",
"label": "业务方 Profile",
"label_key": "admin.schedule.form.voucherCheckProfile",
"required": True,
"default": "sales",
},
{
"key": "notify_failure_enabled",
"type": "boolean",
@@ -386,7 +433,44 @@ def _register_builtin_platform_jobs() -> None:
"default": True,
},
),
defaults=dict(DEFAULT_JOB_PARAMS),
defaults=dict(DEFAULT_PO_PRINT_JOB_PARAMS),
))
register_platform_job(PlatformJobDefinition(
key="accounting-voucher-oa-sales-release",
label="立账凭证销货放行单拉取",
label_key="admin.schedule.form.platformJobAccountingVoucherOaSalesRelease",
handler=run_voucher_oa_sales_release_schedule,
description="每周二 05:30 从 E10 筛上月已归档销货放行单,下载表单 PDF 并上传到「销货单」;早于 06:00 检核周批。",
description_key="admin.schedule.form.accountingVoucherOaSalesReleaseHint",
category="finance",
params_schema=(
{
"key": "scope_code",
"type": "select",
"label": "账套",
"label_key": "admin.schedule.form.voucherCheckScope",
"required": True,
"default": "HXJM",
"options": [{"value": "HXJM", "label": "HXJM"}],
},
{
"key": "profile_code",
"type": "text",
"label": "业务方 Profile",
"label_key": "admin.schedule.form.voucherCheckProfile",
"required": True,
"default": "sales",
},
{
"key": "notify_failure_enabled",
"type": "boolean",
"label": "失败告警",
"label_key": "admin.schedule.form.voucherCheckNotifyFailure",
"required": False,
"default": True,
},
),
defaults=dict(DEFAULT_OA_SALES_RELEASE_JOB_PARAMS),
))
register_platform_job(PlatformJobDefinition(
key="in-transit-receipt-file",
@@ -371,6 +371,14 @@ def prepare_schedule_queue() -> int:
current_app.logger.warning("[schedule-worker] RPA cleanup warnings: %s", "; ".join(cleanup_warnings[:5]))
_worker_initialized = True
# 调拨来源等待回调 Job 的超时回收与下方 RPA 心跳告警同属每轮领取维护:
# 不能挂在 worker 启动一次性分支里,否则进程长期驻留期间超时任务永远无法终态化。
from app.services.in_transit_transfer.receipt_callback_bridge import recover_stale_waiting_source_jobs
transfer_stale = recover_stale_waiting_source_jobs()
if transfer_stale:
current_app.logger.info("[schedule-worker] recovered %d stale transfer waiting source jobs", transfer_stale)
try:
from app.services.shipping_notice.rpa_worker_heartbeat_alert import maybe_alert_rpa_worker_status
@@ -18,11 +18,12 @@ from typing import Any
from flask import current_app
from app import db
from app.models import ScheduleRun, ScheduleTask, User
from app.models import ScheduleRun, ScheduleTask, ShippingReceiptReportFile, User
from app.services.schedule.cron_util import normalize_cron_expr
from app.services.schedule.dify_snapshot import capture_dify_execution_snapshot
from app.services.schedule.excel_service import export_schedule_result_excel
from app.services.schedule import resolve_schedule_executor, resolve_schedule_header
from app.services.schedule import resolve_schedule_executor, resolve_schedule_header, normalize_platform_api_path
from app.services.schedule.freight_receipt_rpa_job import RECEIPT_RPA_JOB_KEY
from app.services.schedule.shipping_inventory_rpa_finalize import (
apply_deferred_schedule_run_state,
is_awaiting_rpa_schedule_run,
@@ -118,6 +119,36 @@ def _build_schedule_run_wecom_jump_params(task: ScheduleTask, run: ScheduleRun)
return params
def _receipt_report_files_for_run(run: ScheduleRun) -> list[ShippingReceiptReportFile]:
"""
收集收料排程 run 名下可投递的收料报表文件;非收料任务返回空列表。
核心逻辑:库存与收料 RPA 共用同一企微通知出口(_notify_schedule_run_wecom),
本函数是收料侧的唯一分叉点——按 platform_api_path 识别收料排程,返回该 run
全部单元已归档且未被清理(archive_deleted_at 为空)的报表文件。
"""
from app.models import ShippingReceiptRpaUnitRun
task = run.task
if (
task is None
or task.schedule_type != 'platform_job'
or normalize_platform_api_path(task.platform_api_path) != RECEIPT_RPA_JOB_KEY
):
return []
return (
ShippingReceiptReportFile.query.join(
ShippingReceiptRpaUnitRun, ShippingReceiptReportFile.unit_run_id == ShippingReceiptRpaUnitRun.id,
)
.filter(
ShippingReceiptRpaUnitRun.schedule_run_id == run.id,
ShippingReceiptReportFile.archive_deleted_at.is_(None),
)
.order_by(ShippingReceiptReportFile.id)
.all()
)
def _build_schedule_run_wecom_description(run: ScheduleRun) -> str:
"""
组装排程完成企微 textcard 正文。
@@ -140,6 +171,9 @@ def _build_schedule_run_wecom_description(run: ScheduleRun) -> str:
if inventory_raw_zip_available_from_summary(summary):
description += '\n原始库存包:点击本通知,登录 HXOPS 后自动下载'
receipt_files = _receipt_report_files_for_run(run)
if receipt_files:
description += f'\n收料报表文件 {len(receipt_files)} 份:已随本通知发送'
return description
@@ -148,8 +182,10 @@ def _notify_schedule_run_wecom(task: ScheduleTask, run: ScheduleRun) -> None:
排程完成后的通用企微通知。
核心逻辑:若 response_summary_json.domain_notification_managed=true(如立账凭证检核),
则跳过以免与领域缺件/失败告警重复。
库存与收料 RPA 共用本出口与同一套门禁:库存附加排程 Excel 与原始库存包;
收料附加该 run 全部单元的收料报表文件(见 _receipt_report_files_for_run)。
"""
from app.services.wecom_notify import (
from app.services.integrations.wecom.notify import (
upload_wecom_temp_media,
send_wecom_file_message,
send_wecom_textcard_message,
@@ -208,6 +244,21 @@ def _notify_schedule_run_wecom(task: ScheduleTask, run: ScheduleRun) -> None:
run.run_no, exc,
)
receipt_media: list[tuple[str, str]] = []
for receipt_file in _receipt_report_files_for_run(run):
try:
from app.services.file_assets.storage import file_asset_storage
receipt_media_id = upload_wecom_temp_media(
file_asset_storage.get_bytes(receipt_file.storage_key), receipt_file.original_filename,
)
receipt_media.append((receipt_media_id, receipt_file.original_filename))
except Exception as exc:
current_app.logger.warning(
'[wecom-schedule] receipt file media upload failed for run %s file %s: %s',
run.run_no, receipt_file.id, exc,
)
textcard_ok_count = 0
errors = []
@@ -263,6 +314,22 @@ def _notify_schedule_run_wecom(task: ScheduleTask, run: ScheduleRun) -> None:
except Exception as exc:
errors.append(f'{u.real_name or u.username}: raw zip exception={exc}')
for receipt_media_id, receipt_filename in receipt_media:
try:
receipt_audit = _create_audit(
f'{_WECOM_EVENT_TYPE}_receipt_file', u,
title, f'[收料报表] {receipt_filename}', uuid.uuid4().hex,
)
receipt_data = send_wecom_file_message(u.wecom_userid, receipt_media_id)
if receipt_data.get('errcode') == 0:
receipt_audit.status = 'sent'
else:
receipt_audit.error_code = str(receipt_data.get('errcode'))
receipt_audit.error_message = str(receipt_data.get('errmsg', 'unknown'))[:255]
errors.append(f'{u.real_name or u.username}: receipt file errcode={receipt_data.get("errcode")}')
except Exception as exc:
errors.append(f'{u.real_name or u.username}: receipt file exception={exc}')
if textcard_ok_count > 0:
run.wecom_notified = True
run.wecom_notified_at = datetime.utcnow()
@@ -39,14 +39,14 @@ _EMPTY_ARCHIVE_SUMMARY: dict[str, Any] = {
def get_inventory_archive_dir() -> str:
"""返回库存 RPA 原始 ZIP 归档根目录(自动创建)。"""
archive_dir = Path(
current_app.config.get("SHIPPING_NOTICE_RPA_INVENTORY_ARCHIVE_DIR")
current_app.config.get("FREIGHT_RPA_INVENTORY_ARCHIVE_DIR")
if current_app
else ""
)
if not str(archive_dir):
from app.core.config.settings import Config
archive_dir = Path(Config.SHIPPING_NOTICE_RPA_INVENTORY_ARCHIVE_DIR)
archive_dir = Path(Config.FREIGHT_RPA_INVENTORY_ARCHIVE_DIR)
archive_dir.mkdir(parents=True, exist_ok=True)
return str(archive_dir)
@@ -251,7 +251,7 @@ def _is_allowed_inventory_archive_path(zip_path: Path) -> bool:
"""
校验归档 ZIP 路径是否安全可下载。
核心逻辑:文件存在、后缀为 .zip、真实路径必须在 SHIPPING_NOTICE_RPA_INVENTORY_ARCHIVE_DIR 内。
核心逻辑:文件存在、后缀为 .zip、真实路径必须在 FREIGHT_RPA_INVENTORY_ARCHIVE_DIR 内。
"""
resolved = zip_path.resolve()
if resolved.suffix.lower() != ".zip":
@@ -272,7 +272,7 @@ def resolve_inventory_raw_zip_download(run: ScheduleRun) -> tuple[Path, str]:
解析 run 已归档的原始库存 ZIP 路径供下载接口 send_file。
核心逻辑:读取 summary.raw_inventory_zip_path,校验文件存在、后缀为 .zip、
且真实路径位于 SHIPPING_NOTICE_RPA_INVENTORY_ARCHIVE_DIR 内;任一不满足则 404。
且真实路径位于 FREIGHT_RPA_INVENTORY_ARCHIVE_DIR 内;任一不满足则 404。
Returns:
tuple[Path, str]: 归档 ZIP 绝对路径与建议下载文件名。
@@ -19,7 +19,10 @@ from app.models import ScheduleRun, ScheduleTask
from app.services.schedule.shipping_inventory_rpa_finalize import AWAITING_RPA_CALLBACK_STATUS
from app.services.shipping_notice.inventory_source_repository import list_database_inventory_sources
from app.services.shipping_notice.rpa import write_inventory_export_batch_trigger
from app.services.shipping_notice.rpa_worker_heartbeat import RPA_WORKER_OFFLINE_MESSAGE
from app.services.shipping_notice.rpa_worker_heartbeat import (
RPA_WORKER_OFFLINE_MESSAGE,
assert_inventory_rpa_worker_ready,
)
ScheduleExecuteResult = tuple[int, int, int, int, list[dict[str, Any]], list[str], list[dict[str, Any]]]
@@ -121,6 +124,8 @@ def run_shipping_inventory_rpa_schedule(task: ScheduleTask, run: ScheduleRun) ->
run_no = run.run_no or f"RUN{datetime.utcnow().strftime('%Y%m%d%H%M%S')}"
try:
# 写 trigger 前强制就绪检查:worker 离线立即 failed,不进入 awaiting_rpa_callback。
assert_inventory_rpa_worker_ready()
trigger_path = write_inventory_export_batch_trigger(
run_no,
sources,
@@ -0,0 +1,23 @@
"""
backend/app/services/schedule/voucher_oa_sales_release_job.py
用途:立账凭证销货放行单拉取 platform_job 薄封装。
依赖:voucher_check.oa_sales_release_runner。
逻辑:job_registry 注册 accounting-voucher-oa-sales-release 后由 schedule worker 调用;早于检核周批。
"""
from __future__ import annotations
from app.models import ScheduleRun, ScheduleTask
from app.services.voucher_check.oa_sales_release_runner import (
ScheduleExecuteResult,
run_oa_sales_release_batch,
)
def run_voucher_oa_sales_release_schedule(task: ScheduleTask, run: ScheduleRun) -> ScheduleExecuteResult:
"""
执行立账凭证销货放行单拉取排程。
核心逻辑:委托 oa_sales_release_runner;默认周二 05:30,检核周批 06:00 只扫目录。
"""
return run_oa_sales_release_batch(task, run)
@@ -0,0 +1,20 @@
"""
backend/app/services/schedule/voucher_po_print_job.py
用途:立账凭证 PO 订单生成 platform_job 薄封装。
依赖:voucher_check.po_print_runner。
逻辑:job_registry 注册 accounting-voucher-po-print 后由 schedule worker 调用;早于检核周批。
"""
from __future__ import annotations
from app.models import ScheduleRun, ScheduleTask
from app.services.voucher_check.po_print_runner import ScheduleExecuteResult, run_po_print_batch
def run_voucher_po_print_schedule(task: ScheduleTask, run: ScheduleRun) -> ScheduleExecuteResult:
"""
执行立账凭证 PO 订单生成排程。
核心逻辑:委托 po_print_runner;默认周二 05:00,检核周批 06:00 只扫目录。
"""
return run_po_print_batch(task, run)
Loaded 100 of 691 files, more files were not shown because too many files have changed in this diff. Show more