Merge branch 'dev' into order-delivery-reply

# Conflicts:
#	.env.shared
#	backend/app/api/chat.py
#	backend/app/core/config/settings.py
#	backend/app/models/user.py
#	backend/app/services/admin/permission_service.py
#	docs/demand.md
#	frontend/src/app/router/routes/workspace.routes.ts
#	frontend/src/features/admin/modules/users/components/UserFormModal.vue
#	frontend/src/features/admin/modules/users/composables/useUsersAdmin.ts
#	frontend/src/features/admin/types/user.types.ts
#	frontend/src/features/auth/stores/auth.store.ts
#	frontend/src/features/user/views/UserProfilePage.vue
#	frontend/src/locales/en/admin.json
#	frontend/src/locales/en/errors.json
#	frontend/src/locales/th/admin.json
#	frontend/src/locales/th/errors.json
#	frontend/src/locales/zh-CN/admin.json
#	frontend/src/locales/zh-CN/errors.json
#	frontend/src/locales/zh-TW/admin.json
#	frontend/src/locales/zh-TW/errors.json
#	frontend/src/shared/utils/auth.ts
This commit is contained in:
HTEWJ\26070045 committed 2026-09-22 10:37:59 +08:00
commit 616034a4cd
541 files changed
+43805 -14767

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'
@@ -11,8 +11,8 @@ 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.models import Agent, PermissionRequest, User
from app.services.integrations.wecom.notify import send_wecom_event_message
_BATCH_ACTION_LABELS = {'add': '新增', 'remove': '移除', 'set': '重置为'}
@@ -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,
@@ -318,6 +360,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 +428,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:
@@ -404,11 +449,14 @@ def update_customer(customer_id: int, data: dict[str, Any], *, actor_id: int | N
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 +466,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', {})
@@ -269,19 +256,18 @@ def _source_payload(source: ShippingInventorySource) -> dict[str, Any]:
def _receipt_report_config_payload(config: ShippingReceiptReportConfig) -> dict[str, Any]:
"""序列化独立收料配置,禁止把库存路径或凭据透传至管理端。"""
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,
'config_version': config.config_version,
'created_at': _iso(config.created_at), 'updated_at': _iso(config.updated_at),
}
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 +275,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 +298,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 +316,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 +326,8 @@ 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.updated_by = actor_id
db.session.flush()
after = _receipt_report_config_payload(config)
@@ -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)
@@ -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 / gateway_adapter / precheck_service / models。
逻辑:默认实现直接接线真实链路 —— 收料文件行读取走 movement_file_repository
(复用货代收料归档 + movement 解析规则,无文件/无规则时返回 None 由
预检走等待 RPA);路由归属规则(Q1)冻结前由 DefaultRouteResolver
fail-closed 拒绝;ERP 访问走 CapabilityGateway(绑定缺失时 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.movement_file_repository import ShippingReceiptFileRepository
from app.services.in_transit_transfer.precheck_service import (
RouteMapping,
RouteNotResolvedError,
@@ -21,28 +22,6 @@ 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:
"""默认路由解析:来源固定仓 + 外部系统仓库映射。
@@ -86,7 +65,7 @@ def set_transfer_dependencies(deps: TransferDeps | None) -> None:
def get_transfer_dependencies() -> TransferDeps:
"""返回装配好的 TransferDeps(测试覆盖优先,默认 fail-closed)。"""
"""返回装配好的 TransferDeps(测试覆盖优先;默认接线真实文件仓库/触发服务/ERP 网关)。"""
if _override is not None:
return _override
return TransferDeps(
@@ -98,21 +77,19 @@ def get_transfer_dependencies() -> TransferDeps:
class _DefaultRpaTrigger:
"""默认收料 RPA 触发器:复用既有收料 RPA trigger 目录。
"""默认收料 RPA 触发器:委托真实触发服务(trigger_receipt_rpa)。
依赖来源配置(ShippingInventorySource + 收料报表配置);来源未启用或
trigger 目录未配置时返回失败(fail-closed),不伪造等待。
真实链路 = 落单元行 + 原子写 trigger 文件;来源/收料配置缺失或 trigger
目录未配置时由触发服务返回 fail-closed(ok=False),本类只透传结果。
"""
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
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}"}
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"),
}
@@ -6,7 +6,9 @@
依赖:ShippingReceiptReportFile / ShippingReceiptReportConfig / file_asset_storage、
movement_contract、openpyxl。
逻辑:按来源取最新未过期(未清理)收料文件;无绑定 movement profile 或文件缺失时
返回 None(fail-closed),绝不伪造 ready 文件。行完整校验由下游 file_parser 完成。
返回 None(fail-closed),绝不伪造 ready 文件。行 dict = 领域字段 + 溯源字段
(sheet=实际工作表标题、row_no=工作表真实 1-based 行号);行完整校验由下游
file_parser 完成。
"""
from __future__ import annotations
@@ -31,14 +33,14 @@ class ShippingReceiptFileRepository:
source_code: 来源实例编码。
business_date: 业务日期(用于展示/匹配成熟度,不强制匹配文件日期)。
Returns:
ReadyReceiptFile(rows 为领域字段名 dict)或 None。
ReadyReceiptFile(rows 为领域字段 + 溯源 sheet/row_no 的 dict)或 None。
"""
from app.models import ShippingInventorySource, ShippingReceiptReportConfig, ShippingReceiptReportFile
source = ShippingInventorySource.query.filter_by(source_code=source_code, enabled=True).first()
if source is None:
return None
config = ShippingReceiptReportConfig.query.filter_by(inventory_source_id=source.id, enabled=True).first()
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
@@ -85,7 +87,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
@@ -112,7 +115,15 @@ def _extract_movement_rows(
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]
# 溯源字段: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]:
@@ -37,6 +37,7 @@ from app.services.in_transit_transfer.erp_adapter import ErpQueryTimeoutError
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 (
@@ -188,7 +189,9 @@ 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)
source_items = _precheck_invoices(
invoices=invoices,
@@ -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)
@@ -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(
schedule_run_id=0, # 调拨触发无 ScheduleRun,沿用 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}
-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
@@ -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,12 @@ 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,
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 +48,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 +67,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",
@@ -128,18 +165,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 +214,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,
+157 -8
View File
@@ -10,24 +10,72 @@ 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 _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 +117,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 +147,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):
@@ -195,6 +256,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 +307,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 +352,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
@@ -441,3 +550,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
@@ -31,7 +31,7 @@ from app.models.order_delivery_reply import (
OrderDeliveryErpLine,
OrderDeliveryLineState,
)
from app.services.wecom_notify import send_wecom_event_message
from app.services.integrations.wecom.notify import send_wecom_event_message
# 企微事件开关名;与 settings.WECOM_NOTIFY_EVENTS 默认值条目一致(同 contract_payment_warning 命名风格)。
WECOM_EVENT_TYPE = "order_delivery_reply_notify"
@@ -29,7 +29,7 @@ from app.models.order_delivery_reply import (
OrderDeliveryErpLine,
OrderDeliveryLineState,
)
from app.services.wecom_notify import send_wecom_event_message
from app.services.integrations.wecom.notify import send_wecom_event_message
# 企微事件开关名:与行级通知共用同一事件(WECOM_NOTIFY_EVENTS 已包含,无需新增配置)。
WECOM_EVENT_TYPE = "order_delivery_reply_notify"
-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
@@ -79,7 +79,7 @@ def finalize_receipt_schedule_run_if_complete(schedule_run_id: int) -> dict:
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,7 +28,7 @@ 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]
@@ -37,7 +37,7 @@ def _build_unit(source: ShippingInventorySource, config: ShippingReceiptReportCo
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(
@@ -78,7 +78,8 @@ 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
+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,
@@ -437,9 +443,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",
@@ -449,7 +496,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",
@@ -35,7 +35,7 @@ def _notify_production_after_sync(task: ScheduleTask, line_count: int) -> list[d
WECOM_EVENT_TYPE,
WORKSPACE_JUMP_PATH,
)
from app.services.wecom_notify import send_wecom_event_message
from app.services.integrations.wecom.notify import send_wecom_event_message
if not task.notify_enabled:
return []
@@ -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
@@ -149,7 +149,7 @@ def _notify_schedule_run_wecom(task: ScheduleTask, run: ScheduleRun) -> None:
核心逻辑:若 response_summary_json.domain_notification_managed=true(如立账凭证检核),
则跳过以免与领域缺件/失败告警重复。
"""
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,
@@ -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)
@@ -3,10 +3,11 @@ services/shipping_notice/auto_progress_controller.py
用途:P0-3 发货任务 AutoProgress 的正式 Task 级串行控制器。
依赖:Job transactional outbox、ShippingProcessExecution/Gate、CandidateSet、现有库存/RPA、匹配和 Excel 服务;
process_gate_job_service.cancel_inventory_external_wait_polls(显式 retry_rpa 终止轮询)。
process_gate_job_service.cancel_inventory_external_wait_polls(显式回到库存准备时终止轮询)。
逻辑:入口只创建或复用一个 Task 活动 Job;Worker 每次仅评估一个正式 Gate,Gate passed 与后继 Job
在同一数据库事务落库。显式 inventory_mode=retry_rpa 时覆盖 waiting_external 残留 poll,
强制入队 retry_inventory_preparation。库存源 RPA Attempt 仍由既有 per_source_rpa_service 独立并行执行。
在同一数据库事务落库。retry_rpa 或 manual_override_source 定向回 inventory_preparation 时
覆盖 waiting_external 残留 poll 并入队准备动作(改源默认 auto 复用指定源快照)。
库存源 RPA Attempt 仍由既有 per_source_rpa_service 独立并行执行。
"""
from __future__ import annotations
@@ -413,9 +414,15 @@ def submit_auto_progress(
from app.services.shipping_notice.process_gate_job_service import enqueue_gate_attempt_job
from app.services.shipping_notice.process_gate_service import queue_gate_attempt
# 显式回到库存准备:用户点「重新获取」(retry_rpa) 或人工改源
# (manual_override_source)。后者 inventory_mode 可为 auto(复用指定源快照),
# 但仍须取消残留 poll / 活动 Attempt,否则会只读轮询、不按新源取数。
explicit_inventory_retry = (
str(inventory_mode or '').strip() == 'retry_rpa'
and str(resume_gate_code or '').strip() == 'inventory_preparation'
str(resume_gate_code or '').strip() == 'inventory_preparation'
and (
str(inventory_mode or '').strip() == 'retry_rpa'
or str(trigger or '').strip() == 'manual_override_source'
)
)
if not explicit_inventory_retry:
sync_fulfillment_gates_from_task(
@@ -0,0 +1,59 @@
"""
backend/app/services/shipping_notice/conversation_title.py
用途:为订单抽取**新建**会话推导业务化标题,替代写死的「订单抽取」。
依赖:仅标准库(datetime/pathlib/re);禁止引入 Flask/DB 依赖,保持可单测。
逻辑:取首个非空附件文件名去扩展名 → 循环剥离邮件前缀 → 截断 24 字符 →
多文件追加「等 N 个文件」→ 追加 MM-DD 日期消歧 → 全空回退「订单抽取」。
仅新建会话时调用;存量会话标题一律不改(设计决策见 2026-09-17 spec)。
"""
from __future__ import annotations
import re
from datetime import datetime
from pathlib import PureWindowsPath
_FALLBACK_TITLE = '订单抽取'
_NAME_MAX_CHARS = 24
_TITLE_MAX_CHARS = 60
# re:/fw:/fwd: 为半角冒号且大小写不敏感;回复/转发为全角冒号。循环剥离以支持多层嵌套。
_MAIL_PREFIX_PATTERN = re.compile(r'^\s*(?:re|fw|fwd)\s*:|^\s*(?:回复|转发):', re.IGNORECASE)
def _strip_mail_prefixes(name: str) -> str:
"""循环剥离单个文件名开头的邮件前缀(Re:/Fw:/Fwd:/回复:/转发:)。"""
current = name.strip()
while True:
stripped = _MAIL_PREFIX_PATTERN.sub('', current, count=1).lstrip()
if stripped == current:
return current
current = stripped
def derive_order_extraction_title(filenames: list[str], created_at: datetime) -> str:
"""
按首个附件文件名推导订单抽取会话标题。
Args:
filenames: 本次冻结 Intake 对应的资产原始文件名,按 Intake 顺序;
允许包含空串占位(保持计数口径)。
created_at: 会话创建时间(服务器 UTC,不做时区换算),提供 MM-DD 消歧后缀。
Returns:
形如「PO#6075309 等 11 个文件 09-15」的标题;文件名全空时回退「订单抽取」;
末尾做 60 字符防御性钳制(24 字主名约束下正常不可达)。
"""
ordered = [str(name or '').strip() for name in filenames]
usable = [name for name in ordered if name]
if not usable:
return _FALLBACK_TITLE
# PureWindowsPath 同时把 '/' 与 '\' 视为目录分隔符,兼容两类上传来源的路径写法。
stem = PureWindowsPath(usable[0]).stem
base = _strip_mail_prefixes(stem)[:_NAME_MAX_CHARS].strip()
if not base:
return _FALLBACK_TITLE
parts = [base]
if len(ordered) > 1:
parts.append(f'等 {len(ordered)} 个文件')
parts.append(f'{created_at.month:02d}-{created_at.day:02d}')
return ' '.join(parts)[:_TITLE_MAX_CHARS]
@@ -26,17 +26,17 @@ def _fernet() -> Fernet:
Raises:
ServiceUnavailableError: 未配置或配置了无效的主密钥。
"""
key = str(current_app.config.get('SHIPPING_NOTICE_RPA_CREDENTIAL_KEY') or '').strip()
key = str(current_app.config.get('FREIGHT_RPA_CREDENTIAL_KEY') or '').strip()
if not key:
raise ServiceUnavailableError(
'SHIPPING_NOTICE_RPA_CREDENTIAL_KEY is not configured',
'FREIGHT_RPA_CREDENTIAL_KEY is not configured',
code='SHIPPING.RPA_CREDENTIAL_KEY_MISSING',
)
try:
return Fernet(key.encode('ascii'))
except (ValueError, UnicodeEncodeError) as exc:
raise ServiceUnavailableError(
'SHIPPING_NOTICE_RPA_CREDENTIAL_KEY is invalid',
'FREIGHT_RPA_CREDENTIAL_KEY is invalid',
code='SHIPPING.RPA_CREDENTIAL_KEY_INVALID',
) from exc
@@ -4,6 +4,9 @@ services/shipping_notice/customer_auto_resolution.py
用途:基于管理员审核的强证据受控自动确认 OT 客户。
依赖:ShippingIdentityEvidence/ShadowResolution/Task、customer_identity_gate、Flask 配置。
逻辑:Candidate 建单后只按影子快照中的已审核授权证据自动确认;不创建 Notice 或分配业务编号。
命中分级与复核侧共用:canonical 等值(unique_strong_match)与完整包含
(unique_containment_match,指纹整体出现在提取值中且证据授权)可自动确认;
截断包含(containment_weak)只供人工建议,永不进入本裁决。
"""
from __future__ import annotations
@@ -29,14 +32,18 @@ from app.services.shipping_notice.customer_identity_gate import (
customer_confirmation_facts,
)
from app.services.shipping_notice.customer_normalization import (
IDENTITY_MATCH_CONTAINMENT_STRONG,
IDENTITY_MATCH_EQUALITY,
canonical_identity_key,
classify_identity_containment,
is_public_email_domain,
normalize_customer_name,
normalize_domain,
normalize_email,
normalize_identity_evidence_value,
)
from app.services.shipping_notice.tool_common import cfg_bool, cfg_float, cfg_int, task_event_task_id
AUTO_RESOLUTION_VERSION = "customer-auto-v2"
AUTO_RESOLUTION_VERSION = "customer-auto-v3"
# 允许自动确认的裁决状态;质量门禁分母与审计均以该集合为准。
AUTO_CONFIRM_ELIGIBLE_STATUSES = frozenset({'unique_strong_match', 'unique_containment_match'})
CUSTOMER_AUDIT_EVENT_TYPES = (
"customer_auto_resolution_evaluated",
"customer_auto_confirmed",
@@ -65,8 +72,8 @@ def _auto_confirmation_quality_gate() -> dict[str, Any]:
eligible_samples = 0
correct_samples = 0
for shadow in labeled:
decision = _resolve_auto_customer_from_shadow_resolution(shadow)
if decision['status'] != 'unique_strong_match':
decision = resolve_auto_customer_decision(shadow)
if decision['status'] not in AUTO_CONFIRM_ELIGIBLE_STATUSES:
continue
eligible_samples += 1
if int(decision['customer_id']) == int(shadow.manual_customer_id):
@@ -229,23 +236,55 @@ def _verified_shadow_value(
config = definition.get('field_config') if isinstance(definition.get('field_config'), dict) else {}
context_source = config.get('context_source') if isinstance(config.get('context_source'), dict) else {}
try:
if context_source.get('option_key') == 'from_email':
return normalize_email(value)
if context_source.get('option_key') == 'from_domain':
return normalize_domain(value)
if config.get('normalizer_key') == 'name':
return normalize_customer_name(value) or None
return str(value or '').strip().upper() or None
# 与影子识别/证据导入共用同一归一化,保证复核键与存储键同源(含换行折叠)。
return normalize_identity_evidence_value(
value,
option_key=context_source.get('option_key'),
normalizer_key=config.get('normalizer_key'),
)
except Exception:
return None
def _resolve_auto_customer_from_shadow_resolution(shadow: ShippingCustomerShadowResolution) -> dict[str, Any]:
def _classify_auto_evidence_match(
*, runtime_normalized: str, evidence_normalized: str, option_key: str,
) -> str | None:
"""
对单个授权证据做自动确认视角的命中分级。
核心逻辑:邮箱/域名只做大小写无关精确等值;文本类先比 canonical 等值
(吸收标点/空白差异),再判「指纹完整出现在提取值中」的强包含;
截断包含(containment_weak)返回给展示层但在此一律判不命中——剩余部分
未经验证,无法排除「另一个更短名的完整客户」,禁止自动确认。
"""
if option_key in {'from_email', 'from_domain'}:
if runtime_normalized.casefold() == evidence_normalized.casefold():
return IDENTITY_MATCH_EQUALITY
return None
if canonical_identity_key(runtime_normalized) == canonical_identity_key(evidence_normalized):
return IDENTITY_MATCH_EQUALITY
match_kind = classify_identity_containment(
runtime_normalized, evidence_normalized, option_key=option_key,
)
return match_kind if match_kind == IDENTITY_MATCH_CONTAINMENT_STRONG else None
def resolve_auto_customer_decision(shadow: ShippingCustomerShadowResolution) -> dict[str, Any]:
"""
按影子记录的冻结定义和当前已审核授权证据求唯一自动确认客户。
业务定义、站点证据、公共邮箱域名及快照外字段都不是自动确认依据;多个客户命中时
一律返回歧义,即使其中一个客户累积的证据更多。
一律返回歧义,即使其中一个客户累积的证据更多。等值命中存在时包含命中不参与裁决;
仅「指纹完整出现在提取值中」(unique_containment_match)这一种包含形态在唯一且
授权时可自动确认,截断形态永不。
Args:
shadow: 已持久化的客户影子识别记录(须含规则快照与证据 JSON)。
Returns:
裁决字典:status(unique_strong_match / unique_containment_match /
ambiguous / unmatched / rule_snapshot_missing 等)、customer_id、
evidence(含 match_kind 溯源)与候选客户列表。
"""
snapshot = _rule_snapshot(shadow)
if snapshot is None:
@@ -256,6 +295,7 @@ def _resolve_auto_customer_from_shadow_resolution(shadow: ShippingCustomerShadow
if isinstance(item, dict) and str(item.get('id') or '')
}
matched: dict[int, list[dict[str, Any]]] = {}
match_tiers: dict[int, str] = {}
for evidence in shadow.evidence_json or []:
if not isinstance(evidence, dict):
continue
@@ -298,8 +338,12 @@ def _resolve_auto_customer_from_shadow_resolution(shadow: ShippingCustomerShadow
auto_match_allowed=True,
).all()
for record in records:
# 主数据中历史录入值也可能保留不同大小写;按指纹语义比较而非原始字符串比较。
if str(record.normalized_value or '').strip().casefold() != normalized.casefold():
match_kind = _classify_auto_evidence_match(
runtime_normalized=verified_normalized,
evidence_normalized=str(record.normalized_value or ''),
option_key=option_key,
)
if match_kind is None:
continue
if record.customer_id is None:
continue
@@ -311,16 +355,34 @@ def _resolve_auto_customer_from_shadow_resolution(shadow: ShippingCustomerShadow
'definition_id': definition_id,
'definition_code': definition.get('definition_code'),
'normalized_value': normalized,
'match_kind': match_kind,
'source': field_value_source,
'context_source': context_source,
})
if (
customer.id not in match_tiers
or match_kind == IDENTITY_MATCH_EQUALITY
):
match_tiers[customer.id] = match_kind
# [STEP] 等值优先:存在等值命中的客户时,包含命中客户不参与裁决;
# 截断包含已在分级阶段被排除,绝不出现在自动确认候选中。
equality_customer_ids = {cid for cid, kind in match_tiers.items() if kind == IDENTITY_MATCH_EQUALITY}
decision_customer_ids = equality_customer_ids or set(match_tiers)
matched = {cid: matched[cid] for cid in decision_customer_ids}
if len(matched) != 1:
result = _decision_base(shadow, status='ambiguous' if matched else 'unmatched')
result['evidence'] = [item for rows in matched.values() for item in rows]
result['candidate_customer_ids'] = sorted(matched)
return result
customer_id = next(iter(matched))
result = _decision_base(shadow, status='unique_strong_match')
result = _decision_base(
shadow,
status=(
'unique_strong_match'
if match_tiers[customer_id] == IDENTITY_MATCH_EQUALITY
else 'unique_containment_match'
),
)
result['customer_id'] = customer_id
result['evidence'] = matched[customer_id]
return result
@@ -362,7 +424,7 @@ def resolve_auto_customer_from_shadow(task: ShippingNotice | ShippingOrderTask)
if shadow is None:
return {"status": "no_shadow", "rule_version": AUTO_RESOLUTION_VERSION, "customer_id": None, "evidence": []}
decision = _resolve_auto_customer_from_shadow_resolution(shadow)
decision = resolve_auto_customer_decision(shadow)
quality_gate = _auto_confirmation_quality_gate()
if not quality_gate['is_eligible']:
return {
@@ -1,9 +1,12 @@
"""
services/shipping_notice/customer_normalization.py
用途:统一客户名称、简码、邮箱、域名和识别证据的标准化与基础校验。
用途:统一客户名称、简码、邮箱、域名和识别证据的标准化与基础校验,
并提供识别证据的 canonical 比较键与包含关系分级。
依赖:re、unicodedata 标准库。
逻辑:管理后台导入与运行期客户裁决共用,避免同一证据在不同入口产生不同匹配键。
逻辑:管理后台导入、运行期影子识别与自动确认复核共用同一证据归一化
(normalize_identity_evidence_value),避免同一证据在不同入口产生不同匹配键;
canonical 键用于标点/空白无关的等值比较,包含分级支撑客户识别的三层匹配。
"""
from __future__ import annotations
@@ -130,3 +133,97 @@ def normalize_identifier(identifier_type: Any, value: Any) -> str:
details={'field': 'identifier_value'},
)
return normalized
# 邮箱/域名上下文键:指纹语义为精确标识,禁止参与包含分级。
_IDENTITY_EMAIL_DOMAIN_OPTION_KEYS = frozenset({'from_email', 'from_domain'})
# 包含命中的最短 canonical 字符数:更短片段(如 'c/o'→'CO')不足以声明同主体,
# 且短指纹一律由 canonical 等值路径承担,不享受包含兜底。
IDENTITY_CONTAINMENT_MIN_CHARS = 8
# 包含关系等值性强弱标记:strong=指纹完整出现在提取值中;weak=提取值疑似指纹截断。
IDENTITY_MATCH_EQUALITY = 'approved_identity_evidence'
IDENTITY_MATCH_CONTAINMENT_STRONG = 'containment_strong'
IDENTITY_MATCH_CONTAINMENT_WEAK = 'containment_weak'
# 等值 > 完整包含 > 截断包含;数值越小身份信号越强。
IDENTITY_MATCH_TIER_RANK = {
IDENTITY_MATCH_EQUALITY: 0,
IDENTITY_MATCH_CONTAINMENT_STRONG: 1,
IDENTITY_MATCH_CONTAINMENT_WEAK: 2,
}
_CANONICAL_STRIP_RE = re.compile(r'[\W_]+', re.UNICODE)
def normalize_identity_evidence_value(
value: Any, *, option_key: Any = None, normalizer_key: Any = None,
) -> str | None:
"""
按识别定义冻结的字段配置生成证据匹配键;导入、影子识别与自动确认复核共用。
核心逻辑:与 identity_rules._normalize_for_snapshot、resolver._normalize、
customer_auto_resolution._verified_shadow_value 的历史分支一一对应;兜底分支统一
走 clean_text(折叠内部空白/换行),修复运行侧保留换行导致多行提取值永远无法
等值命中单行注册证据的不对称缺陷。
Args:
value: 已裁决 Header 字段值或管理员录入的原始证据值。
option_key: 字段上下文来源(from_email/from_domain 时按邮箱/域名校验归一)。
normalizer_key: 冻结 Schema 字段配置的 normalizer('name' 走客户名称词管线)。
Returns:
归一化匹配键;空值返回 None(调用方按各自契约决定跳过或报错)。
Raises:
ValidationError: 邮箱/域名值不合法(由下游 normalize_* 抛出,调用方自行容错)。
"""
kind = clean_text(option_key).lower() if option_key else ''
if kind == 'from_email':
return normalize_email(value)
if kind == 'from_domain':
return normalize_domain(value)
if clean_text(normalizer_key or '').lower() == 'name':
return normalize_customer_name(value) or None
return clean_text(value).upper() or None
def canonical_identity_key(value: Any) -> str:
"""
生成识别证据的 canonical 比较键:NFKC + casefold + 剔除全部非字母数字。
核心逻辑:中文等 Unicode 词字符保留(支持中文客户名),标点、空白、下划线
全部剔除,使 'QCH, INC.' 与 'QCH INC.' 这类打印差异在等值比较中不再分裂。
邮箱/域名指纹禁止使用本键比较('@'、'.' 属于语义字符),调用方须先分流。
"""
return _CANONICAL_STRIP_RE.sub('', unicodedata.normalize('NFKC', str(value or '')).casefold())
def classify_identity_containment(
runtime_normalized: Any, evidence_normalized: Any, *, option_key: Any = None,
) -> str | None:
"""
对文本类识别证据做双向包含分级,供客户识别的弱命中层使用。
Args:
runtime_normalized: 运行时提取值(已经 normalize_identity_evidence_value 归一)。
evidence_normalized: 库内已注册证据值(同上归一)。
option_key: 字段上下文来源;from_email/from_domain 直接返回 None。
Returns:
IDENTITY_MATCH_CONTAINMENT_STRONG:注册指纹完整出现在提取值中(提取多带
折行尾巴),身份信号可参与受控自动确认;
IDENTITY_MATCH_CONTAINMENT_WEAK:提取值疑似指纹截断片段(剩余部分未经验
证,无法区分「截断」与「另一个更短名的完整客户」),只允许作为人工确认建议;
None:无包含关系,或包含侧短于 IDENTITY_CONTAINMENT_MIN_CHARS。
"""
kind = clean_text(option_key).lower() if option_key else ''
if kind in _IDENTITY_EMAIL_DOMAIN_OPTION_KEYS:
return None
runtime_key = canonical_identity_key(runtime_normalized)
evidence_key = canonical_identity_key(evidence_normalized)
if not runtime_key or not evidence_key:
return None
if len(evidence_key) >= IDENTITY_CONTAINMENT_MIN_CHARS and evidence_key in runtime_key:
return IDENTITY_MATCH_CONTAINMENT_STRONG
if len(runtime_key) >= IDENTITY_CONTAINMENT_MIN_CHARS and runtime_key in evidence_key:
return IDENTITY_MATCH_CONTAINMENT_WEAK
return None
@@ -36,9 +36,10 @@ def refresh_candidate_shadow_resolution(candidate: ShippingOrderCandidate) -> Sh
resolution = resolve_candidate_identity(candidate, intake)
evidence = list(resolution['evidence'])
matches = list(resolution['customer_matches'])
# 状态一律以 resolver 的层级裁决为准(等值 > 完整包含 > 截断包含),
# 本地不再按分数重复判定,避免两处排序/歧义语义分叉;top_score 取排序首位的累计权重。
status = str(resolution['status'])
top_score = float(matches[0]['score']) if matches else None
tied = [item for item in matches if float(item['score']) == top_score] if top_score is not None else []
status = 'unmatched' if not matches else 'unique_candidate' if len(tied) == 1 else 'ambiguous'
row = db.session.query(ShippingCustomerShadowResolution).filter_by(candidate_id=int(candidate.id)).first()
if row is None:
row = ShippingCustomerShadowResolution(candidate_id=int(candidate.id), intake_id=int(candidate.intake_id))
@@ -11,6 +11,11 @@ services/shipping_notice/document_layout/order_profile_matcher.py
禁止表顶宽带兜底;多 pattern 观测结果并集与签名身份 token 口径一致;
主表业务行裁剪只消费模板 termination_rules/exclusion_regions,无硬编码结束词表;
无必选锚点的近亲模板才用表头原子硬互斥;已配置 required_anchors 时身份交给锚点门禁;
表头可经 Schema 别名表(header_to_field)把命中短语归一为 field:: 字段语义原子
(schema_canonical_header_atoms),实现跨措辞的身份对齐,未配置时退化为词级原子;
canonical 序列(schema_canonical_header_tokens)供 signature_conflict 硬门禁的
二次机会评估复用同一表头打分逻辑(effective = max(原始, canonical),仅无必选
锚点且契约可用时生效,七维上报分数维持原始值);
单逻辑表头将折行副标签按 x 并入所属列(保留文案),不拆成新身份列。
"""
@@ -126,6 +131,7 @@ def match_frozen_coordinate_profiles(
profiles: list[dict[str, Any]],
layout: dict[str, Any],
customer_hint_id: int | None = None,
header_to_field: dict[str, str] | None = None,
) -> ProfileMatchResult:
"""
对同一文档的冻结 Profile 做签名硬门禁、分项评分与唯一匹配。
@@ -134,6 +140,10 @@ def match_frozen_coordinate_profiles(
profiles: 已发布模板快照列表;须含 matching_signature 与 definition。
layout: 冻结 layout 快照,含 tables 与 coordinate_evidence。
customer_hint_id: 可选运行期客户 ID,仅用于 trusted_business_context 维度。
header_to_field: 可选 Schema 表头别名契约(TableHeaderContract.header_to_field,
key 为归一化表头文案、value 为 field_code);传入时无必选锚点路径的表头
原子互斥先经 schema_canonical_header_atoms 归一为字段语义原子再比对,
实现跨别名身份对齐;None/空时退化为词级原子(既有行为)。
Returns:
ProfileMatchResult:含 Top1/Top2/Margin、evidence_coverage 与候选分项得分。
@@ -233,6 +243,7 @@ def match_frozen_coordinate_profiles(
optional_hits=optional_hits,
customer_ids=raw.get('customer_ids') if isinstance(raw.get('customer_ids'), list) else None,
customer_hint_id=customer_hint_id,
header_to_field=header_to_field,
)
reason_codes.extend(hard_conflict_codes)
if _profile_requires_unavailable_structure_evidence(
@@ -894,8 +905,17 @@ def _compute_dimension_results(
optional_hits: list[bool],
customer_ids: list[int] | None,
customer_hint_id: int | None,
header_to_field: dict[str, str] | None = None,
) -> tuple[dict[str, MatchDimensionResult], list[str]]:
"""基于签名与冻结证据计算统一七维三态结果。"""
"""
基于签名与冻结证据计算统一七维三态结果。
Args:
header_to_field: 可选 Schema 表头别名契约;非 None/非空时表头原子互斥
(仅无必选锚点路径)先按别名归一为字段语义原子,None 时走词级原子;
同时启用 signature_conflict 门禁的二次机会评估(见 [STEP 1.1]),
七维上报分数不受其影响,维持原始值。
"""
hard_conflicts: list[str] = []
results: dict[str, MatchDimensionResult] = {}
@@ -906,20 +926,36 @@ def _compute_dimension_results(
signature=signature, observed=observed, required_hits=required_hits,
enforce_atom_discriminator=enforce_header_atoms,
)
# 七维上报维持原始得分;canonical 二次评估得分只参与下方 signature_conflict 门禁。
results['header_semantic_position'] = header_result
if (
enforce_header_atoms
and header_result.state == 'mismatched'
and _header_discriminator_atoms_conflict(signature=signature, observed=observed)
and _header_discriminator_atoms_conflict(
signature=signature, observed=observed, header_to_field=header_to_field,
)
):
hard_conflicts.append('profile_header_discriminator_conflict')
elif (
header_result.state == 'mismatched'
and signature
and signature.get('table_patterns')
and header_result.score < 0.35
):
hard_conflicts.append('profile_header_signature_conflict')
elif header_result.state == 'mismatched' and signature and signature.get('table_patterns'):
# [STEP 1.1] 二次机会门禁:原始软分被词级原子互斥压到 0.35 以下的候选,
# 在「无必选锚点 + 别名契约可用」前提下用 canonical token 复用同一打分
# 逻辑重估一次(effective = max(原始, canonical)),使跨别名措辞不再被
# 第二道表头硬门禁误杀;不满足前提时 effective 即原始分,行为零变化。
effective_score = header_result.score
if header_result.score < 0.35 and enforce_header_atoms and header_to_field:
canonical_result = _score_header_semantic_position(
signature=signature, observed=observed, required_hits=required_hits,
enforce_atom_discriminator=False,
expected_tokens_override=schema_canonical_header_tokens(
_signature_identity_header_tokens(signature), header_to_field,
),
observed_tokens_override=schema_canonical_header_tokens(
[str(item) for item in observed.get('header_tokens') or []], header_to_field,
),
)
effective_score = max(effective_score, canonical_result.score)
if effective_score < 0.35:
hard_conflicts.append('profile_header_signature_conflict')
# [STEP 2] column_topology
column_result = _score_column_topology(signature=signature, observed=observed, profile=profile)
@@ -969,16 +1005,32 @@ def _score_header_semantic_position(
observed: dict[str, Any],
required_hits: list[bool],
enforce_atom_discriminator: bool = True,
expected_tokens_override: list[str] | None = None,
observed_tokens_override: list[str] | None = None,
) -> MatchDimensionResult:
"""比对真实表头 token、横向顺序和位置。
核心逻辑:无必选锚点时先做表头原子硬互斥;有必选锚点则只走软评分。
期望侧先截断单逻辑表头的折行副标签污染。
Args:
expected_tokens_override: 期望侧 token 覆盖(如 Schema 别名归一后的
canonical 序列);None 时按 `_signature_identity_header_tokens`
既有口径取值,行为不变。提供时软评分(含词命中率与顺序比)整体
切换到该序列上进行,供二次机会门禁复用同一套打分逻辑。
observed_tokens_override: 观测侧 token 覆盖(口径同上);None 时按
`observed['header_tokens']` 既有口径取值,行为不变。
"""
if signature is None:
return MatchDimensionResult(state='unavailable', score=0.0)
expected_tokens = [str(item).casefold() for item in _signature_identity_header_tokens(signature)]
observed_tokens = [str(item).casefold() for item in observed.get('header_tokens') or []]
if expected_tokens_override is None:
expected_tokens = [str(item).casefold() for item in _signature_identity_header_tokens(signature)]
else:
expected_tokens = [str(item).casefold() for item in expected_tokens_override]
if observed_tokens_override is None:
observed_tokens = [str(item).casefold() for item in observed.get('header_tokens') or []]
else:
observed_tokens = [str(item).casefold() for item in observed_tokens_override]
required_ratio = (sum(required_hits) / len(required_hits)) if required_hits else 1.0
if not expected_tokens:
if not required_hits:
@@ -997,8 +1049,16 @@ def _score_header_semantic_position(
return MatchDimensionResult(state='mismatched', score=0.0)
matched = sum(1 for token in expected_tokens if token in observed_tokens)
token_ratio = matched / len(expected_tokens)
expected_order = [str(item).casefold() for item in _signature_identity_header_order(signature)]
observed_order = observed.get('header_tokens') or []
expected_order = (
expected_tokens
if expected_tokens_override is not None
else [str(item).casefold() for item in _signature_identity_header_order(signature)]
)
observed_order = (
observed_tokens
if observed_tokens_override is not None
else observed.get('header_tokens') or []
)
shared = [item for item in expected_order if item in observed_order]
order_ratio = 1.0
if len(shared) > 1:
@@ -1018,6 +1078,21 @@ def _score_header_semantic_position(
_HEADER_ATOM_STOPWORDS = frozenset({'and', 'the', 'of', 'or', 'to', 'for', 'with', 'by'})
_HEADER_ATOM_MIN_LEN = 3
_HEADER_PAREN_GLOSS = re.compile(r'[\((][^\))]*[\))]')
# 字段语义原子前缀:词级原子只含 [a-z0-9],不可能出现冒号,与前缀无碰撞空间。
_HEADER_FIELD_MARKER = 'field::'
def _header_normalized_words(text: str) -> list[str]:
"""
表头统一词管线:剥括号注记 → casefold → 去撇号 → 按非字母数字切分。
核心逻辑:词级原子化与 Schema 别名短语匹配共用同一切词口径,保证两条路径
产出的身份原子完全同源;返回非空小写词序列(中文等非 [a-z0-9] 文本切词为空,
调用方按各自的跳过策略处理)。
"""
normalized = _HEADER_PAREN_GLOSS.sub(' ', str(text).casefold())
normalized = re.sub(r"['’]", '', normalized)
return [part for part in re.split(r'[^a-z0-9]+', normalized) if part]
def _sanitize_signature_table_identity(
@@ -1081,32 +1156,209 @@ def _header_token_atoms(tokens: list[str]) -> frozenset[str]:
"""
将表头 token 拆成稳定原子,供无锚点近亲模板互斥。
核心逻辑:先拼接 token 再去掉括号注记(通用印刷 gloss,跨 token 空格切开时
仍可剥除),再去撇号并按非字母数字切分;过滤过短词与虚词。签名侧与运行时共用。
核心逻辑:先拼接 token(让跨 token 空格切开的括号注记仍可整体剥除),再走
_header_normalized_words 统一词管线切词;过滤过短词与虚词。签名侧与运行时共用。
"""
joined = ' '.join(str(token) for token in tokens)
normalized = _HEADER_PAREN_GLOSS.sub(' ', joined.casefold())
normalized = re.sub(r"['’]", '', normalized)
atoms: set[str] = set()
for part in re.split(r'[^a-z0-9]+', normalized):
for part in _header_normalized_words(joined):
if len(part) >= _HEADER_ATOM_MIN_LEN and part not in _HEADER_ATOM_STOPWORDS:
atoms.add(part)
return frozenset(atoms)
def schema_canonical_header_atoms(
tokens: list[str],
header_to_field: dict[str, str] | None,
) -> frozenset[str]:
"""
将表头 token 按 Schema 别名归一为字段语义原子,供订单模板身份匹配跨别名对齐。
用途:同一业务字段在不同供应商模板中的表头措辞不同(如 Ship Date / Requested
Ship Date / 出货日期),词级原子只能字面碰撞;本函数借助 Schema 别名表把命中
别名的表头文本升级为 field::<field_code> 标记原子,使身份比较基于字段语义而非
具体措辞。未配置别名时零行为变化,完全退化为词级原子。
核心逻辑:
- header_to_field 为 None/空 dict 时直接返回词级原子(兼容旧签名,零风险);
- 先把每个别名 key 经与 token 完全相同的词管线(剥括号注记 → casefold →
去撇号 → 按非字母数字切词)转为词元组;同一词元组 casefold 后指向多个
field_code 时整体弃用该短语——身份归属不允许歧义;
- 逐 token 用同一词管线切词后做贪心最长短语匹配:命中即消费整段并产出
field::<field_code> 原子(短语内单词不再残留);未命中的剩余单词沿用词级
原子的既有过滤(长度 >= _HEADER_ATOM_MIN_LEN 且不在 _HEADER_ATOM_STOPWORDS);
- 中文别名经词管线切词后为空词元组 → 自然跳过(有意行为):词级原子本就只
保留 [a-z0-9],中文措辞无法构成词级身份,语义升级依赖别名表配置英文别名。
Args:
tokens: 表头 token 列表(可为合并格长文案,如 "Requested Ship Date Unit
Price");空串/空白 token 会被跳过(吸收 MinerU 空格占位)。
header_to_field: TableHeaderContract.header_to_field(普通 dict[str, str],
key 为 Schema 别名的归一化表头文案,value 为 field_code);鸭子类型
消费,不引入 order_schema → matcher 反向依赖;None/空表示未配置。
Returns:
frozenset[str]:field::<field_code> 标记原子与词级原子的并集。
"""
if not header_to_field:
return _header_token_atoms(tokens)
# [STEP 1] 构建短语字典:别名 key → 词元组 → field_code;casefold 跨字段
# 碰撞的短语整体弃用(身份归属不允许歧义,宁缺勿错)。
grouped: dict[tuple[str, ...], dict[str, str]] = {}
for alias, field_code in header_to_field.items():
words = tuple(_header_normalized_words(alias))
if not words:
# 中文等非 [a-z0-9] 别名切词为空:无法参与词级匹配,有意跳过。
continue
grouped.setdefault(words, {}).setdefault(str(field_code).casefold(), str(field_code))
phrase_to_field: dict[tuple[str, ...], str] = {
words: next(iter(codes.values()))
for words, codes in grouped.items()
if len(codes) == 1
}
# [STEP 2] 逐 token 贪心最长短语匹配;未命中单词走既有词级原子过滤。
atoms: set[str] = set()
for token in tokens:
if not str(token).strip():
# 空串/纯空白 token(MinerU 空格占位)直接跳过。
continue
words = _header_normalized_words(token)
index = 0
while index < len(words):
match_end = 0
match_code = ''
# 从当前起点尝试最长短语(先试整段剩余,再逐级缩短)。
for end in range(len(words), index, -1):
code = phrase_to_field.get(tuple(words[index:end]))
if code is not None:
match_end = end
match_code = code
break
if match_end:
atoms.add(_HEADER_FIELD_MARKER + match_code)
index = match_end
continue
word = words[index]
if len(word) >= _HEADER_ATOM_MIN_LEN and word not in _HEADER_ATOM_STOPWORDS:
atoms.add(word)
index += 1
return frozenset(atoms)
def schema_canonical_header_tokens(
tokens: list[str],
header_to_field: dict[str, str] | None,
) -> list[str]:
"""
将表头 token 按 Schema 别名归一为序列语义的 canonical token 列表。
用途:供 `profile_header_signature_conflict` 二次机会门禁复用
`_score_header_semantic_position` 的既有软评分——词级互斥把跨别名措辞的
原始分压成 0 后,用本函数归一出的 canonical 序列重估一次,命中别名的片段
以统一的 field::<field_code> 标记项参与序列比较,实现跨措辞的软分 rescue。
与 `schema_canonical_header_atoms` 的关系:二者共用同一词管线
(`_header_normalized_words`)与同一贪心最长短语匹配口径、同一未命中词过滤,
但语义不同——atoms 是集合语义(去重、无序,供硬互斥集合全等比较),本函数
是序列语义(保序、允许重复,供软评分按序列比较)。二者各自独立实现,
不得互相调用/推导;同一输入下本函数结果去重即 atoms 结果(同源语义)。
核心逻辑:
- header_to_field 为 None/空 dict 时原样返回输入列表(零归一、零行为变化);
- 短语字典构建与 atoms [STEP 1] 完全同源:别名 key 经同一词管线转词元组,
同一词元组 casefold 后指向多个 field_code 时整体弃用(身份不允许歧义);
- 逐 token 贪心最长短语匹配:命中片段消费整段并在原位置产出**单个**
`field::<field_code>` 列表项(短语内单词不残留);未命中词按 atoms 同一
过滤(长度 >= _HEADER_ATOM_MIN_LEN 且不在 _HEADER_ATOM_STOPWORDS)原词保留;
- 空串/纯空白 token(MinerU 空格占位)跳过,与 atoms 口径一致。
Args:
tokens: 表头 token 列表(期望侧传 `_signature_identity_header_tokens`
的结果、观测侧传 `observed['header_tokens']`);可为合并格长文案。
header_to_field: TableHeaderContract.header_to_field(dict[str, str],
key 为 Schema 别名归一化表头文案、value 为 field_code);
None/空表示未配置。
Returns:
list[str]:canonical token 序列(保序、允许重复)。
"""
if not header_to_field:
return tokens
# [STEP 1] 短语字典:与 schema_canonical_header_atoms 完全同源的构建口径。
grouped: dict[tuple[str, ...], dict[str, str]] = {}
for alias, field_code in header_to_field.items():
words = tuple(_header_normalized_words(alias))
if not words:
# 中文等非 [a-z0-9] 别名切词为空:无法参与词级匹配,有意跳过。
continue
grouped.setdefault(words, {}).setdefault(str(field_code).casefold(), str(field_code))
phrase_to_field: dict[tuple[str, ...], str] = {
words: next(iter(codes.values()))
for words, codes in grouped.items()
if len(codes) == 1
}
# [STEP 2] 逐 token 贪心最长短语匹配;序列语义:命中产出单个标记列表项,
# 未命中单词原样保留(沿用 atoms 过滤),整体保序、允许重复。
canonical: list[str] = []
for token in tokens:
if not str(token).strip():
# 空串/纯空白 token(MinerU 空格占位)直接跳过。
continue
words = _header_normalized_words(token)
index = 0
while index < len(words):
match_end = 0
match_code = ''
# 从当前起点尝试最长短语(先试整段剩余,再逐级缩短)。
for end in range(len(words), index, -1):
code = phrase_to_field.get(tuple(words[index:end]))
if code is not None:
match_end = end
match_code = code
break
if match_end:
canonical.append(_HEADER_FIELD_MARKER + match_code)
index = match_end
continue
word = words[index]
if len(word) >= _HEADER_ATOM_MIN_LEN and word not in _HEADER_ATOM_STOPWORDS:
canonical.append(word)
index += 1
return canonical
def _header_discriminator_atoms_conflict(
*,
signature: dict[str, Any] | None,
observed: dict[str, Any],
header_to_field: dict[str, str] | None = None,
) -> bool:
"""签名与观测表头原子集合不一致时视为互斥冲突(仅无必选锚点路径调用)。"""
"""
签名与观测表头原子集合不一致时视为互斥冲突(仅无必选锚点路径调用)。
Args:
header_to_field: 可选 Schema 表头别名契约;非 None/非空时签名侧与观测侧
token 均先经 schema_canonical_header_atoms 归一为字段语义原子再比较
全等,使跨别名措辞(同字段不同表头文案)不再误判互斥;None/空时
两侧均走词级原子(既有行为,零变化)。
"""
if signature is None or not signature.get('table_patterns'):
return False
expected_tokens = _signature_identity_header_tokens(signature)
observed_tokens = [str(item) for item in observed.get('header_tokens') or []]
if not expected_tokens or not observed_tokens:
return False
return _header_token_atoms(expected_tokens) != _header_token_atoms(observed_tokens)
if header_to_field:
expected_atoms = schema_canonical_header_atoms(expected_tokens, header_to_field)
observed_atoms = schema_canonical_header_atoms(observed_tokens, header_to_field)
else:
expected_atoms = _header_token_atoms(expected_tokens)
observed_atoms = _header_token_atoms(observed_tokens)
return expected_atoms != observed_atoms
def _score_column_topology(
@@ -56,6 +56,7 @@ from app.services.shipping_notice.order_schema.field_rules import normalize_orde
from app.services.shipping_notice.reservation_region import (
apply_reservation_region_candidates,
reservation_region_candidates_from_layout,
resolve_candidate_line_numbers,
)
@@ -551,6 +552,10 @@ def _candidate_for_sample(
header_field_id=str((reservation_fields.get('header') or {}).get('field_id') or '') or None,
line_field_id=str((reservation_fields.get('line') or {}).get('field_id') or '') or None,
line_count=len(rows),
# 盲测与正式解析共用 LN 值定位,防止预览与正式路由行归属不一致。
line_numbers=resolve_candidate_line_numbers([
row.get('customer_po_line_no') if isinstance(row, dict) else None for row in rows
]),
)
if applied.header_value and reservation_fields.get('header'):
header = reservation_fields['header']
@@ -0,0 +1,290 @@
"""
backend/app/services/shipping_notice/done_line_report.py
用途:「我的待办」已完成(已核验上传成功)发货通知的平铺明细行报表读模型与专用导出。
依赖:query_service 的可见性与上传成功口径(_visible_tasks_query_for_todos /
_verified_upload_success_sql_expr);shipping_order_snapshot 冻结快照。
逻辑:Notice(uploaded) → OT → Snapshot → SnapshotLine 展开为标准 12 字段行;页面另附
OT/business 编号列便于溯源,导出严格 12 列不落编号。已用数量 / open_qty 当前无
数据源,契约占位为 None(前端与 Excel 均留空)。约定出货日期取行级 required_date
(field_values_json),缺失时回退快照表头 typed 列;订单单号取表头
source_order_number(field_id 键)。支持 客户 / 料号 / 发货通知日期(Notice
创建日期)筛选,按明细行分页;导出复用同一查询,行数受 DONE_LINE_EXPORT_LIMIT 防护。
"""
from __future__ import annotations
from datetime import date, datetime, time
from io import BytesIO
from typing import Any
from zoneinfo import ZoneInfo
from openpyxl import Workbook
from sqlalchemy import asc, desc
from app import db
from app.core.errors import ValidationError
from app.models import (
ShippingNotice,
ShippingOrderField,
ShippingOrderSnapshot,
ShippingOrderSnapshotLine,
ShippingOrderTask,
)
from app.services.shipping_notice.query_service import (
_verified_upload_success_sql_expr,
_visible_tasks_query_for_todos,
)
# 导出防护上限:超出即截断(明细行报表场景远低于该量级)。
DONE_LINE_EXPORT_LIMIT = 10000
# 导出固定 12 列中文表头;顺序即业务标准格式,OT 编号不落列。
DONE_REPORT_HEADERS: tuple[str, ...] = (
"客户", "客户编号", "订单日期", "订单项次", "料号", "数量",
"约定出货日期", "客户PO", "已用数量", "open qty", "订单单号", "单价",
)
def _parse_notice_date(value: Any, *, label: str) -> date:
"""解析 YYYY-MM-DD 日期参数;非法输入抛 ValidationError,禁止静默吞掉。"""
text = str(value or '').strip()
if not text:
raise ValidationError(f'{label} must be YYYY-MM-DD', code='SHIPPING.DONE_LINE_DATE_INVALID')
try:
return datetime.strptime(text[:10], '%Y-%m-%d').date()
except ValueError as exc:
raise ValidationError(f'{label} must be YYYY-MM-DD', code='SHIPPING.DONE_LINE_DATE_INVALID') from exc
def _done_lines_query(
user_id: int,
*,
is_admin: bool = False,
customer: str | None = None,
part_number: str | None = None,
notice_date_from: Any = None,
notice_date_to: Any = None,
):
"""
构造已完成通知明细行的联表查询(Notice → OT → Snapshot → SnapshotLine)。
核心逻辑:仅取已核验上传成功的正式 Notice;可见性复用待办口径(非管理员仅创建者);
客户按快照 客户名称/客户编号 模糊、料号按 行料号/客户料号 模糊、发货通知日期按
Notice created_at 自然日闭区间过滤。
Raises:
ValidationError: 日期参数非法。
"""
q = (
_visible_tasks_query_for_todos(user_id, is_admin=is_admin)
.filter(_verified_upload_success_sql_expr())
.join(ShippingOrderTask, ShippingOrderTask.id == ShippingNotice.order_task_id)
.join(ShippingOrderSnapshot, ShippingOrderSnapshot.task_id == ShippingOrderTask.id)
.join(ShippingOrderSnapshotLine, ShippingOrderSnapshotLine.snapshot_id == ShippingOrderSnapshot.id)
)
customer_needle = str(customer or '').strip()
if customer_needle:
like = f"%{customer_needle}%"
q = q.filter(
db.or_(
ShippingOrderSnapshot.customer_name.ilike(like),
ShippingOrderSnapshot.customer_code.ilike(like),
)
)
part_needle = str(part_number or '').strip()
if part_needle:
like = f"%{part_needle}%"
q = q.filter(
db.or_(
ShippingOrderSnapshotLine.part_number.ilike(like),
ShippingOrderSnapshotLine.customer_part_number.ilike(like),
)
)
if notice_date_from:
from_day = notice_date_from if isinstance(notice_date_from, date) else _parse_notice_date(notice_date_from, label='notice_date_from')
q = q.filter(ShippingNotice.created_at >= datetime.combine(from_day, time.min))
if notice_date_to:
to_day = notice_date_to if isinstance(notice_date_to, date) else _parse_notice_date(notice_date_to, label='notice_date_to')
q = q.filter(ShippingNotice.created_at <= datetime.combine(to_day, time.max))
return q
def _report_field_ids() -> dict[tuple[str, str], str]:
"""读取报表所需的标准字段资产 id(field_code+scope 唯一),供 JSON 值回源。"""
rows = ShippingOrderField.query.filter(
ShippingOrderField.field_code.in_(('required_date', 'source_order_number')),
ShippingOrderField.status == 'active',
).all()
return {(row.field_code, row.scope): str(row.id) for row in rows}
def _date_text(value: Any) -> str | None:
"""日期值统一为 YYYY-MM-DD 文本;date 对象取日期部分,字符串截前十位。"""
if value in (None, ''):
return None
if hasattr(value, 'isoformat'):
return str(value.isoformat())[:10]
text = str(value).strip()
return text[:10] or None
def _num_text(value: Any) -> float | None:
"""数量/单价序列化为 JSON number;缺失返回 None(禁止 0 冒充)。"""
if value in (None, ''):
return None
return float(value)
def _serialize_done_line(
notice: ShippingNotice,
snapshot: ShippingOrderSnapshot,
line: ShippingOrderSnapshotLine,
field_ids: dict[tuple[str, str], str],
) -> dict[str, Any]:
"""按标准 12 字段 + 溯源编号序列化一行明细;无数据源字段契约留空。"""
required_date_field_id = field_ids.get(('required_date', 'line'))
required_date = (
(line.field_values_json or {}).get(required_date_field_id)
if required_date_field_id else None
)
if required_date in (None, ''):
required_date = snapshot.required_date
source_order_field_id = field_ids.get(('source_order_number', 'header'))
source_order_number = (
(snapshot.header_values_json or {}).get(source_order_field_id)
if source_order_field_id else None
)
return {
# 溯源编号:仅页面展示,导出不落列。
'task_no': notice.task_no,
'business_no': notice.business_no,
# 标准 12 字段。
'customer_name': snapshot.customer_name,
'customer_code': snapshot.customer_code,
'order_date': _date_text(snapshot.order_date),
'line_no': line.line_no,
'part_number': line.part_number,
'qty': _num_text(line.qty),
'required_date': _date_text(required_date),
'customer_po_number': snapshot.customer_po_number,
'used_qty': None,
'open_qty': None,
'source_order_number': source_order_number,
'unit_price': _num_text(line.unit_price),
}
def list_done_notice_lines(
user_id: int,
*,
is_admin: bool = False,
customer: str | None = None,
part_number: str | None = None,
notice_date_from: Any = None,
notice_date_to: Any = None,
page: int = 1,
page_size: int = 20,
) -> dict[str, Any]:
"""
分页列出已完成通知的平铺明细行(跨 Notice 混排,不按 OT 聚合)。
Returns:
{items, page, page_size, total};item 结构见 _serialize_done_line。
"""
normalized_page = max(1, int(page))
normalized_page_size = max(1, min(int(page_size), 100))
q = _done_lines_query(
user_id,
is_admin=is_admin,
customer=customer,
part_number=part_number,
notice_date_from=notice_date_from,
notice_date_to=notice_date_to,
)
total = int(q.count())
field_ids = _report_field_ids()
items: list[dict[str, Any]] = []
if total:
offset = (normalized_page - 1) * normalized_page_size
rows = (
q.with_entities(ShippingNotice, ShippingOrderSnapshot, ShippingOrderSnapshotLine)
.order_by(
desc(ShippingNotice.created_at), desc(ShippingNotice.id),
asc(ShippingOrderSnapshotLine.position),
)
.offset(offset)
.limit(normalized_page_size)
.all()
)
items = [
_serialize_done_line(notice, snapshot, line, field_ids)
for notice, snapshot, line in rows
]
return {
'items': items,
'page': normalized_page,
'page_size': normalized_page_size,
'total': total,
}
def build_done_lines_xlsx(
user_id: int,
*,
is_admin: bool = False,
customer: str | None = None,
part_number: str | None = None,
notice_date_from: Any = None,
notice_date_to: Any = None,
) -> tuple[BytesIO, str]:
"""
按当前筛选生成标准 12 列明细 Excel(不落 OT 编号列),返回流与下载文件名。
核心逻辑:与列表同源查询、不分页;超过 DONE_LINE_EXPORT_LIMIT 截断并在文件名
带时间戳,避免同日下载互相覆盖。单元格空值写 None(留空),禁止以 0 伪装。
"""
q = _done_lines_query(
user_id,
is_admin=is_admin,
customer=customer,
part_number=part_number,
notice_date_from=notice_date_from,
notice_date_to=notice_date_to,
)
rows = (
q.with_entities(ShippingNotice, ShippingOrderSnapshot, ShippingOrderSnapshotLine)
.order_by(
desc(ShippingNotice.created_at), desc(ShippingNotice.id),
asc(ShippingOrderSnapshotLine.position),
)
.limit(DONE_LINE_EXPORT_LIMIT)
.all()
)
field_ids = _report_field_ids()
workbook = Workbook()
sheet = workbook.active
sheet.title = '通知明细'
sheet.append(list(DONE_REPORT_HEADERS))
for notice, snapshot, line in rows:
item = _serialize_done_line(notice, snapshot, line, field_ids)
sheet.append([
item['customer_name'],
item['customer_code'],
item['order_date'],
item['line_no'],
item['part_number'],
item['qty'],
item['required_date'],
item['customer_po_number'],
item['used_qty'],
item['open_qty'],
item['source_order_number'],
item['unit_price'],
])
buffer = BytesIO()
workbook.save(buffer)
buffer.seek(0)
stamp = datetime.now(ZoneInfo('Asia/Shanghai')).strftime('%Y%m%d_%H%M%S')
filename = f'done-lines-{stamp}.xlsx'
return buffer, filename
@@ -0,0 +1,129 @@
"""
services/shipping_notice/effective_order_view.py
用途:向履约链提供「冻结快照 + 冻结后人工修正」的有效订单值视图。
依赖:export.order_field_id_values(冻结投影)、ShippingOrderFieldValue/ShippingOrderLine/
ShippingOrderTask/ShippingOrderSnapshot(修正事实与行对位)。
逻辑:快照仍是审计锚点,本模块把当前 accepted Extraction 的 FieldValue 按(行 position × field_id)
对位叠加到快照投影上,供库存匹配、Excel 导出与 Notice 行物化统一消费;整行替换(增删行)
后 position 不再可比,行级叠加保守跳过(保持冻结值),由后续行集有效视图统一承接。
"""
from __future__ import annotations
from decimal import Decimal, InvalidOperation
from typing import Any
from app import db
from app.models import (
ShippingOrderFieldValue,
ShippingOrderLine,
ShippingOrderSnapshot,
ShippingOrderTask,
)
from app.services.shipping_notice.export import order_field_id_values
def _owner_task(task: Any) -> Any:
"""与 export.order_field_id_values 同源的任务归属解析(Notice → OT;OT 原样返回)。"""
order_task_id = getattr(task, 'order_task_id', None)
if order_task_id:
return db.session.get(ShippingOrderTask, order_task_id)
return task
def effective_order_field_values(task: Any) -> tuple[dict[str, Any], list[dict[str, Any]]]:
"""
返回叠加了冻结后人工修正的订单 Header/Line 有效值(形状同 order_field_id_values)。
核心逻辑:以冻结快照为基线;当前 accepted Extraction 的 FieldValue 按(行 position ×
field_id)对位覆盖。当前 Extraction 与快照 Extraction 不同(发生过整行替换)时跳过
行级叠加,避免错位污染匹配键;单头值不受行替换影响,始终叠加最新已接受值。
Args:
task: ShippingNotice 或 ShippingOrderTask。
Returns:
(header dict[field_id, value], lines list[dict[field_id, value]])。
"""
header, lines = order_field_id_values(task)
owner = _owner_task(task)
current_id = getattr(owner, 'current_order_extraction_id', None)
if current_id is None:
return header, lines
snapshot = (
db.session.get(ShippingOrderSnapshot, int(owner.order_snapshot_id))
if getattr(owner, 'order_snapshot_id', None) else None
)
header = dict(header)
lines = [dict(row) for row in lines]
values = ShippingOrderFieldValue.query.filter_by(extraction_id=int(current_id)).all()
# [STEP 1] 单头修正:整行替换会把单头决定复制到新 Extraction(见 task_order_field_editor),
# 因此单头值始终以当前 Extraction 的已接受值为准。
for item in values:
if item.line_id is None:
header[str(item.field_id)] = item.value_json
# [STEP 2] 行级修正:仅在当前 Extraction 即冻结来源 Extraction 时按 position 对位。
if snapshot is not None and int(current_id) == int(snapshot.extraction_id):
position_by_line_id = {
int(row.id): int(row.position)
for row in ShippingOrderLine.query.filter_by(extraction_id=int(current_id)).all()
}
overlay_by_index: dict[int, dict[str, Any]] = {}
for item in values:
if item.line_id is None:
continue
index = position_by_line_id.get(int(item.line_id))
if index is None:
continue
overlay_by_index.setdefault(index, {})[str(item.field_id)] = item.value_json
for index, row in enumerate(lines):
row.update(overlay_by_index.get(index, {}))
return header, lines
def _coerce_qty(value: Any) -> Decimal | None:
"""把字段值安全转为数量;空/非法值返回 None。"""
if value in (None, ''):
return None
try:
return Decimal(str(value).replace(',', '').strip())
except (InvalidOperation, ValueError, TypeError):
return None
def effective_line_facts_for_notice(owner: ShippingOrderTask) -> dict[int, dict[str, Any]]:
"""
按 snapshot_line_id 返回 Notice 行物化所需的有效事实(强类型键 + 完整字段值)。
核心逻辑:经 effective_order_field_values 取有效值后,按冻结履约规则的
required_field_ids 把 part_number/reservation_id/qty 三个用途键解析为强类型事实;
缺少规则映射时对应键为 None(由消费方回退冻结列)。
Args:
owner: 已冻结订单的 ShippingOrderTask。
Returns:
{snapshot_line_id: {'part_number', 'reservation_id', 'qty', 'field_values'}}。
Raises:
ValueError: 任务没有冻结快照。
"""
snapshot = (
db.session.get(ShippingOrderSnapshot, int(owner.order_snapshot_id))
if getattr(owner, 'order_snapshot_id', None) else None
)
if snapshot is None:
raise ValueError('任务没有可用于通知行物化的冻结订单快照')
_header, lines = effective_order_field_values(owner)
required_ids = (snapshot.rule_versions_json or {}).get('fulfillment_rule', {}).get('required_field_ids')
required_ids = required_ids if isinstance(required_ids, dict) else {}
part_fid = str(required_ids.get('part_number') or '')
rsv_fid = str(required_ids.get('reservation_id') or '')
qty_fid = str(required_ids.get('qty') or '')
facts: dict[int, dict[str, Any]] = {}
for line_orm, values in zip(snapshot.lines, lines, strict=True):
facts[int(line_orm.id)] = {
'part_number': values.get(part_fid) if part_fid else None,
'reservation_id': values.get(rsv_fid) if rsv_fid else None,
'qty': _coerce_qty(values.get(qty_fid)) if qty_fid else None,
'field_values': dict(values),
}
return facts
@@ -2,8 +2,10 @@
依赖:受控 HTML 网格解析、冻结订单 Schema 表头契约、PO/Reservation 标准化。
逻辑:订单字段表头只复用 Run/当前发布 Schema 的显式别名;邮件专属的分配事实
仍使用受控固定列。表格歧义或缺 PO 保留原因,不将正文直接转成订单。
仍使用受控固定列。表格歧义保留原因,不将正文直接转成订单。
无 PO 表头时,若已映射料号或预约号仍解析行(供 merge mpn_fallback);二者皆无才整表跳过。
非法非 PO 字段跳过本列并记 issue,避免可选列拖垮 Reservation/库存源线索。
reservation_id 通过安全抽取后写入归一本体(含短数字行序后缀)。
多表按文档顺序叠行:靠前为新,同行身份键先到为准;旧表仅补全新表未覆盖的行。
"""
@@ -22,6 +24,7 @@ from app.services.shipping_notice.order_schema.field_rules import (
)
from app.services.shipping_notice.order_schema.table_contract import normalize_table_header
from app.services.shipping_notice.po_number import normalize_po_number
from app.services.shipping_notice.reservation_id import validated_reservation_id
def _schema_configs(schema_definition: dict[str, Any]) -> dict[str, dict[str, Any]]:
@@ -56,14 +59,24 @@ def _supplement_row_identity(row: dict[str, Any]) -> tuple[str, str, str] | None
return None
_IDENTITY_FIELD_CODES = frozenset({
'part_number', 'customer_part_number', 'reservation_id',
})
_PO_FIELD_CODES = frozenset({'customer_po_number', 'po_number'})
def _mapping_has_identity(mapped_fields: set[str]) -> bool:
"""表头或行是否具备可与 PDF 关联的身份列(料号或预约号)。"""
return bool(mapped_fields & _IDENTITY_FIELD_CODES)
def _normalize_schema_row(
values: dict[str, str], *, schema_definition: dict[str, Any], issues: list[str],
) -> dict[str, Any] | None:
"""按冻结 Schema 规范化并校验 EML 单元格;非法非 PO 字段跳过,不拖垮整行。
核心逻辑:PO 仍是行身份门槛;其余字段解析/校验失败只记
``email_supplement_field_invalid`` 并省略该字段,避免可选列(如 PO Date)
非法时把 Reservation / 库存源线索一并丢掉。
核心逻辑:有 PO 则写入 PO;无 PO 时须具备料号或合法预约号才成行,供 merge 兜底。
其余字段解析/校验失败只记 ``email_supplement_field_invalid`` 并省略该字段。
Args:
values: 表头映射后的 field_code → 原始单元格文本。
@@ -71,7 +84,7 @@ def _normalize_schema_row(
issues: 可追加的问题码列表(调用方持有,本函数原地写入)。
Returns:
规范化后的补充行;缺有效 PO 时返回 None。
规范化后的补充行;无 PO 且无料号/预约号时返回 None。
"""
configs = _schema_configs(schema_definition)
normalized: dict[str, Any] = {}
@@ -80,7 +93,7 @@ def _normalize_schema_row(
if config is None:
normalized[field_code] = raw_value
continue
# [STEP] 非 PO 字段失败只跳过本列;PO 失败则稍后由 po 门槛统一拒行。
# [STEP] 非 PO 字段失败只跳过本列;PO 失败则稍后统一处理。
try:
value = normalize_order_field_value(raw_value, config)
except Exception:
@@ -89,14 +102,26 @@ def _normalize_schema_row(
if value is None or not validate_order_field_value(value, config):
issues.append('email_supplement_field_invalid')
continue
# [STEP] reservation_id:校验已通过安全抽取后,落库写入归一本体(如 35354-1 → 35354)。
if field_code == 'reservation_id':
cleaned = validated_reservation_id(raw_value) or validated_reservation_id(value)
if not cleaned:
issues.append('email_supplement_field_invalid')
continue
value = cleaned
normalized[field_code] = value
po_code = 'customer_po_number' if 'customer_po_number' in normalized else 'po_number'
po_number = normalize_po_number(normalized.get(po_code))
if not po_number:
issues.append('email_supplement_row_po_missing')
return None
normalized[po_code] = po_number
return normalized
if po_number:
normalized[po_code] = po_number
return normalized
# [STEP] 无 PO:有料号或合法预约号仍成行;否则丢弃。
has_part = any(str(normalized.get(code) or '').strip() for code in ('part_number', 'customer_part_number'))
has_reservation = bool(validated_reservation_id(normalized.get('reservation_id')))
if has_part or has_reservation:
return normalized
issues.append('email_supplement_row_po_missing')
return None
def _field_map(grid: Any, *, schema_definition: dict[str, Any]) -> tuple[dict[int, str], list[str]]:
@@ -127,11 +152,25 @@ def _field_map(grid: Any, *, schema_definition: dict[str, Any]) -> tuple[dict[in
selected_by_field[field_code] = (priority, column)
elif len(hits) > 1:
issues.append('email_supplement_header_ambiguous')
if not ({'customer_po_number', 'po_number'} & set(mapped.values())):
mapped_fields = set(mapped.values())
if not (mapped_fields & _PO_FIELD_CODES):
# 无 PO:有料号/预约号时仅作可观测标记(不阻断解析);否则硬失败。
issues.append('email_supplement_po_header_missing')
return mapped, sorted(set(issues))
def _blocking_table_issues(table_issues: list[str], *, mapped_fields: set[str]) -> list[str]:
"""返回会跳过整表的 issue;无 PO 但已有身份列时,po_header_missing 不阻断。"""
soft_po_missing = (
'email_supplement_po_header_missing' in table_issues
and _mapping_has_identity(mapped_fields)
)
return [
code for code in table_issues
if not (soft_po_missing and code == 'email_supplement_po_header_missing')
]
def _schema_header_priority(schema_definition: dict[str, Any], field_code: str, normalized_header: str) -> int:
"""返回字段表头的 Schema 声明顺序,供同字段多别名确定性裁决。"""
priorities: list[int] = []
@@ -192,7 +231,7 @@ def parse_email_allocation_tables(*, html_tables: list[str], content_hash: str,
continue
mapping, table_issues = _field_map(grid, schema_definition=schema_definition)
issues.extend(table_issues)
if table_issues:
if _blocking_table_issues(table_issues, mapped_fields=set(mapping.values())):
continue
for row_index in range(1, grid.row_count):
values: dict[str, str] = {}
@@ -250,7 +289,9 @@ def parse_email_allocation_text(*, body_text: str, content_hash: str, schema_def
break
expected.append(field)
if not ({'customer_po_number', 'po_number'} & set(expected)):
return result
# 与 HTML 路径一致:无 PO 时须已识别料号或预约号表头,否则安全返回空。
if not _mapping_has_identity(set(expected)):
return result
column_count = len(expected)
rows: list[dict[str, Any]] = []
seen_rows: set[tuple[str, ...]] = set()
+304 -56
View File
@@ -5,6 +5,8 @@ services/shipping_notice/export.py
依赖:ShippingExcelTemplate/ShippingExportArtifact、冻结 ShippingOrderSnapshot、库存快照与 openpyxl。
逻辑:锁定 Source、模板、冻结订单快照、库存解析 Profile 和库存快照,按白名单映射写入模板;
导出前按本单 match_keys(通常 reservation+part)裁剪库存候选再匹配,避免全量快照进匹配;
整单 ODM 裁决依次应用:客户 odm_ids 范围 → 用户选择(OT.chosen_odm_id)→
唯一可行交集自动收敛;模板消费 odm 字段时生效;
Header 的 system_fact:warehouse_id 取本 Notice 唯一行库位(PVMI 契约);多库位冲突失败;
在最终导出行集上按通知明细项次写入模板;内部遍历序号不属于业务字段。
订单内部项次 line_no 只能通过 order_field 映射,不得再作为系统事实。
@@ -45,8 +47,12 @@ from app.services.file_assets.storage import file_asset_storage
def _notice_source_code(task: ShippingNotice) -> str | None:
"""返回正式 Notice 行级匹配中唯一使用的库存源;多源导出必须显式拒绝。"""
task_id = getattr(task, 'order_task_id', None)
"""返回正式 Notice 行级匹配中唯一使用的库存源;多源导出必须显式拒绝。
匹配事实的 task_id 挂在正式 OT 上:传 Notice 时取 order_task_id,
传 OT 本身时取 id(整单 ODM 候选投影会在物化前以 OT 调用)。
"""
task_id = getattr(task, 'order_task_id', None) or getattr(task, 'id', None)
if task_id is None:
return None
task_id = int(task_id)
@@ -63,6 +69,23 @@ def _notice_source_code(task: ShippingNotice) -> str | None:
return codes[0] if len(codes) == 1 else None
def _notice_chosen_odm(task: ShippingNotice) -> str | None:
"""读取当前行级匹配事实上的整单 ODM 用户选择(notice_odm_choice_service 落库)。"""
task_id = getattr(task, 'order_task_id', None) or getattr(task, 'id', None)
if task_id is None:
return None
values = [
str(row[0]).strip()
for row in db.session.query(ShippingNoticeLineInventoryMatch.chosen_odm_id).filter(
ShippingNoticeLineInventoryMatch.task_id == int(task_id),
ShippingNoticeLineInventoryMatch.is_current.is_(True),
ShippingNoticeLineInventoryMatch.chosen_odm_id.isnot(None),
).distinct().all()
if row[0]
]
return values[0] if values else None
def _notice_inventory_file_id(task: ShippingNotice) -> int | None:
"""从 Notice 行级匹配读取本次导出的唯一库存文件。"""
task_id = getattr(task, 'order_task_id', None)
@@ -119,7 +142,10 @@ def _source_notice_for_order_facts(notice: ShippingNotice) -> ShippingNotice:
def order_field_id_values(task: ShippingNotice) -> tuple[dict[str, Any], list[dict[str, Any]]]:
"""从 OT 冻结订单事实按稳定 field_id 返回 Header/Line 值。"""
"""从 OT 冻结订单事实按稳定 field_id 返回 Header/Line 值。
库存匹配/Excel 消费方应改用 effective_order_view.effective_order_field_values 获取含冻结后修正的有效值。
"""
from app.services.shipping_notice.task_supersession_service import assert_task_not_supersession_blocked
assert_task_not_supersession_blocked(task)
owner = db.session.get(ShippingOrderTask, task.order_task_id) if getattr(task, 'order_task_id', None) else task
@@ -426,29 +452,7 @@ def _match_inventory_lines(
return []
if not match_keys:
raise ValueError('库存解析模板缺少订单与库存匹配键')
from app.models import ShippingInventoryField
ids = {
int(item.get('inventory_field_id'))
for item in match_keys
if isinstance(item, dict) and str(item.get('inventory_field_id') or '').isdigit()
}
catalog = {
str(item.id): str(item.id)
for item in ShippingInventoryField.query.filter(ShippingInventoryField.id.in_(ids)).all()
}
normalized_keys: list[dict[str, str]] = []
for item in match_keys:
if not isinstance(item, dict):
raise ValueError('库存解析模板匹配键无效')
field_id = str(item.get('inventory_field_id') or '').strip()
inventory_field = catalog.get(field_id)
if not inventory_field:
raise ValueError('库存解析模板引用的库存字段已不可用')
normalized_keys.append({
'order_field_id': str(item.get('order_field_id') or ''),
'inventory_field': inventory_field,
})
normalized_keys = _normalize_match_keys(match_keys)
result: list[dict[str, Any]] = []
for position, order_line in enumerate(order_lines, start=1):
expected = [
@@ -586,34 +590,176 @@ def _input_checksum(
return hashlib.sha256(raw.encode('utf-8')).hexdigest()
def generate_shipment_excel(
task: ShippingNotice,
) -> tuple[str, str, ShippingExportArtifact]:
"""
按库存源发布模板生成 Excel,并在当前事务新增不可变 Artifact。
【AI 触发时机】:仅由 generate_excel Tool 在库存匹配完成后调用;Agent 禁止传模板或字段映射。
def _resolve_odm_inventory_field_id() -> int | None:
"""返回 odm_id 库存字段目录 ID;目录未配置或已停用时返回 None(整单 ODM 裁决整体跳过)。"""
field = ShippingInventoryField.query.filter_by(field_code='odm_id', status='active').first()
return int(field.id) if field is not None else None
Returns:
(绝对文件路径, 下载文件名, 待随任务事务提交的 Artifact)。
def _normalize_match_keys(match_keys: list[dict[str, Any]]) -> list[dict[str, str]]:
"""
校验并规范化库存解析模板匹配键为 {order_field_id, inventory_field} 列表。
Raises:
ValueError: 库存源、模板、订单 Extraction 或解析 Profile 未形成完整发布链。
AppError: 没有可导出的满足/已审计放行行,或输入事实不完整。
ValueError: 匹配键缺失、无效或引用的库存字段已不可用。
"""
from app.services.shipping_notice.task_disposition_service import task_is_active
from app.services.shipping_notice.task_supersession_service import assert_task_not_supersession_blocked
ids = {
int(item.get('inventory_field_id'))
for item in match_keys
if isinstance(item, dict) and str(item.get('inventory_field_id') or '').isdigit()
}
catalog = {
str(item.id): str(item.id)
for item in ShippingInventoryField.query.filter(ShippingInventoryField.id.in_(ids)).all()
}
normalized_keys: list[dict[str, str]] = []
for item in match_keys:
if not isinstance(item, dict):
raise ValueError('库存解析模板匹配键无效')
field_id = str(item.get('inventory_field_id') or '').strip()
inventory_field = catalog.get(field_id)
if not inventory_field:
raise ValueError('库存解析模板引用的库存字段已不可用')
normalized_keys.append({
'order_field_id': str(item.get('order_field_id') or ''),
'inventory_field': inventory_field,
})
return normalized_keys
# OT 在库存门禁通过后才物化为正式 Notice;之后导出链路只接受 Notice。
from app.models import ShippingOrderTask
if isinstance(task, ShippingOrderTask):
from app.services.shipping_notice.shipping_notice_creation_service import (
create_shipping_notice_after_inventory_gate,
def _per_line_odm_sets(
order_lines: list[dict[str, Any]],
inventory_lines: list[dict[str, Any]],
normalized_keys: list[dict[str, str]],
odm_key: str,
) -> list[set[str]]:
"""逐导出行收集命中库存行的 odm 值集合;缺匹配键行与未命中行返回空集。"""
sets: list[set[str]] = []
for order_line in order_lines:
expected = [
(_match_text(order_line.get(item['order_field_id'])), item['inventory_field'])
for item in normalized_keys
]
if any(not value for value, _field in expected):
sets.append(set())
continue
matched = {
_match_text(row.get(odm_key))
for row in inventory_lines
if all(_match_text(row.get(field)) == value for value, field in expected)
}
matched.discard('')
sets.append(matched)
return sets
def _intersect_odm_sets(sets: list[set[str]]) -> set[str]:
"""各行命中 odm 集合的交集;未命中行(空集)不参与约束,全部为空返回空集。"""
active = [item for item in sets if item]
if not active:
return set()
return set.intersection(*active)
def _adjudicate_notice_odm(
*,
line_values: list[dict[str, Any]],
inventory_lines: list[dict[str, Any]],
match_keys: list[dict[str, Any]],
odm_field_id: int | None,
snapshot: ShippingOrderSnapshot,
chosen_odm_raw: str | None,
) -> dict[str, Any]:
"""
整单(Notice)级 ODM 收敛裁决;模板不消费 odm 字段时直接跳过。
逻辑:客户 ODM ID 范围非空先过滤;用户选择(OT.chosen_odm_id)次之;
无范围且无选择时,各导出行命中 odm 交集唯一则自动收敛(唯一可行解,无需人工)。
多值并存时不过滤,由逐行折叠按现有契约阻断,并由工作台下发候选供用户选择。
Returns:
{'inventory_lines': 收敛后的库存行, 'feasible_odm_ids': 排序候选,
'whitelist_applied': 是否应用了客户范围, 'chosen_odm_id': 用户选择(展示值)}
Raises:
ValueError: 范围排除全部命中,或用户选择在当前库存中已不存在。
"""
result = {
'inventory_lines': inventory_lines,
'feasible_odm_ids': [],
'per_line_odm_ids': [],
'whitelist_applied': False,
'chosen_odm_id': None,
}
if odm_field_id is None:
return result
odm_key = str(odm_field_id)
# 归一化值 → 原始展示值:候选/已选回显保留库存行原样大小写。
odm_display: dict[str, str] = {}
for row in inventory_lines:
raw = str(row.get(odm_key) or '').strip()
if raw:
odm_display.setdefault(_match_text(raw), raw)
customer = db.session.get(ShippingCustomer, int(snapshot.customer_id)) if snapshot.customer_id else None
customer_odm_ids = [
_match_text(value) for value in (customer.odm_ids or []) if _match_text(value)
] if customer is not None else []
chosen_odm = _match_text(chosen_odm_raw) if str(chosen_odm_raw or '').strip() else None
result['chosen_odm_id'] = odm_display.get(chosen_odm, str(chosen_odm_raw).strip()) if chosen_odm else None
normalized_keys = _normalize_match_keys(match_keys)
pre_odm_sets = _per_line_odm_sets(line_values, inventory_lines, normalized_keys, odm_key)
if customer_odm_ids:
result['whitelist_applied'] = True
scope = set(customer_odm_ids)
inventory_lines = [row for row in inventory_lines if _match_text(row.get(odm_key)) in scope]
# 范围把原本有命中的行全部排除时,必须给出指向客户数据的可行动错误,
# 避免回落成误导性的「没有匹配的库存记录」。
if any(pre_odm_sets) and not any(_per_line_odm_sets(line_values, inventory_lines, normalized_keys, odm_key)):
raise ValueError('订单行命中的库存记录 ODM ID 不在客户数据维护的 ODM ID 范围内,请检查客户数据或库存文件')
# 逐行候选取「客户范围过滤后、选择收敛前」的集合:用户在任何一行改选,候选都来自同一口径。
scoped_sets = (
_per_line_odm_sets(line_values, inventory_lines, normalized_keys, odm_key)
if customer_odm_ids else pre_odm_sets
)
if chosen_odm:
inventory_lines = [row for row in inventory_lines if _match_text(row.get(odm_key)) == chosen_odm]
if any(pre_odm_sets) and not any(_per_line_odm_sets(line_values, inventory_lines, normalized_keys, odm_key)):
raise ValueError('发货通知已选择的 ODM ID 在当前库存中不存在,请重新选择')
elif not customer_odm_ids:
# 无范围、无选择:交集唯一即唯一可行解,自动收敛;多值留给折叠阻断 + 人工选择。
feasible = _intersect_odm_sets(pre_odm_sets)
if len(feasible) == 1:
inventory_lines = [row for row in inventory_lines if _match_text(row.get(odm_key)) in feasible]
result['inventory_lines'] = inventory_lines
result['per_line_odm_ids'] = [
sorted(odm_display.get(value, value) for value in line_set)
for line_set in scoped_sets
]
result['feasible_odm_ids'] = sorted(
odm_display.get(value, value)
for value in _intersect_odm_sets(
_per_line_odm_sets(line_values, inventory_lines, normalized_keys, odm_key),
)
task = create_shipping_notice_after_inventory_gate(task)
if not task_is_active(task):
raise ValueError('已作废或归档的任务不能生成发货 Excel')
assert_task_not_supersession_blocked(task)
assert_notice_has_no_export_artifact(task)
)
return result
def prepare_export_match_inputs(task: ShippingNotice) -> dict[str, Any]:
"""
汇集发货 Excel 导出匹配所需的只读输入;不物化、不写库。
【AI 触发时机】:generate_shipment_excel 的行匹配准备,以及工作台整单 ODM
候选投影(notice_odm_choice_service)复用,保证两者消费同一份匹配事实。
Returns:
source/template/snapshot/header_values/line_values/inventory_lines/
match_keys/line_inventory_fields/header_inventory_fields/verification/
selected_snapshot_line_ids/release_overrides_by_line/released_export_line_indexes。
"""
from app.services.shipping_notice.reservation_service import (
current_available_snapshot_line_ids,
)
# [T6 E2] 滚动履约只导出当前可用行;短缺/冲突行由下方 Reservation 资格筛选排除。
source_code = str(_notice_source_code(task) or '').strip().upper()
source = ShippingInventorySource.query.filter_by(source_code=source_code, enabled=True).first()
@@ -636,12 +782,8 @@ def generate_shipment_excel(
snapshot = db.session.get(ShippingOrderSnapshot, snapshot_id) if snapshot_id else None
if snapshot is None:
raise ValueError('任务没有可用于导出的冻结订单快照')
header_values, all_line_values = order_field_id_values(task)
export_date = datetime.now(ZoneInfo('Asia/Shanghai')).date()
from app.services.shipping_notice.reservation_service import (
current_available_snapshot_line_ids,
reserve_available_for_artifact,
)
from app.services.shipping_notice.effective_order_view import effective_order_field_values
header_values, all_line_values = effective_order_field_values(task)
profile_definition = source.parsing_profile.definition_json if isinstance(source.parsing_profile.definition_json, dict) else {}
match_keys = profile_definition.get('match_keys') if isinstance(profile_definition.get('match_keys'), list) else []
line_inventory_fields = _inventory_fields_by_mode(mappings, 'line')
@@ -676,6 +818,26 @@ def generate_shipment_excel(
for source_index, line in enumerate(snapshot.lines)
if source_index in release_overrides_by_source_line
}
# [STEP 1] 已结案(close_unfulfillable)行不再有履约要求:即使预约仍有库存,
# 也必须从滚动导出资格中剔除(与上方放行查询同源同口径:只认活动决定)。
closed_snapshot_line_ids = set()
if source_notice.id is not None:
closed_rows = (
ShippingOrderReviewLineDecision.query
.join(ShippingOrderReviewCase, ShippingOrderReviewLineDecision.review_case_id == ShippingOrderReviewCase.id)
.filter(
ShippingOrderReviewCase.confirmed_task_id == int(source_notice.id),
ShippingOrderReviewLineDecision.is_active.is_(True),
ShippingOrderReviewLineDecision.decision_code == 'close_unfulfillable',
)
.all()
)
closed_snapshot_line_ids = {
int(snapshot.lines[int(decision.line_index)].id)
for decision in closed_rows
if decision.line_index is not None
and 0 <= int(decision.line_index) < len(snapshot.lines)
}
selected_snapshot_line_ids = {
int(row.snapshot_line_id)
for row in ShippingNoticeLine.query.filter_by(notice_id=int(task.id)).all()
@@ -686,6 +848,7 @@ def generate_shipment_excel(
source_notice,
released_snapshot_line_ids=released_snapshot_line_ids,
selected_snapshot_line_ids=selected_snapshot_line_ids or None,
closed_snapshot_line_ids=closed_snapshot_line_ids,
)
except ConflictError:
raise
@@ -696,6 +859,7 @@ def generate_shipment_excel(
continue
row = dict(values)
row['__order_line_index'] = source_index
row['__snapshot_line_id'] = int(line.id)
line_values.append(row)
from app.services.shipping_notice.inventory_file_store import resolve_inventory_lines_for_execution
@@ -703,8 +867,6 @@ def generate_shipment_excel(
# 裁成候选子集,再做模板字段匹配——禁止上万行全量快照进入逐行匹配。
inventory_lines = resolve_inventory_lines_for_execution(source_notice)
if (line_inventory_fields or header_inventory_fields) and match_keys and line_values:
from app.models import ShippingInventoryField
match_field_ids = {
int(item.get('inventory_field_id'))
for item in match_keys
@@ -742,6 +904,90 @@ def generate_shipment_excel(
and not isinstance(row.get('__order_line_index'), bool)
and int(row['__order_line_index']) in released_source_line_indexes
}
return {
'source': source,
'template': template,
'snapshot': snapshot,
'mappings': mappings,
'source_notice': source_notice,
'header_values': header_values,
'line_values': line_values,
'inventory_lines': inventory_lines,
'match_keys': match_keys,
'line_inventory_fields': line_inventory_fields,
'header_inventory_fields': header_inventory_fields,
'verification': verification,
'released_snapshot_line_ids': released_snapshot_line_ids,
'selected_snapshot_line_ids': selected_snapshot_line_ids,
'release_overrides_by_line': release_overrides_by_line,
'released_export_line_indexes': released_export_line_indexes,
}
def generate_shipment_excel(
task: ShippingNotice,
) -> tuple[str, str, ShippingExportArtifact]:
"""
按库存源发布模板生成 Excel,并在当前事务新增不可变 Artifact。
【AI 触发时机】:仅由 generate_excel Tool 在库存匹配完成后调用;Agent 禁止传模板或字段映射。
Args:
chosen_odm_id: 整单 ODM ID 用户选择(本次生成的请求参数,不落库);
多 ODM 冲突时由工作台下发候选后随 Gate 动作传入,仅当其在当前库存命中时生效。
Returns:
(绝对文件路径, 下载文件名, 待随任务事务提交的 Artifact)。
Raises:
ValueError: 库存源、模板、订单 Extraction 或解析 Profile 未形成完整发布链。
AppError: 没有可导出的满足/已审计放行行,或输入事实不完整。
"""
from app.services.shipping_notice.task_disposition_service import task_is_active
from app.services.shipping_notice.task_supersession_service import assert_task_not_supersession_blocked
# OT 在库存门禁通过后才物化为正式 Notice;之后导出链路只接受 Notice。
from app.models import ShippingOrderTask
if isinstance(task, ShippingOrderTask):
from app.services.shipping_notice.shipping_notice_creation_service import (
create_shipping_notice_after_inventory_gate,
)
task = create_shipping_notice_after_inventory_gate(task)
if not task_is_active(task):
raise ValueError('已作废或归档的任务不能生成发货 Excel')
assert_task_not_supersession_blocked(task)
assert_notice_has_no_export_artifact(task)
inputs = prepare_export_match_inputs(task)
source = inputs['source']
template = inputs['template']
snapshot = inputs['snapshot']
mappings = inputs['mappings']
source_notice = inputs['source_notice']
header_values = inputs['header_values']
line_values = inputs['line_values']
match_keys = inputs['match_keys']
line_inventory_fields = inputs['line_inventory_fields']
header_inventory_fields = inputs['header_inventory_fields']
inventory_lines = inputs['inventory_lines']
verification = inputs['verification']
released_snapshot_line_ids = inputs['released_snapshot_line_ids']
selected_snapshot_line_ids = inputs['selected_snapshot_line_ids']
release_overrides_by_line = inputs['release_overrides_by_line']
released_export_line_indexes = inputs['released_export_line_indexes']
export_date = datetime.now(ZoneInfo('Asia/Shanghai')).date()
# [STEP 3.5] 整单 ODM 裁决:客户 ODM ID 范围 → 用户选择 → 唯一可行交集自动收敛。
odm_field_id = (
_resolve_odm_inventory_field_id()
if (line_inventory_fields or header_inventory_fields) else None
)
adjudication = _adjudicate_notice_odm(
line_values=line_values,
inventory_lines=inventory_lines,
match_keys=match_keys,
odm_field_id=odm_field_id,
snapshot=snapshot,
chosen_odm_raw=_notice_chosen_odm(task),
)
inventory_lines = adjudication['inventory_lines']
matched_inventory_lines = _match_inventory_lines(
line_values,
inventory_lines,
@@ -854,6 +1100,8 @@ def generate_shipment_excel(
)
db.session.add(artifact)
db.session.flush()
from app.services.shipping_notice.reservation_service import reserve_available_for_artifact
reserve_available_for_artifact(
source_notice,
artifact=artifact,
@@ -2,9 +2,10 @@
backend/app/services/shipping_notice/fulfillment_audit.py
用途:履约关键节点与敏感访问写入统一审计事件的轻量封装。
依赖:audit_service.append_shipping_audit_event、Flask g.request_id / request、AppError。
依赖:audit_service.append_shipping_audit_event、Flask g.request_id、core.http_context、AppError、db.session。
逻辑:由 candidate / decision / fulfillment_workflow / workspace 读取与导出 / Workflow 写路径调用;
默认 strict=True,审计写入失败时抛错,禁止业务成功而审计缺失;访问审计逐次留痕;
默认 strict=True;审计写入包在 SAVEPOINT 内,失败不污染外层业务事务;
strict=False 时仅记日志(门禁路径用,禁止审计打断匹配等业务结果);
自动附带 request_id 与客户端 IP/UA(仅哈希入库);透传 Workflow 软引用字段。
"""
@@ -13,6 +14,7 @@ from __future__ import annotations
import logging
from typing import Any
from app import db
from app.core.errors import ServiceUnavailableError
from app.services.shipping_notice.audit_service import append_shipping_audit_event
@@ -35,10 +37,11 @@ def _client_request_context() -> tuple[str | None, str | None]:
核心逻辑:优先 X-Forwarded-For 首段;无请求上下文时返回 (None, None)。
"""
try:
from flask import request
forwarded = str(request.headers.get('X-Forwarded-For') or '').split(',')[0].strip()
ip = forwarded or str(request.remote_addr or '').strip() or None
ua = str(request.headers.get('User-Agent') or '').strip() or None
from app.core.http_context import header, remote_addr
forwarded = header('X-Forwarded-For').split(',')[0].strip()
ip = forwarded or remote_addr() or None
ua = header('User-Agent').strip() or None
return ip, ua
except RuntimeError:
return None, None
@@ -93,7 +96,8 @@ def record_fulfillment_audit(
"""
追加履约审计。
核心逻辑:默认与业务同事务写入;strict=True 时失败抛错,保证必须留存;
核心逻辑:审计写入包在 SAVEPOINT 内,与外层业务状态隔离;strict=True 时失败抛错,
但已回滚审计子事务,不把会话留在失败态;strict=False 时仅记日志,业务继续。
自动附带 request_id 与客户端 IP/UA 哈希;透传 Workflow 软引用。
Args:
@@ -102,49 +106,55 @@ def record_fulfillment_audit(
before/after: 必须已是白名单可投影的状态摘要。
error_code: 拒绝/失败时的稳定业务错误码。
sensitivity_level: 可选敏感分级(如 sensitive),透传审计表。
strict: True 时审计失败阻断调用方;False 时仅记日志(仅限显式降级场景)。
strict: True 时审计失败阻断调用方;False 时仅记日志(门禁等业务关键路径)。
"""
request_id = _request_id()
client_ip, user_agent = _client_request_context()
try:
append_shipping_audit_event(
event_type=event_type,
aggregate_type=aggregate_type,
aggregate_id=str(aggregate_id),
action=action,
actor_type=actor_type,
actor_id=actor_id,
request_id=request_id,
operation_id=request_id,
run_no=run_no,
task_no=task_no,
document_id=document_id,
review_case_no=review_case_no,
conversation_id=conversation_id,
workflow_id=workflow_id,
workflow_item_id=workflow_item_id,
workflow_item_version_id=workflow_item_version_id,
version_no=version_no,
owner_user_id=owner_user_id,
client_ip=client_ip,
user_agent=user_agent,
reason_code=reason_code,
reason=reason,
result=result,
error_code=error_code,
before=before,
after=after,
metadata=metadata or {},
source=source,
sensitivity_level=sensitivity_level,
)
# [STEP] SAVEPOINT:审计 INSERT 失败不得污染外层业务事务(否则匹配等结果会整单回滚)。
with db.session.begin_nested():
append_shipping_audit_event(
event_type=event_type,
aggregate_type=aggregate_type,
aggregate_id=str(aggregate_id),
action=action,
actor_type=actor_type,
actor_id=actor_id,
request_id=request_id,
operation_id=request_id,
run_no=run_no,
task_no=task_no,
document_id=document_id,
review_case_no=review_case_no,
conversation_id=conversation_id,
workflow_id=workflow_id,
workflow_item_id=workflow_item_id,
workflow_item_version_id=workflow_item_version_id,
version_no=version_no,
owner_user_id=owner_user_id,
client_ip=client_ip,
user_agent=user_agent,
reason_code=reason_code,
reason=reason,
result=result,
error_code=error_code,
before=before,
after=after,
metadata=metadata or {},
source=source,
sensitivity_level=sensitivity_level,
)
except Exception as exc:
_LOGGER.exception('fulfillment audit append failed event_type=%s aggregate_id=%s', event_type, aggregate_id)
if strict:
raise ServiceUnavailableError(
'Shipping audit persistence failed',
f'Shipping audit persistence failed: {exc}',
code='SHIPPING_NOTICE.AUDIT_PERSIST_FAILED',
details={'event_type': event_type, 'aggregate_id': str(aggregate_id)},
details={
'event_type': event_type,
'aggregate_id': str(aggregate_id),
'cause': str(exc)[:500],
},
) from exc
@@ -420,7 +420,7 @@ def _auto_upload_enabled() -> bool:
def _rpa_upload_timeout_seconds() -> int:
"""货代上传 RPA 等待回调超时秒数。"""
try:
return max(int(current_app.config.get('SHIPPING_NOTICE_RPA_UPLOAD_TIMEOUT_SECONDS') or 30), 1)
return max(int(current_app.config.get('FREIGHT_RPA_UPLOAD_TIMEOUT_SECONDS') or 30), 1)
except (TypeError, ValueError):
return 30
@@ -569,7 +569,7 @@ def _trigger_freight_upload_rpa(
timeout = _rpa_upload_timeout_seconds()
set_task_step_progress(
task,
step_key='step7_upload_freight',
stage="freight_uploading",
step_title='上传货代',
status='running',
message=t('workflow.fulfillment.upload_triggered_wait', lang=lang),
@@ -718,12 +718,47 @@ def _released_snapshot_line_ids_for_task(task: ShippingNotice) -> set[int]:
}
def _closed_snapshot_line_ids_for_task(task: ShippingNotice) -> set[int]:
"""读取当前任务已结案(close_unfulfillable)的冻结行 ID,供满足性与聚合豁免共用。
核心逻辑:与 ``_released_snapshot_line_ids_for_task`` 同源同口径——只认活动决定,
经 line_index 映射快照行;结案行不再是履约要求,在满足性/建单/导出各处按豁免处理。
"""
from app.models import ShippingOrderReviewCase, ShippingOrderReviewLineDecision
if task.id is None:
return set()
if not getattr(task, 'order_snapshot_id', None):
return set()
decisions = (
ShippingOrderReviewLineDecision.query
.join(ShippingOrderReviewCase, ShippingOrderReviewLineDecision.review_case_id == ShippingOrderReviewCase.id)
.filter(
ShippingOrderReviewCase.confirmed_task_id == int(task.id),
ShippingOrderReviewLineDecision.is_active.is_(True),
ShippingOrderReviewLineDecision.decision_code == 'close_unfulfillable',
)
.all()
)
from app.models import ShippingOrderSnapshot
snapshot = db.session.get(ShippingOrderSnapshot, int(task.order_snapshot_id))
if snapshot is None:
return set()
return {
int(snapshot.lines[int(row.line_index)].id)
for row in decisions
if row.line_index is not None
and 0 <= int(row.line_index) < len(snapshot.lines)
}
def match_completed(task: ShippingNotice) -> bool:
"""
STP 整单满足性门禁:仅当全部明细匹配成功(fulfillable 且每行 ok)时通过。
核心逻辑:该函数只代表整单满足性,不代表滚动 Excel 是否存在可导出行。
已人工放行的短缺行视同满足(与 ``_recompute_task_match_aggregate`` 同源)。
已人工放行的短缺行视同满足;已结案(close_unfulfillable)行不再是履约要求,
从覆盖校验与逐行判定中双重豁免;全部行结案时无剩余履约内容,按不通过处理。
"""
from app.models import ShippingNoticeLineInventoryMatch
@@ -738,17 +773,23 @@ def match_completed(task: ShippingNotice) -> bool:
db.session.get(ShippingOrderSnapshot, int(task.order_snapshot_id))
if getattr(task, 'order_snapshot_id', None) else None
)
expected_line_ids = {int(line.id) for line in getattr(snapshot, 'lines', []) or []}
closed_ids = _closed_snapshot_line_ids_for_task(task)
expected_line_ids = {int(line.id) for line in getattr(snapshot, 'lines', []) or []} - closed_ids
if not expected_line_ids:
# 全部行已结案:订单无剩余履约内容,不得自动进入建通知/Excel(应走作废流程)。
return False
current_line_ids = {
int(row.snapshot_line_id)
for row in rows
if getattr(row, 'snapshot_line_id', None) is not None
}
# 满足性必须覆盖冻结订单的全部项次;仅有部分当前 Match 不能代表整单可履约。
if expected_line_ids and current_line_ids != expected_line_ids:
} - closed_ids
# 满足性必须覆盖剩余待履约的全部项次;仅有部分当前 Match 不能代表整单可履约。
if current_line_ids != expected_line_ids:
return False
released_ids = _released_snapshot_line_ids_for_task(task)
for row in rows:
if getattr(row, 'snapshot_line_id', None) is not None and int(row.snapshot_line_id) in closed_ids:
continue
result = str(row.match_result or '').strip()
shortage = _line_shortage_qty(getattr(row, 'shortage_qty', None))
if result == 'matched' and shortage <= 0:
@@ -823,6 +864,7 @@ def exportable_snapshot_line_ids(task: ShippingNotice) -> set[int]:
_verification, line_ids = current_available_snapshot_line_ids(
_source_notice_for_order_facts(task),
released_snapshot_line_ids=_released_snapshot_line_ids_for_export(task),
closed_snapshot_line_ids=_closed_snapshot_line_ids_for_task(task),
)
except ConflictError:
return set()
@@ -1249,7 +1291,7 @@ def match_inventory_line(payload: dict[str, Any], *, line_no: int) -> dict[str,
line_result_status = str(match_payload.get('match_status') or 'unfulfillable')
set_task_step_progress(
task,
step_key="step5_match_inventory",
stage="inventory_matching",
step_title="匹配库存",
status="running",
message=t("workflow.fulfillment.match_running", lang=lang),
@@ -1344,6 +1386,8 @@ def _recompute_task_match_aggregate(task: ShippingNotice) -> tuple[str, list[dic
核心逻辑:与 ``match_completed`` 同款放行语义——已人工放行(release_inventory_shortage)
且仍有缺口的行视同满足,不再计入 has_block/缺货;否则会与 Excel 门禁分裂,
出现"Gate 认为满足、任务却仍标 unfulfillable"的矛盾。
已结案(close_unfulfillable)行不再是履约要求:不阻断、不进缺货列表,
但也不计入满足(结案行非可履约内容),全结案 ⇒ unfulfillable,与 match_completed 口径一致。
"""
rows = (
ShippingNoticeLineInventoryMatch.query
@@ -1353,6 +1397,7 @@ def _recompute_task_match_aggregate(task: ShippingNotice) -> tuple[str, list[dic
if not rows:
return 'unfulfillable', []
released_snapshot_line_ids = _released_snapshot_line_ids_for_task(task)
closed_snapshot_line_ids = _closed_snapshot_line_ids_for_task(task)
has_ok = False
has_block = False
shortages: list[dict[str, Any]] = []
@@ -1378,7 +1423,12 @@ def _recompute_task_match_aggregate(task: ShippingNotice) -> tuple[str, list[dic
# 已审计放行的短缺行视同满足:不阻断、不进入缺货列表。
shortage = _line_shortage_qty(shortage_qty)
released = entry['snapshot_line_id'] in released_snapshot_line_ids
if match_result == 'matched' and shortage <= 0:
closed = entry['snapshot_line_id'] in closed_snapshot_line_ids
if closed:
# [BE-结案-豁免] 结案行不再是履约要求:不阻断、不进缺货列表,
# 但也不计入满足(非可履约内容);全结案 ⇒ 无可履约内容 ⇒ unfulfillable。
entry['line_status'] = 'closed'
elif match_result == 'matched' and shortage <= 0:
entry['line_status'] = 'ok'
has_ok = True
elif released and shortage > 0:
@@ -1390,21 +1440,25 @@ def _recompute_task_match_aggregate(task: ShippingNotice) -> tuple[str, list[dic
has_block = True
shortages.append(entry)
line_results.append(entry)
owner = _workflow_owner(task)
if hasattr(owner, 'step_payload_json'):
payload = dict(owner.step_payload_json or {})
payload['current_match_projection'] = {
'match_status': 'partial' if has_block and has_ok else ('unfulfillable' if has_block else 'fulfillable'),
'line_results': line_results,
'shortage': {'lines': shortages},
}
owner.step_payload_json = payload
# 结案行既不计满足也不阻断:无 ok 且无 block(如全结案)时无可履约内容 ⇒ unfulfillable,
# 与 match_completed 的整单口径保持一致,避免 Gate 同步误判满足后空转编排。
if has_block and has_ok:
status = 'partial'
elif has_block:
status = 'unfulfillable'
else:
elif has_ok:
status = 'fulfillable'
else:
status = 'unfulfillable'
owner = _workflow_owner(task)
if hasattr(owner, 'step_payload_json'):
payload = dict(owner.step_payload_json or {})
payload['current_match_projection'] = {
'match_status': status,
'line_results': line_results,
'shortage': {'lines': shortages},
}
owner.step_payload_json = payload
return status, shortages
@@ -1615,7 +1669,11 @@ def match_inventory(payload: dict[str, Any]) -> dict[str, Any]:
if lang:
inv_payload["lang"] = lang
return ensure_inventory(inv_payload)
_order_header_values, order_field_lines = order_field_id_values(task)
# [STEP 2] 兜底匹配基线读取有效视图(冻结快照 + 冻结后人工修正):
# 匹配身份键(料号/预约等字段值)必须与展示值(__required_qty/__display_part_number)
# 同源,否则出现"按冻结料号匹配、却展示有效料号"的混合投影。
from app.services.shipping_notice.effective_order_view import effective_order_field_values
_order_header_values, order_field_lines = effective_order_field_values(task)
purpose_lines = task_line_purpose_values(task, required={'part_number', 'quantity', 'reservation_id'})
for index, order_line in enumerate(order_field_lines):
purpose_line = purpose_lines[index] if index < len(purpose_lines) else {}
@@ -1639,7 +1697,7 @@ def match_inventory(payload: dict[str, Any]) -> dict[str, Any]:
)
set_task_step_progress(
task,
step_key="step5_match_inventory",
stage="inventory_matching",
step_title="匹配库存",
status="running",
message=t("workflow.fulfillment.match_running", lang=lang),
@@ -1731,7 +1789,7 @@ def match_inventory(payload: dict[str, Any]) -> dict[str, Any]:
)
set_task_step_progress(
task,
step_key="step5_match_inventory",
stage="inventory_matching",
step_title="匹配库存",
**_match_step_progress_fields(
match_status=match_status,
@@ -1810,7 +1868,7 @@ def match_inventory(payload: dict[str, Any]) -> dict[str, Any]:
percent = 10 if total <= 0 else min(95, max(10, int(processed * 100 / total)))
set_task_step_progress(
task,
step_key="step5_match_inventory",
stage="inventory_matching",
step_title="匹配库存",
status="running",
message=t("workflow.fulfillment.match_running", lang=lang),
@@ -1867,7 +1925,7 @@ def match_inventory(payload: dict[str, Any]) -> dict[str, Any]:
)
set_task_step_progress(
task,
step_key="step5_match_inventory",
stage="inventory_matching",
step_title="匹配库存",
**_match_step_progress_fields(
match_status=match_status,
@@ -2039,6 +2097,7 @@ def generate_excel(payload: dict[str, Any]) -> dict[str, Any]:
_verification, available_line_ids = current_available_snapshot_line_ids(
_source_notice_for_order_facts(task),
closed_snapshot_line_ids=_closed_snapshot_line_ids_for_task(task),
)
except ConflictError:
available_line_ids = set()
@@ -2066,7 +2125,7 @@ def generate_excel(payload: dict[str, Any]) -> dict[str, Any]:
)
set_task_step_progress(
task,
step_key="step6_generate_file",
stage="excel_generating",
step_title="生成发货文件",
status="running",
message=t("workflow.fulfillment.generate_running", lang=lang),
@@ -2120,7 +2179,7 @@ def generate_excel(payload: dict[str, Any]) -> dict[str, Any]:
_clear_notice_invalidated_from_stage(task)
set_task_step_progress(
task,
step_key="step6_generate_file",
stage="excel_generating",
step_title="生成发货文件",
status="completed",
message=t("workflow.fulfillment.generate_completed", lang=lang),
@@ -2451,7 +2510,7 @@ def rpa_report_upload(payload: dict[str, Any]) -> dict[str, Any]:
_close_uploaded_task(task, actor_type='rpa', actor_id=None)
set_task_step_progress(
task,
step_key="step7_upload_freight",
stage="freight_uploading",
step_title="上传货代",
status="completed",
message=t("workflow.fulfillment.rpa_uploaded", lang=lang),
@@ -2507,7 +2566,7 @@ def rpa_report_upload(payload: dict[str, Any]) -> dict[str, Any]:
# unknown 已可能提交但无法确认外部系统结果:保持待人工,禁止自动重试,避免重复上传。
set_task_step_progress(
task,
step_key="step7_upload_freight",
stage="freight_uploading",
step_title="上传货代",
status="needs_human",
message=t("workflow.fulfillment.upload_unknown_wait_manual", lang=lang),
@@ -2527,7 +2586,7 @@ def rpa_report_upload(payload: dict[str, Any]) -> dict[str, Any]:
apply_task_transition(task, TaskTransition.WAITING_UPLOAD)
set_task_step_progress(
task,
step_key="step7_upload_freight",
stage="freight_uploading",
step_title="上传货代",
status="needs_human",
message=t("workflow.fulfillment.upload_failed_wait_manual", lang=lang),
+5 -5
View File
@@ -2,7 +2,7 @@
services/shipping_notice/i18n.py
用途:维护发货通知链路的多语言文案与语言解析工具。
依赖:Flask request 上下文、模块内 `_MESSAGES` 文案字典。
依赖:core.http_context、模块内 `_MESSAGES` 文案字典。
逻辑:由 parse_summary、field_alignment_summary、workflow 提示文案等上游模块调用本文件输出用户可读消息。
"""
@@ -10,7 +10,7 @@ from __future__ import annotations
from typing import Any
from flask import has_request_context, request
from app.core.http_context import has_http_request, header
SUPPORTED_LANGS = ("zh", "en", "th")
@@ -422,11 +422,11 @@ def resolve_lang(payload: dict[str, Any] | None = None) -> str:
if val:
return normalize_lang(val)
if has_request_context():
hdr = str(request.headers.get("X-Lang") or "").strip()
if has_http_request():
hdr = header("X-Lang").strip()
if hdr:
return normalize_lang(hdr)
accept = str(request.headers.get("Accept-Language") or "").strip()
accept = header("Accept-Language").strip()
if accept:
return normalize_lang(accept.split(",")[0].strip())
return "zh"
@@ -2,6 +2,8 @@
用途:基于已发布身份规则集产生客户主体与送货站点的可解释影子候选。
依赖:身份规则快照、受控订单字段裁决值、客户/站点证据主数据。
逻辑:只读取 Candidate 所属 Extraction 的 accepted/corroborated Header FieldValue;站点候选不反向确认客户主体。
客户命中分三层:canonical 等值 > 完整包含(指纹整体出现在提取值中)> 截断包含(仅人工建议);
邮箱/域名指纹只做精确等值,禁止包含比较。
"""
from __future__ import annotations
@@ -23,12 +25,14 @@ from app.models import (
ShippingOrderSchemaVersion,
)
from app.services.shipping_notice.customer_normalization import (
normalize_customer_name,
normalize_domain,
normalize_email,
IDENTITY_MATCH_EQUALITY,
IDENTITY_MATCH_TIER_RANK,
canonical_identity_key,
classify_identity_containment,
normalize_identity_evidence_value,
)
RESOLUTION_VERSION = 'shadow-v2'
RESOLUTION_VERSION = 'shadow-v3'
ACCEPTED_DECISION_STATUSES = frozenset({'accepted', 'corroborated'})
@@ -37,14 +41,11 @@ def _normalize(definition: dict[str, Any], value: object) -> str | None:
try:
field_config = definition.get('field_config') if isinstance(definition.get('field_config'), dict) else {}
source = field_config.get('context_source') if isinstance(field_config.get('context_source'), dict) else {}
if source.get('option_key') == 'from_email':
return normalize_email(value)
if source.get('option_key') == 'from_domain':
return normalize_domain(value)
if field_config.get('normalizer_key') == 'name':
return normalize_customer_name(value) or None
normalized = str(value or '').strip().upper()
return normalized or None
return normalize_identity_evidence_value(
value,
option_key=source.get('option_key'),
normalizer_key=field_config.get('normalizer_key'),
)
except Exception:
return None
@@ -154,6 +155,8 @@ def _source_evidence(
normalized = _normalize(definition, value)
if not normalized:
continue
field_config = definition.get('field_config') if isinstance(definition.get('field_config'), dict) else {}
context_source = field_config.get('context_source') if isinstance(field_config.get('context_source'), dict) else {}
evidence.append({
'definition_id': definition_id,
'definition_code': code,
@@ -161,6 +164,8 @@ def _source_evidence(
'target_type': definition.get('target_type'),
'raw_value': value,
'normalized_value': normalized,
# 供命中分级使用:邮箱/域名指纹只做精确等值,不参与包含比较。
'option_key': str(context_source.get('option_key') or ''),
'weight': int(definition.get('default_weight') or 0),
'source': source,
})
@@ -178,27 +183,68 @@ def _customer_match_payload(customer: ShippingCustomer, *, score: float, reasons
}
def _classify_evidence_match(
*, runtime_value: str, evidence_value: str, option_key: str,
) -> str | None:
"""
对单个已审核证据做命中分级:等值 > 完整包含 > 截断包含。
核心逻辑:邮箱/域名指纹语义字符(@、.)参与构成身份,只做归一化后精确等值;
文本类指纹先比 canonical 等值(吸收标点/空白/大小写差异),再判双向包含。
"""
if option_key in {'from_email', 'from_domain'}:
return IDENTITY_MATCH_EQUALITY if runtime_value == evidence_value else None
if canonical_identity_key(runtime_value) == canonical_identity_key(evidence_value):
return IDENTITY_MATCH_EQUALITY
return classify_identity_containment(runtime_value, evidence_value, option_key=option_key)
def _rank_customer_matches(evidence: list[dict[str, Any]]) -> list[dict[str, Any]]:
"""按同定义已审核证据聚合客户候选;同分保留歧义,禁止排序取首条。"""
"""
按同定义已审核证据聚合客户候选,附命中层级;禁止排序取首条抹平歧义。
核心逻辑:每个(运行时证据, 注册证据)对先分级;同一客户取其最强命中层级,
排序先按层级升序(等值候选始终排在包含候选前),再按累计权重降序。
顶层(最强层级)候选唯一时调用方才判 unique_candidate,多家并列即 ambiguous。
"""
scores: dict[int, float] = defaultdict(float)
reasons: dict[int, list[dict[str, Any]]] = defaultdict(list)
tiers: dict[int, str] = {}
customers = {item.id: item for item in ShippingCustomer.query.filter_by(status='active').all()}
for item in evidence:
if item['target_type'] != 'customer':
continue
records = ShippingIdentityEvidence.query.filter_by(
definition_id=item['definition_id'], normalized_value=item['normalized_value'], status='approved',
definition_id=item['definition_id'], status='approved',
).all()
for record in records:
customer = customers.get(record.customer_id) if record.customer_id is not None else None
if customer is None:
continue
match_kind = _classify_evidence_match(
runtime_value=str(item['normalized_value'] or ''),
evidence_value=str(record.normalized_value or ''),
option_key=str(item.get('option_key') or ''),
)
if match_kind is None:
continue
scores[customer.id] += item['weight']
reasons[customer.id].append({**item, 'evidence_id': record.id, 'match_kind': 'approved_identity_evidence'})
return sorted(
[_customer_match_payload(customers[customer_id], score=score, reasons=reasons[customer_id]) for customer_id, score in scores.items()],
key=lambda item: (-float(item['score']), int(item['customer_id'])),
)
reasons[customer.id].append({**item, 'evidence_id': record.id, 'match_kind': match_kind})
if customer.id not in tiers or IDENTITY_MATCH_TIER_RANK[match_kind] < IDENTITY_MATCH_TIER_RANK[tiers[customer.id]]:
tiers[customer.id] = match_kind
ranked = [
_customer_match_payload(customers[customer_id], score=score, reasons=reasons[customer_id])
for customer_id, score in scores.items()
]
# 客户最强层级在聚合后补写,再按(层级, 权重, 客户 ID)排序。
for item in ranked:
item['match_kind'] = tiers[int(item['customer_id'])]
ranked.sort(key=lambda item: (
IDENTITY_MATCH_TIER_RANK[str(item['match_kind'])],
-float(item['score']),
int(item['customer_id']),
))
return ranked
def _rank_site_matches(evidence: list[dict[str, Any]]) -> list[dict[str, Any]]:
@@ -252,11 +298,20 @@ def resolve_candidate_identity(candidate: ShippingOrderCandidate, intake: Shippi
evidence, extraction = _source_evidence(definitions, candidate=candidate, intake=intake)
customer_matches = _rank_customer_matches(evidence)
site_matches = _rank_site_matches(evidence)
top_score = float(customer_matches[0]['score']) if customer_matches else None
tied = [item for item in customer_matches if float(item['score']) == top_score] if top_score is not None else []
# [STEP] 顶层 = 候选中的最强命中层级;仅顶层唯一才 unique_candidate,
# 强层级唯一时弱层级候选仅作展示,不参与歧义计算。
top_tier_candidates: list[dict[str, Any]] = []
if customer_matches:
top_tier_rank = min(
IDENTITY_MATCH_TIER_RANK[str(item['match_kind'])] for item in customer_matches
)
top_tier_candidates = [
item for item in customer_matches
if IDENTITY_MATCH_TIER_RANK[str(item['match_kind'])] == top_tier_rank
]
return {
'resolution_version': RESOLUTION_VERSION,
'status': 'unmatched' if not customer_matches else 'unique_candidate' if len(tied) == 1 else 'ambiguous',
'status': 'unmatched' if not customer_matches else 'unique_candidate' if len(top_tier_candidates) == 1 else 'ambiguous',
'evidence': evidence,
'customer_matches': customer_matches,
'site_matches': site_matches,
@@ -219,7 +219,7 @@ def _expire_timed_out_runs(source: ShippingInventorySource) -> None:
同一 RPA Profile 的批量站点由 Windows Worker 串行执行。每个站点沿用单站
等待窗口会让排在后面的站点尚未被领取就超时,因此同组按站点数量线性扩展。
"""
timeout = max(1, int(current_app.config['SHIPPING_NOTICE_RPA_INVENTORY_TIMEOUT_SECONDS']))
timeout = max(1, int(current_app.config['FREIGHT_RPA_INVENTORY_TIMEOUT_SECONDS']))
runs = ShippingInventoryConfigurationTestRun.query.filter(
ShippingInventoryConfigurationTestRun.inventory_source_id == source.id,
ShippingInventoryConfigurationTestRun.status.in_(['awaiting_rpa', 'processing']),
@@ -357,7 +357,7 @@ def report_test_export(payload: dict[str, Any]) -> dict[str, Any]:
db.session.commit()
return _payload(run)
# Windows Worker 回传 C:\HxopsRpa...\inventory_drop\file.xlsx;Linux 后端必须映射到
# SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR 下同名文件,否则 Path(windows).is_file() 恒假。
# FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR 下同名文件,否则 Path(windows).is_file() 恒假。
raw_file_path = str(payload.get('file_path') or '').strip()
path: Path | None = None
from app.services.shipping_notice.rpa import inventory_drop_dir
@@ -5,7 +5,8 @@ services/shipping_notice/inventory_file_store.py
依赖:models.ShippingInventoryFile/ShippingTaskInventoryLink、inventory_snapshot、export._storage_root。
逻辑:inventory_workflow 上传或解析库存时写入库存快照(Link 挂在正式 OT);
fulfillment_workflow / Excel 导出经 resolve_inventory_lines_for_execution:
冻结候选 OT 读 prepare 合并行,单源读 active Link 文件;禁止用 Notice.id 漏读 OT Link。
冻结候选读所属 OT 的 prepare 合并行(传入 Notice 时回源 order_task_id),单源读 active Link 文件;
禁止用 Notice.id 漏读 OT Link,导出数据源不得偏离行级匹配门禁命中的候选事实。
"""
from __future__ import annotations
@@ -242,6 +243,9 @@ def resolve_inventory_lines_for_execution(
本次执行使用的库存行;不会回写任务或通知单的库存行缓存。
"""
# [STEP 1] STP 冻结候选:匹配输入来自各源快照合并,不读被污染的单文件缓存。
# Notice 主键 ≠ OT 且不带候选集指针;冻结候选事实统一回源所属 OT 读取,
# 防止导出路径把多源任务退化成单源 Link,出现「行匹配过门禁但生成 Excel 失败」。
from app.models import ShippingOrderTask
from app.services.shipping_notice.stp_inventory_freeze import (
task_frozen_inventory_source_codes,
)
@@ -249,8 +253,12 @@ def resolve_inventory_lines_for_execution(
prepare_candidate_inventory_lines,
)
if len(task_frozen_inventory_source_codes(task)) >= 1:
prep = prepare_candidate_inventory_lines(task)
owner_task = task
order_task_id = getattr(task, 'order_task_id', None)
if order_task_id:
owner_task = db.session.get(ShippingOrderTask, int(order_task_id)) or task
if len(task_frozen_inventory_source_codes(owner_task)) >= 1:
prep = prepare_candidate_inventory_lines(owner_task)
if prep.get('status') == 'ready':
rows = [row for row in list(prep.get('lines') or []) if isinstance(row, dict)]
if rows:
@@ -687,7 +695,7 @@ def start_inventory_file_linked_tasks(inv_file: ShippingInventoryFile | None) ->
if task.task_no in task_nos and not current_inventory_matches_for_task(task) and not has_verified_upload_success(task):
set_task_step_progress(
task,
step_key="step5_match_inventory",
stage="inventory_matching",
step_title="匹配库存",
status="running",
message="本批库存快照已确认,等待匹配库存",
@@ -101,7 +101,7 @@ def inventory_loaded_response(
)
set_task_step_progress(
task,
step_key="step3_inventory_prepare",
stage="inventory_fetching",
step_title="获取库存",
status="completed",
message=f"已载入库存 {len(inventory_lines)} 行",
@@ -56,11 +56,11 @@ def callback_quarantine_dir() -> Path | None:
def callback_cleanup_max_attempts() -> int:
"""cleanup job 最大重试次数(SHIPPING_NOTICE_RPA_CALLBACK_CLEANUP_MAX_ATTEMPTS)。"""
"""cleanup job 最大重试次数(FREIGHT_RPA_CALLBACK_CLEANUP_MAX_ATTEMPTS)。"""
try:
return max(
1,
int(current_app.config.get("SHIPPING_NOTICE_RPA_CALLBACK_CLEANUP_MAX_ATTEMPTS") or _DEFAULT_MAX_CLEANUP_ATTEMPTS),
int(current_app.config.get("FREIGHT_RPA_CALLBACK_CLEANUP_MAX_ATTEMPTS") or _DEFAULT_MAX_CLEANUP_ATTEMPTS),
)
except (TypeError, ValueError):
return _DEFAULT_MAX_CLEANUP_ATTEMPTS
@@ -1212,7 +1212,7 @@ def ensure_inventory_via_rpa(
_set_workflow_error(task, None)
set_task_step_progress(
task,
step_key='step3_inventory_prepare',
stage="inventory_fetching",
step_title='获取库存',
status='running',
message='已重新触发库存获取,等待各库存源回调。' if manual_retry_round else '已触发库存获取,等待各库存源回调。',
@@ -1240,7 +1240,7 @@ def ensure_inventory_via_rpa(
poll_read_only = not allow_auto_retry
set_task_step_progress(
task,
step_key='step3_inventory_prepare',
stage="inventory_fetching",
step_title='获取库存',
status='needs_human',
message='库存 RPA 未能为全部库存源生成结果。',
@@ -1353,7 +1353,7 @@ def ensure_inventory_via_rpa(
)
set_task_step_progress(
task,
step_key="step3_inventory_prepare",
stage="inventory_fetching",
step_title="获取库存",
status="running",
message=progress_message,
@@ -1403,7 +1403,7 @@ def ensure_inventory_via_rpa(
_set_workflow_error(task, human_message[:500])
set_task_step_progress(
task,
step_key="step3_inventory_prepare",
stage="inventory_fetching",
step_title="获取库存",
status="needs_human",
message=human_message,
@@ -1553,7 +1553,7 @@ def _handle_rpa_inventory_skipped(
_set_workflow_error(task, None)
set_task_step_progress(
task,
step_key="step3_inventory_prepare",
stage="inventory_fetching",
step_title="获取库存",
status="needs_human",
message="货代系统当前无可用库存",
@@ -1600,7 +1600,7 @@ def _handle_rpa_inventory_failed(
})
set_task_step_progress(
task,
step_key='step3_inventory_prepare',
stage="inventory_fetching",
step_title='获取库存',
status='needs_human',
message=_workflow_error(task),
@@ -1950,7 +1950,7 @@ def rpa_report_inventory(payload: dict[str, Any]) -> dict[str, Any]:
}
set_task_step_progress(
task,
step_key="step3_inventory_prepare",
stage="inventory_fetching",
step_title="获取库存",
status="running",
message="RPA 库存文件已返回,正在读取库存快照",
@@ -132,7 +132,7 @@ def _link_ready_candidate_prep_or_block(
apply_task_transition(task, TaskTransition.INV_UNAVAIL)
set_task_step_progress(
task,
step_key='step3_inventory_prepare',
stage="inventory_fetching",
step_title='获取库存',
status='needs_human',
message=t('workflow.inventory.unavailable', lang=lang),
@@ -312,7 +312,7 @@ def upload_inventory_file(task_id: str, upload: Any) -> dict[str, Any]:
try:
set_task_step_progress(
task,
step_key="step3_inventory_prepare",
stage="inventory_fetching",
step_title="获取库存",
status="running",
message=t("workflow.inventory.uploading", lang=lang),
@@ -461,7 +461,7 @@ def ensure_inventory(payload: dict[str, Any]) -> dict[str, Any]:
apply_task_transition(task, TaskTransition.INV_UNAVAIL)
set_task_step_progress(
task,
step_key="step3_inventory_prepare",
stage="inventory_fetching",
step_title="获取库存",
status="needs_human",
message=t("workflow.inventory.unavailable", lang=lang),
@@ -502,7 +502,7 @@ def ensure_inventory(payload: dict[str, Any]) -> dict[str, Any]:
task.error_message = None
set_task_step_progress(
task,
step_key="step3_inventory_prepare",
stage="inventory_fetching",
step_title="获取库存",
status="running",
message="已触发库存获取,等待各库存源回调。",
@@ -530,7 +530,7 @@ def ensure_inventory(payload: dict[str, Any]) -> dict[str, Any]:
apply_task_transition(task, TaskTransition.INV_UNAVAIL)
set_task_step_progress(
task,
step_key="step3_inventory_prepare",
stage="inventory_fetching",
step_title="获取库存",
status="needs_human",
message="库存 RPA 未能为全部库存源生成结果。",
@@ -556,7 +556,7 @@ def ensure_inventory(payload: dict[str, Any]) -> dict[str, Any]:
apply_task_transition(task, TaskTransition.INV_UNAVAIL)
set_task_step_progress(
task,
step_key="step3_inventory_prepare",
stage="inventory_fetching",
step_title="获取库存",
status="needs_human",
message=t("workflow.inventory.unavailable", lang=lang),
@@ -625,7 +625,7 @@ def ensure_inventory(payload: dict[str, Any]) -> dict[str, Any]:
apply_task_transition(task, TaskTransition.INV_UNAVAIL)
set_task_step_progress(
task,
step_key="step3_inventory_prepare",
stage="inventory_fetching",
step_title="获取库存",
status="needs_human",
message=t("workflow.inventory.unavailable", lang=lang),
@@ -5,8 +5,8 @@ services/shipping_notice/lifecycle_projection.py
依赖:process_gate_contract 的阻断原因归属;调用方提供正式 Gate、Case/Candidate 或已核验成功事实。
逻辑:已核验上传成功 → 已持久化处理阶段 → 正式 Process Gate → 可解释阻断原因;
[B''] 处理阶段是阶段唯一权威,正式 Gate 不再覆盖/升降阶段,仅在处理阶段缺失时
兜底;无正式事实时保持未分类。本模块只做只读业务投影,不授权任何写操作;
阶段入口与实际动作权限必须分开。
兜底;无正式事实时保持未分类。
本模块只做只读业务投影,不授权任何写操作;阶段入口与实际动作权限必须分开。
"""
from __future__ import annotations
@@ -508,6 +508,26 @@ def load_current_match_facts_by_task(task_id: int | None) -> dict[int, dict[str,
return out
def load_current_match_facts_by_line_index(task_id: int | None) -> dict[int, dict[str, Any]]:
"""按 line_index 索引当前匹配事实(Case 履约投影专用)。
核心逻辑:与 load_current_match_facts_by_task 同一查询;Case 草稿行只有
_line_index 没有 snapshot_line_id,必须按行号索引才能关联上事实。
"""
if task_id is None:
return {}
rows = (
ShippingNoticeLineInventoryMatch.query
.filter_by(task_id=int(task_id), is_current=True)
.all()
)
return {
int(row.line_index): serialize_match_fact(row)
for row in rows
if row.line_index is not None
}
def aggregate_match_status_for_task(task_id: int | None) -> str | None:
"""根据当前行级 Match 聚合任务匹配状态,禁止读取 OT/Notice 缓存字段。"""
facts = list(load_current_match_facts_by_task(task_id).values())
@@ -21,6 +21,7 @@ def replace_notice_lines_from_snapshot(
snapshot: ShippingOrderSnapshot,
snapshot_line_ids: set[int] | None = None,
inventory_facts_by_snapshot_line_id: dict[int, dict[str, Any]] | None = None,
line_overrides: dict[int, dict[str, Any]] | None = None,
) -> int:
"""
用 Snapshot 行替换指定 Notice 的 shipping_notice_lines。
@@ -29,6 +30,10 @@ def replace_notice_lines_from_snapshot(
notice_id: shipping_notices.id。
snapshot: 已 flush 且带 lines 的 Snapshot。
snapshot_line_ids: 仅写入本次发货通知选中的冻结行;为空时兼容整单冻结。
inventory_facts_by_snapshot_line_id: 行级库存事实(来源/文件/仓库)。
line_overrides: effective_order_view.effective_line_facts_for_notice 的输出,
按 snapshot_line_id 携带冻结后人工修正;仅非 None 值覆盖快照列,
缺失或 None 时回退冻结快照值。
Returns:
写入行数。
@@ -44,6 +49,7 @@ def replace_notice_lines_from_snapshot(
continue
notice_position += 1
inventory_facts = dict(inventory_facts_by_snapshot_line_id.get(int(line.id)) or {})
override = (line_overrides or {}).get(int(line.id)) or {}
rows.append(
ShippingNoticeLine(
notice_id=int(notice_id),
@@ -51,13 +57,17 @@ def replace_notice_lines_from_snapshot(
position=notice_position - 1,
# 发货通知项次按当前通知单重新从 1 编排。
line_no=notice_position,
part_number=getattr(line, 'part_number', None),
reservation_id=getattr(line, 'reservation_id', None),
required_qty=getattr(line, 'qty', None),
part_number=override.get('part_number')
if override.get('part_number') is not None else getattr(line, 'part_number', None),
reservation_id=override.get('reservation_id')
if override.get('reservation_id') is not None else getattr(line, 'reservation_id', None),
required_qty=override.get('qty')
if override.get('qty') is not None else getattr(line, 'qty', None),
inventory_source_code=inventory_facts.get('inventory_source_code'),
inventory_file_id=inventory_facts.get('inventory_file_id'),
inventory_warehouse_id=inventory_facts.get('inventory_warehouse_id'),
field_values_json=dict(getattr(line, 'field_values_json', None) or {}),
field_values_json=dict(override['field_values'])
if override.get('field_values') else dict(getattr(line, 'field_values_json', None) or {}),
created_at=now,
)
)
@@ -0,0 +1,177 @@
"""
services/shipping_notice/notice_odm_choice_service.py
用途:发货通知整单(Notice)级 ODM ID 的逐行候选投影与用户选择持久化。
依赖:export(prepare_export_match_inputs/_adjudicate_notice_odm)、ShippingNoticeLineInventoryMatch、AppError。
逻辑:候选 = 各导出行命中 odm(先经客户 odm_ids 范围过滤)的交集,与导出收敛共用同一
事实源(prepare_export_match_inputs);选择写在当前行级匹配事实行
(shipping_notice_line_inventory_matches.chosen_odm_id)上,按「同一库存快照文件」
圈同步范围——改任一行,同文件全部 is_current 行统一变更(Header 契约是整单一个值);
重匹配产生新匹配轮次后旧选择自然失效。实际收敛由导出裁决执行,本服务只投影与落库。
"""
from __future__ import annotations
from typing import Any
from app import db
from app.core.errors import AppError
from app.models import ShippingCustomer, ShippingNoticeLineInventoryMatch
_ODM_CHOICE_INVALID_CODE = 'SHIPPING.NOTICE_ODM_CHOICE_INVALID'
def _adjudication_task_id(task) -> int | None:
"""返回裁决挂接的 OT 主键:Notice 取 order_task_id,OT 取自身 id。"""
return getattr(task, 'order_task_id', None) or getattr(task, 'id', None)
def notice_odm_options(task) -> dict[str, Any]:
"""
投影整单 ODM 逐行候选与当前用户选择;只读,不物化 Notice、不写库。
【AI 触发时机】:工作台通知准备面板需要展示「一个预约单号多个 ODM ID」的
行级候选与已选值时调用;禁止用它替代导出收敛——实际过滤由导出裁决执行。
Returns:
{odm_field_id, lines: [{snapshot_line_id, odm_values, chosen_odm_id}],
customer_odm_ids, whitelist_applied};模板不消费 odm 字段时 lines 为空列表。
"""
from app.services.shipping_notice.export import (
_adjudicate_notice_odm,
_notice_chosen_odm,
_resolve_odm_inventory_field_id,
prepare_export_match_inputs,
)
empty: dict[str, Any] = {
'odm_field_id': None,
'lines': [],
'customer_odm_ids': [],
'whitelist_applied': False,
}
# OT / Notice 都可直接投影(导出取数兼容两者);导出时再按正式链路裁决。
try:
inputs = prepare_export_match_inputs(task)
except (ValueError, AppError):
return empty
odm_field_id = (
_resolve_odm_inventory_field_id()
if (inputs['line_inventory_fields'] or inputs['header_inventory_fields']) else None
)
if odm_field_id is None:
return empty
snapshot = inputs['snapshot']
customer = db.session.get(ShippingCustomer, int(snapshot.customer_id)) if snapshot.customer_id else None
customer_odm_ids = (
[str(value or '').strip() for value in (customer.odm_ids or []) if str(value or '').strip()]
if customer is not None else []
)
try:
adjudication = _adjudicate_notice_odm(
line_values=inputs['line_values'],
inventory_lines=inputs['inventory_lines'],
match_keys=inputs['match_keys'],
odm_field_id=odm_field_id,
snapshot=snapshot,
chosen_odm_raw=_notice_chosen_odm(task),
)
except ValueError:
# 范围排除全部命中 / 选择已失效:候选投影为空,用户需先修客户数据或重选。
return {
'odm_field_id': odm_field_id,
'lines': [],
'customer_odm_ids': customer_odm_ids,
'whitelist_applied': True,
}
lines_payload = []
for row, odm_values in zip(inputs['line_values'], adjudication['per_line_odm_ids'], strict=True):
lines_payload.append({
'snapshot_line_id': row.get('__snapshot_line_id'),
'odm_values': list(odm_values),
'chosen_odm_id': adjudication['chosen_odm_id'],
})
return {
'odm_field_id': odm_field_id,
'lines': lines_payload,
'customer_odm_ids': customer_odm_ids,
'whitelist_applied': adjudication['whitelist_applied'],
}
def set_notice_odm_choice(task, *, snapshot_line_id: int, odm_id: str) -> dict[str, Any]:
"""
保存整单 ODM ID 用户选择:更新目标行的当前匹配事实,并同步同一快照文件的行。
同步范围 = 与目标行 `inventory_snapshot_id` 相同的全部 is_current 匹配行
(Header 契约是整单一个值,同文件行必须一致);校验取同步范围内各行候选的交集,
保证选择不会把其他行变成无匹配。
Args:
task: 正式 Notice 或其 OT。
snapshot_line_id: 用户编辑的冻结订单行 ID(工作台行主键)。
odm_id: 用户选定的 ODM ID。
Returns:
{task_id, odm_id, synced_line_count, odm_values}。
Raises:
AppError: 无当前匹配事实、行不存在,或所选值不在同步范围可行候选内
(SHIPPING.NOTICE_ODM_CHOICE_INVALID)。
"""
normalized = str(odm_id or '').strip()
options = notice_odm_options(task)
task_id = _adjudication_task_id(task)
if not task_id:
raise AppError(
code=_ODM_CHOICE_INVALID_CODE,
message='Shipping task is required before recording ODM choice',
http_status=409,
)
target_row = (
ShippingNoticeLineInventoryMatch.query
.filter_by(
task_id=int(task_id),
snapshot_line_id=int(snapshot_line_id or 0),
is_current=True,
)
.first()
)
if target_row is None:
raise AppError(
code=_ODM_CHOICE_INVALID_CODE,
message='No current inventory match fact for the given line',
http_status=409,
details={'snapshot_line_id': snapshot_line_id},
)
# 同步范围:与目标行关联同一快照文件的全部当前匹配行。
scope_rows = (
ShippingNoticeLineInventoryMatch.query
.filter_by(task_id=int(task_id), is_current=True)
.filter(ShippingNoticeLineInventoryMatch.inventory_snapshot_id == target_row.inventory_snapshot_id)
.all()
) if target_row.inventory_snapshot_id is not None else [target_row]
lines_by_sid = {
str(item.get('snapshot_line_id')): item for item in options.get('lines') or []
}
scope_candidates: list[set[str]] = []
for row in scope_rows:
entry = lines_by_sid.get(str(row.snapshot_line_id))
if entry is not None:
scope_candidates.append({str(v).strip().casefold() for v in entry.get('odm_values') or []})
feasible: set[str] = set.intersection(*scope_candidates) if scope_candidates else set()
if not normalized or normalized.strip().casefold() not in feasible:
raise AppError(
code=_ODM_CHOICE_INVALID_CODE,
message='Selected ODM ID is not among the feasible values',
http_status=409,
details={'odm_id': normalized, 'odm_values': sorted(feasible)},
)
# 同步落库:同一快照文件的全部当前匹配行写同一选择(前后端同步语义的落库侧)。
for row in scope_rows:
row.chosen_odm_id = normalized
db.session.flush()
return {
'task_id': int(task_id),
'odm_id': normalized,
'synced_line_count': len(scope_rows),
'odm_values': sorted(feasible),
}
@@ -30,6 +30,7 @@ from app.services.shipping_notice import order_document_profile_lease_service as
from app.services.shipping_notice import order_document_profile_service as profile_service
from app.services.shipping_notice.order_profile_value_adapter import get_value_adapter
from app.services.shipping_notice.audit_service import append_shipping_audit_event
from app.services.shipping_notice.order_schema.table_contract import compile_table_header_contract
from app.services.shipping_notice.document_layout.order_profile_signature import (
LAYOUT_SIGNATURE_ID,
MATCHER_POLICY_ID,
@@ -1235,6 +1236,15 @@ def _build_coordinate_overlap_evidence(
definition = dict(profile.definition_json or {})
thresholds = _match_thresholds(definition)
schema_definition = profile.schema_version.definition_json if profile.schema_version is not None else {}
try:
header_to_field = compile_table_header_contract(
schema_definition if isinstance(schema_definition, dict) else {},
).header_to_field
except ValidationError:
# 冻结 Schema definition 非法(别名碰撞等)时容忍降级:None 使 overlap
# 证据的表头原子互斥退化为词级原子,不阻断模板验证;空 definition 编译
# 出空映射,matcher 侧与 None 同口径。
header_to_field = None
published = published_rival_snapshots_for_overlap(profile)
candidates = [draft_snapshot, *published]
sample_role_pollution = _detect_sample_role_pollution(profile)
@@ -1243,7 +1253,9 @@ def _build_coordinate_overlap_evidence(
outcomes: list[dict[str, Any]] = []
for sample in samples:
layout = _load_sample_layout(sample)
match = match_frozen_coordinate_profiles(profiles=candidates, layout=layout)
match = match_frozen_coordinate_profiles(
profiles=candidates, layout=layout, header_to_field=header_to_field,
)
parse_result = None
if match.profile_code == profile.profile_code and int(match.version or 0) == int(profile.version):
if parse_result_resolver is not None:
@@ -1296,7 +1308,9 @@ def _build_coordinate_overlap_evidence(
'reason_code': 'representative_layout_unavailable',
})
continue
match = match_frozen_coordinate_profiles(profiles=candidates, layout=layout)
match = match_frozen_coordinate_profiles(
profiles=candidates, layout=layout, header_to_field=header_to_field,
)
source_unique = (
match.status in {'unique_match', 'selected_by_score'}
and match.profile_code == published_snapshot.get('profile_code')
@@ -56,6 +56,7 @@ from app.models import (
ShippingOrderSchemaVersion,
User,
)
from app.services.shipping_notice.conversation_title import derive_order_extraction_title
from app.services.shipping_notice.order_extraction_route_contract import (
PARSER_ENGINE_VERSION,
PARSER_POLICY_VERSION,
@@ -697,6 +698,16 @@ def _load_intakes(
return rows
def _intake_filenames(intakes: list[ShippingOrderIntake]) -> list[str]:
"""按 Intake 顺序取资产原始文件名;无资产或资产缺失以空串占位,保持计数口径。"""
asset_ids = [int(intake.asset_id) for intake in intakes if intake.asset_id]
if not asset_ids:
return []
rows = db.session.query(FileAsset.id, FileAsset.original_filename).filter(FileAsset.id.in_(asset_ids)).all()
filename_by_id = {row[0]: str(row[1] or '') for row in rows}
return [filename_by_id.get(int(intake.asset_id), '') for intake in intakes if intake.asset_id]
def _resolve_conversation(
*,
user_id: int,
@@ -713,6 +724,7 @@ def _resolve_conversation(
intakes: 已按用户锁定且通过业务资格校验的 Intake。
Returns:
已存在或本事务新建的 ChatSession;调用方负责最终提交。
新建会话的 title 由 conversation_title 按首个 Intake 文件名派生;已存在会话不改动标题。
Raises:
ConflictError: 所选 Intake 已分属不同会话,或与显式会话不一致。
"""
@@ -737,7 +749,7 @@ def _resolve_conversation(
session_id=uuid.uuid4().hex,
user_id=user_id,
agent_id=agent_id,
title='订单抽取',
title=derive_order_extraction_title(_intake_filenames(intakes), datetime.utcnow()),
status='running',
created_at=datetime.utcnow(),
updated_at=datetime.utcnow(),
@@ -1263,13 +1275,29 @@ def revive_layout_prerequisite_failed_units(run: ShippingOrderProcessingRun) ->
def _enqueue_ready_order_extraction_job(
run: ShippingOrderProcessingRun, *, message: str,
run: ShippingOrderProcessingRun,
*,
message: str,
continue_from_running: bool = False,
) -> int:
"""
为已有 ready 活的 Run 入队(或复用)extraction Job,并抬高 queued 优先级以便插队。
核心逻辑:enqueue 去重可能返回仍在排队的早建 Job;必须把其 priority 提到
_ORDER_EXTRACTION_READY_PRIORITY,否则 claim 仍按 created_at 先消化 layout。
自交接续抽(预算耗尽 / layout ready)须先 finish(commit=False) 释放
running 唯一槽,再以 continue_from_running=True 仅对 queued 去重入队,
避免复用即将结束的 running Job,也避免 UniqueViolation。
Args:
run: 订单抽取 Run。
message: Job 初始状态说明。
continue_from_running: True 时 dedupe_statuses=('queued',),供当前 Job
已同事务标 success 后的自交接;False(默认)可复用 queued/running,
供 layout 完成回调唤醒。
Returns:
入队或复用的 Job.id。
"""
from app.jobs.queue import enqueue
from app.jobs.types import JobType
@@ -1283,6 +1311,7 @@ def _enqueue_ready_order_extraction_job(
priority=_ORDER_EXTRACTION_READY_PRIORITY,
max_attempts=3,
message=message,
dedupe_statuses=('queued',) if continue_from_running else None,
commit=False,
)
job = db.session.get(Job, int(job_id))
@@ -64,6 +64,7 @@ from app.services.shipping_notice.order_profile_value_adapter import get_value_a
from app.services.shipping_notice.order_schema.field_rules import normalize_order_field_value, validate_order_field_value
from app.services.shipping_notice.reservation_region import (
apply_reservation_region_candidates,
resolve_candidate_line_numbers,
)
@@ -1071,7 +1072,12 @@ def _profile_table_candidates(
'issues': ['order_profile_selected_identity_invalid'], 'match': profile_match,
}
else:
match = match_frozen_coordinate_profiles(profiles=coordinate_profiles, layout=layout)
# 主路由匹配与下游表格解析共用同一冻结 Schema 表头契约:matcher 侧
# 表头原子互斥按别名归一为字段语义原子,跨措辞近亲模板不误杀。
match = match_frozen_coordinate_profiles(
profiles=coordinate_profiles, layout=layout,
header_to_field=contract.header_to_field,
)
affinity_applied = False
if not match_only:
match = _apply_parse_validation_gate(
@@ -1542,9 +1548,8 @@ def _apply_reparse_profile_affinity(
), None)
if candidate is None:
return match, False
verified = match_frozen_coordinate_profiles(profiles=[frozen], layout=layout)
if verified.status != 'unique_match':
return match, False
# 契约编译须先于复验:复验与解析验证消费同一份冻结 Schema definition,
# 表头原子互斥才能与正式取值走同一别名口径。
schema_snapshot = (
run.input_snapshot_json.get('schema')
if isinstance(getattr(run, 'input_snapshot_json', None), dict)
@@ -1555,6 +1560,18 @@ def _apply_reparse_profile_affinity(
if isinstance(schema_snapshot, dict) and isinstance(schema_snapshot.get('definition'), dict)
else {}
)
try:
header_to_field = compile_table_header_contract(schema_definition).header_to_field
except ValidationError:
# 冻结 definition 非法(别名碰撞等)时容忍降级:None 使匹配退化为
# 词级原子,不阻断重识别亲和性;definition 为空时编译结果为空映射,
# matcher 侧与 None 同口径。
header_to_field = None
verified = match_frozen_coordinate_profiles(
profiles=[frozen], layout=layout, header_to_field=header_to_field,
)
if verified.status != 'unique_match':
return match, False
parse_result = validate_profile_parse_candidate(
profile_snapshot=frozen,
layout=layout,
@@ -2090,14 +2107,18 @@ def route_deterministic_unit(run: Any, *, unit: Any) -> DeterministicRouteResult
)
decision['parsed_table_count'] = 1
decision['route_type'] = 'profile_deterministic'
# 模板确定性取值已成功,复核只针对业务归属(Reservation 专区/行校验)。
# 必须以 deterministic 携带原因码交 STP 裁 needs_review,让已解析订单
# 继续落 provisional Candidate 供复核台编辑;review_required 会被
# Worker 当作"无可信取值"丢弃,复核草稿将退化为空白手工单。
if any(order.get('reservation_region_status') == 'needs_review' for order in orders):
decision['fallback_reason_codes'] = ['reservation_region_needs_review']
return _apply_stp_route_adjudication(
decision, execution_mode='review_required', orders=orders,
decision, execution_mode='deterministic', orders=orders,
)
if decision.get('fallback_reason_codes'):
return _apply_stp_route_adjudication(
decision, execution_mode='review_required', orders=orders,
decision, execution_mode='deterministic', orders=orders,
)
decision['fallback_reason_codes'] = []
return _apply_stp_route_adjudication(decision, execution_mode='deterministic', orders=orders)
@@ -2357,11 +2378,31 @@ def _build_approved_profile_order_result(
if candidates:
header_target = reservation_scope.get('header')
line_target = reservation_scope.get('line')
# Reservation 注释的 L#n 引用单据印刷行号(LN 列),必须按 customer_po_line_no
# 值定位逻辑行;LN 非连续(部分行已拆单)时按位置写入会错配并误报越界。
line_numbers: list[int | None] | None = None
if line_target:
ln_field_id = next(
(str(item.get('field_id') or '') for item in fields
if str(item.get('field_code') or '') == 'customer_po_line_no'),
None,
)
if ln_field_id:
line_numbers = resolve_candidate_line_numbers([
next(
(observation.get('value') for field in group.get('fields') or []
if str(field.get('field_id') or '') == ln_field_id
for observation in field.get('observations') or []),
None,
)
for group in line_groups
])
applied = apply_reservation_region_candidates(
candidates=candidates,
header_field_id=str(header_target.get('field_id') or '') if header_target else None,
line_field_id=str(line_target.get('field_id') or '') if line_target else None,
line_count=len(line_groups),
line_numbers=line_numbers,
)
if applied.header_value and header_target:
header_evidence = next((item for item in candidates if item.get('scope') == 'header'), {})
@@ -2379,9 +2420,10 @@ def _build_approved_profile_order_result(
]
if line_target:
for line_no, value in applied.line_values.items():
# line_no 已是逻辑行序号;候选里携带的是印刷行号,证据只按值回查。
line_evidence = next((
item for item in candidates
if item.get('scope') == 'line' and item.get('line_no') == line_no and item.get('value') == value
if item.get('scope') == 'line' and item.get('value') == value
), {})
line_groups[line_no - 1].setdefault('fields', []).append({'field_id': str(line_target.get('field_id') or ''), 'observations': [{
'value': value, 'document_id': int(unit.document_id),
@@ -2390,7 +2432,8 @@ def _build_approved_profile_order_result(
line_id = str(line_target.get('field_id') or '')
line_code = str(line_target.get('field_code') or '')
for missing in source_missing_fields['lines']:
if isinstance(missing, dict) and int(missing.get('line_index') or -1) == line_no - 1:
# 不能用 `or -1` 兜底:line_index 0 是合法值,会被 falsy 判断跳过。
if isinstance(missing, dict) and missing.get('line_index') == line_no - 1:
missing['field_ids'] = [field_id for field_id in missing['field_ids'] if field_id != line_id]
missing['field_codes'] = [field_code for field_code in missing['field_codes'] if field_code != line_code]
source_missing_fields['lines'] = [
@@ -2540,7 +2583,15 @@ def _confirmed_profile_order_fields(run: Any, *, unit: Any) -> list[dict[str, An
layout = ensure_on_demand_coordinate_evidence(
document=document_model, layout=layout, page_nos=required_pages,
)
match = match_frozen_coordinate_profiles(profiles=profiles, layout=layout)
try:
header_to_field = compile_table_header_contract(definition).header_to_field
except ValidationError:
# 冻结 definition 非法(别名碰撞等)时容忍降级:None 使匹配退化为
# 词级原子,confirmed 字段锁集返回空,不抛错。
header_to_field = None
match = match_frozen_coordinate_profiles(
profiles=profiles, layout=layout, header_to_field=header_to_field,
)
match, _affinity_applied = _apply_reparse_profile_affinity(
run=run, unit=unit, profiles=profiles, match=match, layout=layout,
)
@@ -2,7 +2,7 @@
services/shipping_notice/order_field_purposes.py
用途:将冻结订单 Snapshot 按冻结货代策略能力投影给履约链。
依赖:冻结履约策略、export.order_field_id_values、ShippingNotice。
依赖:冻结履约策略、effective_order_view.effective_order_field_values、ShippingNotice。
逻辑:路由、门禁、匹配和展示只通过固定规则冻结的 stable field_id 定位字段,禁止读取 Schema business_purpose 或任务行固定列。
"""
@@ -12,7 +12,8 @@ from typing import Any
from app import db
from app.models import ShippingOrderSnapshot, ShippingNotice
from app.services.shipping_notice.export import _source_notice_for_order_facts, order_field_id_values
from app.services.shipping_notice.effective_order_view import effective_order_field_values
from app.services.shipping_notice.export import _source_notice_for_order_facts
_PURPOSE_BY_CAPABILITY = {
@@ -47,9 +48,9 @@ def task_line_purpose_field_ids(task: ShippingNotice, *, required: set[str] | No
def task_line_purpose_values(task: ShippingNotice, *, required: set[str] | None = None) -> list[dict[str, Any]]:
"""按订单行位置返回用途键值,值只来自冻结 Snapshot。"""
"""按订单行位置返回用途键值,值来自冻结 Snapshot 叠加冻结后人工修正的有效视图(effective_order_view)。"""
purpose_ids = task_line_purpose_field_ids(task, required=required)
_header, lines = order_field_id_values(task)
_header, lines = effective_order_field_values(task)
return [
{purpose: line.get(field_id) for purpose, field_id in purpose_ids.items()}
for line in lines
@@ -258,19 +258,26 @@ def retry_review_case_customer_resolution(
case = _load_writable_case(user_id=user_id, case_no=case_no)
matches: list[dict[str, Any]] = []
if case.candidate_id:
from app.services.shipping_notice.customer_auto_resolution import (
AUTO_CONFIRM_ELIGIBLE_STATUSES,
resolve_auto_customer_decision,
)
from app.services.shipping_notice.customer_shadow_resolution import refresh_candidate_shadow_resolution
candidate = db.session.get(ShippingOrderCandidate, int(case.candidate_id))
if candidate is not None:
shadow = refresh_candidate_shadow_resolution(candidate)
# [STEP 2] 重新识别后若客户指纹唯一命中,直接写入确认结果;投影函数保持纯读。
# [STEP 2] 重新识别后与任务期协调器共用同一分级裁决:canonical 等值唯一或
# 「指纹完整出现」包含唯一且证据授权才自动确认;截断建议(containment_weak)
# 只进候选展示,绝不在此确认。投影函数保持纯读。
decision = resolve_auto_customer_decision(shadow)
if (
shadow.status == 'unique_candidate'
and shadow.top_customer_id
str(decision.get('status') or '') in AUTO_CONFIRM_ELIGIBLE_STATUSES
and decision.get('customer_id') is not None
and not resolve_review_case_customer_resolved(case=case, candidate=candidate)
):
confirm_customer_resolution(
candidate,
customer_id=int(shadow.top_customer_id),
customer_id=int(decision['customer_id']),
actor_id=None,
method='auto_rule',
reason='客户识别指纹唯一命中自动确认',
@@ -10,6 +10,7 @@ services/shipping_notice/order_review_draft_service.py
逻辑:只修改独立 Draft JSON;每次写入锁定 Case/Draft、校验草稿版本与 WorkflowItem 可写状态,
追加 CaseEvent + ShippingAuditEvent,并镜像 review_field_changed 到订单抽取进度流;
Item 已关闭/重识别中的冲突经 `_reject_draft_operation` 落 rejected 审计;
STP 等待入队/排队/执行期间拒绝草稿内容写入(显式 validate 仍放行供自动协调器);
整单校验汇总客户确认、有效 Reservation、行级库存源候选与自动建单资格;
行级必填 reservation_id 空值时先回退表头(与建单资格 / Schema Runtime 一致),再报缺失;
确认建单摘要同样回填行级 reservation_id,供物化 FieldValue / 冻结门禁消费;
@@ -225,7 +226,7 @@ def _locked_case(*, user_id: int, case_no: str, action: str) -> ShippingOrderRev
按 owner 分别锁定 Case 和当前 Draft;不可编辑时写拒绝审计。
核心逻辑:两段 FOR UPDATE 避免 joinedload+nullable 侧锁问题;Case 可识别后
若状态不在可编辑集合,先落 rejected 审计再抛错。
若状态不在可编辑集合,先落 rejected 审计再抛错;STP 已接手时拒绝内容写入。
"""
case = (
ShippingOrderReviewCase.query
@@ -248,9 +249,92 @@ def _locked_case(*, user_id: int, case_no: str, action: str) -> ShippingOrderRev
action=action,
error=ConflictError('Order review case is not editable', code='SHIPPING.REVIEW_CASE_NOT_EDITABLE'),
)
# draft_validated 放行:自动协调器在入队前仍需显式校验;内容写入一律拦截。
if str(action or '').strip() != 'draft_validated' and _stp_automation_holds_draft(case):
_reject_draft_operation(
case,
actor_id=int(user_id),
action=action,
error=ConflictError(
'Draft is locked while system auto-create is in progress',
code='SHIPPING.REVIEW_DRAFT_LOCKED_BY_AUTOMATION',
),
)
return case
def _stp_waiting_timeout_seconds() -> int:
"""与 order_review_projection 同源的 STP waiting_to_start 超时秒数。"""
try:
from flask import current_app
return max(int(current_app.config.get('SHIPPING_NOTICE_STP_WAITING_TIMEOUT_SECONDS', 120) or 120), 15)
except Exception: # noqa: BLE001
return 120
def _stp_automation_holds_draft(case: ShippingOrderReviewCase) -> bool:
"""
判断 STP 是否已接手草稿(等待入队 / 排队 / 执行),期间禁止人工改草稿。
核心逻辑:有活跃 Job → 锁定;无 Job 但 can_auto_create+can_build 且未超时 → 锁定。
"""
from datetime import datetime, timezone
from app.jobs.types import JobType
from app.models import Job
from app.services.shipping_notice.order_stp_auto_create_service import build_stp_idempotency_key
if case.confirmed_task_id is not None:
return False
draft = case.current_draft
if draft is None or case.document_id is None:
return False
run = case.run
run_no = str(getattr(run, 'run_no', '') or '').strip()
if run_no:
business_ref = build_stp_idempotency_key(
run_no=run_no,
document_id=int(case.document_id),
draft_version=int(draft.draft_version),
)
active = (
Job.query.filter(
Job.domain == 'shipping_notice',
Job.job_type == JobType.SHIPPING_STP_AUTO_CREATE.value,
Job.business_ref == business_ref,
Job.status.in_(('queued', 'running')),
)
.order_by(Job.id.desc())
.first()
)
if active is not None:
return True
validation = draft.validation_result_json if isinstance(draft.validation_result_json, dict) else {}
if not (bool(validation.get('can_auto_create')) and bool(validation.get('can_build'))):
return False
if str(case.status or '') in {'confirmed', 'non_order', 'quality_issue'}:
return False
validated_at = None
raw_validated = str(validation.get('validated_at') or '').strip()
if raw_validated:
try:
text = raw_validated[:-1] + '+00:00' if raw_validated.endswith('Z') else raw_validated
validated_at = datetime.fromisoformat(text)
except ValueError:
validated_at = None
anchor = validated_at or getattr(case, 'updated_at', None) or getattr(draft, 'updated_at', None)
if anchor is not None:
if getattr(anchor, 'tzinfo', None) is None:
anchor = anchor.replace(tzinfo=timezone.utc)
age = (datetime.now(timezone.utc) - anchor).total_seconds()
if age >= _stp_waiting_timeout_seconds():
return False
return True
def _expected_version(value: Any) -> int:
"""写入接口必须明确带版本号,避免缺省值退化为最后写入者获胜。"""
if isinstance(value, bool):
@@ -426,12 +426,20 @@ def _manual_required_release_fields(fields: list[dict[str, Any]]) -> list[dict[s
]
def _sync_confirmed_task_fulfillment_gates(*, case: ShippingOrderReviewCase, actor_id: int) -> None:
def _sync_confirmed_task_fulfillment_gates(
*,
case: ShippingOrderReviewCase,
actor_id: int,
trigger: str = 'inventory_shortage_released',
) -> None:
"""
短缺放行后同步正式 OT Gate,并异步触发唯一明细的独立 Notice/Excel 创建。
短缺放行/行结案后同步正式 OT Gate,并异步触发唯一明细的独立 Notice/Excel 创建。
核心逻辑:Gate 重投影不改写库存事实;复用既有 auto-fulfill Job,由 Job 再判断
是否恰好只有一条开放且可履约的明细。多条明细不会自动合并,仍由用户勾选创建 wave。
Args:
trigger: 编排触发标签(放行 inventory_shortage_released / 结案 line_fulfillment_closed)。
"""
task_id = getattr(case, 'confirmed_task_id', None)
if task_id is None:
@@ -469,7 +477,7 @@ def _sync_confirmed_task_fulfillment_gates(*, case: ShippingOrderReviewCase, act
submit_auto_progress(
task=task,
trigger='inventory_shortage_released',
trigger=trigger,
operator_id=actor_id,
commit=False,
)
@@ -480,7 +488,7 @@ def _sync_confirmed_task_fulfillment_gates(*, case: ShippingOrderReviewCase, act
enqueue_post_ot_auto_fulfill_job(
task_no=str(task.task_no),
trigger='inventory_shortage_released',
trigger=trigger,
commit=False,
)
@@ -763,7 +771,6 @@ def project_review_case_line_decisions(
"""
from app.services.shipping_notice.line_inventory_match_projection import (
line_auto_fulfill_enabled,
load_current_match_facts_by_task,
project_line_inventory_view,
)
from app.services.shipping_notice.order_review_workbench_projection import (
@@ -810,7 +817,11 @@ def project_review_case_line_decisions(
'status': 'resolving',
'source': 'inventory_source_clue',
}
match_facts = load_current_match_facts_by_task(formal_ot.get('task_id'))
# [BE-键修复] Case 草稿行只有 _line_index;补一条按行号索引的事实通道。
from app.services.shipping_notice.line_inventory_match_projection import (
load_current_match_facts_by_line_index,
)
match_facts_by_line = load_current_match_facts_by_line_index(formal_ot.get('task_id'))
labels = dict(source_labels or {})
if not labels:
draft = getattr(case, 'current_draft', None)
@@ -835,7 +846,12 @@ def project_review_case_line_decisions(
decision = by_key.get(key)
# 正式 OT 的库存数量以当前行匹配事实为准;草稿 validation_result 只保留
# 解析阶段投影,不能因为其中没有 available_qty 就错误阻断人工出单。
fact = match_facts.get(key)
# [BE-键修复] 草稿行只有 _line_index;旧实现误用 draft_line_id 查 snapshot_line_id 键,恒 miss。
line_index = draft_line.get('_line_index')
fact = (
match_facts_by_line.get(int(line_index))
if line_index is not None else None
)
fact_detail = dict((fact or {}).get('detail_json') or {}) if isinstance(fact, dict) else {}
fulfill_proj = dict(proj)
if isinstance(fact, dict):
@@ -1083,7 +1099,7 @@ def decide_review_line_fulfillment(
case_no: Case 编号。
draft_line_id: 草稿行键。
decision_code: 决定码。
reason: 关闭/重开/短缺放行必填原因。
reason: 关闭/重开必填原因;短缺放行可选(人工放行事实由审计链记录)。
release_field_values: 短缺放行时模板行级库存字段的人工补录值。
expected_draft_version: 可选草稿乐观锁。
actor_is_admin: 是否管理员(重开授权)。
@@ -1098,7 +1114,9 @@ def decide_review_line_fulfillment(
code='SHIPPING.REVIEW_LINE_DECISION_INVALID',
details={'decision_code': code},
)
if code in {DECISION_CLOSE, DECISION_REOPEN, DECISION_RELEASE_SHORTAGE} and not str(reason or '').strip():
# [BE-放行免因] 短缺放行不强制原因:人工放行事实已由审计链完整记录
# (操作人 + 时间 + 决定快照 release_field_values);结案/重开仍要求原因。
if code in {DECISION_CLOSE, DECISION_REOPEN} and not str(reason or '').strip():
raise ValidationError(
'Reason is required',
code='SHIPPING.REVIEW_LINE_DECISION_REASON_REQUIRED',
@@ -1239,8 +1257,13 @@ def decide_review_line_fulfillment(
db.session.add(row)
# [STEP 2] 审计 after 投影依赖数据库分配的主键,必须先 flush。
db.session.flush()
if code == DECISION_RELEASE_SHORTAGE:
_sync_confirmed_task_fulfillment_gates(case=case, actor_id=int(user_id))
if code in {DECISION_RELEASE_SHORTAGE, DECISION_CLOSE}:
# [BE-结案-豁免] 结案与放行同为库存充分性 Gate 的受控事实:决定落库后立即重算并触发编排。
_sync_confirmed_task_fulfillment_gates(
case=case,
actor_id=int(user_id),
trigger='inventory_shortage_released' if code == DECISION_RELEASE_SHORTAGE else 'line_fulfillment_closed',
)
from app.services.shipping_notice.fulfillment_audit import record_fulfillment_audit
@@ -24,7 +24,7 @@ from app import db
from app.core.config.settings import Config
from app.core.errors import ConflictError, NotFoundError, ValidationError
from app.models import Agent, ShippingOrderReviewCase, ShippingOrderReviewSuggestion
from app.services.dify import DifyService
from app.services.integrations.dify import DifyService
from app.services.shipping_notice.agent_resolver import resolve_chat_agent
from app.services.shipping_notice.fulfillment_audit import record_fulfillment_audit
from app.services.shipping_notice.order_review_draft_service import (
@@ -1065,6 +1065,54 @@ def _queue_current_gate_hint(case: ShippingOrderReviewCase) -> dict[str, Any] |
return None
# 队列当前 Gate 活跃口径:在 _queue_current_gate_hint 活跃集合上补 queued/failed_terminal,
# 供 needs_attention 兜底取 Gate,避免终态失败的单被漏判。
_QUEUE_CURRENT_GATE_STATUSES = frozenset({
'pending', 'queued', 'running', 'blocked_retryable', 'blocked_manual', 'waiting_external', 'failed_terminal',
})
# 需要人工介入的 Gate 状态;waiting_external/running/pending/queued 属系统在办,不算需人工。
_QUEUE_ATTENTION_GATE_STATUSES = frozenset({'blocked_manual', 'blocked_retryable', 'failed_terminal'})
def _queue_gate_needs_attention(case: ShippingOrderReviewCase) -> bool:
"""
判定 Case 当前正式门禁是否需要人工介入;供队列摘要下发 needs_attention。
只读会话级批量缓存(_load_review_case_summary_batch 已预取 Execution/Gate),
零额外 SQL;当前 Gate 取 execution.current_gate_code 对应 Gate,缺失时按
sequence_no 取第一个活跃 Gate。调用方禁止据此之外再自行推断阻塞。
Args:
case: 当前复核 Case。
Returns:
当前 Gate 状态 ∈ {blocked_manual, blocked_retryable, failed_terminal} 时 True;
无 Execution / 无活跃 Gate 时 False。
"""
cache = db.session.info.get('shipping_conversation_projection_read_cache')
if not isinstance(cache, dict) or getattr(case, 'id', None) is None:
return False
execution = (cache.get('execution_by_case_id') or {}).get(int(case.id))
if execution is None:
return False
gate_code = str(getattr(execution, 'current_gate_code', None) or '').strip().lower()
gates = (cache.get('gates_by_execution_id') or {}).get(int(execution.id), []) or []
current = None
if gate_code:
for gate in gates:
if str(getattr(gate, 'gate_code', '') or '').strip().lower() == gate_code:
current = gate
break
if current is None:
for gate in gates:
if str(getattr(gate, 'status', '') or '').strip().lower() in _QUEUE_CURRENT_GATE_STATUSES:
current = gate
break
if current is None:
return False
return str(getattr(current, 'status', '') or '').strip().lower() in _QUEUE_ATTENTION_GATE_STATUSES
def _serialize_review_case_summary(
case: ShippingOrderReviewCase,
*,
@@ -1157,6 +1205,7 @@ def _serialize_review_case_summary(
'status': case.status,
'draft_version': int(draft.draft_version) if draft is not None else None,
'issue_count': len(draft.issue_summary_json or []) if draft is not None else 0,
'needs_attention': _queue_gate_needs_attention(case),
# Intake 解析失败没有 Candidate,恢复必须从当前阶段卡调用原 SNI retry API。
# 其它 Intake 状态(尤其 parsing/cancelled)不得由前端显示或猜测重试。
'available_actions': (
@@ -1377,6 +1426,28 @@ def _load_review_case_summary_batch(
}
def _queue_summary_bucket(item: dict[str, Any]) -> str:
"""
队列计数桶归类;优先级与前端队列图标一致:需人工 > 终态完成 > 进行中。
桶是"处置去向"粗归类,与五态图标非一一映射(non_order 计入 completed,
图标为中性别灰○);needs_attention(门禁阻塞)恒优先于 completed,
避免阻塞单被计数成"完成"。
Args:
item: 队列 item 投影(含 status / needs_attention / lifecycle_stage)。
Returns:
'needs_action' | 'completed' | 'processing'。
"""
status = str(item.get('status') or '')
if status in ('unreviewed', 'draft', 'ready', 'quality_issue') or item.get('needs_attention'):
return 'needs_action'
if status in ('non_order', 'closed', 'completed') or str(item.get('lifecycle_stage') or '') == 'upload_complete':
return 'completed'
return 'processing'
def serialize_review_queue(runs: list[ShippingOrderProcessingRun]) -> dict[str, Any]:
"""返回会话级文件当前队列;Run/Case 历史均不参与主队列平铺。"""
if not runs:
@@ -1444,10 +1515,11 @@ def serialize_review_queue(runs: list[ShippingOrderProcessingRun]) -> dict[str,
db.session.info.pop('shipping_conversation_projection_read_cache', None)
else:
db.session.info['shipping_conversation_projection_read_cache'] = previous_cache
buckets = [_queue_summary_bucket(item) for item in items]
counts = {
'total': len(items),
'needs_action': sum(1 for item in items if item['status'] in ('unreviewed', 'draft', 'ready')),
'processing': sum(1 for item in items if item['status'] in ('confirming', 'reparse_pending')),
'completed': sum(1 for item in items if item['status'] in ('confirmed', 'non_order', 'quality_issue')),
'needs_action': buckets.count('needs_action'),
'processing': buckets.count('processing'),
'completed': buckets.count('completed'),
}
return {'conversation_id': conversation_id, 'summary': counts, 'items': items}
Loaded 100 of 541 files, more files were not shown because too many files have changed in this diff. Show more